Skip to content

Commit 1c035ff

Browse files
committed
feat rasp plugin and Probe and log init
1 parent 4dc1fc6 commit 1c035ff

File tree

6 files changed

+62
-56
lines changed

6 files changed

+62
-56
lines changed

rasp/jvm/JVMAgent/src/main/java/com/security/smithloader/SmithAgent.java

+29-27
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import com.security.smithloader.log.SmithAgentLogger;
1212

1313
import java.lang.instrument.Instrumentation;
14+
import java.lang.reflect.Constructor;
1415
import java.lang.reflect.Method;
1516
import java.util.concurrent.locks.ReentrantLock;
1617

@@ -74,32 +75,34 @@ private static boolean loadSmithProber(String proberPath, Instrumentation inst)
7475
try {
7576
xLoader = new SmithLoader(proberPath, null);
7677
SmithProberClazz = xLoader.loadClass("com.security.smith.SmithProbe");
77-
Method[] methods = SmithProberClazz.getDeclaredMethods();
78-
for (Method method : methods) {
79-
if (method.isSynthetic()) {
80-
System.out.println("Lambda method: " + method.getName());
81-
}
82-
else {
83-
System.out.println("method: " + method.getName());
84-
}
85-
}
8678

8779
Class<?>[] emptyArgTypes = new Class[]{};
8880
//SmithProberObj = Reflection.invokeStaticMethod(SmithProberClazz,"getInstance", emptyArgTypes);
89-
SmithProberObj = SmithProberClazz.newInstance();
90-
91-
Class<?>[] objArgTypes = new Class[]{Object.class};
92-
Reflection.invokeMethod(SmithProberObj,"setClassLoader",objArgTypes,xLoader);
93-
Class<?>[] argType = new Class[]{Instrumentation.class};
94-
Reflection.invokeMethod(SmithProberObj,"setInst",argType,inst);
95-
Reflection.invokeMethod(SmithProberObj,"init",emptyArgTypes);
96-
SmithProberProxyObj = Reflection.invokeMethod(SmithProberObj,"getSmithProbeProxy", emptyArgTypes);
97-
binited = true;
98-
99-
100-
Reflection.invokeMethod(SmithProberObj,"start",emptyArgTypes);
101-
102-
bret = true;
81+
if (SmithProberClazz != null) {
82+
Constructor<?> constructor = SmithProberClazz.getDeclaredConstructor();
83+
constructor.setAccessible(true);
84+
SmithProberObj = constructor.newInstance();
85+
if (SmithProberObj != null) {
86+
Class<?>[] objArgTypes = new Class[]{Object.class};
87+
Reflection.invokeMethod(SmithProberObj,"setClassLoader",objArgTypes,xLoader);
88+
Class<?>[] argType = new Class[]{Instrumentation.class};
89+
Reflection.invokeMethod(SmithProberObj,"setInst",argType,inst);
90+
Reflection.invokeMethod(SmithProberObj,"init",emptyArgTypes);
91+
SmithProberProxyObj = Reflection.invokeMethod(SmithProberObj,"getSmithProbeProxy", emptyArgTypes);
92+
binited = true;
93+
94+
95+
Reflection.invokeMethod(SmithProberObj,"start",emptyArgTypes);
96+
97+
bret = true;
98+
} else {
99+
SmithAgentLogger.logger.info("call SmithProbe init failed");
100+
}
101+
} else {
102+
SmithAgentLogger.logger.info("load com.security.smith.SmithProbe failed");
103+
bret = false;
104+
}
105+
103106
}
104107
catch(Exception e) {
105108
SmithAgentLogger.exception(e);
@@ -135,7 +138,7 @@ private static Boolean unLoadSmithProber() {
135138
SmithAgentLogger.logger.info("unLoadSmithProber Entry");
136139

137140
try {
138-
if(SmithProberObj != null) {
141+
if (SmithProberObj != null) {
139142
SmithAgentLogger.logger.info("Start unload prober");
140143
Class<?>[] emptyArgTypes = new Class[]{};
141144
Reflection.invokeMethod(SmithProberObj,"stop",emptyArgTypes);
@@ -151,8 +154,7 @@ private static Boolean unLoadSmithProber() {
151154
SmithAgentLogger.logger.info("unload prober end");
152155

153156
bret = true;
154-
}
155-
else {
157+
} else {
156158
bret = true;
157159
}
158160
}
@@ -253,8 +255,8 @@ public static void agentmain(String agentArgs, Instrumentation inst) {
253255
else {
254256
System.setProperty("smith.rasp", probeVersion+"-"+checksumStr);
255257
System.setProperty("smith.status", "attach");
258+
System.setProperty("rasp.probe", "smith");
256259
}
257-
System.setProperty("rasp.probe", "smith");
258260
}
259261
}
260262
finally {

rasp/jvm/JVMProbe/src/main/java/com/security/smith/SmithProbe.java

+2-12
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,7 @@ public InputStream getResourceAsStream(String name) {
164164
}
165165

166166
public void init() {
167+
SmithLogger.loggerProberInit();
167168
SmithLogger.logger.info("probe init enter");
168169
smithClasses = new ConcurrentHashMap<>();
169170
patchers = new ConcurrentHashMap<>();
@@ -276,9 +277,8 @@ public void stop() {
276277
smithproxyTimerTask = null;
277278
smithproxyTimer = null;
278279

279-
SmithLogger.loggerProberUnInit();
280-
281280
SmithLogger.logger.info("probe stop leave");
281+
SmithLogger.loggerProberUnInit();
282282
}
283283

284284
public void uninit() {
@@ -586,7 +586,6 @@ public byte[] transform(ClassLoader loader, String className, Class<?> classBein
586586
else {
587587
classWriter = new SmithClassWriter(ClassWriter.COMPUTE_FRAMES);
588588
}
589-
590589
ClassVisitor classVisitor = new SmithClassVisitor(
591590
Opcodes.ASM9,
592591
classWriter,
@@ -596,15 +595,6 @@ public byte[] transform(ClassLoader loader, String className, Class<?> classBein
596595
);
597596

598597
classReader.accept(classVisitor, ClassReader.EXPAND_FRAMES);
599-
/*
600-
try (FileOutputStream fos = new FileOutputStream("/tmp/"+classType.getClassName()+".class")) {
601-
byte[] bytecode = classWriter.toByteArray();
602-
fos.write(bytecode);
603-
System.out.println(classType.getClassName() + " 字节码保存成功!");
604-
} catch (IOException e) {
605-
e.printStackTrace();
606-
}
607-
*/
608598

609599
return classWriter.toByteArray();
610600
} catch (Exception e) {

rasp/jvm/JVMProbe/src/main/java/com/security/smith/SmithProbeProxy.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ else if(className.contains("java.lang.ThreadLocal")) {
9999
}
100100
}
101101
catch(Throwable t) {
102-
t.printStackTrace();
102+
SmithLogger.exception(t);
103103
}
104104
}
105105

rasp/jvm/JVMProbe/src/main/java/com/security/smith/log/SmithLogger.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ public class SmithLogger {
1414
public static Logger logger = Logger.getLogger("RASP");
1515
private static FileHandler fileHandler = null;
1616

17-
static {
17+
18+
public static void loggerProberInit() {
1819
logger.setUseParentHandlers(false);
1920

2021
try {

rasp/librasp/src/comm.rs

+4-13
Original file line numberDiff line numberDiff line change
@@ -192,17 +192,8 @@ impl RASPComm for ThreadMode {
192192
) -> AnyhowResult<()> {
193193
match check_need_mount(_mnt_namespace) {
194194
Ok(same_ns) => {
195-
if same_ns{
196-
self.using_mount = false;
197-
info!(
198-
"process {} namespace as same as root, so no need to mount, using_mount : {}", pid, self.using_mount
199-
);
200-
} else {
201-
self.using_mount = true;
202-
info!(
203-
"process {} namespace are not same as root, so need to mount", pid
204-
);
205-
}
195+
self.using_mount = same_ns;
196+
info!("process {} namespace using_mount : {}", pid, self.using_mount);
206197
}
207198
Err(e) => {
208199
warn!(
@@ -294,13 +285,13 @@ fn mount(pid: i32, from: &str, to: &str) -> AnyhowResult<()> {
294285
};
295286
}
296287

297-
fn check_need_mount(pid_mntns: &String) -> AnyhowResult<bool> {
288+
pub fn check_need_mount(pid_mntns: &String) -> AnyhowResult<bool> {
298289
let root_mnt = std::fs::read_link("/proc/1/ns/mnt")?;
299290
debug!(
300291
"pid namespace && root namespace : {} && {}",
301292
pid_mntns, root_mnt.display()
302293
);
303-
Ok(&root_mnt.display().to_string() == pid_mntns)
294+
Ok(&root_mnt.display().to_string() != pid_mntns)
304295
}
305296

306297
pub struct EbpfMode {

rasp/librasp/src/manager.rs

+24-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use std::process::Command;
77
use anyhow::{anyhow, Result, Result as AnyhowResult};
88
use crossbeam::channel::Sender;
99
use fs_extra::dir::{copy, create_all, CopyOptions};
10-
use fs_extra::file::{copy as file_copy, CopyOptions as FileCopyOptions};
10+
use fs_extra::file::{copy as file_copy, remove as file_remove, CopyOptions as FileCopyOptions};
1111
use libraspserver::proto::{PidMissingProbeConfig, ProbeConfigData};
1212
use log::*;
1313

@@ -17,7 +17,7 @@ use crate::jvm::{java_attach, java_detach, JVMProbe, JVMProbeState};
1717
use crate::nodejs::{nodejs_attach, NodeJSProbe};
1818
use crate::php::{php_attach, PHPProbeState};
1919
use crate::{
20-
comm::{Control, EbpfMode, ProcessMode, RASPComm, ThreadMode},
20+
comm::{Control, EbpfMode, ProcessMode, RASPComm, ThreadMode, check_need_mount},
2121
process::ProcessInfo,
2222
runtime::{ProbeCopy, ProbeState, ProbeStateInspect, RuntimeInspect},
2323
settings,
@@ -348,6 +348,9 @@ impl RASPManager {
348348
ProbeState::AttachedVersionNotMatch => {
349349
match java_detach(pid) {
350350
Ok(result) => {
351+
if let Ok(true) = check_need_mount(mnt_namespace) {
352+
Self::remove_dir_from_to_dest(format!("{}/{}", root_dir.clone(), settings::RASP_JAVA_DIR()));
353+
}
351354
if self.can_copy(mnt_namespace) {
352355
for from in JVMProbe::names().0.iter() {
353356
self.copy_file_from_to_dest(from.clone(), root_dir.clone())?;
@@ -701,6 +704,25 @@ impl RASPManager {
701704
}
702705
};
703706
}
707+
708+
pub fn remove_dir_from_to_dest(dest_root: String) -> AnyhowResult<()> {
709+
if Path::new(&dest_root).exists() {
710+
return match std::fs::remove_dir_all(dest_root.clone()) {
711+
Ok(_) => {
712+
info!("remove file: {}", dest_root);
713+
Ok(())
714+
}
715+
Err(e) => {
716+
warn!("can not remove: {}", e);
717+
Err(anyhow!(
718+
"remove failed: dir {}, err: {}",
719+
dest_root.clone(), e))
720+
}
721+
}
722+
}
723+
return Ok(());
724+
}
725+
704726
pub fn copy_dir_from_to_dest(&self, from: String, dest_root: String) -> AnyhowResult<()> {
705727
let target = format!("{}{}", dest_root, from);
706728
if Path::new(&target).exists() {

0 commit comments

Comments
 (0)