Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#java# 规范 针对js脚本引擎的代码注入 增补修订建议 #14

Open
k4n5ha0 opened this issue May 24, 2021 · 0 comments
Open

Comments

@k4n5ha0
Copy link

k4n5ha0 commented May 24, 2021

攻击者可以构造恶意js注入到js引擎执行恶意代码,所以在java中使用js引擎应使用安全的沙盒模式执行js代码。

脆弱代码:

public void runCustomTrigger(String script) {
	ScriptEngineManager factory = new ScriptEngineManager();
	ScriptEngine engine = factory.getEngineByName("JavaScript");

	// 不执行安全校验,直接eval执行可能造成恶意的js代码执行
	engine.eval(script); 
}

解决方案:

java 8 或者 8 以上版本使用 delight-nashorn-sandbox 组件

<dependency>
    <groupId>org.javadelight</groupId>
    <artifactId>delight-nashorn-sandbox</artifactId>
    <version>[insert latest version]</version>
</dependency>

// 创建沙盒
NashornSandbox sandbox = NashornSandboxes.create();

// 沙盒内默认禁止js代码访问所有的java类对象
// 沙盒可以手工授权js代码能访问的java类对象
sandbox.allow(File.class);

// eval执行js代码
sandbox.eval("var File = Java.type('java.io.File'); File;")

java 7 使用 Rhino 引擎

public void runCustomTrigger(String script) {
	// 启用 Rhino 引擎的js沙盒模式
	SandboxContextFactory contextFactory = new SandboxContextFactory();
	Context context = contextFactory.makeContext();
	contextFactory.enterContext(context);
	try {
		ScriptableObject prototype = context.initStandardObjects();
		prototype.setParentScope(null);
		Scriptable scope = context.newObject(prototype);
		scope.setPrototype(prototype);

		context.evaluateString(scope,script, null, -1, null);
	} finally {
		context.exit();
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant