reality_client.go 7.6 KB

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