Java Jsch组件研究

JSch 是 SSH2 协议在 Java 中的一种实现,通过 JSch 可以连接到任意一台 SSHD 服务器,实现远程命令执行、SSH会话、端口转发、X11 转发、文件操作等功能。

JSch使用

创建一个 maven 项目,引入 jsch 的依赖

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>

通过 JSch 创建 ssh session,之后调用 channel 实现命令执行、交互式 shell、文件操作、转发等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public String case01Exec(String user, String host, int port, String password, String filename) throws JSchException, IOException {
JSch jsch = new JSch();

Session session = jsch.getSession(user, host, 22);

session.setPassword(password);
session.connect();
String command = "scp -f " + filename;
Channel channel = session.openChannel("exec");

((ChannelExec) channel).setCommand(command);

// get I/O streams for remote scp
OutputStream out = channel.getOutputStream();

channel.connect();
return "success";
}

其中,channel 类型包括:session、shell、exec、x11、auth-agent@openssh.com、direct-tcpip、forwarded-tcpip、sftp、subsystem,分别对应 jsch 不同的 channel 实现类。

note: Spring-JSch靶场 将在 https://github.com/VulScanSpace 开源

SAST与IAST如何检测?

漏洞触发方法为 com.jcraft.jsch.ChannelExec.setCommand(java.lang.String),因此,设置 ChannelExec 类的 setCommand 方法为 sink 点即可实现漏洞检测。

通过 CodeQL 的 CWE-078/ExecTainted.ql 规则可实现检测,CodeQL 的规则详情如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Provides classes for JSch OS command injection detection
*/

import java

/** The class `com.jcraft.jsch.ChannelExec`. */
private class JSchChannelExec extends RefType {
JSchChannelExec() { this.hasQualifiedName("com.jcraft.jsch", "ChannelExec") }
}

/** A method to set an OS Command for the execution. */
private class ChannelExecSetCommandMethod extends Method, ExecCallable {
ChannelExecSetCommandMethod() {
this.hasName("setCommand") and
this.getDeclaringType() instanceof JSchChannelExec
}

override int getAnExecutedArgument() { result = 0 }
}

JSch 远程命令执行漏洞如何修复?

远程命令执行的漏洞修复方案与命令执行的修复方案相同,严格限制输入的命令即可,推荐修复方案:限制输入的命令/参数,只允许输入 [a-zA-Z0-9.] 正则中的内容

参考链接

进击的DevSecOps,持续分享SAST/IAST/RASP的技术原理及甲方落地实践。如果你对 SAST、IAST、RASP方向感兴趣,可以扫描下方二维码关注公众号,获得更及时的内容推送。

owefsad wechat
进击的DevSecOps,持续分享SAST/IAST/RASP的技术原理及甲方落地实践。如果你对 SAST、IAST、RASP方向感兴趣,可以扫描下方二维码关注公众号,获得更及时的内容推送。
0%