reality_server.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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/adapter"
  12. "github.com/sagernet/sing-box/common/dialer"
  13. "github.com/sagernet/sing-box/log"
  14. "github.com/sagernet/sing-box/option"
  15. "github.com/sagernet/sing/common/debug"
  16. E "github.com/sagernet/sing/common/exceptions"
  17. M "github.com/sagernet/sing/common/metadata"
  18. N "github.com/sagernet/sing/common/network"
  19. "github.com/sagernet/sing/common/ntp"
  20. )
  21. var _ ServerConfigCompat = (*RealityServerConfig)(nil)
  22. type RealityServerConfig struct {
  23. config *reality.Config
  24. }
  25. func NewRealityServer(ctx context.Context, logger log.Logger, options option.InboundTLSOptions) (*RealityServerConfig, error) {
  26. var tlsConfig reality.Config
  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 options.Certificate != "" || options.CertificatePath != "" {
  64. return nil, E.New("certificate is unavailable in reality")
  65. }
  66. if options.Key != "" || options.KeyPath != "" {
  67. return nil, E.New("key is unavailable in reality")
  68. }
  69. tlsConfig.SessionTicketsDisabled = true
  70. tlsConfig.Type = N.NetworkTCP
  71. tlsConfig.Dest = options.Reality.Handshake.ServerOptions.Build().String()
  72. tlsConfig.ServerNames = map[string]bool{options.ServerName: true}
  73. privateKey, err := base64.RawURLEncoding.DecodeString(options.Reality.PrivateKey)
  74. if err != nil {
  75. return nil, E.Cause(err, "decode private key")
  76. }
  77. if len(privateKey) != 32 {
  78. return nil, E.New("invalid private key")
  79. }
  80. tlsConfig.PrivateKey = privateKey
  81. tlsConfig.MaxTimeDiff = time.Duration(options.Reality.MaxTimeDifference)
  82. tlsConfig.ShortIds = make(map[[8]byte]bool)
  83. for i, shortIDString := range options.Reality.ShortID {
  84. var shortID [8]byte
  85. decodedLen, err := hex.Decode(shortID[:], []byte(shortIDString))
  86. if err != nil {
  87. return nil, E.Cause(err, "decode short_id[", i, "]: ", shortIDString)
  88. }
  89. if decodedLen > 8 {
  90. return nil, E.New("invalid short_id[", i, "]: ", shortIDString)
  91. }
  92. tlsConfig.ShortIds[shortID] = true
  93. }
  94. handshakeDialer, err := dialer.New(adapter.RouterFromContext(ctx), options.Reality.Handshake.DialerOptions)
  95. if err != nil {
  96. return nil, err
  97. }
  98. tlsConfig.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
  99. return handshakeDialer.DialContext(ctx, network, M.ParseSocksaddr(addr))
  100. }
  101. if debug.Enabled {
  102. tlsConfig.Show = true
  103. }
  104. return &RealityServerConfig{&tlsConfig}, nil
  105. }
  106. func (c *RealityServerConfig) ServerName() string {
  107. return c.config.ServerName
  108. }
  109. func (c *RealityServerConfig) SetServerName(serverName string) {
  110. c.config.ServerName = serverName
  111. }
  112. func (c *RealityServerConfig) NextProtos() []string {
  113. return c.config.NextProtos
  114. }
  115. func (c *RealityServerConfig) SetNextProtos(nextProto []string) {
  116. c.config.NextProtos = nextProto
  117. }
  118. func (c *RealityServerConfig) Config() (*tls.Config, error) {
  119. return nil, E.New("unsupported usage for reality")
  120. }
  121. func (c *RealityServerConfig) Client(conn net.Conn) (Conn, error) {
  122. return ClientHandshake(context.Background(), conn, c)
  123. }
  124. func (c *RealityServerConfig) Start() error {
  125. return nil
  126. }
  127. func (c *RealityServerConfig) Close() error {
  128. return nil
  129. }
  130. func (c *RealityServerConfig) Server(conn net.Conn) (Conn, error) {
  131. return ServerHandshake(context.Background(), conn, c)
  132. }
  133. func (c *RealityServerConfig) ServerHandshake(ctx context.Context, conn net.Conn) (Conn, error) {
  134. tlsConn, err := reality.Server(ctx, conn, c.config)
  135. if err != nil {
  136. return nil, err
  137. }
  138. return &realityConnWrapper{Conn: tlsConn}, nil
  139. }
  140. func (c *RealityServerConfig) Clone() Config {
  141. return &RealityServerConfig{
  142. config: c.config.Clone(),
  143. }
  144. }
  145. var _ Conn = (*realityConnWrapper)(nil)
  146. type realityConnWrapper struct {
  147. *reality.Conn
  148. }
  149. func (c *realityConnWrapper) ConnectionState() ConnectionState {
  150. state := c.Conn.ConnectionState()
  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. }