github.com/xraypb/Xray-core@v1.8.1/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/quic-go/quic-go/quicvarint"
    11  	"github.com/xraypb/Xray-core/common"
    12  	"github.com/xraypb/Xray-core/common/buf"
    13  	"github.com/xraypb/Xray-core/common/errors"
    14  	ptls "github.com/xraypb/Xray-core/common/protocol/tls"
    15  	"golang.org/x/crypto/hkdf"
    16  )
    17  
    18  type SniffHeader struct {
    19  	domain string
    20  }
    21  
    22  func (s SniffHeader) Protocol() string {
    23  	return "quic"
    24  }
    25  
    26  func (s SniffHeader) Domain() string {
    27  	return s.domain
    28  }
    29  
    30  const (
    31  	versionDraft29 uint32 = 0xff00001d
    32  	version1       uint32 = 0x1
    33  )
    34  
    35  var (
    36  	quicSaltOld  = []byte{0xaf, 0xbf, 0xec, 0x28, 0x99, 0x93, 0xd2, 0x4c, 0x9e, 0x97, 0x86, 0xf1, 0x9c, 0x61, 0x11, 0xe0, 0x43, 0x90, 0xa8, 0x99}
    37  	quicSalt     = []byte{0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a}
    38  	initialSuite = &CipherSuiteTLS13{
    39  		ID:     tls.TLS_AES_128_GCM_SHA256,
    40  		KeyLen: 16,
    41  		AEAD:   AEADAESGCMTLS13,
    42  		Hash:   crypto.SHA256,
    43  	}
    44  	errNotQuic        = errors.New("not quic")
    45  	errNotQuicInitial = errors.New("not initial packet")
    46  )
    47  
    48  func SniffQUIC(b []byte) (*SniffHeader, error) {
    49  	buffer := buf.FromBytes(b)
    50  	typeByte, err := buffer.ReadByte()
    51  	if err != nil {
    52  		return nil, errNotQuic
    53  	}
    54  	isLongHeader := typeByte&0x80 > 0
    55  	if !isLongHeader || typeByte&0x40 == 0 {
    56  		return nil, errNotQuicInitial
    57  	}
    58  
    59  	vb, err := buffer.ReadBytes(4)
    60  	if err != nil {
    61  		return nil, errNotQuic
    62  	}
    63  
    64  	versionNumber := binary.BigEndian.Uint32(vb)
    65  
    66  	if versionNumber != 0 && typeByte&0x40 == 0 {
    67  		return nil, errNotQuic
    68  	} else if versionNumber != versionDraft29 && versionNumber != version1 {
    69  		return nil, errNotQuic
    70  	}
    71  
    72  	if (typeByte&0x30)>>4 != 0x0 {
    73  		return nil, errNotQuicInitial
    74  	}
    75  
    76  	var destConnID []byte
    77  	if l, err := buffer.ReadByte(); err != nil {
    78  		return nil, errNotQuic
    79  	} else if destConnID, err = buffer.ReadBytes(int32(l)); err != nil {
    80  		return nil, errNotQuic
    81  	}
    82  
    83  	if l, err := buffer.ReadByte(); err != nil {
    84  		return nil, errNotQuic
    85  	} else if common.Error2(buffer.ReadBytes(int32(l))) != nil {
    86  		return nil, errNotQuic
    87  	}
    88  
    89  	tokenLen, err := quicvarint.Read(buffer)
    90  	if err != nil || tokenLen > uint64(len(b)) {
    91  		return nil, errNotQuic
    92  	}
    93  
    94  	if _, err = buffer.ReadBytes(int32(tokenLen)); err != nil {
    95  		return nil, errNotQuic
    96  	}
    97  
    98  	packetLen, err := quicvarint.Read(buffer)
    99  	if err != nil {
   100  		return nil, errNotQuic
   101  	}
   102  
   103  	hdrLen := len(b) - int(buffer.Len())
   104  
   105  	origPNBytes := make([]byte, 4)
   106  	copy(origPNBytes, b[hdrLen:hdrLen+4])
   107  
   108  	var salt []byte
   109  	if versionNumber == version1 {
   110  		salt = quicSalt
   111  	} else {
   112  		salt = quicSaltOld
   113  	}
   114  	initialSecret := hkdf.Extract(crypto.SHA256.New, destConnID, salt)
   115  	secret := hkdfExpandLabel(crypto.SHA256, initialSecret, []byte{}, "client in", crypto.SHA256.Size())
   116  	hpKey := hkdfExpandLabel(initialSuite.Hash, secret, []byte{}, "quic hp", initialSuite.KeyLen)
   117  	block, err := aes.NewCipher(hpKey)
   118  	if err != nil {
   119  		return nil, err
   120  	}
   121  
   122  	cache := buf.New()
   123  	defer cache.Release()
   124  
   125  	mask := cache.Extend(int32(block.BlockSize()))
   126  	block.Encrypt(mask, b[hdrLen+4:hdrLen+4+16])
   127  	b[0] ^= mask[0] & 0xf
   128  	for i := range b[hdrLen : hdrLen+4] {
   129  		b[hdrLen+i] ^= mask[i+1]
   130  	}
   131  	packetNumberLength := b[0]&0x3 + 1
   132  	if packetNumberLength != 1 {
   133  		return nil, errNotQuicInitial
   134  	}
   135  	var packetNumber uint32
   136  	{
   137  		n, err := buffer.ReadByte()
   138  		if err != nil {
   139  			return nil, err
   140  		}
   141  		packetNumber = uint32(n)
   142  	}
   143  
   144  	if packetNumber != 0 {
   145  		return nil, errNotQuicInitial
   146  	}
   147  
   148  	extHdrLen := hdrLen + int(packetNumberLength)
   149  	copy(b[extHdrLen:hdrLen+4], origPNBytes[packetNumberLength:])
   150  	data := b[extHdrLen : int(packetLen)+hdrLen]
   151  
   152  	key := hkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic key", 16)
   153  	iv := hkdfExpandLabel(crypto.SHA256, secret, []byte{}, "quic iv", 12)
   154  	cipher := AEADAESGCMTLS13(key, iv)
   155  	nonce := cache.Extend(int32(cipher.NonceSize()))
   156  	binary.BigEndian.PutUint64(nonce[len(nonce)-8:], uint64(packetNumber))
   157  	decrypted, err := cipher.Open(b[extHdrLen:extHdrLen], nonce, data, b[:extHdrLen])
   158  	if err != nil {
   159  		return nil, err
   160  	}
   161  	buffer = buf.FromBytes(decrypted)
   162  	frameType, err := buffer.ReadByte()
   163  	if err != nil {
   164  		return nil, io.ErrUnexpectedEOF
   165  	}
   166  	if frameType != 0x6 {
   167  		// not crypto frame
   168  		return &SniffHeader{domain: ""}, nil
   169  	}
   170  	if common.Error2(quicvarint.Read(buffer)) != nil {
   171  		return nil, io.ErrUnexpectedEOF
   172  	}
   173  	dataLen, err := quicvarint.Read(buffer)
   174  	if err != nil {
   175  		return nil, io.ErrUnexpectedEOF
   176  	}
   177  	if dataLen > uint64(buffer.Len()) {
   178  		return nil, io.ErrUnexpectedEOF
   179  	}
   180  	frameData, err := buffer.ReadBytes(int32(dataLen))
   181  	common.Must(err)
   182  	tlsHdr := &ptls.SniffHeader{}
   183  	err = ptls.ReadClientHello(frameData, tlsHdr)
   184  	if err != nil {
   185  		return nil, err
   186  	}
   187  
   188  	return &SniffHeader{domain: tlsHdr.Domain()}, nil
   189  }
   190  
   191  func hkdfExpandLabel(hash crypto.Hash, secret, context []byte, label string, length int) []byte {
   192  	b := make([]byte, 3, 3+6+len(label)+1+len(context))
   193  	binary.BigEndian.PutUint16(b, uint16(length))
   194  	b[2] = uint8(6 + len(label))
   195  	b = append(b, []byte("tls13 ")...)
   196  	b = append(b, []byte(label)...)
   197  	b = b[:3+6+len(label)+1]
   198  	b[3+6+len(label)] = uint8(len(context))
   199  	b = append(b, context...)
   200  
   201  	out := make([]byte, length)
   202  	n, err := hkdf.Expand(hash.New, secret, b).Read(out)
   203  	if err != nil || n != length {
   204  		panic("quic: HKDF-Expand-Label invocation failed unexpectedly")
   205  	}
   206  	return out
   207  }