tls.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  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. goHeaderWriteSubset = "net/http.Header.writeSubset"
  32. goGrpcServerHandleStream = "google.golang.org/grpc.(*Server).handleStream"
  33. goGrpcHttp2OperateHeader = "google.golang.org/grpc/internal/transport.(*http2Server).operateHeaders"
  34. goGrpcServerWritestatus = "google.golang.org/grpc/internal/transport.(*http2Server).WriteStatus"
  35. goGrpcClientConnInvoke = "google.golang.org/grpc.(*ClientConn).Invoke"
  36. goGrpcClientLoopyHeaderHandler = "google.golang.org/grpc/internal/transport.(*loopyWriter).headerHandler"
  37. goGrpcHttp2ClientNewStream = "google.golang.org/grpc/internal/transport.(*http2Client).NewStream"
  38. goReadContinuedLineSlice = "net/textproto.(*Reader).readContinuedLineSlice"
  39. )
  40. var (
  41. opensslVersionRe = regexp.MustCompile(`OpenSSL\s(\d\.\d+\.\d+)`)
  42. )
  43. func (t *Tracer) AttachOpenSslUprobes(pid uint32) ([]link.Link, error) {
  44. if t.DisableL7Tracing() {
  45. return nil, nil
  46. }
  47. libPath, version := getSslLibPathAndVersion(pid)
  48. if libPath == "" || version == "" {
  49. return nil, nil
  50. }
  51. log := func(msg string, err error) {
  52. if err != nil {
  53. for _, s := range []string{"no such file or directory", "no such process", "permission denied"} {
  54. if strings.HasSuffix(err.Error(), s) {
  55. return
  56. }
  57. }
  58. klog.Errorf("pid=%d libssl_version=%s: %s: %s", pid, version, msg, err)
  59. return
  60. }
  61. klog.Infof("pid=%d libssl_version=%s: %s", pid, version, msg)
  62. }
  63. exe, err := link.OpenExecutable(libPath)
  64. if err != nil {
  65. log("failed to open executable", err)
  66. return nil, err
  67. }
  68. var links []link.Link
  69. writeEnter := "openssl_SSL_write_enter"
  70. readEnter := "openssl_SSL_read_enter"
  71. readExEnter := "openssl_SSL_read_ex_enter"
  72. readExit := "openssl_SSL_read_exit"
  73. switch {
  74. case semver.Compare(version, "v3.0.0") >= 0:
  75. writeEnter = "openssl_SSL_write_enter_v3_0"
  76. readEnter = "openssl_SSL_read_enter_v3_0"
  77. readExEnter = "openssl_SSL_read_ex_enter_v3_0"
  78. case semver.Compare(version, "v1.1.1") >= 0:
  79. writeEnter = "openssl_SSL_write_enter_v1_1_1"
  80. readEnter = "openssl_SSL_read_enter_v1_1_1"
  81. readExEnter = "openssl_SSL_read_ex_enter_v1_1_1"
  82. }
  83. type prog struct {
  84. symbol string
  85. uprobe string
  86. uretprobe string
  87. }
  88. progs := []prog{
  89. {symbol: "SSL_write", uprobe: writeEnter},
  90. {symbol: "SSL_read", uprobe: readEnter},
  91. {symbol: "SSL_read", uretprobe: readExit},
  92. }
  93. if semver.Compare(version, "v1.1.1") >= 0 {
  94. progs = append(progs, []prog{
  95. {symbol: "SSL_write_ex", uprobe: writeEnter},
  96. {symbol: "SSL_read_ex", uprobe: readExEnter},
  97. {symbol: "SSL_read_ex", uretprobe: readExit},
  98. }...)
  99. }
  100. for _, p := range progs {
  101. if p.uprobe != "" {
  102. l, err := exe.Uprobe(p.symbol, t.uprobes[p.uprobe], nil)
  103. klog.Infoln("fucktls crypto/tls uprobes attached", p.symbol)
  104. if err != nil {
  105. //log("failed to attach uprobe", err)
  106. klog.Infoln("fucktls crypto/tls uprobes attached error", p.symbol)
  107. return nil, err
  108. }
  109. links = append(links, l)
  110. }
  111. if p.uretprobe != "" {
  112. klog.Infoln("fucktls crypto/tls uprobes attached ret", p.symbol)
  113. l, err := exe.Uretprobe(p.symbol, t.uprobes[p.uretprobe], nil)
  114. if err != nil {
  115. klog.Infoln("fucktls crypto/tls uprobes attached ret error", p.symbol)
  116. //log("failed to attach uretprobe", err)
  117. return nil, err
  118. }
  119. links = append(links, l)
  120. }
  121. }
  122. //log("libssl uprobes attached", nil)
  123. return links, nil
  124. }
  125. func (t *Tracer) AttachGoTlsUprobes(pid uint32, appInfo *AppInfo, codeType uint16) ([]link.Link, error) {
  126. if t.DisableL7Tracing() {
  127. return nil, nil
  128. }
  129. path := proc.Path(pid, "exe")
  130. instanceID := appInfo.InstanceIdHash.HashtVal
  131. appID := appInfo.AppIdHash.HashtVal
  132. var err error
  133. var name, version string
  134. log := func(msg string, err error) {
  135. if err != nil {
  136. for _, s := range []string{"not a Go executable", "no such file or directory", "no such process", "permission denied"} {
  137. if strings.HasSuffix(err.Error(), s) {
  138. return
  139. }
  140. }
  141. klog.Errorf("pid=%d golang_app=%s golang_version=%s: %s: %s", pid, name, version, msg, err)
  142. return
  143. }
  144. klog.Infof("pid=%d golang_app=%s golang_version=%s: %s", pid, name, version, msg)
  145. }
  146. bi, err := buildinfo.ReadFile(path)
  147. if err != nil {
  148. log("failed to read build info", err)
  149. return nil, err
  150. }
  151. // isGolangApp = true
  152. name, err = os.Readlink(path)
  153. if err != nil {
  154. log("failed to read name", err)
  155. return nil, err
  156. }
  157. version = strings.Replace(bi.GoVersion, "go", "v", 1)
  158. if semver.Compare(version, minSupportedGoVersion) < 0 {
  159. log(fmt.Sprintf("go_versions below %s are not supported", minSupportedGoVersion), nil)
  160. return nil, err
  161. }
  162. ef, err := elf.Open(path)
  163. if err != nil {
  164. log("failed to open as elf binary", err)
  165. return nil, err
  166. }
  167. defer ef.Close()
  168. symbols, err := ef.Symbols()
  169. if err != nil {
  170. if errors.Is(err, elf.ErrNoSymbols) {
  171. log("no symbol section", nil)
  172. return nil, err
  173. }
  174. log("failed to read symbols", err)
  175. return nil, err
  176. }
  177. textSection := ef.Section(".text")
  178. if textSection == nil {
  179. log("no text section", nil)
  180. return nil, err
  181. }
  182. textSectionData, err := textSection.Data()
  183. if err != nil {
  184. log("failed to read text section", err)
  185. return nil, err
  186. }
  187. textSectionLen := uint64(len(textSectionData) - 1)
  188. exe, err := link.OpenExecutable(path)
  189. if err != nil {
  190. log("failed to open executable", err)
  191. return nil, err
  192. }
  193. // 检测 gRPC 版本
  194. var grpcMajorVersion, grpcMinorVersion int
  195. for _, dep := range bi.Deps {
  196. if strings.Contains(dep.Path, "grpc") {
  197. klog.Infoln("Found gRPC dependency:", dep.Path, "version:", dep.Version)
  198. // 解析版本号
  199. version := dep.Version
  200. if version != "" {
  201. // 移除可能的 "v" 前缀
  202. version = strings.TrimPrefix(version, "v")
  203. parts := strings.Split(version, ".")
  204. if len(parts) >= 2 {
  205. major, err := strconv.Atoi(parts[0])
  206. if err != nil {
  207. klog.WithError(err).Warnf("Error parsing major version from %s", parts[0])
  208. continue
  209. }
  210. minor, err := strconv.Atoi(parts[1])
  211. if err != nil {
  212. klog.WithError(err).Warnf("Error parsing minor version from %s", parts[1])
  213. continue
  214. }
  215. klog.Infof("Detected gRPC version: %d.%d for PID %d", major, minor, pid)
  216. grpcMajorVersion = major
  217. grpcMinorVersion = minor
  218. // // 根据版本选择相应的探针策略
  219. // if major == 1 && minor >= 69 {
  220. // klog.Infof("Using modern gRPC handler for version %d.%d", major, minor)
  221. // } else {
  222. // klog.Infof("Using legacy gRPC handler for version %d.%d", major, minor)
  223. // }
  224. }
  225. }
  226. }
  227. }
  228. offset, ok := tracer.GetOffset(tracer.NewID("std", "runtime", "g", "goid"), path)
  229. bucketsOff, ok2 := tracer.GetOffset(tracer.NewID("std", "runtime", "hmap", "buckets"), path)
  230. if ok && ok2 {
  231. realVersion := strings.Replace(bi.GoVersion, "go", "", 1)
  232. parts := strings.Split(realVersion, ".")
  233. var major, minor, revision int
  234. if len(parts) >= 2 {
  235. major, err = strconv.Atoi(parts[0])
  236. if err != nil {
  237. log("Error converting major version:", err)
  238. return nil, err
  239. }
  240. minor, err = strconv.Atoi(parts[1])
  241. if err != nil {
  242. log("Error converting minor version:", err)
  243. return nil, err
  244. }
  245. if len(parts) >= 3 {
  246. revision, err = strconv.Atoi(parts[2])
  247. if err != nil {
  248. log("Error converting revision version:", err)
  249. }
  250. }
  251. goVersion := ((major & 0xFF) << 16) + ((minor & 0xFF) << 8) + min(revision, 255)
  252. info := EbpfProcInfo{}
  253. info.Version = uint32(goVersion)
  254. info.Offsets[OFFSET_IDX_GOID_RUNTIME_G] = uint16(offset)
  255. info.NetTCPConnItab = uint64(0)
  256. info.CryptoTLSConnItab = uint64(0)
  257. info.CredentialsSyscallConnItab = uint64(0)
  258. info.InstanceId = instanceID
  259. info.AppId = appID
  260. info.CodeType = codeType
  261. if grpcMajorVersion >= 1 && grpcMinorVersion >= 60 {
  262. info.IsNewFramePos = 1
  263. } else {
  264. info.IsNewFramePos = 0
  265. }
  266. // go
  267. info.BucketsPtrPos = bucketsOff
  268. fields := map[*uint64]tracer.ID{
  269. &info.MethodPtrPos: tracer.NewID("std", "net/http", "Request", "Method"),
  270. &info.UrlPtrPos: tracer.NewID("std", "net/http", "Request", "URL"),
  271. &info.PathPtrPos: tracer.NewID("std", "net/url", "URL", "Path"),
  272. &info.StatusCodePos: tracer.NewID("std", "net/http", "response", "status"),
  273. &info.RequestHostPos: tracer.NewID("std", "net/http", "Request", "Host"),
  274. &info.ProtoPos: tracer.NewID("std", "net/http", "Request", "Proto"),
  275. &info.CtxPtrPos: tracer.NewID("std", "net/http", "Request", "ctx"),
  276. &info.HeadersPtrPos: tracer.NewID("std", "net/http", "Request", "Header"),
  277. &info.HttpClientNextidPos: tracer.NewID("google.golang.org/grpc", "google.golang.org/grpc/internal/transport", "http2Client", "nextID"),
  278. &info.StreamMethodPtrPos: tracer.NewID("google.golang.org/grpc", "google.golang.org/grpc/internal/transport", "Stream", "method"),
  279. &info.StreamCtxPos: tracer.NewID("google.golang.org/grpc", "google.golang.org/grpc/internal/transport", "Stream", "ctx"),
  280. &info.IoWriterBufPtrPos: tracer.NewID("std", "bufio", "Writer", "buf"),
  281. &info.IoWriterNPos: tracer.NewID("std", "bufio", "Writer", "n"),
  282. }
  283. for field, id := range fields {
  284. off, ok := tracer.GetOffset(id, path)
  285. if !ok {
  286. klog.Warnf("failed to get offset for ID: %v", id)
  287. }
  288. *field = off
  289. }
  290. // 获取内存地址
  291. if appInfo.GoProcCache.StartAddr == 0 && appInfo.GoProcCache.EndAddr == 0 {
  292. allocDetails, allocErr := tracer.Allocate(int(pid))
  293. if allocErr != nil {
  294. return nil, allocErr
  295. }
  296. if allocDetails != nil {
  297. //info.StartAddr = allocDetails.StartAddr
  298. //info.EndAddr = allocDetails.EndAddr
  299. appInfo.GoProcCache.StartAddr = allocDetails.StartAddr
  300. appInfo.GoProcCache.EndAddr = allocDetails.EndAddr
  301. }
  302. }
  303. info.StartAddr = appInfo.GoProcCache.StartAddr
  304. info.EndAddr = appInfo.GoProcCache.EndAddr
  305. klog.Debugln("Major:", major)
  306. klog.Debugln("Minor:", minor)
  307. klog.Debugln("Revision:", revision)
  308. klog.Debugln("goVersion", goVersion)
  309. klog.WithField("pid", pid).Debugln("info.StartAddr", info.StartAddr)
  310. klog.WithField("pid", pid).Debugln("info.EndAddr", info.EndAddr)
  311. _, err = tracer.UpdateProcInfoToMap(t.collection, pid, info)
  312. if err != nil {
  313. klog.Error("failed to update program info", err)
  314. return nil, err
  315. }
  316. appInfo.EBPFProcInfo = &info
  317. }
  318. }
  319. var links []link.Link
  320. for _, s := range symbols {
  321. if elf.ST_TYPE(s.Info) != elf.STT_FUNC || s.Size == 0 {
  322. continue
  323. }
  324. switch s.Name {
  325. case goTlsWriteSymbol, goTlsReadSymbol:
  326. case goExecute, goNewproc1, goRunqget, goServeHTTP, goTransport, goHeaderWriteSubset, goGrpcHttp2OperateHeader, goGrpcServerHandleStream, goGrpcServerWritestatus, goGrpcClientConnInvoke, goGrpcClientLoopyHeaderHandler, goGrpcHttp2ClientNewStream, goReadContinuedLineSlice:
  327. default:
  328. continue
  329. }
  330. address := s.Value
  331. for _, p := range ef.Progs {
  332. if p.Type != elf.PT_LOAD || (p.Flags&elf.PF_X) == 0 {
  333. continue
  334. }
  335. if p.Vaddr <= s.Value && s.Value < (p.Vaddr+p.Memsz) {
  336. address = s.Value - p.Vaddr + p.Off
  337. break
  338. }
  339. }
  340. //fmt.Println("s.Name-----:", s.Name)
  341. switch s.Name {
  342. case goExecute:
  343. l, err := exe.Uprobe(s.Name, t.uprobes["runtime_execute"], &link.UprobeOptions{Address: address})
  344. if err != nil {
  345. log("failed to attach write_enter uprobe", err)
  346. klog.Infoln("runtime.execute no")
  347. return nil, err
  348. } else {
  349. klog.Infoln("runtime.execute ok")
  350. }
  351. links = append(links, l)
  352. case goNewproc1:
  353. l, err := exe.Uprobe(s.Name, t.uprobes["enter_runtime_newproc1"], &link.UprobeOptions{Address: address})
  354. if err != nil {
  355. log("failed to attach newproc1 uprobe", err)
  356. return nil, err
  357. }
  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. log("failed to attach enter_runtime_newproc1 uprobe", fmt.Errorf("no return offsets found"))
  368. return nil, err
  369. }
  370. for _, offset := range returnOffsets {
  371. l, err := exe.Uprobe(s.Name, t.uprobes["exit_runtime_newproc1"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  372. if err != nil {
  373. log("failed to attach exit_runtime_newproc1 uprobe", err)
  374. return nil, err
  375. }
  376. links = append(links, l)
  377. }
  378. case goRunqget:
  379. l, err := exe.Uprobe(s.Name, t.uprobes["enter_runtime_runqget"], &link.UprobeOptions{Address: address})
  380. if err != nil {
  381. log("failed to attach goRunqget uprobe", err)
  382. return nil, err
  383. }
  384. links = append(links, l)
  385. //sStart := s.Value - textSection.Addr
  386. //sEnd := sStart + s.Size
  387. //if sEnd > textSectionLen {
  388. // continue
  389. //}
  390. //sBytes := textSectionData[sStart:sEnd]
  391. //returnOffsets := getReturnOffsets(ef.Machine, sBytes)
  392. //if len(returnOffsets) == 0 {
  393. // log("failed to attach enter_runtime_newproc1 uprobe", fmt.Errorf("no return offsets found"))
  394. // return nil
  395. //}
  396. //for _, offset := range returnOffsets {
  397. // l, err := exe.Uprobe(s.Name, t.uprobes["exit_runtime_newproc1"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  398. // if err != nil {
  399. // log("failed to attach exit_runtime_newproc1 uprobe", err)
  400. // return nil
  401. // }
  402. // links = append(links, l)
  403. //}
  404. case goGrpcClientConnInvoke:
  405. // 根据 gRPC 版本选择相应的探针
  406. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_ClientConn_Invoke"], &link.UprobeOptions{Address: address})
  407. if err != nil {
  408. klog.WithError(err).Errorf("failed to attach uprobe_ClientConn_Invoke uprobe")
  409. continue
  410. }
  411. klog.Infoln("uprobe_ClientConn_Invoke ok")
  412. links = append(links, l)
  413. sStart := s.Value - textSection.Addr
  414. sEnd := sStart + s.Size
  415. if sEnd > textSectionLen {
  416. continue
  417. }
  418. sBytes := textSectionData[sStart:sEnd]
  419. returnOffsets := getReturnOffsets(ef.Machine, sBytes)
  420. if len(returnOffsets) == 0 {
  421. err = fmt.Errorf("failed to attach uprobe_ClientConn_Invoke no return offsets found")
  422. klog.Errorln(err)
  423. return nil, err
  424. }
  425. for _, offset := range returnOffsets {
  426. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_ClientConn_Invoke_Returns"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  427. if err != nil {
  428. klog.WithError(err).Errorln(fmt.Errorf("failed to attach uprobe_ClientConn_Invoke_Returns uprobe"))
  429. return nil, err
  430. }
  431. links = append(links, l)
  432. }
  433. case goGrpcClientLoopyHeaderHandler:
  434. // 根据 gRPC 版本选择相应的探针
  435. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_LoopyWriter_HeaderHandler"], &link.UprobeOptions{Address: address})
  436. if err != nil {
  437. klog.WithError(err).Errorf("failed to attach uprobe_LoopyWriter_HeaderHandler uprobe")
  438. continue
  439. }
  440. klog.Infoln("uprobe_LoopyWriter_HeaderHandler ok")
  441. links = append(links, l)
  442. case goGrpcHttp2ClientNewStream:
  443. // 根据 gRPC 版本选择相应的探针
  444. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_http2Client_NewStream"], &link.UprobeOptions{Address: address})
  445. if err != nil {
  446. klog.WithError(err).Errorf("failed to attach uprobe_http2Client_NewStream uprobe")
  447. continue
  448. }
  449. klog.Infoln("uprobe_http2Client_NewStream ok")
  450. links = append(links, l)
  451. case goGrpcHttp2OperateHeader:
  452. // 根据 gRPC 版本选择相应的探针
  453. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_http2Server_operateHeader"], &link.UprobeOptions{Address: address})
  454. if err != nil {
  455. klog.WithError(err).Errorf("failed to attach uprobe_http2Server_operateHeader uprobe")
  456. continue
  457. }
  458. klog.Infoln("uprobe_http2Server_operateHeader ok")
  459. links = append(links, l)
  460. // case goGrpcServerWritestatus:
  461. // // 根据 gRPC 版本选择相应的 WriteStatus 探针
  462. // l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_http2Server_WriteStatus"], &link.UprobeOptions{Address: address})
  463. // if err != nil {
  464. // klog.WithError(err).Errorf("failed to attach uprobe_http2Server_WriteStatus uprobe")
  465. // continue
  466. // }
  467. // links = append(links, l)
  468. case goGrpcServerHandleStream:
  469. // 根据 gRPC 版本选择相应的探针
  470. probeName := t.selectGRPCServerProbe(grpcMajorVersion, grpcMinorVersion)
  471. l, err := exe.Uprobe(s.Name, t.uprobes[probeName], &link.UprobeOptions{Address: address})
  472. if err != nil {
  473. klog.WithError(err).Errorf("failed to attach %s uprobe", probeName)
  474. continue
  475. }
  476. klog.Infof("%s ok (gRPC v%d.%d)", probeName, grpcMajorVersion, grpcMinorVersion)
  477. links = append(links, l)
  478. sStart := s.Value - textSection.Addr
  479. sEnd := sStart + s.Size
  480. klog.Infoln("google.golang.org/grpc.(*Server).handleStream ok----111111")
  481. if sEnd > textSectionLen {
  482. continue
  483. }
  484. klog.Infoln("google.golang.org/grpc.(*Server).handleStream ok----2222")
  485. sBytes := textSectionData[sStart:sEnd]
  486. returnOffsets := getReturnOffsets(ef.Machine, sBytes)
  487. if len(returnOffsets) == 0 {
  488. err = fmt.Errorf("failed to attach uprobe_server_handleStream2 no return offsets found")
  489. klog.Errorln(err)
  490. return nil, err
  491. }
  492. for _, offset := range returnOffsets {
  493. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_server_handleStream_Returns"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  494. if err != nil {
  495. klog.WithError(err).Errorln(fmt.Errorf("failed to attach exit_runtime_newproc1 uprobe"))
  496. return nil, err
  497. }
  498. klog.Infoln("google.golang.org/grpc.(*Server).handleStream ok----")
  499. links = append(links, l)
  500. }
  501. case goServeHTTP:
  502. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_HandlerFunc_ServeHTTP"], &link.UprobeOptions{Address: address})
  503. if err != nil {
  504. klog.WithError(err).Errorln("failed to attach uprobe_HandlerFunc_ServeHTTP uprobe")
  505. continue
  506. }
  507. klog.Infoln("net/http.serverHandler.ServeHTTP ok")
  508. links = append(links, l)
  509. sStart := s.Value - textSection.Addr
  510. sEnd := sStart + s.Size
  511. if sEnd > textSectionLen {
  512. continue
  513. }
  514. sBytes := textSectionData[sStart:sEnd]
  515. returnOffsets := getReturnOffsets(ef.Machine, sBytes)
  516. if len(returnOffsets) == 0 {
  517. err = fmt.Errorf("failed to attach uprobe_HandlerFunc_ServeHTTP no return offsets found")
  518. klog.Errorln(err)
  519. return nil, err
  520. }
  521. for _, offset := range returnOffsets {
  522. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_HandlerFunc_ServeHTTP_Returns"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  523. if err != nil {
  524. klog.WithError(err).Errorln(fmt.Errorf("failed to attach exit_runtime_newproc1 uprobe"))
  525. return nil, err
  526. }
  527. links = append(links, l)
  528. }
  529. case goTransport:
  530. if t.DisableE2ETracing() {
  531. continue
  532. }
  533. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_Transport_roundTrip"], &link.UprobeOptions{Address: address})
  534. if err != nil {
  535. klog.WithError(err).Errorln(fmt.Errorf("failed to attach write_enter uprobe"))
  536. continue
  537. } else {
  538. }
  539. klog.Infoln("net/http.uprobe_Transport_roundTrip ok")
  540. links = append(links, l)
  541. sStart := s.Value - textSection.Addr
  542. sEnd := sStart + s.Size
  543. if sEnd > textSectionLen {
  544. continue
  545. }
  546. sBytes := textSectionData[sStart:sEnd]
  547. returnOffsets := getReturnOffsets(ef.Machine, sBytes)
  548. if len(returnOffsets) == 0 {
  549. err = fmt.Errorf("failed to attach uprobe_Transport_roundTrip uprobe no return offsets found")
  550. klog.Errorln(err)
  551. return nil, err
  552. }
  553. for _, offset := range returnOffsets {
  554. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_Transport_roundTrip_Returns"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  555. if err != nil {
  556. klog.WithError(err).Errorln("failed to attach exit_runtime_newproc1 uprobe")
  557. return nil, err
  558. }
  559. links = append(links, l)
  560. }
  561. case goHeaderWriteSubset:
  562. if t.DisableE2ETracing() {
  563. continue
  564. }
  565. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_writeSubset"], &link.UprobeOptions{Address: address})
  566. if err != nil {
  567. klog.WithError(err).Errorln("failed to attach uprobe_writeSubset uprobe")
  568. continue
  569. }
  570. klog.Infoln("net/http.Header.writeSubset ok")
  571. links = append(links, l)
  572. case goTlsWriteSymbol:
  573. klog.Infoln("fucktls goTlsWriteSymbol crypto/tls uprobes attached")
  574. l, err := exe.Uprobe(s.Name, t.uprobes["go_crypto_tls_write_enter"], &link.UprobeOptions{Address: address})
  575. if err != nil {
  576. klog.WithError(err).Errorln("failed to attach write_enter uprobe")
  577. return nil, err
  578. }
  579. links = append(links, l)
  580. case goTlsReadSymbol:
  581. klog.Infoln("fucktls goTlsReadSymbol crypto/tls uprobes attached")
  582. l, err := exe.Uprobe(s.Name, t.uprobes["go_crypto_tls_read_enter"], &link.UprobeOptions{Address: address})
  583. if err != nil {
  584. klog.WithError(err).Errorln("failed to attach read_enter uprobe")
  585. return nil, err
  586. }
  587. links = append(links, l)
  588. sStart := s.Value - textSection.Addr
  589. sEnd := sStart + s.Size
  590. if sEnd > textSectionLen {
  591. continue
  592. }
  593. sBytes := textSectionData[sStart:sEnd]
  594. returnOffsets := getReturnOffsets(ef.Machine, sBytes)
  595. if len(returnOffsets) == 0 {
  596. err = fmt.Errorf("failed to attach read_exit uprobe no return offsets found")
  597. klog.Errorln(err)
  598. return nil, err
  599. }
  600. for _, offset := range returnOffsets {
  601. l, err := exe.Uprobe(s.Name, t.uprobes["go_crypto_tls_read_exit"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  602. if err != nil {
  603. klog.WithError(err).Errorln("failed to attach read_exit uprobe")
  604. return nil, err
  605. }
  606. links = append(links, l)
  607. }
  608. case goReadContinuedLineSlice:
  609. klog.Infoln("net/textproto.(*Reader).readContinuedLineSlice uprobe attaching")
  610. sStart := s.Value - textSection.Addr
  611. sEnd := sStart + s.Size
  612. if sEnd > textSectionLen {
  613. klog.Warnln("net/textproto.(*Reader).readContinuedLineSlice: sEnd > textSectionLen")
  614. continue
  615. }
  616. sBytes := textSectionData[sStart:sEnd]
  617. returnOffsets := getReturnOffsets(ef.Machine, sBytes)
  618. if len(returnOffsets) == 0 {
  619. err = fmt.Errorf("failed to attach uprobe_textproto_Reader_readContinuedLineSlice_Returns: no return offsets found")
  620. klog.Errorln(err)
  621. return nil, err
  622. }
  623. for _, offset := range returnOffsets {
  624. l, err := exe.Uprobe(s.Name, t.uprobes["uprobe_textproto_Reader_readContinuedLineSlice_Returns"], &link.UprobeOptions{Address: address, Offset: uint64(offset)})
  625. if err != nil {
  626. klog.WithError(err).Errorln("failed to attach uprobe_textproto_Reader_readContinuedLineSlice_Returns uprobe")
  627. return nil, err
  628. }
  629. klog.Infof("net/textproto.(*Reader).readContinuedLineSlice uprobe attached at offset %d", offset)
  630. links = append(links, l)
  631. }
  632. }
  633. }
  634. if len(links) == 0 {
  635. return nil, err
  636. }
  637. klog.Infoln("crypto/tls uprobes attached")
  638. return links, nil
  639. }
  640. func getSslLibPathAndVersion(pid uint32) (string, string) {
  641. f, err := os.Open(proc.Path(pid, "maps"))
  642. if err != nil {
  643. return "", ""
  644. }
  645. defer f.Close()
  646. scanner := bufio.NewScanner(f)
  647. scanner.Split(bufio.ScanLines)
  648. var libsslPath, libcryptoPath string
  649. for scanner.Scan() {
  650. parts := strings.Fields(scanner.Text())
  651. if len(parts) <= 5 {
  652. continue
  653. }
  654. libPath := parts[5]
  655. switch {
  656. case libsslPath == "" && strings.Contains(libPath, "libssl.so"):
  657. fullPath := proc.Path(pid, "root", libPath)
  658. if _, err = os.Stat(fullPath); err == nil {
  659. libsslPath = fullPath
  660. }
  661. case libcryptoPath == "" && strings.Contains(libPath, "libcrypto.so"):
  662. fullPath := proc.Path(pid, "root", libPath)
  663. if _, err = os.Stat(fullPath); err == nil {
  664. libcryptoPath = fullPath
  665. }
  666. default:
  667. continue
  668. }
  669. if libsslPath != "" && libcryptoPath != "" {
  670. break
  671. }
  672. }
  673. if libsslPath == "" || libcryptoPath == "" {
  674. return "", ""
  675. }
  676. ef, err := elf.Open(libcryptoPath)
  677. if err != nil {
  678. return "", ""
  679. }
  680. defer ef.Close()
  681. rodataSection := ef.Section(".rodata")
  682. if rodataSection == nil {
  683. return "", ""
  684. }
  685. rodataSectionData, err := rodataSection.Data()
  686. if err != nil {
  687. return "", ""
  688. }
  689. var version string
  690. for _, b := range bytes.Split(rodataSectionData, []byte("\x00")) {
  691. if len(b) == 0 {
  692. continue
  693. }
  694. s := string(b)
  695. if !strings.HasPrefix(s, "OpenSSL") {
  696. continue
  697. }
  698. if m := opensslVersionRe.FindStringSubmatch(s); len(m) > 1 {
  699. version = m[1]
  700. }
  701. }
  702. return libsslPath, "v" + version
  703. }
  704. // selectGRPCServerProbe 根据 gRPC 版本选择服务端探针
  705. func (t *Tracer) selectGRPCServerProbe(major, minor int) string {
  706. // 根据 gRPC 版本选择相应的探针
  707. if major == 1 && minor >= 69 {
  708. // 现代版本 (>= 1.69.0) 使用新的探针
  709. klog.Infof("Selecting modern gRPC server probe for version %d.%d", major, minor)
  710. return "uprobe_server_handleStream2"
  711. } else {
  712. // 传统版本 (< 1.69.0) 使用旧的探针
  713. klog.Infof("Selecting legacy gRPC server probe for version %d.%d", major, minor)
  714. return "uprobe_server_handleStream"
  715. }
  716. }
  717. func getReturnOffsets(machine elf.Machine, instructions []byte) []int {
  718. var res []int
  719. switch machine {
  720. case elf.EM_X86_64:
  721. for i := 0; i < len(instructions); {
  722. ins, err := x86asm.Decode(instructions[i:], 64)
  723. if err == nil && ins.Op == x86asm.RET {
  724. res = append(res, i)
  725. }
  726. i += ins.Len
  727. }
  728. case elf.EM_AARCH64:
  729. for i := 0; i < len(instructions); {
  730. ins, err := arm64asm.Decode(instructions[i:])
  731. if err == nil && ins.Op == arm64asm.RET {
  732. res = append(res, i)
  733. }
  734. i += 4
  735. }
  736. }
  737. return res
  738. }
  739. func min(a, b int) int {
  740. if a < b {
  741. return a
  742. }
  743. return b
  744. }