tls.go 17 KB

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