tls.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. package ebpftracer
  2. import (
  3. "bufio"
  4. "bytes"
  5. "debug/buildinfo"
  6. "debug/elf"
  7. "errors"
  8. "fmt"
  9. "github.com/coroot/coroot-node-agent/ebpftracer/tracer"
  10. "os"
  11. "regexp"
  12. "strconv"
  13. "strings"
  14. "github.com/cilium/ebpf/link"
  15. "github.com/coroot/coroot-node-agent/proc"
  16. "golang.org/x/arch/arm64/arm64asm"
  17. "golang.org/x/arch/x86/x86asm"
  18. "golang.org/x/mod/semver"
  19. "k8s.io/klog/v2"
  20. )
  21. const (
  22. minSupportedGoVersion = "v1.17.0"
  23. goTlsWriteSymbol = "crypto/tls.(*Conn).Write"
  24. goTlsReadSymbol = "crypto/tls.(*Conn).Read"
  25. goExecute = "runtime.execute"
  26. goNewproc1 = "runtime.newproc1"
  27. goServeHTTP = "net/http.serverHandler.ServeHTTP"
  28. goTransport = "net/http.(*Transport).roundTrip"
  29. )
  30. var (
  31. opensslVersionRe = regexp.MustCompile(`OpenSSL\s(\d\.\d+\.\d+)`)
  32. )
  33. func (t *Tracer) AttachOpenSslUprobes(pid uint32) []link.Link {
  34. if t.disableL7Tracing {
  35. return nil
  36. }
  37. libPath, version := getSslLibPathAndVersion(pid)
  38. if libPath == "" || version == "" {
  39. return nil
  40. }
  41. log := func(msg string, err error) {
  42. if err != nil {
  43. for _, s := range []string{"no such file or directory", "no such process", "permission denied"} {
  44. if strings.HasSuffix(err.Error(), s) {
  45. return
  46. }
  47. }
  48. klog.ErrorfDepth(1, "pid=%d libssl_version=%s: %s: %s", pid, version, msg, err)
  49. return
  50. }
  51. klog.InfofDepth(1, "pid=%d libssl_version=%s: %s", pid, version, msg)
  52. }
  53. exe, err := link.OpenExecutable(libPath)
  54. if err != nil {
  55. log("failed to open executable", err)
  56. return nil
  57. }
  58. var links []link.Link
  59. writeEnter := "openssl_SSL_write_enter"
  60. readEnter := "openssl_SSL_read_enter"
  61. readExEnter := "openssl_SSL_read_ex_enter"
  62. readExit := "openssl_SSL_read_exit"
  63. switch {
  64. case semver.Compare(version, "v3.0.0") >= 0:
  65. writeEnter = "openssl_SSL_write_enter_v3_0"
  66. readEnter = "openssl_SSL_read_enter_v3_0"
  67. readExEnter = "openssl_SSL_read_ex_enter_v3_0"
  68. case semver.Compare(version, "v1.1.1") >= 0:
  69. writeEnter = "openssl_SSL_write_enter_v1_1_1"
  70. readEnter = "openssl_SSL_read_enter_v1_1_1"
  71. readExEnter = "openssl_SSL_read_ex_enter_v1_1_1"
  72. }
  73. type prog struct {
  74. symbol string
  75. uprobe string
  76. uretprobe string
  77. }
  78. progs := []prog{
  79. {symbol: "SSL_write", uprobe: writeEnter},
  80. {symbol: "SSL_write_ex", uprobe: writeEnter},
  81. {symbol: "SSL_read", uprobe: readEnter},
  82. {symbol: "SSL_read_ex", uprobe: readExEnter},
  83. {symbol: "SSL_read", uretprobe: readExit},
  84. {symbol: "SSL_read_ex", uretprobe: readExit},
  85. }
  86. for _, p := range progs {
  87. if p.uprobe != "" {
  88. l, err := exe.Uprobe(p.symbol, t.uprobes[p.uprobe], nil)
  89. if err != nil {
  90. log("failed to attach uprobe", err)
  91. return nil
  92. }
  93. links = append(links, l)
  94. }
  95. if p.uretprobe != "" {
  96. l, err := exe.Uretprobe(p.symbol, t.uprobes[p.uretprobe], nil)
  97. if err != nil {
  98. log("failed to attach uretprobe", err)
  99. return nil
  100. }
  101. links = append(links, l)
  102. }
  103. }
  104. log("libssl uprobes attached", nil)
  105. return links
  106. }
  107. // TODO: 核心方法
  108. func (t *Tracer) AttachGoTlsUprobes(pid uint32) []link.Link { // TODO: 核心方法
  109. fmt.Println("AttachGoTlsUprobes------------pid: ", pid)
  110. // TODO: 区分语言
  111. // return t.AttachTlsUprobes4GO(pid)
  112. return t.AttachTlsUprobes4Java(pid)
  113. }
  114. func (t *Tracer) AttachTlsUprobes4Java(pid uint32) []link.Link {
  115. fmt.Println("AttachTlsUprobes4Java-------pid: ", pid)
  116. //if pid != 13096 {
  117. // return nil
  118. //}
  119. path := proc.Path(pid, "exe")
  120. fmt.Println("path: ", path)
  121. exe, err := link.OpenExecutable(path)
  122. if err != nil {
  123. fmt.Println("OpenExecutable error: ", err)
  124. return nil
  125. }
  126. var links []link.Link
  127. // 733f8cc7aaa0 fd0 Lsun/net/www/protocol/http/HttpURLConnection;::setRequestProperty
  128. // 参考: l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_Transport_roundTrip"], &link.UprobeOptions{Address: address})
  129. //spec := &ebpf.ProgramSpec{
  130. // Name: "uprobe_HttpURLConnection_setRequestProperty",
  131. // Type: ebpf.Kprobe,
  132. // //// AttachTo: "uprobe_HttpURLConnection_setRequestProperty",
  133. // //Instructions: asm.Instructions{
  134. // // asm.Instruction{OpCode: Opcode. },
  135. // //},
  136. // // Type: ebpf.TracePoint,
  137. // License: "GPL",
  138. //}
  139. //println("&ebpf.ProgramSpec: ", spec)
  140. //prog, err := ebpf.NewProgram(spec) // func NewProgram(spec *ProgramSpec) (*Program, error) {
  141. //if err != nil {
  142. // fmt.Println("NewProgram: ", err)
  143. // return nil
  144. //}
  145. prog := t.uprobes["uprobe_HttpURLConnection_setRequestProperty"]
  146. fmt.Println("t.uprobes[\"uprobe_HttpURLConnection_setRequestProperty\"]=", prog)
  147. // 733f8cc7aaa0 fd0 Lsun/net/www/protocol/http/HttpURLConnection;::setRequestProperty
  148. // 报错: creating perf_uprobe PMU: token /proc/13096/exe:0x733f8cc7aaa0: opening perf event: invalid argument
  149. // &link.UprobeOptions{Address: 0x733f8cc7aaa0, Offset: 0xfd0, PID: 13096}
  150. // 733f8cc7aaa0(16进制) -> 126716782029472(10进制),很进制无关系, 报一样的错误....
  151. // fd0(十六进制) -> 4048(十进制)
  152. // 126716782033520 -> 733f8cc7ba70(十六进制)
  153. // 7ab420b42ee0 978 Lorg/springframework/boot/loader/jar/JarURLConnection;::getInputStream
  154. //7ab421408920 fb0 Lsun/net/www/protocol/http/HttpURLConnection;::setRequestProperty
  155. // 4016 134914070583504 7ab4214098d0
  156. link, err := exe.Uprobe("Lsun/net/www/protocol/http/HttpURLConnection;::setRequestProperty", prog, &link.UprobeOptions{Address: 0x7ab4214098d0})
  157. if err != nil {
  158. fmt.Println("exe.Uprobe error: ", err) // 报错: TODO: exe.Uprobe error: prog cannot be nil: invalid input
  159. return nil
  160. }
  161. links = append(links, link)
  162. return links
  163. }
  164. func (t *Tracer) AttachTlsUprobes4GO(pid uint32) []link.Link {
  165. fmt.Println("AttachTlsUprobes4GO------------pid: ", pid)
  166. if t.disableL7Tracing {
  167. return nil
  168. }
  169. path := proc.Path(pid, "exe")
  170. var err error
  171. var name, version string
  172. log := func(msg string, err error) {
  173. if err != nil {
  174. for _, s := range []string{"not a Go executable", "no such file or directory", "no such process", "permission denied"} {
  175. if strings.HasSuffix(err.Error(), s) {
  176. return
  177. }
  178. }
  179. klog.ErrorfDepth(1, "pid=%d golang_app=%s golang_version=%s: %s: %s", pid, name, version, msg, err)
  180. return
  181. }
  182. klog.InfofDepth(1, "pid=%d golang_app=%s golang_version=%s: %s", pid, name, version, msg)
  183. }
  184. bi, err := buildinfo.ReadFile(path)
  185. if err != nil {
  186. log("failed to read build info", err)
  187. return nil
  188. }
  189. name, err = os.Readlink(path)
  190. if err != nil {
  191. log("failed to read name", err)
  192. return nil
  193. }
  194. version = strings.Replace(bi.GoVersion, "go", "v", 1)
  195. if semver.Compare(version, minSupportedGoVersion) < 0 {
  196. log(fmt.Sprintf("go_versions below %s are not supported", minSupportedGoVersion), nil)
  197. return nil
  198. }
  199. ef, err := elf.Open(path) // TODO: 核心逻辑
  200. if err != nil {
  201. log("failed to open as elf binary", err)
  202. return nil
  203. }
  204. defer ef.Close()
  205. // TODO: 判断是java进程还是go进程...
  206. // var lan := "x"
  207. symbols, err := ef.Symbols()
  208. // fmt.Println("--------------AttachGoTlsUprobes---------------symbols------", symbols)
  209. if err != nil {
  210. if errors.Is(err, elf.ErrNoSymbols) {
  211. log("no symbol section", nil)
  212. return nil
  213. }
  214. log("failed to read symbols", err)
  215. return nil
  216. }
  217. textSection := ef.Section(".text")
  218. if textSection == nil {
  219. log("no text section", nil)
  220. return nil
  221. }
  222. textSectionData, err := textSection.Data()
  223. if err != nil {
  224. log("failed to read text section", err)
  225. return nil
  226. }
  227. textSectionLen := uint64(len(textSectionData) - 1)
  228. exe, err := link.OpenExecutable(path)
  229. if err != nil {
  230. log("failed to open executable", err)
  231. return nil
  232. }
  233. offset, ok := tracer.GetOffset(tracer.NewID("std", "runtime", "g", "goid"), path)
  234. fmt.Println(offset, ok, version)
  235. if ok {
  236. realVersion := strings.Replace(bi.GoVersion, "go", "", 1)
  237. parts := strings.Split(realVersion, ".")
  238. var major, minor, revision int
  239. if len(parts) >= 3 {
  240. major, err = strconv.Atoi(parts[0])
  241. if err != nil {
  242. log("Error converting major version:", err)
  243. }
  244. minor, err = strconv.Atoi(parts[1])
  245. if err != nil {
  246. log("Error converting minor version:", err)
  247. }
  248. revision, err = strconv.Atoi(parts[2])
  249. if err != nil {
  250. log("Error converting revision version:", err)
  251. }
  252. goVersion := ((major & 0xFF) << 16) + ((minor & 0xFF) << 8) + min(revision, 255)
  253. klog.Infoln("Major:", major)
  254. klog.Infoln("Minor:", minor)
  255. klog.Infoln("Revision:", revision)
  256. klog.Infoln("goVersion", goVersion)
  257. info := tracer.EbpfProcInfo{}
  258. info.Version = uint32(goVersion)
  259. info.Offsets[tracer.OFFSET_IDX_GOID_RUNTIME_G] = uint16(offset)
  260. info.NetTCPConnItab = uint64(0)
  261. info.CryptoTLSConnItab = uint64(0)
  262. info.CredentialsSyscallConnItab = uint64(0)
  263. _, err = tracer.UpdateProcInfoToMap(t.collection, pid, info)
  264. if err != nil {
  265. klog.Error("failed to update program info", err)
  266. }
  267. }
  268. }
  269. var links []link.Link
  270. for _, s := range symbols { // TODO: 遍历的方式找Func的Offset?
  271. if elf.ST_TYPE(s.Info) != elf.STT_FUNC || s.Size == 0 {
  272. continue
  273. }
  274. switch s.Name {
  275. //case goTlsWriteSymbol, goTlsReadSymbol:
  276. case goExecute, goNewproc1, goServeHTTP, goTransport:
  277. default:
  278. continue
  279. }
  280. address := s.Value
  281. for _, p := range ef.Progs {
  282. if p.Type != elf.PT_LOAD || (p.Flags&elf.PF_X) == 0 {
  283. continue
  284. }
  285. if p.Vaddr <= s.Value && s.Value < (p.Vaddr+p.Memsz) {
  286. address = s.Value - p.Vaddr + p.Off
  287. break
  288. }
  289. }
  290. fmt.Println("s.Name-----:", s.Name) // TODO: s.Name-----: runtime.execute | net/http.serverHandler.ServeHTTP
  291. fmt.Println("s.Value-----:", s.Value)
  292. switch s.Name {
  293. case goExecute:
  294. l, err := exe.Uprobe(s.Name, t.uprobes["runtime_execute"], &link.UprobeOptions{Address: address})
  295. if err != nil {
  296. log("failed to attach write_enter uprobe", err)
  297. klog.Infoln("runtime.execute no")
  298. return nil
  299. } else {
  300. klog.Infoln("runtime.execute ok")
  301. }
  302. links = append(links, l)
  303. case goNewproc1:
  304. l, err := exe.Uprobe(s.Name, t.uprobes["enter_runtime_newproc1"], &link.UprobeOptions{Address: address})
  305. if err != nil {
  306. log("failed to attach newproc1 uprobe", err)
  307. return nil
  308. }
  309. links = append(links, l)
  310. sStart := s.Value - textSection.Addr
  311. sEnd := sStart + s.Size
  312. if sEnd > textSectionLen {
  313. continue
  314. }
  315. sBytes := textSectionData[sStart:sEnd]
  316. returnOffsets := getReturnOffsets(ef.Machine, sBytes)
  317. if len(returnOffsets) == 0 {
  318. log("failed to attach enter_runtime_newproc1 uprobe", fmt.Errorf("no return offsets found"))
  319. return nil
  320. }
  321. for _, offset := range returnOffsets {
  322. l, err := exe.Uprobe(s.Name, t.uprobes["exit_runtime_newproc1"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  323. if err != nil {
  324. log("failed to attach exit_runtime_newproc1 uprobe", err)
  325. return nil
  326. }
  327. links = append(links, l)
  328. }
  329. case goServeHTTP:
  330. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_HandlerFunc_ServeHTTP"], &link.UprobeOptions{Address: address})
  331. if err != nil {
  332. log("failed to attach write_enter uprobe", err)
  333. fmt.Println("net/http.serverHandler.ServeHTTP no")
  334. fmt.Println(err)
  335. continue
  336. } else {
  337. fmt.Println("net/http.serverHandler.ServeHTTP ok")
  338. }
  339. links = append(links, l)
  340. sStart := s.Value - textSection.Addr
  341. sEnd := sStart + s.Size
  342. if sEnd > textSectionLen {
  343. continue
  344. }
  345. sBytes := textSectionData[sStart:sEnd]
  346. returnOffsets := getReturnOffsets(ef.Machine, sBytes)
  347. if len(returnOffsets) == 0 {
  348. log("failed to attach uprobe_HandlerFunc_ServeHTTP uprobe", fmt.Errorf("no return offsets found"))
  349. return nil
  350. }
  351. for _, offset := range returnOffsets {
  352. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_HandlerFunc_ServeHTTP_Returns"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  353. if err != nil {
  354. log("failed to attach exit_runtime_newproc1 uprobe", err)
  355. return nil
  356. }
  357. links = append(links, l)
  358. }
  359. case goTransport:
  360. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_Transport_roundTrip"], &link.UprobeOptions{Address: address})
  361. if err != nil {
  362. log("failed to attach write_enter uprobe", err)
  363. fmt.Println("net/http.uprobe_Transport_roundTrip no")
  364. fmt.Println(err)
  365. continue
  366. } else {
  367. fmt.Println("net/http.uprobe_Transport_roundTrip ok")
  368. }
  369. links = append(links, l)
  370. sStart := s.Value - textSection.Addr
  371. sEnd := sStart + s.Size
  372. if sEnd > textSectionLen {
  373. continue
  374. }
  375. sBytes := textSectionData[sStart:sEnd]
  376. returnOffsets := getReturnOffsets(ef.Machine, sBytes)
  377. if len(returnOffsets) == 0 {
  378. log("failed to attach uprobe_Transport_roundTrip uprobe", fmt.Errorf("no return offsets found"))
  379. return nil
  380. }
  381. for _, offset := range returnOffsets {
  382. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_Transport_roundTrip_Returns"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  383. if err != nil {
  384. log("failed to attach exit_runtime_newproc1 uprobe", err)
  385. return nil
  386. }
  387. links = append(links, l)
  388. }
  389. case goTlsWriteSymbol:
  390. l, err := exe.Uprobe(s.Name, t.uprobes["go_crypto_tls_write_enter"], &link.UprobeOptions{Address: address})
  391. if err != nil {
  392. log("failed to attach write_enter uprobe", err)
  393. return nil
  394. }
  395. links = append(links, l)
  396. case goTlsReadSymbol:
  397. l, err := exe.Uprobe(s.Name, t.uprobes["go_crypto_tls_read_enter"], &link.UprobeOptions{Address: address})
  398. if err != nil {
  399. log("failed to attach read_enter uprobe", err)
  400. return nil
  401. }
  402. links = append(links, l)
  403. sStart := s.Value - textSection.Addr
  404. sEnd := sStart + s.Size
  405. if sEnd > textSectionLen {
  406. continue
  407. }
  408. sBytes := textSectionData[sStart:sEnd]
  409. returnOffsets := getReturnOffsets(ef.Machine, sBytes)
  410. if len(returnOffsets) == 0 {
  411. log("failed to attach read_exit uprobe", fmt.Errorf("no return offsets found"))
  412. return nil
  413. }
  414. for _, offset := range returnOffsets {
  415. l, err := exe.Uprobe(s.Name, t.uprobes["go_crypto_tls_read_exit"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  416. if err != nil {
  417. log("failed to attach read_exit uprobe", err)
  418. return nil
  419. }
  420. links = append(links, l)
  421. }
  422. }
  423. }
  424. if len(links) == 0 {
  425. return nil
  426. }
  427. log("crypto/tls uprobes attached", nil)
  428. return links
  429. }
  430. func getSslLibPathAndVersion(pid uint32) (string, string) {
  431. f, err := os.Open(proc.Path(pid, "maps"))
  432. if err != nil {
  433. return "", ""
  434. }
  435. defer f.Close()
  436. scanner := bufio.NewScanner(f)
  437. scanner.Split(bufio.ScanLines)
  438. var libsslPath, libcryptoPath string
  439. for scanner.Scan() {
  440. parts := strings.Fields(scanner.Text())
  441. if len(parts) <= 5 {
  442. continue
  443. }
  444. libPath := parts[5]
  445. switch {
  446. case libsslPath == "" && strings.Contains(libPath, "libssl.so"):
  447. fullPath := proc.Path(pid, "root", libPath)
  448. if _, err = os.Stat(fullPath); err == nil {
  449. libsslPath = fullPath
  450. }
  451. case libcryptoPath == "" && strings.Contains(libPath, "libcrypto.so"):
  452. fullPath := proc.Path(pid, "root", libPath)
  453. if _, err = os.Stat(fullPath); err == nil {
  454. libcryptoPath = fullPath
  455. }
  456. default:
  457. continue
  458. }
  459. if libsslPath != "" && libcryptoPath != "" {
  460. break
  461. }
  462. }
  463. if libsslPath == "" || libcryptoPath == "" {
  464. return "", ""
  465. }
  466. ef, err := elf.Open(libcryptoPath)
  467. if err != nil {
  468. return "", ""
  469. }
  470. defer ef.Close()
  471. rodataSection := ef.Section(".rodata")
  472. if rodataSection == nil {
  473. return "", ""
  474. }
  475. rodataSectionData, err := rodataSection.Data()
  476. if err != nil {
  477. return "", ""
  478. }
  479. var version string
  480. for _, b := range bytes.Split(rodataSectionData, []byte("\x00")) {
  481. if len(b) == 0 {
  482. continue
  483. }
  484. s := string(b)
  485. if !strings.HasPrefix(s, "OpenSSL") {
  486. continue
  487. }
  488. if m := opensslVersionRe.FindStringSubmatch(s); len(m) > 1 {
  489. version = m[1]
  490. }
  491. }
  492. return libsslPath, "v" + version
  493. }
  494. func getReturnOffsets(machine elf.Machine, instructions []byte) []int {
  495. var res []int
  496. switch machine {
  497. case elf.EM_X86_64:
  498. for i := 0; i < len(instructions); {
  499. ins, err := x86asm.Decode(instructions[i:], 64)
  500. if err == nil && ins.Op == x86asm.RET {
  501. res = append(res, i)
  502. }
  503. i += ins.Len
  504. }
  505. case elf.EM_AARCH64:
  506. for i := 0; i < len(instructions); {
  507. ins, err := arm64asm.Decode(instructions[i:])
  508. if err == nil && ins.Op == arm64asm.RET {
  509. res = append(res, i)
  510. }
  511. i += 4
  512. }
  513. }
  514. return res
  515. }
  516. func min(a, b int) int {
  517. if a < b {
  518. return a
  519. }
  520. return b
  521. }