Command injection attack: tempered input value with && - java

Controller:
#PostMapping("/output/")
#ResponseBody
public Object command_injected(#RequestParam String command) {
Map<String, String> response_data = new HashMap<String, String>();
try {
String output = "";
Process p = Runtime.getRuntime().exec("ping -c 3 " + command) ;
String line = "";
BufferedReader inputStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader errorStream = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = inputStream.readLine()) != null) {
output += line + "<br/>";
}
inputStream.close();
while ((line = errorStream.readLine()) != null) {
output += line + "<br/>";
}
errorStream.close();
p.waitFor();
response_data.put("status", "success");
response_data.put("msg", output);
return response_data;
} catch (Exception e) {
e.printStackTrace();
response_data.put("status", "error");
response_data.put("msg", "No output found");
return response_data;
}
}
example input (Linux):
8.8.8.8 && ls && whoami
To show a command injection attack, I want to temper my input using &&. If I enter only IP address, this thing works. If I enter the above example, things are not ok and giving me the following:
ping: whoami: Temporary failure in name resolution
Please help!!

Related

How to fetch a string from a output in console in java and compare it with the expected value

Below is the code:
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The following is my output:
Context successfully set
Script started
LXKADMIN|In/OutBoundValidation|-|50149.11065.26960.11788|inbound=OFF|outbound=OFF
inbound=OFF|outbound=OFF
Script complete
STEP 1: COMPLETED
PASSED: step1
I want to fetch the line 5 "inbound=OFF|outbound=OFF" and check if its value is matching "inbound=OFF|outbound=OFF" then my test case will pass else it will fail.
The TCL Script is:
tcl;
eval {
puts "Script started"
set schemaValidationStr [mql temp query bus LXKADMIN In/OutBoundValidation * select id description dump '|']
puts $schemaValidationStr
set schemaValidation [string range $schemaValidationStr 57 end]
puts $schemaValidation
puts "Script complete"
}
Any suggestion will be really helpful.
If your question is just how to verify that the output returned by your TCL script, contains a specific line, than you might try this:
public static final int CHECK_LINE_NR = 4;
public static final String EXPECTED_LINE_VALUE = "inbound=OFF|outbound=OFF";
public boolean verifyScriptOutput(ChannelExec channel)
throws IOException
{
// Check all lines in output
BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
String line;
int linenr = 0;
while ((line = reader.readLine()) != null)
{
linenr++;
if (linenr == CHECK_LINE_NR)
return (line.equals(EXPECTED_LINE_VALUE));
}
// If we get here, output has less lines
return (false);
} // verifyScriptOutput
The point at which you are reasoning is not possible because you can not access the console and see what is visualized. Instead you should process the input that the console gets, and outputs it, which is the line variable in your case.
If for you is enough to see that inbound=OFF|outbound=OFF you can search that substring in the line like this:
if(line.indexOf("inbound=OFF|outbound=OFF") != -1) {
// you have a match
}
I'm not sure I understood the question, but you might try this:
public static final int CHECK_LINE_NR = 4;
public static final String CHECK_LINE_VALUE = "inbound=OFF|outbound=OFF";
InputStream in = channelExec.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
int linenr;
boolean line_check_passed;
linenr = 0;
line_check_passed = false;
while ((line = reader.readLine()) != null) {
linenr++;
if (linenr == CHECK_LINE_NR)
line_check_passed = line.equals(CHECK_LINE_VALUE);
System.out.println(line);
}
} catch (JSchException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
public static boolean check(InputStream in, int line, String expected) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
int i = 0;
String str;
while ((str = reader.readLine()) != null) {
if (i < line)
i++;
else
return expected.equals(str);
}
return false;
}

Empty line in arraylist Java

