Commit 336793c0 by 钱炳权

ssh至服务器并用websocket返回运行数据

parent 4f3c6779
......@@ -19,6 +19,27 @@
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<dependencies>
<!--WebSocket核心依赖包-->
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.8</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.7.2</version>
</dependency>
<dependency> <!--远程Linux连接依赖-->
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
......
package com.example.fuzzControll;
import com.example.fuzzControll.tools.LinuxCommandUtil;
import com.jcraft.jsch.JSchException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import java.io.IOException;
import java.util.Arrays;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class FuzzIntegration {
public static void main(String[] args) {
public static void main(String[] args) throws JSchException, IOException {
Arrays.stream(args).forEach(System.out::println);
SpringApplication.run(FuzzIntegration.class, args);
System.out.println("Start successfully!");
// String host = "192.168.9.177";
// int port = 22;
// String user = "root";
// String password = "123456";
// // 手动创建对象实现连接
// LinuxCommandUtil linuxCommandUtil = new LinuxCommandUtil();
// linuxCommandUtil.connect(host, port, user, password);
// linuxCommandUtil.execCmd("source /etc/profile");
// linuxCommandUtil.close();
// linuxCommandUtil.connect(host, port, user, password);
// linuxCommandUtil.execCmd("source /etc/profile && afl-fuzz -d -i /usr/fuzzenv/fuzzenv/aflnet/tutorials/live555/in-rtsp -o /home/2024-06-12-09-44-02-RTSP-output -x /usr/fuzzenv/fuzzenv/aflnet/tutorials/live555/rtsp.dict -N tcp://127.0.0.1/8554 -P RTSP -D 1000 -K -E -R -F -q 3 -s 3 /usr/fuzzenv/fuzzenv/live555/testProgs/testOnDemandRTSPServer 8554");
// linuxCommandUtil.close();
//
// // 直接一次性连接ssh并执行指令
// System.out.println(LinuxCommandUtil.exeLinuxBySSH(host, port, user, password, "cat /home/project/test.txt"));
//
// // 给本地下发linux指令
// LinuxCommandUtil.exeLocLinuxCmd("pwd");
}
}
package com.example.fuzzControll.conf;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component("AflnetSshProperties")
@ConfigurationProperties(prefix = "aflnetssh")
public class AflnetSshProperties {
String host;
int port;
String user;
String password;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.example.fuzzControll.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.example.fuzzControll.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RestController;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.net.URI;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author
*/
@Component("WebSocket")
@ServerEndpoint("/websocket/testResult/{name}")
@Slf4j
@CrossOrigin
public class WebSocket {
private Session session; //与某个客户端连接对话,通过此对客户端发送消息
private static final ConcurrentHashMap<String, WebSocket> WEBSOCKET_CONCURRENTHASHMAP = new ConcurrentHashMap<String, WebSocket>(); //存放所有连接的客户端
@OnOpen
public void onOpen(Session session, @PathParam(value = "name") String name) {
this.session = session; //默认客户端,没有重名
WEBSOCKET_CONCURRENTHASHMAP.put(name, this);
log.info("Websocket is connected! The man is {}.There are {} people in the connection ", name, WEBSOCKET_CONCURRENTHASHMAP.size());
}
@OnClose
public void onClose() {
for (String name : WEBSOCKET_CONCURRENTHASHMAP.keySet()) {
if (this == WEBSOCKET_CONCURRENTHASHMAP.get(name)) {
WEBSOCKET_CONCURRENTHASHMAP.remove(name);
break;
}
}
log.info("Websocket is closed! There are {} people in the connection ", WEBSOCKET_CONCURRENTHASHMAP.size());
}
@OnError
public void onError(Session session, Throwable throwable) {
System.out.println("error:");
throwable.printStackTrace();
}
@OnMessage
// @SendTo("")
public void onMessage(Session session, String message) {
for (String senderStr : WEBSOCKET_CONCURRENTHASHMAP.keySet()) {//获取sender的Stirng
if (WEBSOCKET_CONCURRENTHASHMAP.get(senderStr).getSession() == session) {
appointSending("fuzzMaster", "web", message.substring(message.indexOf(";") + 1));
}
}
}
public void groupSending(String message, Session exIncludeSession) {
for (String name : WEBSOCKET_CONCURRENTHASHMAP.keySet()) {
try {
if (exIncludeSession == WEBSOCKET_CONCURRENTHASHMAP.get(name).session) {
continue;
}
WEBSOCKET_CONCURRENTHASHMAP.get(name).session.getBasicRemote().sendText(name + ":" + message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void appointSending(String sender, String name, String message) {
try {
// WEBSOCKET_CONCURRENTHASHMAP.get(name).session.getBasicRemote().sendText(sender + ":" + message);
WEBSOCKET_CONCURRENTHASHMAP.get(name).session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
public Session getSession() {
return session;
}
}
\ No newline at end of file
package com.example.fuzzControll.pojo.vo;
import lombok.Data;
@Data
public class TestReturnEntity {
String run_time;
String cycles_done;
String last_new_path;
String total_paths;
String last_uniq_crash;
String uniq_crashes;
String last_uniq_hang;
String uniq_hangs;
String now_processing;
String map_density;
String paths_timed_out;
String count_coverage;
String now_trying;
String favored_paths;
String stage_execs;
String new_edges_on;
String total_execs;
String total_crashes;
String exec_speed;
String total_tmouts;
String bit_flips;
String levels;
String byte_flips;
String pending;
String arithmetics;
String pend_fav;
String known_ints;
String own_finds;
String dictionary;
String imported;
String havoc;
String stability;
String trim;
}
......@@ -9,10 +9,12 @@ import com.example.fuzzControll.service.TestService;
import com.example.fuzzControll.tools.CmdTools;
import com.example.fuzzControll.tools.GlobalParameters;
import com.example.fuzzControll.tools.TestControlTools;
import com.jcraft.jsch.JSchException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
......@@ -29,7 +31,7 @@ public class TestServiceImpl implements TestService {
//todo 不同服务不同端口
@Override
public void testStart(CmdStartParams cmdStartParams) throws AflnetException, CmdException {
public void testStart(CmdStartParams cmdStartParams) {
TestControlTools.setIsRunning(true);
String cmd = cmdTools.parse(cmdStartParams);
Date date = new Date();
......@@ -37,7 +39,13 @@ public class TestServiceImpl implements TestService {
String outputFileName = df.format(date)+cmdStartParams.getProtopcol()+"-output";
String finalCmd = CmdConstent.RUN_AFLNET_BEFORE + outputFileName + CmdConstent.RUN_AFLNET_AFTER + cmd + aflnetProperties.getAflnetPath() + "live555/testProgs/testOnDemandRTSPServer 8554";
log.info("The cmd is [{}]",finalCmd);
cmdTools.runProgramCmd(finalCmd, outputFileName + ".zip");
try {
cmdTools.runProgramCmd("source /etc/profile && "+finalCmd);
} catch (JSchException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
......
package com.example.fuzzControll.tools;
import com.alibaba.fastjson.JSONObject;
import com.example.fuzzControll.conf.AflnetSshProperties;
import com.example.fuzzControll.exception.AflnetException;
import com.example.fuzzControll.exception.CmdException;
import com.example.fuzzControll.pojo.vo.*;
import com.jcraft.jsch.JSchException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
......@@ -18,7 +20,7 @@ import java.util.stream.Collectors;
public class CmdTools {
Boolean show = true;
Boolean send = false;
/**
* 运行不需要后台运行cmd
*/
......@@ -42,17 +44,16 @@ public class CmdTools {
* 运行需要后台运行cmd
* 通过websocket返回数据
*/
public void runProgramCmd(String cmd, String outputFileName) throws AflnetException {
try {
Process process = Runtime.getRuntime().exec(cmd);
printMessageToCmd(process.getInputStream());
printMessage(process.getErrorStream(), new ArrayList<String>());
process.waitFor();
log.info("Aflnet cmd have been run.");
} catch (Exception e) {
e.printStackTrace();
throw new AflnetException("Aflnet run error");
}
public void runProgramCmd(String cmd) throws AflnetException, JSchException, IOException {
AflnetSshProperties aflnetSshProperties = GlobalParameters.aflnetSshProperties;
String host = aflnetSshProperties.getHost();
int port =aflnetSshProperties.getPort();
String user = aflnetSshProperties.getUser();
String password = aflnetSshProperties.getPassword();
// 手动创建对象实现连接
LinuxCommandUtil linuxCommandUtil = new LinuxCommandUtil();
linuxCommandUtil.connect(host, port, user, password);
linuxCommandUtil.execCmd(cmd);
}
......@@ -130,5 +131,102 @@ public class CmdTools {
}
return cmd.toString();
}
public TestReturnEntity makeReturnEntity(String line, TestReturnEntity returnEntity) {
if (line.contains("All set and ready to roll!") || line.contains("american fuzzy") || line.contains("process timing overall results")) {
show = false;
} else if (line.contains("PROGRAM ABORT")) {
log.error("Aflnet run failed !");
throw new AflnetException("Aflnet run failed !");
}
if (show) {
log.info(line);
}
if (line.contains("run time")) {
send = false;
int run_time = line.indexOf(":");
int cycles_done = line.indexOf("cycles done :");
returnEntity.setRun_time(line.substring(run_time + 1, run_time + 30));
returnEntity.setCycles_done(line.substring(cycles_done + 13, cycles_done + 18));
} else if (line.contains("last new path")) {
int last_new_path = line.indexOf(":");
int total_paths = line.indexOf("total paths :");
returnEntity.setLast_new_path(line.substring(last_new_path + 1, last_new_path + 30));
returnEntity.setTotal_paths(line.substring(total_paths + 13, line.indexOf("total paths :") + 16));
} else if (line.contains("last uniq crash")) {
int last_uniq_crash = line.indexOf(":");
int uniq_crashes = line.indexOf("uniq crashes :");
returnEntity.setLast_uniq_crash(line.substring(last_uniq_crash + 1, last_uniq_crash + 30));
returnEntity.setUniq_crashes(line.substring(uniq_crashes + 14, uniq_crashes + 19));
} else if (line.contains("last uniq hang")) {
int last_uniq_hang = line.indexOf(":");
int uniq_hangs = line.indexOf("uniq hangs :");
returnEntity.setLast_uniq_hang(line.substring(last_uniq_hang + 1, last_uniq_hang + 30));
returnEntity.setUniq_hangs(line.substring(uniq_hangs + 12, uniq_hangs + 16));
} else if (line.contains("now processing")) {
int now_processing = line.indexOf(":");
int map_density = line.indexOf("map density :");
returnEntity.setNow_processing(line.substring(now_processing + 1, now_processing + 12));
returnEntity.setMap_density(line.substring(map_density + 13, map_density + 25));
} else if (line.contains("paths timed out")) {
int paths_timed_out = line.indexOf(":");
int count_coverage = line.indexOf("count coverage :");
returnEntity.setPaths_timed_out(line.substring(paths_timed_out + 1, paths_timed_out + 12));
returnEntity.setCount_coverage(line.substring(count_coverage + 16, count_coverage + 35));
} else if (line.contains("now trying")) {
int now_trying = line.indexOf(":");
int favored_paths = line.indexOf("favored paths :");
returnEntity.setNow_trying(line.substring(now_trying + 1, now_trying + 18));
returnEntity.setFavored_paths(line.substring(favored_paths + 15, favored_paths + 28));
} else if (line.contains("stage execs")) {
int stage_execs = line.indexOf(":");
int new_edges_on = line.indexOf("new edges on :");
returnEntity.setStage_execs(line.substring(stage_execs + 1, stage_execs + 18));
returnEntity.setNew_edges_on(line.substring(new_edges_on + 14, new_edges_on + 31));
} else if (line.contains("total execs")) {
int total_execs = line.indexOf(":");
int total_crashes = line.indexOf("total crashes :");
returnEntity.setTotal_execs(line.substring(total_execs + 1, total_execs + 5));
returnEntity.setTotal_crashes(line.substring(total_crashes + 15, total_crashes + 31));
} else if (line.contains("exec speed") && line.contains("total tmouts")) {
int exec_speed = line.indexOf(":");
int total_tmouts = line.indexOf("total tmouts :");
returnEntity.setExec_speed(line.substring(exec_speed + 1, exec_speed + 25));
returnEntity.setTotal_tmouts(line.substring(total_tmouts + 14, total_tmouts + 27));
} else if (line.contains("bit flips")) {
int bit_flips = line.indexOf(":");
int levels = line.indexOf("levels :");
returnEntity.setBit_flips(line.substring(bit_flips + 1, bit_flips + 18));
returnEntity.setLevels(line.substring(levels + 8, levels + 12));
} else if (line.contains("byte flips")) {
int byte_flips = line.indexOf(":");
int pending = line.indexOf("pending :");
returnEntity.setByte_flips(line.substring(byte_flips + 1, byte_flips + 16));
returnEntity.setPending(line.substring(pending + 9, pending + 12));
} else if (line.contains("arithmetics")) {
int arithmetics = line.indexOf(":");
int pend_fav = line.indexOf("pend fav :");
returnEntity.setArithmetics(line.substring(arithmetics + 1, arithmetics + 16));
returnEntity.setPend_fav(line.substring(pend_fav + 10, pend_fav + 16));
} else if (line.contains("known ints")) {
int known_ints = line.indexOf(":");
int own_finds = line.indexOf("own finds :");
returnEntity.setKnown_ints(line.substring(known_ints + 1, known_ints + 16));
returnEntity.setOwn_finds(line.substring(own_finds + 11, own_finds + 14));
} else if (line.contains("dictionary") && line.contains("imported")) {
int dictionary = line.indexOf(":");
int imported = line.indexOf("imported :");
returnEntity.setDictionary(line.substring(dictionary + 1, dictionary + 16));
returnEntity.setImported(line.substring(imported + 10, imported + 16));
} else if (line.contains("havoc")) {
int havoc = line.indexOf(":");
int stability = line.indexOf("stability :");
returnEntity.setHavoc(line.substring(havoc + 1, havoc + 18));
returnEntity.setStability(line.substring(stability + 11, stability + 20));
} else if (line.contains("trim")) {
send = true;
int trim = line.indexOf(":");
returnEntity.setTrim(line.substring(trim + 1, trim + 10));
}
return returnEntity;
}
}
\ No newline at end of file
package com.example.fuzzControll.tools;
import com.example.fuzzControll.conf.AflnetProperties;
import com.example.fuzzControll.conf.AflnetSshProperties;
import com.example.fuzzControll.conf.SpringContextUtil;
import com.example.fuzzControll.controller.WebSocket;
import java.util.concurrent.ConcurrentHashMap;
public class GlobalParameters {
public static AflnetSshProperties aflnetSshProperties = (AflnetSshProperties) SpringContextUtil.getBean("AflnetSshProperties");
public static AflnetProperties aflnetProperties = (AflnetProperties) SpringContextUtil.getBean("AflnetProperties");
public static WebSocket webSocket = (WebSocket) SpringContextUtil.getBean("WebSocket");
}
package com.example.fuzzControll.tools;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.fastjson.JSONObject;
import com.example.fuzzControll.pojo.vo.TestReturnEntity;
import org.apache.commons.io.IOUtils;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class LinuxCommandUtil {
private Session session;
private ChannelExec channelExec;
/**
* 默认执行本地linux指令
*/
public static String exeLocLinuxCmd(String cmd) {
String result = "";
Runtime run = Runtime.getRuntime();
try {
Process process = run.exec(cmd);
InputStream in = process.getInputStream();
BufferedReader bs = new BufferedReader(new InputStreamReader(in));
process.destroy();
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 远程执行linux指令
*/
public static String exeLinuxBySSH(String host, int port, String user, String password, String command) throws JSchException, IOException {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand(command);
channelExec.setErrStream(System.err);
channelExec.connect();
String out = IOUtils.toString(in, "UTF-8");
channelExec.disconnect();
session.disconnect();
return out;
}
/**
* 创建连接
*/
public Session connect(String host, int port, String user, String password) throws JSchException {
JSch jsch = new JSch();
session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
channelExec = (ChannelExec) session.openChannel("exec");
return session;
}
/**
* 执行指令
*/
public void execCmd(String command) throws JSchException, IOException {
List<String> result = new ArrayList<>();
InputStream in = channelExec.getInputStream();
channelExec.setCommand(command);
channelExec.setErrStream(System.err);
channelExec.connect();
Reader reader = new InputStreamReader(in);
BufferedReader bf = new BufferedReader(reader);
CmdTools cmdTools = new CmdTools();
String line = null;
TestReturnEntity returnEntity = new TestReturnEntity();
try {
while ((line = bf.readLine()) != null && TestControlTools.getIsRunning()) {
cmdTools.makeReturnEntity(line, returnEntity);
if (cmdTools.send) {
String data = JSONObject.toJSONString(returnEntity);
try {
GlobalParameters.webSocket.appointSending("fuzzMaster", "web", data);
} catch (Exception ignored) {
}
}
}
//结束就关闭
if(!TestControlTools.getIsRunning()){
close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 关闭连接
*/
public void close() {
channelExec.disconnect();
session.disconnect();
}
}
\ No newline at end of file
......@@ -18,4 +18,11 @@ aflnet:
outputPath: "/home/" #D:/code/companyProjects/files/
aflnetPath: "/usr/fuzzenv/fuzzenv/"#alfnet路径
web:
ip: 192.168.9.177
aflnetssh:
host: 192.168.9.177
port: 22
user: root
password: 123456
\ No newline at end of file
......@@ -5,6 +5,6 @@ spring:
active: dev #默认为开发环境
server:
port: 8104
port: 8100
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>websocket client</title>
<script type="text/javascript">
var ws1 = null;
var ws2 = null;
function myFunction() {
ws1 = new WebSocket("ws://192.168.9.177:8100/websocket/testResult/web");
ws1.onmessage = function (evt) {
console.log(evt);
var received_msg =JSON.parse(evt.data) ;
const nameValue = Object.values(received_msg)
var context = '<div class="sendMsg">' +
'aflnet:<br/>'+
'aflnet<h3>'+nameValue+'</h3><br/>'+
' </div>';
document.getElementById("sendDiv").innerHTML = context;
};
ws1.onclose = function () {
// 关闭 websocket
alert("连接已关闭...");
};
}
</script>
<body onload="javascript:myFunction()">
<div id="sendDiv">
</div>
</body>
</html>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment