reality_server.go 7.3 KB

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