reality_client.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. //go:build with_utls
  2. package tls
  3. import (
  4. "bytes"
  5. "context"
  6. "crypto/aes"
  7. "crypto/cipher"
  8. "crypto/ecdh"
  9. "crypto/ed25519"
  10. "crypto/hmac"
  11. "crypto/sha256"
  12. "crypto/sha512"
  13. "crypto/tls"
  14. "crypto/x509"
  15. "encoding/base64"
  16. "encoding/binary"
  17. "encoding/hex"
  18. "fmt"
  19. "io"
  20. mRand "math/rand"
  21. "net"
  22. "net/http"
  23. "reflect"
  24. "strings"
  25. "time"
  26. "unsafe"
  27. "github.com/sagernet/sing-box/adapter"
  28. "github.com/sagernet/sing-box/option"
  29. "github.com/sagernet/sing/common"
  30. "github.com/sagernet/sing/common/debug"
  31. E "github.com/sagernet/sing/common/exceptions"
  32. "github.com/sagernet/sing/common/logger"
  33. "github.com/sagernet/sing/common/ntp"
  34. aTLS "github.com/sagernet/sing/common/tls"
  35. utls "github.com/metacubex/utls"
  36. "golang.org/x/crypto/hkdf"
  37. "golang.org/x/net/http2"
  38. )
  39. var _ ConfigCompat = (*RealityClientConfig)(nil)
  40. type RealityClientConfig struct {
  41. ctx context.Context
  42. uClient *UTLSClientConfig
  43. publicKey []byte
  44. shortID [8]byte
  45. }
  46. func NewRealityClient(ctx context.Context, logger logger.ContextLogger, serverAddress string, options option.OutboundTLSOptions) (*RealityClientConfig, error) {
  47. if options.UTLS == nil || !options.UTLS.Enabled {
  48. return nil, E.New("uTLS is required by reality client")
  49. }
  50. uClient, err := NewUTLSClient(ctx, logger, serverAddress, options)
  51. if err != nil {
  52. return nil, err
  53. }
  54. publicKey, err := base64.RawURLEncoding.DecodeString(options.Reality.PublicKey)
  55. if err != nil {
  56. return nil, E.Cause(err, "decode public_key")
  57. }
  58. if len(publicKey) != 32 {
  59. return nil, E.New("invalid public_key")
  60. }
  61. var shortID [8]byte
  62. decodedLen, err := hex.Decode(shortID[:], []byte(options.Reality.ShortID))
  63. if err != nil {
  64. return nil, E.Cause(err, "decode short_id")
  65. }
  66. if decodedLen > 8 {
  67. return nil, E.New("invalid short_id")
  68. }
  69. return &RealityClientConfig{ctx, uClient.(*UTLSClientConfig), publicKey, shortID}, nil
  70. }
  71. func (e *RealityClientConfig) ServerName() string {
  72. return e.uClient.ServerName()
  73. }
  74. func (e *RealityClientConfig) SetServerName(serverName string) {
  75. e.uClient.SetServerName(serverName)
  76. }
  77. func (e *RealityClientConfig) NextProtos() []string {
  78. return e.uClient.NextProtos()
  79. }
  80. func (e *RealityClientConfig) SetNextProtos(nextProto []string) {
  81. e.uClient.SetNextProtos(nextProto)
  82. }
  83. func (e *RealityClientConfig) STDConfig() (*STDConfig, error) {
  84. return nil, E.New("unsupported usage for reality")
  85. }
  86. func (e *RealityClientConfig) Client(conn net.Conn) (Conn, error) {
  87. return ClientHandshake(context.Background(), conn, e)
  88. }
  89. func (e *RealityClientConfig) ClientHandshake(ctx context.Context, conn net.Conn) (aTLS.Conn, error) {
  90. verifier := &realityVerifier{
  91. serverName: e.uClient.ServerName(),
  92. }
  93. uConfig := e.uClient.config.Clone()
  94. uConfig.InsecureSkipVerify = true
  95. uConfig.SessionTicketsDisabled = true
  96. uConfig.VerifyPeerCertificate = verifier.VerifyPeerCertificate
  97. uConn := utls.UClient(conn, uConfig, e.uClient.id)
  98. verifier.UConn = uConn
  99. err := uConn.BuildHandshakeState()
  100. if err != nil {
  101. return nil, err
  102. }
  103. for _, extension := range uConn.Extensions {
  104. if ce, ok := extension.(*utls.SupportedCurvesExtension); ok {
  105. ce.Curves = common.Filter(ce.Curves, func(curveID utls.CurveID) bool {
  106. return curveID != utls.X25519MLKEM768
  107. })
  108. }
  109. if ks, ok := extension.(*utls.KeyShareExtension); ok {
  110. ks.KeyShares = common.Filter(ks.KeyShares, func(share utls.KeyShare) bool {
  111. return share.Group != utls.X25519MLKEM768
  112. })
  113. }
  114. }
  115. err = uConn.BuildHandshakeState()
  116. if err != nil {
  117. return nil, err
  118. }
  119. if len(uConfig.NextProtos) > 0 {
  120. for _, extension := range uConn.Extensions {
  121. if alpnExtension, isALPN := extension.(*utls.ALPNExtension); isALPN {
  122. alpnExtension.AlpnProtocols = uConfig.NextProtos
  123. break
  124. }
  125. }
  126. }
  127. hello := uConn.HandshakeState.Hello
  128. hello.SessionId = make([]byte, 32)
  129. copy(hello.Raw[39:], hello.SessionId)
  130. var nowTime time.Time
  131. if uConfig.Time != nil {
  132. nowTime = uConfig.Time()
  133. } else {
  134. nowTime = time.Now()
  135. }
  136. binary.BigEndian.PutUint64(hello.SessionId, uint64(nowTime.Unix()))
  137. hello.SessionId[0] = 1
  138. hello.SessionId[1] = 8
  139. hello.SessionId[2] = 1
  140. binary.BigEndian.PutUint32(hello.SessionId[4:], uint32(time.Now().Unix()))
  141. copy(hello.SessionId[8:], e.shortID[:])
  142. if debug.Enabled {
  143. fmt.Printf("REALITY hello.sessionId[:16]: %v\n", hello.SessionId[:16])
  144. }
  145. publicKey, err := ecdh.X25519().NewPublicKey(e.publicKey)
  146. if err != nil {
  147. return nil, err
  148. }
  149. keyShareKeys := uConn.HandshakeState.State13.KeyShareKeys
  150. if keyShareKeys == nil {
  151. return nil, E.New("nil KeyShareKeys")
  152. }
  153. ecdheKey := keyShareKeys.Ecdhe
  154. if ecdheKey == nil {
  155. return nil, E.New("nil ecdheKey")
  156. }
  157. authKey, err := ecdheKey.ECDH(publicKey)
  158. if err != nil {
  159. return nil, err
  160. }
  161. if authKey == nil {
  162. return nil, E.New("nil auth_key")
  163. }
  164. verifier.authKey = authKey
  165. _, err = hkdf.New(sha256.New, authKey, hello.Random[:20], []byte("REALITY")).Read(authKey)
  166. if err != nil {
  167. return nil, err
  168. }
  169. aesBlock, _ := aes.NewCipher(authKey)
  170. aesGcmCipher, _ := cipher.NewGCM(aesBlock)
  171. aesGcmCipher.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw)
  172. copy(hello.Raw[39:], hello.SessionId)
  173. if debug.Enabled {
  174. fmt.Printf("REALITY hello.sessionId: %v\n", hello.SessionId)
  175. fmt.Printf("REALITY uConn.AuthKey: %v\n", authKey)
  176. }
  177. err = uConn.HandshakeContext(ctx)
  178. if err != nil {
  179. return nil, err
  180. }
  181. if debug.Enabled {
  182. fmt.Printf("REALITY Conn.Verified: %v\n", verifier.verified)
  183. }
  184. if !verifier.verified {
  185. go realityClientFallback(e.ctx, uConn, e.uClient.ServerName(), e.uClient.id)
  186. return nil, E.New("reality verification failed")
  187. }
  188. return &realityClientConnWrapper{uConn}, nil
  189. }
  190. func realityClientFallback(ctx context.Context, uConn net.Conn, serverName string, fingerprint utls.ClientHelloID) {
  191. defer uConn.Close()
  192. client := &http.Client{
  193. Transport: &http2.Transport{
  194. DialTLSContext: func(ctx context.Context, network, addr string, config *tls.Config) (net.Conn, error) {
  195. return uConn, nil
  196. },
  197. TLSClientConfig: &tls.Config{
  198. Time: ntp.TimeFuncFromContext(ctx),
  199. RootCAs: adapter.RootPoolFromContext(ctx),
  200. },
  201. },
  202. }
  203. request, _ := http.NewRequest("GET", "https://"+serverName, nil)
  204. request.Header.Set("User-Agent", fingerprint.Client)
  205. request.AddCookie(&http.Cookie{Name: "padding", Value: strings.Repeat("0", mRand.Intn(32)+30)})
  206. response, err := client.Do(request)
  207. if err != nil {
  208. return
  209. }
  210. _, _ = io.Copy(io.Discard, response.Body)
  211. response.Body.Close()
  212. }
  213. func (e *RealityClientConfig) Clone() Config {
  214. return &RealityClientConfig{
  215. e.ctx,
  216. e.uClient.Clone().(*UTLSClientConfig),
  217. e.publicKey,
  218. e.shortID,
  219. }
  220. }
  221. type realityVerifier struct {
  222. *utls.UConn
  223. serverName string
  224. authKey []byte
  225. verified bool
  226. }
  227. func (c *realityVerifier) VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  228. p, _ := reflect.TypeOf(c.Conn).Elem().FieldByName("peerCertificates")
  229. certs := *(*([]*x509.Certificate))(unsafe.Pointer(uintptr(unsafe.Pointer(c.Conn)) + p.Offset))
  230. if pub, ok := certs[0].PublicKey.(ed25519.PublicKey); ok {
  231. h := hmac.New(sha512.New, c.authKey)
  232. h.Write(pub)
  233. if bytes.Equal(h.Sum(nil), certs[0].Signature) {
  234. c.verified = true
  235. return nil
  236. }
  237. }
  238. opts := x509.VerifyOptions{
  239. DNSName: c.serverName,
  240. Intermediates: x509.NewCertPool(),
  241. }
  242. for _, cert := range certs[1:] {
  243. opts.Intermediates.AddCert(cert)
  244. }
  245. if _, err := certs[0].Verify(opts); err != nil {
  246. return err
  247. }
  248. return nil
  249. }
  250. type realityClientConnWrapper struct {
  251. *utls.UConn
  252. }
  253. func (c *realityClientConnWrapper) ConnectionState() tls.ConnectionState {
  254. state := c.Conn.ConnectionState()
  255. //nolint:staticcheck
  256. return tls.ConnectionState{
  257. Version: state.Version,
  258. HandshakeComplete: state.HandshakeComplete,
  259. DidResume: state.DidResume,
  260. CipherSuite: state.CipherSuite,
  261. NegotiatedProtocol: state.NegotiatedProtocol,
  262. NegotiatedProtocolIsMutual: state.NegotiatedProtocolIsMutual,
  263. ServerName: state.ServerName,
  264. PeerCertificates: state.PeerCertificates,
  265. VerifiedChains: state.VerifiedChains,
  266. SignedCertificateTimestamps: state.SignedCertificateTimestamps,
  267. OCSPResponse: state.OCSPResponse,
  268. TLSUnique: state.TLSUnique,
  269. }
  270. }
  271. func (c *realityClientConnWrapper) Upstream() any {
  272. return c.UConn
  273. }
  274. // Due to low implementation quality, the reality server intercepted half close and caused memory leaks.
  275. // We fixed it by calling Close() directly.
  276. func (c *realityClientConnWrapper) CloseWrite() error {
  277. return c.Close()
  278. }
  279. func (c *realityClientConnWrapper) ReaderReplaceable() bool {
  280. return true
  281. }
  282. func (c *realityClientConnWrapper) WriterReplaceable() bool {
  283. return true
  284. }