protected synchronized static void getRandomProxy(String srcFile) throws FileNotFoundException {
List<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
System.out.println(line);
}
int k = 0;
for (int i = 0; i < words.size(); i++) {
k++;
String[] splitted = words.get(i).split(":");
String ip = splitted[0];
String port = splitted[splitted.length - 1];
// System.out.println(k + " " + ip + " * " + port);
}
} catch (IOException iOException) {
} finally {
try {
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I want to get output printed without empty lines .
These are kind of results am getting Like :
result 1.
result 2.
result 3.
i want output like :
result 1.
result 2.
result 3.
without blank lines.
Don't add the String to the list if it's empty :
if(!line.trim().isEmpty()) {
words.add(line);
System.out.println(line);
}
If you still want to add the blank lines to the list but don't display them, just move the condition :
words.add(line);
if(!line.trim().isEmpty())
System.out.println(line);
Doc
Use System.out.print. Note that the file contains a newline char at the end of each line.
If srcFile is created with Notepad, try removing first the carriage return char System.out.print(line.replaceAll("\\r",""))
ArrayList<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim(); // remove leading and trailing whitespace
if (!line.isEmpty() && !line.equals("")) {
words.add(line);
System.out.println(line);
}
}

No output from Runtime.getRuntime().exec("ls")

ping and date returned output, but it's not returning anything from "ls" or "pwd". What I want to do ultimately is run an SSH command. Any idea what I am missing below?
//Works and shows the output
executeCommand("ping -c 3 " + "google.com");
//Works and shows the output
executeCommand("date");
//Does not work. No output
executeCommand("sudo ls");
//Does not work. No output
executeCommand("ls");
private void executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("Output", "Output: " + output.toString());
}
I have two solutions
first solution (you need Java 7):
...
ProcessBuilder pb = new ProcessBuilder("ls");
pb.redirectOutput(Redirect.INHERIT);
Process p = pb.start();
second solution:
Process p=Runtime.getRuntime().exec("ls");
InputStream is = p.getInputStream();
int c;
StringBuilder commandResponse = new StringBuilder();
while( (c = is.read()) != -1) {
commandResponse.append((char)c);
}
System.out.println(commandResponse);
is.close();

Java - Remote Console

For my server coded in java I want to add a console. I connect to my server using a socket.
Here is the code I've made for the console:
On my server:
public class ServerConsole
{
public String exec(String[] cmd)
{
try
{
Process child = Runtime.getRuntime().exec(cmd);
InputStream in = child.getInputStream();
StringBuffer buffer = new StringBuffer();
int c;
while ((c = in.read()) != -1)
{
buffer.append((char)c);
}
in.close();
return buffer.toString();
}
catch (Exception e) {}
return "FAILED";
}
}
This class execute the given command and returns a string that contains the content of the console after execution.
I call this method like that:
String cmd_data_cmd = inputStream.readUTF();
String[] dataCmd = cmd_data_cmd.split("#");
OSCmd osCmd = new OSCmd();
outputStream.writeUTF(osCmd.exec(dataCmd));
Where inputStream is the stream I use with my socket. It works well!
Now, on the client side, I've made that:
String[] cmd = cmd_input.getText().split(" ");
String new_cmd = "";
for (String part : cmd)
new_cmd += (new_cmd.equals("") ? "": "#") + part;
this.outputSocket.writeUTF(new_cmd);
DataInputStream result_input = new DataInputStream(this.input);
String tmp = result_input.readUTF();
System.out.println(tmp);
This should returns me the result displayed in the console but actually, nothing happens. It just freezes when I start that part of code.
Any idea how to do that?
Thanks.
Here is the solution:
String[] cmd_exec = {};
String os_name = System.getProperty("os.name").toLowerCase();
if (os_name.indexOf("win") >= 0)
cmd_exec = new String[]{"cmd.exe", "/c", cmd};
else if (os_name.indexOf("mac") >= 0)
cmd_exec = new String[]{"/usr/bin/open", "-a", cmd};
else if (os_name.indexOf("nix") >= 0 || os_name.indexOf("nux") >= 0)
cmd_exec = new String[]{"/bin/bash", cmd};
else if (os_name.indexOf("sunos") >= 0)
cmd_exec = new String[]{"/bin/bash", cmd};
Process child = Runtime.getRuntime().exec(cmd_exec);
String line;
while ((line = stdInput.readLine()) != null)
{
buffer.append("\t" + new String(line.getBytes("UTF-8"), "UTF-8") + "\n");
}
stdInput.close();
while ((line = stdError.readLine()) != null)
{
buffer.append("\t" + new String(line.getBytes("UTF-8"), "UTF-8") + "\n");
}
stdError.close();
child.destroy();
Hope this will help someone else.

How to compile & run java and C file from java code?

