Source file src/vendor/golang.org/x/net/quic/packet_protection.go

     1  // Copyright 2023 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package quic
     6  
     7  import (
     8  	"crypto"
     9  	"crypto/aes"
    10  	"crypto/cipher"
    11  	"crypto/sha256"
    12  	"crypto/tls"
    13  	"errors"
    14  	"hash"
    15  
    16  	"golang.org/x/crypto/chacha20"
    17  	"golang.org/x/crypto/chacha20poly1305"
    18  	"golang.org/x/crypto/cryptobyte"
    19  	"golang.org/x/crypto/hkdf"
    20  )
    21  
    22  var errInvalidPacket = errors.New("quic: invalid packet")
    23  
    24  // headerProtectionSampleSize is the size of the ciphertext sample used for header protection.
    25  // https://www.rfc-editor.org/rfc/rfc9001#section-5.4.2
    26  const headerProtectionSampleSize = 16
    27  
    28  // aeadOverhead is the difference in size between the AEAD output and input.
    29  // All cipher suites defined for use with QUIC have 16 bytes of overhead.
    30  const aeadOverhead = 16
    31  
    32  // A headerKey applies or removes header protection.
    33  // https://www.rfc-editor.org/rfc/rfc9001#section-5.4
    34  type headerKey struct {
    35  	hp headerProtection
    36  }
    37  
    38  func (k headerKey) isSet() bool {
    39  	return k.hp != nil
    40  }
    41  
    42  func (k *headerKey) init(suite uint16, secret []byte) {
    43  	h, keySize := hashForSuite(suite)
    44  	hpKey := hkdfExpandLabel(h.New, secret, "quic hp", nil, keySize)
    45  	switch suite {
    46  	case tls.TLS_AES_128_GCM_SHA256, tls.TLS_AES_256_GCM_SHA384:
    47  		c, err := aes.NewCipher(hpKey)
    48  		if err != nil {
    49  			panic(err)
    50  		}
    51  		k.hp = &aesHeaderProtection{cipher: c}
    52  	case tls.TLS_CHACHA20_POLY1305_SHA256:
    53  		k.hp = chaCha20HeaderProtection{hpKey}
    54  	default:
    55  		panic("BUG: unknown cipher suite")
    56  	}
    57  }
    58  
    59  // protect applies header protection.
    60  // pnumOff is the offset of the packet number in the packet.
    61  func (k headerKey) protect(hdr []byte, pnumOff int) {
    62  	// Apply header protection.
    63  	pnumSize := int(hdr[0]&0x03) + 1
    64  	sample := hdr[pnumOff+4:][:headerProtectionSampleSize]
    65  	mask := k.hp.headerProtection(sample)
    66  	if isLongHeader(hdr[0]) {
    67  		hdr[0] ^= mask[0] & 0x0f
    68  	} else {
    69  		hdr[0] ^= mask[0] & 0x1f
    70  	}
    71  	for i := 0; i < pnumSize; i++ {
    72  		hdr[pnumOff+i] ^= mask[1+i]
    73  	}
    74  }
    75  
    76  // unprotect removes header protection.
    77  // pnumOff is the offset of the packet number in the packet.
    78  // pnumMax is the largest packet number seen in the number space of this packet.
    79  func (k headerKey) unprotect(pkt []byte, pnumOff int, pnumMax packetNumber) (hdr, pay []byte, pnum packetNumber, _ error) {
    80  	if len(pkt) < pnumOff+4+headerProtectionSampleSize {
    81  		return nil, nil, 0, errInvalidPacket
    82  	}
    83  	numpay := pkt[pnumOff:]
    84  	sample := numpay[4:][:headerProtectionSampleSize]
    85  	mask := k.hp.headerProtection(sample)
    86  	if isLongHeader(pkt[0]) {
    87  		pkt[0] ^= mask[0] & 0x0f
    88  	} else {
    89  		pkt[0] ^= mask[0] & 0x1f
    90  	}
    91  	pnumLen := int(pkt[0]&0x03) + 1
    92  	pnum = packetNumber(0)
    93  	for i := 0; i < pnumLen; i++ {
    94  		numpay[i] ^= mask[1+i]
    95  		pnum = (pnum << 8) | packetNumber(numpay[i])
    96  	}
    97  	pnum = decodePacketNumber(pnumMax, pnum, pnumLen)
    98  	hdr = pkt[:pnumOff+pnumLen]
    99  	pay = numpay[pnumLen:]
   100  	return hdr, pay, pnum, nil
   101  }
   102  
   103  // headerProtection is the  header_protection function as defined in:
   104  // https://www.rfc-editor.org/rfc/rfc9001#section-5.4.1
   105  //
   106  // This function takes a sample of the packet ciphertext
   107  // and returns a 5-byte mask which will be applied to the
   108  // protected portions of the packet header.
   109  type headerProtection interface {
   110  	headerProtection(sample []byte) (mask [5]byte)
   111  }
   112  
   113  // AES-based header protection.
   114  // https://www.rfc-editor.org/rfc/rfc9001#section-5.4.3
   115  type aesHeaderProtection struct {
   116  	cipher  cipher.Block
   117  	scratch [aes.BlockSize]byte
   118  }
   119  
   120  func (hp *aesHeaderProtection) headerProtection(sample []byte) (mask [5]byte) {
   121  	hp.cipher.Encrypt(hp.scratch[:], sample)
   122  	copy(mask[:], hp.scratch[:])
   123  	return mask
   124  }
   125  
   126  // ChaCha20-based header protection.
   127  // https://www.rfc-editor.org/rfc/rfc9001#section-5.4.4
   128  type chaCha20HeaderProtection struct {
   129  	key []byte
   130  }
   131  
   132  func (hp chaCha20HeaderProtection) headerProtection(sample []byte) (mask [5]byte) {
   133  	counter := uint32(sample[3])<<24 | uint32(sample[2])<<16 | uint32(sample[1])<<8 | uint32(sample[0])
   134  	nonce := sample[4:16]
   135  	c, err := chacha20.NewUnauthenticatedCipher(hp.key, nonce)
   136  	if err != nil {
   137  		panic(err)
   138  	}
   139  	c.SetCounter(counter)
   140  	c.XORKeyStream(mask[:], mask[:])
   141  	return mask
   142  }
   143  
   144  // A packetKey applies or removes packet protection.
   145  // https://www.rfc-editor.org/rfc/rfc9001#section-5.1
   146  type packetKey struct {
   147  	aead cipher.AEAD // AEAD function used for packet protection.
   148  	iv   []byte      // IV used to construct the AEAD nonce.
   149  }
   150  
   151  func (k *packetKey) init(suite uint16, secret []byte) {
   152  	// https://www.rfc-editor.org/rfc/rfc9001#section-5.1
   153  	h, keySize := hashForSuite(suite)
   154  	key := hkdfExpandLabel(h.New, secret, "quic key", nil, keySize)
   155  	switch suite {
   156  	case tls.TLS_AES_128_GCM_SHA256, tls.TLS_AES_256_GCM_SHA384:
   157  		k.aead = newAESAEAD(key)
   158  	case tls.TLS_CHACHA20_POLY1305_SHA256:
   159  		k.aead = newChaCha20AEAD(key)
   160  	default:
   161  		panic("BUG: unknown cipher suite")
   162  	}
   163  	k.iv = hkdfExpandLabel(h.New, secret, "quic iv", nil, k.aead.NonceSize())
   164  }
   165  
   166  func newAESAEAD(key []byte) cipher.AEAD {
   167  	c, err := aes.NewCipher(key)
   168  	if err != nil {
   169  		panic(err)
   170  	}
   171  	aead, err := cipher.NewGCM(c)
   172  	if err != nil {
   173  		panic(err)
   174  	}
   175  	return aead
   176  }
   177  
   178  func newChaCha20AEAD(key []byte) cipher.AEAD {
   179  	var err error
   180  	aead, err := chacha20poly1305.New(key)
   181  	if err != nil {
   182  		panic(err)
   183  	}
   184  	return aead
   185  }
   186  
   187  func (k packetKey) protect(hdr, pay []byte, pnum packetNumber) []byte {
   188  	k.xorIV(pnum)
   189  	defer k.xorIV(pnum)
   190  	return k.aead.Seal(hdr, k.iv, pay, hdr)
   191  }
   192  
   193  func (k packetKey) unprotect(hdr, pay []byte, pnum packetNumber) (dec []byte, err error) {
   194  	k.xorIV(pnum)
   195  	defer k.xorIV(pnum)
   196  	return k.aead.Open(pay[:0], k.iv, pay, hdr)
   197  }
   198  
   199  // xorIV xors the packet protection IV with the packet number.
   200  func (k packetKey) xorIV(pnum packetNumber) {
   201  	k.iv[len(k.iv)-8] ^= uint8(pnum >> 56)
   202  	k.iv[len(k.iv)-7] ^= uint8(pnum >> 48)
   203  	k.iv[len(k.iv)-6] ^= uint8(pnum >> 40)
   204  	k.iv[len(k.iv)-5] ^= uint8(pnum >> 32)
   205  	k.iv[len(k.iv)-4] ^= uint8(pnum >> 24)
   206  	k.iv[len(k.iv)-3] ^= uint8(pnum >> 16)
   207  	k.iv[len(k.iv)-2] ^= uint8(pnum >> 8)
   208  	k.iv[len(k.iv)-1] ^= uint8(pnum)
   209  }
   210  
   211  // A fixedKeys is a header protection key and fixed packet protection key.
   212  // The packet protection key is fixed (it does not update).
   213  //
   214  // Fixed keys are used for Initial and Handshake keys, which do not update.
   215  type fixedKeys struct {
   216  	hdr headerKey
   217  	pkt packetKey
   218  }
   219  
   220  func (k *fixedKeys) init(suite uint16, secret []byte) {
   221  	k.hdr.init(suite, secret)
   222  	k.pkt.init(suite, secret)
   223  }
   224  
   225  func (k fixedKeys) isSet() bool {
   226  	return k.hdr.hp != nil
   227  }
   228  
   229  // protect applies packet protection to a packet.
   230  //
   231  // On input, hdr contains the packet header, pay the unencrypted payload,
   232  // pnumOff the offset of the packet number in the header, and pnum the untruncated
   233  // packet number.
   234  //
   235  // protect returns the result of appending the encrypted payload to hdr and
   236  // applying header protection.
   237  func (k fixedKeys) protect(hdr, pay []byte, pnumOff int, pnum packetNumber) []byte {
   238  	pkt := k.pkt.protect(hdr, pay, pnum)
   239  	k.hdr.protect(pkt, pnumOff)
   240  	return pkt
   241  }
   242  
   243  // unprotect removes packet protection from a packet.
   244  //
   245  // On input, pkt contains the full protected packet, pnumOff the offset of
   246  // the packet number in the header, and pnumMax the largest packet number
   247  // seen in the number space of this packet.
   248  //
   249  // unprotect removes header protection from the header in pkt, and returns
   250  // the unprotected payload and packet number.
   251  func (k fixedKeys) unprotect(pkt []byte, pnumOff int, pnumMax packetNumber) (pay []byte, num packetNumber, err error) {
   252  	hdr, pay, pnum, err := k.hdr.unprotect(pkt, pnumOff, pnumMax)
   253  	if err != nil {
   254  		return nil, 0, err
   255  	}
   256  	pay, err = k.pkt.unprotect(hdr, pay, pnum)
   257  	if err != nil {
   258  		return nil, 0, err
   259  	}
   260  	return pay, pnum, nil
   261  }
   262  
   263  // A fixedKeyPair is a read/write pair of fixed keys.
   264  type fixedKeyPair struct {
   265  	r, w fixedKeys
   266  }
   267  
   268  func (k *fixedKeyPair) discard() {
   269  	*k = fixedKeyPair{}
   270  }
   271  
   272  func (k *fixedKeyPair) canRead() bool {
   273  	return k.r.isSet()
   274  }
   275  
   276  func (k *fixedKeyPair) canWrite() bool {
   277  	return k.w.isSet()
   278  }
   279  
   280  // An updatingKeys is a header protection key and updatable packet protection key.
   281  // updatingKeys are used for 1-RTT keys, where the packet protection key changes
   282  // over the lifetime of a connection.
   283  // https://www.rfc-editor.org/rfc/rfc9001#section-6
   284  type updatingKeys struct {
   285  	suite      uint16
   286  	hdr        headerKey
   287  	pkt        [2]packetKey // current, next
   288  	nextSecret []byte       // secret used to generate pkt[1]
   289  }
   290  
   291  func (k *updatingKeys) init(suite uint16, secret []byte) {
   292  	k.suite = suite
   293  	k.hdr.init(suite, secret)
   294  	// Initialize pkt[1] with secret_0, and then call update to generate secret_1.
   295  	k.pkt[1].init(suite, secret)
   296  	k.nextSecret = secret
   297  	k.update()
   298  }
   299  
   300  // update performs a key update.
   301  // The current key in pkt[0] is discarded.
   302  // The next key in pkt[1] becomes the current key.
   303  // A new next key is generated in pkt[1].
   304  func (k *updatingKeys) update() {
   305  	k.nextSecret = updateSecret(k.suite, k.nextSecret)
   306  	k.pkt[0] = k.pkt[1]
   307  	k.pkt[1].init(k.suite, k.nextSecret)
   308  }
   309  
   310  func updateSecret(suite uint16, secret []byte) (nextSecret []byte) {
   311  	h, _ := hashForSuite(suite)
   312  	return hkdfExpandLabel(h.New, secret, "quic ku", nil, len(secret))
   313  }
   314  
   315  // An updatingKeyPair is a read/write pair of updating keys.
   316  //
   317  // We keep two keys (current and next) in both read and write directions.
   318  // When an incoming packet's phase matches the current phase bit,
   319  // we unprotect it using the current keys; otherwise we use the next keys.
   320  //
   321  // When updating=false, outgoing packets are protected using the current phase.
   322  //
   323  // An update is initiated and updating is set to true when:
   324  //   - we decide to initiate a key update; or
   325  //   - we successfully unprotect a packet using the next keys,
   326  //     indicating the peer has initiated a key update.
   327  //
   328  // When updating=true, outgoing packets are protected using the next phase.
   329  // We do not change the current phase bit or generate new keys yet.
   330  //
   331  // The update concludes when we receive an ACK frame for a packet sent
   332  // with the next keys. At this time, we set updating to false, flip the
   333  // phase bit, and update the keys. This permits us to handle up to 1-RTT
   334  // of reordered packets before discarding the previous phase's keys after
   335  // an update.
   336  type updatingKeyPair struct {
   337  	phase        uint8 // current key phase (r.pkt[0], w.pkt[0])
   338  	updating     bool
   339  	authFailures int64        // total packet unprotect failures
   340  	minSent      packetNumber // min packet number sent since entering the updating state
   341  	minReceived  packetNumber // min packet number received in the next phase
   342  	updateAfter  packetNumber // packet number after which to initiate key update
   343  	r, w         updatingKeys
   344  }
   345  
   346  func (k *updatingKeyPair) init() {
   347  	// 1-RTT packets until the first key update.
   348  	//
   349  	// We perform the first key update early in the connection so a peer
   350  	// which does not support key updates will fail rapidly,
   351  	// rather than after the connection has been long established.
   352  	//
   353  	// The QUIC interop runner "keyupdate" test requires that the client
   354  	// initiate a key rotation early in the connection. Increasing this
   355  	// value may cause interop test failures; if we do want to increase it,
   356  	// we should either skip the keyupdate test or provide a way to override
   357  	// the setting in interop tests.
   358  	k.updateAfter = 100
   359  }
   360  
   361  func (k *updatingKeyPair) canRead() bool {
   362  	return k.r.hdr.hp != nil
   363  }
   364  
   365  func (k *updatingKeyPair) canWrite() bool {
   366  	return k.w.hdr.hp != nil
   367  }
   368  
   369  // handleAckFor finishes a key update after receiving an ACK for a packet in the next phase.
   370  func (k *updatingKeyPair) handleAckFor(pnum packetNumber) {
   371  	if k.updating && pnum >= k.minSent {
   372  		k.updating = false
   373  		k.phase ^= keyPhaseBit
   374  		k.r.update()
   375  		k.w.update()
   376  	}
   377  }
   378  
   379  // needAckEliciting reports whether we should send an ack-eliciting packet in the next phase.
   380  // The first packet sent in a phase is ack-eliciting, since the peer must acknowledge a
   381  // packet in the new phase for us to finish the update.
   382  func (k *updatingKeyPair) needAckEliciting() bool {
   383  	return k.updating && k.minSent == maxPacketNumber
   384  }
   385  
   386  // protect applies packet protection to a packet.
   387  // Parameters and returns are as for fixedKeyPair.protect.
   388  func (k *updatingKeyPair) protect(hdr, pay []byte, pnumOff int, pnum packetNumber) []byte {
   389  	var pkt []byte
   390  	if k.updating {
   391  		hdr[0] |= k.phase ^ keyPhaseBit
   392  		pkt = k.w.pkt[1].protect(hdr, pay, pnum)
   393  		k.minSent = min(pnum, k.minSent)
   394  	} else {
   395  		hdr[0] |= k.phase
   396  		pkt = k.w.pkt[0].protect(hdr, pay, pnum)
   397  		if pnum >= k.updateAfter {
   398  			// Initiate a key update, starting with the next packet we send.
   399  			//
   400  			// We do this after protecting the current packet
   401  			// to allow Conn.appendFrames to ensure that the first packet sent
   402  			// in the new phase is ack-eliciting.
   403  			k.updating = true
   404  			k.minSent = maxPacketNumber
   405  			k.minReceived = maxPacketNumber
   406  			// The lowest confidentiality limit for a supported AEAD is 2^23 packets.
   407  			// https://www.rfc-editor.org/rfc/rfc9001#section-6.6-5
   408  			//
   409  			// Schedule our next update for half that.
   410  			k.updateAfter += (1 << 22)
   411  		}
   412  	}
   413  	k.w.hdr.protect(pkt, pnumOff)
   414  	return pkt
   415  }
   416  
   417  // unprotect removes packet protection from a packet.
   418  // Parameters and returns are as for fixedKeyPair.unprotect.
   419  func (k *updatingKeyPair) unprotect(pkt []byte, pnumOff int, pnumMax packetNumber) (pay []byte, pnum packetNumber, err error) {
   420  	hdr, pay, pnum, err := k.r.hdr.unprotect(pkt, pnumOff, pnumMax)
   421  	if err != nil {
   422  		return nil, 0, err
   423  	}
   424  	// To avoid timing signals that might indicate the key phase bit is invalid,
   425  	// we always attempt to unprotect the packet with one key.
   426  	//
   427  	// If the key phase bit matches and the packet number doesn't come after
   428  	// the start of an in-progress update, use the current phase.
   429  	// Otherwise, use the next phase.
   430  	if hdr[0]&keyPhaseBit == k.phase && (!k.updating || pnum < k.minReceived) {
   431  		pay, err = k.r.pkt[0].unprotect(hdr, pay, pnum)
   432  	} else {
   433  		pay, err = k.r.pkt[1].unprotect(hdr, pay, pnum)
   434  		if err == nil {
   435  			if !k.updating {
   436  				// The peer has initiated a key update.
   437  				k.updating = true
   438  				k.minSent = maxPacketNumber
   439  				k.minReceived = pnum
   440  			} else {
   441  				k.minReceived = min(pnum, k.minReceived)
   442  			}
   443  		}
   444  	}
   445  	if err != nil {
   446  		k.authFailures++
   447  		if k.authFailures >= aeadIntegrityLimit(k.r.suite) {
   448  			return nil, 0, localTransportError{code: errAEADLimitReached}
   449  		}
   450  		return nil, 0, err
   451  	}
   452  	return pay, pnum, nil
   453  }
   454  
   455  // aeadIntegrityLimit returns the integrity limit for an AEAD:
   456  // The maximum number of received packets that may fail authentication
   457  // before closing the connection.
   458  //
   459  // https://www.rfc-editor.org/rfc/rfc9001#section-6.6-4
   460  func aeadIntegrityLimit(suite uint16) int64 {
   461  	switch suite {
   462  	case tls.TLS_AES_128_GCM_SHA256, tls.TLS_AES_256_GCM_SHA384:
   463  		return 1 << 52
   464  	case tls.TLS_CHACHA20_POLY1305_SHA256:
   465  		return 1 << 36
   466  	default:
   467  		panic("BUG: unknown cipher suite")
   468  	}
   469  }
   470  
   471  // https://www.rfc-editor.org/rfc/rfc9001#section-5.2-2
   472  var initialSalt = []byte{0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a}
   473  
   474  // initialKeys returns the keys used to protect Initial packets.
   475  //
   476  // The Initial packet keys are derived from the Destination Connection ID
   477  // field in the client's first Initial packet.
   478  //
   479  // https://www.rfc-editor.org/rfc/rfc9001#section-5.2
   480  func initialKeys(cid []byte, side connSide) fixedKeyPair {
   481  	initialSecret := hkdf.Extract(sha256.New, cid, initialSalt)
   482  	var clientKeys fixedKeys
   483  	clientSecret := hkdfExpandLabel(sha256.New, initialSecret, "client in", nil, sha256.Size)
   484  	clientKeys.init(tls.TLS_AES_128_GCM_SHA256, clientSecret)
   485  	var serverKeys fixedKeys
   486  	serverSecret := hkdfExpandLabel(sha256.New, initialSecret, "server in", nil, sha256.Size)
   487  	serverKeys.init(tls.TLS_AES_128_GCM_SHA256, serverSecret)
   488  	if side == clientSide {
   489  		return fixedKeyPair{r: serverKeys, w: clientKeys}
   490  	} else {
   491  		return fixedKeyPair{w: serverKeys, r: clientKeys}
   492  	}
   493  }
   494  
   495  // checkCipherSuite returns an error if suite is not a supported cipher suite.
   496  func checkCipherSuite(suite uint16) error {
   497  	switch suite {
   498  	case tls.TLS_AES_128_GCM_SHA256:
   499  	case tls.TLS_AES_256_GCM_SHA384:
   500  	case tls.TLS_CHACHA20_POLY1305_SHA256:
   501  	default:
   502  		return errors.New("invalid cipher suite")
   503  	}
   504  	return nil
   505  }
   506  
   507  func hashForSuite(suite uint16) (h crypto.Hash, keySize int) {
   508  	switch suite {
   509  	case tls.TLS_AES_128_GCM_SHA256:
   510  		return crypto.SHA256, 128 / 8
   511  	case tls.TLS_AES_256_GCM_SHA384:
   512  		return crypto.SHA384, 256 / 8
   513  	case tls.TLS_CHACHA20_POLY1305_SHA256:
   514  		return crypto.SHA256, chacha20.KeySize
   515  	default:
   516  		panic("BUG: unknown cipher suite")
   517  	}
   518  }
   519  
   520  // hkdfExpandLabel implements HKDF-Expand-Label from RFC 8446, Section 7.1.
   521  //
   522  // Copied from crypto/tls/key_schedule.go.
   523  func hkdfExpandLabel(hash func() hash.Hash, secret []byte, label string, context []byte, length int) []byte {
   524  	var hkdfLabel cryptobyte.Builder
   525  	hkdfLabel.AddUint16(uint16(length))
   526  	hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
   527  		b.AddBytes([]byte("tls13 "))
   528  		b.AddBytes([]byte(label))
   529  	})
   530  	hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
   531  		b.AddBytes(context)
   532  	})
   533  	out := make([]byte, length)
   534  	n, err := hkdf.Expand(hash, secret, hkdfLabel.BytesOrPanic()).Read(out)
   535  	if err != nil || n != length {
   536  		panic("quic: HKDF-Expand-Label invocation failed unexpectedly")
   537  	}
   538  	return out
   539  }
   540  

View as plain text