reality_server.go 6.5 KB

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