github.com/imannamdari/v2ray-core/v5@v5.0.5/common/protocol/quic/sniff.go (about)

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