reality_server.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. //go:build with_reality_server
  2. package tls
  3. import (
  4. "context"
  5. "crypto/tls"
  6. "encoding/base64"
  7. "encoding/hex"
  8. "net"
  9. "time"
  10. "github.com/sagernet/reality"
  11. "github.com/sagernet/sing-box/common/dialer"
  12. "github.com/sagernet/sing-box/log"
  13. "github.com/sagernet/sing-box/option"
  14. "github.com/sagernet/sing/common/debug"
  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. )
  20. var _ ServerConfigCompat = (*RealityServerConfig)(nil)
  21. type RealityServerConfig struct {
  22. config *reality.Config
  23. }
  24. func NewRealityServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (*RealityServerConfig, error) {
  25. var tlsConfig reality.Config
  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.Type = N.NetworkTCP
  70. tlsConfig.Dest = options.Reality.Handshake.ServerOptions.Build().String()
  71. tlsConfig.ServerNames = map[string]bool{options.ServerName: true}
  72. privateKey, err := base64.RawURLEncoding.DecodeString(options.Reality.PrivateKey)
  73. if err != nil {
  74. return nil, E.Cause(err, "decode private key")
  75. }
  76. if len(privateKey) != 32 {
  77. return nil, E.New("invalid private key")
  78. }
  79. tlsConfig.PrivateKey = privateKey
  80. tlsConfig.MaxTimeDiff = time.Duration(options.Reality.MaxTimeDifference)
  81. tlsConfig.ShortIds = make(map[[8]byte]bool)
  82. for i, shortIDString := range options.Reality.ShortID {
  83. var shortID [8]byte
  84. decodedLen, err := hex.Decode(shortID[:], []byte(shortIDString))
  85. if err != nil {
  86. return nil, E.Cause(err, "decode short_id[", i, "]: ", shortIDString)
  87. }
  88. if decodedLen > 8 {
  89. return nil, E.New("invalid short_id[", i, "]: ", shortIDString)
  90. }
  91. tlsConfig.ShortIds[shortID] = true
  92. }
  93. handshakeDialer, err := dialer.New(ctx, options.Reality.Handshake.DialerOptions)
  94. if err != nil {
  95. return nil, err
  96. }
  97. tlsConfig.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
  98. return handshakeDialer.DialContext(ctx, network, M.ParseSocksaddr(addr))
  99. }
  100. if debug.Enabled {
  101. tlsConfig.Show = true
  102. }
  103. return &RealityServerConfig{&tlsConfig}, nil
  104. }
  105. func (c *RealityServerConfig) ServerName() string {
  106. return c.config.ServerName
  107. }
  108. func (c *RealityServerConfig) SetServerName(serverName string) {
  109. c.config.ServerName = serverName
  110. }
  111. func (c *RealityServerConfig) NextProtos() []string {
  112. return c.config.NextProtos
  113. }
  114. func (c *RealityServerConfig) SetNextProtos(nextProto []string) {
  115. c.config.NextProtos = nextProto
  116. }
  117. func (c *RealityServerConfig) Config() (*tls.Config, error) {
  118. return nil, E.New("unsupported usage for reality")
  119. }
  120. func (c *RealityServerConfig) Client(conn net.Conn) (Conn, error) {
  121. return ClientHandshake(context.Background(), conn, c)
  122. }
  123. func (c *RealityServerConfig) Start() error {
  124. return nil
  125. }
  126. func (c *RealityServerConfig) Close() error {
  127. return nil
  128. }
  129. func (c *RealityServerConfig) Server(conn net.Conn) (Conn, error) {
  130. return ServerHandshake(context.Background(), conn, c)
  131. }
  132. func (c *RealityServerConfig) ServerHandshake(ctx context.Context, conn net.Conn) (Conn, error) {
  133. tlsConn, err := reality.Server(ctx, conn, c.config)
  134. if err != nil {
  135. return nil, err
  136. }
  137. return &realityConnWrapper{Conn: tlsConn}, nil
  138. }
  139. func (c *RealityServerConfig) Clone() Config {
  140. return &RealityServerConfig{
  141. config: c.config.Clone(),
  142. }
  143. }
  144. var _ Conn = (*realityConnWrapper)(nil)
  145. type realityConnWrapper struct {
  146. *reality.Conn
  147. }
  148. func (c *realityConnWrapper) ConnectionState() ConnectionState {
  149. state := c.Conn.ConnectionState()
  150. //nolint:staticcheck
  151. return tls.ConnectionState{
  152. Version: state.Version,
  153. HandshakeComplete: state.HandshakeComplete,
  154. DidResume: state.DidResume,
  155. CipherSuite: state.CipherSuite,
  156. NegotiatedProtocol: state.NegotiatedProtocol,
  157. NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
  158. ServerName: state.ServerName,
  159. PeerCertificates: state.PeerCertificates,
  160. VerifiedChains: state.VerifiedChains,
  161. SignedCertificateTimestamps: state.SignedCertificateTimestamps,
  162. OCSPResponse: state.OCSPResponse,
  163. TLSUnique: state.TLSUnique,
  164. }
  165. }
  166. func (c *realityConnWrapper) Upstream() any {
  167. return c.Conn
  168. }
  169. // Due to low implementation quality, the reality server intercepted half close and caused memory leaks.
  170. // We fixed it by calling Close() directly.
  171. func (c *realityConnWrapper) CloseWrite() error {
  172. return c.Close()
  173. }