summary refs log tree commit diff
path: root/crypto/src/tls/RecordStream.cs
blob: a5926d05bf99d03c84722906b2357c30050ce024 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
using System;
using System.Diagnostics;
using System.IO;

using Org.BouncyCastle.Tls.Crypto;
using Org.BouncyCastle.Utilities;

namespace Org.BouncyCastle.Tls
{
    /// <summary>An implementation of the TLS 1.0/1.1/1.2 record layer.</summary>
    internal sealed class RecordStream
    {
        private const int DefaultPlaintextLimit = (1 << 14);

        private readonly Record m_inputRecord = new Record();
        private readonly SequenceNumber m_readSeqNo = new SequenceNumber(), m_writeSeqNo = new SequenceNumber();

        private readonly TlsProtocol m_handler;
        private readonly Stream m_input;
        private readonly Stream m_output;

        private TlsCipher m_pendingCipher = null;
        private TlsCipher m_readCipher = TlsNullNullCipher.Instance;
        private TlsCipher m_readCipherDeferred = null;
        private TlsCipher m_writeCipher = TlsNullNullCipher.Instance;

        private ProtocolVersion m_writeVersion = null;

        private int m_plaintextLimit = DefaultPlaintextLimit;
        private int m_ciphertextLimit = DefaultPlaintextLimit;
        private bool m_ignoreChangeCipherSpec = false;

        internal RecordStream(TlsProtocol handler, Stream input, Stream output)
        {
            this.m_handler = handler;
            this.m_input = input;
            this.m_output = output;
        }

        internal int PlaintextLimit
        {
            get { return m_plaintextLimit; }
        }

        internal void SetPlaintextLimit(int plaintextLimit)
        {
            this.m_plaintextLimit = plaintextLimit;
            this.m_ciphertextLimit = m_readCipher.GetCiphertextDecodeLimit(plaintextLimit);
        }

        internal void SetWriteVersion(ProtocolVersion writeVersion)
        {
            this.m_writeVersion = writeVersion;
        }

        internal void SetIgnoreChangeCipherSpec(bool ignoreChangeCipherSpec)
        {
            this.m_ignoreChangeCipherSpec = ignoreChangeCipherSpec;
        }

        internal void SetPendingCipher(TlsCipher tlsCipher)
        {
            this.m_pendingCipher = tlsCipher;
        }

        /// <exception cref="IOException"/>
        internal void NotifyChangeCipherSpecReceived()
        {
            if (m_pendingCipher == null)
                throw new TlsFatalAlert(AlertDescription.unexpected_message, "No pending cipher");

            EnablePendingCipherRead(false);
        }

        /// <exception cref="IOException"/>
        internal void EnablePendingCipherRead(bool deferred)
        {
            if (m_pendingCipher == null)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            if (m_readCipherDeferred != null)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            if (deferred)
            {
                this.m_readCipherDeferred = m_pendingCipher;
            }
            else
            {
                this.m_readCipher = m_pendingCipher;
                this.m_ciphertextLimit = m_readCipher.GetCiphertextDecodeLimit(m_plaintextLimit);
                m_readSeqNo.Reset();
            }
        }

        /// <exception cref="IOException"/>
        internal void EnablePendingCipherWrite()
        {
            if (m_pendingCipher == null)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            this.m_writeCipher = this.m_pendingCipher;
            m_writeSeqNo.Reset();
        }

        /// <exception cref="IOException"/>
        internal void FinaliseHandshake()
        {
            if (m_readCipher != m_pendingCipher || m_writeCipher != m_pendingCipher)
                throw new TlsFatalAlert(AlertDescription.handshake_failure);

            this.m_pendingCipher = null;
        }

        internal bool NeedsKeyUpdate()
        {
            return m_writeSeqNo.CurrentValue >= (1L << 20);
        }

        /// <exception cref="IOException"/>
        internal void NotifyKeyUpdateReceived()
        {
            m_readCipher.RekeyDecoder();
            m_readSeqNo.Reset();
        }

        /// <exception cref="IOException"/>
        internal void NotifyKeyUpdateSent()
        {
            m_writeCipher.RekeyEncoder();
            m_writeSeqNo.Reset();
        }

        /// <exception cref="IOException"/>
        internal RecordPreview PreviewRecordHeader(byte[] recordHeader)
        {
            short recordType = CheckRecordType(recordHeader, RecordFormat.TypeOffset);

            //ProtocolVersion recordVersion = TlsUtilities.ReadVersion(recordHeader, RecordFormat.VersionOffset);

            int length = TlsUtilities.ReadUint16(recordHeader, RecordFormat.LengthOffset);

            CheckLength(length, m_ciphertextLimit, AlertDescription.record_overflow);

            int recordSize = RecordFormat.FragmentOffset + length;
            int applicationDataLimit = 0;

            // NOTE: For TLS 1.3, this only MIGHT be application data
            if (ContentType.application_data == recordType && m_handler.IsApplicationDataReady)
            {
                applicationDataLimit = System.Math.Max(0, System.Math.Min(m_plaintextLimit,
                    m_readCipher.GetPlaintextLimit(length)));
            }

            return new RecordPreview(recordSize, applicationDataLimit);
        }

