netguard.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. package email
  2. /*
  3. netguard.go
  4. Every outbound connection the mail backend makes goes through dialGuarded.
  5. A mail account is just a host and port typed in by a user, so without a
  6. guard any ArozOS user could make the server open connections into the
  7. LAN or to services bound to localhost. Unless the caller is an admin (or
  8. the admin allowed it), the host is resolved here, every address is
  9. checked, and the connection is made to the vetted IP — never to the name
  10. again — so a DNS answer cannot change between the check and the dial.
  11. */
  12. import (
  13. "context"
  14. "crypto/tls"
  15. "errors"
  16. "fmt"
  17. "net"
  18. "net/http"
  19. "strconv"
  20. "strings"
  21. "time"
  22. )
  23. const (
  24. dialTimeout = 20 * time.Second
  25. handshakeTimeout = 20 * time.Second
  26. )
  27. // cgnatBlock is the carrier-grade NAT range (RFC 6598), used by Tailscale and
  28. // many ISPs, which net.IP.IsPrivate does not cover.
  29. var cgnatBlock = &net.IPNet{IP: net.IPv4(100, 64, 0, 0), Mask: net.CIDRMask(10, 32)}
  30. // isRestrictedIP reports whether ip points into a local or special network.
  31. func isRestrictedIP(ip net.IP) bool {
  32. if ip == nil {
  33. return true
  34. }
  35. if v4 := ip.To4(); v4 != nil {
  36. ip = v4
  37. }
  38. return ip.IsLoopback() || ip.IsPrivate() || ip.IsUnspecified() ||
  39. ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() ||
  40. ip.IsInterfaceLocalMulticast() || ip.IsMulticast() ||
  41. cgnatBlock.Contains(ip)
  42. }
  43. // resolver is swapped by tests.
  44. var lookupIPAddr = func(ctx context.Context, host string) ([]net.IPAddr, error) {
  45. return net.DefaultResolver.LookupIPAddr(ctx, host)
  46. }
  47. // dialGuarded opens a TCP connection to host:port. With allowPrivate false
  48. // every resolved address must be public.
  49. func dialGuarded(ctx context.Context, host string, port int, allowPrivate bool) (net.Conn, error) {
  50. host = strings.TrimSpace(host)
  51. if host == "" {
  52. return nil, errors.New("server host is empty")
  53. }
  54. if port <= 0 || port > 65535 {
  55. return nil, fmt.Errorf("invalid port %d", port)
  56. }
  57. dialer := &net.Dialer{Timeout: dialTimeout, KeepAlive: 30 * time.Second}
  58. if allowPrivate {
  59. return dialer.DialContext(ctx, "tcp", net.JoinHostPort(host, strconv.Itoa(port)))
  60. }
  61. var addresses []net.IP
  62. if literal := net.ParseIP(strings.Trim(host, "[]")); literal != nil {
  63. addresses = []net.IP{literal}
  64. } else {
  65. resolved, err := lookupIPAddr(ctx, host)
  66. if err != nil {
  67. return nil, err
  68. }
  69. for _, address := range resolved {
  70. addresses = append(addresses, address.IP)
  71. }
  72. }
  73. if len(addresses) == 0 {
  74. return nil, fmt.Errorf("%s did not resolve to any address", host)
  75. }
  76. var lastErr error = ErrBlockedAddress
  77. for _, ip := range addresses {
  78. if isRestrictedIP(ip) {
  79. continue
  80. }
  81. conn, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort(ip.String(), strconv.Itoa(port)))
  82. if err == nil {
  83. return conn, nil
  84. }
  85. lastErr = err
  86. }
  87. return nil, lastErr
  88. }
  89. // tlsConfigFor builds the client TLS configuration for a server name.
  90. func tlsConfigFor(host string, nextProto string) *tls.Config {
  91. config := &tls.Config{
  92. ServerName: strings.Trim(host, "[]"),
  93. MinVersion: tls.VersionTLS12,
  94. }
  95. if nextProto != "" {
  96. config.NextProtos = []string{nextProto}
  97. }
  98. return config
  99. }
  100. // dialTLS opens an implicit-TLS connection with the handshake completed.
  101. func dialTLS(ctx context.Context, host string, port int, allowPrivate bool, nextProto string) (net.Conn, error) {
  102. raw, err := dialGuarded(ctx, host, port, allowPrivate)
  103. if err != nil {
  104. return nil, err
  105. }
  106. tlsConn := tls.Client(raw, tlsConfigFor(host, nextProto))
  107. handshakeCtx, cancel := context.WithTimeout(ctx, handshakeTimeout)
  108. defer cancel()
  109. if err := tlsConn.HandshakeContext(handshakeCtx); err != nil {
  110. raw.Close()
  111. return nil, describeTLSError(err)
  112. }
  113. return tlsConn, nil
  114. }
  115. // describeTLSError turns the common certificate failures into sentences.
  116. func describeTLSError(err error) error {
  117. var hostnameErr *tls.CertificateVerificationError
  118. if errors.As(err, &hostnameErr) {
  119. return fmt.Errorf("the server certificate could not be verified: %v", hostnameErr.Err)
  120. }
  121. if strings.Contains(err.Error(), "first record does not look like a TLS handshake") {
  122. return errors.New("the server did not answer with TLS, try STARTTLS or a different port")
  123. }
  124. return err
  125. }
  126. // guardedHTTPClient returns an HTTP client whose connections obey the same
  127. // address policy, used for autoconfig documents fetched from a user-typed
  128. // domain.
  129. func guardedHTTPClient(allowPrivate bool, timeout time.Duration) *http.Client {
  130. transport := &http.Transport{
  131. Proxy: nil,
  132. DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
  133. host, portText, err := net.SplitHostPort(address)
  134. if err != nil {
  135. return nil, err
  136. }
  137. port, err := strconv.Atoi(portText)
  138. if err != nil {
  139. return nil, err
  140. }
  141. return dialGuarded(ctx, host, port, allowPrivate)
  142. },
  143. TLSHandshakeTimeout: handshakeTimeout,
  144. ResponseHeaderTimeout: timeout,
  145. MaxIdleConns: 4,
  146. IdleConnTimeout: 30 * time.Second,
  147. }
  148. return &http.Client{
  149. Transport: transport,
  150. Timeout: timeout,
  151. CheckRedirect: func(req *http.Request, via []*http.Request) error {
  152. if len(via) >= 3 {
  153. return errors.New("too many redirects")
  154. }
  155. return nil
  156. },
  157. }
  158. }