Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Run a batch file from Java application

I am trying to run a .bat file from my Java application, but I am worried about the command line injection or any other possible attacks that might arise if I run a .bat using a Java application. Is there a secure way that to run a .bat file using a Java application?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Well the short answer is to clean the input being sent to the batch script. Effectively this means the command line parameters. For example,

Process p = Runtime.getRuntime().exec("runBatch.bat")

If you don’t pass anything to the batch file that is entirely safe because there is nothing the user could manipulate that would make you do something you didn’t intend. This is assuming the hacker can’t swap out the batch script you run, but that’s attacking something else in your environment other than your Java software (ie OS, file shares, file permissions, etc).

This all depends on what command line parameters you are sending to the batch script.

Process p = Runtime.getRuntime().exec(new String[] { "runBatch.bat", arg1, arg2 });

If arg1 and arg2 could be populated from user input then you’ll need to clean them. Mostly, I’d be keen to focus of any file paths they could try and mess with. For example, if you wanted to have them provide information about certain file paths, but that file path shouldn’t escape a root directory then you need to contain the resulting path to that directory.

   File rootDir = new File("...")
   File arg1 = new File( userInput )
   File arg2 = new File( userInput )
   
   if( isWithin( rootDir, arg1 ) && isWithin( rootDir, arg2 ) ) {
      Runtime.getRuntime().exec( new String[] { "runBatch.bat", arg1, arg2 } )
   }

public boolean isWithn( File rootDir, File file ) {
   return arg1. getCanonicalPath().startsWith( rootDir. getCanonicalPath() );
}

Beyond that you just need to sanity check other parameters to make sure they are what you expect.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading