tls.go 14 KB

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