forked from Oryx-Embedded/CycloneSSL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tls_client.c
1944 lines (1692 loc) · 60.4 KB
/
tls_client.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
/**
* @file tls_client.c
* @brief Handshake message processing (TLS client)
*
* @section License
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* Copyright (C) 2010-2022 Oryx Embedded SARL. All rights reserved.
*
* This file is part of CycloneSSL Open.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @section Description
*
* The TLS protocol provides communications security over the Internet. The
* protocol allows client/server applications to communicate in a way that
* is designed to prevent eavesdropping, tampering, or message forgery
*
* @author Oryx Embedded SARL (www.oryx-embedded.com)
* @version 2.1.4
**/
//Switch to the appropriate trace level
#define TRACE_LEVEL TLS_TRACE_LEVEL
//Dependencies
#include <string.h>
#include "tls.h"
#include "tls_cipher_suites.h"
#include "tls_handshake.h"
#include "tls_client.h"
#include "tls_client_extensions.h"
#include "tls_client_misc.h"
#include "tls_common.h"
#include "tls_extensions.h"
#include "tls_certificate.h"
#include "tls_signature.h"
#include "tls_key_material.h"
#include "tls_transcript_hash.h"
#include "tls_record.h"
#include "tls_misc.h"
#include "tls13_client.h"
#include "tls13_client_extensions.h"
#include "tls13_client_misc.h"
#include "dtls_record.h"
#include "dtls_misc.h"
#include "pkix/pem_import.h"
#include "date_time.h"
#include "debug.h"
//Check TLS library configuration
#if (TLS_SUPPORT == ENABLED && TLS_CLIENT_SUPPORT == ENABLED)
/**
* @brief Send ClientHello message
*
* When a client first connects to a server, it is required to send
* the ClientHello as its first message. The client can also send a
* ClientHello in response to a HelloRequest or on its own initiative
* in order to renegotiate the security parameters in an existing
* connection
*
* @param[in] context Pointer to the TLS context
* @return Error code
**/
error_t tlsSendClientHello(TlsContext *context)
{
error_t error;
size_t length;
TlsClientHello *message;
//Point to the buffer where to format the message
message = (TlsClientHello *) (context->txBuffer + context->txBufferLen);
#if (DTLS_SUPPORT == ENABLED)
//DTLS protocol?
if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
{
//When sending the first ClientHello, the client does not have a cookie yet
if(context->cookieLen == 0)
{
//Generate the client random value using a cryptographically-safe
//pseudorandom number generator
error = tlsGenerateRandomValue(context, context->clientRandom);
}
else
{
//When responding to a HelloVerifyRequest, the client must use the
//same random value as it did in the original ClientHello
error = NO_ERROR;
}
}
else
#endif
//TLS protocol?
{
//Initial or updated ClientHello?
if(context->state == TLS_STATE_CLIENT_HELLO)
{
//Generate the client random value using a cryptographically-safe
//pseudorandom number generator
error = tlsGenerateRandomValue(context, context->clientRandom);
}
else
{
//When responding to a HelloRetryRequest, the client must use the
//same random value as it did in the initial ClientHello
error = NO_ERROR;
}
}
#if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
//Check status code
if(!error)
{
//In versions of TLS prior to TLS 1.3, the SessionTicket extension is used
//to resume a TLS session without requiring session-specific state at the
//TLS server
if(context->versionMin <= TLS_VERSION_1_2)
{
//Initial ClientHello?
if(context->state == TLS_STATE_CLIENT_HELLO)
{
#if (TLS_TICKET_SUPPORT == ENABLED)
//When presenting a ticket, the client may generate and include a
//session ID in the TLS ClientHello
if(tlsIsTicketValid(context) && context->sessionIdLen == 0)
{
//If the server accepts the ticket and the session ID is not
//empty, then it must respond with the same session ID present in
//the ClientHello. This allows the client to easily differentiate
//when the server is resuming a session from when it is falling
//back to a full handshake
error = tlsGenerateSessionId(context, 32);
}
#endif
}
}
}
#endif
#if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
//Check status code
if(!error)
{
//TLS 1.3 supported by the client?
if(context->versionMax >= TLS_VERSION_1_3 &&
context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM)
{
//Initial or updated ClientHello?
if(context->state == TLS_STATE_CLIENT_HELLO)
{
#if (TLS13_MIDDLEBOX_COMPAT_SUPPORT == ENABLED)
//In compatibility mode the session ID field must be non-empty
if(context->sessionIdLen == 0)
{
//A client not offering a pre-TLS 1.3 session must generate a
//new 32-byte value. This value need not be random but should
//be unpredictable to avoid implementations fixating on a
//specific value (refer to RFC 8446, section 4.1.2)
error = tlsGenerateSessionId(context, 32);
}
#endif
//Check status code
if(!error)
{
//Any preferred ECDHE or FFDHE group?
if(tls13IsGroupSupported(context, context->preferredGroup))
{
//Pregenerate key share using preferred named group
error = tls13GenerateKeyShare(context, context->preferredGroup);
}
else
{
//Request group selection from the server, at the cost of an
//additional round trip
context->preferredGroup = TLS_GROUP_NONE;
}
}
}
else
{
//The updated ClientHello message is not encrypted
tlsFreeEncryptionEngine(&context->encryptionEngine);
}
}
//Save current time
context->clientHelloTimestamp = osGetSystemTime();
}
#endif
//Check status code
if(!error)
{
//Format ClientHello message
error = tlsFormatClientHello(context, message, &length);
}
//Check status code
if(!error)
{
//Debug message
TRACE_INFO("Sending ClientHello message (%" PRIuSIZE " bytes)...\r\n", length);
TRACE_DEBUG_ARRAY(" ", message, length);
//Send handshake message
error = tlsSendHandshakeMessage(context, message, length,
TLS_TYPE_CLIENT_HELLO);
}
//Check status code
if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
{
//Initial ClientHello?
if(context->state == TLS_STATE_CLIENT_HELLO)
{
//Wait for a ServerHello or HelloRetryRequest message
context->state = TLS_STATE_SERVER_HELLO;
}
else
{
//Wait for a ServerHello message
context->state = TLS_STATE_SERVER_HELLO_2;
}
}
//Return status code
return error;
}
/**
* @brief Send ClientKeyExchange message
*
* This message is always sent by the client. It must immediately
* follow the client Certificate message, if it is sent. Otherwise,
* it must be the first message sent by the client after it receives
* the ServerHelloDone message
*
* @param[in] context Pointer to the TLS context
* @return Error code
**/
error_t tlsSendClientKeyExchange(TlsContext *context)
{
error_t error;
size_t length;
TlsClientKeyExchange *message;
//Point to the buffer where to format the message
message = (TlsClientKeyExchange *) (context->txBuffer + context->txBufferLen);
//Format ClientKeyExchange message
error = tlsFormatClientKeyExchange(context, message, &length);
//Check status code
if(!error)
{
//Debug message
TRACE_INFO("Sending ClientKeyExchange message (%" PRIuSIZE " bytes)...\r\n", length);
TRACE_DEBUG_ARRAY(" ", message, length);
//Send handshake message
error = tlsSendHandshakeMessage(context, message, length,
TLS_TYPE_CLIENT_KEY_EXCHANGE);
}
//Check status code
if(error == NO_ERROR || error == ERROR_WOULD_BLOCK || error == ERROR_TIMEOUT)
{
//Derive session keys from the premaster secret
error = tlsGenerateSessionKeys(context);
//Key material successfully generated?
if(!error)
{
//Send a CertificateVerify message to the server
context->state = TLS_STATE_CLIENT_CERTIFICATE_VERIFY;
}
}
//Return status code
return error;
}
/**
* @brief Format ClientHello message
* @param[in] context Pointer to the TLS context
* @param[out] message Buffer where to format the ClientHello message
* @param[out] length Length of the resulting ClientHello message
* @return Error code
**/
error_t tlsFormatClientHello(TlsContext *context,
TlsClientHello *message, size_t *length)
{
error_t error;
size_t n;
uint8_t *p;
uint_t cipherSuiteTypes;
TlsExtensionList *extensionList;
//In TLS 1.3, the client indicates its version preferences in the
//SupportedVersions extension and the legacy_version field must be
//set to 0x0303, which is the version number for TLS 1.2
context->clientVersion = MIN(context->versionMax, TLS_VERSION_1_2);
#if (DTLS_SUPPORT == ENABLED)
//DTLS protocol?
if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
{
//Translate TLS version into DTLS version
context->clientVersion = dtlsTranslateVersion(context->clientVersion);
}
#endif
//In previous versions of TLS, the version field is used for version
//negotiation and represents the highest version number supported by
//the client
message->clientVersion = htons(context->clientVersion);
//Client random value
osMemcpy(message->random, context->clientRandom, 32);
//Point to the session ID
p = message->sessionId;
//Length of the handshake message
*length = sizeof(TlsClientHello);
//The session ID value identifies a session the client wishes to reuse for
//this connection
error = tlsFormatSessionId(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the session ID
message->sessionIdLen = (uint8_t) n;
//Point to the next field
p += n;
//Adjust the length of the message
*length += n;
#if (DTLS_SUPPORT == ENABLED)
//DTLS protocol?
if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
{
//Format Cookie field
error = dtlsFormatCookie(context, p, &n);
//Any error to report?
if(error)
return error;
//Point to the next field
p += n;
//Adjust the length of the message
*length += n;
}
#endif
//Format the list of cipher suites supported by the client
error = tlsFormatCipherSuites(context, &cipherSuiteTypes, p, &n);
//Any error to report?
if(error)
return error;
//Point to the next field
p += n;
//Adjust the length of the message
*length += n;
//Format the list of compression methods supported by the client
error = tlsFormatCompressMethods(context, p, &n);
//Any error to report?
if(error)
return error;
//Point to the next field
p += n;
//Adjust the length of the message
*length += n;
//Clients may request extended functionality from servers by sending
//data in the extensions field
extensionList = (TlsExtensionList *) p;
//Total length of the extension list
extensionList->length = 0;
//Point to the first extension of the list
p += sizeof(TlsExtensionList);
//In TLS 1.2, the client can indicate its version preferences in the
//SupportedVersions extension
error = tlsFormatClientSupportedVersionsExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#if (TLS_SNI_SUPPORT == ENABLED)
//In order to provide the server name, clients may include a ServerName
//extension
error = tlsFormatClientSniExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#endif
#if (TLS_MAX_FRAG_LEN_SUPPORT == ENABLED)
//In order to negotiate smaller maximum fragment lengths, clients may
//include a MaxFragmentLength extension
error = tlsFormatClientMaxFragLenExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#endif
#if (TLS_RECORD_SIZE_LIMIT_SUPPORT == ENABLED)
//The value of RecordSizeLimit is the maximum size of record in octets
//that the endpoint is willing to receive
error = tlsFormatClientRecordSizeLimitExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#endif
//A client that proposes ECC/FFDHE cipher suites in its ClientHello message
//should send the SupportedGroups extension
error = tlsFormatSupportedGroupsExtension(context, cipherSuiteTypes, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
//A client that proposes ECC cipher suites in its ClientHello message
//should send the EcPointFormats extension
error = tlsFormatClientEcPointFormatsExtension(context, cipherSuiteTypes,
p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
//Include the SignatureAlgorithms extension only if TLS 1.2 is supported
error = tlsFormatSignatureAlgorithmsExtension(context, cipherSuiteTypes,
p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#if (TLS_SIGN_ALGOS_CERT_SUPPORT == ENABLED)
//The SignatureAlgorithmsCert extension allows a client to indicate which
//signature algorithms it can validate in X.509 certificates
error = tlsFormatSignatureAlgorithmsCertExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#endif
#if (TLS_ALPN_SUPPORT == ENABLED)
//The ALPN extension contains the list of protocols advertised by the
//client, in descending order of preference
error = tlsFormatClientAlpnExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#endif
#if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED)
//In order to indicate the support of raw public keys, clients include the
//ClientCertType extension in an extended ClientHello message
error = tlsFormatClientCertTypeListExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
//In order to indicate the support of raw public keys, clients include the
//ServerCertType extension in an extended ClientHello message
error = tlsFormatServerCertTypeListExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#endif
#if (TLS_EXT_MASTER_SECRET_SUPPORT == ENABLED)
//In all handshakes, a client implementing RFC 7627 must send the
//ExtendedMasterSecret extension in its ClientHello
error = tlsFormatClientEmsExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#endif
#if (TLS_TICKET_SUPPORT == ENABLED)
//The SessionTicket extension is used to resume a TLS session without
//requiring session-specific state at the TLS server
error = tlsFormatClientSessionTicketExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#endif
#if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
//If the connection's secure_renegotiation flag is set to TRUE, the client
//must include a RenegotiationInfo extension in its ClientHello message
error = tlsFormatClientRenegoInfoExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#endif
#if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
//TLS 1.3 supported by the client?
if(context->versionMax >= TLS_VERSION_1_3 &&
context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM)
{
Tls13PskIdentityList *identityList;
Tls13PskBinderList *binderList;
//Clients must not use cookies in their initial ClientHello
if(context->state != TLS_STATE_CLIENT_HELLO)
{
//When sending the new ClientHello, the client must copy the contents
//of the Cookie extension received in the HelloRetryRequest into a
//Cookie extension in the new ClientHello
error = tls13FormatCookieExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
}
//The KeyShare extension contains the client's cryptographic parameters
error = tls13FormatClientKeyShareExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#if (TLS13_EARLY_DATA_SUPPORT == ENABLED)
//If the client opts to send application data in its first flight of
//messages, it must supply both the PreSharedKey and EarlyData extensions
error = tls13FormatClientEarlyDataExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#endif
//In order to use PSKs, clients must send a PskKeyExchangeModes extension
error = tls13FormatPskKeModesExtension(context, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#if (TLS_CLIENT_HELLO_PADDING_SUPPORT == ENABLED)
//The first pass calculates the length of the PreSharedKey extension
error = tls13FormatClientPreSharedKeyExtension(context, p, &n,
&identityList, &binderList);
//Any error to report?
if(error)
return error;
//Determine the length of the resulting message
n += *length + sizeof(TlsExtensionList) + extensionList->length;
//Add a padding extension to ensure the ClientHello is never between
//256 and 511 bytes in length
error = tlsFormatClientHelloPaddingExtension(context, n, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#endif
//The extensions may appear in any order, with the exception of
//PreSharedKey which must be the last extension in the ClientHello
error = tls13FormatClientPreSharedKeyExtension(context, p, &n,
&identityList, &binderList);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
//Convert the length of the extension list to network byte order
extensionList->length = htons(extensionList->length);
//Total length of the message
*length += sizeof(TlsExtensionList) + htons(extensionList->length);
//Fix PSK binder values in the PreSharedKey extension
error = tls13ComputePskBinders(context, message, *length, identityList,
binderList);
//Any error to report?
if(error)
return error;
}
else
#endif
{
#if (TLS_CLIENT_HELLO_PADDING_SUPPORT == ENABLED)
//Retrieve the actual length of the message
n = *length;
//Any extensions included in the ClientHello message?
if(extensionList->length > 0)
n += sizeof(TlsExtensionList) + extensionList->length;
//Add a padding extension to ensure the ClientHello is never between
//256 and 511 bytes in length
error = tlsFormatClientHelloPaddingExtension(context, n, p, &n);
//Any error to report?
if(error)
return error;
//Fix the length of the extension list
extensionList->length += (uint16_t) n;
//Point to the next field
p += n;
#endif
//Any extensions included in the ClientHello message?
if(extensionList->length > 0)
{
//Convert the length of the extension list to network byte order
extensionList->length = htons(extensionList->length);
//Total length of the message
*length += sizeof(TlsExtensionList) + htons(extensionList->length);
}
}
//Successful processing
return NO_ERROR;
}
/**
* @brief Format ClientKeyExchange message
* @param[in] context Pointer to the TLS context
* @param[out] message Buffer where to format the ClientKeyExchange message
* @param[out] length Length of the resulting ClientKeyExchange message
* @return Error code
**/
error_t tlsFormatClientKeyExchange(TlsContext *context,
TlsClientKeyExchange *message, size_t *length)
{
error_t error;
size_t n;
uint8_t *p;
//Point to the beginning of the handshake message
p = message;
//Length of the handshake message
*length = 0;
#if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
//PSK key exchange method?
if(context->keyExchMethod == TLS_KEY_EXCH_PSK ||
context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK ||
context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
{
//The client indicates which key to use by including a PSK identity
//in the ClientKeyExchange message
error = tlsFormatPskIdentity(context, p, &n);
//Any error to report?
if(error)
return error;
//Advance data pointer
p += n;
//Adjust the length of the message
*length += n;
}
#endif
//RSA, Diffie-Hellman or ECDH key exchange method?
if(context->keyExchMethod != TLS_KEY_EXCH_PSK)
{
//Format client's key exchange parameters
error = tlsFormatClientKeyParams(context, p, &n);
//Any error to report?
if(error)
return error;
//Advance data pointer
p += n;
//Adjust the length of the message
*length += n;
}
#if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
//PSK key exchange method?
if(context->keyExchMethod == TLS_KEY_EXCH_PSK ||
context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK ||
context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK ||
context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
{
//Invalid pre-shared key?
if(context->pskLen == 0)
return ERROR_INVALID_KEY_LENGTH;
//Generate premaster secret
error = tlsGeneratePskPremasterSecret(context);
//Any error to report?
if(error)
return error;
}
#endif
//Successful processing
return NO_ERROR;
}
/**
* @brief Parse HelloRequest message
*
* HelloRequest is a simple notification that the client should begin the
* negotiation process anew. In response, the client should send a ClientHello
* message when convenient
*
* @param[in] context Pointer to the TLS context
* @param[in] message Incoming HelloRequest message to parse
* @param[in] length Message length
* @return Error code
**/
error_t tlsParseHelloRequest(TlsContext *context,
const TlsHelloRequest *message, size_t length)
{
error_t error;
//Debug message
TRACE_INFO("HelloRequest message received (%" PRIuSIZE " bytes)...\r\n", length);
TRACE_DEBUG_ARRAY(" ", message, length);
//Check TLS version
if(context->version > TLS_VERSION_1_2)
return ERROR_UNEXPECTED_MESSAGE;
//The HelloRequest message does not contain any data
if(length != 0)
return ERROR_DECODING_FAILED;
//Check current state
if(context->state == TLS_STATE_APPLICATION_DATA)
{
#if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
//Check whether the secure_renegociation flag is set
if(context->secureRenegoEnabled && context->secureRenegoFlag)
{
//Release existing session ticket, if any
if(context->ticket != NULL)
{
osMemset(context->ticket, 0, context->ticketLen);
tlsFreeMem(context->ticket);
context->ticket = NULL;
context->ticketLen = 0;
}
#if (DTLS_SUPPORT == ENABLED)
//Release DTLS cookie
if(context->cookie != NULL)
{
tlsFreeMem(context->cookie);
context->cookie = NULL;
context->cookieLen = 0;
}
#endif
//HelloRequest is a simple notification that the client should begin
//the negotiation process anew
context->state = TLS_STATE_CLIENT_HELLO;
//Continue processing
error = NO_ERROR;
}
else
#endif
{
//If the connection's secure_renegotiation flag is set to FALSE, it
//is recommended that clients refuse this renegotiation request (refer
//to RFC 5746, section 4.2)
error = tlsSendAlert(context, TLS_ALERT_LEVEL_FATAL,
TLS_ALERT_NO_RENEGOTIATION);
}
}
else
{
//The HelloRequest message can be sent at any time but it should be
//ignored by the client if it arrives in the middle of a handshake
error = NO_ERROR;
}
//Return status code
return error;
}
/**
* @brief Parse ServerHello message
*
* The server will send this message in response to a ClientHello
* message when it was able to find an acceptable set of algorithms.
* If it cannot find such a match, it will respond with a handshake
* failure alert
*
* @param[in] context Pointer to the TLS context
* @param[in] message Incoming ServerHello message to parse
* @param[in] length Message length
* @return Error code
**/
error_t tlsParseServerHello(TlsContext *context,
const TlsServerHello *message, size_t length)
{
error_t error;
uint16_t cipherSuite;
uint8_t compressMethod;
const uint8_t *p;
TlsHelloExtensions extensions;
//Debug message
TRACE_INFO("ServerHello message received (%" PRIuSIZE " bytes)...\r\n", length);
TRACE_DEBUG_ARRAY(" ", message, length);
//Check current state
if(context->state != TLS_STATE_SERVER_HELLO &&
context->state != TLS_STATE_SERVER_HELLO_2 &&
context->state != TLS_STATE_SERVER_HELLO_3)
{
//Report an error
return ERROR_UNEXPECTED_MESSAGE;
}
//Check the length of the ServerHello message
if(length < sizeof(TlsServerHello))
return ERROR_DECODING_FAILED;
//Point to the session ID
p = message->sessionId;
//Remaining bytes to process
length -= sizeof(TlsServerHello);
//Check the length of the session ID
if(message->sessionIdLen > length)
return ERROR_DECODING_FAILED;
if(message->sessionIdLen > 32)
return ERROR_DECODING_FAILED;
//Point to the next field
p += message->sessionIdLen;
//Remaining bytes to process
length -= message->sessionIdLen;
//Malformed ServerHello message?
if(length < sizeof(uint16_t))
return ERROR_DECODING_FAILED;
//Get the negotiated cipher suite
cipherSuite = LOAD16BE(p);
//Point to the next field
p += sizeof(uint16_t);
//Remaining bytes to process
length -= sizeof(uint16_t);
//Malformed ServerHello message?
if(length < sizeof(uint8_t))
return ERROR_DECODING_FAILED;
//Get the negotiated compression method
compressMethod = *p;
//Point to the next field
p += sizeof(uint8_t);
//Remaining bytes to process
length -= sizeof(uint8_t);
//Server version
TRACE_INFO(" serverVersion = 0x%04" PRIX16 " (%s)\r\n",
ntohs(message->serverVersion),
tlsGetVersionName(ntohs(message->serverVersion)));
//Server random value
TRACE_INFO(" random\r\n");
TRACE_INFO_ARRAY(" ", message->random, 32);
//Session identifier