Skip to content

Commit 9798059

Browse files
author
threedr3am
committed
first commit.
0 parents  commit 9798059

File tree

10 files changed

+339
-0
lines changed

10 files changed

+339
-0
lines changed

.DS_Store

6 KB
Binary file not shown.

.gitignore

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
.idea
2+
target

README.md

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
## LOG-AGENT
2+
3+
利用agent hock指定的class,在jar运行周期内,用于跟踪被执行的方法,辅助做一些事情,比如挖洞啊
4+
5+
这样子,就不用干看代码的啦,说不定一运行就能找到漏洞的啦,想想3分钟一个CVE就激动啦
6+
7+
### 编译jar
8+
```
9+
mvn clean compile assembly:single
10+
```
11+
12+
### 运行
13+
```
14+
java -javaagent:/Users/threedr3am/log-agent.jar="^org\.aaa\.bbb$" -jar bug-test-env-1-1.0-SNAPSHOT.jar
15+
```
16+
1. /Users/threedr3am/log-agent.jar: 编译出来的agent jar
17+
2. "^org\.aaa\.bbb$": 双引号内为需要hock的class name匹配正则
18+
3. bug-test-env-1-1.0-SNAPSHOT.jar: 运行的jar
19+
20+
### 辅助挖洞比较实用的正则
21+
```
22+
(org\.aaa\.bbb)|(java\.io\.ObjectInputStream)|(sun\.rmi\.registry)|(com\.sun\.jndi)|(javax\.naming\.InitialContext)|(org\.hibernate\.validator\.internal\.engine\.constraintvalidation\.ConstraintValidatorContextImpl)|(org\.springframework\.expression)|(javax\.el)|(org\.springframework\.jdbc\.core\.StatementCallback)|(javax\.xml\.parsers\.DocumentBuilder)|(org\.jdom\.input\.SAXBuilder)|(javax\.xml\.parsers\.SAXParser)|(org\.dom4j\.io\.SAXReader)|(javax\.xml\.transform\.sax\.SAXTransformerFactory)|(javax\.xml\.validation\.SchemaFactory)|(javax\.xml\.transform\.Transformer)|(javax\.xml\.bind\.Unmarshaller)|(javax\.xml\.validation\.Validator)|(org\.xml\.sax\.XMLReader)|(java\.lang\.Runtime)|(java\.lang\.ProcessBuilder)|(java\.beans\.XMLDecoder)|(org\.yaml\.snakeyaml\.Yaml)|(java\.net\.URL)|(com\.fasterxml\.jackson\.databind\.ObjectMapper)|(com\.alibaba\.fastjson\.JSON)
23+
```
24+
- org\.aaa\.bbb: 改成当前运行jar能匹配上所有class的包名(因为这样能知道当前服务的执行栈信息,更好的定位漏洞)

log-agent.iml

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<module type="JAVA_MODULE" version="4" />

