reality_client.go 6.2 KB

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