Commit 15821e94 by 钱炳权

参数配置开发:访问数据库搭建、列表查询、id查询

parent 4450c729
2024-04-25 15:14:31.948 [main] WARN c.a.cloud.nacos.client.NacosPropertySourceBuilder - Ignore the empty nacos configuration and get it based on dataId[fuzz-backend] & group[DEFAULT_GROUP]
2024-04-25 15:14:31.964 [main] WARN c.a.cloud.nacos.client.NacosPropertySourceBuilder - Ignore the empty nacos configuration and get it based on dataId[fuzz-backend.properties] & group[DEFAULT_GROUP]
2024-04-25 15:14:31.969 [main] WARN c.a.cloud.nacos.client.NacosPropertySourceBuilder - Ignore the empty nacos configuration and get it based on dataId[fuzz-backend-dev.properties] & group[DEFAULT_GROUP]
2024-04-25 15:14:31.969 [main] INFO o.s.c.b.c.PropertySourceBootstrapConfiguration - Located property source: [BootstrapPropertySource {name='bootstrapProperties-fuzz-backend-dev.properties,DEFAULT_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-fuzz-backend.properties,DEFAULT_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-fuzz-backend,DEFAULT_GROUP'}]
2024-04-25 15:14:32.001 [main] INFO com.example.fuzzControll.FuzzControlApplication - The following 1 profile is active: "dev"
2024-04-25 15:14:32.668 [main] INFO o.springframework.cloud.context.scope.GenericScope - BeanFactory id=318b10bd-7133-31f2-9c63-7502a72d32f4
2024-04-25 15:14:32.928 [main] INFO o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat initialized with port(s): 8102 (http)
2024-04-25 15:14:32.934 [main] INFO org.apache.catalina.core.StandardService - Starting service [Tomcat]
2024-04-25 15:14:32.934 [main] INFO org.apache.catalina.core.StandardEngine - Starting Servlet engine: [Apache Tomcat/9.0.64]
2024-04-25 15:14:33.113 [main] INFO o.a.c.core.ContainerBase.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
2024-04-25 15:14:33.113 [main] INFO o.s.b.w.s.c.ServletWebServerApplicationContext - Root WebApplicationContext: initialization completed in 1106 ms
2024-04-25 15:14:34.172 [main] WARN o.s.c.l.c.LoadBalancerCacheAutoConfiguration$LoadBalancerCaffeineWarnLogger - Spring Cloud LoadBalancer is currently working with the default cache. While this cache implementation is useful for development and tests, it's recommended to use Caffeine cache in production.You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.
2024-04-25 15:14:34.225 [main] INFO o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat started on port(s): 8102 (http) with context path ''
2024-04-25 15:14:34.240 [main] INFO c.a.n.p.auth.spi.client.ClientAuthPluginManager - [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.impl.NacosClientAuthServiceImpl success.
2024-04-25 15:14:34.240 [main] INFO c.a.n.p.auth.spi.client.ClientAuthPluginManager - [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.ram.RamClientAuthServiceImpl success.
2024-04-25 15:14:34.381 [main] INFO c.a.cloud.nacos.registry.NacosServiceRegistry - nacos registry, DEFAULT_GROUP fuzz-backend 192.168.50.247:8102 register finished
2024-04-25 15:14:34.631 [main] INFO com.example.fuzzControll.FuzzControlApplication - Started FuzzControlApplication in 6.718 seconds (JVM running for 10.554)
2024-04-25 15:14:34.636 [main] INFO c.a.cloud.nacos.refresh.NacosContextRefresher - [Nacos Config] Listening config: dataId=fuzz-backend.properties, group=DEFAULT_GROUP
2024-04-25 15:14:34.636 [main] INFO c.a.cloud.nacos.refresh.NacosContextRefresher - [Nacos Config] Listening config: dataId=fuzz-backend, group=DEFAULT_GROUP
2024-04-25 15:14:34.636 [main] INFO c.a.cloud.nacos.refresh.NacosContextRefresher - [Nacos Config] Listening config: dataId=fuzz-backend-dev.properties, group=DEFAULT_GROUP
2024-04-25 16:26:57.472 [Thread-7] WARN com.alibaba.nacos.common.notify.NotifyCenter - [NotifyCenter] Start destroying Publisher
2024-04-25 16:26:57.472 [Thread-1] WARN com.alibaba.nacos.common.http.HttpClientBeanHolder - [HttpClientBeanHolder] Start destroying common HttpClient
2024-04-25 16:26:57.478 [Thread-7] WARN com.alibaba.nacos.common.notify.NotifyCenter - [NotifyCenter] Destruction of the end
2024-04-25 16:26:57.478 [Thread-1] WARN com.alibaba.nacos.common.http.HttpClientBeanHolder - [HttpClientBeanHolder] Destruction of the end
2024-04-25 16:26:57.712 [SpringApplicationShutdownHook] INFO c.a.cloud.nacos.registry.NacosServiceRegistry - De-registering from Nacos Server now...
2024-04-25 16:26:57.722 [SpringApplicationShutdownHook] INFO c.a.cloud.nacos.registry.NacosServiceRegistry - De-registration finished.
2024-04-25 16:27:02.767 [main] WARN c.a.cloud.nacos.client.NacosPropertySourceBuilder - Ignore the empty nacos configuration and get it based on dataId[fuzz-backend] & group[DEFAULT_GROUP]
2024-04-25 16:27:02.770 [main] WARN c.a.cloud.nacos.client.NacosPropertySourceBuilder - Ignore the empty nacos configuration and get it based on dataId[fuzz-backend.properties] & group[DEFAULT_GROUP]
2024-04-25 16:27:02.773 [main] WARN c.a.cloud.nacos.client.NacosPropertySourceBuilder - Ignore the empty nacos configuration and get it based on dataId[fuzz-backend-dev.properties] & group[DEFAULT_GROUP]
2024-04-25 16:27:02.773 [main] INFO o.s.c.b.c.PropertySourceBootstrapConfiguration - Located property source: [BootstrapPropertySource {name='bootstrapProperties-fuzz-backend-dev.properties,DEFAULT_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-fuzz-backend.properties,DEFAULT_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-fuzz-backend,DEFAULT_GROUP'}]
2024-04-25 16:27:02.786 [main] INFO com.example.fuzzControll.FuzzControlApplication - The following 1 profile is active: "dev"
2024-04-25 16:27:03.160 [main] INFO o.springframework.cloud.context.scope.GenericScope - BeanFactory id=76e0e081-869a-3116-9df6-9c24efd445b3
2024-04-25 16:27:03.321 [main] INFO o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat initialized with port(s): 8101 (http)
2024-04-25 16:27:03.327 [main] INFO org.apache.catalina.core.StandardService - Starting service [Tomcat]
2024-04-25 16:27:03.327 [main] INFO org.apache.catalina.core.StandardEngine - Starting Servlet engine: [Apache Tomcat/9.0.64]
2024-04-25 16:27:03.472 [main] INFO o.a.c.core.ContainerBase.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
2024-04-25 16:27:03.472 [main] INFO o.s.b.w.s.c.ServletWebServerApplicationContext - Root WebApplicationContext: initialization completed in 681 ms
2024-04-25 16:27:04.370 [main] WARN o.s.c.l.c.LoadBalancerCacheAutoConfiguration$LoadBalancerCaffeineWarnLogger - Spring Cloud LoadBalancer is currently working with the default cache. While this cache implementation is useful for development and tests, it's recommended to use Caffeine cache in production.You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.
2024-04-25 16:27:04.423 [main] INFO o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat started on port(s): 8101 (http) with context path ''
2024-04-25 16:27:04.431 [main] INFO c.a.n.p.auth.spi.client.ClientAuthPluginManager - [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.impl.NacosClientAuthServiceImpl success.
2024-04-25 16:27:04.431 [main] INFO c.a.n.p.auth.spi.client.ClientAuthPluginManager - [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.ram.RamClientAuthServiceImpl success.
2024-04-25 16:27:04.564 [main] INFO c.a.cloud.nacos.registry.NacosServiceRegistry - nacos registry, DEFAULT_GROUP fuzz-backend 192.168.50.247:8101 register finished
2024-04-25 16:27:04.809 [main] INFO com.example.fuzzControll.FuzzControlApplication - Started FuzzControlApplication in 3.989 seconds (JVM running for 4.491)
2024-04-25 16:27:04.817 [main] INFO c.a.cloud.nacos.refresh.NacosContextRefresher - [Nacos Config] Listening config: dataId=fuzz-backend.properties, group=DEFAULT_GROUP
2024-04-25 16:27:04.818 [main] INFO c.a.cloud.nacos.refresh.NacosContextRefresher - [Nacos Config] Listening config: dataId=fuzz-backend, group=DEFAULT_GROUP
2024-04-25 16:27:04.818 [main] INFO c.a.cloud.nacos.refresh.NacosContextRefresher - [Nacos Config] Listening config: dataId=fuzz-backend-dev.properties, group=DEFAULT_GROUP
2024-04-25 17:27:15.632 [Thread-7] WARN com.alibaba.nacos.common.notify.NotifyCenter - [NotifyCenter] Start destroying Publisher
2024-04-25 17:27:15.632 [Thread-1] WARN com.alibaba.nacos.common.http.HttpClientBeanHolder - [HttpClientBeanHolder] Start destroying common HttpClient
2024-04-25 17:27:15.637 [Thread-7] WARN com.alibaba.nacos.common.notify.NotifyCenter - [NotifyCenter] Destruction of the end
2024-04-25 17:27:15.637 [Thread-1] WARN com.alibaba.nacos.common.http.HttpClientBeanHolder - [HttpClientBeanHolder] Destruction of the end
2024-04-25 17:27:15.839 [SpringApplicationShutdownHook] INFO c.a.cloud.nacos.registry.NacosServiceRegistry - De-registering from Nacos Server now...
2024-04-25 17:27:15.842 [SpringApplicationShutdownHook] INFO c.a.cloud.nacos.registry.NacosServiceRegistry - De-registration finished.
2024-04-25 17:27:20.984 [main] WARN c.a.cloud.nacos.client.NacosPropertySourceBuilder - Ignore the empty nacos configuration and get it based on dataId[fuzz-backend] & group[DEFAULT_GROUP]
2024-04-25 17:27:20.987 [main] WARN c.a.cloud.nacos.client.NacosPropertySourceBuilder - Ignore the empty nacos configuration and get it based on dataId[fuzz-backend.properties] & group[DEFAULT_GROUP]
2024-04-25 17:27:20.991 [main] WARN c.a.cloud.nacos.client.NacosPropertySourceBuilder - Ignore the empty nacos configuration and get it based on dataId[fuzz-backend-dev.properties] & group[DEFAULT_GROUP]
2024-04-25 17:27:20.991 [main] INFO o.s.c.b.c.PropertySourceBootstrapConfiguration - Located property source: [BootstrapPropertySource {name='bootstrapProperties-fuzz-backend-dev.properties,DEFAULT_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-fuzz-backend.properties,DEFAULT_GROUP'}, BootstrapPropertySource {name='bootstrapProperties-fuzz-backend,DEFAULT_GROUP'}]
2024-04-25 17:27:21.002 [main] INFO com.example.fuzzControll.FuzzControlApplication - The following 1 profile is active: "dev"
2024-04-25 17:27:21.362 [main] INFO o.springframework.cloud.context.scope.GenericScope - BeanFactory id=76e0e081-869a-3116-9df6-9c24efd445b3
2024-04-25 17:27:21.476 [main] INFO o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat initialized with port(s): 8101 (http)
2024-04-25 17:27:21.480 [main] INFO org.apache.catalina.core.StandardService - Starting service [Tomcat]
2024-04-25 17:27:21.480 [main] INFO org.apache.catalina.core.StandardEngine - Starting Servlet engine: [Apache Tomcat/9.0.64]
2024-04-25 17:27:21.539 [main] INFO o.a.c.core.ContainerBase.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
2024-04-25 17:27:21.539 [main] INFO o.s.b.w.s.c.ServletWebServerApplicationContext - Root WebApplicationContext: initialization completed in 530 ms
2024-04-25 17:27:22.433 [main] WARN o.s.c.l.c.LoadBalancerCacheAutoConfiguration$LoadBalancerCaffeineWarnLogger - Spring Cloud LoadBalancer is currently working with the default cache. While this cache implementation is useful for development and tests, it's recommended to use Caffeine cache in production.You can switch to using Caffeine cache, by adding it and org.springframework.cache.caffeine.CaffeineCacheManager to the classpath.
2024-04-25 17:27:22.487 [main] INFO o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat started on port(s): 8101 (http) with context path ''
2024-04-25 17:27:22.495 [main] INFO c.a.n.p.auth.spi.client.ClientAuthPluginManager - [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.impl.NacosClientAuthServiceImpl success.
2024-04-25 17:27:22.495 [main] INFO c.a.n.p.auth.spi.client.ClientAuthPluginManager - [ClientAuthPluginManager] Load ClientAuthService com.alibaba.nacos.client.auth.ram.RamClientAuthServiceImpl success.
2024-04-25 17:27:22.633 [main] INFO c.a.cloud.nacos.registry.NacosServiceRegistry - nacos registry, DEFAULT_GROUP fuzz-backend 192.168.50.247:8101 register finished
2024-04-25 17:27:22.881 [main] INFO com.example.fuzzControll.FuzzControlApplication - Started FuzzControlApplication in 3.898 seconds (JVM running for 4.446)
2024-04-25 17:27:22.885 [main] INFO c.a.cloud.nacos.refresh.NacosContextRefresher - [Nacos Config] Listening config: dataId=fuzz-backend.properties, group=DEFAULT_GROUP
2024-04-25 17:27:22.886 [main] INFO c.a.cloud.nacos.refresh.NacosContextRefresher - [Nacos Config] Listening config: dataId=fuzz-backend, group=DEFAULT_GROUP
2024-04-25 17:27:22.887 [main] INFO c.a.cloud.nacos.refresh.NacosContextRefresher - [Nacos Config] Listening config: dataId=fuzz-backend-dev.properties, group=DEFAULT_GROUP
2024-04-25 17:28:37.923 [Thread-7] WARN com.alibaba.nacos.common.notify.NotifyCenter - [NotifyCenter] Start destroying Publisher
2024-04-25 17:28:37.923 [Thread-1] WARN com.alibaba.nacos.common.http.HttpClientBeanHolder - [HttpClientBeanHolder] Start destroying common HttpClient
2024-04-25 17:28:37.924 [Thread-7] WARN com.alibaba.nacos.common.notify.NotifyCenter - [NotifyCenter] Destruction of the end
2024-04-25 17:28:37.925 [Thread-1] WARN com.alibaba.nacos.common.http.HttpClientBeanHolder - [HttpClientBeanHolder] Destruction of the end
2024-04-25 17:28:38.179 [SpringApplicationShutdownHook] INFO c.a.cloud.nacos.registry.NacosServiceRegistry - De-registering from Nacos Server now...
2024-04-25 17:28:38.183 [SpringApplicationShutdownHook] INFO c.a.cloud.nacos.registry.NacosServiceRegistry - De-registration finished.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>fuzzIntegration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>fuzzIntegration</name>
<description>fuzzIntegration</description>
<properties>
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>2021.0.5</spring-cloud.version>
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
</properties>
<dependencies>
<!-- 微服务依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>3.1.5</version>
</dependency>
<!-- springCloud相关-->
<!-- SpringCloud依赖开始-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
<version>3.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2021.0.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<version>3.1.5</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2021.0.5.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.31</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.7.2</version>
</dependency>
<!-- log4j - slf4j 日志依赖 结束-->
<dependency>
<groupId>com.fasterxml.uuid</groupId>
<artifactId>java-uuid-generator</artifactId>
<version>3.1.5</version>
</dependency>
<!-- log4j - slf4j 日志依赖 开始-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<!--WebSocket核心依赖包-->
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.8</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!--PageHelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.4.6</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.13</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
<!-- 配置java版本 不配置的话默认父类配置的是1.7-->
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
package com.example.fuzzControll;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import java.util.Arrays;
@SpringBootApplication
public class FuzzIntegration {
public static void main(String[] args) {
Arrays.stream(args).forEach(System.out::println);
SpringApplication.run(FuzzIntegration.class, args);
System.out.println("Start successfully!");
}
}
package com.example.fuzzControll.annotion;
import java.lang.annotation.*;
/**
* 方法后置处理
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface NeedCutAfter {
String name() default "";
String function() default "";
}
package com.example.fuzzControll.annotion;
import java.lang.annotation.*;
/**
* 方法前置处理
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface NeedCutAround {
String name() default "";
String function() default "";
}
package com.example.fuzzControll.annotion;
import java.lang.annotation.*;
/**
* 方法前置处理
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface NeedCutBefore {
String name() default "";
String function() default "";
}
package com.example.fuzzControll.aop;
import com.example.fuzzControll.annotion.NeedCutBefore;
import com.example.fuzzControll.exception.mysqlException.MysqlException;
import com.example.fuzzControll.exception.testException.AflnetException;
import com.example.fuzzControll.tools.system.GlobalClass;
import com.example.fuzzControll.tools.system.SystemRunningParams;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Aspect
@Component
@Slf4j
public class afterAop implements Ordered {
@Pointcut(value = "@annotation(com.example.fuzzControll.annotion.NeedCutAfter)")
private void afterCut() {
}
@Around("afterCut()")
public void after(JoinPoint point) throws Throwable {
Signature signature = point.getSignature();
MethodSignature methodSignature = null;
if (!(signature instanceof MethodSignature)) {
throw new IllegalArgumentException("该注解只能用于方法");
}
methodSignature = (MethodSignature) signature;
Object target = point.getTarget();
Method currentMethod = null;
try {
currentMethod = target.getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
} catch (NoSuchMethodException e) {
log.error("NoSuchMethod!");
e.printStackTrace();
throw new RuntimeException(e);
}
NeedCutBefore logotype = currentMethod.getAnnotation(NeedCutBefore.class);
/*相关处理逻辑,负责数据存入*/
switch (logotype.name()) {
case "aflnet":
// aflnet(logotype.function());
break;
case "kitty":
// kittyAfter(logotype.function());
break;
default:
throw new AflnetException("Cut error: There is no name of anotation!");
}
}
@Override
public int getOrder() {
return 3;
}
}
package com.example.fuzzControll.conf;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component("AflnetProperties")
@ConfigurationProperties(prefix = "aflnet")
public class AflnetProperties {
String seedPath;
String outputPath;
String aflnetPath;
public String getAflnetPath() {
return aflnetPath;
}
public void setAflnetPath(String aflnetPath) {
this.aflnetPath = aflnetPath;
}
public String getOutputPath() {
return outputPath;
}
public void setOutputPath(String outputPath) {
this.outputPath = outputPath;
}
public String getSeedPath() {
return seedPath;
}
public void setSeedPath(String seedPath) {
this.seedPath = seedPath;
}
}
\ No newline at end of file
package com.example.fuzzControll.conf;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component("IntegrationPathProperties")
@ConfigurationProperties(prefix = "integrationpath")
public class IntegrationPathProperties {
String webSocketUri;
public String getWebSocketUri() {
return webSocketUri;
}
public void setWebSocketUri(String webSocketUri) {
this.webSocketUri = webSocketUri;
}
}
package com.example.fuzzControll.conf;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component("kittyProperties")
@ConfigurationProperties(prefix = "kitty")
public class KittyProperties {
String logOutPath;
String path;
String venvPath;
String methodPath;
String vulnerabilityTypePath;
String templateInfoHttp;
String statsHttp;
String stagesHttp;
String reportHttp;
String mutationPath;
public String getLogOutPath() {
return logOutPath;
}
public void setLogOutPath(String logOutPath) {
this.logOutPath = logOutPath;
}
public String getMutationPath() {
return mutationPath;
}
public void setMutationPath(String mutationPath) {
this.mutationPath = mutationPath;
}
public String getTemplateInfoHttp() {
return templateInfoHttp;
}
public void setTemplateInfoHttp(String templateInfoHttp) {
this.templateInfoHttp = templateInfoHttp;
}
public String getStatsHttp() {
return statsHttp;
}
public void setStatsHttp(String statsHttp) {
this.statsHttp = statsHttp;
}
public String getStagesHttp() {
return stagesHttp;
}
public void setStagesHttp(String stagesHttp) {
this.stagesHttp = stagesHttp;
}
public String getReportHttp() {
return reportHttp;
}
public void setReportHttp(String reportHttp) {
this.reportHttp = reportHttp;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getVenvPath() {
return venvPath;
}
public void setVenvPath(String venvPath) {
this.venvPath = venvPath;
}
public String getMethodPath() {
return methodPath;
}
public void setMethodPath(String methodPath) {
this.methodPath = methodPath;
}
public String getVulnerabilityTypePath() {
return vulnerabilityTypePath;
}
public void setVulnerabilityTypePath(String vulnerabilityTypePath) {
this.vulnerabilityTypePath = vulnerabilityTypePath;
}
}
/********************************************************************
* 版权所有(C)2023,中国电子科技集团公司第五十研究所。 *
* 文件名称: SpringContextUtil.java//文件名称
* 文件标识: QN2.489.437
* 内容摘要: 获取spring上下文//简要描述本文件的内容,包括主要模块、函数及其功能的说明
* 其它说明: 无
* 当前版本: V1.00.00
* 作者: 张思湛 中国电子科技集团公司电子科学研究院
* 完成日期: 2023年9月18日
* 修改记录1: // 修改历史记录,包括修改日期、修改者及修改内容
* 修改日期:
* 版本号:
* 修改人:
* 修改内容:
* 修改记录2: ……
********************************************************************/
package com.example.fuzzControll.conf;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public SpringContextUtil() {
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringContextUtil.applicationContext == null) {
SpringContextUtil.applicationContext = applicationContext;
}
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static Object getBean(Class<?> requiredType) {
return applicationContext.getBean(requiredType);
}
}
package com.example.fuzzControll.conf;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration
@EnableFeignClients
@EnableAspectJAutoProxy(proxyTargetClass = true,exposeProxy = true)
public class SystemConfig {
}
package com.example.fuzzControll.controller.dataController;
import com.example.fuzzControll.domain.bo.AflnetDataParams;
import com.example.fuzzControll.domain.vo.AjaxResult;
import com.example.fuzzControll.service.AflnetPersistenceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/aflnet")
@Slf4j
public class AflnetDataController {
@Autowired
AflnetPersistenceService aflnetPersistenceService;
/**
* 读取数据库文件至指定目录
*/
@RequestMapping(value = "/loadFile", method = RequestMethod.GET)
public AjaxResult AflnetResultSelect(@RequestBody AflnetDataParams aflnetDataParams) {
try {
aflnetPersistenceService.loadInFile(aflnetDataParams.getMissionId(),aflnetDataParams.getFilPath());
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.error("File load failed!");
}
return AjaxResult.success("File loaded successfully!");
}
}
package com.example.fuzzControll.controller.dataController;
import com.example.fuzzControll.domain.bo.FuzzLogTransEntity;
import com.example.fuzzControll.service.FuzzLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.List;
@RestController
@RequestMapping("/log")
@Slf4j
public class FuzzLogController {
@Autowired
FuzzLogService FuzzLogService;
/**
* 下载对应任务的日志;不同任务返回数据类型不同,需要做个表来区分
*/
@RequestMapping(value = "/download/{missionId}", method = RequestMethod.GET)
public List<FuzzLogTransEntity> getFuzzLog(@PathVariable("missionId") int missionId) throws IOException {
try {
return FuzzLogService.getFuzzLog(missionId);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
package com.example.fuzzControll.controller.dataController;
import com.example.fuzzControll.domain.vo.AjaxResult;
import com.example.fuzzControll.domain.bo.KittyDataParams;
import com.example.fuzzControll.domain.vo.KittyResult;
import com.example.fuzzControll.service.KittyFuzzPersistenceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/kittyServer")
@Slf4j
public class KittyDataController {
@Autowired
KittyFuzzPersistenceService fuzzPersistenceService;
/**
* 查询kitty结果
*/
@RequestMapping(value = "/KittyResultSelect", method = RequestMethod.GET)
public AjaxResult KittyResultSelect() {
List<KittyResult> results;
try {
results = fuzzPersistenceService.getKittyResults();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.error();
}
return AjaxResult.success(results);
}
/**
* 查询kittyPackage
*/
@RequestMapping(value = "/kittyPackageFileLoad", method = RequestMethod.POST)
public AjaxResult kittyPackageFileLoad(@RequestBody KittyDataParams kittyDataParams) {
try {
fuzzPersistenceService.loadKittyLogFileInLocal(kittyDataParams);
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.error();
}
return AjaxResult.success("load success!");
}
}
package com.example.fuzzControll.controller.dataController;
import com.alibaba.fastjson.JSON;
import com.example.fuzzControll.exception.serverException.ServerException;
import com.example.fuzzControll.domain.vo.AjaxResult;
import com.example.fuzzControll.service.GetServerMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* kitty服务器信息
*/
@RestController
@RequestMapping("/kittyServer")
@Slf4j
public class KittyServerMessageController {
@Autowired
GetServerMessageService getServerMessageService;
/**
* 获取服务器stats信息
*/
@RequestMapping(value = "/stats", method = RequestMethod.GET)
public AjaxResult getStats( ) {
try {
return AjaxResult.success(JSON.parse(getServerMessageService.getStats()));
} catch (ServerException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error("stats信息获取失败!");
}
}
/**
* 获取服务器templateInfo信息
*/
@RequestMapping(value = "/templateInfo", method = RequestMethod.GET)
public AjaxResult getTemplateInfo( ) {
try {
return AjaxResult.success(JSON.parse(getServerMessageService.getTemplateInfo()));
} catch (ServerException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error("templateInfo信息获取失败!");
}
}
/**
* 获取服务器stages信息
*/
@RequestMapping(value = "/stages", method = RequestMethod.GET)
public AjaxResult getStages( ) {
try {
return AjaxResult.success(JSON.parse(getServerMessageService.getStages()));
} catch (ServerException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error("stages信息获取失败!");
}
}
/**
* 获取服务器report信息
*/
@RequestMapping(value = "/report", method = RequestMethod.GET)
public AjaxResult getReport( ) {
try {
return AjaxResult.success(JSON.parse(getServerMessageService.getReport()));
} catch (ServerException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error("report信息获取失败!");
}
}
}
package com.example.fuzzControll.controller.dataController;
import com.example.fuzzControll.mapper.MissionInfoMapper;
import com.example.fuzzControll.domain.vo.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
@RequestMapping("/mission")
@Slf4j
public class MissionInfoController {
@Autowired
MissionInfoMapper missionInfoMapper;
/**
* 查看任务信息
*/
@RequestMapping(value = "/getList", method = RequestMethod.GET)
public AjaxResult getMissionInfo() throws IOException {
try {
return AjaxResult.success(missionInfoMapper.selectMissionInfoList());
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.error("SelectMissionInfoList error!");
}
}
}
package com.example.fuzzControll.controller.dataController;
import com.example.fuzzControll.exception.testException.CmdException;
import com.example.fuzzControll.exception.fileExcption.FileException;
import com.example.fuzzControll.domain.vo.AjaxResult;
import com.example.fuzzControll.service.SeedFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* aflnet种子文件
*/
@Slf4j
@RestController
@RequestMapping("/seedFile")
public class SeedFileController {
@Autowired
SeedFileService service;
/**
* 种子文件查询接口
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
public AjaxResult list() {
List<String> files = null;
try {
files = service.getSeedFiles();
} catch (CmdException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error();
}
return AjaxResult.success(files);
}
/**
* 种子文件删除接口
*/
@RequestMapping(value = "/delete", method = RequestMethod.POST)
public AjaxResult delete(@RequestParam("fileName") String fileName) {
try {
service.delFile(fileName);
} catch (CmdException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error("种子文件删除失败!");
}
return AjaxResult.success("种子文件删除成功!");
}
/**
* seeFileUpload
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public AjaxResult upload(@RequestParam("file") MultipartFile file) {
try {
service.upload(file);
} catch (FileException | CmdException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error("上传文件失败!");
}
return AjaxResult.success("上传文件成功!");
}
}
package com.example.fuzzControll.controller.dataController;
import com.example.fuzzControll.service.websocketClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* websocket 客户端
*/
@Slf4j
@RestController
@RequestMapping("/websocket")
public class WebsocketController {
@Autowired
websocketClientService websocketClientService;
@RequestMapping(value = "/connect", method = RequestMethod.GET)
public void connect(){
try {
websocketClientService.connect();
} catch (Exception e) {
e.printStackTrace();
}
log.info("Connect success!");
}
@RequestMapping(value = "/disConnect", method = RequestMethod.GET)
public void disConnect(){
try {
websocketClientService.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
log.info("Disconnect success!");
}
}
package com.example.fuzzControll.controller.testController;
import com.example.fuzzControll.exception.mysqlException.MysqlException;
import com.example.fuzzControll.exception.testException.AflnetException;
import com.example.fuzzControll.exception.threadException.MyExceptionHandler;
import com.example.fuzzControll.domain.vo.AjaxResult;
import com.example.fuzzControll.domain.bo.CmdStartParams;
import com.example.fuzzControll.service.TestService;
import com.example.fuzzControll.tools.system.GlobalClass;
import com.example.fuzzControll.tools.system.SystemRunningParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* aflnet测试控制
*/
@Slf4j
@RestController
@RequestMapping("/test")
public class AlfnetController {
@Autowired
TestService service;
/**
* 测试启动
*/
@RequestMapping(value = "/testStart", method = RequestMethod.POST)
public AjaxResult start(@RequestBody final CmdStartParams cmdStartParams) {
//todo 捕获子线程错误
try {
SystemRunningParams.aflnetData.put("missionName", cmdStartParams.getProtopcol());
Thread subThread = new Thread(new Runnable() {
@Override
public void run() {
service.testStart(cmdStartParams);
}
});
SystemRunningParams.ThreadState.put(subThread,"start");
subThread.setUncaughtExceptionHandler(new MyExceptionHandler());
subThread.start();
// subThread.join();
Thread.sleep(1000*10);//暂停3s,让系统运行至指令完全运行 todo跟据系统运行设定时间
if ("error".equals(SystemRunningParams.ThreadState.get(subThread))) {//使用join串行就无法停止
throw new Exception();
}
} catch (Exception e) {
return AjaxResult.error("测试启动失败!");
}
return AjaxResult.success("测试已启动!");
}
/**
* 测试停止
*/
@RequestMapping(value = "/testStop", method = RequestMethod.GET)
public AjaxResult testStop() {
try {
service.testStop();
} catch (AflnetException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error("测试停止失败!");
} catch (MysqlException e) {
log.error("File backup error: " + e.getMessage());
}
return AjaxResult.success("测试停止成功!");
}
}
package com.example.fuzzControll.controller.testController;
import com.example.fuzzControll.annotion.NeedCutBefore;
import com.example.fuzzControll.exception.testException.CmdException;
import com.example.fuzzControll.exception.testException.FuzzException;
import com.example.fuzzControll.domain.vo.AjaxResult;
import com.example.fuzzControll.domain.bo.TestEntity;
import com.example.fuzzControll.service.GenerateMethodService;
import com.example.fuzzControll.service.MutationService;
import com.example.fuzzControll.service.ProtocolTemplateService;
import com.example.fuzzControll.service.VulnerabilityTypeService;
import com.example.fuzzControll.tools.system.SystemRunningParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* 不同类型的测试方法
*/
@Slf4j
@RestController
@RequestMapping("/testClass")
public class KittyController {
@Autowired
GenerateMethodService generateMethodService;
@Autowired
MutationService mutationService;
@Autowired
ProtocolTemplateService protocolTemplateService;
@Autowired
VulnerabilityTypeService vulnerabilityTypeService;
/**
* 模板
*/
@RequestMapping(value = "/protocolTemplate", method = RequestMethod.POST)
public AjaxResult protocolTemplate(@RequestBody TestEntity testEntity) {
try {
SystemRunningParams.kittyData.put("missionName",testEntity.getTestClassName());
Map<String, List<String>> result = protocolTemplateService.generation(testEntity,1);
return AjaxResult.success(result == null ? "模板文件生成未成功运行!第三方接口可能存在问题。" : result);
} catch (CmdException | FuzzException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error("模板生成失败!系统存在问题。");
}
}
/**
* 生成方法
*/
@RequestMapping(value = "/generate", method = RequestMethod.POST)
public AjaxResult generate(@RequestBody TestEntity testEntity) {
try {
SystemRunningParams.kittyData.put("missionName",testEntity.getTestClassName());
Map<String, List<String>> result = generateMethodService.generation(testEntity,1);
return AjaxResult.success(result == null ? "生成方法未成功运行!第三方接口可能存在问题。" : result);
} catch (CmdException | FuzzException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error("生成方法使用失败!系统存在问题。");
}
}
/**
* 变异方法
*/
@RequestMapping(value = "/mutation", method = RequestMethod.POST)
public AjaxResult mutation(@RequestBody TestEntity testEntity) {
try {
SystemRunningParams.kittyData.put("missionName",testEntity.getTestClassName());
Map<String, List<String>> result = mutationService.generation(testEntity,1);
return AjaxResult.success(result == null ? "mutationTest未成功运行!第三方接口可能存在问题。" : result);
} catch (CmdException | FuzzException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error("mutationTest失败!系统存在问题。");
}
}
/**
* 漏洞类型
*/
@RequestMapping(value = "/vulnerabilityType", method = RequestMethod.POST)
public AjaxResult vulnerability(@RequestBody TestEntity testEntity) {
try {
SystemRunningParams.kittyData.put("missionName",testEntity.getTestClassName());
Map<String, List<String>> result = vulnerabilityTypeService.generation(testEntity,1);
return AjaxResult.success(result == null ? "漏洞类型未成功运行!第三方接口可能存在问题。" : result);
} catch (CmdException | FuzzException e) {
log.error(e.getDefaultMessage());
return AjaxResult.error("漏洞类型测试失败!系统存在问题。");
}
}
}
package com.example.fuzzControll.domain.bo;
import lombok.Data;
@Data
public class AflnetDataParams {
private String filPath;
private int missionId;
public AflnetDataParams() {
}
public AflnetDataParams(String filPath, int missionId) {
this.filPath = filPath;
this.missionId = missionId;
}
}
package com.example.fuzzControll.domain.bo;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Data
@Getter
@Setter
public class CmdStartParams {
String netinfo; //netInfo
String protopcol; //protocol
int waiting; //usec
String nsname;//netnsname
Boolean kill;
Boolean awareMode;
Boolean regionMutationOperators;
Boolean falseNegativeMode;
String script;//script
int stateSelectionAlgo;
int seedSelectionAlgo;
}
package com.example.fuzzControll.domain.bo;
import lombok.Data;
@Data
public class FuzzLogTransEntity {
private byte[] file;
private String name;
public FuzzLogTransEntity(byte[] file, String name) {
this.file = file;
this.name = name;
}
public FuzzLogTransEntity() {
}
}
package com.example.fuzzControll.domain.bo;
import lombok.Data;
@Data
public class KittyDataParams {
private String filPath;
private int missionId;
public KittyDataParams() {
}
public KittyDataParams(String filPath, int missionId) {
this.filPath = filPath;
this.missionId = missionId;
}
}
package com.example.fuzzControll.domain.bo;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Data
@Getter
@Setter
public class TestEntity {
String testClassName;
String[] paramJson;
}
package com.example.fuzzControll.domain.po;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.util.Date;
@Data
public class MissionInfo {
@JsonIgnore
private int id;
private int missionId;
@JsonIgnore
private int tableId;//返回数据忽略字段;aflnet 为1 kitty为2
private Date createTime;
private String missionName;
@JsonIgnore
private int state;
private Long runTime;
private String stateName;
public MissionInfo() {
}
public MissionInfo(int missionId, int tableId, Date createTime, String missionName, int state, Long runTime) {
this.missionId = missionId;
this.tableId = tableId;
this.createTime = createTime;
this.missionName = missionName;
this.state = state;
this.runTime = runTime;
}
public MissionInfo(int missionId, Date createTime, String missionName, Long runTime, String stateName) {
this.missionId = missionId;
this.createTime = createTime;
this.missionName = missionName;
this.runTime = runTime;
this.stateName = stateName;
}
}
package com.example.fuzzControll.domain.vo;
import lombok.Data;
@Data
public class AflnetResult {
private int id;
private int missionId;
private byte[] file;
private String fileName;
public AflnetResult(int missionId, byte[] file, String fileName) {
this.missionId = missionId;
this.file = file;
this.fileName = fileName;
}
public AflnetResult() {
}
}
package com.example.fuzzControll.domain.vo;
import java.util.HashMap;
public class AjaxResult extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
/**
* 状态码
*/
public static final String CODE_TAG = "code";
/**
* 返回内容
*/
public static final String MSG_TAG = "data";
/**
* 数据对象
*/
public static final String DATA_TAG = "data";
/**
* 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
*/
public AjaxResult() {
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param data 返回内容
*/
public AjaxResult(int code, String data) {
super.put(CODE_TAG, code);
super.put(MSG_TAG, data);
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
* @param data 数据对象
*/
public AjaxResult(int code, String msg, Object data) {
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
if (data != null) {
super.put(DATA_TAG, data);
}
}
/**
* 返回成功消息
*
* @return 成功消息
*/
public static AjaxResult success() {
return AjaxResult.success("success");
}
/**
* 返回成功数据
*
* @return 成功消息
*/
public static AjaxResult success(Object data) {
return AjaxResult.success("success", data);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @return 成功消息
*/
public static AjaxResult success(String msg) {
return AjaxResult.success(msg, null);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 成功消息
*/
public static AjaxResult success(String msg, Object data) {
return new AjaxResult(200, msg, data);
}
/**
* 返回警告消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult warn(String msg) {
return AjaxResult.warn(msg, null);
}
/**
* 返回警告消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public static AjaxResult warn(String msg, Object data) {
return new AjaxResult(403, msg, data);
}
/**
* 返回错误消息
*
* @return 错误消息
*/
public static AjaxResult error() {
return AjaxResult.error("操作失败");
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @return 错误消息
*/
public static AjaxResult error(String msg) {
return AjaxResult.error(msg, null);
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 错误消息
*/
public static AjaxResult error(String msg, Object data) {
return new AjaxResult(500, msg, data);
}
/**
* 返回错误消息
*
* @param code 状态码
* @param msg 返回内容
* @return 错误消息
*/
public static AjaxResult error(int code, String msg) {
return new AjaxResult(code, msg, null);
}
/**
* 方便链式调用
*
* @param key 键
* @param value 值
* @return 数据对象
*/
@Override
public AjaxResult put(String key, Object value) {
super.put(key, value);
return this;
}
}
\ No newline at end of file
package com.example.fuzzControll.domain.vo;
import lombok.Data;
@Data
public class KittyPackageFile {
private int id;
private int missionId;
private String kittyRecvFileName;
private String kittySendFileName;
private byte[] kittyRecvFile;
private byte[] kittySendFile;
public KittyPackageFile(int missionId, String kittyRecvFileName, String kittySendFileName, byte[] kittyRecvFile, byte[] kittySendFile) {
this.missionId = missionId;
this.kittyRecvFileName = kittyRecvFileName;
this.kittySendFileName = kittySendFileName;
this.kittyRecvFile = kittyRecvFile;
this.kittySendFile = kittySendFile;
}
@Override
public String toString() {
return "kittyPackageFile{" +
"id=" + id +
", missionId=" + missionId +
", kittyRecvFileName='" + kittyRecvFileName + '\'' +
", kittySendFileName='" + kittySendFileName + '\'' +
", kittyRecvFile=" + kittyRecvFile.length +
", kittySendFile=" +kittySendFile.length +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getMissionId() {
return missionId;
}
public void setMissionId(int missionId) {
this.missionId = missionId;
}
public String getKittyRecvFileName() {
return kittyRecvFileName;
}
public void setKittyRecvFileName(String kittyRecvFileName) {
this.kittyRecvFileName = kittyRecvFileName;
}
public String getKittySendFileName() {
return kittySendFileName;
}
public void setKittySendFileName(String kittySendFileName) {
this.kittySendFileName = kittySendFileName;
}
public byte[] getKittyRecvFile() {
return kittyRecvFile;
}
public void setKittyRecvFile(byte[] kittyRecvFile) {
this.kittyRecvFile = kittyRecvFile;
}
public byte[] getKittySendFile() {
return kittySendFile;
}
public void setKittySendFile(byte[] kittySendFile) {
this.kittySendFile = kittySendFile;
}
}
package com.example.fuzzControll.domain.vo;
import lombok.Data;
@Data
public class KittyResult {
private int id;
private int missionId;
private String resultOut;
private String resultError;
public KittyResult() {
}
public KittyResult(int missionId, String resultOut, String resultError) {
this.missionId = missionId;
this.resultOut = resultOut;
this.resultError = resultError;
}
}
package com.example.fuzzControll.domain.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;
}
package com.example.fuzzControll.exception;
/**
* 基础异常
*/
public class BaseException extends RuntimeException{
private static final long serialVersionUID = 1L;
/**
* 错误消息
*/
private String defaultMessage;
/**
* 所属模块
*/
private String module;
public BaseException() {
}
public BaseException(String defaultMessage, String module) {
this.defaultMessage = defaultMessage;
this.module = module;
}
public String getDefaultMessage() {
return defaultMessage;
}
}
package com.example.fuzzControll.exception.fileExcption;
import com.example.fuzzControll.exception.BaseException;
/**
* 文件操作异常
*/
public class FileException extends BaseException {
private static final long serialVersionUID = 1L;
public FileException(String defaultMessage) {
super(defaultMessage, "file");
}
}
package com.example.fuzzControll.exception.mysqlException;
import com.example.fuzzControll.exception.BaseException;
public class MysqlException extends BaseException {
private static final long serialVersionUID = 1L;
public MysqlException(String defaultMessage) {
super(defaultMessage, "mysql");
}
}
package com.example.fuzzControll.exception.serverException;
import com.example.fuzzControll.exception.BaseException;
public class ServerException extends BaseException {
private static final long serialVersionUID = 1L;
public ServerException(String defaultMessage) {
super(defaultMessage, "server");
}
}
package com.example.fuzzControll.exception.testException;
import com.example.fuzzControll.exception.BaseException;
public class AflnetException extends BaseException {
private static final long serialVersionUID = 1L;
public AflnetException(String defaultMessage) {
super(defaultMessage, "aflnet");
}
}
package com.example.fuzzControll.exception.testException;
import com.example.fuzzControll.exception.BaseException;
/**
* cmd运行异常
*/
public class CmdException extends BaseException {
private static final long serialVersionUID = 1L;
public CmdException() {
}
public CmdException(String defaultMessage) {
super(defaultMessage, "cmd");
}
}
package com.example.fuzzControll.exception.testException;
import com.example.fuzzControll.exception.BaseException;
public class FuzzException extends BaseException {
private static final long serialVersionUID = 1L;
public FuzzException(String defaultMessage) {
super(defaultMessage, "lock");
}
}
package com.example.fuzzControll.exception.testException;
import com.example.fuzzControll.exception.BaseException;
public class KittyException extends BaseException {
private static final long serialVersionUID = 1L;
public KittyException(String defaultMessage) {
super(defaultMessage, "kitty");
}
}
package com.example.fuzzControll.exception.threadException;
import com.example.fuzzControll.exception.BaseException;
public class LockException extends BaseException {
private static final long serialVersionUID = 1L;
public LockException(String defaultMessage) {
super(defaultMessage, "fuzz");
}
}
package com.example.fuzzControll.exception.threadException;
import com.example.fuzzControll.tools.system.GlobalClass;
import com.example.fuzzControll.tools.system.SystemRunningParams;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyExceptionHandler implements Thread.UncaughtExceptionHandler
{
@Override
public void uncaughtException(Thread t, Throwable e)
{
SystemRunningParams.ThreadState.put(t,"error");
}
}
package com.example.fuzzControll.inital;
import com.example.fuzzControll.tools.system.SystemRunningParams;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
/**
* 系统全局初始化
*/
@Component
public class SystemInitial {
@PostConstruct
public void doConstruct() throws Exception {
SystemRunningParams.init();
}
}
package com.example.fuzzControll.mapper;
import com.example.fuzzControll.domain.vo.AflnetResult;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
@Mapper
@Component("AflnetMapper")
public interface AflnetMapper {
/**
* 查询kitty模糊测试结果
*/
// List<KittyResult> getKittyResults();
/**
* 存储alfnet测试结果
*/
int aflnetOutputBackup(AflnetResult aflnetResult);
AflnetResult selectResultById(int missionId);
}
package com.example.fuzzControll.mapper;
import com.example.fuzzControll.domain.vo.KittyResult;
import com.example.fuzzControll.domain.vo.KittyPackageFile;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Mapper
@Component("KittyMapper")
public interface KittyMapper {
/**
* 查询kitty模糊测试结果
*/
List<KittyResult> getKittyResults();
int kittyResultsBackup(KittyResult kittyResult);
int kittyPackagesBackup(KittyPackageFile kittyPackageFile);
KittyPackageFile getKittyPackageFileById(int missionId);
KittyResult getKittyResultByMissionId(int missionId);
/**
* 查询kitty日志
*/
// List<KittyLog> selectByNodeType(int nodeType);
}
package com.example.fuzzControll.mapper;
import com.example.fuzzControll.domain.po.MissionInfo;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
import java.util.List;
@Mapper
@Component("MissionInfoMapper")
public interface MissionInfoMapper {
MissionInfo selectByMissionId(int missionId);
/**
* 查询任务信息列表
*/
List<MissionInfo> selectMissionInfoList();
/**
* 查询当前任务Id
*/
int selectTopMissionId();
void insertMission(MissionInfo missionInfo);
void updateMission(int state,Long runTime,int missionId);
}
package com.example.fuzzControll.service;
public interface AflnetPersistenceService {
public int aflnetResultBackup(String filename, int state, Long runTime);
public void loadInFile(int missionId,String filePath);
}
package com.example.fuzzControll.service;
import com.example.fuzzControll.domain.bo.FuzzLogTransEntity;
import java.util.List;
public interface FuzzLogService {
List<FuzzLogTransEntity> getFuzzLog(int missionId) throws IllegalAccessException;
}
package com.example.fuzzControll.service;
import com.example.fuzzControll.domain.bo.TestEntity;
import java.util.List;
import java.util.Map;
public interface GenerateMethodService {
Map<String,List<String>> generation(TestEntity testEntity,int missionId);
}
package com.example.fuzzControll.service;
public interface GetServerMessageService {
String getStats();
String getTemplateInfo();
String getStages();
String getReport();
}
package com.example.fuzzControll.service;
import com.example.fuzzControll.domain.bo.KittyDataParams;
import com.example.fuzzControll.domain.vo.KittyResult;
import java.util.List;
public interface KittyFuzzPersistenceService {
List<KittyResult> getKittyResults();
public int KittyPackagesBackup(int missionId);
public int kittyResultsBackup(KittyResult kittyResult);
void loadKittyLogFileInLocal(KittyDataParams kittyDataParams);
}
package com.example.fuzzControll.service;
import com.example.fuzzControll.domain.bo.TestEntity;
import java.util.List;
import java.util.Map;
public interface MutationService {
Map<String, List<String>> generation(TestEntity testEntity,int missionId);
}
package com.example.fuzzControll.service;
import com.example.fuzzControll.domain.bo.TestEntity;
import java.util.List;
import java.util.Map;
public interface ProtocolTemplateService {
Map<String,List<String>> generation(TestEntity testEntity,int missionId);
}
package com.example.fuzzControll.service;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.ReentrantLock;
public interface SeedFileService {
public List<String> getSeedFiles();
void delFile(String fileName);
void upload(MultipartFile file) ;
int getSeedFileCount(String msg );
}
package com.example.fuzzControll.service;
import com.example.fuzzControll.domain.bo.CmdStartParams;
public interface TestService {
void testStart(CmdStartParams cmdStartParams);
void testStop();
}
package com.example.fuzzControll.service;
import com.example.fuzzControll.domain.bo.TestEntity;
import java.util.List;
import java.util.Map;
public interface VulnerabilityTypeService {
Map<String, List<String>> generation(TestEntity testEntity,int missionId);
}
package com.example.fuzzControll.service.impl;
import com.example.fuzzControll.domain.vo.AflnetResult;
import com.example.fuzzControll.domain.bo.FuzzLogTransEntity;
import com.example.fuzzControll.domain.vo.KittyResult;
import com.example.fuzzControll.domain.po.MissionInfo;
import com.example.fuzzControll.exception.mysqlException.MysqlException;
import com.example.fuzzControll.mapper.AflnetMapper;
import com.example.fuzzControll.mapper.KittyMapper;
import com.example.fuzzControll.mapper.MissionInfoMapper;
import com.example.fuzzControll.service.FuzzLogService;
import com.example.fuzzControll.tools.file.FileTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service("FuzzLogService")
public class FuzzLogServiceImpl implements FuzzLogService {
@Autowired
MissionInfoMapper missionInfoMapper;
@Autowired
AflnetMapper aflnetMapper;
@Autowired
KittyMapper kittyMapper;
FileTools fileTools = new FileTools();
@Override
public List<FuzzLogTransEntity> getFuzzLog(int missionId) throws IllegalAccessException {
MissionInfo missionInfo = missionInfoMapper.selectByMissionId(missionId);
if (missionInfo == null) {
return null;
}
switch (missionInfo.getTableId()) {
case 1:
return downloadAflnetFile(missionInfo);
case 3:
return downloadKittyProtocalFile(missionInfo);
case 2:
return downloadKittyOtherMethodFile(missionInfo);
default:
throw new IllegalAccessException("Invalid mission!");
}
}
@Transactional(rollbackFor = MysqlException.class)
public List<FuzzLogTransEntity> downloadKittyProtocalFile(MissionInfo missionInfo) {
/*获取结果日志*/
List<FuzzLogTransEntity> fuzzLogList = new ArrayList<FuzzLogTransEntity>();
KittyResult kittyResult = kittyMapper.getKittyResultByMissionId(missionInfo.getMissionId());
StringBuffer buffer = new StringBuffer();
buffer.append(kittyResult.getResultError()).append(System.lineSeparator()).append(kittyResult.getResultOut());
FuzzLogTransEntity fuzzLogTransEntity = new FuzzLogTransEntity(buffer.toString().getBytes(), missionInfo.getMissionName() + ".txt");
fuzzLogList.add(fuzzLogTransEntity);
/*获取数据包文件*/
// KittyPackageFile kittyPackageFile = kittyMapper.getKittyPackageFileById(missionInfo.getMissionId());
// FuzzLogTransEntity fuzzLogTransEntitySend = new FuzzLogTransEntity(kittyPackageFile.getKittySendFile(), kittyPackageFile.getKittyRecvFileName());
// FuzzLogTransEntity fuzzLogTransEntityRecv = new FuzzLogTransEntity(kittyPackageFile.getKittyRecvFile(), kittyPackageFile.getKittyRecvFileName());
// fuzzLogList.add(fuzzLogTransEntitySend);
// fuzzLogList.add(fuzzLogTransEntityRecv);
return fuzzLogList;
}
@Transactional(rollbackFor = MysqlException.class)
public List<FuzzLogTransEntity> downloadKittyOtherMethodFile(MissionInfo missionInfo) {
List<FuzzLogTransEntity> fuzzLogList = new ArrayList<FuzzLogTransEntity>();
KittyResult kittyResult = kittyMapper.getKittyResultByMissionId(missionInfo.getMissionId());
StringBuffer buffer = new StringBuffer();
buffer.append(kittyResult.getResultError()).append(System.lineSeparator()).append(kittyResult.getResultOut());
FuzzLogTransEntity fuzzLogTransEntity = new FuzzLogTransEntity(buffer.toString().getBytes(), missionInfo.getMissionName() + ".txt");
fuzzLogList.add(fuzzLogTransEntity);
return fuzzLogList;
}
@Transactional(rollbackFor = MysqlException.class)
public List<FuzzLogTransEntity> downloadAflnetFile(MissionInfo missionInfo) {
List<FuzzLogTransEntity> fuzzLogList = new ArrayList<FuzzLogTransEntity>();
AflnetResult aflnetResult = aflnetMapper.selectResultById(missionInfo.getMissionId());
FuzzLogTransEntity fuzzLogTransEntity = new FuzzLogTransEntity(aflnetResult.getFile(), aflnetResult.getFileName());
fuzzLogList.add(fuzzLogTransEntity);
return fuzzLogList;
}
}
package com.example.fuzzControll.service.impl;
import com.example.fuzzControll.annotion.NeedCutAround;
import com.example.fuzzControll.annotion.NeedCutBefore;
import com.example.fuzzControll.conf.KittyProperties;
import com.example.fuzzControll.exception.testException.CmdException;
import com.example.fuzzControll.exception.testException.FuzzException;
import com.example.fuzzControll.domain.bo.TestEntity;
import com.example.fuzzControll.service.GenerateMethodService;
import com.example.fuzzControll.tools.test.TestCmdTools;
import com.example.fuzzControll.tools.test.TestTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Service
@Slf4j
public class GenerateMethodServiceImpl implements GenerateMethodService {
TestCmdTools cmdTools = new TestCmdTools();
@Autowired
KittyProperties kitty;
@Override
@NeedCutAround(name ="kitty",function = "generation")
public Map<String, List<String>> generation(TestEntity testEntity,int missionId) throws FuzzException, CmdException {
String cmd = parseParameters(testEntity);
if (cmd.isEmpty()) {
throw new FuzzException("cmd is null ! The number of parameters does not match!");
}
return cmdTools.runProgramCmdAndResult(cmd,"generate","Generate-"+testEntity.getTestClassName());
}
public String parseParameters(TestEntity testEntity) {
try {
switch (testEntity.getTestClassName().toLowerCase()) {
case "foreach":
return cmd(testEntity, "-f");
case "repeat":
return cmd(testEntity, "-r");
case "oneof":
return cmd(testEntity, "-o");
case "switch":
return cmd(testEntity, "-s");
case "pad":
return cmd(testEntity, "-p");
case "template":
return cmd(testEntity, "-t");
case "meta":
return cmd(testEntity, "-m");
case "if":
return cmd(testEntity, "-c");
case "ifnot":
return cmd(testEntity, "-e");
case "trunc"://have error
return cmd(testEntity, "-u");
default:
throw new FuzzException("Unknown method !");
}
} catch (FuzzException e) {
throw new FuzzException("Unknown method !");
}
}
private String cmd(TestEntity testEntity, String cmd) throws FuzzException {
if (!TestTools.paramsLenghtTest(testEntity.getParamJson().length, 5, "generationMethod"))
return "";
String target_host = null;
String target_port = null;
String s1 = null;
String s2 = null;
String s3 = null;
try {
target_host = testEntity.getParamJson()[0];
target_port = testEntity.getParamJson()[1];
s1 = testEntity.getParamJson()[2];
s2 = testEntity.getParamJson()[3];
s3 = testEntity.getParamJson()[4];
} catch (Exception e) {
throw new FuzzException("Parameter parsing failed !");
}
return kitty.getVenvPath() + " " + kitty.getMethodPath() + "generate_method_test.py " + cmd + " " + s1 + " " + s2 + " " + s3 + " --host=" + target_host + " --port=" + target_port;
}
}
package com.example.fuzzControll.service.impl;
import com.example.fuzzControll.conf.KittyProperties;
import com.example.fuzzControll.exception.serverException.ServerException;
import com.example.fuzzControll.service.GetServerMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Slf4j
@Service("getServerMessageService")
public class GetServerMessageImpl implements GetServerMessageService {
@Autowired
KittyProperties kitty;
public String getServerMsg(String messageName) {
switch (messageName) {
case "templateInfo": {
HttpGet httpGetTemplateInfo = new HttpGet(kitty.getTemplateInfoHttp());
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse templateInfoResponse = httpClient.execute(httpGetTemplateInfo);) {
return EntityUtils.toString(templateInfoResponse.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
throw new ServerException("get server templateInfo error !");
}
}
case "stats": {
HttpGet httpGetStats = new HttpGet(kitty.getStatsHttp());
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse statsResponse = httpClient.execute(httpGetStats);) {
return EntityUtils.toString(statsResponse.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
throw new ServerException("get server stats error !");
}
}
case "report": {
HttpGet httpGetStats = new HttpGet(kitty.getReportHttp());
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse reportResponse = httpClient.execute(httpGetStats);) {
return EntityUtils.toString(reportResponse.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
throw new ServerException("get server report error !");
}
}
case "stages": {
HttpGet httpGetStats = new HttpGet(kitty.getStagesHttp());
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse stagesResponse = httpClient.execute(httpGetStats);) {
return EntityUtils.toString(stagesResponse.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
throw new ServerException("get server stages error !");
}
}
default:
return "";
}
}
@Override
public String getStats() {
return getServerMsg("stats");
}
@Override
public String getTemplateInfo() throws ServerException{
return getServerMsg("templateInfo");
}
@Override
public String getStages() throws ServerException{
return getServerMsg("stages");
}
@Override
public String getReport() throws ServerException{
return getServerMsg("report");
}
}
package com.example.fuzzControll.service.impl;
import com.example.fuzzControll.annotion.NeedCutAround;
import com.example.fuzzControll.annotion.NeedCutBefore;
import com.example.fuzzControll.conf.KittyProperties;
import com.example.fuzzControll.exception.testException.CmdException;
import com.example.fuzzControll.exception.testException.FuzzException;
import com.example.fuzzControll.domain.bo.TestEntity;
import com.example.fuzzControll.service.VulnerabilityTypeService;
import com.example.fuzzControll.tools.test.TestCmdTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
@Slf4j
@Service("vulnerabilityTypeService")
public class VulnerabilityTypeServiceImpl implements VulnerabilityTypeService {
TestCmdTools cmdTools = new TestCmdTools();
@Autowired
KittyProperties kitty;
@Override
@NeedCutAround(name ="kitty",function = "generation")
public Map<String, List<String>> generation(TestEntity testEntity,int missionId) throws FuzzException, CmdException {
String cmd = parseParameters(testEntity);
if (cmd.isEmpty()) {
throw new FuzzException("cmd is null ! The number of parameters does not match!");
}
return cmdTools.runProgramCmdAndResult(cmd,"vulnerability","Vulnerability-"+testEntity.getTestClassName());
}
public String parseParameters(TestEntity testEntity) {
try {
switch (testEntity.getTestClassName().toLowerCase()) {
case "array_index_out_of_bounds_vulnerability"://have error
return cmd(testEntity, 0);
case "boundary_condition_vulnerability"://have error
return cmd(testEntity, 1);
case "buffer_overflow_vulnerability"://have error
return cmd(testEntity, 2);
case "command_injection_vulnerability"://have error
return cmd(testEntity, 3);
case "memory_duplicate_release_vulnerability"://have error
return cmd(testEntity, 4);
case "format_string_vulnerability"://have error
return cmd(testEntity, 5);
case "integer_overflow_vulnerability"://have error
return cmd(testEntity, 6);
case "numeric_error_vulnerability"://have error
return cmd(testEntity, 7);
case "symbol_extension_vulnerability"://have error
return cmd(testEntity, 8);
case "uaf_vulnerability"://have error
return cmd(testEntity, 9);
case "cross_script_vulnerability"://have error
return cmd(testEntity, 10);
case "sql_injection_vulnerability"://have error
return cmd(testEntity, 11);
default:
throw new FuzzException("Unknown method!");
}
} catch (FuzzException e) {
throw new FuzzException("Unknown class!");
}
}
private String cmd(TestEntity testEntity, int kindNum) {
return kitty.getVenvPath() + " " + kitty.getVulnerabilityTypePath() + "vul_types_test.py " + kindNum;
}
}
package com.example.fuzzControll.service.impl;
import com.example.fuzzControll.conf.IntegrationPathProperties;
import com.example.fuzzControll.service.websocketClientService;
import lombok.extern.slf4j.Slf4j;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.net.URI;
import java.net.URISyntaxException;
@Slf4j
@Service("websocketClientService")
public class websocketClientServiceImpl implements websocketClientService {
public static WebSocketClient webSocketClient = null;
@Autowired
IntegrationPathProperties properties;
@Override
public void connect() {
try {
webSocketClient = new WebSocketClient(new URI(properties.getWebSocketUri()+"fuzzIntegration")) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
log.info("connect...");
}
@Override
public void onMessage(String s) {
log.info("get message:{}", s);
}
@Override
public void onClose(int i, String s, boolean b) {
log.info("disconnect code:{} reason:{} {}", i, s, b);
}
@Override
public void onError(Exception e) {
log.info("connect error!");
}
};
webSocketClient.connect();
}catch (URISyntaxException e){
e.printStackTrace();
}
}
@Override
public void disconnect() {
try {
webSocketClient.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package com.example.fuzzControll.service;
import org.java_websocket.client.WebSocketClient;
public interface websocketClientService {
void connect();
void disconnect();
}
package com.example.fuzzControll.tools.file;
import com.example.fuzzControll.conf.AflnetProperties;
import com.example.fuzzControll.conf.SpringContextUtil;
import com.example.fuzzControll.exception.fileExcption.FileException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
@Slf4j
public class FileTools {
AflnetProperties properties = (AflnetProperties) SpringContextUtil.getBean("AflnetProperties");
public void load(MultipartFile file) throws FileException {
if (file == null) {
throw new FileException("upload file is null !");
}
try (InputStream inputStream = file.getInputStream();
FileOutputStream outputStream = new FileOutputStream(properties.getSeedPath() + "/" + file.getOriginalFilename());) {
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
throw new FileException("write file error !");
}
}
/**
* 文件备份至数据库
*
* @param filename
* @return
*/
public byte[] fileReadAndTranstoBytes(String path, String filename) {
File file = new File(path + filename);
byte[] buffer = new byte[(int) file.length()];
try (
FileInputStream inputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);) {
if (file.length() > Integer.MAX_VALUE && file.length() <= 0) {
log.error("KittyLogFile is too long or has no content!");
}
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
System.out.println(buffer.length);
}
} catch (Exception e) {
e.printStackTrace();
}
return buffer;
}
/**
* 读取数据库文件至本地
*/
public void loadFileInLocal(String fileLoadPath, String fileName, byte[] fileBytes) {
File file = new File(fileLoadPath + "/" + fileName);
try (FileOutputStream fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(fileBytes);
BufferedInputStream bufferedInputStream = new BufferedInputStream(byteArrayInputStream);) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
bufferedOutputStream.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
throw new FileException("Cannot find path:" + fileLoadPath + "! Maybe there is no permission for this file!");
} catch (IOException e) {
throw new FileException("Load file failed!");
}
}
}
package com.example.fuzzControll.tools.system;
import com.example.fuzzControll.conf.AflnetProperties;
import com.example.fuzzControll.conf.KittyProperties;
import com.example.fuzzControll.conf.SpringContextUtil;
import com.example.fuzzControll.mapper.KittyMapper;
import com.example.fuzzControll.mapper.MissionInfoMapper;
import com.example.fuzzControll.service.AflnetPersistenceService;
import com.example.fuzzControll.service.KittyFuzzPersistenceService;
import com.example.fuzzControll.tools.test.TestCmdTools;
import java.util.concurrent.ConcurrentHashMap;
/**
* 系统类全局参数,负责代码调用
*/
public class GlobalClass {
public static KittyMapper kittyMapper = (KittyMapper) SpringContextUtil.getBean("KittyMapper");
public static KittyProperties kittyProperties = (KittyProperties) SpringContextUtil.getBean("kittyProperties");
public static KittyFuzzPersistenceService kittyFuzzPersistenceService =(KittyFuzzPersistenceService) SpringContextUtil.getBean("KittyFuzzPersistenceService");
public static AflnetProperties aflnetProperties = (AflnetProperties) SpringContextUtil.getBean("AflnetProperties");
public static AflnetPersistenceService aflnetPersistenceService = (AflnetPersistenceService) SpringContextUtil.getBean("AflnetPersistenceService");
public static MissionInfoMapper missionInfoMapper = (MissionInfoMapper) SpringContextUtil.getBean("MissionInfoMapper");
public static TestCmdTools testCmdTools = (TestCmdTools) SpringContextUtil.getBean("TestCmdTools");
}
package com.example.fuzzControll.tools.system;
import java.util.concurrent.ConcurrentHashMap;
/**
* 系统运行时,全局参数
*/
public class SystemRunningParams {
/**
* 系统全局测试时间参数
*/
public static ConcurrentHashMap<String, ConcurrentHashMap<String, Long>> testTimeMessage = new ConcurrentHashMap<>();
/**
* 多线程异常控制
*/
public static ConcurrentHashMap<Thread, String> ThreadState = new ConcurrentHashMap<>();
/**
* 系统中运行的aflnet当前missionId
*/
public static int aflnetMissionId = 0;
/**
* 系统中运行的kitty当前missionId
*/
public static int kittyMissionId = 0;
/**
* aflnet运行时数据
*/
public static ConcurrentHashMap<String, String> aflnetData = new ConcurrentHashMap<>();//当前aflnet任务的数据
/**
* kitty运行时数据
*/
public static ConcurrentHashMap<String, String> kittyData = new ConcurrentHashMap<>();//当前kitty任务的数据
public static void init(){
/*初始化aflnet和kitty时间参数*/
testTimeMessage.put("aflnet",new ConcurrentHashMap<>());
testTimeMessage.put("kitty",new ConcurrentHashMap<>());
/*初始化两个测试的起止时间*/
testTimeMessage.get("aflnet").put("start", 0L);
testTimeMessage.get("aflnet").put("end", 0L);
testTimeMessage.get("kitty").put("start", 0L);
testTimeMessage.get("kitty").put("end", 0L);
}
}
package com.example.fuzzControll.tools.test;
import com.example.fuzzControll.exception.testException.CmdException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Component
public class SingleCmdTools {
public List<String> runCmd(String cmd, String caller) throws CmdException {
List<String> result = new ArrayList<String>();
try {
log.info(caller + " is running!");
Process process = Runtime.getRuntime().exec(cmd);
printMessage(process.getInputStream(), result);
printMessage(process.getErrorStream(), new ArrayList<String>());
process.waitFor();
log.info(caller + " end!");
} catch (Exception e) {
e.printStackTrace();
throw new CmdException(caller + " run cmd failed!");
}
return result;
}
private List<String> printMessage(final InputStream input, final List<String> result) {
new Thread(new Runnable() {
@Override
public void run() {
Reader reader = new InputStreamReader(input);
BufferedReader bf = new BufferedReader(reader);
String line = null;
try {
while ((line = bf.readLine()) != null) {
result.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return result;
}
}
package com.example.fuzzControll.tools.test;
import com.alibaba.fastjson.JSONObject;
import com.example.fuzzControll.annotion.NeedCutBefore;
import com.example.fuzzControll.domain.bo.CmdStartParams;
import com.example.fuzzControll.domain.vo.KittyResult;
import com.example.fuzzControll.domain.vo.TestReturnEntity;
import com.example.fuzzControll.exception.testException.AflnetException;
import com.example.fuzzControll.exception.testException.CmdException;
import com.example.fuzzControll.exception.mysqlException.MysqlException;
import com.example.fuzzControll.service.impl.websocketClientServiceImpl;
import com.example.fuzzControll.tools.system.GlobalClass;
import com.example.fuzzControll.tools.system.SystemRunningParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import java.io.*;
import java.util.*;
import java.util.stream.Collectors;
//todo need modify
@Slf4j
@Component("TestCmdTools")
public class TestCmdTools {
Boolean send = false;
Boolean show = true;
/**
* 运行不需要后台运行cmd
*/
public List<String> runCmd(String cmd, String caller) throws CmdException {
List<String> result = new ArrayList<String>();
try {
log.info(caller + " is running!");
Process process = Runtime.getRuntime().exec(cmd);
printMessage(process.getInputStream(), result);
printMessage(process.getErrorStream(), new ArrayList<String>());
process.waitFor();
log.info(caller + " end!");
} catch (Exception e) {
e.printStackTrace();
throw new CmdException(caller + " run cmd failed!");
}
return result;
}
//todo 不同协议种子路径也不同
/**
* 运行需要后台运行cmd
* 通过websocket返回数据
*/
@NeedCutBefore(name = "aflnet", function = "startBackup")
public void runProgramCmd(String cmd, String outputFileName) throws AflnetException {
try {
Process process = Runtime.getRuntime().exec(cmd);//执行模糊测试指令
/*打印模糊测试输出*/
printMessageToWeb(process.getInputStream());
printMessage(process.getErrorStream(), new ArrayList<String>());
process.waitFor();
log.info("Aflnet cmd have been run.");
} catch (Exception e) {
log.error("alfnet run error!:" + e.getMessage());
throw new AflnetException("Aflnet run error");
}
}
/**
* 运行需要后台运行cmd
* 将数据存入文件中
*/
public Map<String, List<String>> runProgramCmdAndResult(String cmd, String caller, String missionName) throws CmdException {
Map<String, List<String>> result = new HashMap();
List<String> out = Collections.synchronizedList(new ArrayList<String>());
List<String> error = Collections.synchronizedList(new ArrayList<String>());
try {
Process process = Runtime.getRuntime().exec(cmd);
printMessageByProgramCmd(process.getInputStream(), out);
printMessageByProgramCmd(process.getErrorStream(), error);
process.waitFor();
} catch (Exception e) {
e.printStackTrace();
throw new CmdException("run fuzz error !");
}
out = out.stream().map(s -> s + System.lineSeparator()).collect(Collectors.toList());
error = error.stream().map(s -> s + System.lineSeparator()).collect(Collectors.toList());
result.put("out", out);
result.put("error", error);
//todo 对于无法运行和数据较长的还需要观察
/*新开一个线程存入数据*/
List<String> finalOut = out;
List<String> finalError = error;
new Thread(new Runnable() {
@Override
public void run() {
dataBackUpTransaction(caller, finalOut, finalError, missionName);
}
}).start();
//todo 需要传入任务参数,后期再开发
return result;
}
private List<String> printMessageByProgramCmd(final InputStream input, final List<String> result) {
new Thread(new Runnable() {
@Override
public void run() {
Reader reader = new InputStreamReader(input);
BufferedReader bf = new BufferedReader(reader);
String line = null;
try {
while ((line = bf.readLine()) != null) {
result.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return result;
}
/**
* 错误输出
*
* @param input
* @param result
* @return
*/
private List<String> printMessage(final InputStream input, final List<String> result) {
new Thread(new Runnable() {
@Override
public void run() {
Reader reader = new InputStreamReader(input);
BufferedReader bf = new BufferedReader(reader);
String line = null;
try {
while ((line = bf.readLine()) != null) {
result.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return result;
}
private void printMessageToWeb(final InputStream input) throws IOException, AflnetException {
show = true;
Reader reader = new InputStreamReader(input);
BufferedReader bf = new BufferedReader(reader);
String line = null;
TestReturnEntity returnEntity = new TestReturnEntity();
while ((line = bf.readLine()) != null && TestControlTools.getIsRunning()) {
makeReturnEntity(line, returnEntity);
if (send) {
String data = JSONObject.toJSONString(returnEntity);
try {
websocketClientServiceImpl.webSocketClient.send(data);
} catch (Exception ignored) {
}
}
}
}
/**
* aflnet模糊测试数据键值对返回
*
* @param line
* @param returnEntity
* @return
*/
private 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);
}
SystemRunningParams.testTimeMessage.get("aflnet").put("start", System.currentTimeMillis());
try {
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));
}
} catch (Exception e) {
log.error("Formarting params error!");
throw new AflnetException("Formarting params error!");
}
return returnEntity;
}
public String parse(CmdStartParams cmdStartParams) throws AflnetException {
if (cmdStartParams == null) {
throw new AflnetException("CmdStartParams is null !");
}
StringBuilder cmd = new StringBuilder();
if (cmdStartParams.getNetinfo() != "" && cmdStartParams.getNetinfo() != null) {
cmd.append(" -N " + cmdStartParams.getNetinfo() + " ");
} else {
log.error("There is no netinfo !");
throw new AflnetException("There is no netinfo !");
}
if (cmdStartParams.getProtopcol() != "") {
cmd.append(" -P " + cmdStartParams.getProtopcol() + " ");
}
if (cmdStartParams.getWaiting() != 0) {
cmd.append(" -D " + cmdStartParams.getWaiting() + " ");
}
if (cmdStartParams.getNsname() != "") {
cmd.append(" -e " + cmdStartParams.getNsname() + " ");
}
if (cmdStartParams.getKill()) {
cmd.append(" -K ");
}
if (cmdStartParams.getAwareMode()) {
cmd.append(" -E " + " ");
}
if (cmdStartParams.getRegionMutationOperators()) {
cmd.append(" -R " + " ");
}
if (cmdStartParams.getFalseNegativeMode()) {
cmd.append(" -F " + " ");
}
if (cmdStartParams.getScript() != "") {
cmd.append(" -c " + cmdStartParams.getScript() + " ");
}
if (cmdStartParams.getStateSelectionAlgo() != 0) {
cmd.append(" -q " + cmdStartParams.getStateSelectionAlgo() + " ");
}
if (cmdStartParams.getSeedSelectionAlgo() != 0) {
cmd.append(" -s " + cmdStartParams.getSeedSelectionAlgo() + " ");
}
return cmd.toString();
}
@Transactional(rollbackFor = MysqlException.class)
public void dataBackUpTransaction(String caller, List<String> out, List<String> error, String missionName) {
int missionId =SystemRunningParams.kittyMissionId;
try {
/*kitty结果存入数据库*/
KittyResult kittyResult = new KittyResult(missionId, out.toString(), error.toString());
GlobalClass.kittyMapper.kittyResultsBackup(kittyResult);
} catch (Exception e) {
e.printStackTrace();
log.error("kitty backup error!");
}
// /*kitty的协议模板方法的日志和数据包文件存入数据库*/
// if (caller.equals("protocolTemplate")) {
//// GlobalClass.kittyFuzzPersistenceService.KittyPackagesBackup(missionId);
// GlobalClass.missionInfoMapper.insertMission(new MissionInfo(missionId, 2, new Date(), missionName,));
// } else {
// /*存入missionInfo信息*/
// GlobalClass.missionInfoMapper.insertMission(new MissionInfo(missionId, 3, new Date(), missionName));
// }
}
}
\ No newline at end of file
package com.example.fuzzControll.tools.test;
public class TestControlTools {
private static Boolean isRunning;
public static Boolean getIsRunning() {
return isRunning;
}
public static void setIsRunning(Boolean isRunning) {
TestControlTools.isRunning = isRunning;
}
}
package com.example.fuzzControll.tools.test;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class TestTools {
public static boolean paramsLenghtTest(int paramsLen, int needParamsLen, String name) {
Boolean isOk = paramsLen == needParamsLen;
return isOk == true ? true : false;
}
}
mybatis:
# 配置mapper的扫描,找到所有的mapper.xml映射文件
mapperLocations: classpath*:mapper/**/*Mapper.xml
# 加载全局的配置文件
configLocation: classpath:mybatis/mybatis-config.xml
logging:
pattern:
file: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n"
console: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n"
file:
# 默认日志路径
path: ./fuzzintegrationlog/log
level:
root: info
org.springframework.data.mongodb.core: debug
com.ice.Application: info
logback:
rollingPolicy:
max-file-size: 10MB
aflnet:
seedPath: "/usr/fuzzenv/fuzzenv/aflnet/tutorials/live555/in-rtsp"#aflnet日志
outputPath: "/home/" #D:/code/companyProjects/files/
aflnetPath: "/usr/fuzzenv/fuzzenv/"#alfnet路径
kitty:
logOutPath: "/home/kittylogs/"#kitty协议模板日志生成路径
path: "/usr/fuzzenv/fuzzenv/fuzz50/kitty/renix/" #kitty项目下的各协议生成模板python文件路径
venvPath: "/usr/fuzzenv/fuzzenv/fuzz50/kitty/venv/bin/python"
methodPath: "/usr/fuzzenv/fuzzenv/fuzz50/kitty/2020test/"#kitty下变异方法路径
vulnerabilityTypePath: "/usr/fuzzenv/fuzzenv/fuzz50/kitty/2020test/"#kitty下漏洞类型python路径
mutationPath: "/usr/fuzzenv/fuzzenv/fuzz50/kitty/2020test/"
templateInfoHttp: "http://127.0.0.1:26001/api/template_info.json"#模板信息请求链接
statsHttp: "http://127.0.0.1:26001/api/stats.json"#运行时数据
stagesHttp: "http://127.0.0.1:26001/api/stages.json"#
reportHttp: "http://127.0.0.1:26001/api/report"#
spring:
cloud:
nacos:
discovery:
server-addr: http://${nacos-docker.ip}:8848
datasource:
url: jdbc:mysql://${mysql-docker.ip}:3307/fuzz?allowPublicKeyRetrieval=true&useSSL=falseuseUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
integrationpath:
webSocketUri: ws://${fuzzmaster-docker.ip}:8101/websocket/testResult/
nacos-docker:
ip: 192.168.50.247
fuzzmaster-docker:
ip: 192.168.50.247
mysql-docker:
ip: 192.168.50.247
\ No newline at end of file
spring:
application:
name: fuzz-backend-integration
profiles:
active: dev #默认为开发环境
server:
port: 8103
__ _ _ _ _ _ _ _
/ _| | | | | | | (_) | | | | (_)
| |_ _ _ ____ ____ ______ | |__ __ _ ___ | | __ ___ _ __ __| | ______ _ _ __ | |_ ___ __ _ _ __ __ _ | |_ _ ___ _ __
| _|| | | ||_ /|_ /|______|| '_ \ / _` | / __|| |/ // _ \| '_ \ / _` ||______|| || '_ \ | __|/ _ \ / _` || '__|/ _` || __|| | / _ \ | '_ \
| | | |_| | / / / / | |_) || (_| || (__ | <| __/| | | || (_| | | || | | || |_| __/| (_| || | | (_| || |_ | || (_) || | | |
|_| \__,_|/___|/___| |_.__/ \__,_| \___||_|\_\\___||_| |_| \__,_| |_||_| |_| \__|\___| \__, ||_| \__,_| \__||_| \___/ |_| |_|
__/ |
|___/
\ No newline at end of file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<javascript>
this.$axios(
</javascript>
</body>
</html>
\ No newline at end of file
# Global logging configuration
# 设置日志输出级别以及输出目的地,可以设置多个输出目的地,开发环境下,日志级别要设置成DEBUG或者ERROR
# 前面写日志级别,逗号后面写输出目的地:我自己下面设置的目的地相对应,以逗号分开
# log4j.rootLogger = [level],appenderName1,appenderName2,…
log4j.rootLogger=INFO,CONSOLE,LOGFILE
# log4j.rootLogger=DEBUG,CONSOLE,LOGFILE
#### 控制台输出 ####
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
# 输出到控制台
log4j.appender.CONSOLE.Target = System.out
# 指定控制台输出日志级别
# log4j.appender.CONSOLE.Threshold = DEBUG
# 默认值是 true, 表示是否立即输出
# log4j.appender.CONSOLE.ImmediateFlush = true
# 设置编码方式
log4j.appender.CONSOLE.Encoding = UTF-8
# 日志输出布局
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
# 如果日志输出布局为PatternLayout 自定义级别,需要使用ConversionPattern指定输出格式
log4j.appender.CONSOLE.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss}] %5p (%c:%L) >>> %m%n
#### 输出错误信息到文件 ####
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
# 指定输出文件路径
#log4j.appender.LOGFILE.File =F://Intellij idea/logs/error.log
log4j.appender.LOGFILE.File =./logs/error.log
#日志输出到文件,默认为true
log4j.appender.LOGFILE.Append = true
# 指定输出日志级别
# log4j.appender.LOGFILE.Threshold = ERROR
# 是否立即输出,默认值是 true,
# log4j.appender.LOGFILE.ImmediateFlush = true
# 设置编码方式
log4j.appender.LOGFILE.Encoding = UTF-8
# 日志输出布局
log4j.appender.LOGFILE.layout = org.apache.log4j.PatternLayout
# 如果日志输出布局为PatternLayout 自定义级别,需要使用ConversionPattern指定输出格式
log4j.appender.LOGFILE.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.fuzzControll.mapper.AflnetMapper">
<resultMap type="com.example.fuzzControll.domain.vo.AflnetResult" id="AflnetResult">
<result property="id" column="id" />
<result property="missionId" column="missionId" />
<result property="file" column="file" />
<result property="fileName" column="fileName" />
</resultMap>
<sql id="selectAlfnetResult">
select id, missionId,file, fileName from alfnetResult
</sql>
<insert id="aflnetOutputBackup">
insert into alfnetResult(id,missionId, file, fileName) values(#{id}, #{missionId},#{file}, #{fileName})
</insert>
<select id="selectResultById" resultMap="AflnetResult">
<include refid="selectAlfnetResult"/>
where missionId = #{missionId};
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.fuzzControll.mapper.KittyMapper">
<resultMap type="com.example.fuzzControll.domain.vo.KittyResult" id="KittyResult">
<result property="id" column="id" />
<result property="missionId" column="missionId" />
<result property="resultOut" column="resultOut" />
<result property="resultError" column="resultError" />
</resultMap>
<resultMap type="com.example.fuzzControll.domain.vo.KittyPackageFile" id="kittyPackageFile">
<result property="id" column="id" />
<result property="missionId" column="missionId" />
<result property="kittyRecvFile" column="kittyRecvFile" />
<result property="kittySendFile" column="kittySendFile" />
<result property="kittyRecvFileName" column="kittyRecvFileName" />
<result property="kittySendFileName" column="kittySendFileName" />
</resultMap>
<sql id="selectKittyResult">
select id, missionId,resultOut, resultError from kittyResult
</sql>
<sql id="selectKittyPackageFile">
select id,missionId, kittyRecvFile, kittySendFile,kittyRecvFileName,kittySendFileName from kittyPackageFile;
</sql>
<insert id="kittyResultsBackup">
insert into kittyResult(id,missionId, resultOut, resultError) values(#{id}, #{missionId},#{resultOut}, #{resultError})
</insert>
<insert id="kittyPackagesBackup">
insert into kittyPackageFile(id,missionId, kittyRecvFile, kittySendFile,kittyRecvFileName,kittySendFileName) values(#{id}, #{missionId},#{kittyRecvFile}, #{kittySendFile}, #{kittyRecvFileName}, #{kittySendFileName})
</insert>
<select id="getKittyResults" resultMap="KittyResult">
<include refid="selectKittyResult"/>
</select>
<select id="getKittyPackageFileById" resultType="com.example.fuzzControll.domain.vo.KittyPackageFile">
<include refid="selectKittyPackageFile"/>
where missionId=#{missionId}
</select>
<select id="getKittyResultByMissionId" resultType="com.example.fuzzControll.domain.vo.KittyResult">
<include refid="selectKittyResult"/>
where missionId = #{missionId}
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.fuzzControll.mapper.MissionInfoMapper">
<resultMap type="com.example.fuzzControll.domain.po.MissionInfo" id="MissionInfoInDataBase">
<result property="id" column="id" />
<result property="missionId" column="missionId" />
<result property="tableId" column="tableId" />
<result property="createTime" column="createTime" />
<result property="missionName" column="missionName" />
<result property="state" column="state" />
<result property="runTime" column="runTime" />
</resultMap>
<resultMap type="com.example.fuzzControll.domain.po.MissionInfo" id="MissionInfoInVo">
<result property="id" column="id" />
<result property="missionId" column="missionId" />
<result property="createTime" column="createTime" />
<result property="missionName" column="missionName" />
<result property="stateName" column="state" />
<result property="runTime" column="runTime" />
</resultMap>
<sql id="selectMissionInfo">
select id, missionId ,createTime,missionName ,state,runTime from missionIdInfo
</sql>
<sql id="selectMissionInfoInDataBase">
select id, missionId,tableId, createTime,missionName ,state,runTime from missionIdInfo
</sql>
<insert id="insertMission">
insert into missionIdInfo(missionId, tableId, createTime, missionName, state, runTime)
values (#{missionId}, #{tableId}, #{createTime}, #{missionName}, #{state}, #{runTime})
</insert>
<update id="updateMission">
update missionIdInfo
set state = #{state}, runTime = #{runTime}
where missionId = #{missionId}
</update>
<select id="selectByMissionId" resultMap="MissionInfoInVo">
<include refid="selectMissionInfoInDataBase"/>
where missionId = #{missionId}
</select>
<select id="selectMissionInfoList" resultMap="MissionInfoInVo">
<include refid="selectMissionInfo"/>
</select>
<select id="selectTopMissionId" resultType="java.lang.Integer">
select IFNULL((select missionId from missionIdInfo order by missionId desc limit 1),0) as missionId;
</select>
</mapper>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 全局参数 -->
<settings>
<!-- 使全局的映射器启用或禁用缓存 -->
<setting name="cacheEnabled" value="true" />
<!-- 允许JDBC 支持自动生成主键 -->
<setting name="useGeneratedKeys" value="true" />
<!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 -->
<setting name="defaultExecutorType" value="SIMPLE" />
<!-- 指定 MyBatis 所用日志的具体实现 -->
<setting name="logImpl" value="SLF4J" />
<!-- 使用驼峰命名法转换字段 -->
<!-- <setting name="mapUnderscoreToCamelCase" value="true"/> -->
</settings>
</configuration>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="static/style.css">
<link rel="icon" type="image/x-icon" href="static/favicon.ico">
<link rel="shortcut icon" type="image/x-icon" href="static/favicon.ico">
<title>Kitty Fuzzer</title>
</head>
<body>
<div id="body">
<script src="js/jquery-1.11.1.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/hexdump.js"></script>
<script src="js/jszip.min.js"></script>
<script src="js/filesaver.min.js"></script>
<script src="js/cytoscape.min.js"></script>
<!-- Title -->
<h1>Fuzzer <div id="kitty_version"></div> - <div id="fuzzer_name">Name Not Supported Yet</div></h1>
<!-- Alert if fuzzer not available -->
<div align="center" class="alert alert-danger alert-large" id="error_message">Fuzzer Not Available<br/></div>
<!--- Main table -->
<div class="container-fluid">
<div class="col-lg-20">
<table class="table table-bordered table-striped">
<colgroup>
<col class="col-lg-3"/>
<col class="col-lg-5"/>
<col class="col-lg-3"/>
<row class="row-lg-2"/>
<row class="row-lg-2"/>
</colgroup>
<tbody>
<!-- top row -->
<tr class="row-lg-2">
<!-- session info -->
<td>
<div class="panel panel-danger kitty-cell">
<div class="panel-heading">Session Info</div>
<table class="table table-hover table-striped table-responsive info-table">
<colgroup>
<col class="col-lg-2"/>
<col class="col-lg-3"/>
</colgroup>
<tbody>
<tr>
<td>Test numbers</td>
<td id="test_list_str">N/A</td>
</tr>
<tr>
<td>Current Index</td>
<td id="current_index">N/A</td>
</tr>
<tr>
<td>Start Time</td>
<td id="start_time">N/A</td>
</tr>
<tr>
<td>ETA</td>
<td id="eta">N/A</td>
</tr>
</tbody>
</table>
<table class="table table-hover table-striped table-responsive info-table" ,
id="progress_table">
<tbody>
<tr>
<td>
<div class="progress">
<div class="progress-bar progress-bar-large progress-bar-danger"
role="progress-bar" id="progress_bar" aria-valuenow="0"
aria-valuemin="0" aria-valuemax="100"></div>
</div>
</td>
</tr>
<tr>
<td>
<button id="pause_button" type="button"
class="btn btn-default btn-danger"></button>
</td>
</tr>
</tbody>
</table>
</div>
</td>
<!-- stage graph -->
<td>
<div class="panel panel-danger kitty-cell">
<div class="panel-heading">Fuzzing Stages</div>
<div class="unknown-data-size" id="stages-graph"></div>
</div>
</td>
<!-- reports -->
<td>
<div class="panel panel-danger kitty-cell">
<div class="panel-heading">
Reports (<span id="failure_count" style="align:right;"></span>)
</div>
<div class="unknown-data-size" id="report-table">
<table id="reports" class="table table-bordered table-striped table-responsive">
<colgroup>
<col class="col-lg-2"/>
</colgroup>
<tbody>
</tbody>
</table>
</div>
<button id="export_all" type="button" class="btn btn-danger"
onclick="exportAllReports()">Export All reports
</button>
</div>
</td>
</tr> <!-- top row end -->
<!-- bottom row -->
<tr class="row-lg-2">
<!-- template structure -->
<td>
<div class="panel panel-danger kitty-cell">
<div class="panel-heading">Template Structure</div>
<div class="monospaced-text unknown-data-size" id="template_structure"></div>
</div>
</td>
<!-- current payload -->
<td>
<div class="panel panel-danger kitty-cell">
<div class="panel-heading">Current Payload</div>
<div class="unknown-data-size monospaced-text" id="current_payload_hexdump"></div>
</div>
</td>
<!-- target info -->
<td>
<div class="panel panel-danger kitty-cell">
<div class="panel-heading">Target Information</div>
</div>
</td>
</tr> <!-- bottom row end -->
</tbody>
</table>
</div> <!-- col-lg-20 -->
</div> <!-- container -->
</div> <!-- body -->
<!-- update the stages graph -->
<script type="text/javascript">
var state = {
template_info: {},
reports: new Array()
};
function renderStageGraph(elements) {
var cy = cytoscape({
container: $('#stages-graph'),
boxSelectionEnabled: false,
autounselectify: true,
selectable: false,
style: cytoscape.stylesheet()
.selector('node')
.css({
'content': 'data(id)',
'background-color': '#f2dede',
})
.selector('edge')
.css({
'target-arrow-shape': 'triangle',
'width': 3,
'line-color': '#f2dede',
'target-arrow-color': '#f2dede',
'background-color': '#f2dede',
})
.selector('.highlighted')
.css({
'background-color': '#c9302c',
'line-color': '#c9302c',
'target-arrow-color': '#c9302c',
'transition-property': 'background-color, line-color, target-arrow-color',
'transition-duration': '0.1s'
}),
elements: elements,
layout: {
name: 'circle',
directed: true,
roots: 'Start',
padding: 10
}
});
};
function triggerStageGraphUpdate() {
$.getJSON('../api/stages.json', updateStageGraph);
}
function is_edge_in_path(curr_path, src, dst) {
return (
(curr_path.indexOf(dst) != -1) &&
(curr_path.indexOf(src) != -1) &&
((curr_path.indexOf(src) + 1) == curr_path.indexOf(dst))
)
}
function get_edge_classes(curr_path, src, dst) {
if(is_edge_in_path(curr_path, src, dst))
return 'highlighted';
else
return '';
}
function has_node(elements, node) {
return elements.nodes.indexOf(node) != -1;
}
function add_node_if_missing(elements, node) {
if(has_node(elements, node) == false) {
elements.nodes.push({data: {id: node}});
}
}
function updateStageGraph(resp) {
var curr_path = resp.current;
var all_stages = resp.stages;
/* Gather a list of all nodes in current path */
if(state.current_path === curr_path.toString())
return;
state.current_path = curr_path.toString();
var elements = {};
elements.nodes = new Array();
elements.edges = new Array();
curr_path.unshift('Start');
$.each(curr_path, function(idx, value) {
elements.nodes.push({data: {id: value}, classes: 'highlighted'});
});
/*
build all the edges, each entry in all_stages holds a
list of destinations from the key
*/
$.each(all_stages, function(src, v) {
/* don't set the same edge twice, even if it occurs twice */
var cache = new Array();
$.each(v, function(idx, dst) {
/* highlight the edge if it is in current path */
var classes = get_edge_classes(curr_path, src, dst);
if(cache.indexOf(dst) == - 1) {
elements.edges.push({
data: {source: src, target: dst, id: src + '--' + dst},
classes:classes,
});
add_node_if_missing(elements, dst);
cache.push(dst);
}
});
add_node_if_missing(elements, src);
});
renderStageGraph(elements);
}
function updateReports(reports) {
if(reports != state.reports) {
$('#reports tbody tr').remove();
state.reports = reports;
if (reports.length > 0) {
reports.sort(function(a, b){return a[0]-b[0]});
var tbody = $('#reports').find('tbody');
$.each(reports, function(index, entry) {
var test_number = entry[0];
tbody.append($('<tr>')
.append($('<td>').text(test_number))
.append($('<td>').text(entry[1]))
.append($('<td>').text(entry[2]))
.attr('onclick', "document.location = '" + "static/report.html?report_id=" + test_number +"';")
.attr('style', 'cursor: pointer;')
.attr('title', 'Show report ' + test_number)
);
});
}
}
}
/* Fetch all reports, return a dictionary - testname/report */
function getAllReports() {
var res = {};
$.each(state.reports, function(index, entry) {
var test_number = entry[0];
var report = $.ajax({
type: 'GET',
url: '../api/report?report_id=' + test_number,
async: false
}).responseText;
res[test_number] = report;
});
return res;
}
/* Store all reports into a single zip file */
function exportAllReports() {
var zip = new JSZip();
var filename = 'kitty_' + state.start_time.toString() + '_reports.zip';
var report_dir = zip.folder('reports');
var reports = getAllReports();
$.each(reports, function(test_number, report) {
report_dir.file('report_' + test_number.toString() + '.json', report);
});
var content = zip.generate({type:"blob"});
saveAs(content, filename);
}
function updatePauseState(paused) {
if(paused != state.paused) {
var btn_text = (paused == true) ? 'Resume' : 'Pause';
var btn_action = (paused == true) ? 'doResume();' : 'doPause();';
$('#pause_button').text(btn_text);
$('#pause_button').attr('onclick', btn_action);
state.paused = paused;
}
}
function updateFieldFromDict(field, d) {
if(state[field] != d[field]) {
state[field] = d[field];
disp = state[field] == null ? '--' : state[field];
$('#' + field).text(disp);
}
}
function updateStats(stats) {
if(stats.start_time != state.start_time) {
updateFieldFromDict('kitty_version', stats);
updateFieldFromDict('test_list_str', stats);
updateFieldFromDict('fuzzer_name', stats);
state.start_time = stats.start_time;
$('#start_time').text(new Date(Math.floor(stats.start_time * 1000)).toISOString().slice(0,19).replace(/T|Z/g," "));
}
updateFieldFromDict('failure_count', stats);
updateFieldFromDict('current_index', stats);
}
function updateCurrentPayload(test_details) {
var curr = test_details.node.value.rendered.base64;
if(state.current_payload != curr) {
$('#current_payload_hexdump').html(convertToHtml(Hexdump.dump(atob(curr))));
state.current_payload = curr;
}
}
function convertToHtml(text) {
var text = $('<div>').text(text).html();
text = text.replace(/ /g, '&nbsp;');
text = text.replace(/\n/g, '<br>');
return text;
}
function updateTemplateStructure(test_details) {
var hash = test_details['node']['hash'];
if(!state.waiting_for_template_structure) {
if(hash != state.template_info.hash) {
$.getJSON('api/template_info.json', function (data) {
state.template_info = data;
state.template_info.hash = hash;
state.waiting_for_template_structure = false;
setTimeout(performUpdate, 10);
});
state.waiting_for_template_structure = true;
}
else {
updateTemplateWithCurrentState(test_details);
}
}
}
function updateTemplateWithCurrentState(test_details) {
var tree_string = buildTree(state.template_info, test_details, 0, test_details.node.mutation.current_index);
$('#template_structure').html(tree_string);
}
function buildTree(node, test_details, depth, relative_mutation_index) {
var res = '';
var node_total_number = node.mutation.total_number;
var mutating = relative_mutation_index < node_total_number && relative_mutation_index > 0;
res += '&nbsp;'.repeat(depth * 2);
res += '<b>' + node.name + '</b>';
res += ' (' + node.field_type + ')';
if(mutating) {
if(node_total_number > 0) {
node_total_number -= 1;
}
res += '(' + relative_mutation_index.toString() + '/' + (node_total_number).toString() + ')';
res = '<span class="mutation-highlight">' + res + '</span>';
}
res += '<br>';
if(node.fields)
$.each(node.fields, function(index, value){
res += buildTree(value, test_details, depth + 1, relative_mutation_index);
relative_mutation_index -= value.mutation.total_number;
});
return res;
}
function updateProgress(stats, eta) {
var start = stats.start_index;
var end = stats.end_index;
var current = stats.current_index;
var percent;
if(current == null) {
percent = 100;
}
else {
percent = Math.round(100.0 / (end - start) * (current - start));
}
$('#progress_bar').text(percent + '%');
$('#progress_bar').css('width', percent + '%').attr('aria-valuenow', percent);
var msg;
if (current == null) {
msg = 'Fuzzing session completed';
}
else {
msg = eta;
}
$('#eta').text(msg);
}
function doPause() {
$.post('/api/action/pause');
$('#pause_button').disabled = true;
}
function doResume() {
$.post('/api/action/resume');
$('#pause_button').disabled = true;
}
function updateFuzzingStage(test_details){
if(test_details.sequence.current != state.current_sequence) {
test_details.sequence.current = state.current_sequence;
triggerStageGraphUpdate();
}
}
function processResponse(data) {
if($('#error_message').is(":visible"))
$('#error_message').hide({duration: 'fast', easing: 'linear'});
if(data.paused != null) {
updatePauseState(data.paused);
}
if(data.stats != null) {
updateStats(data.stats);
updateProgress(data.stats, data.eta);
}
if(data.current_test != null){
updateTemplateStructure(data.current_test);
updateFuzzingStage(data.current_test);
updateCurrentPayload(data.current_test);
}
if(data.reports_extended != null) {
updateReports(data.reports_extended);
}
setTimeout(performUpdate, 3000);
}
function handleFailure() {
if(!$('#error_message').is(":visible"))
$('#error_message').show();
setTimeout(performUpdate, 10000);
}
function performUpdate() {
$.getJSON('api/stats.json', processResponse).fail(handleFailure);
}
updatePauseState(false);
performUpdate();
</script>
</body>
</html>
] with root cause
com.alibaba.fastjson2.JSONException: offset 1, character <, line 1, column 2, fastjson-version 2.0.31 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="static/style.css">
<link rel="icon" type="image/x-icon" href="static/favicon.ico">
<link rel="shortcut icon" type="image/x-icon" href="static/favicon.ico">
<title>Kitty Fuzzer</title>
</head>
<body>
<div id="body">
<script src="js/jquery-1.11.1.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/hexdump.js"></script>
<script src="js/jszip.min.js"></script>
<script src="js/filesaver.min.js"></script>
<script src="js/cytoscape.min.js"></script>
<!-- Title -->
<h1>Fuzzer <div id="kitty_version"></div> - <div id="fuzzer_name">Name Not Supported Yet</div></h1>
<!-- Alert if fuzzer not available -->
<div align="center" class="alert alert-danger alert-large" id="error_message">Fuzzer Not Available<br/></div>
<!--- Main table -->
<div class="container-fluid">
<div class="col-lg-20">
<table class="table table-bordered table-striped">
<colgroup>
<col class="col-lg-3"/>
<col class="col-lg-5"/>
<col class="col-lg-3"/>
<row class="row-lg-2"/>
<row class="row-lg-2"/>
</colgroup>
<tbody>
<!-- top row -->
<tr class="row-lg-2">
<!-- session info -->
<td>
<div class="panel panel-danger kitty-cell">
<div class="panel-heading">Session Info</div>
<table class="table table-hover table-striped table-responsive info-table">
<colgroup>
<col class="col-lg-2"/>
<col class="col-lg-3"/>
</colgroup>
<tbody>
<tr>
<td>Test numbers</td>
<td id="test_list_str">N/A</td>
</tr>
<tr>
<td>Current Index</td>
<td id="current_index">N/A</td>
</tr>
<tr>
<td>Start Time</td>
<td id="start_time">N/A</td>
</tr>
<tr>
<td>ETA</td>
<td id="eta">N/A</td>
</tr>
</tbody>
</table>
<table class="table table-hover table-striped table-responsive info-table" ,
id="progress_table">
<tbody>
<tr>
<td>
<div class="progress">
<div class="progress-bar progress-bar-large progress-bar-danger"
role="progress-bar" id="progress_bar" aria-valuenow="0"
aria-valuemin="0" aria-valuemax="100"></div>
</div>
</td>
</tr>
<tr>
<td>
<button id="pause_button" type="button"
class="btn btn-default btn-danger"></button>
</td>
</tr>
</tbody>
</table>
</div>
</td>
<!-- stage graph -->
<td>
<div class="panel panel-danger kitty-cell">
<div class="panel-heading">Fuzzing Stages</div>
<div class="unknown-data-size" id="stages-graph"></div>
</div>
</td>
<!-- reports -->
<td>
<div class="panel panel-danger kitty-cell">
<div class="panel-heading">
Reports (<span id="failure_count" style="align:right;"></span>)
</div>
<div class="unknown-data-size" id="report-table">
<table id="reports" class="table table-bordered table-striped table-responsive">
<colgroup>
<col class="col-lg-2"/>
</colgroup>
<tbody>
</tbody>
</table>
</div>
<button id="export_all" type="button" class="btn btn-danger"
onclick="exportAllReports()">Export All reports
</button>
</div>
</td>
</tr> <!-- top row end -->
<!-- bottom row -->
<tr class="row-lg-2">
<!-- template structure -->
<td>
<div class="panel panel-danger kitty-cell">
<div class="panel-heading">Template Structure</div>
<div class="monospaced-text unknown-data-size" id="template_structure"></div>
</div>
</td>
<!-- current payload -->
<td>
<div class="panel panel-danger kitty-cell">
<div class="panel-heading">Current Payload</div>
<div class="unknown-data-size monospaced-text" id="current_payload_hexdump"></div>
</div>
</td>
<!-- target info -->
<td>
<div class="panel panel-danger kitty-cell">
<div class="panel-heading">Target Information</div>
</div>
</td>
</tr> <!-- bottom row end -->
</tbody>
</table>
</div> <!-- col-lg-20 -->
</div> <!-- container -->
</div> <!-- body -->
<!-- update the stages graph -->
<script type="text/javascript">
var state = {
template_info: {},
reports: new Array()
};
function renderStageGraph(elements) {
var cy = cytoscape({
container: $('#stages-graph'),
boxSelectionEnabled: false,
autounselectify: true,
selectable: false,
style: cytoscape.stylesheet()
.selector('node')
.css({
'content': 'data(id)',
'background-color': '#f2dede',
})
.selector('edge')
.css({
'target-arrow-shape': 'triangle',
'width': 3,
'line-color': '#f2dede',
'target-arrow-color': '#f2dede',
'background-color': '#f2dede',
})
.selector('.highlighted')
.css({
'background-color': '#c9302c',
'line-color': '#c9302c',
'target-arrow-color': '#c9302c',
'transition-property': 'background-color, line-color, target-arrow-color',
'transition-duration': '0.1s'
}),
elements: elements,
layout: {
name: 'circle',
directed: true,
roots: 'Start',
padding: 10
}
});
};
function triggerStageGraphUpdate() {
$.getJSON('../api/stages.json', updateStageGraph);
}
function is_edge_in_path(curr_path, src, dst) {
return (
(curr_path.indexOf(dst) != -1) &&
(curr_path.indexOf(src) != -1) &&
((curr_path.indexOf(src) + 1) == curr_path.indexOf(dst))
)
}
function get_edge_classes(curr_path, src, dst) {
if(is_edge_in_path(curr_path, src, dst))
return 'highlighted';
else
return '';
}
function has_node(elements, node) {
return elements.nodes.indexOf(node) != -1;
}
function add_node_if_missing(elements, node) {
if(has_node(elements, node) == false) {
elements.nodes.push({data: {id: node}});
}
}
function updateStageGraph(resp) {
var curr_path = resp.current;
var all_stages = resp.stages;
/* Gather a list of all nodes in current path */
if(state.current_path === curr_path.toString())
return;
state.current_path = curr_path.toString();
var elements = {};
elements.nodes = new Array();
elements.edges = new Array();
curr_path.unshift('Start');
$.each(curr_path, function(idx, value) {
elements.nodes.push({data: {id: value}, classes: 'highlighted'});
});
/*
build all the edges, each entry in all_stages holds a
list of destinations from the key
*/
$.each(all_stages, function(src, v) {
/* don't set the same edge twice, even if it occurs twice */
var cache = new Array();
$.each(v, function(idx, dst) {
/* highlight the edge if it is in current path */
var classes = get_edge_classes(curr_path, src, dst);
if(cache.indexOf(dst) == - 1) {
elements.edges.push({
data: {source: src, target: dst, id: src + '--' + dst},
classes:classes,
});
add_node_if_missing(elements, dst);
cache.push(dst);
}
});
add_node_if_missing(elements, src);
});
renderStageGraph(elements);
}
function updateReports(reports) {
if(reports != state.reports) {
$('#reports tbody tr').remove();
state.reports = reports;
if (reports.length > 0) {
reports.sort(function(a, b){return a[0]-b[0]});
var tbody = $('#reports').find('tbody');
$.each(reports, function(index, entry) {
var test_number = entry[0];
tbody.append($('<tr>')
.append($('<td>').text(test_number))
.append($('<td>').text(entry[1]))
.append($('<td>').text(entry[2]))
.attr('onclick', "document.location = '" + "static/report.html?report_id=" + test_number +"';")
.attr('style', 'cursor: pointer;')
.attr('title', 'Show report ' + test_number)
);
});
}
}
}
/* Fetch all reports, return a dictionary - testname/report */
function getAllReports() {
var res = {};
$.each(state.reports, function(index, entry) {
var test_number = entry[0];
var report = $.ajax({
type: 'GET',
url: '../api/report?report_id=' + test_number,
async: false
}).responseText;
res[test_number] = report;
});
return res;
}
/* Store all reports into a single zip file */
function exportAllReports() {
var zip = new JSZip();
var filename = 'kitty_' + state.start_time.toString() + '_reports.zip';
var report_dir = zip.folder('reports');
var reports = getAllReports();
$.each(reports, function(test_number, report) {
report_dir.file('report_' + test_number.toString() + '.json', report);
});
var content = zip.generate({type:"blob"});
saveAs(content, filename);
}
function updatePauseState(paused) {
if(paused != state.paused) {
var btn_text = (paused == true) ? 'Resume' : 'Pause';
var btn_action = (paused == true) ? 'doResume();' : 'doPause();';
$('#pause_button').text(btn_text);
$('#pause_button').attr('onclick', btn_action);
state.paused = paused;
}
}
function updateFieldFromDict(field, d) {
if(state[field] != d[field]) {
state[field] = d[field];
disp = state[field] == null ? '--' : state[field];
$('#' + field).text(disp);
}
}
function updateStats(stats) {
if(stats.start_time != state.start_time) {
updateFieldFromDict('kitty_version', stats);
updateFieldFromDict('test_list_str', stats);
updateFieldFromDict('fuzzer_name', stats);
state.start_time = stats.start_time;
$('#start_time').text(new Date(Math.floor(stats.start_time * 1000)).toISOString().slice(0,19).replace(/T|Z/g," "));
}
updateFieldFromDict('failure_count', stats);
updateFieldFromDict('current_index', stats);
}
function updateCurrentPayload(test_details) {
var curr = test_details.node.value.rendered.base64;
if(state.current_payload != curr) {
$('#current_payload_hexdump').html(convertToHtml(Hexdump.dump(atob(curr))));
state.current_payload = curr;
}
}
function convertToHtml(text) {
var text = $('<div>').text(text).html();
text = text.replace(/ /g, '&nbsp;');
text = text.replace(/\n/g, '<br>');
return text;
}
function updateTemplateStructure(test_details) {
var hash = test_details['node']['hash'];
if(!state.waiting_for_template_structure) {
if(hash != state.template_info.hash) {
$.getJSON('api/template_info.json', function (data) {
state.template_info = data;
state.template_info.hash = hash;
state.waiting_for_template_structure = false;
setTimeout(performUpdate, 10);
});
state.waiting_for_template_structure = true;
}
else {
updateTemplateWithCurrentState(test_details);
}
}
}
function updateTemplateWithCurrentState(test_details) {
var tree_string = buildTree(state.template_info, test_details, 0, test_details.node.mutation.current_index);
$('#template_structure').html(tree_string);
}
function buildTree(node, test_details, depth, relative_mutation_index) {
var res = '';
var node_total_number = node.mutation.total_number;
var mutating = relative_mutation_index < node_total_number && relative_mutation_index > 0;
res += '&nbsp;'.repeat(depth * 2);
res += '<b>' + node.name + '</b>';
res += ' (' + node.field_type + ')';
if(mutating) {
if(node_total_number > 0) {
node_total_number -= 1;
}
res += '(' + relative_mutation_index.toString() + '/' + (node_total_number).toString() + ')';
res = '<span class="mutation-highlight">' + res + '</span>';
}
res += '<br>';
if(node.fields)
$.each(node.fields, function(index, value){
res += buildTree(value, test_details, depth + 1, relative_mutation_index);
relative_mutation_index -= value.mutation.total_number;
});
return res;
}
function updateProgress(stats, eta) {
var start = stats.start_index;
var end = stats.end_index;
var current = stats.current_index;
var percent;
if(current == null) {
percent = 100;
}
else {
percent = Math.round(100.0 / (end - start) * (current - start));
}
$('#progress_bar').text(percent + '%');
$('#progress_bar').css('width', percent + '%').attr('aria-valuenow', percent);
var msg;
if (current == null) {
msg = 'Fuzzing session completed';
}
else {
msg = eta;
}
$('#eta').text(msg);
}
function doPause() {
$.post('/api/action/pause');
$('#pause_button').disabled = true;
}
function doResume() {
$.post('/api/action/resume');
$('#pause_button').disabled = true;
}
function updateFuzzingStage(test_details){
if(test_details.sequence.current != state.current_sequence) {
test_details.sequence.current = state.current_sequence;
triggerStageGraphUpdate();
}
}
function processResponse(data) {
if($('#error_message').is(":visible"))
$('#error_message').hide({duration: 'fast', easing: 'linear'});
if(data.paused != null) {
updatePauseState(data.paused);
}
if(data.stats != null) {
updateStats(data.stats);
updateProgress(data.stats, data.eta);
}
if(data.current_test != null){
updateTemplateStructure(data.current_test);
updateFuzzingStage(data.current_test);
updateCurrentPayload(data.current_test);
}
if(data.reports_extended != null) {
updateReports(data.reports_extended);
}
setTimeout(performUpdate, 3000);
}
function handleFailure() {
if(!$('#error_message').is(":visible"))
$('#error_message').show();
setTimeout(performUpdate, 10000);
}
function performUpdate() {
$.getJSON('api/stats.json', processResponse).fail(handleFailure);
}
updatePauseState(false);
performUpdate();
</script>
</body>
</html>
\ No newline at end of file
This source diff could not be displayed because it is too large. You can view the blob instead.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>fuzzbackendmaster</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>fuzzbackendmaster</name>
<description>fuzzbackendmaster</description>
<properties>
<java.version>11</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>2021.0.5</spring-cloud.version>
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
</properties>
<dependencies>
<!-- 微服务依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>3.1.5</version>
</dependency>
<!-- springCloud相关-->
<!-- SpringCloud依赖开始-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
<version>3.1.2</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>2021.0.5.0</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
<version>3.1.5</version>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2021.0.5.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.9</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.31</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.7.2</version>
</dependency>
<!-- log4j - slf4j 日志依赖 结束-->
<dependency>
<groupId>com.fasterxml.uuid</groupId>
<artifactId>java-uuid-generator</artifactId>
<version>3.1.5</version>
</dependency>
<!-- log4j - slf4j 日志依赖 开始-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.6.13</version>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.example.fuzzbackendmaster;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
import java.util.Arrays;
@SpringBootApplication
@EnableFeignClients
public class FuzzBackendMaster {
//todo 不同测试方法,不同同时启动,会出现问题
public static void main(String[] args) {
Arrays.stream(args).forEach(System.out::println);
SpringApplication.run(FuzzBackendMaster.class, args);
System.out.println("Start successfully!");
}
}
/********************************************************************
* 版权所有(C)2023,中国电子科技集团公司第五十研究所。 *
* 文件名称: SpringContextUtil.java//文件名称
* 文件标识: QN2.489.437
* 内容摘要: 获取spring上下文//简要描述本文件的内容,包括主要模块、函数及其功能的说明
* 其它说明: 无
* 当前版本: V1.00.00
* 作者: 张思湛 中国电子科技集团公司电子科学研究院
* 完成日期: 2023年9月18日
* 修改记录1: // 修改历史记录,包括修改日期、修改者及修改内容
* 修改日期:
* 版本号:
* 修改人:
* 修改内容:
* 修改记录2: ……
********************************************************************/
package com.example.fuzzbackendmaster.conf;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public SpringContextUtil() {
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringContextUtil.applicationContext == null) {
SpringContextUtil.applicationContext = applicationContext;
}
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static Object getBean(Class<?> requiredType) {
return applicationContext.getBean(requiredType);
}
}
package com.example.fuzzbackendmaster.conf;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebsocketConf {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.example.fuzzbackendmaster.controller;
import com.example.fuzzbackendmaster.service.FuzzIntegrationFileApi;
import com.example.fuzzbackendmaster.service.FuzzLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
@RequestMapping("/log")
@CrossOrigin
public class FuzzLogController {
@Autowired
FuzzLogService fuzzLogService;
/**
* 下载对应任务的日志;不同任务返回数据类型不同,需要做个表来区分
*/
@RequestMapping(value = "/download/{missionId}", method = RequestMethod.GET)
public void getFuzzLog(@PathVariable("missionId") int missionId,HttpServletResponse response) throws IOException {
try {
fuzzLogService.getFuzzLog(missionId,response);
} catch (Exception e) {
e.printStackTrace();
response.sendError(500, "Download failed!");
}
}
}
package com.example.fuzzbackendmaster.controller;
import com.example.fuzzbackendmaster.pojo.vo.AjaxResult;
import com.example.fuzzbackendmaster.service.FuzzIntegrationFileApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* kitty服务器信息
*/
@RestController
@RequestMapping("/kittyServer")
@CrossOrigin
@Slf4j
public class KittyServerMessageController {
@Autowired
FuzzIntegrationFileApi fuzzIntegrationFileApi;
/**
* 获取服务器stats信息
*/
@RequestMapping(value = "/stats", method = RequestMethod.GET)
public AjaxResult getStats() {
return fuzzIntegrationFileApi.getStats();
}
/**
* 获取服务器templateInfo信息
*/
@RequestMapping(value = "/templateInfo", method = RequestMethod.GET)
public AjaxResult getTemplateInfo() {
return fuzzIntegrationFileApi.getTemplateInfo();
}
/**
* 获取服务器stages信息
*/
@RequestMapping(value = "/stages", method = RequestMethod.GET)
public AjaxResult getStages() {
return fuzzIntegrationFileApi.getStages();
}
/**
* 获取服务器report信息
*/
//todo 了解该功能使用方式
@RequestMapping(value = "/report", method = RequestMethod.GET)
public AjaxResult getReport() {
return fuzzIntegrationFileApi.getReport();
}
}
\ No newline at end of file
package com.example.fuzzbackendmaster.controller;
import com.example.fuzzbackendmaster.pojo.vo.AjaxResult;
import com.example.fuzzbackendmaster.service.FuzzIntegrationFileApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@RestController
@RequestMapping("/mission")
@CrossOrigin
public class MissionInfoController {
@Autowired
FuzzIntegrationFileApi fuzzIntegrationFileApi;
/**
* 查看任务信息
*/
@RequestMapping(value = "/getList", method = RequestMethod.GET)
public AjaxResult getMissionInfo() throws IOException {
return fuzzIntegrationFileApi.selectMissionInfoList();
}
}
package com.example.fuzzbackendmaster.controller;
import com.example.fuzzbackendmaster.pojo.vo.AjaxResult;
import com.example.fuzzbackendmaster.service.FuzzIntegrationFileApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/**
* aflnet种子文件
*/
@Slf4j
@RestController
@RequestMapping("/seedFile")
@CrossOrigin
public class SeedFileController {
@Autowired
FuzzIntegrationFileApi fuzzIntegrationFileApi;
/**
* 种子文件查询接口
*/
@RequestMapping(value = "/list", method = RequestMethod.GET)
public AjaxResult list() {
return fuzzIntegrationFileApi.list();
}
/**
* 种子文件删除接口
*/
@RequestMapping(value = "/delete/{fileName}", method = RequestMethod.GET)
public AjaxResult delete(@PathVariable("fileName") String fileName) {
return fuzzIntegrationFileApi.delFile(fileName);
}
/**
* seeFileUpload
*/
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public AjaxResult upload(MultipartFile file) {
return fuzzIntegrationFileApi.upload(file);
}
}
package com.example.fuzzbackendmaster.controller;
import com.example.fuzzbackendmaster.exception.CmdException;
import com.example.fuzzbackendmaster.exception.FuzzException;
import com.example.fuzzbackendmaster.pojo.vo.AjaxResult;
import com.example.fuzzbackendmaster.pojo.vo.TestEntity;
import com.example.fuzzbackendmaster.service.FuzzIntegrationFileApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* 不同类型的测试方法
*/
@Slf4j
@RestController
@RequestMapping("/testClass")
@CrossOrigin
public class TestClassController {
@Autowired
FuzzIntegrationFileApi fuzzIntegrationFileApi;
/**
* 模板
*/
@RequestMapping(value = "/protocolTemplate", method = RequestMethod.POST)
public AjaxResult protocolTemplate(@RequestBody TestEntity testEntity) {
return fuzzIntegrationFileApi.protocolTemplate(testEntity);
}
/**
* 生成方法
*/
@RequestMapping(value = "/generate", method = RequestMethod.POST)
public AjaxResult generate(@RequestBody TestEntity testEntity) {
return fuzzIntegrationFileApi.generate(testEntity);
}
/**
* 变异方法
*/
@RequestMapping(value = "/mutation", method = RequestMethod.POST)
public AjaxResult mutation(@RequestBody TestEntity testEntity) {
return fuzzIntegrationFileApi.mutation(testEntity);
}
/**
* 漏洞类型
*/
@RequestMapping(value = "/vulnerabilityType", method = RequestMethod.POST)
public AjaxResult upload(@RequestBody TestEntity testEntity) {
return fuzzIntegrationFileApi.vulnerability(testEntity);
}
}
package com.example.fuzzbackendmaster.controller;
import com.example.fuzzbackendmaster.pojo.vo.AjaxResult;
import com.example.fuzzbackendmaster.pojo.vo.CmdStartParams;
import com.example.fuzzbackendmaster.service.FuzzIntegrationFileApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
* aflnet测试控制
*/
@Slf4j
@RestController
@RequestMapping("/aflnet")
@CrossOrigin
public class TestController {
@Autowired
FuzzIntegrationFileApi fuzzIntegrationFileApi;
/**
* 测试启动
*/
@RequestMapping(value = "/testStart", method = RequestMethod.POST)
public AjaxResult testStart(@RequestBody final CmdStartParams cmdStartParams) {
//启动时就开始连接
fuzzIntegrationFileApi.connect();
return fuzzIntegrationFileApi.testStart(cmdStartParams);
}
/**
* 测试停止
*/
@RequestMapping(value = "/testStop", method = RequestMethod.GET)
public AjaxResult testStop() {
//停止时就开始关闭
fuzzIntegrationFileApi.disconnect();
return fuzzIntegrationFileApi.testStop();
}
}
\ No newline at end of file
package com.example.fuzzbackendmaster.controller;
import com.example.fuzzbackendmaster.conf.SpringContextUtil;
import com.example.fuzzbackendmaster.service.FuzzIntegrationFileApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.messaging.handler.annotation.SendTo;
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 org.springframework.web.socket.client.WebSocketClient;
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
@ServerEndpoint("/websocket/testResult/{name}")
@Slf4j
@CrossOrigin
public class WebSocket {
private Session session; //与某个客户端连接对话,通过此对客户端发送消息
private static final ConcurrentHashMap<String, WebSocket> WEBSOCKET_CONCURRENTHASHMAP = new ConcurrentHashMap<String, WebSocket>(); //存放所有连接的客户端
private static FuzzIntegrationFileApi fuzzIntegrationFileApi;
@Autowired
public void setOrderService(FuzzIntegrationFileApi fuzzIntegrationFileApi) {
WebSocket.fuzzIntegrationFileApi = fuzzIntegrationFileApi;
}
@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.fuzzbackendmaster.exception;
public class AflnetException extends BaseException {
private static final long serialVersionUID = 1L;
public AflnetException(String defaultMessage) {
super(defaultMessage, "aflnet");
}
}
package com.example.fuzzbackendmaster.exception;
/**
* 基础异常
*/
public class BaseException extends RuntimeException{
private static final long serialVersionUID = 1L;
/**
* 错误消息
*/
private String defaultMessage;
/**
* 所属模块
*/
private String module;
public BaseException() {
}
public BaseException(String defaultMessage, String module) {
this.defaultMessage = defaultMessage;
this.module = module;
}
public String getDefaultMessage() {
return defaultMessage;
}
}
package com.example.fuzzbackendmaster.exception;
/**
* cmd运行异常
*/
public class CmdException extends BaseException {
private static final long serialVersionUID = 1L;
public CmdException() {
}
public CmdException(String defaultMessage) {
super(defaultMessage, "cmd");
}
}
package com.example.fuzzbackendmaster.exception;
/**
* 文件操作异常
*/
public class FileException extends BaseException {
private static final long serialVersionUID = 1L;
public FileException(String defaultMessage) {
super(defaultMessage, "file");
}
}
package com.example.fuzzbackendmaster.exception;
public class FuzzException extends BaseException {
private static final long serialVersionUID = 1L;
public FuzzException(String defaultMessage) {
super(defaultMessage, "fuzz");
}
}
package com.example.fuzzbackendmaster.exception;
public class ServerException extends BaseException {
private static final long serialVersionUID = 1L;
public ServerException(String defaultMessage) {
super(defaultMessage, "server");
}
}
package com.example.fuzzbackendmaster.pojo.vo;
import java.util.HashMap;
public class AjaxResult extends HashMap<String, Object> {
private static final long serialVersionUID = 1L;
/**
* 状态码
*/
public static final String CODE_TAG = "code";
/**
* 返回内容
*/
public static final String MSG_TAG = "data";
/**
* 数据对象
*/
public static final String DATA_TAG = "data";
/**
* 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
*/
public AjaxResult() {
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param data 返回内容
*/
public AjaxResult(int code, String data) {
super.put(CODE_TAG, code);
super.put(MSG_TAG, data);
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
* @param data 数据对象
*/
public AjaxResult(int code, String msg, Object data) {
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
if (data != null) {
super.put(DATA_TAG, data);
}
}
/**
* 返回成功消息
*
* @return 成功消息
*/
public static AjaxResult success() {
return AjaxResult.success("success");
}
/**
* 返回成功数据
*
* @return 成功消息
*/
public static AjaxResult success(Object data) {
return AjaxResult.success("success", data);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @return 成功消息
*/
public static AjaxResult success(String msg) {
return AjaxResult.success(msg, null);
}
/**
* 返回成功消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 成功消息
*/
public static AjaxResult success(String msg, Object data) {
return new AjaxResult(200, msg, data);
}
/**
* 返回警告消息
*
* @param msg 返回内容
* @return 警告消息
*/
public static AjaxResult warn(String msg) {
return AjaxResult.warn(msg, null);
}
/**
* 返回警告消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 警告消息
*/
public static AjaxResult warn(String msg, Object data) {
return new AjaxResult(403, msg, data);
}
/**
* 返回错误消息
*
* @return 错误消息
*/
public static AjaxResult error() {
return AjaxResult.error("操作失败");
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @return 错误消息
*/
public static AjaxResult error(String msg) {
return AjaxResult.error(msg, null);
}
/**
* 返回错误消息
*
* @param msg 返回内容
* @param data 数据对象
* @return 错误消息
*/
public static AjaxResult error(String msg, Object data) {
return new AjaxResult(500, msg, data);
}
/**
* 返回错误消息
*
* @param code 状态码
* @param msg 返回内容
* @return 错误消息
*/
public static AjaxResult error(int code, String msg) {
return new AjaxResult(code, msg, null);
}
/**
* 方便链式调用
*
* @param key 键
* @param value 值
* @return 数据对象
*/
@Override
public AjaxResult put(String key, Object value) {
super.put(key, value);
return this;
}
}
\ No newline at end of file
package com.example.fuzzbackendmaster.pojo.vo;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Data
@Getter
@Setter
public class CmdStartParams {
String netinfo; //netInfo
String protopcol; //protocol
int waiting; //usec
String nsname;//netnsname
Boolean kill;
Boolean awareMode;
Boolean regionMutationOperators;
Boolean falseNegativeMode;
String script;//script
int stateSelectionAlgo;
int seedSelectionAlgo;
}
package com.example.fuzzbackendmaster.pojo.vo;
import lombok.Data;
@Data
public class FuzzLogTransEntity {
private byte[] file;
private String name;
public FuzzLogTransEntity(byte[] file, String name) {
this.file = file;
this.name = name;
}
public FuzzLogTransEntity() {
}
}
package com.example.fuzzbackendmaster.pojo.vo;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
@Data
@Getter
@Setter
public class TestEntity {
String testClassName;
String[] paramJson;
}
package com.example.fuzzbackendmaster.service;
import com.example.fuzzbackendmaster.pojo.vo.AjaxResult;
import com.example.fuzzbackendmaster.pojo.vo.CmdStartParams;
import com.example.fuzzbackendmaster.pojo.vo.FuzzLogTransEntity;
import com.example.fuzzbackendmaster.pojo.vo.TestEntity;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@FeignClient(value = "fuzz-backend-integration")
public interface FuzzIntegrationFileApi {
/**
* seedFlole
*/
@RequestMapping(value = "/seedFile/list", method = RequestMethod.GET)
AjaxResult list();
@RequestMapping(value = "/seedFile/upload", method = RequestMethod.GET, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
AjaxResult upload(@RequestPart("file") MultipartFile file);
@RequestMapping(value = "/seedFile/delete", method = RequestMethod.GET, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
AjaxResult delFile(@RequestPart("fileName") String fileName);
/**
* testclass
*/
@RequestMapping(value = "/testClass/protocolTemplate", method = RequestMethod.POST)
AjaxResult protocolTemplate(@RequestBody TestEntity testEntity);
@RequestMapping(value = "/testClass/generate", method = RequestMethod.POST)
AjaxResult generate(@RequestBody TestEntity testEntity);
@RequestMapping(value = "/testClass/mutation", method = RequestMethod.POST)
AjaxResult mutation(@RequestBody TestEntity testEntity);
@RequestMapping(value = "/testClass/vulnerabilityType", method = RequestMethod.POST)
AjaxResult vulnerability(@RequestBody TestEntity testEntity);
/**
* Aflnet
*/
@RequestMapping(value = "/test/testStop", method = RequestMethod.GET)
AjaxResult testStop();
@RequestMapping(value = "/test/testStart", method = RequestMethod.POST)
AjaxResult testStart(@RequestBody final CmdStartParams cmdStartParams);
@RequestMapping(value = "/kittyServer/stats", method = RequestMethod.GET)
AjaxResult getStats();
@RequestMapping(value = "/kittyServer/templateInfo", method = RequestMethod.GET)
AjaxResult getTemplateInfo();
@RequestMapping(value = "/kittyServer/stages", method = RequestMethod.GET)
AjaxResult getStages();
@RequestMapping(value = "/kittyServer/report", method = RequestMethod.GET)
AjaxResult getReport();
/**
* websocket
*/
@RequestMapping(value = "/websocket/connect", method = RequestMethod.GET)
void connect();
@RequestMapping(value = "/websocket/disConnect", method = RequestMethod.GET)
void disconnect();
@RequestMapping(value = "/log/download/{missionId}", method = RequestMethod.GET)
List<FuzzLogTransEntity> getFuzzLog(@PathVariable("missionId") int missionId);
/**
* 查询任务信息
* @return
*/
@RequestMapping(value = "/mission/getList", method = RequestMethod.GET)
AjaxResult selectMissionInfoList();
}
package com.example.fuzzbackendmaster.service;
import javax.servlet.http.HttpServletResponse;
public interface FuzzLogService {
void getFuzzLog(int missionId, HttpServletResponse response) throws IllegalAccessException;
}
package com.example.fuzzbackendmaster.service.impl;
import com.example.fuzzbackendmaster.pojo.vo.FuzzLogTransEntity;
import com.example.fuzzbackendmaster.service.FuzzIntegrationFileApi;
import com.example.fuzzbackendmaster.service.FuzzLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.List;
@Service("FuzzLogService")
public class FuzzLogServiceImpl implements FuzzLogService {
@Autowired
FuzzIntegrationFileApi fuzzIntegrationFileApi;
@Override
public void getFuzzLog(int missionId, HttpServletResponse response) throws IllegalAccessException {
List<FuzzLogTransEntity> fuzzLogTransEntityList = fuzzIntegrationFileApi.getFuzzLog(missionId);
if(fuzzLogTransEntityList.size()==0){
throw new IllegalStateException();
}
for(FuzzLogTransEntity fuzzLogTransEntity:fuzzLogTransEntityList){
if (fuzzLogTransEntity == null && fuzzLogTransEntity.getFile() == null) {
throw new IllegalStateException();
}
downloadFile(fuzzLogTransEntity.getName(), fuzzLogTransEntity.getFile(), response);
}
}
/**
* 浏览器前端下载后台文件,文件为二进制格式
*/
public void downloadFile(String fileName, byte[] file, HttpServletResponse response) {
if (fileName != null && !"".equals(fileName)) {
if (file != null && file.length != 0) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
try (OutputStream os = response.getOutputStream();) {
os.write(file, 0, file.length);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
package com.example.fuzzbackendmaster.utils;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
public class FileTools {
/**
* 浏览器前端下载后台文件,文件为二进制格式
*/
public void downloadFile(String fileName, byte[] file, HttpServletResponse response) {
if (fileName != null && !fileName.equals("")) {
if (file != null && file.length != 0) {
response.setContentType("application/force-download");// 设置强制下载不打开
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
try (OutputStream os = response.getOutputStream();) {
os.write(file, 0, file.length);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
logging:
pattern:
file: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n"
console: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n"
file:
# 默认日志路径
path: ./fuzzbackendmasterlog/log
level:
root: info
org.springframework.data.mongodb.core: debug
com.ice.Application: info
logback:
rollingPolicy:
max-file-size: 10MB
spring:
cloud:
nacos:
discovery:
server-addr: http://${nacos-docker.ip}:8848
nacos-docker:
ip: 192.168.50.247
spring:
application:
name: fuzz-backend-master
profiles:
active: dev #默认为开发环境
server:
port: 8103
__ _ _ _ _
/ _| | | | | | | | |
| |_ _ _ ____ ____ ______ | |__ __ _ ___ | | __ ___ _ __ __| | ______ _ __ ___ __ _ ___ | |_ ___ _ __
| _|| | | ||_ /|_ /|______|| '_ \ / _` | / __|| |/ // _ \| '_ \ / _` ||______|| '_ ` _ \ / _` |/ __|| __|/ _ \| '__|
| | | |_| | / / / / | |_) || (_| || (__ | <| __/| | | || (_| | | | | | | || (_| |\__ \| |_| __/| |
|_| \__,_|/___|/___| |_.__/ \__,_| \___||_|\_\\___||_| |_| \__,_| |_| |_| |_| \__,_||___/ \__|\___||_|
# Global logging configuration
# 设置日志输出级别以及输出目的地,可以设置多个输出目的地,开发环境下,日志级别要设置成DEBUG或者ERROR
# 前面写日志级别,逗号后面写输出目的地:我自己下面设置的目的地相对应,以逗号分开
# log4j.rootLogger = [level],appenderName1,appenderName2,…
log4j.rootLogger=INFO,CONSOLE,LOGFILE
# log4j.rootLogger=DEBUG,CONSOLE,LOGFILE
#### 控制台输出 ####
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
# 输出到控制台
log4j.appender.CONSOLE.Target = System.out
# 指定控制台输出日志级别
# log4j.appender.CONSOLE.Threshold = DEBUG
# 默认值是 true, 表示是否立即输出
# log4j.appender.CONSOLE.ImmediateFlush = true
# 设置编码方式
log4j.appender.CONSOLE.Encoding = UTF-8
# 日志输出布局
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
# 如果日志输出布局为PatternLayout 自定义级别,需要使用ConversionPattern指定输出格式
log4j.appender.CONSOLE.layout.ConversionPattern=[%d{yyyy-MM-dd HH:mm:ss}] %5p (%c:%L) >>> %m%n
#### 输出错误信息到文件 ####
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
# 指定输出文件路径
#log4j.appender.LOGFILE.File =F://Intellij idea/logs/error.log
log4j.appender.LOGFILE.File =./logs/error.log
#日志输出到文件,默认为true
log4j.appender.LOGFILE.Append = true
# 指定输出日志级别
# log4j.appender.LOGFILE.Threshold = ERROR
# 是否立即输出,默认值是 true,
# log4j.appender.LOGFILE.ImmediateFlush = true
# 设置编码方式
log4j.appender.LOGFILE.Encoding = UTF-8
# 日志输出布局
log4j.appender.LOGFILE.layout = org.apache.log4j.PatternLayout
# 如果日志输出布局为PatternLayout 自定义级别,需要使用ConversionPattern指定输出格式
log4j.appender.LOGFILE.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
<!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.50.247:8101/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