Client builds

This commit is contained in:
Aidan Hahn 2019-05-17 01:28:26 -07:00
parent ee2b7f0b4c
commit d6e73cf7ad
No known key found for this signature in database
GPG key ID: 327711E983899316
10 changed files with 297 additions and 356 deletions

View file

@ -18,10 +18,13 @@ buildscript {
plugins { plugins {
id 'java' id 'java'
id 'com.google.protobuf' version '0.8.8'
id 'application' id 'application'
} }
apply plugin: 'com.google.protobuf' def grpcVersion = '1.22.0-SNAPSHOT'
def protobufVersion = '3.7.1'
def protocVersion = protobufVersion
repositories { repositories {
// Use jcenter for resolving your dependencies. // Use jcenter for resolving your dependencies.
@ -36,6 +39,9 @@ dependencies {
// Use JUnit test framework // Use JUnit test framework
testImplementation 'junit:junit:4.12' testImplementation 'junit:junit:4.12'
// Used by GRPC generated code
compile 'org.glassfish:javax.annotation:10.0-b28'
// grpc stuff // grpc stuff
compile 'io.grpc:grpc-netty-shaded:1.20.0' compile 'io.grpc:grpc-netty-shaded:1.20.0'
compile 'io.grpc:grpc-protobuf:1.20.0' compile 'io.grpc:grpc-protobuf:1.20.0'
@ -44,7 +50,7 @@ dependencies {
} }
// Define the main class for the application // Define the main class for the application
mainClassName = 'JobServ.App' mainClassName = 'JobServ.JobServClient'
protobuf { protobuf {
protoc { protoc {
@ -64,4 +70,10 @@ protobuf {
} }
} }
apply plugin: 'application'
mainClassName = 'JobServ.JobServClient'
jar {
manifest {
attributes('Main-Class' : mainClassName)
}
}

Binary file not shown.

View file

@ -1,5 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-5.2.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

172
gradlew vendored
View file

@ -1,172 +0,0 @@
#!/usr/bin/env sh
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin, switch paths to Windows format before running java
if $cygwin ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"

84
gradlew.bat vendored
View file

@ -1,84 +0,0 @@
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View file

@ -1,10 +0,0 @@
/*
* This file was generated by the Gradle 'init' task.
*
* The settings file is used to specify which projects to include in your build.
*
* Detailed information about configuring a multi-project build in Gradle can be found
* in the user manual at https://docs.gradle.org/5.2.1/userguide/multi_project_builds.html
*/
rootProject.name = 'JobServ'

View file

@ -0,0 +1,216 @@
package JobServ;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Scanner;
// GRPC Client Class
public class JobServClient {
// RequestMessage types
// TODO: refactor to enum?
public static final int OUTPUT = 0;
public static final int RETURN = 1;
public static final int PAUSE = 2;
public static final int RESUME = 3;
public static final int STATUS = 4;
/* The client should not use the same logging module as the server.
* In a more robust product the server logging module will take advantage of system level
* log aggregators such as journalctl, which the client should not be writing to on the users system
*/
private static final Logger logger = Logger.getLogger(JobServClient.class.getName());
private final ManagedChannel channel;
/* blockingStub is used when the client needs to block until the server responds
* the client doesnt nessesarily need to support asynchronously firing off commands
* in this shell-like interface it would be disconcerting to get multiple returns out of order
*/
private final ShellServerGrpc.ShellServerBlockingStub blockingStub;
// Constructor connects to server
public JobServClient(String host, int port) {
this(ManagedChannelBuilder.forAddress(host, port)
// TODO: MTLS
.usePlaintext()
.build());
}
// private overload of constructor, used in the above constructor
JobServClient(ManagedChannel channel) {
this.channel = channel;
blockingStub = ShellServerGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
// sends the server a RequestMessage, blocks until response
// returns an integer representing process status
private int makeProcessRequest(int pid, int requestType) {
logger.info("[+] Sending request");
RequestMessage request = RequestMessage.newBuilder()
.setPID(pid)
.setRequestType(requestType)
.build();
JobStatusMessage response;
try {
// blocking network operation
response = blockingStub.getStatusDetail(request);
} catch (StatusRuntimeException e) {
/* if this was using an async stub it might be
* worthwhile to include the PID and request type
*/
logger.log(Level.WARNING, "[-]Status Request Failed: %s", e.getStatus());
return -1;
}
// return process status
return response.getProcessStatus();
}
// sends the server a request for output from PID
// different from getProcessStatus in output expected from the server
// returns process output as string
public String getProcessOutput(int pid) {
logger.info("[+] requesting output");
RequestMessage request = RequestMessage.newBuilder()
.setPID(pid)
.setRequestType(OUTPUT)
.build();
OutputMessage response;
try {
// blocking network operation
response = blockingStub.getJobOutput(request);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "[-] Request for output failed: %s", e.getStatus());
// TODO: refactor this out by throwing here and catching in the shell
return "";
}
return response.getProcessOutput();
}
// sends the server a command for a new job, blocks until response
// returns new pid of job
public int sendNewJobMessage(String command) {
// thought of escaping this, but the vulnerability is only client side, from client user input.
logger.info("[+] Sending command to server");
NewJobMessage request = NewJobMessage.newBuilder()
.setCommand(command)
.build();
JobStatusMessage response;
try {
// blocking network operation
response = blockingStub.makeNewJob(request);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "[-] Request for new job failed!");
return -1;
}
if(response.getPID() == -1) {
logger.log(Level.WARNING, "New job creation failed server side!");
}
return response.getPID();
}
// Client entrypoint
public static void main(String[] args) throws Exception {
// check args
if(args.length != 3) {
System.out.println("Usage: $ jobservclient host port");
return;
}
// start client (or fail if port is improperly formatted)
JobServClient client;
try {
client = new JobServClient(args[1], Integer.parseInt(args[2]));
} catch (NumberFormatException e) {
System.out.println("Invalid Port");
return;
}
Scanner reader = new Scanner(System.in);
while(true) {
System.out.print("> ");
int pid, status;
String input = reader.next();
switch (input) {
case "pause":
System.out.println("Enter a PID");
pid = reader.nextInt();
status = client.makeProcessRequest(pid, PAUSE);
// TODO: parse status return
break;
case "resume":
System.out.println("Enter a PID");
pid = reader.nextInt();
status = client.makeProcessRequest(pid, RESUME);
// TODO: parse status return
break;
case "new":
System.out.println("Enter a command");
String command = reader.next();
pid = client.sendNewJobMessage(command);
System.out.println(String.format("New process on server: %d", pid));
break;
case "output":
System.out.println("Enter a PID");
pid = reader.nextInt();
String out = client.getProcessOutput(pid);
System.out.println(out);
break;
case "status":
System.out.println("Enter a PID");
pid = reader.nextInt();
status = client.makeProcessRequest(pid, STATUS);
System.out.println(String.format("Current status of program is: %d", status));
break;
case "return":
System.out.println("Enter a PID");
pid = reader.nextInt();
status = client.makeProcessRequest(pid, RETURN);
System.out.println(String.format("Exit code of process is: %d", status));
break;
case "quit":
reader.close();
return;
case "help":
System.out.println("pause: pauses a process on the server");
System.out.println("resume: resumes a process on the server");
System.out.println("new: starts a new process on the server");
System.out.println("output: garners (new) output from a process on the server");
System.out.println("status: outputs the current status of a program on the server");
System.out.println("return: outputs exit code of a process on the sercer");
break;
default:
System.out.println("Improper output, try 'help'");
break;
}
}
}
}

View file

@ -14,81 +14,80 @@ public class JobServServer {
// starts the GRPC API Server // starts the GRPC API Server
private void start() throws IOException { private void start() throws IOException {
// TODO: this should be passed in from a configuration manager // TODO: this should be passed in from a configuration manager
int port = 8448; int port = 8448;
server = ServerBUilder.forPort(port) server = ServerBUilder.forPort(port)
.addService(new JobServImpl()) .addService(new JobServImpl())
.build() .build()
.start(); .start();
logger.info("Server initialized without tls"); logger.info("Server initialized without tls");
Runtime.getRuntime().addShutdownHook(new thread() { Runtime.getRuntime().addShutdownHook(new thread() {
@Override @Override
public void run() { public void run() {
// JVM shutdown might break logger functionality // JVM shutdown might break logger functionality
// so investigate this.... // so investigate this....
logger.info("Shutting down server"); logger.info("Shutting down server");
JobServServer.this.stop(); JobServServer.this.stop();
} }
}); });
} }
private void stop() { private void stop() {
if (server != null) { if (server != null) {
server.shutdown(); server.shutdown();
} }
} }
// spinlock for main() // spinlock for main()
private void blockUntilShutdown() throws InterruptedException { private void blockUntilShutdown() throws InterruptedException {
if (server != null) { if (server != null) {
server.awaitTermination(); server.awaitTermination();
} }
} }
// Main funciton. starts GRPC server and spins until server is shutdown // Main function. starts GRPC server and spins until server is shutdown
public static void main(String[] args) throws IOException, InterruptedException { public static void main(String[] args) throws IOException, InterruptedException {
final JobServServer server = new JobServServer(); final JobServServer server = new JobServServer();
server.start(); server.start();
server.blockUntilShutdown(); server.blockUntilShutdown();
} }
// wrap around stub code generated by GRPC // wrap around stub code generated by GRPC
static class JobServImpl extends JobServGrpc.JobServImplBase { static class JobServImpl extends JobServ.JobServImplBase {
@Override @Override
public void getStatusDetail(RequestMessage request, public void getStatusDetail(RequestMessage request,
StreamObserver<JobStatusMessage> responder) { StreamObserver<JobStatusMessage> responder) {
// TODO: Implement job controller, check request type, do the thing // TODO: Implement job controller, check request type, do the thing
JobStatusMessage reply = JobStatusMessage.newBuilder() JobStatusMessage reply = JobStatusMessage.newBuilder()
.setPID(-1) .setPID(-1)
.setProcessStatus(-1) .setProcessStatus(-1)
.build(); .build();
responder.onNext(reply); responder.onNext(reply);
responder.onCompleted(); responder.onCompleted();
} }
@Override @Override
public void getJobOutput(RequestMessage request, public void getJobOutput(RequestMessage request,
StreamObserver<OutputMessage> responder) { StreamObserver<OutputMessage> responder) {
// TODO: Implement job controller, get output, do the thing // TODO: Implement job controller, get output, do the thing
OutputMessage reply = OutputMessage.newBuilder() OutputMessage reply = OutputMessage.newBuilder()
.setPID(-1) .setPID(-1)
.setProcessOutput("Hello World!") .build();
.build(); responder.onNext(reply);
responder.onNext(reply); responder.onCompleted();
responder.onCompleted(); }
}
@Override
@Override public void makeNewJob(NewJobMessage request,
public void makeNewJob(NewJobMessage request, StreamObserver<JobStatusMessage> responder) {
StreamObserver<JobStatusMessage> responder) { // TODO: Implement job controller, Start Job, do the thing
// TODO: Implement job controller, Start Job, do the thing JobStatusMessage reply = JobStatusMessage.newBuilder()
JobStatusMessage reply = JobStatusMessage.newBuilder() .setPID(-1)
.setPID(-1) .setJobStatus(-1)
.setProcessStatus(-1) .build();
.build(): responder.onNext(reply);
responder.onNext(reply); responder.onCompleted();
responder.onCompleted(); }
}
} }
} }

View file

@ -1,13 +1,13 @@
syntax = "proto3"; syntax = "proto3";
option java_multiple_files = true; option java_multiple_files = true;
option java_package = "com.ajhahn.jobserv"; option java_package = "JobServ";
option java_outer_classname = "JobServProto"; option java_outer_classname = "JobServGrpc";
option objc_class_prefix = "JSV"; option objc_class_prefix = "JSV";
package jobserv; package JobServ;
service jobserv { service ShellServer {
rpc getStatusDetail (RequestMessage) returns (JobStatusMessage) {} rpc getStatusDetail (RequestMessage) returns (JobStatusMessage) {}
rpc getJobOutput (RequestMessage) returns (OutputMessage) {} rpc getJobOutput (RequestMessage) returns (OutputMessage) {}
rpc makeNewJob (NewJobMessage) returns (JobStatusMessage) {} rpc makeNewJob (NewJobMessage) returns (JobStatusMessage) {}
@ -28,6 +28,5 @@ message JobStatusMessage {
} }
message OutputMessage { message OutputMessage {
int32 PID = 1;
string ProcessOutput = 2; string ProcessOutput = 2;
} }

View file

@ -1,14 +0,0 @@
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package JobServ;
import org.junit.Test;
import static org.junit.Assert.*;
public class AppTest {
@Test public void testAppHasAGreeting() {
App classUnderTest = new App();
assertNotNull("app should have a greeting", classUnderTest.getGreeting());
}
}