        internal RecordPreview PreviewOutputRecord(int contentLength)
        {
            int contentLimit = System.Math.Max(0, System.Math.Min(m_plaintextLimit, contentLength));
            int recordSize = PreviewOutputRecordSize(contentLimit);
            return new RecordPreview(recordSize, contentLimit);
        }

        internal int PreviewOutputRecordSize(int contentLength)
        {
            Debug.Assert(contentLength <= m_plaintextLimit);

            return RecordFormat.FragmentOffset + m_writeCipher.GetCiphertextEncodeLimit(contentLength, m_plaintextLimit);
        }

        /// <exception cref="IOException"/>
        internal bool ReadFullRecord(byte[] input, int inputOff, int inputLen)
        {
            if (inputLen < RecordFormat.FragmentOffset)
                return false;

            int length = TlsUtilities.ReadUint16(input, inputOff + RecordFormat.LengthOffset);
            if (inputLen != (RecordFormat.FragmentOffset + length))
                return false;

            short recordType = CheckRecordType(input, inputOff + RecordFormat.TypeOffset);

            ProtocolVersion recordVersion = TlsUtilities.ReadVersion(input, inputOff + RecordFormat.VersionOffset);

            CheckLength(length, m_ciphertextLimit, AlertDescription.record_overflow);

            if (m_ignoreChangeCipherSpec && ContentType.change_cipher_spec == recordType)
            {
                CheckChangeCipherSpec(input, inputOff + RecordFormat.FragmentOffset, length);
                return true;
            }

            TlsDecodeResult decoded = DecodeAndVerify(recordType, recordVersion, input,
                inputOff + RecordFormat.FragmentOffset, length);

            m_handler.ProcessRecord(decoded.contentType, decoded.buf, decoded.off, decoded.len);
            return true;
        }

        /// <exception cref="IOException"/>
        internal bool ReadRecord()
        {
            if (!m_inputRecord.ReadHeader(m_input))
                return false;

            short recordType = CheckRecordType(m_inputRecord.m_buf, RecordFormat.TypeOffset);

            ProtocolVersion recordVersion = TlsUtilities.ReadVersion(m_inputRecord.m_buf, RecordFormat.VersionOffset);

            int length = TlsUtilities.ReadUint16(m_inputRecord.m_buf, RecordFormat.LengthOffset);

            CheckLength(length, m_ciphertextLimit, AlertDescription.record_overflow);

            m_inputRecord.ReadFragment(m_input, length);

            TlsDecodeResult decoded;
            try
            {
                if (m_ignoreChangeCipherSpec && ContentType.change_cipher_spec == recordType)
                {
                    CheckChangeCipherSpec(m_inputRecord.m_buf, RecordFormat.FragmentOffset, length);
                    return true;
                }

                decoded = DecodeAndVerify(recordType, recordVersion, m_inputRecord.m_buf, RecordFormat.FragmentOffset,
                    length);
            }
            finally
            {
                m_inputRecord.Reset();
            }

            m_handler.ProcessRecord(decoded.contentType, decoded.buf, decoded.off, decoded.len);
            return true;
        }

        /// <exception cref="IOException"/>
        internal TlsDecodeResult DecodeAndVerify(short recordType, ProtocolVersion recordVersion, byte[] ciphertext,
            int off, int len)
        {
            long seqNo = m_readSeqNo.NextValue(AlertDescription.unexpected_message);
            TlsDecodeResult decoded = m_readCipher.DecodeCiphertext(seqNo, recordType, recordVersion, ciphertext, off,
                len);

            CheckLength(decoded.len, m_plaintextLimit, AlertDescription.record_overflow);

            /*
             * RFC 5246 6.2.1 Implementations MUST NOT send zero-length fragments of Handshake, Alert,
             * or ChangeCipherSpec content types.
             */
            if (decoded.len < 1 && decoded.contentType != ContentType.application_data)
                throw new TlsFatalAlert(AlertDescription.illegal_parameter);

            return decoded;
        }

