-
Notifications
You must be signed in to change notification settings - Fork 16
/
tls_client_misc.c
1525 lines (1338 loc) · 48 KB
/
tls_client_misc.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_misc.c
* @brief Helper functions for TLS client
*
* @section License
*
* SPDX-License-Identifier: GPL-2.0-or-later
*
* Copyright (C) 2010-2024 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.
*
* @author Oryx Embedded SARL (www.oryx-embedded.com)
* @version 2.4.4
**/
//Switch to the appropriate trace level
#define TRACE_LEVEL TLS_TRACE_LEVEL
//Dependencies
#include "tls.h"
#include "tls_cipher_suites.h"
#include "tls_client.h"
#include "tls_client_misc.h"
#include "tls_common.h"
#include "tls_extensions.h"
#include "tls_sign_verify.h"
#include "tls_sign_misc.h"
#include "tls_cache.h"
#include "tls_ffdhe.h"
#include "tls_record.h"
#include "tls_misc.h"
#include "debug.h"
//Check TLS library configuration
#if (TLS_SUPPORT == ENABLED && TLS_CLIENT_SUPPORT == ENABLED)
/**
* @brief Format initial ClientHello message
* @param[in] context Pointer to the TLS context
* @return Error code
**/
error_t tlsFormatInitialClientHello(TlsContext *context)
{
error_t error;
size_t length;
TlsRecord *record;
TlsHandshake *message;
//Point to the buffer where to format the TLS record
record = (TlsRecord *) context->txBuffer;
//Point to the buffer where to format the handshake message
message = (TlsHandshake *) record->data;
//Format ClientHello message
error = tlsFormatClientHello(context, (TlsClientHello *) message->data,
&length);
//Check status code
if(!error)
{
//Set the type of the handshake message
message->msgType = TLS_TYPE_CLIENT_HELLO;
//Fix the length of the handshake message
STORE24BE(length, message->length);
//Total length of the handshake message
length += sizeof(TlsHandshake);
//Fix the length of the TLS record
record->length = htons(length);
}
//Return status code
return error;
}
/**
* @brief Format session ID
* @param[in] context Pointer to the TLS context
* @param[in] p Output stream where to write session ID
* @param[out] written Total number of bytes that have been written
* @return Error code
**/
error_t tlsFormatSessionId(TlsContext *context, uint8_t *p,
size_t *written)
{
size_t n;
//TLS 1.3 supported by the client?
if(context->versionMax >= TLS_VERSION_1_3 &&
(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM ||
context->transportProtocol == TLS_TRANSPORT_PROTOCOL_EAP))
{
//A client which has a cached session ID set by a pre-TLS 1.3 server
//should set this field to that value
osMemcpy(p, context->sessionId, context->sessionIdLen);
n = context->sessionIdLen;
}
else
{
#if (TLS_SESSION_RESUME_SUPPORT == ENABLED)
//The session ID value identifies a session the client wishes to reuse
//for this connection
osMemcpy(p, context->sessionId, context->sessionIdLen);
n = context->sessionIdLen;
#else
//Session resumption is not supported
n = 0;
#endif
}
#if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
//Secure renegotiation?
if(context->secureRenegoEnabled && context->secureRenegoFlag)
{
//Do not offer a session ID when renegotiating
n = 0;
}
#endif
//Total number of bytes that have been written
*written = n;
//Successful processing
return NO_ERROR;
}
/**
* @brief Format the list of cipher suites supported by the client
* @param[in] context Pointer to the TLS context
* @param[in] p Output stream where to write the list of cipher suites
* @param[out] written Total number of bytes that have been written
* @return Error code
**/
error_t tlsFormatCipherSuites(TlsContext *context, uint8_t *p,
size_t *written)
{
uint_t i;
uint_t j;
uint_t k;
uint_t n;
uint16_t identifier;
TlsCipherSuites *cipherSuites;
//Types of cipher suites proposed by the client
context->cipherSuiteTypes = TLS_CIPHER_SUITE_TYPE_UNKNOWN;
//Point to the list of cryptographic algorithms supported by the client
cipherSuites = (TlsCipherSuites *) p;
//Number of cipher suites in the array
n = 0;
//Determine the number of supported cipher suites
k = tlsGetNumSupportedCipherSuites();
//Debug message
TRACE_DEBUG("Cipher suites:\r\n");
//Any preferred cipher suites?
if(context->numCipherSuites > 0)
{
//Loop through the list of preferred cipher suites
for(i = 0; i < context->numCipherSuites; i++)
{
//Loop through the list of supported cipher suites
for(j = 0; j < k; j++)
{
//Retrieve cipher suite identifier
identifier = tlsSupportedCipherSuites[j].identifier;
//Supported cipher suite?
if(identifier == context->cipherSuites[i])
{
//Check whether the cipher suite can be negotiated with the
//current protocol version
if(tlsIsCipherSuiteAcceptable(&tlsSupportedCipherSuites[j],
context->versionMin, context->versionMax,
context->transportProtocol))
{
//Copy cipher suite identifier
cipherSuites->value[n++] = htons(identifier);
//Debug message
TRACE_DEBUG(" 0x%04" PRIX16 " (%s)\r\n", identifier,
tlsGetCipherSuiteName(identifier));
//Check whether the identifier matches an ECC or FFDHE cipher
//suite
context->cipherSuiteTypes |= tlsGetCipherSuiteType(identifier);
}
}
}
}
}
else
{
//Loop through the list of supported cipher suites
for(j = 0; j < k; j++)
{
//Retrieve cipher suite identifier
identifier = tlsSupportedCipherSuites[j].identifier;
//Check whether the cipher suite can be negotiated with the
//current protocol version
if(tlsIsCipherSuiteAcceptable(&tlsSupportedCipherSuites[j],
context->versionMin, context->versionMax,
context->transportProtocol))
{
//Copy cipher suite identifier
cipherSuites->value[n++] = htons(identifier);
//Debug message
TRACE_DEBUG(" 0x%04" PRIX16 " (%s)\r\n", identifier,
tlsGetCipherSuiteName(identifier));
//Check whether the identifier matches an ECC or FFDHE cipher
//suite
context->cipherSuiteTypes |= tlsGetCipherSuiteType(identifier);
}
}
}
#if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
//Check whether secure renegotiation is enabled
if(context->secureRenegoEnabled)
{
//Initial handshake?
if(context->clientVerifyDataLen == 0)
{
//The client includes the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling
//cipher suite value in its ClientHello
cipherSuites->value[n++] = HTONS(TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
}
}
#endif
#if (TLS_FALLBACK_SCSV_SUPPORT == ENABLED)
//Check whether support for FALLBACK_SCSV is enabled
if(context->fallbackScsvEnabled)
{
//The TLS_FALLBACK_SCSV cipher suite value is meant for use by clients
//that repeat a connection attempt with a downgraded protocol
if(context->versionMax != TLS_MAX_VERSION)
{
//The client should put TLS_FALLBACK_SCSV after all cipher suites
//that it actually intends to negotiate
cipherSuites->value[n++] = HTONS(TLS_FALLBACK_SCSV);
}
}
#endif
//Length of the array, in bytes
cipherSuites->length = htons(n * 2);
//Total number of bytes that have been written
*written = sizeof(TlsCipherSuites) + n * 2;
//Successful processing
return NO_ERROR;
}
/**
* @brief Format the list of compression methods supported by the client
* @param[in] context Pointer to the TLS context
* @param[in] p Output stream where to write the list of compression methods
* @param[out] written Total number of bytes that have been written
* @return Error code
**/
error_t tlsFormatCompressMethods(TlsContext *context, uint8_t *p,
size_t *written)
{
TlsCompressMethods *compressMethods;
//List of compression algorithms supported by the client
compressMethods = (TlsCompressMethods *) p;
//The CRIME exploit takes advantage of TLS compression, so conservative
//implementations do not enable compression at the TLS level
compressMethods->length = 1;
compressMethods->value[0] = TLS_COMPRESSION_METHOD_NULL;
//Total number of bytes that have been written
*written = sizeof(TlsCompressMethods) + compressMethods->length;
//Successful processing
return NO_ERROR;
}
/**
* @brief Format PSK identity
* @param[in] context Pointer to the TLS context
* @param[in] p Output stream where to write the PSK identity hint
* @param[out] written Total number of bytes that have been written
* @return Error code
**/
error_t tlsFormatPskIdentity(TlsContext *context, uint8_t *p,
size_t *written)
{
size_t n;
TlsPskIdentity *pskIdentity;
//Point to the PSK identity
pskIdentity = (TlsPskIdentity *) p;
#if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
//Any PSK identity defined?
if(context->pskIdentity != NULL)
{
//Determine the length of the PSK identity
n = osStrlen(context->pskIdentity);
//Copy PSK identity
osMemcpy(pskIdentity->value, context->pskIdentity, n);
}
else
#endif
{
//No PSK identity is provided
n = 0;
}
//The PSK identity is preceded by a 2-byte length field
pskIdentity->length = htons(n);
//Total number of bytes that have been written
*written = sizeof(TlsPskIdentity) + n;
//Successful processing
return NO_ERROR;
}
/**
* @brief Format client's key exchange parameters
* @param[in] context Pointer to the TLS context
* @param[in] p Output stream where to write the client's key exchange parameters
* @param[out] written Total number of bytes that have been written
* @return Error code
**/
__weak_func error_t tlsFormatClientKeyParams(TlsContext *context, uint8_t *p,
size_t *written)
{
#if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
error_t error;
size_t n;
#if (TLS_RSA_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED)
//RSA key exchange method?
if(context->keyExchMethod == TLS_KEY_EXCH_RSA ||
context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
{
//If RSA is being used for key agreement and authentication, the
//client generates a 48-byte premaster secret
context->premasterSecretLen = 48;
//The first 2 bytes code the latest version supported by the client
STORE16BE(context->clientVersion, context->premasterSecret);
//The last 46 bytes contain securely-generated random bytes
error = context->prngAlgo->read(context->prngContext,
context->premasterSecret + 2, 46);
//Any error to report?
if(error)
return error;
//Encrypt the premaster secret using the server public key
error = rsaesPkcs1v15Encrypt(context->prngAlgo, context->prngContext,
&context->peerRsaPublicKey, context->premasterSecret, 48, p + 2, &n);
//RSA encryption failed?
if(error)
return error;
//The RSA-encrypted premaster secret in a ClientKeyExchange is preceded by
//two length bytes
STORE16BE(n, p);
//Total number of bytes that have been written
*written = n + 2;
}
else
#endif
#if (TLS_DH_ANON_KE_SUPPORT == ENABLED || TLS_DHE_RSA_KE_SUPPORT == ENABLED || \
TLS_DHE_DSS_KE_SUPPORT == ENABLED || TLS_DHE_PSK_KE_SUPPORT == ENABLED)
//Diffie-Hellman key exchange method?
if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK)
{
//Generate an ephemeral key pair
error = dhGenerateKeyPair(&context->dhContext,
context->prngAlgo, context->prngContext);
//Any error to report?
if(error)
return error;
//Encode the client's public value to an opaque vector
error = tlsWriteMpi(&context->dhContext.ya, p, &n);
//Any error to report?
if(error)
return error;
//Total number of bytes that have been written
*written = n;
//Calculate the negotiated key Z
error = dhComputeSharedSecret(&context->dhContext,
context->premasterSecret, TLS_PREMASTER_SECRET_SIZE,
&context->premasterSecretLen);
//Any error to report?
if(error)
return error;
//Leading bytes of Z that contain all zero bits are stripped before
//it is used as the premaster secret (RFC 4346, section 8.2.1)
for(n = 0; n < context->premasterSecretLen; n++)
{
if(context->premasterSecret[n] != 0x00)
break;
}
//Any leading zero bytes?
if(n > 0)
{
//Strip leading zero bytes from the negotiated key
osMemmove(context->premasterSecret, context->premasterSecret + n,
context->premasterSecretLen - n);
//Adjust the length of the premaster secret
context->premasterSecretLen -= n;
}
}
else
#endif
#if (TLS_ECDH_ANON_KE_SUPPORT == ENABLED || TLS_ECDHE_RSA_KE_SUPPORT == ENABLED || \
TLS_ECDHE_ECDSA_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
//ECDH key exchange method?
if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
{
#if (TLS_ECC_CALLBACK_SUPPORT == ENABLED)
//Any registered callback?
if(context->ecdhCallback != NULL)
{
//Invoke user callback function
error = context->ecdhCallback(context);
}
else
#endif
{
//No callback function defined
error = ERROR_UNSUPPORTED_ELLIPTIC_CURVE;
}
//Check status code
if(error == ERROR_UNSUPPORTED_ELLIPTIC_CURVE)
{
//Generate an ephemeral key pair
error = ecdhGenerateKeyPair(&context->ecdhContext,
context->prngAlgo, context->prngContext);
//Any error to report?
if(error)
return error;
//Calculate the negotiated key Z
error = ecdhComputeSharedSecret(&context->ecdhContext,
context->premasterSecret, TLS_PREMASTER_SECRET_SIZE,
&context->premasterSecretLen);
//Any error to report?
if(error)
return error;
}
else if(error != NO_ERROR)
{
//Report an error
return error;
}
//Encode the client's public key to an opaque vector
error = tlsWriteEcPoint(&context->ecdhContext.params,
&context->ecdhContext.qa.q, p, &n);
//Any error to report?
if(error)
return error;
//Total number of bytes that have been written
*written = n;
}
else
#endif
//Invalid key exchange method?
{
//Just for sanity
(void) error;
(void) n;
//The specified key exchange method is not supported
return ERROR_UNSUPPORTED_KEY_EXCH_ALGO;
}
//Successful processing
return NO_ERROR;
#else
//Not implemented
return ERROR_NOT_IMPLEMENTED;
#endif
}
/**
* @brief Parse PSK identity hint
* @param[in] context Pointer to the TLS context
* @param[in] p Input stream where to read the PSK identity hint
* @param[in] length Number of bytes available in the input stream
* @param[out] consumed Total number of bytes that have been consumed
* @return Error code
**/
error_t tlsParsePskIdentityHint(TlsContext *context, const uint8_t *p,
size_t length, size_t *consumed)
{
size_t n;
TlsPskIdentityHint *pskIdentityHint;
//Point to the PSK identity hint
pskIdentityHint = (TlsPskIdentityHint *) p;
//Malformed ServerKeyExchange message?
if(length < sizeof(TlsPskIdentityHint))
return ERROR_DECODING_FAILED;
if(length < (sizeof(TlsPskIdentityHint) + ntohs(pskIdentityHint->length)))
return ERROR_DECODING_FAILED;
//Retrieve the length of the PSK identity hint
n = ntohs(pskIdentityHint->length);
#if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
//Any registered callback?
if(context->pskCallback != NULL)
{
error_t error;
//The client selects which identity to use depending on the PSK identity
//hint provided by the server
error = context->pskCallback(context, pskIdentityHint->value, n);
//Any error to report?
if(error)
return ERROR_UNKNOWN_IDENTITY;
}
#endif
//Total number of bytes that have been consumed
*consumed = sizeof(TlsPskIdentityHint) + n;
//Successful processing
return NO_ERROR;
}
/**
* @brief Parse server's key exchange parameters
* @param[in] context Pointer to the TLS context
* @param[in] p Input stream where to read the server's key exchange parameters
* @param[in] length Number of bytes available in the input stream
* @param[out] consumed Total number of bytes that have been consumed
* @return Error code
**/
error_t tlsParseServerKeyParams(TlsContext *context, const uint8_t *p,
size_t length, size_t *consumed)
{
#if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
error_t error;
const uint8_t *params;
//Initialize status code
error = NO_ERROR;
//Point to the server's key exchange parameters
params = p;
#if (TLS_DH_ANON_KE_SUPPORT == ENABLED || TLS_DHE_RSA_KE_SUPPORT == ENABLED || \
TLS_DHE_DSS_KE_SUPPORT == ENABLED || TLS_DHE_PSK_KE_SUPPORT == ENABLED)
//Diffie-Hellman key exchange method?
if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK)
{
uint_t k;
size_t n;
//Convert the prime modulus to a multiple precision integer
error = tlsReadMpi(&context->dhContext.params.p, p, length, &n);
//Check status code
if(!error)
{
//Get the length of the prime modulus, in bits
k = mpiGetBitLength(&context->dhContext.params.p);
//Make sure the prime modulus is acceptable
if(k < TLS_MIN_DH_MODULUS_SIZE || k > TLS_MAX_DH_MODULUS_SIZE)
{
error = ERROR_ILLEGAL_PARAMETER;
}
}
//Check status code
if(!error)
{
//Advance data pointer
p += n;
//Remaining bytes to process
length -= n;
//Convert the generator to a multiple precision integer
error = tlsReadMpi(&context->dhContext.params.g, p, length, &n);
}
//Check status code
if(!error)
{
//Advance data pointer
p += n;
//Remaining bytes to process
length -= n;
//Convert the server's public value to a multiple precision integer
error = tlsReadMpi(&context->dhContext.yb, p, length, &n);
}
//Check status code
if(!error)
{
//Advance data pointer
p += n;
//Remaining bytes to process
length -= n;
//Verify peer's public value
error = dhCheckPublicKey(&context->dhContext.params,
&context->dhContext.yb);
}
//Check status code
if(!error)
{
//Debug message
TRACE_DEBUG("Diffie-Hellman parameters:\r\n");
TRACE_DEBUG(" Prime modulus:\r\n");
TRACE_DEBUG_MPI(" ", &context->dhContext.params.p);
TRACE_DEBUG(" Generator:\r\n");
TRACE_DEBUG_MPI(" ", &context->dhContext.params.g);
TRACE_DEBUG(" Server public value:\r\n");
TRACE_DEBUG_MPI(" ", &context->dhContext.yb);
}
}
else
#endif
#if (TLS_ECDH_ANON_KE_SUPPORT == ENABLED || TLS_ECDHE_RSA_KE_SUPPORT == ENABLED || \
TLS_ECDHE_ECDSA_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
//ECDH key exchange method?
if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
{
size_t n;
uint8_t curveType;
const EcCurveInfo *curveInfo;
//Initialize curve parameters
curveInfo = NULL;
//Malformed ServerKeyExchange message?
if(length < sizeof(curveType))
{
error = ERROR_DECODING_FAILED;
}
//Check status code
if(!error)
{
//Retrieve the type of the elliptic curve domain parameters
curveType = *p;
//Advance data pointer
p += sizeof(curveType);
//Remaining bytes to process
length -= sizeof(curveType);
//Only named curves are supported
if(curveType != TLS_EC_CURVE_TYPE_NAMED_CURVE)
{
error = ERROR_ILLEGAL_PARAMETER;
}
}
//Check status code
if(!error)
{
//Malformed ServerKeyExchange message?
if(length < sizeof(uint16_t))
{
error = ERROR_DECODING_FAILED;
}
}
//Check status code
if(!error)
{
//Get elliptic curve identifier
context->namedGroup = LOAD16BE(p);
//Advance data pointer
p += sizeof(uint16_t);
//Remaining bytes to process
length -= sizeof(uint16_t);
//TLS 1.3 group?
if(context->namedGroup == TLS_GROUP_BRAINPOOLP256R1_TLS13 ||
context->namedGroup == TLS_GROUP_BRAINPOOLP384R1_TLS13 ||
context->namedGroup == TLS_GROUP_BRAINPOOLP512R1_TLS13 ||
context->namedGroup == TLS_GROUP_CURVE_SM2)
{
//These elliptic curves do not apply to any older versions of TLS
error = ERROR_ILLEGAL_PARAMETER;
}
else
{
//Retrieve the corresponding EC domain parameters
curveInfo = tlsGetCurveInfo(context, context->namedGroup);
//Make sure the elliptic curve is supported
if(curveInfo == NULL)
{
//The elliptic curve is not supported
error = ERROR_ILLEGAL_PARAMETER;
}
}
}
//Check status code
if(!error)
{
//Load EC domain parameters
error = ecLoadDomainParameters(&context->ecdhContext.params,
curveInfo);
}
//Check status code
if(!error)
{
//Read server's public key
error = tlsReadEcPoint(&context->ecdhContext.params,
&context->ecdhContext.qb.q, p, length, &n);
}
//Check status code
if(!error)
{
//Advance data pointer
p += n;
//Remaining bytes to process
length -= n;
//Verify peer's public key
error = ecdhCheckPublicKey(&context->ecdhContext.params,
&context->ecdhContext.qb.q);
}
//Check status code
if(!error)
{
//Debug message
TRACE_DEBUG(" Server public key X:\r\n");
TRACE_DEBUG_MPI(" ", &context->ecdhContext.qb.q.x);
TRACE_DEBUG(" Server public key Y:\r\n");
TRACE_DEBUG_MPI(" ", &context->ecdhContext.qb.q.y);
}
}
else
#endif
//Invalid key exchange method?
{
//It is not legal to send the ServerKeyExchange message when a key
//exchange method other than DHE_DSS, DHE_RSA, DH_anon, ECDHE_RSA,
//ECDHE_ECDSA or ECDH_anon is selected
error = ERROR_UNEXPECTED_MESSAGE;
}
//Total number of bytes that have been consumed
*consumed = p - params;
//Return status code
return error;
#else
//Not implemented
return ERROR_NOT_IMPLEMENTED;
#endif
}
/**
* @brief Verify server's key exchange parameters signature (TLS 1.0 and TLS 1.1)
* @param[in] context Pointer to the TLS context
* @param[in] signature Pointer to the digital signature
* @param[in] length Number of bytes available in the input stream
* @param[in] params Pointer to the server's key exchange parameters
* @param[in] paramsLen Length of the server's key exchange parameters
* @param[out] consumed Total number of bytes that have been consumed
* @return Error code
**/
error_t tlsVerifyServerKeySignature(TlsContext *context,
const TlsDigitalSignature *signature, size_t length,
const uint8_t *params, size_t paramsLen, size_t *consumed)
{
error_t error;
#if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
//Initialize status code
error = NO_ERROR;
//Check the length of the digitally-signed element
if(length < sizeof(TlsDigitalSignature))
return ERROR_DECODING_FAILED;
if(length < (sizeof(TlsDigitalSignature) + ntohs(signature->length)))
return ERROR_DECODING_FAILED;
#if (TLS_RSA_SIGN_SUPPORT == ENABLED)
//RSA signature algorithm?
if(context->peerCertType == TLS_CERT_RSA_SIGN)
{
Md5Context *md5Context;
Sha1Context *sha1Context;
//Allocate a memory buffer to hold the MD5 context
md5Context = tlsAllocMem(sizeof(Md5Context));
//Successful memory allocation?
if(md5Context != NULL)
{
//Compute MD5(ClientHello.random + ServerHello.random +
//ServerKeyExchange.params)
md5Init(md5Context);
md5Update(md5Context, context->clientRandom, TLS_RANDOM_SIZE);
md5Update(md5Context, context->serverRandom, TLS_RANDOM_SIZE);
md5Update(md5Context, params, paramsLen);
md5Final(md5Context, context->serverVerifyData);
//Release previously allocated memory
tlsFreeMem(md5Context);
}
else
{
//Failed to allocate memory
error = ERROR_OUT_OF_MEMORY;
}
//Check status code
if(!error)
{
//Allocate a memory buffer to hold the SHA-1 context
sha1Context = tlsAllocMem(sizeof(Sha1Context));
//Successful memory allocation?
if(sha1Context != NULL)
{
//Compute SHA(ClientHello.random + ServerHello.random +
//ServerKeyExchange.params)
sha1Init(sha1Context);
sha1Update(sha1Context, context->clientRandom, TLS_RANDOM_SIZE);
sha1Update(sha1Context, context->serverRandom, TLS_RANDOM_SIZE);
sha1Update(sha1Context, params, paramsLen);
sha1Final(sha1Context, context->serverVerifyData + MD5_DIGEST_SIZE);
//Release previously allocated memory
tlsFreeMem(sha1Context);
}
else
{
//Failed to allocate memory
error = ERROR_OUT_OF_MEMORY;
}
}
//Check status code
if(!error)
{
//RSA signature verification
error = tlsVerifyRsaSignature(&context->peerRsaPublicKey,
context->serverVerifyData, signature->value, ntohs(signature->length));
}
}
else
#endif
#if (TLS_DSA_SIGN_SUPPORT == ENABLED)
//DSA signature algorithm?
if(context->peerCertType == TLS_CERT_DSS_SIGN)
{
Sha1Context *sha1Context;
//Allocate a memory buffer to hold the SHA-1 context
sha1Context = tlsAllocMem(sizeof(Sha1Context));
//Successful memory allocation?
if(sha1Context != NULL)
{
//Compute SHA(ClientHello.random + ServerHello.random +
//ServerKeyExchange.params)
sha1Init(sha1Context);
sha1Update(sha1Context, context->clientRandom, TLS_RANDOM_SIZE);
sha1Update(sha1Context, context->serverRandom, TLS_RANDOM_SIZE);
sha1Update(sha1Context, params, paramsLen);
sha1Final(sha1Context, context->serverVerifyData);
//Release previously allocated memory
tlsFreeMem(sha1Context);
}
else
{
//Failed to allocate memory
error = ERROR_OUT_OF_MEMORY;
}
//Check status code
if(!error)
{
//DSA signature verification
error = tlsVerifyDsaSignature(context, context->serverVerifyData,
SHA1_DIGEST_SIZE, signature->value, ntohs(signature->length));
}
}
else
#endif
#if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
//ECDSA signature algorithm?
if(context->peerCertType == TLS_CERT_ECDSA_SIGN)
{
Sha1Context *sha1Context;
//Allocate a memory buffer to hold the SHA-1 context
sha1Context = tlsAllocMem(sizeof(Sha1Context));
//Successful memory allocation?
if(sha1Context != NULL)
{
//Compute SHA(ClientHello.random + ServerHello.random +
//ServerKeyExchange.params)
sha1Init(sha1Context);
sha1Update(sha1Context, context->clientRandom, TLS_RANDOM_SIZE);
sha1Update(sha1Context, context->serverRandom, TLS_RANDOM_SIZE);
sha1Update(sha1Context, params, paramsLen);
sha1Final(sha1Context, context->serverVerifyData);
//Release previously allocated memory
tlsFreeMem(sha1Context);
}
//Check status code
if(!error)
{
//ECDSA signature verification
error = tlsVerifyEcdsaSignature(context, context->serverVerifyData,
SHA1_DIGEST_SIZE, signature->value, ntohs(signature->length));
}
}
else
#endif