1

I'm looking to use the Jython in a Java project I'm working on. And I'm wondering 2 things.

  1. Can I disable access to Java classes from Python scripts. IE. stop scripts from being able to do things like from java.util import Date?

  2. And can I change the output stream that print "Hello" etc write to, so that I can redirect a scripts output for my implementation?

Or will I have to edit the actual Jython classes to disable and change this?

tomass1996
  • 545
  • 4
  • 6

2 Answers2

0

In order to restrict access to specific Java classes you could implement a custom class loader and register it to Jython:

this.pyInterpreter.getSystemState().setClassLoader(this.userCodeClassLoader);

If you are doing this because of security issues (disallow some actions on server machine that runs user code) you have to notice that Jython also provides built-in function implementations that won't be caught by your class loader:

Built-in Python function implementations

AndyG
  • 39,700
  • 8
  • 109
  • 143
PAX
  • 1,056
  • 15
  • 33
0

One additional approach is to analyze all imports in Python parse tree. I think it's better having more than one security measure:

   String code = "import sys\n"+"from java.io import File\n"+"sys.exit()";
   AnalyzingParser anPar = new  AnalyzingParser(new ANTLRStringStream(code), "", "ascii");

   mod tree=anPar.parseModule();
   Visitor vis = new Visitor() {
       @Override
       public Object visitImport(Import node) throws Exception {
          System.out.println(node);
                       return node;
       }

       @Override
       public Object visitImportFrom(ImportFrom node) throws Exception {
          System.out.println(node);
                       return node;
       }
         };
   List<PythonTree> children=tree.getChildren();
   for (PythonTree c : children){
         vis.visit(c);
   }
PAX
  • 1,056
  • 15
  • 33