sniff.go 8.9 KB

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