Debian Codegraph @

record-layer.go

raw symbols SCIP
1 package mint
2
3 import (
4 "crypto/cipher"
5 "fmt"
6 "io"
7 "sync"
8 )
9
10 const (
11 sequenceNumberLen = 8 // sequence number length
12 recordHeaderLenTLS = 5 // record header length (TLS)
13 recordHeaderLenDTLS = 13 // record header length (DTLS)
14 maxFragmentLen = 1 << 14 // max number of bytes in a record
15 labelForKey = "key"
16 labelForIV = "iv"
17 )
18
19 type DecryptError string
20
21 func (err DecryptError) Error() string {
22 return string(err)
23 }
24
25 type Direction uint8
26
27 const (
28 DirectionWrite = Direction(1)
29 DirectionRead = Direction(2)
30 )
31
32 // struct {
33 // ContentType type;
34 // ProtocolVersion record_version [0301 for CH, 0303 for others]
35 // uint16 length;
36 // opaque fragment[TLSPlaintext.length];
37 // } TLSPlaintext;
38 type TLSPlaintext struct {
39 // Omitted: record_version (static)
40 // Omitted: length (computed from fragment)
41 contentType RecordType
42 epoch Epoch
43 seq uint64
44 fragment []byte
45 }
46
47 func NewTLSPlaintext(ct RecordType, epoch Epoch, fragment []byte) *TLSPlaintext {
48 return &TLSPlaintext{
49 contentType: ct,
50 epoch: epoch,
51 fragment: fragment,
52 }
53 }
54
55 func (t TLSPlaintext) Fragment() []byte {
56 return t.fragment
57 }
58
59 type cipherState struct {
60 epoch Epoch // DTLS epoch
61 ivLength int // Length of the seq and nonce fields
62 seq uint64 // Zero-padded sequence number
63 iv []byte // Buffer for the IV
64 cipher cipher.AEAD // AEAD cipher
65 }
66
67 type RecordLayerFactory interface {
68 NewLayer(conn io.ReadWriter, dir Direction) RecordLayer
69 }
70
71 type RecordLayer interface {
72 Lock()
73 Unlock()
74 SetVersion(v uint16)
75 SetLabel(s string)
76 Rekey(epoch Epoch, factory AEADFactory, keys *KeySet) error
77 ResetClear(seq uint64)
78 DiscardReadKey(epoch Epoch)
79 PeekRecordType(block bool) (RecordType, error)
80 ReadRecord() (*TLSPlaintext, error)
81 WriteRecord(pt *TLSPlaintext) error
82 Epoch() Epoch
83 }
84
85 type DefaultRecordLayer struct {
86 sync.Mutex
87 label string
88 direction Direction
89 version uint16 // The current version number
90 conn io.ReadWriter // The underlying connection
91 frame *frameReader // The buffered frame reader
92 nextData []byte // The next record to send
93 cachedRecord *TLSPlaintext // Last record read, cached to enable "peek"
94 cachedError error // Error on the last record read
95
96 cipher *cipherState
97 readCiphers map[Epoch]*cipherState
98
99 datagram bool
100 }
101
102 func (r *DefaultRecordLayer) Impl() *DefaultRecordLayer {
103 return r
104 }
105
106 type recordLayerFrameDetails struct {
107 datagram bool
108 }
109
110 func (d recordLayerFrameDetails) headerLen() int {
111 if d.datagram {
112 return recordHeaderLenDTLS
113 }
114 return recordHeaderLenTLS
115 }
116
117 func (d recordLayerFrameDetails) defaultReadLen() int {
118 return d.headerLen() + maxFragmentLen
119 }
120
121 func (d recordLayerFrameDetails) frameLen(hdr []byte) (int, error) {
122 return (int(hdr[d.headerLen()-2]) << 8) | int(hdr[d.headerLen()-1]), nil
123 }
124
125 func newCipherStateNull() *cipherState {
126 return &cipherState{EpochClear, 0, 0, nil, nil}
127 }
128
129 func newCipherStateAead(epoch Epoch, factory AEADFactory, key []byte, iv []byte) (*cipherState, error) {
130 cipher, err := factory(key)
131 if err != nil {
132 return nil, err
133 }
134
135 return &cipherState{epoch, len(iv), 0, iv, cipher}, nil
136 }
137
138 func NewRecordLayerTLS(conn io.ReadWriter, dir Direction) *DefaultRecordLayer {
139 r := DefaultRecordLayer{}
140 r.label = ""
141 r.direction = dir
142 r.conn = conn
143 r.frame = newFrameReader(recordLayerFrameDetails{false})
144 r.cipher = newCipherStateNull()
145 r.version = tls10Version
146 return &r
147 }
148
149 func NewRecordLayerDTLS(conn io.ReadWriter, dir Direction) *DefaultRecordLayer {
150 r := DefaultRecordLayer{}
151 r.label = ""
152 r.direction = dir
153 r.conn = conn
154 r.frame = newFrameReader(recordLayerFrameDetails{true})
155 r.cipher = newCipherStateNull()
156 r.readCiphers = make(map[Epoch]*cipherState, 0)
157 r.readCiphers[0] = r.cipher
158 r.datagram = true
159 return &r
160 }
161
162 func (r *DefaultRecordLayer) SetVersion(v uint16) {
163 r.version = v
164 }
165
166 func (r *DefaultRecordLayer) ResetClear(seq uint64) {
167 r.cipher = newCipherStateNull()
168 r.cipher.seq = seq
169 }
170
171 func (r *DefaultRecordLayer) Epoch() Epoch {
172 return r.cipher.epoch
173 }
174
175 func (r *DefaultRecordLayer) SetLabel(s string) {
176 r.label = s
177 }
178
179 func (r *DefaultRecordLayer) Rekey(epoch Epoch, factory AEADFactory, keys *KeySet) error {
180 cipher, err := newCipherStateAead(epoch, factory, keys.Keys[labelForKey], keys.Keys[labelForIV])
181 if err != nil {
182 return err
183 }
184 r.cipher = cipher
185 if r.datagram && r.direction == DirectionRead {
186 r.readCiphers[epoch] = cipher
187 }
188 return nil
189 }
190
191 // TODO([email protected]): This is never used, which is a bug.
192 func (r *DefaultRecordLayer) DiscardReadKey(epoch Epoch) {
193 if !r.datagram {
194 return
195 }
196
197 _, ok := r.readCiphers[epoch]
198 assert(ok)
199 delete(r.readCiphers, epoch)
200 }
201
202 func (c *cipherState) combineSeq(datagram bool) uint64 {
203 seq := c.seq
204 if datagram {
205 seq |= uint64(c.epoch) << 48
206 }
207 return seq
208 }
209
210 func (c *cipherState) computeNonce(seq uint64) []byte {
211 nonce := make([]byte, len(c.iv))
212 copy(nonce, c.iv)
213
214 s := seq
215
216 offset := len(c.iv)
217 for i := 0; i < 8; i++ {
218 nonce[(offset-i)-1] ^= byte(s & 0xff)
219 s >>= 8
220 }
221 logf(logTypeCrypto, "Computing nonce for sequence # %x -> %x", seq, nonce)
222
223 return nonce
224 }
225
226 func (c *cipherState) incrementSequenceNumber() {
227 if c.seq >= (1<<48 - 1) {
228 // Not allowed to let sequence number wrap.
229 // Instead, must renegotiate before it does.
230 // Not likely enough to bother. This is the
231 // DTLS limit.
232 panic("TLS: sequence number wraparound")
233 }
234 c.seq++
235 }
236
237 func (c *cipherState) overhead() int {
238 if c.cipher == nil {
239 return 0
240 }
241 return c.cipher.Overhead()
242 }
243
244 func (r *DefaultRecordLayer) encrypt(cipher *cipherState, seq uint64, header []byte, pt *TLSPlaintext, padLen int) []byte {
245 assert(r.direction == DirectionWrite)
246 logf(logTypeIO, "%s Encrypt seq=[%x]", r.label, seq)
247 // Expand the fragment to hold contentType, padding, and overhead
248 originalLen := len(pt.fragment)
249 plaintextLen := originalLen + 1 + padLen
250 ciphertextLen := plaintextLen + cipher.overhead()
251
252 ciphertext := make([]byte, ciphertextLen)
253 copy(ciphertext, pt.fragment)
254 ciphertext[originalLen] = byte(pt.contentType)
255 for i := 1; i <= padLen; i++ {
256 ciphertext[originalLen+i] = 0
257 }
258
259 // Encrypt the fragment
260 payload := ciphertext[:plaintextLen]
261 cipher.cipher.Seal(payload[:0], cipher.computeNonce(seq), payload, header)
262 return ciphertext
263 }
264
265 func (r *DefaultRecordLayer) decrypt(seq uint64, header []byte, pt *TLSPlaintext) (*TLSPlaintext, int, error) {
266 assert(r.direction == DirectionRead)
267 logf(logTypeIO, "%s Decrypt seq=[%x]", r.label, seq)
268 if len(pt.fragment) < r.cipher.overhead() {
269 msg := fmt.Sprintf("tls.record.decrypt: Record too short [%d] < [%d]", len(pt.fragment), r.cipher.overhead())
270 return nil, 0, DecryptError(msg)
271 }
272
273 decryptLen := len(pt.fragment) - r.cipher.overhead()
274 out := &TLSPlaintext{
275 contentType: pt.contentType,
276 fragment: make([]byte, decryptLen),
277 }
278
279 // Decrypt
280 _, err := r.cipher.cipher.Open(out.fragment[:0], r.cipher.computeNonce(seq), pt.fragment, header)
281 if err != nil {
282 logf(logTypeIO, "%s AEAD decryption failure [%x]", r.label, pt)
283 return nil, 0, DecryptError("tls.record.decrypt: AEAD decrypt failed")
284 }
285
286 // Find the padding boundary
287 padLen := 0
288 for ; padLen < decryptLen+1 && out.fragment[decryptLen-padLen-1] == 0; padLen++ {
289 }
290
291 // Transfer the content type
292 newLen := decryptLen - padLen - 1
293 out.contentType = RecordType(out.fragment[newLen])
294
295 // Truncate the message to remove contentType, padding, overhead
296 out.fragment = out.fragment[:newLen]
297 out.seq = seq
298 return out, padLen, nil
299 }
300
301 func (r *DefaultRecordLayer) PeekRecordType(block bool) (RecordType, error) {
302 var pt *TLSPlaintext
303 var err error
304
305 for {
306 pt, err = r.nextRecord(false)
307 if err == nil {
308 break
309 }
310 if !block || err != AlertWouldBlock {
311 return 0, err
312 }
313 }
314 return pt.contentType, nil
315 }
316
317 func (r *DefaultRecordLayer) ReadRecord() (*TLSPlaintext, error) {
318 pt, err := r.nextRecord(false)
319
320 // Consume the cached record if there was one
321 r.cachedRecord = nil
322 r.cachedError = nil
323
324 return pt, err
325 }
326
327 func (r *DefaultRecordLayer) ReadRecordAnyEpoch() (*TLSPlaintext, error) {
328 pt, err := r.nextRecord(true)
329
330 // Consume the cached record if there was one
331 r.cachedRecord = nil
332 r.cachedError = nil
333
334 return pt, err
335 }
336
337 func (r *DefaultRecordLayer) nextRecord(allowOldEpoch bool) (*TLSPlaintext, error) {
338 cipher := r.cipher
339 if r.cachedRecord != nil {
340 logf(logTypeIO, "%s Returning cached record", r.label)
341 return r.cachedRecord, r.cachedError
342 }
343
344 // Loop until one of three things happens:
345 //
346 // 1. We get a frame
347 // 2. We try to read off the socket and get nothing, in which case
348 // returnAlertWouldBlock
349 // 3. We get an error.
350 var err error
351 err = AlertWouldBlock
352 var header, body []byte
353
354 for err != nil {
355 if r.frame.needed() > 0 {
356 buf := make([]byte, r.frame.details.headerLen()+maxFragmentLen)
357 n, err := r.conn.Read(buf)
358 if err != nil {
359 logf(logTypeIO, "%s Error reading, %v", r.label, err)
360 return nil, err
361 }
362
363 if n == 0 {
364 return nil, AlertWouldBlock
365 }
366
367 logf(logTypeIO, "%s Read %v bytes", r.label, n)
368
369 buf = buf[:n]
370 r.frame.addChunk(buf)
371 }
372
373 header, body, err = r.frame.process()
374 // Loop around onAlertWouldBlock to see if some
375 // data is now available.
376 if err != nil && err != AlertWouldBlock {
377 return nil, err
378 }
379 }
380
381 pt := &TLSPlaintext{}
382 // Validate content type
383 switch RecordType(header[0]) {
384 default:
385 return nil, fmt.Errorf("tls.record: Unknown content type %02x", header[0])
386 case RecordTypeAlert, RecordTypeHandshake, RecordTypeApplicationData, RecordTypeAck:
387 pt.contentType = RecordType(header[0])
388 }
389
390 // Validate version
391 if !allowWrongVersionNumber && (header[1] != 0x03 || header[2] != 0x01) {
392 return nil, fmt.Errorf("tls.record: Invalid version %02x%02x", header[1], header[2])
393 }
394
395 // Validate size < max
396 size := (int(header[len(header)-2]) << 8) + int(header[len(header)-1])
397
398 if size > maxFragmentLen+256 {
399 return nil, fmt.Errorf("tls.record: Ciphertext size too big")
400 }
401
402 pt.fragment = make([]byte, size)
403 copy(pt.fragment, body)
404
405 // TODO([email protected]): Enforce that for epoch > 0, the content type is app data.
406
407 // Attempt to decrypt fragment
408 seq := cipher.seq
409 if r.datagram {
410 // TODO([email protected]): Handle duplicates.
411 seq, _ = decodeUint(header[3:11], 8)
412 epoch := Epoch(seq >> 48)
413
414 // Look up the cipher suite from the epoch
415 c, ok := r.readCiphers[epoch]
416 if !ok {
417 logf(logTypeIO, "%s Message from unknown epoch: [%v]", r.label, epoch)
418 return nil, AlertWouldBlock
419 }
420
421 if epoch != cipher.epoch {
422 logf(logTypeIO, "%s Message from non-current epoch: [%v != %v] out-of-epoch reads=%v", r.label, epoch,
423 cipher.epoch, allowOldEpoch)
424 if !allowOldEpoch {
425 return nil, AlertWouldBlock
426 }
427 cipher = c
428 }
429 }
430
431 if cipher.cipher != nil {
432 logf(logTypeIO, "%s RecordLayer.ReadRecord epoch=[%s] seq=[%x] [%d] ciphertext=[%x]", r.label, cipher.epoch.label(), seq, pt.contentType, pt.fragment)
433 pt, _, err = r.decrypt(seq, header, pt)
434 if err != nil {
435 logf(logTypeIO, "%s Decryption failed", r.label)
436 return nil, err
437 }
438 }
439 pt.epoch = cipher.epoch
440
441 // Check that plaintext length is not too long
442 if len(pt.fragment) > maxFragmentLen {
443 return nil, fmt.Errorf("tls.record: Plaintext size too big")
444 }
445
446 logf(logTypeIO, "%s RecordLayer.ReadRecord [%d] [%x]", r.label, pt.contentType, pt.fragment)
447
448 r.cachedRecord = pt
449 cipher.incrementSequenceNumber()
450 return pt, nil
451 }
452
453 func (r *DefaultRecordLayer) WriteRecord(pt *TLSPlaintext) error {
454 return r.writeRecordWithPadding(pt, r.cipher, 0)
455 }
456
457 func (r *DefaultRecordLayer) WriteRecordWithPadding(pt *TLSPlaintext, padLen int) error {
458 return r.writeRecordWithPadding(pt, r.cipher, padLen)
459 }
460
461 func (r *DefaultRecordLayer) writeRecordWithPadding(pt *TLSPlaintext, cipher *cipherState, padLen int) error {
462 seq := cipher.combineSeq(r.datagram)
463 length := len(pt.fragment)
464 var contentType RecordType
465 if cipher.cipher != nil {
466 length += 1 + padLen + cipher.cipher.Overhead()
467 contentType = RecordTypeApplicationData
468 } else {
469 contentType = pt.contentType
470 }
471 var header []byte
472
473 if !r.datagram {
474 header = []byte{byte(contentType),
475 byte(r.version >> 8), byte(r.version & 0xff),
476 byte(length >> 8), byte(length)}
477 } else {
478 header = make([]byte, 13)
479 version := dtlsConvertVersion(r.version)
480 copy(header, []byte{byte(contentType),
481 byte(version >> 8), byte(version & 0xff),
482 })
483 encodeUint(seq, 8, header[3:])
484 encodeUint(uint64(length), 2, header[11:])
485 }
486
487 var ciphertext []byte
488 if cipher.cipher != nil {
489 logf(logTypeIO, "%s RecordLayer.WriteRecord epoch=[%s] seq=[%x] [%d] plaintext=[%x]", r.label, cipher.epoch.label(), cipher.seq, pt.contentType, pt.fragment)
490 ciphertext = r.encrypt(cipher, seq, header, pt, padLen)
491 } else {
492 if padLen > 0 {
493 return fmt.Errorf("tls.record: Padding can only be done on encrypted records")
494 }
495 ciphertext = pt.fragment
496 }
497
498 if len(ciphertext) > maxFragmentLen {
499 return fmt.Errorf("tls.record: Record size too big")
500 }
501
502 record := append(header, ciphertext...)
503
504 logf(logTypeIO, "%s RecordLayer.WriteRecord epoch=[%s] seq=[%x] [%d] ciphertext=[%x]", r.label, cipher.epoch.label(), cipher.seq, contentType, ciphertext)
505
506 cipher.incrementSequenceNumber()
507 _, err := r.conn.Write(record)
508 return err
509 }