0

I have a form data which recieved java code from user and store it in the database.

So how do I sanitize the input to make sure that it is indeed java code?

Ninja
  • 1
  • 1

2 Answers2

-1

what do you want to achiveve with that, you want to save java code to database?, well if you want to do something like that then you need regular expressions i think, thats the first thing it comes to my head

Pavul Zavala
  • 427
  • 5
  • 11
  • Yes. I only want to save java code into the database. What I have in mind is to write the user Input into a temp file and try to execute the file as a java file. The problem I am facing is that the file name to be compile must have the same java class name. If not it is bound to have an error during compilation. Any walk around? – Ninja Aug 20 '16 at 05:41
-1

This sounds somewhat dangerous (not the storing of java text code in a DB), but why would such a use case come up. Nevertheless...

If you are not going to be expecting all aspects of the Java language, you may want to look into BeanShell. Beanshell can take java source code and evaluate it without compiling. You can likely "source" the code without executing it. If it passes, then it is java code, if not, then it is not java code. However, Beanshell does not accept all modern syntax and structures of newer Java editions.

One easy way to verify that it is indeed java code is to try to compile it (this of course gets messy if the code requires dependencies). If you do take this route, then make sure you are compiling in a DMZ computer/user (I am not aware of any risks of compiling untrusted code, but there might be).... just don't run the code after you compile it!

adamM
  • 1,116
  • 10
  • 29