        /// <exception cref="IOException"/>
        internal void WriteRecord(short contentType, byte[] plaintext, int plaintextOffset, int plaintextLength)
        {
#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
            WriteRecord(contentType, plaintext.AsSpan(plaintextOffset, plaintextLength));
#else
            // Never send anything until a valid ClientHello has been received
            if (m_writeVersion == null)
                return;

            /*
             * RFC 5246 6.2.1 The length should not exceed 2^14.
             */
            CheckLength(plaintextLength, m_plaintextLimit, AlertDescription.internal_error);

            /*
             * RFC 5246 6.2.1 Implementations MUST NOT send zero-length fragments of Handshake, Alert,
             * or ChangeCipherSpec content types.
             */
            if (plaintextLength < 1 && contentType != ContentType.application_data)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            long seqNo = m_writeSeqNo.NextValue(AlertDescription.internal_error);
            ProtocolVersion recordVersion = m_writeVersion;

            TlsEncodeResult encoded = m_writeCipher.EncodePlaintext(seqNo, contentType, recordVersion,
                RecordFormat.FragmentOffset, plaintext, plaintextOffset, plaintextLength);

            int ciphertextLength = encoded.len - RecordFormat.FragmentOffset;
            TlsUtilities.CheckUint16(ciphertextLength);

            TlsUtilities.WriteUint8(encoded.recordType, encoded.buf, encoded.off + RecordFormat.TypeOffset);
            TlsUtilities.WriteVersion(recordVersion, encoded.buf, encoded.off + RecordFormat.VersionOffset);
            TlsUtilities.WriteUint16(ciphertextLength, encoded.buf, encoded.off + RecordFormat.LengthOffset);

            // TODO[tls-port] Can we support interrupted IO on .NET?
            //try
            //{
                m_output.Write(encoded.buf, encoded.off, encoded.len);
            //}
            //catch (InterruptedIOException e)
            //{
            //    throw new TlsFatalAlert(AlertDescription.internal_error, e);
            //}

            m_output.Flush();
#endif
        }

#if NETCOREAPP2_1_OR_GREATER || NETSTANDARD2_1_OR_GREATER
        /// <exception cref="IOException"/>
        internal void WriteRecord(short contentType, ReadOnlySpan<byte> plaintext)
        {
            // Never send anything until a valid ClientHello has been received
            if (m_writeVersion == null)
                return;

            /*
             * RFC 5246 6.2.1 The length should not exceed 2^14.
             */
            CheckLength(plaintext.Length, m_plaintextLimit, AlertDescription.internal_error);

            /*
             * RFC 5246 6.2.1 Implementations MUST NOT send zero-length fragments of Handshake, Alert,
             * or ChangeCipherSpec content types.
             */
            if (plaintext.Length < 1 && contentType != ContentType.application_data)
                throw new TlsFatalAlert(AlertDescription.internal_error);

            long seqNo = m_writeSeqNo.NextValue(AlertDescription.internal_error);
            ProtocolVersion recordVersion = m_writeVersion;

            TlsEncodeResult encoded = m_writeCipher.EncodePlaintext(seqNo, contentType, recordVersion,
                RecordFormat.FragmentOffset, plaintext);

            int ciphertextLength = encoded.len - RecordFormat.FragmentOffset;
            TlsUtilities.CheckUint16(ciphertextLength);

            TlsUtilities.WriteUint8(encoded.recordType, encoded.buf, encoded.off + RecordFormat.TypeOffset);
            TlsUtilities.WriteVersion(recordVersion, encoded.buf, encoded.off + RecordFormat.VersionOffset);
            TlsUtilities.WriteUint16(ciphertextLength, encoded.buf, encoded.off + RecordFormat.LengthOffset);

            // TODO[tls-port] Can we support interrupted IO on .NET?
            //try
            //{
                m_output.Write(encoded.buf, encoded.off, encoded.len);
            //}
            //catch (InterruptedIOException e)
            //{
            //    throw new TlsFatalAlert(AlertDescription.internal_error, e);
            //}

            m_output.Flush();
        }
#endif

        /// <exception cref="IOException"/>
        internal void Close()
        {
            m_inputRecord.Reset();

            IOException io = null;
            try
            {
                Platform.Dispose(m_input);
            }
            catch (IOException e)
            {
                io = e;
            }

            try
            {
                Platform.Dispose(m_output);
            }
            catch (IOException e)
            {
                if (io == null)
                {
                    io = e;
                }
                else
                {
                    // TODO[tls] Available from JDK 7
                    //io.addSuppressed(e);
                }
            }

            if (io != null)
                throw io;
        }

        /// <exception cref="IOException"/>
        private void CheckChangeCipherSpec(byte[] buf, int off, int len)
        {
            if (1 != len || (byte)ChangeCipherSpec.change_cipher_spec != buf[off])
            {
                throw new TlsFatalAlert(AlertDescription.unexpected_message,
                    "Malformed " + ContentType.GetText(ContentType.change_cipher_spec));
            }
        }

