inject_linux_amd64.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. package inject
  2. /*
  3. #cgo CFLAGS: -I include
  4. #cgo amd64 LDFLAGS: ${SRCDIR}/lib/libhotpatch_amd64.a
  5. #cgo arm64 LDFLAGS: ${SRCDIR}/lib/libhotpatch_arm64.a
  6. #include "hotpatch.h"
  7. #include <stdlib.h>
  8. */
  9. import "C"
  10. import (
  11. "bufio"
  12. "debug/elf"
  13. "fmt"
  14. klog "github.com/sirupsen/logrus"
  15. "golang.org/x/arch/x86/x86asm"
  16. "os"
  17. "strings"
  18. "syscall"
  19. "time"
  20. "unsafe"
  21. )
  22. const (
  23. IO_FD_FDID_SYM_OFFSET = 129
  24. NET_SEND_SYM_OFFSET = 518
  25. )
  26. type InstInfo struct {
  27. SymName string
  28. SymSize uint64
  29. SymAddr uint64
  30. PC uint64
  31. Inst x86asm.Inst
  32. OriginInst x86asm.Inst
  33. OriginCode []byte
  34. TargetAddr uint64
  35. OriginTargetAddr uint64
  36. }
  37. type InnerSymbolInfo struct {
  38. IO_fd_fdID InstInfo
  39. NET_Send InstInfo
  40. }
  41. type LibNetInfo struct {
  42. LibName string
  43. LibPath string
  44. FuncSymbol InstInfo
  45. InnerSymbol InnerSymbolInfo
  46. ProcLoadPath string
  47. }
  48. type UprobeData struct {
  49. Offset int
  50. Func string
  51. ELFPath string
  52. }
  53. type JvmInjector struct {
  54. Pid int
  55. ReleaseLibNetInfo LibNetInfo
  56. DebugLibNetInfo LibNetInfo
  57. RecodeInfo LibNetInfo
  58. // 原方法首个指令不为jmp | ReleaseLibNetInfo 读取无异常
  59. PreCheck struct {
  60. NeedInjectionCheck bool // 原指令校验 true表示可以继续执行注入
  61. LoadingCheck bool // true 表示加载成功
  62. IoFdCheck bool // fd地址校验
  63. NetSendFuncCheck bool // netsend校验
  64. EbpfCanInjection bool // 满足则注入ebpf
  65. }
  66. AfterCheck struct {
  67. IoFdCheck bool
  68. NetSendFuncCheck bool
  69. }
  70. Uprobe UprobeData
  71. Rootfs string
  72. }
  73. func (j *JvmInjector) findReleaseAddressInfoFromMem() error {
  74. funcAbsAddress := j.ReleaseLibNetInfo.FuncSymbol.SymAddr
  75. releaseFuncSym := InnerSymbolInfo{}
  76. code, err := j.readMemory(funcAbsAddress, j.ReleaseLibNetInfo.FuncSymbol.SymSize)
  77. if err != nil {
  78. return err
  79. }
  80. pc := uint64(0)
  81. callCount := 0
  82. preContext := InstInfo{}
  83. for pc < uint64(len(code)) {
  84. inst, err := x86asm.Decode(code[pc:], 64)
  85. if err != nil {
  86. fmt.Printf("Decode error at offset 0x%x: %v\n", pc, err)
  87. pc++ // Skip this byte and try to decode again
  88. continue
  89. }
  90. //fmt.Printf("Decoded instuction at 0x%x: %v\n", funcAbsAddress+pc, Inst)
  91. //fmt.Printf("Decoded x86 instuction at 0x%x: %v\n", funcAbsAddress+pc, x86asm.IntelSyntax(inst, 0, nil))
  92. //fmt.Printf("Decoded GNU instuction at 0x%x: %v\n", funcAbsAddress+pc, x86asm.GNUSyntax(Inst, 0, nil))
  93. currentData := InstInfo{
  94. PC: pc,
  95. SymAddr: funcAbsAddress + pc,
  96. Inst: inst,
  97. //IntelInst: x86asm.IntelSyntax(inst, 0, nil),
  98. }
  99. if pc == 0 && inst.Op == x86asm.JMP {
  100. // 已经被修改过的首指令
  101. j.PreCheck.EbpfCanInjection = true
  102. j.Uprobe.ELFPath = j.DebugLibNetInfo.LibPath
  103. klog.Infof("[inject] Inst already modified. <%s>", x86asm.IntelSyntax(inst, 0, nil))
  104. return nil
  105. }
  106. if pc == 0 {
  107. j.ReleaseLibNetInfo.FuncSymbol.PC = currentData.PC
  108. j.ReleaseLibNetInfo.FuncSymbol.Inst = currentData.Inst
  109. j.ReleaseLibNetInfo.FuncSymbol.OriginInst = currentData.Inst
  110. }
  111. if inst.Op == x86asm.MOV {
  112. if dst, okDst := inst.Args[0].(x86asm.Mem); okDst {
  113. if dst.Base == x86asm.RBP {
  114. if src, okSrc := inst.Args[1].(x86asm.Reg); okSrc {
  115. if src == x86asm.R9L {
  116. // debug so
  117. klog.Infof("[inject] release.so is debug.so. <%s>", x86asm.IntelSyntax(inst, 0, nil))
  118. j.PreCheck.EbpfCanInjection = true
  119. j.Uprobe.ELFPath = j.ReleaseLibNetInfo.LibPath
  120. return fmt.Errorf("MOV from register %v to memory %v\n", src, dst)
  121. //return nil
  122. }
  123. }
  124. }
  125. }
  126. //src, okSrc := inst.Args[1].(x86asm.Reg)
  127. //fmt.Println(inst.Args)
  128. //fmt.Printf("Instruction: %+v\n", inst)
  129. //
  130. //fmt.Println(okSrc)
  131. //if okDst && okSrc && dst == x86asm.RBP && src == x86asm.R9L {
  132. // fmt.Println("Instruction is 'mov %r9d, %rbp'")
  133. //}
  134. }
  135. if inst.Op == x86asm.CALL {
  136. //fmt.Printf("Pre instuction at 0x%x: %v\n", preContext.PC, preContext.Inst)
  137. if callCount == 0 {
  138. releaseFuncSym.IO_fd_fdID = preContext
  139. releaseFuncSym.IO_fd_fdID.SymName = "<IO_fd_fdID>(Release)"
  140. preInst := preContext.Inst
  141. fmt.Println(preInst.Op)
  142. fmt.Println((preInst.Args))
  143. // 计算目标地址
  144. if preInst.Op == x86asm.MOV &&
  145. len(preInst.Args) == 4 &&
  146. preInst.Args[0] != nil &&
  147. preInst.Args[0] == x86asm.RDX &&
  148. preInst.Args[1] != nil {
  149. if mem, ok := preInst.Args[1].(x86asm.Mem); ok && mem.Base == x86asm.RIP {
  150. relOffset := mem.Disp // 直接从Mem结构体中读取偏移
  151. targetAddress := preContext.SymAddr + uint64(preInst.Len) + uint64(relOffset)
  152. fmt.Printf("Target address: 0x%x\n", targetAddress)
  153. releaseFuncSym.IO_fd_fdID.TargetAddr = targetAddress
  154. } else {
  155. return fmt.Errorf("The instruction does not use RIP-relative addressing.")
  156. }
  157. } else {
  158. return fmt.Errorf("The decoded instruction is not a MOV to RDX.")
  159. }
  160. //os.Exit(1)
  161. }
  162. callCount++
  163. if callCount == 4 {
  164. releaseFuncSym.NET_Send = currentData
  165. fmt.Printf("4 call Decoded instuction at 0x%x: %v\n", funcAbsAddress+pc, inst)
  166. relOffset, ok := inst.Args[0].(x86asm.Rel)
  167. if !ok {
  168. return fmt.Errorf("The instruction does not use RIP-relative addressing.")
  169. }
  170. targetAddress := currentData.SymAddr + uint64(inst.Len) + uint64(relOffset)
  171. releaseFuncSym.NET_Send.TargetAddr = targetAddress
  172. fmt.Println(releaseFuncSym.NET_Send)
  173. releaseFuncSym.NET_Send.SymName = "<NET_Send>(Release)"
  174. fmt.Printf("Target address: 0x%x\n", targetAddress)
  175. }
  176. }
  177. preContext = InstInfo{
  178. PC: pc,
  179. SymAddr: funcAbsAddress + pc,
  180. Inst: inst,
  181. }
  182. pc += uint64(inst.Len)
  183. }
  184. j.ReleaseLibNetInfo.InnerSymbol = releaseFuncSym
  185. j.ReleaseLibNetInfo.FuncSymbol.OriginCode = code[0:5]
  186. return nil
  187. }
  188. func (j *JvmInjector) findDebugAddressInfoFromMem() (uint64, error) {
  189. funcAbsAddress := j.DebugLibNetInfo.FuncSymbol.SymAddr
  190. debugFuncSym := InnerSymbolInfo{}
  191. //debugFuncSym.FuncSymbol.SymAddr = funcAbsAddress
  192. //offset := sym.Value
  193. size := j.DebugLibNetInfo.FuncSymbol.SymSize
  194. code, err := j.readMemory(funcAbsAddress, size)
  195. //fmt.Println(code, err)
  196. if err != nil {
  197. return 0, err
  198. }
  199. pc := uint64(0)
  200. preContext := InstInfo{}
  201. for pc < uint64(len(code)) {
  202. inst, err := x86asm.Decode(code[pc:], 64)
  203. if err != nil {
  204. fmt.Printf("Decode error at offset 0x%x: %v\n", pc, err)
  205. pc++ // Skip this byte and try to decode again
  206. continue
  207. }
  208. //fmt.Printf("Decoded instuction at 0x%x: %v\n", funcAbsAddress+pc, Inst)
  209. //fmt.Printf("Decoded x86 instuction at 0x%x: %v\n", funcAbsAddress+pc, x86asm.IntelSyntax(inst, 0, nil))
  210. //fmt.Printf("Decoded GNU instuction at 0x%x: %v\n", funcAbsAddress+pc, x86asm.GNUSyntax(Inst, 0, nil))
  211. currentData := InstInfo{
  212. PC: pc,
  213. SymAddr: funcAbsAddress + pc,
  214. Inst: inst,
  215. }
  216. if pc == 0 {
  217. j.DebugLibNetInfo.FuncSymbol.PC = currentData.PC
  218. j.DebugLibNetInfo.FuncSymbol.Inst = currentData.Inst
  219. j.DebugLibNetInfo.FuncSymbol.OriginInst = currentData.Inst
  220. }
  221. if pc == IO_FD_FDID_SYM_OFFSET {
  222. fmt.Printf("Instuction at 0x%x: %v\n", preContext.PC, preContext.Inst)
  223. debugFuncSym.IO_fd_fdID = currentData
  224. debugFuncSym.IO_fd_fdID.SymName = "<IO_fd_fdID>(Debug)"
  225. // 计算目标地址
  226. if currentData.Inst.Op == x86asm.MOV &&
  227. len(currentData.Inst.Args) == 4 &&
  228. currentData.Inst.Args[0] != nil &&
  229. currentData.Inst.Args[0] == x86asm.RDX &&
  230. currentData.Inst.Args[1] != nil {
  231. if mem, ok := currentData.Inst.Args[1].(x86asm.Mem); ok && mem.Base == x86asm.RIP {
  232. // 直接从Mem结构体中读取偏移
  233. relOffset := mem.Disp
  234. targetAddress := currentData.SymAddr + uint64(currentData.Inst.Len) + uint64(relOffset)
  235. fmt.Printf("Find %s Target address: 0x%x\n", debugFuncSym.IO_fd_fdID.SymName, targetAddress)
  236. debugFuncSym.IO_fd_fdID.TargetAddr = targetAddress
  237. // 保存原始数据
  238. debugFuncSym.IO_fd_fdID.OriginTargetAddr = targetAddress
  239. debugFuncSym.IO_fd_fdID.OriginInst = currentData.Inst
  240. j.PreCheck.IoFdCheck = true
  241. } else {
  242. return 0, fmt.Errorf("The instruction does not use RIP-relative addressing.")
  243. }
  244. } else {
  245. return 0, fmt.Errorf("The decoded instruction is not a MOV to RDX.")
  246. }
  247. }
  248. if pc == NET_SEND_SYM_OFFSET {
  249. debugFuncSym.NET_Send = currentData
  250. fmt.Printf("4 call Decoded instuction at 0x%x: %v\n", funcAbsAddress+pc, inst)
  251. relOffset, ok := (inst.Args[0].(x86asm.Rel))
  252. if !ok {
  253. return 0, fmt.Errorf("The decoded instruction is not a Rel.")
  254. }
  255. targetAddress := currentData.SymAddr + uint64(inst.Len) + uint64(relOffset)
  256. debugFuncSym.NET_Send.TargetAddr = targetAddress
  257. debugFuncSym.NET_Send.SymName = "<NET_Send>(Debug)"
  258. fmt.Printf("Find %s Target address: 0x%x\n", debugFuncSym.NET_Send.SymName, targetAddress)
  259. // 保存原始数据
  260. debugFuncSym.NET_Send.OriginTargetAddr = targetAddress
  261. debugFuncSym.NET_Send.OriginInst = currentData.Inst
  262. j.PreCheck.NetSendFuncCheck = true
  263. }
  264. preContext = InstInfo{
  265. PC: pc,
  266. SymAddr: funcAbsAddress + pc,
  267. Inst: inst,
  268. }
  269. pc += uint64(inst.Len)
  270. }
  271. j.DebugLibNetInfo.InnerSymbol = debugFuncSym
  272. return 0, nil
  273. }
  274. func (j *JvmInjector) checkDebugFuncSymAfterChange() (uint64, error) {
  275. funcAbsAddress := j.DebugLibNetInfo.FuncSymbol.SymAddr
  276. debugFuncSym := InnerSymbolInfo{}
  277. code, err := j.readMemory(funcAbsAddress, j.DebugLibNetInfo.FuncSymbol.SymSize)
  278. if err != nil {
  279. return 0, err
  280. }
  281. pc := uint64(0)
  282. preContext := InstInfo{}
  283. for pc < uint64(len(code)) {
  284. inst, err := x86asm.Decode(code[pc:], 64)
  285. if err != nil {
  286. fmt.Printf("Decode error at offset 0x%x: %v\n", pc, err)
  287. pc++ // Skip this byte and try to decode again
  288. continue
  289. }
  290. //fmt.Printf("Decoded instuction at 0x%x: %v\n", funcAbsAddress+pc, Inst)
  291. //fmt.Printf("Decoded x86 instuction at 0x%x: %v\n", funcAbsAddress+pc, x86asm.IntelSyntax(inst, 0, nil))
  292. //fmt.Printf("Decoded GNU instuction at 0x%x: %v\n", funcAbsAddress+pc, x86asm.GNUSyntax(Inst, 0, nil))
  293. currentData := InstInfo{
  294. PC: pc,
  295. SymAddr: funcAbsAddress + pc,
  296. Inst: inst,
  297. }
  298. if pc == NET_SEND_SYM_OFFSET {
  299. fmt.Printf("Instuction at 0x%x: %v\n", preContext.PC, preContext.Inst)
  300. debugFuncSym.IO_fd_fdID = currentData
  301. debugFuncSym.IO_fd_fdID.SymName = "<IO_fd_fdID>(Debug)"
  302. // 计算目标地址
  303. if currentData.Inst.Op == x86asm.MOV &&
  304. len(currentData.Inst.Args) == 4 &&
  305. currentData.Inst.Args[0] != nil &&
  306. currentData.Inst.Args[0] == x86asm.RDX &&
  307. currentData.Inst.Args[1] != nil {
  308. if mem, ok := currentData.Inst.Args[1].(x86asm.Mem); ok && mem.Base == x86asm.RIP {
  309. // 直接从Mem结构体中读取偏移
  310. relOffset := mem.Disp
  311. targetAddress := currentData.SymAddr + uint64(currentData.Inst.Len) + uint64(relOffset)
  312. fmt.Printf("Find %s Target address: 0x%x\n", debugFuncSym.IO_fd_fdID.SymName, targetAddress)
  313. debugFuncSym.IO_fd_fdID.TargetAddr = targetAddress
  314. //j.PreCheck.IoFdCheck = true
  315. if targetAddress == j.ReleaseLibNetInfo.InnerSymbol.IO_fd_fdID.TargetAddr {
  316. j.DebugLibNetInfo.InnerSymbol.IO_fd_fdID.TargetAddr = targetAddress
  317. j.DebugLibNetInfo.InnerSymbol.IO_fd_fdID.Inst = currentData.Inst
  318. j.AfterCheck.IoFdCheck = true
  319. fmt.Println("ok")
  320. }
  321. } else {
  322. return 0, fmt.Errorf("The instruction does not use RIP-relative addressing.")
  323. }
  324. } else {
  325. return 0, fmt.Errorf("The decoded instruction is not a MOV to RDX.")
  326. }
  327. }
  328. if pc == NET_SEND_SYM_OFFSET {
  329. debugFuncSym.NET_Send = currentData
  330. //fmt.Println(currentData.IntelInst)
  331. //fmt.Printf("4 call Decoded instuction at 0x%x: %v\n", funcAbsAddress+pc, inst)
  332. relOffset, ok := (inst.Args[0].(x86asm.Rel))
  333. if !ok {
  334. return 0, fmt.Errorf("The decoded instruction is not a Rel.")
  335. }
  336. targetAddress := currentData.SymAddr + uint64(inst.Len) + uint64(relOffset)
  337. debugFuncSym.NET_Send.TargetAddr = targetAddress
  338. debugFuncSym.NET_Send.SymName = "<NET_Send>(Debug)"
  339. fmt.Printf("Find %s Target address: 0x%x\n", debugFuncSym.NET_Send.SymName, targetAddress)
  340. if targetAddress == j.ReleaseLibNetInfo.InnerSymbol.NET_Send.TargetAddr {
  341. j.DebugLibNetInfo.InnerSymbol.NET_Send.TargetAddr = targetAddress
  342. j.DebugLibNetInfo.InnerSymbol.NET_Send.Inst = currentData.Inst
  343. j.AfterCheck.NetSendFuncCheck = true
  344. }
  345. }
  346. preContext = InstInfo{
  347. PC: pc,
  348. SymAddr: funcAbsAddress + pc,
  349. Inst: inst,
  350. }
  351. pc += uint64(inst.Len)
  352. }
  353. return 0, nil
  354. }
  355. func (j *JvmInjector) checkReleaseFuncSymAfterChange() error {
  356. funcAbsAddress := j.ReleaseLibNetInfo.FuncSymbol.SymAddr
  357. code, err := j.readMemory(funcAbsAddress, j.ReleaseLibNetInfo.FuncSymbol.SymSize)
  358. if err != nil {
  359. return fmt.Errorf("readMemory error in checkReleaseFuncSymAfterChange <%v>", err)
  360. }
  361. inst, err := x86asm.Decode(code[0:], 64)
  362. if err != nil {
  363. return fmt.Errorf("Decode error in checkReleaseFuncSymAfterChange <%v>", err)
  364. }
  365. if inst.Op != x86asm.JMP {
  366. return fmt.Errorf("The instruction does not JMP.")
  367. }
  368. relOffset, ok := inst.Args[0].(x86asm.Rel)
  369. if !ok {
  370. return fmt.Errorf("The instruction does not use RIP-relative addressing.")
  371. }
  372. // 验证target与Debug入口是否一致
  373. targetAddress := funcAbsAddress + uint64(inst.Len) + uint64(relOffset)
  374. if targetAddress != j.DebugLibNetInfo.FuncSymbol.SymAddr {
  375. return fmt.Errorf("Function entry jmp address does not match expectations.")
  376. }
  377. return nil
  378. }
  379. // readMemory 用于读取指定地址的内存数据
  380. func (j *JvmInjector) readMemory(address uint64, size uint64) ([]byte, error) {
  381. memFile := fmt.Sprintf("/proc/%d/mem", j.Pid)
  382. file, err := os.Open(memFile)
  383. if err != nil {
  384. return nil, err
  385. }
  386. defer file.Close()
  387. data := make([]byte, size)
  388. _, err = file.ReadAt(data, int64(address))
  389. if err != nil {
  390. return nil, err
  391. }
  392. return data, nil
  393. }
  394. // findLibraryBases 用于在 /proc/[pid]/maps 文件中查找库的所有基地址
  395. func findLibraryBasesList(pid int, libraryName string, libPath string) ([]uint64, error) {
  396. mapsFile := fmt.Sprintf("/proc/%d/maps", pid)
  397. file, err := os.Open(mapsFile)
  398. if err != nil {
  399. return nil, err
  400. }
  401. defer file.Close()
  402. var bases []uint64
  403. scanner := bufio.NewScanner(file)
  404. for scanner.Scan() {
  405. line := scanner.Text()
  406. if strings.Contains(line, libraryName) && strings.Contains(line, libPath) {
  407. var start, end uint64
  408. fmt.Sscanf(line, "%x-%x", &start, &end)
  409. bases = append(bases, start)
  410. }
  411. }
  412. if len(bases) == 0 {
  413. return nil, fmt.Errorf("library %s not found", libraryName)
  414. }
  415. return bases, nil
  416. }
  417. func (j *JvmInjector) findLibBaseFromProcMaps(libName string) (uint64, string, error) {
  418. mapsFile := fmt.Sprintf("/proc/%d/maps", j.Pid)
  419. file, err := os.Open(mapsFile)
  420. if err != nil {
  421. return 0, "", err
  422. }
  423. defer file.Close()
  424. var start, end uint64
  425. scanner := bufio.NewScanner(file)
  426. for scanner.Scan() {
  427. line := scanner.Text()
  428. if strings.Contains(line, "/"+libName) {
  429. fmt.Sscanf(line, "%x-%x", &start, &end)
  430. fields := strings.Fields(line)
  431. if len(fields) > 5 {
  432. path := fields[5]
  433. if strings.HasSuffix(path, ".so") {
  434. klog.Infof("[inject] found library in map %s", path)
  435. return start, j.Rootfs + path, nil
  436. }
  437. }
  438. }
  439. }
  440. return 1, "", fmt.Errorf("library %s not found", libName)
  441. }
  442. func (j *JvmInjector) findLibBaseByPathFromProcMaps(libPath string) (uint64, string, error) {
  443. mapsFile := fmt.Sprintf("/proc/%d/maps", j.Pid)
  444. file, err := os.Open(mapsFile)
  445. if err != nil {
  446. return 0, "", err
  447. }
  448. defer file.Close()
  449. var start, end uint64
  450. scanner := bufio.NewScanner(file)
  451. for scanner.Scan() {
  452. line := scanner.Text()
  453. if strings.Contains(line, libPath) {
  454. fmt.Sscanf(line, "%x-%x", &start, &end)
  455. fields := strings.Fields(line)
  456. if len(fields) > 5 {
  457. path := fields[5]
  458. if strings.HasSuffix(path, ".so") {
  459. fmt.Printf("Found library %s\n", path)
  460. return start, path, nil
  461. }
  462. }
  463. }
  464. }
  465. return 1, "", fmt.Errorf("library %s not found in process.", libPath)
  466. }
  467. func (j *JvmInjector) getFunctionOffset(libPath, functionName string) (elf.Symbol, error) {
  468. elfFile, err := elf.Open(libPath)
  469. if err != nil {
  470. return elf.Symbol{}, fmt.Errorf("failed to open ELF file: %v", err)
  471. }
  472. defer elfFile.Close()
  473. symbols, err := elfFile.DynamicSymbols()
  474. if err != nil {
  475. return elf.Symbol{}, fmt.Errorf("failed to read dynamic symbols: %v", err)
  476. }
  477. for _, sym := range symbols {
  478. if sym.Name == functionName {
  479. fmt.Println("size:", sym.Size)
  480. return sym, nil
  481. }
  482. }
  483. //textSection := elfFile.Section(".text")
  484. //if textSection == nil {
  485. // fmt.Println("textSection is null")
  486. // //return nil
  487. //}
  488. //textSectionData, err := textSection.Data()
  489. //if err != nil {
  490. // fmt.Println("textSectionData error is", err)
  491. // //return nil
  492. //}
  493. //textSectionLen := uint64(len(textSectionData) - 1)
  494. return elf.Symbol{}, fmt.Errorf("function %s not found", functionName)
  495. }
  496. //var PID string
  497. func (j *JvmInjector) findReleaseFuncContextFromLibPath() error {
  498. // 获取release库的基地址
  499. baseAddress, libPath, err := j.findLibBaseFromProcMaps(j.ReleaseLibNetInfo.LibName)
  500. functionName := j.ReleaseLibNetInfo.FuncSymbol.SymName
  501. j.ReleaseLibNetInfo.LibPath = libPath
  502. libName := j.ReleaseLibNetInfo.LibName
  503. if err != nil {
  504. return fmt.Errorf("Error finding base addresses: %v", err)
  505. }
  506. klog.Infof("[inject] Base address of %s: %x", libName, baseAddress)
  507. // 获取函数的偏移量
  508. functionSym, err := j.getFunctionOffset(libPath, functionName)
  509. // 计算函数的实际内存地址
  510. j.ReleaseLibNetInfo.FuncSymbol.SymAddr = baseAddress + functionSym.Value
  511. j.ReleaseLibNetInfo.FuncSymbol.SymSize = functionSym.Size
  512. if err != nil {
  513. klog.WithError(err).Errorf("Error getting function offset")
  514. return err
  515. }
  516. klog.Infof("[inject] Actual memory address of %s at base 0x%x: 0x%x", functionName, baseAddress, j.ReleaseLibNetInfo.FuncSymbol.SymAddr)
  517. err = j.findReleaseAddressInfoFromMem()
  518. if err != nil {
  519. return err
  520. } else {
  521. j.PreCheck.NeedInjectionCheck = true
  522. }
  523. return nil
  524. }
  525. func (j *JvmInjector) findDebugFuncContextFromLibPath() error {
  526. //libName := j.DebugLibNetInfo.LibPath
  527. // 获取release库的基地址
  528. baseAddress, libPath, err := j.findLibBaseByPathFromProcMaps(j.DebugLibNetInfo.ProcLoadPath)
  529. klog.Infof("[inject] debug base address of %s : %x", libPath, baseAddress)
  530. functionName := j.DebugLibNetInfo.FuncSymbol.SymName
  531. //j.DebugLibNetInfo.LibPath = libPath
  532. if err != nil {
  533. return err
  534. }
  535. // 获取函数的偏移量
  536. functionSym, err := j.getFunctionOffset(j.DebugLibNetInfo.LibPath, functionName)
  537. // 计算函数的实际内存地址
  538. j.DebugLibNetInfo.FuncSymbol.SymAddr = baseAddress + functionSym.Value
  539. j.DebugLibNetInfo.FuncSymbol.SymSize = functionSym.Size
  540. if err != nil {
  541. return fmt.Errorf("Error getting function offset: %v", err)
  542. }
  543. _, err = j.findDebugAddressInfoFromMem()
  544. if err != nil {
  545. return fmt.Errorf("Error finding first CALL instuction: %v", err)
  546. }
  547. fmt.Printf("First CALL instuction o1f %s at base 0x%x\n", functionName, baseAddress)
  548. return nil
  549. }
  550. func printCodeData(data LibNetInfo) {
  551. fmt.Printf("========FuncEnter <0x%x> \n", data.FuncSymbol.SymAddr)
  552. fmt.Printf("Name %s | CurrentAddr:<0x%x>\nOrigin-TargetAddr:<0x%x> | TargetAddr:<0x%x> \nOrigin-Inst:<%s> | Inst:<%s> \n",
  553. data.InnerSymbol.IO_fd_fdID.SymName,
  554. data.InnerSymbol.IO_fd_fdID.SymAddr,
  555. data.InnerSymbol.IO_fd_fdID.OriginTargetAddr,
  556. data.InnerSymbol.IO_fd_fdID.TargetAddr,
  557. x86asm.IntelSyntax(data.InnerSymbol.IO_fd_fdID.OriginInst, 0, nil),
  558. x86asm.IntelSyntax(data.InnerSymbol.IO_fd_fdID.Inst, 0, nil))
  559. fmt.Printf("\nName %s | CurrentAddr:<0x%x>\nOrigin-TargetAddr:<0x%x> | TargetAddr:<0x%x>\nOrigin-Inst:<%s> | Inst:<%s> \n",
  560. data.InnerSymbol.NET_Send.SymName,
  561. data.InnerSymbol.NET_Send.SymAddr,
  562. data.InnerSymbol.NET_Send.OriginTargetAddr,
  563. data.InnerSymbol.NET_Send.TargetAddr,
  564. x86asm.IntelSyntax(data.InnerSymbol.NET_Send.OriginInst, 0, nil),
  565. x86asm.IntelSyntax(data.InnerSymbol.NET_Send.Inst, 0, nil))
  566. fmt.Println("========")
  567. }
  568. func (j *JvmInjector) jvmInjectLib() int {
  569. dll := C.CString(j.DebugLibNetInfo.ProcLoadPath)
  570. rootfs := C.CString(j.Rootfs)
  571. defer C.free(unsafe.Pointer(dll))
  572. result := C.cw_inject_library(C.int(j.Pid), C.int(1), dll, rootfs)
  573. fmt.Printf("Result: %d\n", result)
  574. return int(result)
  575. }
  576. func (j *JvmInjector) validateAllPreCheck() bool {
  577. return j.PreCheck.NeedInjectionCheck && j.PreCheck.LoadingCheck && j.PreCheck.IoFdCheck && j.PreCheck.NetSendFuncCheck
  578. }
  579. func (j *JvmInjector) validateAllModifyCheck() bool {
  580. return j.AfterCheck.IoFdCheck && j.AfterCheck.NetSendFuncCheck
  581. }
  582. /*修改部分*/
  583. func readData(pid int, addr uintptr) (uint64, error) {
  584. var data uint64
  585. if _, err := syscall.PtracePeekData(pid, addr, (*[8]byte)(unsafe.Pointer(&data))[:]); err != nil {
  586. return 0, fmt.Errorf("ptrace PEEKDATA: %v", err)
  587. }
  588. return data, nil
  589. }
  590. func writeData(pid int, addr uintptr, data uint64) error {
  591. if _, err := syscall.PtracePokeData(pid, addr, (*[8]byte)(unsafe.Pointer(&data))[:]); err != nil {
  592. return fmt.Errorf("ptrace POKEDATA: %v", err)
  593. }
  594. return nil
  595. }
  596. func modifyIoFdTargetAddr(pid int, insertAddr, distAddr uintptr) error {
  597. newOffset := distAddr - (insertAddr + 7)
  598. targetAddr := insertAddr + 3
  599. // 获取目标地址处的数据
  600. originalData, err := readData(pid, targetAddr)
  601. if err != nil {
  602. return err
  603. }
  604. // 更新数据中的目标偏移
  605. updatedData := (originalData & 0xFFFFFFFF00000000) | uint64(newOffset&0xFFFFFFFF)
  606. err = writeData(pid, targetAddr, updatedData)
  607. if err != nil {
  608. return err
  609. }
  610. return nil
  611. }
  612. func modifyNetSetTargetAddr(pid int, sendDebugAddr, sendReleaseAddr uintptr) error {
  613. sendOffset := sendReleaseAddr - sendDebugAddr - 5
  614. // 读取原始数据
  615. alignedAddr := sendDebugAddr & ^(uintptr(unsafe.Sizeof(uintptr(0))) - 1)
  616. originalData, err := readData(pid, alignedAddr)
  617. if err != nil {
  618. return err
  619. }
  620. bytes := (*[8]byte)(unsafe.Pointer(&originalData))
  621. offsetLocation := (sendDebugAddr % uintptr(unsafe.Sizeof(uintptr(0)))) + 1
  622. *(*uint32)(unsafe.Pointer(&bytes[offsetLocation])) = uint32(sendOffset)
  623. err = writeData(pid, alignedAddr, originalData)
  624. if err != nil {
  625. return err
  626. }
  627. return nil
  628. }
  629. func modifyReleaseFuncEnter(pid int, originEnterAddr, debugEnterAddr uintptr) error {
  630. offset := debugEnterAddr - (originEnterAddr + 5)
  631. // 读取原始数据
  632. alignedAddr := originEnterAddr & ^(uintptr(unsafe.Sizeof(uintptr(0))) - 1)
  633. originalData, err := readData(pid, alignedAddr)
  634. if err != nil {
  635. return err
  636. }
  637. bytes := (*[8]byte)(unsafe.Pointer(&originalData))
  638. bytes[originEnterAddr%uintptr(unsafe.Sizeof(uintptr(0)))] = 0xe9
  639. *(*uint32)(unsafe.Pointer(&bytes[(originEnterAddr%uintptr(unsafe.Sizeof(uintptr(0))))+1])) = uint32(offset)
  640. err = writeData(pid, alignedAddr, originalData)
  641. if err != nil {
  642. return err
  643. }
  644. return nil
  645. }
  646. func restoreOriginalInstructions(pid int, addr uintptr, instructions []byte) error {
  647. alignedAddr := addr & ^(uintptr(unsafe.Sizeof(uintptr(0))) - 1)
  648. originalData, err := readData(pid, alignedAddr)
  649. if err != nil {
  650. return err
  651. }
  652. bytes := (*[8]byte)(unsafe.Pointer(&originalData))
  653. for i := 0; i < len(instructions); i++ {
  654. bytes[addr%uintptr(unsafe.Sizeof(uintptr(0)))+uintptr(i)] = instructions[i]
  655. }
  656. err = writeData(pid, alignedAddr, originalData)
  657. if err != nil {
  658. return err
  659. }
  660. return nil
  661. }
  662. //func main() {
  663. // flag.StringVar(&PID, "p", "", "PID")
  664. // flag.Parse()
  665. // pidStr := PID // 替换为目标进程的 PID
  666. // pid, err := strconv.Atoi(pidStr)
  667. // if err != nil {
  668. // log.Fatalf("Invalid PID: %v", err)
  669. // }
  670. // functionName := "Java_java_net_SocketOutputStream_socketWrite0"
  671. // libraryName := "libnet.so"
  672. //
  673. // cwLibraryName := "cwlibnet.so"
  674. // cwLibraryPath := "/root/cwlibnet.so"
  675. //
  676. // jvmInjector := &JvmInjector{
  677. // pid: pid,
  678. // ReleaseLibNetInfo: LibNetInfo{
  679. // libName: libraryName,
  680. // FuncSymbol: instInfo{
  681. // SymName: functionName,
  682. // },
  683. // },
  684. // DebugLibNetInfo: LibNetInfo{
  685. // // TODO 根据版本设置
  686. // libName: cwLibraryName,
  687. // // TODO 根据版本设置
  688. // libPath: cwLibraryPath,
  689. // FuncSymbol: instInfo{
  690. // SymName: functionName,
  691. // },
  692. // },
  693. // }
  694. //
  695. // err = jvmInject(jvmInjector)
  696. // fmt.Println(err)
  697. //}
  698. func JvmInject(jvmInjector *JvmInjector) error {
  699. pid := jvmInjector.Pid
  700. var err error
  701. err = jvmInjector.findReleaseFuncContextFromLibPath()
  702. // Debug版本无需修改寄存器
  703. // 已经加载so并指令修改正确的
  704. if jvmInjector.PreCheck.EbpfCanInjection {
  705. klog.Infoln("[inject] eBPF can injection.")
  706. return nil
  707. }
  708. if err != nil {
  709. klog.WithError(err).Errorf("[inject] Error message during release phase.")
  710. return err
  711. }
  712. // 原指令校验通过
  713. if !jvmInjector.PreCheck.NeedInjectionCheck {
  714. return err
  715. }
  716. printCodeData(jvmInjector.ReleaseLibNetInfo)
  717. _type, _, err := jvmInjector.findLibBaseByPathFromProcMaps(jvmInjector.DebugLibNetInfo.LibPath)
  718. if err != nil {
  719. // load so
  720. if _type == 1 {
  721. klog.Infoln("[inject] start load so.")
  722. resCode := jvmInjector.jvmInjectLib()
  723. if resCode == 0 {
  724. klog.Infof("[inject] load so successful. proc load path is [%s], file path in node is [%s]", jvmInjector.DebugLibNetInfo.ProcLoadPath, jvmInjector.DebugLibNetInfo.LibPath)
  725. jvmInjector.PreCheck.LoadingCheck = true
  726. } else {
  727. klog.Errorf("[inject] Failed load so. so path is [%s]", jvmInjector.DebugLibNetInfo.LibPath)
  728. return fmt.Errorf("[inject] Failed load so. code is %d so path is [%s]", resCode, jvmInjector.DebugLibNetInfo.LibPath)
  729. }
  730. }
  731. } else {
  732. jvmInjector.PreCheck.LoadingCheck = true
  733. }
  734. if !jvmInjector.PreCheck.LoadingCheck {
  735. fmt.Println("Failed load so")
  736. return err
  737. }
  738. err = jvmInjector.findDebugFuncContextFromLibPath()
  739. fmt.Println("find debug Context", err)
  740. if err != nil {
  741. return err
  742. }
  743. if !jvmInjector.validateAllPreCheck() {
  744. fmt.Println("failed validateAllPreCheck ", jvmInjector.PreCheck)
  745. return err
  746. }
  747. // 修改
  748. debugFuncEnterAddr := uintptr(jvmInjector.DebugLibNetInfo.FuncSymbol.SymAddr)
  749. debugIoFdAddr := uintptr(jvmInjector.DebugLibNetInfo.InnerSymbol.IO_fd_fdID.SymAddr)
  750. debugNetSendAddr := uintptr(jvmInjector.DebugLibNetInfo.InnerSymbol.NET_Send.SymAddr)
  751. originFuncEnterAddr := uintptr(jvmInjector.ReleaseLibNetInfo.FuncSymbol.SymAddr)
  752. ioFdReleaseTargetAddr := uintptr(jvmInjector.ReleaseLibNetInfo.InnerSymbol.IO_fd_fdID.TargetAddr)
  753. netSendReleaseTargetAddr := uintptr(jvmInjector.ReleaseLibNetInfo.InnerSymbol.NET_Send.TargetAddr)
  754. fmt.Printf("<0x%x> -> <0x%x>\n", originFuncEnterAddr, debugFuncEnterAddr)
  755. fmt.Printf("<0x%x> -> <0x%x>\n", debugIoFdAddr, ioFdReleaseTargetAddr)
  756. fmt.Printf("<0x%x> -> <0x%x>\n", debugNetSendAddr, netSendReleaseTargetAddr)
  757. // 附加到目标进程
  758. err = syscall.PtraceAttach(pid)
  759. if err != nil {
  760. fmt.Printf("ptrace ATTACH: %v", err)
  761. }
  762. // 等待目标进程停止
  763. if _, err := syscall.Wait4(pid, nil, 0, nil); err != nil {
  764. fmt.Printf("wait4: %v", err)
  765. return err
  766. }
  767. time.Now().UnixNano()
  768. // 修改目标的内存
  769. err = modifyIoFdTargetAddr(pid, debugIoFdAddr, ioFdReleaseTargetAddr)
  770. if err != nil {
  771. fmt.Println(err)
  772. return err
  773. }
  774. err = modifyNetSetTargetAddr(pid, debugNetSendAddr, netSendReleaseTargetAddr)
  775. fmt.Println(err)
  776. if err != nil {
  777. fmt.Println(err)
  778. return err
  779. }
  780. // 二次效验 读取并验证地址
  781. _, err = jvmInjector.checkDebugFuncSymAfterChange()
  782. printCodeData(jvmInjector.ReleaseLibNetInfo)
  783. printCodeData(jvmInjector.DebugLibNetInfo)
  784. // 效验目标函数内地址是否与预期一致
  785. if !jvmInjector.validateAllModifyCheck() && err == nil {
  786. return err
  787. }
  788. // 更新函数入口
  789. err = modifyReleaseFuncEnter(pid, originFuncEnterAddr, debugFuncEnterAddr)
  790. if err != nil {
  791. fmt.Println(err)
  792. return err
  793. }
  794. // 校验jmp地址修改正确
  795. err = jvmInjector.checkReleaseFuncSymAfterChange()
  796. if err != nil {
  797. fmt.Println(err)
  798. if len(jvmInjector.ReleaseLibNetInfo.FuncSymbol.OriginCode) == 5 {
  799. err = restoreOriginalInstructions(pid, originFuncEnterAddr, jvmInjector.ReleaseLibNetInfo.FuncSymbol.OriginCode)
  800. if err != nil {
  801. fmt.Println(err)
  802. return err
  803. }
  804. }
  805. }
  806. // 恢复执行
  807. if err = syscall.PtraceDetach(pid); err != nil {
  808. fmt.Printf("ptrace DETACH: %v", err)
  809. return err
  810. }
  811. return nil
  812. }