sniff.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. package quic
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/aes"
  6. "crypto/tls"
  7. "encoding/binary"
  8. "io"
  9. "github.com/xtls/quic-go/quicvarint"
  10. "github.com/xtls/xray-core/common"
  11. "github.com/xtls/xray-core/common/buf"
  12. "github.com/xtls/xray-core/common/bytespool"
  13. "github.com/xtls/xray-core/common/errors"
  14. ptls "github.com/xtls/xray-core/common/protocol/tls"
  15. "golang.org/x/crypto/hkdf"
  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) (resultReturn *SniffHeader, errorReturn error) {
  43. // In extremely rare cases, this sniffer may cause slice error
  44. // and we set recover() here to prevent crash.
  45. // TODO: Thoroughly fix this panic
  46. defer func() {
  47. if r := recover(); r != nil {
  48. errors.LogError(context.Background(), "Failed to sniff QUIC: ", r)
  49. resultReturn = nil
  50. errorReturn = common.ErrNoClue
  51. }
  52. }()
  53. // Crypto data separated across packets
  54. cryptoLen := 0
  55. cryptoData := bytespool.Alloc(int32(len(b)))
  56. defer bytespool.Free(cryptoData)
  57. // Parse QUIC packets
  58. for len(b) > 0 {
  59. buffer := buf.FromBytes(b)
  60. typeByte, err := buffer.ReadByte()
  61. if err != nil {
  62. return nil, errNotQuic
  63. }
  64. isLongHeader := typeByte&0x80 > 0
  65. if !isLongHeader || typeByte&0x40 == 0 {
  66. return nil, errNotQuicInitial
  67. }
  68. vb, err := buffer.ReadBytes(4)
  69. if err != nil {
  70. return nil, errNotQuic
  71. }
  72. versionNumber := binary.BigEndian.Uint32(vb)
  73. if versionNumber != 0 && typeByte&0x40 == 0 {
  74. return nil, errNotQuic
  75. } else if versionNumber != versionDraft29 && versionNumber != version1 {
  76. return nil, errNotQuic
  77. }
  78. packetType := (typeByte & 0x30) >> 4
  79. isQuicInitial := packetType == 0x0
  80. var destConnID []byte
  81. if l, err := buffer.ReadByte(); err != nil {
  82. return nil, errNotQuic
  83. } else if destConnID, err = buffer.ReadBytes(int32(l)); err != nil {
  84. return nil, errNotQuic
  85. }
  86. if l, err := buffer.ReadByte(); err != nil {
  87. return nil, errNotQuic
  88. } else if common.Error2(buffer.ReadBytes(int32(l))) != nil {
  89. return nil, errNotQuic
  90. }
  91. tokenLen, err := quicvarint.Read(buffer)
  92. if err != nil || tokenLen > uint64(len(b)) {
  93. return nil, errNotQuic
  94. }
  95. if _, err = buffer.ReadBytes(int32(tokenLen)); err != nil {
  96. return nil, errNotQuic
  97. }
  98. packetLen, err := quicvarint.Read(buffer)
  99. if err != nil {
  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. origPNBytes := make([]byte, 4)
  112. copy(origPNBytes, b[hdrLen:hdrLen+4])
  113. var salt []byte
  114. if versionNumber == version1 {
  115. salt = quicSalt
  116. } else {
  117. salt = quicSaltOld
  118. }
  119. initialSecret := hkdf.Extract(crypto.SHA256.New, destConnID, salt)
  120. secret := hkdfExpandLabel(crypto.SHA256, initialSecret, []byte{}, "client in", crypto.SHA256.Size())
  121. hpKey := hkdfExpandLabel(initialSuite.Hash, secret, []byte{}, "quic hp", initialSuite.KeyLen)
  122. block, err := aes.NewCipher(hpKey)
  123. if err != nil {
  124. return nil, err
  125. }
  126. cache := buf.New()
  127. defer cache.Release()
  128. mask := cache.Extend(int32(block.BlockSize()))
  129. block.Encrypt(mask, b[hdrLen+4:hdrLen+4+16])
  130. b[0] ^= mask[0] & 0xf
  131. for i := range b[hdrLen : hdrLen+4] {
  132. b[hdrLen+i] ^= mask[i+1]
  133. }
  134. packetNumberLength := b[0]&0x3 + 1
  135. if packetNumberLength != 1 {
  136. return nil, errNotQuicInitial
  137. }
  138. var packetNumber uint32
  139. {
  140. n, err := buffer.ReadByte()
  141. if err != nil {
  142. return nil, err
  143. }
  144. packetNumber = uint32(n)
  145. }
  146. extHdrLen := hdrLen + int(packetNumberLength)
  147. copy(b[extHdrLen:hdrLen+4], origPNBytes[packetNumberLength:])
  148. data := b[extHdrLen : int(packetLen)+hdrLen]
  149. key := hkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic key", 16)
  150. iv := hkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic iv", 12)
  151. cipher := AEADAESGCMTLS13(key, iv)
  152. nonce := cache.Extend(int32(cipher.NonceSize()))
  153. binary.BigEndian.PutUint64(nonce[len(nonce)-8:], uint64(packetNumber))
  154. decrypted, err := cipher.Open(b[extHdrLen:extHdrLen], nonce, data, b[:extHdrLen])
  155. if err != nil {
  156. return nil, err
  157. }
  158. buffer = buf.FromBytes(decrypted)
  159. for i := 0; !buffer.IsEmpty(); i++ {
  160. frameType := byte(0x0) // Default to PADDING frame
  161. for frameType == 0x0 && !buffer.IsEmpty() {
  162. frameType, _ = buffer.ReadByte()
  163. }
  164. switch frameType {
  165. case 0x00: // PADDING frame
  166. case 0x01: // PING frame
  167. case 0x02, 0x03: // ACK frame
  168. if _, err = quicvarint.Read(buffer); err != nil { // Field: Largest Acknowledged
  169. return nil, io.ErrUnexpectedEOF
  170. }
  171. if _, err = quicvarint.Read(buffer); err != nil { // Field: ACK Delay
  172. return nil, io.ErrUnexpectedEOF
  173. }
  174. ackRangeCount, err := quicvarint.Read(buffer) // Field: ACK Range Count
  175. if err != nil {
  176. return nil, io.ErrUnexpectedEOF
  177. }
  178. if _, err = quicvarint.Read(buffer); err != nil { // Field: First ACK Range
  179. return nil, io.ErrUnexpectedEOF
  180. }
  181. for i := 0; i < int(ackRangeCount); i++ { // Field: ACK Range
  182. if _, err = quicvarint.Read(buffer); err != nil { // Field: ACK Range -> Gap
  183. return nil, io.ErrUnexpectedEOF
  184. }
  185. if _, err = quicvarint.Read(buffer); err != nil { // Field: ACK Range -> ACK Range Length
  186. return nil, io.ErrUnexpectedEOF
  187. }
  188. }
  189. if frameType == 0x03 {
  190. if _, err = quicvarint.Read(buffer); err != nil { // Field: ECN Counts -> ECT0 Count
  191. return nil, io.ErrUnexpectedEOF
  192. }
  193. if _, err = quicvarint.Read(buffer); err != nil { // Field: ECN Counts -> ECT1 Count
  194. return nil, io.ErrUnexpectedEOF
  195. }
  196. if _, err = quicvarint.Read(buffer); err != nil { //nolint:misspell // Field: ECN Counts -> ECT-CE Count
  197. return nil, io.ErrUnexpectedEOF
  198. }
  199. }
  200. case 0x06: // CRYPTO frame, we will use this frame
  201. offset, err := quicvarint.Read(buffer) // Field: Offset
  202. if err != nil {
  203. return nil, io.ErrUnexpectedEOF
  204. }
  205. length, err := quicvarint.Read(buffer) // Field: Length
  206. if err != nil || length > uint64(buffer.Len()) {
  207. return nil, io.ErrUnexpectedEOF
  208. }
  209. if cryptoLen < int(offset+length) {
  210. cryptoLen = int(offset + length)
  211. if len(cryptoData) < cryptoLen {
  212. newCryptoData := bytespool.Alloc(int32(cryptoLen))
  213. copy(newCryptoData, cryptoData)
  214. bytespool.Free(cryptoData)
  215. cryptoData = newCryptoData
  216. }
  217. }
  218. if _, err := buffer.Read(cryptoData[offset : offset+length]); err != nil { // Field: Crypto Data
  219. return nil, io.ErrUnexpectedEOF
  220. }
  221. case 0x1c: // CONNECTION_CLOSE frame, only 0x1c is permitted in initial packet
  222. if _, err = quicvarint.Read(buffer); err != nil { // Field: Error Code
  223. return nil, io.ErrUnexpectedEOF
  224. }
  225. if _, err = quicvarint.Read(buffer); err != nil { // Field: Frame Type
  226. return nil, io.ErrUnexpectedEOF
  227. }
  228. length, err := quicvarint.Read(buffer) // Field: Reason Phrase Length
  229. if err != nil {
  230. return nil, io.ErrUnexpectedEOF
  231. }
  232. if _, err := buffer.ReadBytes(int32(length)); err != nil { // Field: Reason Phrase
  233. return nil, io.ErrUnexpectedEOF
  234. }
  235. default:
  236. // Only above frame types are permitted in initial packet.
  237. // See https://www.rfc-editor.org/rfc/rfc9000.html#section-17.2.2-8
  238. return nil, errNotQuicInitial
  239. }
  240. }
  241. tlsHdr := &ptls.SniffHeader{}
  242. err = ptls.ReadClientHello(cryptoData[:cryptoLen], tlsHdr)
  243. if err != nil {
  244. // The crypto data may have not been fully recovered in current packets,
  245. // So we continue to sniff rest packets.
  246. b = restPayload
  247. continue
  248. }
  249. return &SniffHeader{domain: tlsHdr.Domain()}, nil
  250. }
  251. return nil, common.ErrNoClue
  252. }
  253. func hkdfExpandLabel(hash crypto.Hash, secret, context []byte, label string, length int) []byte {
  254. b := make([]byte, 3, 3+6+len(label)+1+len(context))
  255. binary.BigEndian.PutUint16(b, uint16(length))
  256. b[2] = uint8(6 + len(label))
  257. b = append(b, []byte("tls13 ")...)
  258. b = append(b, []byte(label)...)
  259. b = b[:3+6+len(label)+1]
  260. b[3+6+len(label)] = uint8(len(context))
  261. b = append(b, context...)
  262. out := make([]byte, length)
  263. n, err := hkdf.Expand(hash.New, secret, b).Read(out)
  264. if err != nil || n != length {
  265. panic("quic: HKDF-Expand-Label invocation failed unexpectedly")
  266. }
  267. return out
  268. }