reality_server.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  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. "os"
  10. "time"
  11. "github.com/sagernet/reality"
  12. "github.com/sagernet/sing-box/adapter"
  13. "github.com/sagernet/sing-box/common/dialer"
  14. "github.com/sagernet/sing-box/log"
  15. "github.com/sagernet/sing-box/option"
  16. "github.com/sagernet/sing/common/debug"
  17. E "github.com/sagernet/sing/common/exceptions"
  18. M "github.com/sagernet/sing/common/metadata"
  19. N "github.com/sagernet/sing/common/network"
  20. )
  21. var _ ServerConfigCompat = (*RealityServerConfig)(nil)
  22. type RealityServerConfig struct {
  23. config *reality.Config
  24. }
  25. func NewRealityServer(ctx context.Context, router adapter.Router, 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 = router.TimeFunc()
  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, shortID := range options.Reality.ShortID {
  84. var shortIDBytesArray [8]byte
  85. decodedLen, err := hex.Decode(shortIDBytesArray[:], []byte(shortID))
  86. if err != nil {
  87. return nil, E.Cause(err, "decode short_id[", i, "]: ", shortID)
  88. }
  89. if decodedLen != 8 {
  90. return nil, E.New("invalid short_id[", i, "]: ", shortID)
  91. }
  92. tlsConfig.ShortIds[shortIDBytesArray] = true
  93. }
  94. handshakeDialer := dialer.New(router, options.Reality.Handshake.DialerOptions)
  95. tlsConfig.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
  96. return handshakeDialer.DialContext(ctx, network, M.ParseSocksaddr(addr))
  97. }
  98. if debug.Enabled {
  99. tlsConfig.Show = true
  100. }
  101. return &RealityServerConfig{&tlsConfig}, nil
  102. }
  103. func (c *RealityServerConfig) ServerName() string {
  104. return c.config.ServerName
  105. }
  106. func (c *RealityServerConfig) SetServerName(serverName string) {
  107. c.config.ServerName = serverName
  108. }
  109. func (c *RealityServerConfig) NextProtos() []string {
  110. return c.config.NextProtos
  111. }
  112. func (c *RealityServerConfig) SetNextProtos(nextProto []string) {
  113. c.config.NextProtos = nextProto
  114. }
  115. func (c *RealityServerConfig) Config() (*tls.Config, error) {
  116. return nil, E.New("unsupported usage for reality")
  117. }
  118. func (c *RealityServerConfig) Client(conn net.Conn) (Conn, error) {
  119. return nil, os.ErrInvalid
  120. }
  121. func (c *RealityServerConfig) Start() error {
  122. return nil
  123. }
  124. func (c *RealityServerConfig) Close() error {
  125. return nil
  126. }
  127. func (c *RealityServerConfig) Server(conn net.Conn) (Conn, error) {
  128. return nil, os.ErrInvalid
  129. }
  130. func (c *RealityServerConfig) ServerHandshake(ctx context.Context, conn net.Conn) (Conn, error) {
  131. tlsConn, err := reality.Server(ctx, conn, c.config)
  132. if err != nil {
  133. return nil, err
  134. }
  135. return &realityConnWrapper{Conn: tlsConn}, nil
  136. }
  137. func (c *RealityServerConfig) Clone() Config {
  138. return &RealityServerConfig{
  139. config: c.config.Clone(),
  140. }
  141. }
  142. var _ Conn = (*realityConnWrapper)(nil)
  143. type realityConnWrapper struct {
  144. *reality.Conn
  145. }
  146. func (c *realityConnWrapper) ConnectionState() ConnectionState {
  147. state := c.Conn.ConnectionState()
  148. return tls.ConnectionState{
  149. Version: state.Version,
  150. HandshakeComplete: state.HandshakeComplete,
  151. DidResume: state.DidResume,
  152. CipherSuite: state.CipherSuite,
  153. NegotiatedProtocol: state.NegotiatedProtocol,
  154. NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
  155. ServerName: state.ServerName,
  156. PeerCertificates: state.PeerCertificates,
  157. VerifiedChains: state.VerifiedChains,
  158. SignedCertificateTimestamps: state.SignedCertificateTimestamps,
  159. OCSPResponse: state.OCSPResponse,
  160. TLSUnique: state.TLSUnique,
  161. }
  162. }
  163. func (c *realityConnWrapper) Upstream() any {
  164. return c.Conn
  165. }