reality_client.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. //go:build with_utls
  2. package tls
  3. import (
  4. "bytes"
  5. "context"
  6. "crypto/aes"
  7. "crypto/cipher"
  8. "crypto/ed25519"
  9. "crypto/hmac"
  10. "crypto/sha256"
  11. "crypto/sha512"
  12. "crypto/tls"
  13. "crypto/x509"
  14. "encoding/base64"
  15. "encoding/binary"
  16. "encoding/hex"
  17. "fmt"
  18. "io"
  19. mRand "math/rand"
  20. "net"
  21. "net/http"
  22. "reflect"
  23. "strings"
  24. "time"
  25. "unsafe"
  26. "github.com/sagernet/sing-box/adapter"
  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(router adapter.Router, 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(router, 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. hello := uConn.HandshakeState.Hello
  99. hello.SessionId = make([]byte, 32)
  100. copy(hello.Raw[39:], hello.SessionId)
  101. var nowTime time.Time
  102. if uConfig.Time != nil {
  103. nowTime = uConfig.Time()
  104. } else {
  105. nowTime = time.Now()
  106. }
  107. binary.BigEndian.PutUint64(hello.SessionId, uint64(nowTime.Unix()))
  108. hello.SessionId[0] = 1
  109. hello.SessionId[1] = 7
  110. hello.SessionId[2] = 5
  111. copy(hello.SessionId[8:], e.shortID[:])
  112. if debug.Enabled {
  113. fmt.Printf("REALITY hello.sessionId[:16]: %v\n", hello.SessionId[:16])
  114. }
  115. authKey := uConn.HandshakeState.State13.EcdheParams.SharedKey(e.publicKey)
  116. if authKey == nil {
  117. return nil, E.New("nil auth_key")
  118. }
  119. verifier.authKey = authKey
  120. _, err = hkdf.New(sha256.New, authKey, hello.Random[:20], []byte("REALITY")).Read(authKey)
  121. if err != nil {
  122. return nil, err
  123. }
  124. aesBlock, _ := aes.NewCipher(authKey)
  125. aesGcmCipher, _ := cipher.NewGCM(aesBlock)
  126. aesGcmCipher.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw)
  127. copy(hello.Raw[39:], hello.SessionId)
  128. if debug.Enabled {
  129. fmt.Printf("REALITY hello.sessionId: %v\n", hello.SessionId)
  130. fmt.Printf("REALITY uConn.AuthKey: %v\n", authKey)
  131. }
  132. err = uConn.HandshakeContext(ctx)
  133. if err != nil {
  134. return nil, err
  135. }
  136. if debug.Enabled {
  137. fmt.Printf("REALITY Conn.Verified: %v\n", verifier.verified)
  138. }
  139. if !verifier.verified {
  140. go realityClientFallback(uConn, e.uClient.ServerName(), e.uClient.id)
  141. return nil, E.New("reality verification failed")
  142. }
  143. return &utlsConnWrapper{uConn}, nil
  144. }
  145. func realityClientFallback(uConn net.Conn, serverName string, fingerprint utls.ClientHelloID) {
  146. defer uConn.Close()
  147. client := &http.Client{
  148. Transport: &http2.Transport{
  149. DialTLSContext: func(ctx context.Context, network, addr string, config *tls.Config) (net.Conn, error) {
  150. return uConn, nil
  151. },
  152. },
  153. }
  154. request, _ := http.NewRequest("GET", "https://"+serverName, nil)
  155. request.Header.Set("User-Agent", fingerprint.Client)
  156. request.AddCookie(&http.Cookie{Name: "padding", Value: strings.Repeat("0", mRand.Intn(32)+30)})
  157. response, err := client.Do(request)
  158. if err != nil {
  159. return
  160. }
  161. _, _ = io.Copy(io.Discard, response.Body)
  162. response.Body.Close()
  163. }
  164. func (e *RealityClientConfig) SetSessionIDGenerator(generator func(clientHello []byte, sessionID []byte) error) {
  165. e.uClient.config.SessionIDGenerator = generator
  166. }
  167. func (e *RealityClientConfig) Clone() Config {
  168. return &RealityClientConfig{
  169. e.uClient.Clone().(*UTLSClientConfig),
  170. e.publicKey,
  171. e.shortID,
  172. }
  173. }
  174. type realityVerifier struct {
  175. *utls.UConn
  176. serverName string
  177. authKey []byte
  178. verified bool
  179. }
  180. func (c *realityVerifier) VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  181. p, _ := reflect.TypeOf(c.Conn).Elem().FieldByName("peerCertificates")
  182. certs := *(*([]*x509.Certificate))(unsafe.Pointer(uintptr(unsafe.Pointer(c.Conn)) + p.Offset))
  183. if pub, ok := certs[0].PublicKey.(ed25519.PublicKey); ok {
  184. h := hmac.New(sha512.New, c.authKey)
  185. h.Write(pub)
  186. if bytes.Equal(h.Sum(nil), certs[0].Signature) {
  187. c.verified = true
  188. return nil
  189. }
  190. }
  191. opts := x509.VerifyOptions{
  192. DNSName: c.serverName,
  193. Intermediates: x509.NewCertPool(),
  194. }
  195. for _, cert := range certs[1:] {
  196. opts.Intermediates.AddCert(cert)
  197. }
  198. if _, err := certs[0].Verify(opts); err != nil {
  199. return err
  200. }
  201. return nil
  202. }