sniff.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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/errors"
  12. "github.com/xtls/xray-core/common/protocol"
  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. if len(b) == 0 {
  43. return nil, common.ErrNoClue
  44. }
  45. // Crypto data separated across packets
  46. cryptoLen := int32(0)
  47. cryptoDataBuf := buf.NewWithSize(32767)
  48. defer cryptoDataBuf.Release()
  49. cache := buf.New()
  50. defer cache.Release()
  51. // Parse QUIC packets
  52. for len(b) > 0 {
  53. buffer := buf.FromBytes(b)
  54. typeByte, err := buffer.ReadByte()
  55. if err != nil {
  56. return nil, errNotQuic
  57. }
  58. isLongHeader := typeByte&0x80 > 0
  59. if !isLongHeader || typeByte&0x40 == 0 {
  60. return nil, errNotQuicInitial
  61. }
  62. vb, err := buffer.ReadBytes(4)
  63. if err != nil {
  64. return nil, errNotQuic
  65. }
  66. versionNumber := binary.BigEndian.Uint32(vb)
  67. if versionNumber != 0 && typeByte&0x40 == 0 {
  68. return nil, errNotQuic
  69. } else if versionNumber != versionDraft29 && versionNumber != version1 {
  70. return nil, errNotQuic
  71. }
  72. packetType := (typeByte & 0x30) >> 4
  73. isQuicInitial := packetType == 0x0
  74. var destConnID []byte
  75. if l, err := buffer.ReadByte(); err != nil {
  76. return nil, errNotQuic
  77. } else if destConnID, err = buffer.ReadBytes(int32(l)); err != nil {
  78. return nil, errNotQuic
  79. }
  80. if l, err := buffer.ReadByte(); err != nil {
  81. return nil, errNotQuic
  82. } else if common.Error2(buffer.ReadBytes(int32(l))) != nil {
  83. return nil, errNotQuic
  84. }
  85. if isQuicInitial { // Only initial packets have token, see https://datatracker.ietf.org/doc/html/rfc9000#section-17.2.2
  86. tokenLen, err := quicvarint.Read(buffer)
  87. if err != nil || tokenLen > uint64(len(b)) {
  88. return nil, errNotQuic
  89. }
  90. if _, err = buffer.ReadBytes(int32(tokenLen)); err != nil {
  91. return nil, errNotQuic
  92. }
  93. }
  94. packetLen, err := quicvarint.Read(buffer)
  95. if err != nil {
  96. return nil, errNotQuic
  97. }
  98. // packetLen is impossible to be shorter than this
  99. if packetLen < 4 {
  100. return nil, errNotQuic
  101. }
  102. hdrLen := len(b) - int(buffer.Len())
  103. if len(b) < hdrLen+int(packetLen) {
  104. return nil, common.ErrNoClue // Not enough data to read as a QUIC packet. QUIC is UDP-based, so this is unlikely to happen.
  105. }
  106. restPayload := b[hdrLen+int(packetLen):]
  107. if !isQuicInitial { // Skip this packet if it's not initial packet
  108. b = restPayload
  109. continue
  110. }
  111. var salt []byte
  112. if versionNumber == version1 {
  113. salt = quicSalt
  114. } else {
  115. salt = quicSaltOld
  116. }
  117. initialSecret := hkdf.Extract(crypto.SHA256.New, destConnID, salt)
  118. secret := hkdfExpandLabel(crypto.SHA256, initialSecret, []byte{}, "client in", crypto.SHA256.Size())
  119. hpKey := hkdfExpandLabel(initialSuite.Hash, secret, []byte{}, "quic hp", initialSuite.KeyLen)
  120. block, err := aes.NewCipher(hpKey)
  121. if err != nil {
  122. return nil, err
  123. }
  124. cache.Clear()
  125. mask := cache.Extend(int32(block.BlockSize()))
  126. block.Encrypt(mask, b[hdrLen+4:hdrLen+4+len(mask)])
  127. b[0] ^= mask[0] & 0xf
  128. packetNumberLength := int(b[0]&0x3 + 1)
  129. for i := range packetNumberLength {
  130. b[hdrLen+i] ^= mask[i+1]
  131. }
  132. key := hkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic key", 16)
  133. iv := hkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic iv", 12)
  134. cipher := AEADAESGCMTLS13(key, iv)
  135. nonce := cache.Extend(int32(cipher.NonceSize()))
  136. _, err = buffer.Read(nonce[len(nonce)-packetNumberLength:])
  137. if err != nil {
  138. return nil, err
  139. }
  140. extHdrLen := hdrLen + packetNumberLength
  141. data := b[extHdrLen : int(packetLen)+hdrLen]
  142. decrypted, err := cipher.Open(b[extHdrLen:extHdrLen], nonce, data, b[:extHdrLen])
  143. if err != nil {
  144. return nil, err
  145. }
  146. buffer = buf.FromBytes(decrypted)
  147. for !buffer.IsEmpty() {
  148. frameType, _ := buffer.ReadByte()
  149. for frameType == 0x0 && !buffer.IsEmpty() {
  150. frameType, _ = buffer.ReadByte()
  151. }
  152. switch frameType {
  153. case 0x00: // PADDING frame
  154. case 0x01: // PING frame
  155. case 0x02, 0x03: // ACK frame
  156. if _, err = quicvarint.Read(buffer); err != nil { // Field: Largest Acknowledged
  157. return nil, io.ErrUnexpectedEOF
  158. }
  159. if _, err = quicvarint.Read(buffer); err != nil { // Field: ACK Delay
  160. return nil, io.ErrUnexpectedEOF
  161. }
  162. ackRangeCount, err := quicvarint.Read(buffer) // Field: ACK Range Count
  163. if err != nil {
  164. return nil, io.ErrUnexpectedEOF
  165. }
  166. if _, err = quicvarint.Read(buffer); err != nil { // Field: First ACK Range
  167. return nil, io.ErrUnexpectedEOF
  168. }
  169. for i := 0; i < int(ackRangeCount); i++ { // Field: ACK Range
  170. if _, err = quicvarint.Read(buffer); err != nil { // Field: ACK Range -> Gap
  171. return nil, io.ErrUnexpectedEOF
  172. }
  173. if _, err = quicvarint.Read(buffer); err != nil { // Field: ACK Range -> ACK Range Length
  174. return nil, io.ErrUnexpectedEOF
  175. }
  176. }
  177. if frameType == 0x03 {
  178. if _, err = quicvarint.Read(buffer); err != nil { // Field: ECN Counts -> ECT0 Count
  179. return nil, io.ErrUnexpectedEOF
  180. }
  181. if _, err = quicvarint.Read(buffer); err != nil { // Field: ECN Counts -> ECT1 Count
  182. return nil, io.ErrUnexpectedEOF
  183. }
  184. if _, err = quicvarint.Read(buffer); err != nil { //nolint:misspell // Field: ECN Counts -> ECT-CE Count
  185. return nil, io.ErrUnexpectedEOF
  186. }
  187. }
  188. case 0x06: // CRYPTO frame, we will use this frame
  189. offset, err := quicvarint.Read(buffer) // Field: Offset
  190. if err != nil {
  191. return nil, io.ErrUnexpectedEOF
  192. }
  193. length, err := quicvarint.Read(buffer) // Field: Length
  194. if err != nil || length > uint64(buffer.Len()) {
  195. return nil, io.ErrUnexpectedEOF
  196. }
  197. currentCryptoLen := int32(offset + length)
  198. if cryptoLen < currentCryptoLen {
  199. if cryptoDataBuf.Cap() < currentCryptoLen {
  200. return nil, io.ErrShortBuffer
  201. }
  202. cryptoDataBuf.Extend(currentCryptoLen - cryptoLen)
  203. cryptoLen = currentCryptoLen
  204. }
  205. if _, err := buffer.Read(cryptoDataBuf.BytesRange(int32(offset), currentCryptoLen)); err != nil { // Field: Crypto Data
  206. return nil, io.ErrUnexpectedEOF
  207. }
  208. case 0x1c: // CONNECTION_CLOSE frame, only 0x1c is permitted in initial packet
  209. if _, err = quicvarint.Read(buffer); err != nil { // Field: Error Code
  210. return nil, io.ErrUnexpectedEOF
  211. }
  212. if _, err = quicvarint.Read(buffer); err != nil { // Field: Frame Type
  213. return nil, io.ErrUnexpectedEOF
  214. }
  215. length, err := quicvarint.Read(buffer) // Field: Reason Phrase Length
  216. if err != nil {
  217. return nil, io.ErrUnexpectedEOF
  218. }
  219. if _, err := buffer.ReadBytes(int32(length)); err != nil { // Field: Reason Phrase
  220. return nil, io.ErrUnexpectedEOF
  221. }
  222. default:
  223. // Only above frame types are permitted in initial packet.
  224. // See https://www.rfc-editor.org/rfc/rfc9000.html#section-17.2.2-8
  225. return nil, errNotQuicInitial
  226. }
  227. }
  228. tlsHdr := &ptls.SniffHeader{}
  229. err = ptls.ReadClientHello(cryptoDataBuf.BytesRange(0, cryptoLen), tlsHdr)
  230. if err != nil {
  231. // The crypto data may have not been fully recovered in current packets,
  232. // So we continue to sniff rest packets.
  233. b = restPayload
  234. continue
  235. }
  236. return &SniffHeader{domain: tlsHdr.Domain()}, nil
  237. }
  238. // All payload is parsed as valid QUIC packets, but we need more packets for crypto data to read client hello.
  239. return nil, protocol.ErrProtoNeedMoreData
  240. }
  241. func hkdfExpandLabel(hash crypto.Hash, secret, context []byte, label string, length int) []byte {
  242. b := make([]byte, 3, 3+6+len(label)+1+len(context))
  243. binary.BigEndian.PutUint16(b, uint16(length))
  244. b[2] = uint8(6 + len(label))
  245. b = append(b, []byte("tls13 ")...)
  246. b = append(b, []byte(label)...)
  247. b = b[:3+6+len(label)+1]
  248. b[3+6+len(label)] = uint8(len(context))
  249. b = append(b, context...)
  250. out := make([]byte, length)
  251. n, err := hkdf.Expand(hash.New, secret, b).Read(out)
  252. if err != nil || n != length {
  253. panic("quic: HKDF-Expand-Label invocation failed unexpectedly")
  254. }
  255. return out
  256. }