reality_client.go 7.9 KB

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