1
2
3
4
5
6
7 package quic
8
9 import (
10 "crypto"
11 "crypto/aes"
12 "crypto/cipher"
13 "crypto/sha256"
14 "crypto/tls"
15 "errors"
16 "hash"
17
18 "golang.org/x/crypto/chacha20"
19 "golang.org/x/crypto/chacha20poly1305"
20 "golang.org/x/crypto/cryptobyte"
21 "golang.org/x/crypto/hkdf"
22 )
23
24 var errInvalidPacket = errors.New("quic: invalid packet")
25
26
27
28 const headerProtectionSampleSize = 16
29
30
31
32 const aeadOverhead = 16
33
34
35
36 type headerKey struct {
37 hp headerProtection
38 }
39
40 func (k headerKey) isSet() bool {
41 return k.hp != nil
42 }
43
44 func (k *headerKey) init(suite uint16, secret []byte) {
45 h, keySize := hashForSuite(suite)
46 hpKey := hkdfExpandLabel(h.New, secret, "quic hp", nil, keySize)
47 switch suite {
48 case tls.TLS_AES_128_GCM_SHA256, tls.TLS_AES_256_GCM_SHA384:
49 c, err := aes.NewCipher(hpKey)
50 if err != nil {
51 panic(err)
52 }
53 k.hp = &aesHeaderProtection{cipher: c}
54 case tls.TLS_CHACHA20_POLY1305_SHA256:
55 k.hp = chaCha20HeaderProtection{hpKey}
56 default:
57 panic("BUG: unknown cipher suite")
58 }
59 }
60
61
62
63 func (k headerKey) protect(hdr []byte, pnumOff int) {
64
65 pnumSize := int(hdr[0]&0x03) + 1
66 sample := hdr[pnumOff+4:][:headerProtectionSampleSize]
67 mask := k.hp.headerProtection(sample)
68 if isLongHeader(hdr[0]) {
69 hdr[0] ^= mask[0] & 0x0f
70 } else {
71 hdr[0] ^= mask[0] & 0x1f
72 }
73 for i := 0; i < pnumSize; i++ {
74 hdr[pnumOff+i] ^= mask[1+i]
75 }
76 }
77
78
79
80
81 func (k headerKey) unprotect(pkt []byte, pnumOff int, pnumMax packetNumber) (hdr, pay []byte, pnum packetNumber, _ error) {
82 if len(pkt) < pnumOff+4+headerProtectionSampleSize {
83 return nil, nil, 0, errInvalidPacket
84 }
85 numpay := pkt[pnumOff:]
86 sample := numpay[4:][:headerProtectionSampleSize]
87 mask := k.hp.headerProtection(sample)
88 if isLongHeader(pkt[0]) {
89 pkt[0] ^= mask[0] & 0x0f
90 } else {
91 pkt[0] ^= mask[0] & 0x1f
92 }
93 pnumLen := int(pkt[0]&0x03) + 1
94 pnum = packetNumber(0)
95 for i := 0; i < pnumLen; i++ {
96 numpay[i] ^= mask[1+i]
97 pnum = (pnum << 8) | packetNumber(numpay[i])
98 }
99 pnum = decodePacketNumber(pnumMax, pnum, pnumLen)
100 hdr = pkt[:pnumOff+pnumLen]
101 pay = numpay[pnumLen:]
102 return hdr, pay, pnum, nil
103 }
104
105
106
107
108
109
110
111 type headerProtection interface {
112 headerProtection(sample []byte) (mask [5]byte)
113 }
114
115
116
117 type aesHeaderProtection struct {
118 cipher cipher.Block
119 scratch [aes.BlockSize]byte
120 }
121
122 func (hp *aesHeaderProtection) headerProtection(sample []byte) (mask [5]byte) {
123 hp.cipher.Encrypt(hp.scratch[:], sample)
124 copy(mask[:], hp.scratch[:])
125 return mask
126 }
127
128
129
130 type chaCha20HeaderProtection struct {
131 key []byte
132 }
133
134 func (hp chaCha20HeaderProtection) headerProtection(sample []byte) (mask [5]byte) {
135 counter := uint32(sample[3])<<24 | uint32(sample[2])<<16 | uint32(sample[1])<<8 | uint32(sample[0])
136 nonce := sample[4:16]
137 c, err := chacha20.NewUnauthenticatedCipher(hp.key, nonce)
138 if err != nil {
139 panic(err)
140 }
141 c.SetCounter(counter)
142 c.XORKeyStream(mask[:], mask[:])
143 return mask
144 }
145
146
147
148 type packetKey struct {
149 aead cipher.AEAD
150 iv []byte
151 }
152
153 func (k *packetKey) init(suite uint16, secret []byte) {
154
155 h, keySize := hashForSuite(suite)
156 key := hkdfExpandLabel(h.New, secret, "quic key", nil, keySize)
157 switch suite {
158 case tls.TLS_AES_128_GCM_SHA256, tls.TLS_AES_256_GCM_SHA384:
159 k.aead = newAESAEAD(key)
160 case tls.TLS_CHACHA20_POLY1305_SHA256:
161 k.aead = newChaCha20AEAD(key)
162 default:
163 panic("BUG: unknown cipher suite")
164 }
165 k.iv = hkdfExpandLabel(h.New, secret, "quic iv", nil, k.aead.NonceSize())
166 }
167
168 func newAESAEAD(key []byte) cipher.AEAD {
169 c, err := aes.NewCipher(key)
170 if err != nil {
171 panic(err)
172 }
173 aead, err := cipher.NewGCM(c)
174 if err != nil {
175 panic(err)
176 }
177 return aead
178 }
179
180 func newChaCha20AEAD(key []byte) cipher.AEAD {
181 var err error
182 aead, err := chacha20poly1305.New(key)
183 if err != nil {
184 panic(err)
185 }
186 return aead
187 }
188
189 func (k packetKey) protect(hdr, pay []byte, pnum packetNumber) []byte {
190 k.xorIV(pnum)
191 defer k.xorIV(pnum)
192 return k.aead.Seal(hdr, k.iv, pay, hdr)
193 }
194
195 func (k packetKey) unprotect(hdr, pay []byte, pnum packetNumber) (dec []byte, err error) {
196 k.xorIV(pnum)
197 defer k.xorIV(pnum)
198 return k.aead.Open(pay[:0], k.iv, pay, hdr)
199 }
200
201
202 func (k packetKey) xorIV(pnum packetNumber) {
203 k.iv[len(k.iv)-8] ^= uint8(pnum >> 56)
204 k.iv[len(k.iv)-7] ^= uint8(pnum >> 48)
205 k.iv[len(k.iv)-6] ^= uint8(pnum >> 40)
206 k.iv[len(k.iv)-5] ^= uint8(pnum >> 32)
207 k.iv[len(k.iv)-4] ^= uint8(pnum >> 24)
208 k.iv[len(k.iv)-3] ^= uint8(pnum >> 16)
209 k.iv[len(k.iv)-2] ^= uint8(pnum >> 8)
210 k.iv[len(k.iv)-1] ^= uint8(pnum)
211 }
212
213
214
215
216
217 type fixedKeys struct {
218 hdr headerKey
219 pkt packetKey
220 }
221
222 func (k *fixedKeys) init(suite uint16, secret []byte) {
223 k.hdr.init(suite, secret)
224 k.pkt.init(suite, secret)
225 }
226
227 func (k fixedKeys) isSet() bool {
228 return k.hdr.hp != nil
229 }
230
231
232
233
234
235
236
237
238
239 func (k fixedKeys) protect(hdr, pay []byte, pnumOff int, pnum packetNumber) []byte {
240 pkt := k.pkt.protect(hdr, pay, pnum)
241 k.hdr.protect(pkt, pnumOff)
242 return pkt
243 }
244
245
246
247
248
249
250
251
252
253 func (k fixedKeys) unprotect(pkt []byte, pnumOff int, pnumMax packetNumber) (pay []byte, num packetNumber, err error) {
254 hdr, pay, pnum, err := k.hdr.unprotect(pkt, pnumOff, pnumMax)
255 if err != nil {
256 return nil, 0, err
257 }
258 pay, err = k.pkt.unprotect(hdr, pay, pnum)
259 if err != nil {
260 return nil, 0, err
261 }
262 return pay, pnum, nil
263 }
264
265
266 type fixedKeyPair struct {
267 r, w fixedKeys
268 }
269
270 func (k *fixedKeyPair) discard() {
271 *k = fixedKeyPair{}
272 }
273
274 func (k *fixedKeyPair) canRead() bool {
275 return k.r.isSet()
276 }
277
278 func (k *fixedKeyPair) canWrite() bool {
279 return k.w.isSet()
280 }
281
282
283
284
285
286 type updatingKeys struct {
287 suite uint16
288 hdr headerKey
289 pkt [2]packetKey
290 nextSecret []byte
291 }
292
293 func (k *updatingKeys) init(suite uint16, secret []byte) {
294 k.suite = suite
295 k.hdr.init(suite, secret)
296
297 k.pkt[1].init(suite, secret)
298 k.nextSecret = secret
299 k.update()
300 }
301
302
303
304
305
306 func (k *updatingKeys) update() {
307 k.nextSecret = updateSecret(k.suite, k.nextSecret)
308 k.pkt[0] = k.pkt[1]
309 k.pkt[1].init(k.suite, k.nextSecret)
310 }
311
312 func updateSecret(suite uint16, secret []byte) (nextSecret []byte) {
313 h, _ := hashForSuite(suite)
314 return hkdfExpandLabel(h.New, secret, "quic ku", nil, len(secret))
315 }
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338 type updatingKeyPair struct {
339 phase uint8
340 updating bool
341 authFailures int64
342 minSent packetNumber
343 minReceived packetNumber
344 updateAfter packetNumber
345 r, w updatingKeys
346 }
347
348 func (k *updatingKeyPair) init() {
349
350
351
352
353
354 k.updateAfter = 1000
355 }
356
357 func (k *updatingKeyPair) canRead() bool {
358 return k.r.hdr.hp != nil
359 }
360
361 func (k *updatingKeyPair) canWrite() bool {
362 return k.w.hdr.hp != nil
363 }
364
365
366 func (k *updatingKeyPair) handleAckFor(pnum packetNumber) {
367 if k.updating && pnum >= k.minSent {
368 k.updating = false
369 k.phase ^= keyPhaseBit
370 k.r.update()
371 k.w.update()
372 }
373 }
374
375
376
377
378 func (k *updatingKeyPair) needAckEliciting() bool {
379 return k.updating && k.minSent == maxPacketNumber
380 }
381
382
383
384 func (k *updatingKeyPair) protect(hdr, pay []byte, pnumOff int, pnum packetNumber) []byte {
385 var pkt []byte
386 if k.updating {
387 hdr[0] |= k.phase ^ keyPhaseBit
388 pkt = k.w.pkt[1].protect(hdr, pay, pnum)
389 k.minSent = min(pnum, k.minSent)
390 } else {
391 hdr[0] |= k.phase
392 pkt = k.w.pkt[0].protect(hdr, pay, pnum)
393 if pnum >= k.updateAfter {
394
395
396
397
398
399 k.updating = true
400 k.minSent = maxPacketNumber
401 k.minReceived = maxPacketNumber
402
403
404
405
406 k.updateAfter += (1 << 22)
407 }
408 }
409 k.w.hdr.protect(pkt, pnumOff)
410 return pkt
411 }
412
413
414
415 func (k *updatingKeyPair) unprotect(pkt []byte, pnumOff int, pnumMax packetNumber) (pay []byte, pnum packetNumber, err error) {
416 hdr, pay, pnum, err := k.r.hdr.unprotect(pkt, pnumOff, pnumMax)
417 if err != nil {
418 return nil, 0, err
419 }
420
421
422
423
424
425
426 if hdr[0]&keyPhaseBit == k.phase && (!k.updating || pnum < k.minReceived) {
427 pay, err = k.r.pkt[0].unprotect(hdr, pay, pnum)
428 } else {
429 pay, err = k.r.pkt[1].unprotect(hdr, pay, pnum)
430 if err == nil {
431 if !k.updating {
432
433 k.updating = true
434 k.minSent = maxPacketNumber
435 k.minReceived = pnum
436 } else {
437 k.minReceived = min(pnum, k.minReceived)
438 }
439 }
440 }
441 if err != nil {
442 k.authFailures++
443 if k.authFailures >= aeadIntegrityLimit(k.r.suite) {
444 return nil, 0, localTransportError{code: errAEADLimitReached}
445 }
446 return nil, 0, err
447 }
448 return pay, pnum, nil
449 }
450
451
452
453
454
455
456 func aeadIntegrityLimit(suite uint16) int64 {
457 switch suite {
458 case tls.TLS_AES_128_GCM_SHA256, tls.TLS_AES_256_GCM_SHA384:
459 return 1 << 52
460 case tls.TLS_CHACHA20_POLY1305_SHA256:
461 return 1 << 36
462 default:
463 panic("BUG: unknown cipher suite")
464 }
465 }
466
467
468 var initialSalt = []byte{0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a}
469
470
471
472
473
474
475
476 func initialKeys(cid []byte, side connSide) fixedKeyPair {
477 initialSecret := hkdf.Extract(sha256.New, cid, initialSalt)
478 var clientKeys fixedKeys
479 clientSecret := hkdfExpandLabel(sha256.New, initialSecret, "client in", nil, sha256.Size)
480 clientKeys.init(tls.TLS_AES_128_GCM_SHA256, clientSecret)
481 var serverKeys fixedKeys
482 serverSecret := hkdfExpandLabel(sha256.New, initialSecret, "server in", nil, sha256.Size)
483 serverKeys.init(tls.TLS_AES_128_GCM_SHA256, serverSecret)
484 if side == clientSide {
485 return fixedKeyPair{r: serverKeys, w: clientKeys}
486 } else {
487 return fixedKeyPair{w: serverKeys, r: clientKeys}
488 }
489 }
490
491
492 func checkCipherSuite(suite uint16) error {
493 switch suite {
494 case tls.TLS_AES_128_GCM_SHA256:
495 case tls.TLS_AES_256_GCM_SHA384:
496 case tls.TLS_CHACHA20_POLY1305_SHA256:
497 default:
498 return errors.New("invalid cipher suite")
499 }
500 return nil
501 }
502
503 func hashForSuite(suite uint16) (h crypto.Hash, keySize int) {
504 switch suite {
505 case tls.TLS_AES_128_GCM_SHA256:
506 return crypto.SHA256, 128 / 8
507 case tls.TLS_AES_256_GCM_SHA384:
508 return crypto.SHA384, 256 / 8
509 case tls.TLS_CHACHA20_POLY1305_SHA256:
510 return crypto.SHA256, chacha20.KeySize
511 default:
512 panic("BUG: unknown cipher suite")
513 }
514 }
515
516
517
518
519 func hkdfExpandLabel(hash func() hash.Hash, secret []byte, label string, context []byte, length int) []byte {
520 var hkdfLabel cryptobyte.Builder
521 hkdfLabel.AddUint16(uint16(length))
522 hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
523 b.AddBytes([]byte("tls13 "))
524 b.AddBytes([]byte(label))
525 })
526 hkdfLabel.AddUint8LengthPrefixed(func(b *cryptobyte.Builder) {
527 b.AddBytes(context)
528 })
529 out := make([]byte, length)
530 n, err := hkdf.Expand(hash, secret, hkdfLabel.BytesOrPanic()).Read(out)
531 if err != nil || n != length {
532 panic("quic: HKDF-Expand-Label invocation failed unexpectedly")
533 }
534 return out
535 }
536
View as plain text