I am working on an Editor application where I can compile and run c,cpp and Java file.I am developing this application using java programming language.I am developing it in Eclipse.
I am able to create new files(c,cpp and java) on specific locations and also I am able to save file to different-2 locations.
And for execution I am using following methods.
String compileFileCommand = "javac "+fileName;
Process compile_process = new ProcessBuilder(compileFileCommand).redirectErrorStream(true).start();
compile_process.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(compile_process.getInputStream()));
String line=reader.readLine();
while(line!=null) {
System.out.println(line);
line=reader.readLine();
}
My problem is that I am not able to compile files from their corresponding locations.
Always giving Exception
java.io.IOException: error=2, No such file or directory
Please tell me how can I compile and run all c,c++ & java files.
Please also give me any other suggestion for my application.
Edited ..
I have used these two methods for compiling and running.On Compiling it creates a class file in case of Java.But all the time I am getting null from InputStreams(both getErrorStream() and getInputStream()).
void compileJavaFile(String fileName)
{
String compileFileCommand = "javac " + fileName;
try
{
System.out.println("Executing Java File");
Process compileProcess = Runtime.getRuntime().exec(compileFileCommand);
String line = "";
BufferedReader bri = new BufferedReader(new InputStreamReader(compileProcess.getInputStream()));
BufferedReader bre = new BufferedReader(new InputStreamReader(compileProcess.getErrorStream()));
while ((line = bri.readLine()) != null)
{
System.out.println(line);
}
bri.close();
while ((line = bre.readLine()) != null)
{
System.out.println(line);
}
bre.close();
compileProcess.waitFor();
System.out.println("Done.");
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runJavaFile(String fileName)
{
String runFileCommand = "java " + fileName.split(".java")[0];
try
{
System.out.println("runFileCommand : " + runFileCommand);
System.out.println("Running Java File");
Process runProcess = Runtime.getRuntime().exec(runFileCommand);
BufferedReader reader = new BufferedReader(new InputStreamReader(runProcess.getInputStream()));
String line = reader.readLine();
System.out.println("line = " + line);
while (line != null)
{
System.out.println(line);
line = reader.readLine();
}
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
And for C and C++ I am using.
void compileCFile(String fileName)
{
String compileFileCommand = "gcc " + fileName;
resultString = "";
try
{
System.out.println("Compiling C File");
Process processCompile = Runtime.getRuntime().exec(compileFileCommand);
BufferedReader brCompileError = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String errorCompile = brCompileError.readLine();
if (errorCompile != null)
System.out.println("Error Compiler = " + errorCompile);
resultString += errorCompile +"\n";
BufferedReader brCompileRun = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String outputCompile = brCompileRun.readLine();
if (outputCompile != null)
System.out.println("Output Compiler = " + outputCompile);
resultString += outputCompile +"\n";
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runCFile(String fileName)
{
String runFileCommand = "./" + fileName.split(".c")[0];
try
{
System.out.println("Running C File");
Process processRun = Runtime.getRuntime().exec(runFileCommand);
BufferedReader brRun = new BufferedReader(new InputStreamReader(processRun.getErrorStream()));
String errorRun = brRun.readLine();
if (errorRun != null)
System.out.println("Error Run = " + errorRun);
BufferedReader brResult = new BufferedReader(new InputStreamReader(processRun.getInputStream()));
String outputRun = brResult.readLine();
if (outputRun != null)
System.out.println("Output Run = " + outputRun);
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void compileCPPFile(String fileName)
{
String compileFileCommand = "g++ " + fileName;
try
{
System.out.println("Compiling CPP File");
Process processCompile = Runtime.getRuntime().exec(compileFileCommand);
BufferedReader brCompileError = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String errorCompile = brCompileError.readLine();
if (errorCompile != null)
System.out.println("Error Compiler = " + errorCompile);
resultString += errorCompile +"\n";
BufferedReader brCompileRun = new BufferedReader(new InputStreamReader(processCompile.getErrorStream()));
String outputCompile = brCompileRun.readLine();
if (outputCompile != null)
System.out.println("Output Compiler = " + outputCompile);
resultString += outputCompile +"\n";
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
void runCPPFile(String fileName)
{
String runFileCommand = "./" + fileName.split(".cpp")[0];
try
{
System.out.println("Running CPP File");
Process processRun = Runtime.getRuntime().exec(runFileCommand);
BufferedReader brRun = new BufferedReader(new InputStreamReader(processRun.getErrorStream()));
String errorRun = brRun.readLine();
if (errorRun != null)
System.out.println("Error Run = " + errorRun);
BufferedReader brResult = new BufferedReader(new InputStreamReader(processRun.getInputStream()));
String outputRun = brResult.readLine();
if (outputRun != null)
System.out.println("Output Run = " + outputRun);
} catch (Exception e)
{
// TODO: handle exception
System.out.println("Exception ");
System.out.println(e.getMessage());
}
}
In case of C and C++ it show error like
g++: /media/disk/eclipse/\/UniversalIDE/CPP/firstCPP: No such file or directory
Please give me solution for my problems ..
Please try following,
Process p = Runtime.getRuntime().exec(command);
command is a string you pass. in command you can pass "javac Test.java" to compile your java file & just like that you can use other commands.
replace the line
String runFileCommand = "./" + fileName.split(".c")[0];
with
String runFileCommand = "./a.out";

Categories

Resources