tls.go 14 KB

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