reality_server.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. //go:build with_utls
  2. package tls
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "fmt"
  9. "net"
  10. "time"
  11. "github.com/sagernet/sing-box/common/dialer"
  12. "github.com/sagernet/sing-box/log"
  13. "github.com/sagernet/sing-box/option"
  14. E "github.com/sagernet/sing/common/exceptions"
  15. M "github.com/sagernet/sing/common/metadata"
  16. N "github.com/sagernet/sing/common/network"
  17. "github.com/sagernet/sing/common/ntp"
  18. utls "github.com/metacubex/utls"
  19. )
  20. var _ ServerConfigCompat = (*RealityServerConfig)(nil)
  21. type RealityServerConfig struct {
  22. config *utls.RealityConfig
  23. }
  24. func NewRealityServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (*RealityServerConfig, error) {
  25. var tlsConfig utls.RealityConfig
  26. if options.ACME != nil && len(options.ACME.Domain) > 0 {
  27. return nil, E.New("acme is unavailable in reality")
  28. }
  29. tlsConfig.Time = ntp.TimeFuncFromContext(ctx)
  30. if options.ServerName != "" {
  31. tlsConfig.ServerName = options.ServerName
  32. }
  33. if len(options.ALPN) > 0 {
  34. tlsConfig.NextProtos = append(tlsConfig.NextProtos, options.ALPN...)
  35. }
  36. if options.MinVersion != "" {
  37. minVersion, err := ParseTLSVersion(options.MinVersion)
  38. if err != nil {
  39. return nil, E.Cause(err, "parse min_version")
  40. }
  41. tlsConfig.MinVersion = minVersion
  42. }
  43. if options.MaxVersion != "" {
  44. maxVersion, err := ParseTLSVersion(options.MaxVersion)
  45. if err != nil {
  46. return nil, E.Cause(err, "parse max_version")
  47. }
  48. tlsConfig.MaxVersion = maxVersion
  49. }
  50. if options.CipherSuites != nil {
  51. find:
  52. for _, cipherSuite := range options.CipherSuites {
  53. for _, tlsCipherSuite := range tls.CipherSuites() {
  54. if cipherSuite == tlsCipherSuite.Name {
  55. tlsConfig.CipherSuites = append(tlsConfig.CipherSuites, tlsCipherSuite.ID)
  56. continue find
  57. }
  58. }
  59. return nil, E.New("unknown cipher_suite: ", cipherSuite)
  60. }
  61. }
  62. if len(options.Certificate) > 0 || options.CertificatePath != "" {
  63. return nil, E.New("certificate is unavailable in reality")
  64. }
  65. if len(options.Key) > 0 || options.KeyPath != "" {
  66. return nil, E.New("key is unavailable in reality")
  67. }
  68. tlsConfig.SessionTicketsDisabled = true
  69. tlsConfig.Log = func(format string, v ...any) {
  70. if logger != nil {
  71. logger.Trace(fmt.Sprintf(format, v...))
  72. }
  73. }
  74. tlsConfig.Type = N.NetworkTCP
  75. tlsConfig.Dest = options.Reality.Handshake.ServerOptions.Build().String()
  76. tlsConfig.ServerNames = map[string]bool{options.ServerName: true}
  77. privateKey, err := base64.RawURLEncoding.DecodeString(options.Reality.PrivateKey)
  78. if err != nil {
  79. return nil, E.Cause(err, "decode private key")
  80. }
  81. if len(privateKey) != 32 {
  82. return nil, E.New("invalid private key")
  83. }
  84. tlsConfig.PrivateKey = privateKey
  85. tlsConfig.MaxTimeDiff = time.Duration(options.Reality.MaxTimeDifference)
  86. tlsConfig.ShortIds = make(map[[8]byte]bool)
  87. if len(options.Reality.ShortID) == 0 {
  88. tlsConfig.ShortIds[[8]byte{0}] = true
  89. } else {
  90. for i, shortIDString := range options.Reality.ShortID {
  91. var shortID [8]byte
  92. decodedLen, err := hex.Decode(shortID[:], []byte(shortIDString))
  93. if err != nil {
  94. return nil, E.Cause(err, "decode short_id[", i, "]: ", shortIDString)
  95. }
  96. if decodedLen > 8 {
  97. return nil, E.New("invalid short_id[", i, "]: ", shortIDString)
  98. }
  99. tlsConfig.ShortIds[shortID] = true
  100. }
  101. }
  102. handshakeDialer, err := dialer.New(ctx, options.Reality.Handshake.DialerOptions, options.Reality.Handshake.ServerIsDomain())
  103. if err != nil {
  104. return nil, err
  105. }
  106. tlsConfig.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
  107. return handshakeDialer.DialContext(ctx, network, M.ParseSocksaddr(addr))
  108. }
  109. if options.ECH != nil && options.ECH.Enabled {
  110. return nil, E.New("Reality is conflict with ECH")
  111. }
  112. if options.KernelRx || options.KernelTx {
  113. return nil, E.New("Reality is conflict with kTLS")
  114. }
  115. return &RealityServerConfig{&tlsConfig}, nil
  116. }
  117. func (c *RealityServerConfig) ServerName() string {
  118. return c.config.ServerName
  119. }
  120. func (c *RealityServerConfig) SetServerName(serverName string) {
  121. c.config.ServerName = serverName
  122. }
  123. func (c *RealityServerConfig) NextProtos() []string {
  124. return c.config.NextProtos
  125. }
  126. func (c *RealityServerConfig) SetNextProtos(nextProto []string) {
  127. c.config.NextProtos = nextProto
  128. }
  129. func (c *RealityServerConfig) STDConfig() (*tls.Config, error) {
  130. return nil, E.New("unsupported usage for reality")
  131. }
  132. func (c *RealityServerConfig) Client(conn net.Conn) (Conn, error) {
  133. return ClientHandshake(context.Background(), conn, c)
  134. }
  135. func (c *RealityServerConfig) Start() error {
  136. return nil
  137. }
  138. func (c *RealityServerConfig) Close() error {
  139. return nil
  140. }
  141. func (c *RealityServerConfig) Server(conn net.Conn) (Conn, error) {
  142. return ServerHandshake(context.Background(), conn, c)
  143. }
  144. func (c *RealityServerConfig) ServerHandshake(ctx context.Context, conn net.Conn) (Conn, error) {
  145. tlsConn, err := utls.RealityServer(ctx, conn, c.config)
  146. if err != nil {
  147. return nil, err
  148. }
  149. return &realityConnWrapper{Conn: tlsConn}, nil
  150. }
  151. func (c *RealityServerConfig) Clone() Config {
  152. return &RealityServerConfig{
  153. config: c.config.Clone(),
  154. }
  155. }
  156. var _ Conn = (*realityConnWrapper)(nil)
  157. type realityConnWrapper struct {
  158. *utls.Conn
  159. }
  160. func (c *realityConnWrapper) ConnectionState() ConnectionState {
  161. state := c.Conn.ConnectionState()
  162. //nolint:staticcheck
  163. return tls.ConnectionState{
  164. Version: state.Version,
  165. HandshakeComplete: state.HandshakeComplete,
  166. DidResume: state.DidResume,
  167. CipherSuite: state.CipherSuite,
  168. NegotiatedProtocol: state.NegotiatedProtocol,
  169. NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
  170. ServerName: state.ServerName,
  171. PeerCertificates: state.PeerCertificates,
  172. VerifiedChains: state.VerifiedChains,
  173. SignedCertificateTimestamps: state.SignedCertificateTimestamps,
  174. OCSPResponse: state.OCSPResponse,
  175. TLSUnique: state.TLSUnique,
  176. }
  177. }
  178. func (c *realityConnWrapper) Upstream() any {
  179. return c.Conn
  180. }
  181. // Due to low implementation quality, the reality server intercepted half close and caused memory leaks.
  182. // We fixed it by calling Close() directly.
  183. func (c *realityConnWrapper) CloseWrite() error {
  184. return c.Close()
  185. }
  186. func (c *realityConnWrapper) ReaderReplaceable() bool {
  187. return true
  188. }
  189. func (c *realityConnWrapper) WriterReplaceable() bool {
  190. return true
  191. }