-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
ssl_msg.c
5946 lines (5087 loc) · 199 KB
/
ssl_msg.c
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Generic SSL/TLS messaging layer functions
* (record layer + retransmission state machine)
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* The SSL 3.0 specification was drafted by Netscape in 1996,
* and became an IETF standard in 1999.
*
* http://wp.netscape.com/eng/ssl3/
* http://www.ietf.org/rfc/rfc2246.txt
* http://www.ietf.org/rfc/rfc4346.txt
*/
#include "common.h"
#if defined(MBEDTLS_SSL_TLS_C)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#include "mbedtls/ssl.h"
#include "mbedtls/ssl_internal.h"
#include "mbedtls/debug.h"
#include "mbedtls/error.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/version.h"
#include "ssl_invasive.h"
#include <string.h>
#if defined(MBEDTLS_USE_PSA_CRYPTO)
#include "mbedtls/psa_util.h"
#include "psa/crypto.h"
#endif
#if defined(MBEDTLS_X509_CRT_PARSE_C)
#include "mbedtls/oid.h"
#endif
static uint32_t ssl_get_hs_total_len( mbedtls_ssl_context const *ssl );
/*
* Start a timer.
* Passing millisecs = 0 cancels a running timer.
*/
void mbedtls_ssl_set_timer( mbedtls_ssl_context *ssl, uint32_t millisecs )
{
if( ssl->f_set_timer == NULL )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "set_timer to %d ms", (int) millisecs ) );
ssl->f_set_timer( ssl->p_timer, millisecs / 4, millisecs );
}
/*
* Return -1 is timer is expired, 0 if it isn't.
*/
int mbedtls_ssl_check_timer( mbedtls_ssl_context *ssl )
{
if( ssl->f_get_timer == NULL )
return( 0 );
if( ssl->f_get_timer( ssl->p_timer ) == 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "timer expired" ) );
return( -1 );
}
return( 0 );
}
#if defined(MBEDTLS_SSL_RECORD_CHECKING)
static int ssl_parse_record_header( mbedtls_ssl_context const *ssl,
unsigned char *buf,
size_t len,
mbedtls_record *rec );
int mbedtls_ssl_check_record( mbedtls_ssl_context const *ssl,
unsigned char *buf,
size_t buflen )
{
int ret = 0;
MBEDTLS_SSL_DEBUG_MSG( 1, ( "=> mbedtls_ssl_check_record" ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "record buffer", buf, buflen );
/* We don't support record checking in TLS because
* (a) there doesn't seem to be a usecase for it, and
* (b) In SSLv3 and TLS 1.0, CBC record decryption has state
* and we'd need to backup the transform here.
*/
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM )
{
ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
goto exit;
}
#if defined(MBEDTLS_SSL_PROTO_DTLS)
else
{
mbedtls_record rec;
ret = ssl_parse_record_header( ssl, buf, buflen, &rec );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 3, "ssl_parse_record_header", ret );
goto exit;
}
if( ssl->transform_in != NULL )
{
ret = mbedtls_ssl_decrypt_buf( ssl, ssl->transform_in, &rec );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 3, "mbedtls_ssl_decrypt_buf", ret );
goto exit;
}
}
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
exit:
/* On success, we have decrypted the buffer in-place, so make
* sure we don't leak any plaintext data. */
mbedtls_platform_zeroize( buf, buflen );
/* For the purpose of this API, treat messages with unexpected CID
* as well as such from future epochs as unexpected. */
if( ret == MBEDTLS_ERR_SSL_UNEXPECTED_CID ||
ret == MBEDTLS_ERR_SSL_EARLY_MESSAGE )
{
ret = MBEDTLS_ERR_SSL_UNEXPECTED_RECORD;
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "<= mbedtls_ssl_check_record" ) );
return( ret );
}
#endif /* MBEDTLS_SSL_RECORD_CHECKING */
#define SSL_DONT_FORCE_FLUSH 0
#define SSL_FORCE_FLUSH 1
#if defined(MBEDTLS_SSL_PROTO_DTLS)
/* Forward declarations for functions related to message buffering. */
static void ssl_buffering_free_slot( mbedtls_ssl_context *ssl,
uint8_t slot );
static void ssl_free_buffered_record( mbedtls_ssl_context *ssl );
static int ssl_load_buffered_message( mbedtls_ssl_context *ssl );
static int ssl_load_buffered_record( mbedtls_ssl_context *ssl );
static int ssl_buffer_message( mbedtls_ssl_context *ssl );
static int ssl_buffer_future_record( mbedtls_ssl_context *ssl,
mbedtls_record const *rec );
static int ssl_next_record_is_in_datagram( mbedtls_ssl_context *ssl );
static size_t ssl_get_maximum_datagram_size( mbedtls_ssl_context const *ssl )
{
size_t mtu = mbedtls_ssl_get_current_mtu( ssl );
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
size_t out_buf_len = ssl->out_buf_len;
#else
size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
#endif
if( mtu != 0 && mtu < out_buf_len )
return( mtu );
return( out_buf_len );
}
static int ssl_get_remaining_space_in_datagram( mbedtls_ssl_context const *ssl )
{
size_t const bytes_written = ssl->out_left;
size_t const mtu = ssl_get_maximum_datagram_size( ssl );
/* Double-check that the write-index hasn't gone
* past what we can transmit in a single datagram. */
if( bytes_written > mtu )
{
/* Should never happen... */
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
return( (int) ( mtu - bytes_written ) );
}
static int ssl_get_remaining_payload_in_datagram( mbedtls_ssl_context const *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t remaining, expansion;
size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
const size_t mfl = mbedtls_ssl_get_output_max_frag_len( ssl );
if( max_len > mfl )
max_len = mfl;
/* By the standard (RFC 6066 Sect. 4), the MFL extension
* only limits the maximum record payload size, so in theory
* we would be allowed to pack multiple records of payload size
* MFL into a single datagram. However, this would mean that there's
* no way to explicitly communicate MTU restrictions to the peer.
*
* The following reduction of max_len makes sure that we never
* write datagrams larger than MFL + Record Expansion Overhead.
*/
if( max_len <= ssl->out_left )
return( 0 );
max_len -= ssl->out_left;
#endif
ret = ssl_get_remaining_space_in_datagram( ssl );
if( ret < 0 )
return( ret );
remaining = (size_t) ret;
ret = mbedtls_ssl_get_record_expansion( ssl );
if( ret < 0 )
return( ret );
expansion = (size_t) ret;
if( remaining <= expansion )
return( 0 );
remaining -= expansion;
if( remaining >= max_len )
remaining = max_len;
return( (int) remaining );
}
/*
* Double the retransmit timeout value, within the allowed range,
* returning -1 if the maximum value has already been reached.
*/
static int ssl_double_retransmit_timeout( mbedtls_ssl_context *ssl )
{
uint32_t new_timeout;
if( ssl->handshake->retransmit_timeout >= ssl->conf->hs_timeout_max )
return( -1 );
/* Implement the final paragraph of RFC 6347 section 4.1.1.1
* in the following way: after the initial transmission and a first
* retransmission, back off to a temporary estimated MTU of 508 bytes.
* This value is guaranteed to be deliverable (if not guaranteed to be
* delivered) of any compliant IPv4 (and IPv6) network, and should work
* on most non-IP stacks too. */
if( ssl->handshake->retransmit_timeout != ssl->conf->hs_timeout_min )
{
ssl->handshake->mtu = 508;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "mtu autoreduction to %d bytes", ssl->handshake->mtu ) );
}
new_timeout = 2 * ssl->handshake->retransmit_timeout;
/* Avoid arithmetic overflow and range overflow */
if( new_timeout < ssl->handshake->retransmit_timeout ||
new_timeout > ssl->conf->hs_timeout_max )
{
new_timeout = ssl->conf->hs_timeout_max;
}
ssl->handshake->retransmit_timeout = new_timeout;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
ssl->handshake->retransmit_timeout ) );
return( 0 );
}
static void ssl_reset_retransmit_timeout( mbedtls_ssl_context *ssl )
{
ssl->handshake->retransmit_timeout = ssl->conf->hs_timeout_min;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "update timeout value to %d millisecs",
ssl->handshake->retransmit_timeout ) );
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
int (*mbedtls_ssl_hw_record_init)( mbedtls_ssl_context *ssl,
const unsigned char *key_enc, const unsigned char *key_dec,
size_t keylen,
const unsigned char *iv_enc, const unsigned char *iv_dec,
size_t ivlen,
const unsigned char *mac_enc, const unsigned char *mac_dec,
size_t maclen ) = NULL;
int (*mbedtls_ssl_hw_record_activate)( mbedtls_ssl_context *ssl, int direction) = NULL;
int (*mbedtls_ssl_hw_record_reset)( mbedtls_ssl_context *ssl ) = NULL;
int (*mbedtls_ssl_hw_record_write)( mbedtls_ssl_context *ssl ) = NULL;
int (*mbedtls_ssl_hw_record_read)( mbedtls_ssl_context *ssl ) = NULL;
int (*mbedtls_ssl_hw_record_finish)( mbedtls_ssl_context *ssl ) = NULL;
#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
/*
* Encryption/decryption functions
*/
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) || \
defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL)
static size_t ssl_compute_padding_length( size_t len,
size_t granularity )
{
return( ( granularity - ( len + 1 ) % granularity ) % granularity );
}
/* This functions transforms a (D)TLS plaintext fragment and a record content
* type into an instance of the (D)TLSInnerPlaintext structure. This is used
* in DTLS 1.2 + CID and within TLS 1.3 to allow flexible padding and to protect
* a record's content type.
*
* struct {
* opaque content[DTLSPlaintext.length];
* ContentType real_type;
* uint8 zeros[length_of_padding];
* } (D)TLSInnerPlaintext;
*
* Input:
* - `content`: The beginning of the buffer holding the
* plaintext to be wrapped.
* - `*content_size`: The length of the plaintext in Bytes.
* - `max_len`: The number of Bytes available starting from
* `content`. This must be `>= *content_size`.
* - `rec_type`: The desired record content type.
*
* Output:
* - `content`: The beginning of the resulting (D)TLSInnerPlaintext structure.
* - `*content_size`: The length of the resulting (D)TLSInnerPlaintext structure.
*
* Returns:
* - `0` on success.
* - A negative error code if `max_len` didn't offer enough space
* for the expansion.
*/
static int ssl_build_inner_plaintext( unsigned char *content,
size_t *content_size,
size_t remaining,
uint8_t rec_type,
size_t pad )
{
size_t len = *content_size;
/* Write real content type */
if( remaining == 0 )
return( -1 );
content[ len ] = rec_type;
len++;
remaining--;
if( remaining < pad )
return( -1 );
memset( content + len, 0, pad );
len += pad;
remaining -= pad;
*content_size = len;
return( 0 );
}
/* This function parses a (D)TLSInnerPlaintext structure.
* See ssl_build_inner_plaintext() for details. */
static int ssl_parse_inner_plaintext( unsigned char const *content,
size_t *content_size,
uint8_t *rec_type )
{
size_t remaining = *content_size;
/* Determine length of padding by skipping zeroes from the back. */
do
{
if( remaining == 0 )
return( -1 );
remaining--;
} while( content[ remaining ] == 0 );
*content_size = remaining;
*rec_type = content[ remaining ];
return( 0 );
}
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID ||
MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
/* `add_data` must have size 13 Bytes if the CID extension is disabled,
* and 13 + 1 + CID-length Bytes if the CID extension is enabled. */
static void ssl_extract_add_data_from_record( unsigned char* add_data,
size_t *add_data_len,
mbedtls_record *rec,
unsigned minor_ver )
{
/* Quoting RFC 5246 (TLS 1.2):
*
* additional_data = seq_num + TLSCompressed.type +
* TLSCompressed.version + TLSCompressed.length;
*
* For the CID extension, this is extended as follows
* (quoting draft-ietf-tls-dtls-connection-id-05,
* https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05):
*
* additional_data = seq_num + DTLSPlaintext.type +
* DTLSPlaintext.version +
* cid +
* cid_length +
* length_of_DTLSInnerPlaintext;
*
* For TLS 1.3, the record sequence number is dropped from the AAD
* and encoded within the nonce of the AEAD operation instead.
*/
unsigned char *cur = add_data;
#if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL)
if( minor_ver != MBEDTLS_SSL_MINOR_VERSION_4 )
#endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
{
((void) minor_ver);
memcpy( cur, rec->ctr, sizeof( rec->ctr ) );
cur += sizeof( rec->ctr );
}
*cur = rec->type;
cur++;
memcpy( cur, rec->ver, sizeof( rec->ver ) );
cur += sizeof( rec->ver );
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
if( rec->cid_len != 0 )
{
memcpy( cur, rec->cid, rec->cid_len );
cur += rec->cid_len;
*cur = rec->cid_len;
cur++;
cur[0] = ( rec->data_len >> 8 ) & 0xFF;
cur[1] = ( rec->data_len >> 0 ) & 0xFF;
cur += 2;
}
else
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
{
cur[0] = ( rec->data_len >> 8 ) & 0xFF;
cur[1] = ( rec->data_len >> 0 ) & 0xFF;
cur += 2;
}
*add_data_len = cur - add_data;
}
#if defined(MBEDTLS_SSL_PROTO_SSL3)
#define SSL3_MAC_MAX_BYTES 20 /* MD-5 or SHA-1 */
/*
* SSLv3.0 MAC functions
*/
static void ssl_mac( mbedtls_md_context_t *md_ctx,
const unsigned char *secret,
const unsigned char *buf, size_t len,
const unsigned char *ctr, int type,
unsigned char out[SSL3_MAC_MAX_BYTES] )
{
unsigned char header[11];
unsigned char padding[48];
int padlen;
int md_size = mbedtls_md_get_size( md_ctx->md_info );
int md_type = mbedtls_md_get_type( md_ctx->md_info );
/* Only MD5 and SHA-1 supported */
if( md_type == MBEDTLS_MD_MD5 )
padlen = 48;
else
padlen = 40;
memcpy( header, ctr, 8 );
header[ 8] = (unsigned char) type;
header[ 9] = (unsigned char)( len >> 8 );
header[10] = (unsigned char)( len );
memset( padding, 0x36, padlen );
mbedtls_md_starts( md_ctx );
mbedtls_md_update( md_ctx, secret, md_size );
mbedtls_md_update( md_ctx, padding, padlen );
mbedtls_md_update( md_ctx, header, 11 );
mbedtls_md_update( md_ctx, buf, len );
mbedtls_md_finish( md_ctx, out );
memset( padding, 0x5C, padlen );
mbedtls_md_starts( md_ctx );
mbedtls_md_update( md_ctx, secret, md_size );
mbedtls_md_update( md_ctx, padding, padlen );
mbedtls_md_update( md_ctx, out, md_size );
mbedtls_md_finish( md_ctx, out );
}
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
#if defined(MBEDTLS_GCM_C) || \
defined(MBEDTLS_CCM_C) || \
defined(MBEDTLS_CHACHAPOLY_C)
static int ssl_transform_aead_dynamic_iv_is_explicit(
mbedtls_ssl_transform const *transform )
{
return( transform->ivlen != transform->fixed_ivlen );
}
/* Compute IV := ( fixed_iv || 0 ) XOR ( 0 || dynamic_IV )
*
* Concretely, this occurs in two variants:
*
* a) Fixed and dynamic IV lengths add up to total IV length, giving
* IV = fixed_iv || dynamic_iv
*
* This variant is used in TLS 1.2 when used with GCM or CCM.
*
* b) Fixed IV lengths matches total IV length, giving
* IV = fixed_iv XOR ( 0 || dynamic_iv )
*
* This variant occurs in TLS 1.3 and for TLS 1.2 when using ChaChaPoly.
*
* See also the documentation of mbedtls_ssl_transform.
*
* This function has the precondition that
*
* dst_iv_len >= max( fixed_iv_len, dynamic_iv_len )
*
* which has to be ensured by the caller. If this precondition
* violated, the behavior of this function is undefined.
*/
static void ssl_build_record_nonce( unsigned char *dst_iv,
size_t dst_iv_len,
unsigned char const *fixed_iv,
size_t fixed_iv_len,
unsigned char const *dynamic_iv,
size_t dynamic_iv_len )
{
size_t i;
/* Start with Fixed IV || 0 */
memset( dst_iv, 0, dst_iv_len );
memcpy( dst_iv, fixed_iv, fixed_iv_len );
dst_iv += dst_iv_len - dynamic_iv_len;
for( i = 0; i < dynamic_iv_len; i++ )
dst_iv[i] ^= dynamic_iv[i];
}
#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */
int mbedtls_ssl_encrypt_buf( mbedtls_ssl_context *ssl,
mbedtls_ssl_transform *transform,
mbedtls_record *rec,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
mbedtls_cipher_mode_t mode;
int auth_done = 0;
unsigned char * data;
unsigned char add_data[13 + 1 + MBEDTLS_SSL_CID_OUT_LEN_MAX ];
size_t add_data_len;
size_t post_avail;
/* The SSL context is only used for debugging purposes! */
#if !defined(MBEDTLS_DEBUG_C)
ssl = NULL; /* make sure we don't use it except for debug */
((void) ssl);
#endif
/* The PRNG is used for dynamic IV generation that's used
* for CBC transformations in TLS 1.1 and TLS 1.2. */
#if !( defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC) && \
( defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2) ) )
((void) f_rng);
((void) p_rng);
#endif
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> encrypt buf" ) );
if( transform == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no transform provided to encrypt_buf" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( rec == NULL
|| rec->buf == NULL
|| rec->buf_len < rec->data_offset
|| rec->buf_len - rec->data_offset < rec->data_len
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
|| rec->cid_len != 0
#endif
)
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad record structure provided to encrypt_buf" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
data = rec->buf + rec->data_offset;
post_avail = rec->buf_len - ( rec->data_len + rec->data_offset );
MBEDTLS_SSL_DEBUG_BUF( 4, "before encrypt: output payload",
data, rec->data_len );
mode = mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc );
if( rec->data_len > MBEDTLS_SSL_OUT_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "Record content %u too large, maximum %d",
(unsigned) rec->data_len,
MBEDTLS_SSL_OUT_CONTENT_LEN ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
/* The following two code paths implement the (D)TLSInnerPlaintext
* structure present in TLS 1.3 and DTLS 1.2 + CID.
*
* See ssl_build_inner_plaintext() for more information.
*
* Note that this changes `rec->data_len`, and hence
* `post_avail` needs to be recalculated afterwards.
*
* Note also that the two code paths cannot occur simultaneously
* since they apply to different versions of the protocol. There
* is hence no risk of double-addition of the inner plaintext.
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL)
if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_4 )
{
size_t padding =
ssl_compute_padding_length( rec->data_len,
MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY );
if( ssl_build_inner_plaintext( data,
&rec->data_len,
post_avail,
rec->type,
padding ) != 0 )
{
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
rec->type = MBEDTLS_SSL_MSG_APPLICATION_DATA;
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
/*
* Add CID information
*/
rec->cid_len = transform->out_cid_len;
memcpy( rec->cid, transform->out_cid, transform->out_cid_len );
MBEDTLS_SSL_DEBUG_BUF( 3, "CID", rec->cid, rec->cid_len );
if( rec->cid_len != 0 )
{
size_t padding =
ssl_compute_padding_length( rec->data_len,
MBEDTLS_SSL_CID_PADDING_GRANULARITY );
/*
* Wrap plaintext into DTLSInnerPlaintext structure.
* See ssl_build_inner_plaintext() for more information.
*
* Note that this changes `rec->data_len`, and hence
* `post_avail` needs to be recalculated afterwards.
*/
if( ssl_build_inner_plaintext( data,
&rec->data_len,
post_avail,
rec->type,
padding ) != 0 )
{
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
rec->type = MBEDTLS_SSL_MSG_CID;
}
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
post_avail = rec->buf_len - ( rec->data_len + rec->data_offset );
/*
* Add MAC before if needed
*/
#if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
if( mode == MBEDTLS_MODE_STREAM ||
( mode == MBEDTLS_MODE_CBC
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
&& transform->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED
#endif
) )
{
if( post_avail < transform->maclen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
#if defined(MBEDTLS_SSL_PROTO_SSL3)
if( transform->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
unsigned char mac[SSL3_MAC_MAX_BYTES];
ssl_mac( &transform->md_ctx_enc, transform->mac_enc,
data, rec->data_len, rec->ctr, rec->type, mac );
memcpy( data + rec->data_len, mac, transform->maclen );
}
else
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
{
unsigned char mac[MBEDTLS_SSL_MAC_ADD];
ssl_extract_add_data_from_record( add_data, &add_data_len, rec,
transform->minor_ver );
mbedtls_md_hmac_update( &transform->md_ctx_enc, add_data,
add_data_len );
mbedtls_md_hmac_update( &transform->md_ctx_enc,
data, rec->data_len );
mbedtls_md_hmac_finish( &transform->md_ctx_enc, mac );
mbedtls_md_hmac_reset( &transform->md_ctx_enc );
memcpy( data + rec->data_len, mac, transform->maclen );
}
else
#endif
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_BUF( 4, "computed mac", data + rec->data_len,
transform->maclen );
rec->data_len += transform->maclen;
post_avail -= transform->maclen;
auth_done++;
}
#endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
/*
* Encrypt
*/
#if defined(MBEDTLS_ARC4_C) || defined(MBEDTLS_CIPHER_NULL_CIPHER)
if( mode == MBEDTLS_MODE_STREAM )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t olen;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
"including %d bytes of padding",
rec->data_len, 0 ) );
if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_enc,
transform->iv_enc, transform->ivlen,
data, rec->data_len,
data, &olen ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
return( ret );
}
if( rec->data_len != olen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
}
else
#endif /* MBEDTLS_ARC4_C || MBEDTLS_CIPHER_NULL_CIPHER */
#if defined(MBEDTLS_GCM_C) || \
defined(MBEDTLS_CCM_C) || \
defined(MBEDTLS_CHACHAPOLY_C)
if( mode == MBEDTLS_MODE_GCM ||
mode == MBEDTLS_MODE_CCM ||
mode == MBEDTLS_MODE_CHACHAPOLY )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char iv[12];
unsigned char *dynamic_iv;
size_t dynamic_iv_len;
int dynamic_iv_is_explicit =
ssl_transform_aead_dynamic_iv_is_explicit( transform );
/* Check that there's space for the authentication tag. */
if( post_avail < transform->taglen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
/*
* Build nonce for AEAD encryption.
*
* Note: In the case of CCM and GCM in TLS 1.2, the dynamic
* part of the IV is prepended to the ciphertext and
* can be chosen freely - in particular, it need not
* agree with the record sequence number.
* However, since ChaChaPoly as well as all AEAD modes
* in TLS 1.3 use the record sequence number as the
* dynamic part of the nonce, we uniformly use the
* record sequence number here in all cases.
*/
dynamic_iv = rec->ctr;
dynamic_iv_len = sizeof( rec->ctr );
ssl_build_record_nonce( iv, sizeof( iv ),
transform->iv_enc,
transform->fixed_ivlen,
dynamic_iv,
dynamic_iv_len );
/*
* Build additional data for AEAD encryption.
* This depends on the TLS version.
*/
ssl_extract_add_data_from_record( add_data, &add_data_len, rec,
transform->minor_ver );
MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (internal)",
iv, transform->ivlen );
MBEDTLS_SSL_DEBUG_BUF( 4, "IV used (transmitted)",
dynamic_iv,
dynamic_iv_is_explicit ? dynamic_iv_len : 0 );
MBEDTLS_SSL_DEBUG_BUF( 4, "additional data used for AEAD",
add_data, add_data_len );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
"including 0 bytes of padding",
rec->data_len ) );
/*
* Encrypt and authenticate
*/
if( ( ret = mbedtls_cipher_auth_encrypt( &transform->cipher_ctx_enc,
iv, transform->ivlen,
add_data, add_data_len, /* add data */
data, rec->data_len, /* source */
data, &rec->data_len, /* destination */
data + rec->data_len, transform->taglen ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_auth_encrypt", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_BUF( 4, "after encrypt: tag",
data + rec->data_len, transform->taglen );
/* Account for authentication tag. */
rec->data_len += transform->taglen;
post_avail -= transform->taglen;
/*
* Prefix record content with dynamic IV in case it is explicit.
*/
if( dynamic_iv_is_explicit != 0 )
{
if( rec->data_offset < dynamic_iv_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
memcpy( data - dynamic_iv_len, dynamic_iv, dynamic_iv_len );
rec->data_offset -= dynamic_iv_len;
rec->data_len += dynamic_iv_len;
}
auth_done++;
}
else
#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */
#if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC)
if( mode == MBEDTLS_MODE_CBC )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t padlen, i;
size_t olen;
/* Currently we're always using minimal padding
* (up to 255 bytes would be allowed). */
padlen = transform->ivlen - ( rec->data_len + 1 ) % transform->ivlen;
if( padlen == transform->ivlen )
padlen = 0;
/* Check there's enough space in the buffer for the padding. */
if( post_avail < padlen + 1 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
for( i = 0; i <= padlen; i++ )
data[rec->data_len + i] = (unsigned char) padlen;
rec->data_len += padlen + 1;
post_avail -= padlen + 1;
#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
/*
* Prepend per-record IV for block cipher in TLS v1.1 and up as per
* Method 1 (6.2.3.2. in RFC4346 and RFC5246)
*/
if( transform->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
{
if( f_rng == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "No PRNG provided to encrypt_record routine" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( rec->data_offset < transform->ivlen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "Buffer provided for encrypted record not large enough" ) );
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
}
/*
* Generate IV
*/
ret = f_rng( p_rng, transform->iv_enc, transform->ivlen );
if( ret != 0 )
return( ret );
memcpy( data - transform->ivlen, transform->iv_enc,
transform->ivlen );
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
MBEDTLS_SSL_DEBUG_MSG( 3, ( "before encrypt: msglen = %d, "
"including %d bytes of IV and %d bytes of padding",
rec->data_len, transform->ivlen,
padlen + 1 ) );
if( ( ret = mbedtls_cipher_crypt( &transform->cipher_ctx_enc,
transform->iv_enc,
transform->ivlen,
data, rec->data_len,
data, &olen ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_cipher_crypt", ret );
return( ret );
}
if( rec->data_len != olen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
if( transform->minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 )
{
/*
* Save IV in SSL3 and TLS1
*/
memcpy( transform->iv_enc, transform->cipher_ctx_enc.iv,
transform->ivlen );
}
else
#endif
{
data -= transform->ivlen;
rec->data_offset -= transform->ivlen;
rec->data_len += transform->ivlen;
}
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
if( auth_done == 0 )
{
unsigned char mac[MBEDTLS_SSL_MAC_ADD];
/*
* MAC(MAC_write_key, seq_num +
* TLSCipherText.type +
* TLSCipherText.version +
* length_of( (IV +) ENC(...) ) +
* IV + // except for TLS 1.0
* ENC(content + padding + padding_length));
*/
if( post_avail < transform->maclen)
{