Highly-opinionated (ex-bullshit-free) MTPROTO proxy for Telegram. If you use v1.0 or upgrade broke you proxy, please read the chapter Version 2
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

doctor.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. package cli
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "errors"
  7. "fmt"
  8. "maps"
  9. "net"
  10. "os"
  11. "slices"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "text/template"
  16. "time"
  17. "github.com/9seconds/mtg/v2/essentials"
  18. "github.com/9seconds/mtg/v2/internal/config"
  19. "github.com/9seconds/mtg/v2/internal/utils"
  20. "github.com/9seconds/mtg/v2/mtglib"
  21. "github.com/9seconds/mtg/v2/mtglib/dcprobe"
  22. "github.com/9seconds/mtg/v2/network/v2"
  23. "github.com/beevik/ntp"
  24. )
  25. var (
  26. tplError = template.Must(
  27. template.New("").Parse(" ‼️ {{ .description }}: {{ .error }}\n"),
  28. )
  29. tplWDeprecatedConfig = template.Must(
  30. template.New("").
  31. Parse(` ⚠️ Option {{ .old | printf "%q" }}{{ if .old_section }} from section [{{ .old_section }}]{{ end }} is deprecated and will be removed in v{{ .when }}. Please use {{ .new | printf "%q" }}{{ if .new_section }} in [{{ .new_section }}] section{{ end }} instead.` + "\n"),
  32. )
  33. tplOTimeSkewness = template.Must(
  34. template.New("").
  35. Parse(" ✅ Time drift is {{ .drift }}, but tolerate-time-skewness is {{ .value }}\n"),
  36. )
  37. tplWTimeSkewness = template.Must(
  38. template.New("").
  39. Parse(" ⚠️ Time drift is {{ .drift }}, but tolerate-time-skewness is {{ .value }}. Please check ntp.\n"),
  40. )
  41. tplETimeSkewness = template.Must(
  42. template.New("").
  43. Parse(" ❌ Time drift is {{ .drift }}, but tolerate-time-skewness is {{ .value }}. You will get many rejected connections!\n"),
  44. )
  45. tplODCConnect = template.Must(
  46. template.New("").Parse(" ✅ DC {{ .dc }} (rpc {{ .rtt }})\n"),
  47. )
  48. tplEDCConnect = template.Must(
  49. template.New("").Parse(" ❌ DC {{ .dc }}: {{ .error }}\n"),
  50. )
  51. tplODNSSNIMatch = template.Must(
  52. template.New("").Parse(" ✅ IP address {{ .ip }} matches secret hostname {{ .hostname }}\n"),
  53. )
  54. tplEDNSSNIMatch = template.Must(
  55. template.New("").Parse(" ❌ Hostname {{ .hostname }} {{ if .resolved }}resolves to {{ .resolved }}, but the proxy's public IP is {{ if .ip4 }}{{ .ip4 }}{{ else }}<not detected>{{ end }} (IPv4) / {{ if .ip6 }}{{ .ip6 }}{{ else }}<not detected>{{ end }} (IPv6) — none of the resolved addresses match{{ else }}cannot be resolved to any host{{ end }}\n"),
  56. )
  57. tplOFrontingDomain = template.Must(
  58. template.New("").Parse(" ✅ {{ .address }} is reachable\n"),
  59. )
  60. tplEFrontingDomain = template.Must(
  61. template.New("").Parse(" ❌ {{ .address }}: {{ .error }}\n"),
  62. )
  63. tplOFrontingTLS = template.Must(
  64. template.New("").Parse(" ✅ TLS certificate for {{ .host }} is valid\n"),
  65. )
  66. tplEFrontingTLS = template.Must(
  67. template.New("").Parse(" ❌ TLS certificate for {{ .host }} is invalid: {{ .error }}\n"),
  68. )
  69. tplSFrontingTLS = template.Must(
  70. template.New("").Parse(" ⏭ TLS certificate check skipped: proxy-protocol is enabled (the listener expects a PROXY header that mtg doctor does not send yet)\n"),
  71. )
  72. )
  73. type Doctor struct {
  74. conf *config.Config
  75. ConfigPath string `kong:"arg,required,type='existingfile',help='Path to the configuration file.',name='config-path'"` //nolint: lll
  76. SkipNativeCheck bool `kong:"help='Skip the native network connectivity check (useful when proxy chaining is configured and direct egress is not expected to work).',name='skip-native-check'"` //nolint: lll
  77. }
  78. func (d *Doctor) Run(cli *CLI, version string) error {
  79. conf, err := utils.ReadConfig(d.ConfigPath)
  80. if err != nil {
  81. return fmt.Errorf("cannot init config: %w", err)
  82. }
  83. d.conf = conf
  84. fmt.Println("Deprecated options")
  85. everythingOK := d.checkDeprecatedConfig()
  86. fmt.Println("Time skewness")
  87. everythingOK = d.checkTimeSkewness() && everythingOK
  88. resolver, err := network.GetDNS(conf.GetDNS())
  89. if err != nil {
  90. return fmt.Errorf("cannot create DNS resolver: %w", err)
  91. }
  92. base := network.New(
  93. resolver,
  94. "",
  95. conf.Network.Timeout.TCP.Get(10*time.Second),
  96. conf.Network.Timeout.HTTP.Get(0),
  97. conf.Network.Timeout.Idle.Get(0),
  98. net.KeepAliveConfig{
  99. Enable: !conf.Network.KeepAlive.Disabled.Get(false),
  100. Idle: conf.Network.KeepAlive.Idle.Get(0),
  101. Interval: conf.Network.KeepAlive.Interval.Get(0),
  102. Count: int(conf.Network.KeepAlive.Count.Get(0)),
  103. },
  104. int(conf.Network.TCPNotSentLowat.Get(network.DefaultTCPNotSentLowat)),
  105. )
  106. fmt.Println("Validate native network connectivity")
  107. if d.SkipNativeCheck {
  108. fmt.Println(" ⏭ Skipped (--skip-native-check)")
  109. } else {
  110. everythingOK = d.checkNetwork(base) && everythingOK
  111. }
  112. for _, url := range conf.Network.Proxies {
  113. value, err := network.NewProxyNetwork(base, url.Get(nil))
  114. if err != nil {
  115. return err
  116. }
  117. fmt.Printf("Validate network connectivity with proxy %s\n", url.Get(nil))
  118. everythingOK = d.checkNetwork(value) && everythingOK
  119. }
  120. fmt.Println("Validate fronting domain connectivity")
  121. everythingOK = d.checkFrontingDomain(base) && everythingOK
  122. fmt.Println("Validate SNI-DNS match")
  123. everythingOK = d.checkSecretHost(resolver, base) && everythingOK
  124. if !everythingOK {
  125. os.Exit(1)
  126. }
  127. return nil
  128. }
  129. func (d *Doctor) checkDeprecatedConfig() bool {
  130. ok := true
  131. if d.conf.DomainFrontingIP.Value != nil {
  132. ok = false
  133. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  134. "when": "2.3.0",
  135. "old": "domain-fronting-ip",
  136. "old_section": "",
  137. "new": "host",
  138. "new_section": "domain-fronting",
  139. })
  140. }
  141. if d.conf.DomainFronting.IP.Value != nil {
  142. ok = false
  143. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  144. "when": "2.4.0",
  145. "old": "ip",
  146. "old_section": "domain-fronting",
  147. "new": "host",
  148. "new_section": "domain-fronting",
  149. })
  150. }
  151. if d.conf.DomainFrontingPort.Value != 0 {
  152. ok = false
  153. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  154. "when": "2.3.0",
  155. "old": "domain-fronting-port",
  156. "old_section": "",
  157. "new": "port",
  158. "new_section": "domain-fronting",
  159. })
  160. }
  161. if d.conf.DomainFrontingProxyProtocol.Value {
  162. ok = false
  163. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  164. "when": "2.3.0",
  165. "old": "domain-fronting-proxy-protocol",
  166. "old_section": "",
  167. "new": "proxy-protocol",
  168. "new_section": "domain-fronting",
  169. })
  170. }
  171. if d.conf.Network.DOHIP.Value != nil {
  172. ok = false
  173. tplWDeprecatedConfig.Execute(os.Stdout, map[string]string{ //nolint: errcheck
  174. "when": "2.3.0",
  175. "old": "doh-ip",
  176. "old_section": "network",
  177. "new": "dns",
  178. "new_section": "network",
  179. })
  180. }
  181. if ok {
  182. fmt.Println(" ✅ All good")
  183. }
  184. return ok
  185. }
  186. func (d *Doctor) checkTimeSkewness() bool {
  187. response, err := ntp.Query("0.pool.ntp.org")
  188. if err != nil {
  189. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  190. "description": "cannot access ntp pool",
  191. "error": err,
  192. })
  193. return false
  194. }
  195. skewness := response.ClockOffset.Abs()
  196. confValue := d.conf.TolerateTimeSkewness.Get(mtglib.DefaultTolerateTimeSkewness)
  197. diff := float64(skewness) / float64(confValue)
  198. tplData := map[string]any{
  199. "drift": response.ClockOffset,
  200. "value": confValue,
  201. }
  202. switch {
  203. case diff < 0.3:
  204. tplOTimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  205. return true
  206. case diff < 0.7:
  207. tplWTimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  208. default:
  209. tplETimeSkewness.Execute(os.Stdout, tplData) //nolint: errcheck
  210. }
  211. return false
  212. }
  213. func (d *Doctor) checkNetwork(ntw mtglib.Network) bool {
  214. dcs := slices.Collect(maps.Keys(essentials.TelegramCoreAddresses))
  215. slices.Sort(dcs)
  216. type dcResult struct {
  217. rtt time.Duration
  218. err error
  219. }
  220. results := make([]dcResult, len(dcs))
  221. var wg sync.WaitGroup
  222. for i, dc := range dcs {
  223. wg.Go(func() {
  224. defer func() {
  225. if r := recover(); r != nil {
  226. results[i].err = fmt.Errorf("panic: %v", r)
  227. }
  228. }()
  229. results[i].rtt, results[i].err = d.checkNetworkAddresses(ntw, dc, essentials.TelegramCoreAddresses[dc])
  230. })
  231. }
  232. wg.Wait()
  233. ok := true
  234. for i, dc := range dcs {
  235. if results[i].err == nil {
  236. tplODCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  237. "dc": dc,
  238. "rtt": results[i].rtt.Round(time.Microsecond),
  239. })
  240. } else {
  241. tplEDCConnect.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  242. "dc": dc,
  243. "error": results[i].err,
  244. })
  245. ok = false
  246. }
  247. }
  248. return ok
  249. }
  250. func (d *Doctor) checkNetworkAddresses(ntw mtglib.Network, dc int, addresses []string) (time.Duration, error) {
  251. checkAddresses := []string{}
  252. switch d.conf.PreferIP.Get("prefer-ip4") {
  253. case "only-ipv4":
  254. for _, addr := range addresses {
  255. host, _, err := net.SplitHostPort(addr)
  256. if err != nil {
  257. panic(err)
  258. }
  259. if ip := net.ParseIP(host); ip != nil && ip.To4() != nil {
  260. checkAddresses = append(checkAddresses, addr)
  261. }
  262. }
  263. case "only-ipv6":
  264. for _, addr := range addresses {
  265. host, _, err := net.SplitHostPort(addr)
  266. if err != nil {
  267. panic(err)
  268. }
  269. if ip := net.ParseIP(host); ip != nil && ip.To4() == nil {
  270. checkAddresses = append(checkAddresses, addr)
  271. }
  272. }
  273. default:
  274. checkAddresses = addresses
  275. }
  276. if len(checkAddresses) == 0 {
  277. return 0, fmt.Errorf("no suitable addresses after IP version filtering")
  278. }
  279. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  280. defer cancel()
  281. var lastErr error
  282. for _, addr := range checkAddresses {
  283. conn, err := ntw.DialContext(ctx, "tcp", addr)
  284. if err != nil {
  285. lastErr = fmt.Errorf("tcp connect to %s: %w", addr, err)
  286. continue
  287. }
  288. rtt, err := dcprobe.Probe(ctx, conn, dc)
  289. conn.Close() //nolint: errcheck
  290. if err != nil {
  291. lastErr = fmt.Errorf("rpc handshake to %s: %w", addr, err)
  292. continue
  293. }
  294. return rtt, nil
  295. }
  296. return 0, lastErr
  297. }
  298. func (d *Doctor) checkFrontingDomain(ntw mtglib.Network) bool {
  299. // SNI must always be the secret host: that is what domain fronting puts on
  300. // the wire and what the certificate is issued for. The TCP target may be a
  301. // different address when domain-fronting.host overrides it (in the
  302. // sni-router setup it is an internal name like "web").
  303. sniHost := d.conf.Secret.Host
  304. dialHost := sniHost
  305. if override := d.conf.GetDomainFrontingHost(); override != "" {
  306. dialHost = override
  307. }
  308. port := d.conf.GetDomainFrontingPort(mtglib.DefaultDomainFrontingPort)
  309. address := net.JoinHostPort(dialHost, strconv.Itoa(int(port)))
  310. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  311. defer cancel()
  312. dialer := ntw.NativeDialer()
  313. conn, err := dialer.DialContext(ctx, "tcp", address)
  314. if err != nil {
  315. tplEFrontingDomain.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  316. "address": address,
  317. "error": err,
  318. })
  319. return false
  320. }
  321. conn.Close() //nolint: errcheck
  322. tplOFrontingDomain.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  323. "address": address,
  324. })
  325. // With proxy-protocol enabled the fronting listener expects a PROXY header
  326. // before the TLS ClientHello, so a bare TLS handshake would hang or be
  327. // rejected and report a misleading failure. mtg doctor does not emit that
  328. // header yet, so skip the certificate probe rather than print a false
  329. // negative. See issue #518.
  330. if d.conf.GetDomainFrontingProxyProtocol(false) {
  331. tplSFrontingTLS.Execute(os.Stdout, nil) //nolint: errcheck
  332. return true
  333. }
  334. // A default crypto/tls client handshake against the fronting endpoint with
  335. // ServerName = secret host validates the whole certificate in one shot:
  336. // chain against the system roots, leaf SAN against the secret host, and
  337. // validity period. An expired / untrusted / wrong-host certificate all
  338. // surface as descriptive x509 errors.
  339. if err := probeFrontingTLS(ctx, dialer, address, sniHost, nil); err != nil {
  340. tplEFrontingTLS.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  341. "host": sniHost,
  342. "error": err,
  343. })
  344. return false
  345. }
  346. tplOFrontingTLS.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  347. "host": sniHost,
  348. })
  349. return true
  350. }
  351. // probeFrontingTLS dials dialAddress over TCP and performs a TLS handshake
  352. // presenting sniHost as the SNI / ServerName. Verification is left at the
  353. // crypto/tls default (InsecureSkipVerify=false), so the handshake fails with a
  354. // descriptive x509 error if the certificate chain is untrusted, the leaf SAN
  355. // does not cover sniHost, or the certificate is expired/not-yet-valid.
  356. //
  357. // rootCAs overrides the trust anchors; it is nil in production (system roots)
  358. // and is only set by tests that need a self-signed anchor.
  359. func probeFrontingTLS(
  360. ctx context.Context,
  361. dialer *net.Dialer,
  362. dialAddress string,
  363. sniHost string,
  364. rootCAs *x509.CertPool,
  365. ) error {
  366. conn, err := dialer.DialContext(ctx, "tcp", dialAddress)
  367. if err != nil {
  368. return fmt.Errorf("cannot dial %s: %w", dialAddress, err)
  369. }
  370. defer conn.Close() //nolint: errcheck
  371. if deadline, ok := ctx.Deadline(); ok {
  372. conn.SetDeadline(deadline) //nolint: errcheck
  373. }
  374. tlsConn := tls.Client(conn, &tls.Config{
  375. ServerName: sniHost,
  376. RootCAs: rootCAs,
  377. MinVersion: tls.VersionTLS12,
  378. })
  379. defer tlsConn.Close() //nolint: errcheck
  380. return tlsConn.HandshakeContext(ctx)
  381. }
  382. func (d *Doctor) checkSecretHost(resolver *net.Resolver, ntw mtglib.Network) bool {
  383. res := runSNICheck(context.Background(), resolver, d.conf, ntw)
  384. if res.ResolveErr != nil {
  385. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  386. "description": fmt.Sprintf("cannot resolve DNS name of %s", d.conf.Secret.Host),
  387. "error": res.ResolveErr,
  388. })
  389. return false
  390. }
  391. if !res.PublicIPKnown() {
  392. tplError.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  393. "description": "cannot detect public IP address",
  394. "error": errors.New("cannot detect automatically and public-ipv4/public-ipv6 are not set in config"),
  395. })
  396. return false
  397. }
  398. if res.IPv4Match || res.IPv6Match {
  399. var matched net.IP
  400. for _, ip := range res.Resolved {
  401. if (res.OurIPv4 != nil && ip.String() == res.OurIPv4.String()) ||
  402. (res.OurIPv6 != nil && ip.String() == res.OurIPv6.String()) {
  403. matched = ip
  404. break
  405. }
  406. }
  407. tplODNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  408. "ip": matched,
  409. "hostname": d.conf.Secret.Host,
  410. })
  411. return true
  412. }
  413. strAddresses := make([]string, 0, len(res.Resolved))
  414. for _, ip := range res.Resolved {
  415. strAddresses = append(strAddresses, `"`+ip.String()+`"`)
  416. }
  417. tplEDNSSNIMatch.Execute(os.Stdout, map[string]any{ //nolint: errcheck
  418. "hostname": d.conf.Secret.Host,
  419. "resolved": strings.Join(strAddresses, ", "),
  420. "ip4": res.OurIPv4,
  421. "ip6": res.OurIPv6,
  422. })
  423. return false
  424. }