reality_client.go 8.4 KB

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