        /// <exception cref="IOException"/>
        private short CheckRecordType(byte[] buf, int off)
        {
            short recordType = TlsUtilities.ReadUint8(buf, off);

            if (null != m_readCipherDeferred && recordType == ContentType.application_data)
            {
                this.m_readCipher = m_readCipherDeferred;
                this.m_readCipherDeferred = null;
                this.m_ciphertextLimit = m_readCipher.GetCiphertextDecodeLimit(m_plaintextLimit);
                m_readSeqNo.Reset();
            }
            else if (m_readCipher.UsesOpaqueRecordType)
            {
                if (ContentType.application_data != recordType)
                {
                    if (m_ignoreChangeCipherSpec && ContentType.change_cipher_spec == recordType)
                    {
                        // See RFC 8446 D.4.
                    }
                    else
                    {
                        throw new TlsFatalAlert(AlertDescription.unexpected_message,
                            "Opaque " + ContentType.GetText(recordType));
                    }
                }
            }
            else
            {
                switch (recordType)
                {
                case ContentType.application_data:
                {
                    if (!m_handler.IsApplicationDataReady)
                    {
                        throw new TlsFatalAlert(AlertDescription.unexpected_message,
                            "Not ready for " + ContentType.GetText(ContentType.application_data));
                    }
                    break;
                }
                case ContentType.alert:
                case ContentType.change_cipher_spec:
                case ContentType.handshake:
        //        case ContentType.heartbeat:
                    break;
                default:
                    throw new TlsFatalAlert(AlertDescription.unexpected_message,
                        "Unsupported " + ContentType.GetText(recordType));
                }
            }

            return recordType;
        }

        /// <exception cref="IOException"/>
        private static void CheckLength(int length, int limit, short alertDescription)
        {
            if (length > limit)
                throw new TlsFatalAlert(alertDescription);
        }

        private sealed class Record
        {
            private readonly byte[] m_header = new byte[RecordFormat.FragmentOffset];

            internal volatile byte[] m_buf;
            internal volatile int m_pos;

            internal Record()
            {
                this.m_buf = m_header;
                this.m_pos = 0;
            }

            /// <exception cref="IOException"/>
            internal void FillTo(Stream input, int length)
            {
                while (m_pos < length)
                {
                    // TODO[tls-port] Can we support interrupted IO on .NET?
                    //try
                    //{
                        int numRead = input.Read(m_buf, m_pos, length - m_pos);
                        if (numRead < 1)
                            break;

                        m_pos += numRead;
                    //}
                    //catch (InterruptedIOException e)
                    //{
                    //    /*
                    //     * Although modifying the bytesTransferred doesn't seem ideal, it's the simplest
                    //     * way to make sure we don't break client code that depends on the exact type,
                    //     * e.g. in Apache's httpcomponents-core-4.4.9, BHttpConnectionBase.isStale
                    //     * depends on the exception type being SocketTimeoutException (or a subclass).
                    //     *
                    //     * We can set to 0 here because the only relevant callstack (via
                    //     * TlsProtocol.readApplicationData) only ever processes one non-empty record (so
                    //     * interruption after partial output cannot occur).
                    //     */
                    //    m_pos += e.bytesTransferred;
                    //    e.bytesTransferred = 0;
                    //    throw e;
                    //}
                }
            }

            /// <exception cref="IOException"/>
            internal void ReadFragment(Stream input, int fragmentLength)
            {
                int recordLength = RecordFormat.FragmentOffset + fragmentLength;
                Resize(recordLength);
                FillTo(input, recordLength);
                if (m_pos < recordLength)
                    throw new EndOfStreamException();
            }

            /// <exception cref="IOException"/>
            internal bool ReadHeader(Stream input)
            {
                FillTo(input, RecordFormat.FragmentOffset);
                if (m_pos == 0)
                    return false;

                if (m_pos < RecordFormat.FragmentOffset)
                    throw new EndOfStreamException();

                return true;
            }

            internal void Reset()
            {
                m_buf = m_header;
                m_pos = 0;
            }

            private void Resize(int length)
            {
                if (m_buf.Length < length)
                {
                    byte[] tmp = new byte[length];
                    Array.Copy(m_buf, 0, tmp, 0, m_pos);
                    m_buf = tmp;
                }
            }
        }

        private sealed class SequenceNumber
        {
            private long m_value = 0L;
            private bool m_exhausted = false;

            internal long CurrentValue
            {
                get { lock (this) return m_value; }
            }

            /// <exception cref="TlsFatalAlert"/>
            internal long NextValue(short alertDescription)
            {
                lock (this)
                {
                    if (m_exhausted)
                        throw new TlsFatalAlert(alertDescription, "Sequence numbers exhausted");

                    long result = m_value;
                    if (++m_value == 0L)
                    {
                        this.m_exhausted = true;
                    }
                    return result;
                }
            }

            internal void Reset()
            {
                lock (this)
                {
                    this.m_value = 0L;
                    this.m_exhausted = false;
                }
            }
        }
    }
}