reality.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. package reality
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/aes"
  6. "crypto/cipher"
  7. "crypto/ecdh"
  8. "crypto/ed25519"
  9. "crypto/hmac"
  10. "crypto/rand"
  11. "crypto/sha256"
  12. "crypto/sha512"
  13. gotls "crypto/tls"
  14. "crypto/x509"
  15. "encoding/binary"
  16. "fmt"
  17. "io"
  18. "math/big"
  19. "net/http"
  20. "reflect"
  21. "regexp"
  22. "strings"
  23. "sync"
  24. "time"
  25. "unsafe"
  26. utls "github.com/refraction-networking/utls"
  27. "github.com/xtls/reality"
  28. "github.com/xtls/xray-core/common/errors"
  29. "github.com/xtls/xray-core/common/net"
  30. "github.com/xtls/xray-core/common/session"
  31. "github.com/xtls/xray-core/core"
  32. "github.com/xtls/xray-core/transport/internet/tls"
  33. "golang.org/x/crypto/chacha20poly1305"
  34. "golang.org/x/crypto/hkdf"
  35. "golang.org/x/net/http2"
  36. )
  37. //go:generate go run github.com/xtls/xray-core/common/errors/errorgen
  38. //go:linkname aesgcmPreferred github.com/refraction-networking/utls.aesgcmPreferred
  39. func aesgcmPreferred(ciphers []uint16) bool
  40. type Conn struct {
  41. *reality.Conn
  42. }
  43. func (c *Conn) HandshakeAddress() net.Address {
  44. if err := c.Handshake(); err != nil {
  45. return nil
  46. }
  47. state := c.ConnectionState()
  48. if state.ServerName == "" {
  49. return nil
  50. }
  51. return net.ParseAddress(state.ServerName)
  52. }
  53. func Server(c net.Conn, config *reality.Config) (net.Conn, error) {
  54. realityConn, err := reality.Server(context.Background(), c, config)
  55. return &Conn{Conn: realityConn}, err
  56. }
  57. type UConn struct {
  58. *utls.UConn
  59. ServerName string
  60. AuthKey []byte
  61. Verified bool
  62. }
  63. func (c *UConn) HandshakeAddress() net.Address {
  64. if err := c.Handshake(); err != nil {
  65. return nil
  66. }
  67. state := c.ConnectionState()
  68. if state.ServerName == "" {
  69. return nil
  70. }
  71. return net.ParseAddress(state.ServerName)
  72. }
  73. func (c *UConn) VerifyPeerCertificate(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error {
  74. p, _ := reflect.TypeOf(c.Conn).Elem().FieldByName("peerCertificates")
  75. certs := *(*([]*x509.Certificate))(unsafe.Pointer(uintptr(unsafe.Pointer(c.Conn)) + p.Offset))
  76. if pub, ok := certs[0].PublicKey.(ed25519.PublicKey); ok {
  77. h := hmac.New(sha512.New, c.AuthKey)
  78. h.Write(pub)
  79. if bytes.Equal(h.Sum(nil), certs[0].Signature) {
  80. c.Verified = true
  81. return nil
  82. }
  83. }
  84. opts := x509.VerifyOptions{
  85. DNSName: c.ServerName,
  86. Intermediates: x509.NewCertPool(),
  87. }
  88. for _, cert := range certs[1:] {
  89. opts.Intermediates.AddCert(cert)
  90. }
  91. if _, err := certs[0].Verify(opts); err != nil {
  92. return err
  93. }
  94. return nil
  95. }
  96. func UClient(c net.Conn, config *Config, ctx context.Context, dest net.Destination) (net.Conn, error) {
  97. localAddr := c.LocalAddr().String()
  98. uConn := &UConn{}
  99. utlsConfig := &utls.Config{
  100. VerifyPeerCertificate: uConn.VerifyPeerCertificate,
  101. ServerName: config.ServerName,
  102. InsecureSkipVerify: true,
  103. SessionTicketsDisabled: true,
  104. }
  105. if utlsConfig.ServerName == "" {
  106. utlsConfig.ServerName = dest.Address.String()
  107. }
  108. uConn.ServerName = utlsConfig.ServerName
  109. fingerprint := tls.GetFingerprint(config.Fingerprint)
  110. if fingerprint == nil {
  111. return nil, newError("REALITY: failed to get fingerprint").AtError()
  112. }
  113. uConn.UConn = utls.UClient(c, utlsConfig, *fingerprint)
  114. {
  115. uConn.BuildHandshakeState()
  116. hello := uConn.HandshakeState.Hello
  117. hello.SessionId = make([]byte, 32)
  118. copy(hello.Raw[39:], hello.SessionId) // the fixed location of `Session ID`
  119. hello.SessionId[0] = core.Version_x
  120. hello.SessionId[1] = core.Version_y
  121. hello.SessionId[2] = core.Version_z
  122. hello.SessionId[3] = 0 // reserved
  123. binary.BigEndian.PutUint32(hello.SessionId[4:], uint32(time.Now().Unix()))
  124. copy(hello.SessionId[8:], config.ShortId)
  125. if config.Show {
  126. newError(fmt.Sprintf("REALITY localAddr: %v\thello.SessionId[:16]: %v\n", localAddr, hello.SessionId[:16])).WriteToLog(session.ExportIDToError(ctx))
  127. }
  128. publicKey, _ := ecdh.X25519().NewPublicKey(config.PublicKey)
  129. uConn.AuthKey, _ = uConn.HandshakeState.State13.EcdheKey.ECDH(publicKey)
  130. if uConn.AuthKey == nil {
  131. return nil, errors.New("REALITY: SharedKey == nil")
  132. }
  133. if _, err := hkdf.New(sha256.New, uConn.AuthKey, hello.Random[:20], []byte("REALITY")).Read(uConn.AuthKey); err != nil {
  134. return nil, err
  135. }
  136. var aead cipher.AEAD
  137. if aesgcmPreferred(hello.CipherSuites) {
  138. block, _ := aes.NewCipher(uConn.AuthKey)
  139. aead, _ = cipher.NewGCM(block)
  140. } else {
  141. aead, _ = chacha20poly1305.New(uConn.AuthKey)
  142. }
  143. if config.Show {
  144. newError(fmt.Sprintf("REALITY localAddr: %v\tuConn.AuthKey[:16]: %v\tAEAD: %T\n", localAddr, uConn.AuthKey[:16], aead)).WriteToLog(session.ExportIDToError(ctx))
  145. }
  146. aead.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw)
  147. copy(hello.Raw[39:], hello.SessionId)
  148. }
  149. if err := uConn.HandshakeContext(ctx); err != nil {
  150. return nil, err
  151. }
  152. if config.Show {
  153. newError(fmt.Sprintf("REALITY localAddr: %v\tuConn.Verified: %v\n", localAddr, uConn.Verified)).WriteToLog(session.ExportIDToError(ctx))
  154. }
  155. if !uConn.Verified {
  156. go func() {
  157. client := &http.Client{
  158. Transport: &http2.Transport{
  159. DialTLSContext: func(ctx context.Context, network, addr string, cfg *gotls.Config) (net.Conn, error) {
  160. newError(fmt.Sprintf("REALITY localAddr: %v\tDialTLSContext\n", localAddr)).WriteToLog(session.ExportIDToError(ctx))
  161. return uConn, nil
  162. },
  163. },
  164. }
  165. prefix := []byte("https://" + uConn.ServerName)
  166. maps.Lock()
  167. if maps.maps == nil {
  168. maps.maps = make(map[string]map[string]bool)
  169. }
  170. paths := maps.maps[uConn.ServerName]
  171. if paths == nil {
  172. paths = make(map[string]bool)
  173. paths[config.SpiderX] = true
  174. maps.maps[uConn.ServerName] = paths
  175. }
  176. firstURL := string(prefix) + getPathLocked(paths)
  177. maps.Unlock()
  178. get := func(first bool) {
  179. var (
  180. req *http.Request
  181. resp *http.Response
  182. err error
  183. body []byte
  184. )
  185. if first {
  186. req, _ = http.NewRequest("GET", firstURL, nil)
  187. } else {
  188. maps.Lock()
  189. req, _ = http.NewRequest("GET", string(prefix)+getPathLocked(paths), nil)
  190. maps.Unlock()
  191. }
  192. req.Header.Set("User-Agent", fingerprint.Client) // TODO: User-Agent map
  193. if first && config.Show {
  194. newError(fmt.Sprintf("REALITY localAddr: %v\treq.UserAgent(): %v\n", localAddr, req.UserAgent())).WriteToLog(session.ExportIDToError(ctx))
  195. }
  196. times := 1
  197. if !first {
  198. times = int(randBetween(config.SpiderY[4], config.SpiderY[5]))
  199. }
  200. for j := 0; j < times; j++ {
  201. if !first && j == 0 {
  202. req.Header.Set("Referer", firstURL)
  203. }
  204. req.AddCookie(&http.Cookie{Name: "padding", Value: strings.Repeat("0", int(randBetween(config.SpiderY[0], config.SpiderY[1])))})
  205. if resp, err = client.Do(req); err != nil {
  206. break
  207. }
  208. req.Header.Set("Referer", req.URL.String())
  209. if body, err = io.ReadAll(resp.Body); err != nil {
  210. break
  211. }
  212. maps.Lock()
  213. for _, m := range href.FindAllSubmatch(body, -1) {
  214. m[1] = bytes.TrimPrefix(m[1], prefix)
  215. if !bytes.Contains(m[1], dot) {
  216. paths[string(m[1])] = true
  217. }
  218. }
  219. req.URL.Path = getPathLocked(paths)
  220. if config.Show {
  221. newError(fmt.Sprintf("REALITY localAddr: %v\treq.Referer(): %v\n", localAddr, req.Referer())).WriteToLog(session.ExportIDToError(ctx))
  222. newError(fmt.Sprintf("REALITY localAddr: %v\tlen(body): %v\n", localAddr, len(body))).WriteToLog(session.ExportIDToError(ctx))
  223. newError(fmt.Sprintf("REALITY localAddr: %v\tlen(paths): %v\n", localAddr, len(paths))).WriteToLog(session.ExportIDToError(ctx))
  224. }
  225. maps.Unlock()
  226. if !first {
  227. time.Sleep(time.Duration(randBetween(config.SpiderY[6], config.SpiderY[7])) * time.Millisecond) // interval
  228. }
  229. }
  230. }
  231. get(true)
  232. concurrency := int(randBetween(config.SpiderY[2], config.SpiderY[3]))
  233. for i := 0; i < concurrency; i++ {
  234. go get(false)
  235. }
  236. // Do not close the connection
  237. }()
  238. time.Sleep(time.Duration(randBetween(config.SpiderY[8], config.SpiderY[9])) * time.Millisecond) // return
  239. return nil, errors.New("REALITY: processed invalid connection")
  240. }
  241. return uConn, nil
  242. }
  243. var (
  244. href = regexp.MustCompile(`href="([/h].*?)"`)
  245. dot = []byte(".")
  246. )
  247. var maps struct {
  248. sync.Mutex
  249. maps map[string]map[string]bool
  250. }
  251. func getPathLocked(paths map[string]bool) string {
  252. stopAt := int(randBetween(0, int64(len(paths)-1)))
  253. i := 0
  254. for s := range paths {
  255. if i == stopAt {
  256. return s
  257. }
  258. i++
  259. }
  260. return "/"
  261. }
  262. func randBetween(left int64, right int64) int64 {
  263. if left == right {
  264. return left
  265. }
  266. bigInt, _ := rand.Int(rand.Reader, big.NewInt(right-left))
  267. return left + bigInt.Int64()
  268. }