我有以下两个代码测试。
首先:JavaTypeTest()按预期阻止对java.io.File的访问。
第二个:JavaMethodGetFileTest(),它在返回java.io.File对象时不会阻止访问,从而绕过过滤器。
在使用Java.type()时是不是应该阻止任何东西?或者我是否应该将对象添加到引擎中?
预期产出:
JavaTypeTest success: true
JavaMethodGetFileTest success: true
实际输出:
JavaTypeTest success: true
Z:\eclipse ws\NashornTests\.
JavaMethodGetFileTest success: false
这背后的原因是我想要一个代理类,它只允许返回允许对象的方法,但是有一个getInstance()方法返回一个dissallowedObject,这样我就可以访问代理中包含的实例,而不会将它暴露给Nashorn
public class NashornTest
{
class NashornClassFilter implements ClassFilter
{
public NashornClassFilter()
{
}
@Override
public boolean exposeToScripts(String clazz)
{
if (clazz.equals("java.io.File")) return false;
return true;
}
}
public static class AllowedClass
{
public AllowedClass()
{
}
public File disallowedMethod()
{
return new File(".");
}
}
public static void main(String[] args)
{
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
NashornClassFilter filter = new NashornTest().new NashornClassFilter();
NashornScriptEngine engine = (NashornScriptEngine) factory.getScriptEngine(filter);
NashornClassFilter filter1 = new NashornTest().new NashornClassFilter();
NashornScriptEngine engine1 = (NashornScriptEngine) factory.getScriptEngine(filter1);
System.out.println("JavaTypeTest success: " + JavaTypeTest(engine));
System.out.println("JavaMethodGetFileTest success: " + JavaMethodGetFileTest(engine1));
}
public static boolean JavaTypeTest(NashornScriptEngine engine)
{
try
{
engine.eval(
"function wrapper(){ "
+ "Java.type('java.io.File');"
+ "}");
((Invocable) engine).invokeFunction("wrapper");
}
catch (RuntimeException e)
{
if(e.getCause() instanceof ClassNotFoundException) return true;
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}
return false;
}
public static boolean JavaMethodGetFileTest(NashornScriptEngine engine)
{
try
{
engine.put("allowed", new AllowedClass());
engine.eval(
"function wrapper(){ "
+ "var file = allowed.disallowedMethod();"
+ "print(file.getAbsolutePath());"
+ "}");
((Invocable) engine).invokeFunction("wrapper");
}
catch(RuntimeException e)
{
if(e.getCause() instanceof ClassNotFoundException) return true;
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
}
return false;
}
}