Skip to content

Commit

Permalink
Merge pull request #724 from smashery/new_cmd_exec_v2
Browse files Browse the repository at this point in the history
Handle Windows oddity in java's process launch library
  • Loading branch information
adfoster-r7 authored Oct 15, 2024
2 parents 8b9fdd5 + 26d0aa3 commit b697cc5
Showing 1 changed file with 60 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,69 @@ public int execute(Meterpreter meterpreter, TLVPacket request, TLVPacket respons
return ERROR_SUCCESS;
}

// On Windows, Java quote-escapes _some_ arguments (like those with spaces), but doesn't deal correctly with some
// edge cases; e.g. empty strings, strings that already have quotes.
protected String escapeArg(String arg) {
if (arg == null) {
return null;
}
String osName = System.getProperty("os.name");
if (osName != null && osName.toLowerCase().contains("windows")) {
if (arg.equals("")) {
return "\"\"";
} else {
StringBuilder sb = new StringBuilder();
int numBackslashes = 0;
boolean needsQuoting = false;
for (int i = 0; i < arg.length(); i++) {
char c = arg.charAt(i);
switch (c) {
case '"': {
for (int nb = 0; nb < numBackslashes; nb++) {
sb.append('\\');
}
numBackslashes = 0;
sb.append('\\');
break;
}
case '\\': {
numBackslashes++;
break;
}
case ' ':
case '\t':
case (char)11:
{
needsQuoting = true;
numBackslashes = 0;
break;
}
default: {
numBackslashes = 0;
break;
}
}
sb.append(c);
}
if (needsQuoting) {
for (int nb = 0; nb < numBackslashes; nb++) {
sb.append('\\');
}
return "\"" + sb.toString() + "\"";
}
return sb.toString();
}
} else {
return arg;
}
}

protected Process execute(String cmd, ArrayList<String> args) throws IOException {
ArrayList<String> cmdAndArgs = new ArrayList<String>();
cmdAndArgs.add(cmd);
cmdAndArgs.addAll(args);
for (String arg : args) {
cmdAndArgs.add(escapeArg(arg));
}
ProcessBuilder builder = new ProcessBuilder(cmdAndArgs);
builder.directory(Loader.getCWD());
return builder.start();
Expand Down

0 comments on commit b697cc5

Please sign in to comment.