1
0

sniff.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package quic
  2. import (
  3. "crypto"
  4. "crypto/aes"
  5. "crypto/tls"
  6. "encoding/binary"
  7. "io"
  8. "github.com/quic-go/quic-go/quicvarint"
  9. "github.com/xtls/xray-core/common"
  10. "github.com/xtls/xray-core/common/buf"
  11. "github.com/xtls/xray-core/common/bytespool"
  12. "github.com/xtls/xray-core/common/errors"
  13. ptls "github.com/xtls/xray-core/common/protocol/tls"
  14. "golang.org/x/crypto/hkdf"
  15. )
  16. type SniffHeader struct {
  17. domain string
  18. }
  19. func (s SniffHeader) Protocol() string {
  20. return "quic"
  21. }
  22. func (s SniffHeader) Domain() string {
  23. return s.domain
  24. }
  25. const (
  26. versionDraft29 uint32 = 0xff00001d
  27. version1 uint32 = 0x1
  28. )
  29. var (
  30. quicSaltOld = []byte{0xaf, 0xbf, 0xec, 0x28, 0x99, 0x93, 0xd2, 0x4c, 0x9e, 0x97, 0x86, 0xf1, 0x9c, 0x61, 0x11, 0xe0, 0x43, 0x90, 0xa8, 0x99}
  31. quicSalt = []byte{0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a}
  32. initialSuite = &CipherSuiteTLS13{
  33. ID: tls.TLS_AES_128_GCM_SHA256,
  34. KeyLen: 16,
  35. AEAD: AEADAESGCMTLS13,
  36. Hash: crypto.SHA256,
  37. }
  38. errNotQuic = errors.New("not quic")
  39. errNotQuicInitial = errors.New("not initial packet")
  40. )
  41. func SniffQUIC(b []byte) (*SniffHeader, error) {
  42. buffer := buf.FromBytes(b)
  43. typeByte, err := buffer.ReadByte()
  44. if err != nil {
  45. return nil, errNotQuic
  46. }
  47. isLongHeader := typeByte&0x80 > 0
  48. if !isLongHeader || typeByte&0x40 == 0 {
  49. return nil, errNotQuicInitial
  50. }
  51. vb, err := buffer.ReadBytes(4)
  52. if err != nil {
  53. return nil, errNotQuic
  54. }
  55. versionNumber := binary.BigEndian.Uint32(vb)
  56. if versionNumber != 0 && typeByte&0x40 == 0 {
  57. return nil, errNotQuic
  58. } else if versionNumber != versionDraft29 && versionNumber != version1 {
  59. return nil, errNotQuic
  60. }
  61. if (typeByte&0x30)>>4 != 0x0 {
  62. return nil, errNotQuicInitial
  63. }
  64. var destConnID []byte
  65. if l, err := buffer.ReadByte(); err != nil {
  66. return nil, errNotQuic
  67. } else if destConnID, err = buffer.ReadBytes(int32(l)); err != nil {
  68. return nil, errNotQuic
  69. }
  70. if l, err := buffer.ReadByte(); err != nil {
  71. return nil, errNotQuic
  72. } else if common.Error2(buffer.ReadBytes(int32(l))) != nil {
  73. return nil, errNotQuic
  74. }
  75. tokenLen, err := quicvarint.Read(buffer)
  76. if err != nil || tokenLen > uint64(len(b)) {
  77. return nil, errNotQuic
  78. }
  79. if _, err = buffer.ReadBytes(int32(tokenLen)); err != nil {
  80. return nil, errNotQuic
  81. }
  82. packetLen, err := quicvarint.Read(buffer)
  83. if err != nil {
  84. return nil, errNotQuic
  85. }
  86. hdrLen := len(b) - int(buffer.Len())
  87. origPNBytes := make([]byte, 4)
  88. copy(origPNBytes, b[hdrLen:hdrLen+4])
  89. var salt []byte
  90. if versionNumber == version1 {
  91. salt = quicSalt
  92. } else {
  93. salt = quicSaltOld
  94. }
  95. initialSecret := hkdf.Extract(crypto.SHA256.New, destConnID, salt)
  96. secret := hkdfExpandLabel(crypto.SHA256, initialSecret, []byte{}, "client in", crypto.SHA256.Size())
  97. hpKey := hkdfExpandLabel(initialSuite.Hash, secret, []byte{}, "quic hp", initialSuite.KeyLen)
  98. block, err := aes.NewCipher(hpKey)
  99. if err != nil {
  100. return nil, err
  101. }
  102. cache := buf.New()
  103. defer cache.Release()
  104. mask := cache.Extend(int32(block.BlockSize()))
  105. block.Encrypt(mask, b[hdrLen+4:hdrLen+4+16])
  106. b[0] ^= mask[0] & 0xf
  107. for i := range b[hdrLen : hdrLen+4] {
  108. b[hdrLen+i] ^= mask[i+1]
  109. }
  110. packetNumberLength := b[0]&0x3 + 1
  111. if packetNumberLength != 1 {
  112. return nil, errNotQuicInitial
  113. }
  114. var packetNumber uint32
  115. {
  116. n, err := buffer.ReadByte()
  117. if err != nil {
  118. return nil, err
  119. }
  120. packetNumber = uint32(n)
  121. }
  122. if packetNumber != 0 && packetNumber != 1 {
  123. return nil, errNotQuicInitial
  124. }
  125. extHdrLen := hdrLen + int(packetNumberLength)
  126. copy(b[extHdrLen:hdrLen+4], origPNBytes[packetNumberLength:])
  127. data := b[extHdrLen : int(packetLen)+hdrLen]
  128. key := hkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic key", 16)
  129. iv := hkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic iv", 12)
  130. cipher := AEADAESGCMTLS13(key, iv)
  131. nonce := cache.Extend(int32(cipher.NonceSize()))
  132. binary.BigEndian.PutUint64(nonce[len(nonce)-8:], uint64(packetNumber))
  133. decrypted, err := cipher.Open(b[extHdrLen:extHdrLen], nonce, data, b[:extHdrLen])
  134. if err != nil {
  135. return nil, err
  136. }
  137. buffer = buf.FromBytes(decrypted)
  138. cryptoLen := uint(0)
  139. cryptoData := bytespool.Alloc(buffer.Len())
  140. defer bytespool.Free(cryptoData)
  141. for i := 0; !buffer.IsEmpty(); i++ {
  142. frameType := byte(0x0) // Default to PADDING frame
  143. for frameType == 0x0 && !buffer.IsEmpty() {
  144. frameType, _ = buffer.ReadByte()
  145. }
  146. switch frameType {
  147. case 0x00: // PADDING frame
  148. case 0x01: // PING frame
  149. case 0x02, 0x03: // ACK frame
  150. if _, err = quicvarint.Read(buffer); err != nil { // Field: Largest Acknowledged
  151. return nil, io.ErrUnexpectedEOF
  152. }
  153. if _, err = quicvarint.Read(buffer); err != nil { // Field: ACK Delay
  154. return nil, io.ErrUnexpectedEOF
  155. }
  156. ackRangeCount, err := quicvarint.Read(buffer) // Field: ACK Range Count
  157. if err != nil {
  158. return nil, io.ErrUnexpectedEOF
  159. }
  160. if _, err = quicvarint.Read(buffer); err != nil { // Field: First ACK Range
  161. return nil, io.ErrUnexpectedEOF
  162. }
  163. for i := 0; i < int(ackRangeCount); i++ { // Field: ACK Range
  164. if _, err = quicvarint.Read(buffer); err != nil { // Field: ACK Range -> Gap
  165. return nil, io.ErrUnexpectedEOF
  166. }
  167. if _, err = quicvarint.Read(buffer); err != nil { // Field: ACK Range -> ACK Range Length
  168. return nil, io.ErrUnexpectedEOF
  169. }
  170. }
  171. if frameType == 0x03 {
  172. if _, err = quicvarint.Read(buffer); err != nil { // Field: ECN Counts -> ECT0 Count
  173. return nil, io.ErrUnexpectedEOF
  174. }
  175. if _, err = quicvarint.Read(buffer); err != nil { // Field: ECN Counts -> ECT1 Count
  176. return nil, io.ErrUnexpectedEOF
  177. }
  178. if _, err = quicvarint.Read(buffer); err != nil { //nolint:misspell // Field: ECN Counts -> ECT-CE Count
  179. return nil, io.ErrUnexpectedEOF
  180. }
  181. }
  182. case 0x06: // CRYPTO frame, we will use this frame
  183. offset, err := quicvarint.Read(buffer) // Field: Offset
  184. if err != nil {
  185. return nil, io.ErrUnexpectedEOF
  186. }
  187. length, err := quicvarint.Read(buffer) // Field: Length
  188. if err != nil || length > uint64(buffer.Len()) {
  189. return nil, io.ErrUnexpectedEOF
  190. }
  191. if cryptoLen < uint(offset+length) {
  192. cryptoLen = uint(offset + length)
  193. }
  194. if _, err := buffer.Read(cryptoData[offset : offset+length]); err != nil { // Field: Crypto Data
  195. return nil, io.ErrUnexpectedEOF
  196. }
  197. case 0x1c: // CONNECTION_CLOSE frame, only 0x1c is permitted in initial packet
  198. if _, err = quicvarint.Read(buffer); err != nil { // Field: Error Code
  199. return nil, io.ErrUnexpectedEOF
  200. }
  201. if _, err = quicvarint.Read(buffer); err != nil { // Field: Frame Type
  202. return nil, io.ErrUnexpectedEOF
  203. }
  204. length, err := quicvarint.Read(buffer) // Field: Reason Phrase Length
  205. if err != nil {
  206. return nil, io.ErrUnexpectedEOF
  207. }
  208. if _, err := buffer.ReadBytes(int32(length)); err != nil { // Field: Reason Phrase
  209. return nil, io.ErrUnexpectedEOF
  210. }
  211. default:
  212. // Only above frame types are permitted in initial packet.
  213. // See https://www.rfc-editor.org/rfc/rfc9000.html#section-17.2.2-8
  214. return nil, errNotQuicInitial
  215. }
  216. }
  217. tlsHdr := &ptls.SniffHeader{}
  218. err = ptls.ReadClientHello(cryptoData[:cryptoLen], tlsHdr)
  219. if err != nil {
  220. return nil, err
  221. }
  222. return &SniffHeader{domain: tlsHdr.Domain()}, nil
  223. }
  224. func hkdfExpandLabel(hash crypto.Hash, secret, context []byte, label string, length int) []byte {
  225. b := make([]byte, 3, 3+6+len(label)+1+len(context))
  226. binary.BigEndian.PutUint16(b, uint16(length))
  227. b[2] = uint8(6 + len(label))
  228. b = append(b, []byte("tls13 ")...)
  229. b = append(b, []byte(label)...)
  230. b = b[:3+6+len(label)+1]
  231. b[3+6+len(label)] = uint8(len(context))
  232. b = append(b, context...)
  233. out := make([]byte, length)
  234. n, err := hkdf.Expand(hash.New, secret, b).Read(out)
  235. if err != nil || n != length {
  236. panic("quic: HKDF-Expand-Label invocation failed unexpectedly")
  237. }
  238. return out
  239. }