pom.xml

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
7+
<groupId>me.threedr3am.log.agent</groupId>
8+
<artifactId>log-agent</artifactId>
9+
<version>1.0-SNAPSHOT</version>
10+
11+
<dependencies>
12+
<dependency>
13+
<groupId>org.javassist</groupId>
14+
<artifactId>javassist</artifactId>
15+
<version>3.27.0-GA</version>
16+
</dependency>
17+
18+
19+
<dependency>
20+
<groupId>org.projectlombok</groupId>
21+
<artifactId>lombok</artifactId>
22+
<version>1.18.2</version>
23+
</dependency>
24+
</dependencies>
25+
26+
<build>
27+
<plugins>
28+
<plugin>
29+
<groupId>org.apache.maven.plugins</groupId>
30+
<artifactId>maven-assembly-plugin</artifactId>
31+
<configuration>
32+
<archive>
33+
<manifest>
34+
<mainClass>me.threedr3am.log.agent.Agent</mainClass>
35+
</manifest>
36+
<manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
37+
</archive>
38+
<descriptorRefs>
39+
<descriptorRef>jar-with-dependencies</descriptorRef>
40+
</descriptorRefs>
41+
<attach>false</attach>
42+
</configuration>
43+
<executions>
44+
<execution>
45+
<id>make-assembly</id>
46+
<phase>package</phase>
47+
<goals>
48+
<goal>single</goal>
49+
</goals>
50+
</execution>
51+
</executions>
52+
</plugin>
53+
<plugin>
54+
<groupId>org.apache.maven.plugins</groupId>
55+
<artifactId>maven-compiler-plugin</artifactId>
56+
<configuration>
57+
<source>8</source>
58+
<target>8</target>
59+
</configuration>
60+
</plugin>
61+
</plugins>
62+
</build>
63+
64+
</project>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package me.threedr3am.log.agent;
2+
3+
import java.lang.instrument.Instrumentation;
4+
import java.util.Arrays;
5+
import java.util.Base64;
6+
import java.util.HashSet;
7+
import java.util.List;
8+
import java.util.regex.Matcher;
9+
import java.util.regex.Pattern;
10+
import java.util.stream.Collectors;
11+
12+
/**
13+
* @author threedr3am
14+
*/
15+
public class Agent {
16+
17+
public static void premain(String agentArg, Instrumentation inst) {
18+
init(agentArg, inst);
19+
}
20+
21+
public static void agentmain(String agentArg, Instrumentation inst) {
22+
init(agentArg, inst);
23+
}
24+
25+
public static synchronized void init(String action, Instrumentation inst) {
26+
System.out.println("[LOG-AGENT] running ...");
27+
System.out.println("[LOG-AGENT] init ...");
28+
System.out.println("[LOG-AGENT] agentArg: " + action);
29+
try {
30+
JarFileHelper.addJarToBootstrap(inst);
31+
CatClassFileTransformer catClassFileTransformer = new CatClassFileTransformer();
32+
if (action != null && !action.isEmpty()) {
33+
catClassFileTransformer.setPkgPattern(action);
34+
}
35+
inst.addTransformer(catClassFileTransformer, true);
36+
Class[] classes = inst.getAllLoadedClasses();
37+
List<Class> classList = Arrays.asList(classes).stream()
38+
.filter(c -> catClassFileTransformer.getPattern().matcher(c.getName()).find() && inst.isModifiableClass(c))
39+
.collect(Collectors.toList());
40+
classList.forEach(aClass -> System.out.println("[LOG-AGENT] retransformClasses ------------> " + aClass.getName()));
41+
classes = classList.toArray(new Class[0]);
42+
if (classes.length > 0) {
43+
inst.retransformClasses(classes);
44+
}
45+
} catch (Throwable e) {
46+
System.err.println("[LOG-AGENT] Failed to initialize, will continue without security protection.");
47+
e.printStackTrace();
48+
}
49+
}
50+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
package me.threedr3am.log.agent;
2+
3+
import java.io.ByteArrayInputStream;
4+
import java.lang.instrument.ClassFileTransformer;
5+
import java.lang.instrument.IllegalClassFormatException;
6+
import java.security.ProtectionDomain;
7+
import java.util.HashSet;
8+
import java.util.Set;
9+
import java.util.regex.Pattern;
10+
import javassist.ClassClassPath;
11+
import javassist.ClassPool;
12+
import javassist.CtClass;
13+
import javassist.CtMethod;
14+
import javassist.LoaderClassPath;
15+
import javassist.Modifier;
16+
17+
/**
18+
* @author threedr3am
19+
*/
20+
public class CatClassFileTransformer implements ClassFileTransformer {
21+
22+
private String pkgPattern = ".";
23+
private Pattern pattern;
24+
25+
public String getPkgPattern() {
26+
return pkgPattern;
27+
}
28+
29+
public void setPkgPattern(String pkgPattern) {
30+
this.pkgPattern = pkgPattern;
31+
}
32+
33+
public Pattern getPattern() {
34+
return pattern;
35+
}
36+
37+
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
38+
if (pattern == null)
39+
pattern = Pattern.compile(pkgPattern);
40+
className = className.replace("/",".");
41+
if (pattern.matcher(className).find()) {
42+
System.out.println("[LOG-AGENT] --------- modify class: " + className);
43+
CtClass ctClass = null;
44+
try {
45+
ClassPool classPool = ClassPool.getDefault();
46+
addLoader(classPool, loader);
47+
ctClass = classPool.makeClass(new ByteArrayInputStream(classfileBuffer));
48+
Set<String> cache = new HashSet();
49+
CtMethod[] ctMethods = ctClass.getMethods();
50+
if (ctMethods != null) {
51+
inject(ctMethods, cache);
52+
}
53+
ctMethods = ctClass.getDeclaredMethods();
54+
if (ctMethods != null) {
55+
inject(ctMethods, cache);
56+
}
57+
return ctClass.toBytecode();
58+
} catch (Throwable e) {
59+
e.printStackTrace();
60+
} finally {
61+
if (ctClass != null) {
62+
ctClass.detach();
63+
}
64+
}
65+
System.out.println("[LOG-AGENT] --------- modify class end.");
66+
}
67+
return classfileBuffer;
68+
}
69+
70+
private void inject(CtMethod[] ctMethods, Set<String> cache) {
71+
for (int i = 0; i < ctMethods.length; i++) {
72+
CtMethod ctMethod = ctMethods[i];
73+
if (ctMethod.isEmpty() || Modifier.isNative(ctMethod.getModifiers()))
74+
continue;
75+
String methodName = ctMethod.getLongName();
76+
if (cache.contains(methodName))
77+
continue;
78+
try {
79+
System.out.println("[LOG-AGENT] method: " + methodName + " " + cache.size());
80+
StringBuilder stringBuilder = new StringBuilder()
81+
.append("{")
82+
.append(String.format(" if (me.threedr3am.log.agent.CatContext.check(\"%s\"))", methodName))
83+
.append(String.format(" System.out.println(\"%s %s\");", "[LOG-AGENT] ", methodName))
84+
.append("}");
85+
ctMethod.insertBefore(stringBuilder.toString());
86+
cache.add(methodName);
87+
} catch (Throwable e) {
88+
System.err.println(String.format("[LOG-AGENT] inject code into method:%s fail!", methodName));
89+
e.printStackTrace();
90+
}
91+
}
92+
}
93+
94+
private void addLoader(ClassPool classPool, ClassLoader loader) {
95+
classPool.appendSystemPath();
96+
classPool.appendClassPath(new ClassClassPath(CatClassFileTransformer.class));
97+
if (loader != null) {
98+
classPool.appendClassPath(new LoaderClassPath(loader));
99+
}
100+
}
101+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package me.threedr3am.log.agent;
2+
3+
import java.util.HashSet;
4+
import java.util.Set;
5+
6+
/**
7+
* @author threedr3am
8+
*/
9+
public class CatContext {
10+
11+
private static ThreadLocal<Set<String>> cache = new ThreadLocal();
12+
13+
public static boolean check(String method) {
14+
if (cache.get() == null) {
15+
cache.set(new HashSet());
16+
System.out.println("[LOG-AGENT] call begin +++++++++++++++++++++++++++++++++++++++++++++++++ ");
17+
}
18+
if (cache.get().contains(method))
19+
return false;
20+
cache.get().add(method);
21+
return true;
22+
}
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/*
2+
* Copyright 2017-2019 Baidu Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package me.threedr3am.log.agent;
18+
19+
import java.io.IOException;
20+
import java.io.UnsupportedEncodingException;
21+
import java.lang.instrument.Instrumentation;
22+
import java.net.URL;
23+
import java.net.URLDecoder;
24+
import java.util.jar.JarFile;
25+
import lombok.extern.slf4j.Slf4j;
26+
27+
public class JarFileHelper {
28+
29+
/**
30+
* 添加jar文件到jdk的跟路径下,优先加载
31+
*
32+
* @param inst {@link Instrumentation}
33+
*/
34+
public static void addJarToBootstrap(Instrumentation inst) throws IOException {
35+
String localJarPath = getLocalJarPath();
36+
inst.appendToBootstrapClassLoaderSearch(new JarFile(localJarPath));
37+
}
38+
39+
/**
40+
* 获取当前所在jar包的路径
41+
*
42+
* @return jar包路径
43+
*/
44+
public static String getLocalJarPath() throws UnsupportedEncodingException {
45+
URL localUrl = Agent.class.getProtectionDomain().getCodeSource().getLocation();
46+
String path = null;
47+
try {
48+
path = URLDecoder.decode(localUrl.getFile().replace("+", "%2B"), "UTF-8");
49+
} catch (UnsupportedEncodingException e) {
50+
System.out.println("[OpenRASP] Failed to get jarFile path.");
51+
throw e;
52+
}
53+
return path;
54+
}
55+
56+
/**
57+
* 获取当前jar包所在的文件夹路径
58+
*
59+
* @return jar包所在文件夹路径
60+
*/
61+
public static String getLocalJarParentPath() throws UnsupportedEncodingException {
62+
String jarPath = getLocalJarPath();
63+
return jarPath.substring(0, jarPath.lastIndexOf("/"));
64+
}
65+
66+
}
+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
Manifest-Version: 1.0
2+
Agent-Class: me.threedr3am.log.agent.Agent
3+
Can-Redefine-Classes: true
4+
Can-Retransform-Classes: true
5+
Premain-Class: me.threedr3am.log.agent.Agent
6+
Main-Class: me.threedr3am.log.agent.Agent
7+

0 commit comments

Comments
 (0)