tls_client_misc.c
Go to the documentation of this file.
1 /**
2  * @file tls_client_misc.c
3  * @brief Helper functions for TLS client
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2024 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneSSL Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.4.4
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL TLS_TRACE_LEVEL
33 
34 //Dependencies
35 #include "tls.h"
36 #include "tls_cipher_suites.h"
37 #include "tls_client.h"
38 #include "tls_client_misc.h"
39 #include "tls_common.h"
40 #include "tls_extensions.h"
41 #include "tls_sign_verify.h"
42 #include "tls_sign_misc.h"
43 #include "tls_cache.h"
44 #include "tls_ffdhe.h"
45 #include "tls_record.h"
46 #include "tls_misc.h"
47 #include "debug.h"
48 
49 //Check TLS library configuration
50 #if (TLS_SUPPORT == ENABLED && TLS_CLIENT_SUPPORT == ENABLED)
51 
52 
53 /**
54  * @brief Format initial ClientHello message
55  * @param[in] context Pointer to the TLS context
56  * @return Error code
57  **/
58 
60 {
61  error_t error;
62  size_t length;
63  TlsRecord *record;
65 
66  //Point to the buffer where to format the TLS record
67  record = (TlsRecord *) context->txBuffer;
68  //Point to the buffer where to format the handshake message
69  message = (TlsHandshake *) record->data;
70 
71  //Format ClientHello message
72  error = tlsFormatClientHello(context, (TlsClientHello *) message->data,
73  &length);
74 
75  //Check status code
76  if(!error)
77  {
78  //Set the type of the handshake message
79  message->msgType = TLS_TYPE_CLIENT_HELLO;
80  //Fix the length of the handshake message
81  STORE24BE(length, message->length);
82 
83  //Total length of the handshake message
84  length += sizeof(TlsHandshake);
85 
86  //Fix the length of the TLS record
87  record->length = htons(length);
88  }
89 
90  //Return status code
91  return error;
92 }
93 
94 
95 /**
96  * @brief Format session ID
97  * @param[in] context Pointer to the TLS context
98  * @param[in] p Output stream where to write session ID
99  * @param[out] written Total number of bytes that have been written
100  * @return Error code
101  **/
102 
104  size_t *written)
105 {
106  size_t n;
107 
108  //TLS 1.3 supported by the client?
109  if(context->versionMax >= TLS_VERSION_1_3 &&
110  (context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM ||
111  context->transportProtocol == TLS_TRANSPORT_PROTOCOL_EAP))
112  {
113  //A client which has a cached session ID set by a pre-TLS 1.3 server
114  //should set this field to that value
115  osMemcpy(p, context->sessionId, context->sessionIdLen);
116  n = context->sessionIdLen;
117  }
118  else
119  {
120 #if (TLS_SESSION_RESUME_SUPPORT == ENABLED)
121  //The session ID value identifies a session the client wishes to reuse
122  //for this connection
123  osMemcpy(p, context->sessionId, context->sessionIdLen);
124  n = context->sessionIdLen;
125 #else
126  //Session resumption is not supported
127  n = 0;
128 #endif
129  }
130 
131 #if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
132  //Secure renegotiation?
133  if(context->secureRenegoEnabled && context->secureRenegoFlag)
134  {
135  //Do not offer a session ID when renegotiating
136  n = 0;
137  }
138 #endif
139 
140  //Total number of bytes that have been written
141  *written = n;
142 
143  //Successful processing
144  return NO_ERROR;
145 }
146 
147 
148 /**
149  * @brief Format the list of cipher suites supported by the client
150  * @param[in] context Pointer to the TLS context
151  * @param[in] p Output stream where to write the list of cipher suites
152  * @param[out] written Total number of bytes that have been written
153  * @return Error code
154  **/
155 
157  size_t *written)
158 {
159  uint_t i;
160  uint_t j;
161  uint_t k;
162  uint_t n;
163  uint16_t identifier;
164  TlsCipherSuites *cipherSuites;
165 
166  //Types of cipher suites proposed by the client
167  context->cipherSuiteTypes = TLS_CIPHER_SUITE_TYPE_UNKNOWN;
168 
169  //Point to the list of cryptographic algorithms supported by the client
170  cipherSuites = (TlsCipherSuites *) p;
171  //Number of cipher suites in the array
172  n = 0;
173 
174  //Determine the number of supported cipher suites
176 
177  //Debug message
178  TRACE_DEBUG("Cipher suites:\r\n");
179 
180  //Any preferred cipher suites?
181  if(context->numCipherSuites > 0)
182  {
183  //Loop through the list of preferred cipher suites
184  for(i = 0; i < context->numCipherSuites; i++)
185  {
186  //Loop through the list of supported cipher suites
187  for(j = 0; j < k; j++)
188  {
189  //Retrieve cipher suite identifier
191 
192  //Supported cipher suite?
193  if(identifier == context->cipherSuites[i])
194  {
195  //Check whether the cipher suite can be negotiated with the
196  //current protocol version
198  context->versionMin, context->versionMax,
199  context->transportProtocol))
200  {
201  //Copy cipher suite identifier
202  cipherSuites->value[n++] = htons(identifier);
203 
204  //Debug message
205  TRACE_DEBUG(" 0x%04" PRIX16 " (%s)\r\n", identifier,
207 
208  //Check whether the identifier matches an ECC or FFDHE cipher
209  //suite
210  context->cipherSuiteTypes |= tlsGetCipherSuiteType(identifier);
211  }
212  }
213  }
214  }
215  }
216  else
217  {
218  //Loop through the list of supported cipher suites
219  for(j = 0; j < k; j++)
220  {
221  //Retrieve cipher suite identifier
223 
224  //Check whether the cipher suite can be negotiated with the
225  //current protocol version
227  context->versionMin, context->versionMax,
228  context->transportProtocol))
229  {
230  //Copy cipher suite identifier
231  cipherSuites->value[n++] = htons(identifier);
232 
233  //Debug message
234  TRACE_DEBUG(" 0x%04" PRIX16 " (%s)\r\n", identifier,
236 
237  //Check whether the identifier matches an ECC or FFDHE cipher
238  //suite
239  context->cipherSuiteTypes |= tlsGetCipherSuiteType(identifier);
240  }
241  }
242  }
243 
244 #if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
245  //Check whether secure renegotiation is enabled
246  if(context->secureRenegoEnabled)
247  {
248  //Initial handshake?
249  if(context->clientVerifyDataLen == 0)
250  {
251  //The client includes the TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling
252  //cipher suite value in its ClientHello
253  cipherSuites->value[n++] = HTONS(TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
254  }
255  }
256 #endif
257 
258 #if (TLS_FALLBACK_SCSV_SUPPORT == ENABLED)
259  //Check whether support for FALLBACK_SCSV is enabled
260  if(context->fallbackScsvEnabled)
261  {
262  //The TLS_FALLBACK_SCSV cipher suite value is meant for use by clients
263  //that repeat a connection attempt with a downgraded protocol
264  if(context->versionMax != TLS_MAX_VERSION)
265  {
266  //The client should put TLS_FALLBACK_SCSV after all cipher suites
267  //that it actually intends to negotiate
268  cipherSuites->value[n++] = HTONS(TLS_FALLBACK_SCSV);
269  }
270  }
271 #endif
272 
273  //Length of the array, in bytes
274  cipherSuites->length = htons(n * 2);
275 
276  //Total number of bytes that have been written
277  *written = sizeof(TlsCipherSuites) + n * 2;
278 
279  //Successful processing
280  return NO_ERROR;
281 }
282 
283 
284 /**
285  * @brief Format the list of compression methods supported by the client
286  * @param[in] context Pointer to the TLS context
287  * @param[in] p Output stream where to write the list of compression methods
288  * @param[out] written Total number of bytes that have been written
289  * @return Error code
290  **/
291 
293  size_t *written)
294 {
295  TlsCompressMethods *compressMethods;
296 
297  //List of compression algorithms supported by the client
298  compressMethods = (TlsCompressMethods *) p;
299 
300  //The CRIME exploit takes advantage of TLS compression, so conservative
301  //implementations do not enable compression at the TLS level
302  compressMethods->length = 1;
303  compressMethods->value[0] = TLS_COMPRESSION_METHOD_NULL;
304 
305  //Total number of bytes that have been written
306  *written = sizeof(TlsCompressMethods) + compressMethods->length;
307 
308  //Successful processing
309  return NO_ERROR;
310 }
311 
312 
313 /**
314  * @brief Format PSK identity
315  * @param[in] context Pointer to the TLS context
316  * @param[in] p Output stream where to write the PSK identity hint
317  * @param[out] written Total number of bytes that have been written
318  * @return Error code
319  **/
320 
322  size_t *written)
323 {
324  size_t n;
325  TlsPskIdentity *pskIdentity;
326 
327  //Point to the PSK identity
328  pskIdentity = (TlsPskIdentity *) p;
329 
330 #if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
331  TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
332  //Any PSK identity defined?
333  if(context->pskIdentity != NULL)
334  {
335  //Determine the length of the PSK identity
336  n = osStrlen(context->pskIdentity);
337  //Copy PSK identity
338  osMemcpy(pskIdentity->value, context->pskIdentity, n);
339  }
340  else
341 #endif
342  {
343  //No PSK identity is provided
344  n = 0;
345  }
346 
347  //The PSK identity is preceded by a 2-byte length field
348  pskIdentity->length = htons(n);
349 
350  //Total number of bytes that have been written
351  *written = sizeof(TlsPskIdentity) + n;
352 
353  //Successful processing
354  return NO_ERROR;
355 }
356 
357 
358 /**
359  * @brief Format client's key exchange parameters
360  * @param[in] context Pointer to the TLS context
361  * @param[in] p Output stream where to write the client's key exchange parameters
362  * @param[out] written Total number of bytes that have been written
363  * @return Error code
364  **/
365 
366 __weak_func error_t tlsFormatClientKeyParams(TlsContext *context, uint8_t *p,
367  size_t *written)
368 {
369 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
370  error_t error;
371  size_t n;
372 
373 #if (TLS_RSA_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED)
374  //RSA key exchange method?
375  if(context->keyExchMethod == TLS_KEY_EXCH_RSA ||
376  context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
377  {
378  //If RSA is being used for key agreement and authentication, the
379  //client generates a 48-byte premaster secret
380  context->premasterSecretLen = 48;
381 
382  //The first 2 bytes code the latest version supported by the client
383  STORE16BE(context->clientVersion, context->premasterSecret);
384 
385  //The last 46 bytes contain securely-generated random bytes
386  error = context->prngAlgo->read(context->prngContext,
387  context->premasterSecret + 2, 46);
388  //Any error to report?
389  if(error)
390  return error;
391 
392  //Encrypt the premaster secret using the server public key
393  error = rsaesPkcs1v15Encrypt(context->prngAlgo, context->prngContext,
394  &context->peerRsaPublicKey, context->premasterSecret, 48, p + 2, &n);
395  //RSA encryption failed?
396  if(error)
397  return error;
398 
399  //The RSA-encrypted premaster secret in a ClientKeyExchange is preceded by
400  //two length bytes
401  STORE16BE(n, p);
402 
403  //Total number of bytes that have been written
404  *written = n + 2;
405  }
406  else
407 #endif
408 #if (TLS_DH_ANON_KE_SUPPORT == ENABLED || TLS_DHE_RSA_KE_SUPPORT == ENABLED || \
409  TLS_DHE_DSS_KE_SUPPORT == ENABLED || TLS_DHE_PSK_KE_SUPPORT == ENABLED)
410  //Diffie-Hellman key exchange method?
411  if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
412  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
413  context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
414  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK)
415  {
416  //Generate an ephemeral key pair
417  error = dhGenerateKeyPair(&context->dhContext,
418  context->prngAlgo, context->prngContext);
419  //Any error to report?
420  if(error)
421  return error;
422 
423  //Encode the client's public value to an opaque vector
424  error = tlsWriteMpi(&context->dhContext.ya, p, &n);
425  //Any error to report?
426  if(error)
427  return error;
428 
429  //Total number of bytes that have been written
430  *written = n;
431 
432  //Calculate the negotiated key Z
433  error = dhComputeSharedSecret(&context->dhContext,
434  context->premasterSecret, TLS_PREMASTER_SECRET_SIZE,
435  &context->premasterSecretLen);
436  //Any error to report?
437  if(error)
438  return error;
439 
440  //Leading bytes of Z that contain all zero bits are stripped before
441  //it is used as the premaster secret (RFC 4346, section 8.2.1)
442  for(n = 0; n < context->premasterSecretLen; n++)
443  {
444  if(context->premasterSecret[n] != 0x00)
445  break;
446  }
447 
448  //Any leading zero bytes?
449  if(n > 0)
450  {
451  //Strip leading zero bytes from the negotiated key
452  osMemmove(context->premasterSecret, context->premasterSecret + n,
453  context->premasterSecretLen - n);
454 
455  //Adjust the length of the premaster secret
456  context->premasterSecretLen -= n;
457  }
458  }
459  else
460 #endif
461 #if (TLS_ECDH_ANON_KE_SUPPORT == ENABLED || TLS_ECDHE_RSA_KE_SUPPORT == ENABLED || \
462  TLS_ECDHE_ECDSA_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
463  //ECDH key exchange method?
464  if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
465  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
466  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
467  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
468  {
469 #if (TLS_ECC_CALLBACK_SUPPORT == ENABLED)
470  //Any registered callback?
471  if(context->ecdhCallback != NULL)
472  {
473  //Invoke user callback function
474  error = context->ecdhCallback(context);
475  }
476  else
477 #endif
478  {
479  //No callback function defined
481  }
482 
483  //Check status code
485  {
486  //Generate an ephemeral key pair
487  error = ecdhGenerateKeyPair(&context->ecdhContext,
488  context->prngAlgo, context->prngContext);
489  //Any error to report?
490  if(error)
491  return error;
492 
493  //Calculate the negotiated key Z
494  error = ecdhComputeSharedSecret(&context->ecdhContext,
495  context->premasterSecret, TLS_PREMASTER_SECRET_SIZE,
496  &context->premasterSecretLen);
497  //Any error to report?
498  if(error)
499  return error;
500  }
501  else if(error != NO_ERROR)
502  {
503  //Report an error
504  return error;
505  }
506 
507  //Encode the client's public key to an opaque vector
508  error = tlsWriteEcPoint(&context->ecdhContext.params,
509  &context->ecdhContext.qa.q, p, &n);
510  //Any error to report?
511  if(error)
512  return error;
513 
514  //Total number of bytes that have been written
515  *written = n;
516  }
517  else
518 #endif
519  //Invalid key exchange method?
520  {
521  //Just for sanity
522  (void) error;
523  (void) n;
524 
525  //The specified key exchange method is not supported
527  }
528 
529  //Successful processing
530  return NO_ERROR;
531 #else
532  //Not implemented
533  return ERROR_NOT_IMPLEMENTED;
534 #endif
535 }
536 
537 
538 /**
539  * @brief Parse PSK identity hint
540  * @param[in] context Pointer to the TLS context
541  * @param[in] p Input stream where to read the PSK identity hint
542  * @param[in] length Number of bytes available in the input stream
543  * @param[out] consumed Total number of bytes that have been consumed
544  * @return Error code
545  **/
546 
547 error_t tlsParsePskIdentityHint(TlsContext *context, const uint8_t *p,
548  size_t length, size_t *consumed)
549 {
550  size_t n;
551  TlsPskIdentityHint *pskIdentityHint;
552 
553  //Point to the PSK identity hint
554  pskIdentityHint = (TlsPskIdentityHint *) p;
555 
556  //Malformed ServerKeyExchange message?
557  if(length < sizeof(TlsPskIdentityHint))
558  return ERROR_DECODING_FAILED;
559  if(length < (sizeof(TlsPskIdentityHint) + ntohs(pskIdentityHint->length)))
560  return ERROR_DECODING_FAILED;
561 
562  //Retrieve the length of the PSK identity hint
563  n = ntohs(pskIdentityHint->length);
564 
565 #if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
566  TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
567  //Any registered callback?
568  if(context->pskCallback != NULL)
569  {
570  error_t error;
571 
572  //The client selects which identity to use depending on the PSK identity
573  //hint provided by the server
574  error = context->pskCallback(context, pskIdentityHint->value, n);
575  //Any error to report?
576  if(error)
577  return ERROR_UNKNOWN_IDENTITY;
578  }
579 #endif
580 
581  //Total number of bytes that have been consumed
582  *consumed = sizeof(TlsPskIdentityHint) + n;
583 
584  //Successful processing
585  return NO_ERROR;
586 }
587 
588 
589 /**
590  * @brief Parse server's key exchange parameters
591  * @param[in] context Pointer to the TLS context
592  * @param[in] p Input stream where to read the server's key exchange parameters
593  * @param[in] length Number of bytes available in the input stream
594  * @param[out] consumed Total number of bytes that have been consumed
595  * @return Error code
596  **/
597 
598 error_t tlsParseServerKeyParams(TlsContext *context, const uint8_t *p,
599  size_t length, size_t *consumed)
600 {
601 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
602  error_t error;
603  const uint8_t *params;
604 
605  //Initialize status code
606  error = NO_ERROR;
607 
608  //Point to the server's key exchange parameters
609  params = p;
610 
611 #if (TLS_DH_ANON_KE_SUPPORT == ENABLED || TLS_DHE_RSA_KE_SUPPORT == ENABLED || \
612  TLS_DHE_DSS_KE_SUPPORT == ENABLED || TLS_DHE_PSK_KE_SUPPORT == ENABLED)
613  //Diffie-Hellman key exchange method?
614  if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
615  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
616  context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
617  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK)
618  {
619  uint_t k;
620  size_t n;
621 
622  //Convert the prime modulus to a multiple precision integer
623  error = tlsReadMpi(&context->dhContext.params.p, p, length, &n);
624 
625  //Check status code
626  if(!error)
627  {
628  //Get the length of the prime modulus, in bits
629  k = mpiGetBitLength(&context->dhContext.params.p);
630 
631  //Make sure the prime modulus is acceptable
632  if(k < TLS_MIN_DH_MODULUS_SIZE || k > TLS_MAX_DH_MODULUS_SIZE)
633  {
634  error = ERROR_ILLEGAL_PARAMETER;
635  }
636  }
637 
638  //Check status code
639  if(!error)
640  {
641  //Advance data pointer
642  p += n;
643  //Remaining bytes to process
644  length -= n;
645 
646  //Convert the generator to a multiple precision integer
647  error = tlsReadMpi(&context->dhContext.params.g, p, length, &n);
648  }
649 
650  //Check status code
651  if(!error)
652  {
653  //Advance data pointer
654  p += n;
655  //Remaining bytes to process
656  length -= n;
657 
658  //Convert the server's public value to a multiple precision integer
659  error = tlsReadMpi(&context->dhContext.yb, p, length, &n);
660  }
661 
662  //Check status code
663  if(!error)
664  {
665  //Advance data pointer
666  p += n;
667  //Remaining bytes to process
668  length -= n;
669 
670  //Verify peer's public value
671  error = dhCheckPublicKey(&context->dhContext.params,
672  &context->dhContext.yb);
673  }
674 
675  //Check status code
676  if(!error)
677  {
678  //Debug message
679  TRACE_DEBUG("Diffie-Hellman parameters:\r\n");
680  TRACE_DEBUG(" Prime modulus:\r\n");
681  TRACE_DEBUG_MPI(" ", &context->dhContext.params.p);
682  TRACE_DEBUG(" Generator:\r\n");
683  TRACE_DEBUG_MPI(" ", &context->dhContext.params.g);
684  TRACE_DEBUG(" Server public value:\r\n");
685  TRACE_DEBUG_MPI(" ", &context->dhContext.yb);
686  }
687  }
688  else
689 #endif
690 #if (TLS_ECDH_ANON_KE_SUPPORT == ENABLED || TLS_ECDHE_RSA_KE_SUPPORT == ENABLED || \
691  TLS_ECDHE_ECDSA_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
692  //ECDH key exchange method?
693  if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
694  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
695  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
696  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
697  {
698  size_t n;
699  uint8_t curveType;
700  const EcCurveInfo *curveInfo;
701 
702  //Initialize curve parameters
703  curveInfo = NULL;
704 
705  //Malformed ServerKeyExchange message?
706  if(length < sizeof(curveType))
707  {
708  error = ERROR_DECODING_FAILED;
709  }
710 
711  //Check status code
712  if(!error)
713  {
714  //Retrieve the type of the elliptic curve domain parameters
715  curveType = *p;
716 
717  //Advance data pointer
718  p += sizeof(curveType);
719  //Remaining bytes to process
720  length -= sizeof(curveType);
721 
722  //Only named curves are supported
723  if(curveType != TLS_EC_CURVE_TYPE_NAMED_CURVE)
724  {
725  error = ERROR_ILLEGAL_PARAMETER;
726  }
727  }
728 
729  //Check status code
730  if(!error)
731  {
732  //Malformed ServerKeyExchange message?
733  if(length < sizeof(uint16_t))
734  {
735  error = ERROR_DECODING_FAILED;
736  }
737  }
738 
739  //Check status code
740  if(!error)
741  {
742  //Get elliptic curve identifier
743  context->namedGroup = LOAD16BE(p);
744 
745  //Advance data pointer
746  p += sizeof(uint16_t);
747  //Remaining bytes to process
748  length -= sizeof(uint16_t);
749 
750  //TLS 1.3 group?
751  if(context->namedGroup == TLS_GROUP_BRAINPOOLP256R1_TLS13 ||
752  context->namedGroup == TLS_GROUP_BRAINPOOLP384R1_TLS13 ||
753  context->namedGroup == TLS_GROUP_BRAINPOOLP512R1_TLS13 ||
754  context->namedGroup == TLS_GROUP_CURVE_SM2)
755  {
756  //These elliptic curves do not apply to any older versions of TLS
757  error = ERROR_ILLEGAL_PARAMETER;
758  }
759  else
760  {
761  //Retrieve the corresponding EC domain parameters
762  curveInfo = tlsGetCurveInfo(context, context->namedGroup);
763 
764  //Make sure the elliptic curve is supported
765  if(curveInfo == NULL)
766  {
767  //The elliptic curve is not supported
768  error = ERROR_ILLEGAL_PARAMETER;
769  }
770  }
771  }
772 
773  //Check status code
774  if(!error)
775  {
776  //Load EC domain parameters
777  error = ecLoadDomainParameters(&context->ecdhContext.params,
778  curveInfo);
779  }
780 
781  //Check status code
782  if(!error)
783  {
784  //Read server's public key
785  error = tlsReadEcPoint(&context->ecdhContext.params,
786  &context->ecdhContext.qb.q, p, length, &n);
787  }
788 
789  //Check status code
790  if(!error)
791  {
792  //Advance data pointer
793  p += n;
794  //Remaining bytes to process
795  length -= n;
796 
797  //Verify peer's public key
798  error = ecdhCheckPublicKey(&context->ecdhContext.params,
799  &context->ecdhContext.qb.q);
800  }
801 
802  //Check status code
803  if(!error)
804  {
805  //Debug message
806  TRACE_DEBUG(" Server public key X:\r\n");
807  TRACE_DEBUG_MPI(" ", &context->ecdhContext.qb.q.x);
808  TRACE_DEBUG(" Server public key Y:\r\n");
809  TRACE_DEBUG_MPI(" ", &context->ecdhContext.qb.q.y);
810  }
811  }
812  else
813 #endif
814  //Invalid key exchange method?
815  {
816  //It is not legal to send the ServerKeyExchange message when a key
817  //exchange method other than DHE_DSS, DHE_RSA, DH_anon, ECDHE_RSA,
818  //ECDHE_ECDSA or ECDH_anon is selected
819  error = ERROR_UNEXPECTED_MESSAGE;
820  }
821 
822  //Total number of bytes that have been consumed
823  *consumed = p - params;
824 
825  //Return status code
826  return error;
827 #else
828  //Not implemented
829  return ERROR_NOT_IMPLEMENTED;
830 #endif
831 }
832 
833 
834 /**
835  * @brief Verify server's key exchange parameters signature (TLS 1.0 and TLS 1.1)
836  * @param[in] context Pointer to the TLS context
837  * @param[in] signature Pointer to the digital signature
838  * @param[in] length Number of bytes available in the input stream
839  * @param[in] params Pointer to the server's key exchange parameters
840  * @param[in] paramsLen Length of the server's key exchange parameters
841  * @param[out] consumed Total number of bytes that have been consumed
842  * @return Error code
843  **/
844 
846  const TlsDigitalSignature *signature, size_t length,
847  const uint8_t *params, size_t paramsLen, size_t *consumed)
848 {
849  error_t error;
850 
851 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
852  //Initialize status code
853  error = NO_ERROR;
854 
855  //Check the length of the digitally-signed element
856  if(length < sizeof(TlsDigitalSignature))
857  return ERROR_DECODING_FAILED;
858  if(length < (sizeof(TlsDigitalSignature) + ntohs(signature->length)))
859  return ERROR_DECODING_FAILED;
860 
861 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
862  //RSA signature algorithm?
863  if(context->peerCertType == TLS_CERT_RSA_SIGN)
864  {
865  Md5Context *md5Context;
866  Sha1Context *sha1Context;
867 
868  //Allocate a memory buffer to hold the MD5 context
869  md5Context = tlsAllocMem(sizeof(Md5Context));
870 
871  //Successful memory allocation?
872  if(md5Context != NULL)
873  {
874  //Compute MD5(ClientHello.random + ServerHello.random +
875  //ServerKeyExchange.params)
876  md5Init(md5Context);
877  md5Update(md5Context, context->clientRandom, TLS_RANDOM_SIZE);
878  md5Update(md5Context, context->serverRandom, TLS_RANDOM_SIZE);
879  md5Update(md5Context, params, paramsLen);
880  md5Final(md5Context, context->serverVerifyData);
881 
882  //Release previously allocated memory
883  tlsFreeMem(md5Context);
884  }
885  else
886  {
887  //Failed to allocate memory
888  error = ERROR_OUT_OF_MEMORY;
889  }
890 
891  //Check status code
892  if(!error)
893  {
894  //Allocate a memory buffer to hold the SHA-1 context
895  sha1Context = tlsAllocMem(sizeof(Sha1Context));
896 
897  //Successful memory allocation?
898  if(sha1Context != NULL)
899  {
900  //Compute SHA(ClientHello.random + ServerHello.random +
901  //ServerKeyExchange.params)
902  sha1Init(sha1Context);
903  sha1Update(sha1Context, context->clientRandom, TLS_RANDOM_SIZE);
904  sha1Update(sha1Context, context->serverRandom, TLS_RANDOM_SIZE);
905  sha1Update(sha1Context, params, paramsLen);
906  sha1Final(sha1Context, context->serverVerifyData + MD5_DIGEST_SIZE);
907 
908  //Release previously allocated memory
909  tlsFreeMem(sha1Context);
910  }
911  else
912  {
913  //Failed to allocate memory
914  error = ERROR_OUT_OF_MEMORY;
915  }
916  }
917 
918  //Check status code
919  if(!error)
920  {
921  //RSA signature verification
922  error = tlsVerifyRsaSignature(&context->peerRsaPublicKey,
923  context->serverVerifyData, signature->value, ntohs(signature->length));
924  }
925  }
926  else
927 #endif
928 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
929  //DSA signature algorithm?
930  if(context->peerCertType == TLS_CERT_DSS_SIGN)
931  {
932  Sha1Context *sha1Context;
933 
934  //Allocate a memory buffer to hold the SHA-1 context
935  sha1Context = tlsAllocMem(sizeof(Sha1Context));
936 
937  //Successful memory allocation?
938  if(sha1Context != NULL)
939  {
940  //Compute SHA(ClientHello.random + ServerHello.random +
941  //ServerKeyExchange.params)
942  sha1Init(sha1Context);
943  sha1Update(sha1Context, context->clientRandom, TLS_RANDOM_SIZE);
944  sha1Update(sha1Context, context->serverRandom, TLS_RANDOM_SIZE);
945  sha1Update(sha1Context, params, paramsLen);
946  sha1Final(sha1Context, context->serverVerifyData);
947 
948  //Release previously allocated memory
949  tlsFreeMem(sha1Context);
950  }
951  else
952  {
953  //Failed to allocate memory
954  error = ERROR_OUT_OF_MEMORY;
955  }
956 
957  //Check status code
958  if(!error)
959  {
960  //DSA signature verification
961  error = tlsVerifyDsaSignature(context, context->serverVerifyData,
962  SHA1_DIGEST_SIZE, signature->value, ntohs(signature->length));
963  }
964  }
965  else
966 #endif
967 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
968  //ECDSA signature algorithm?
969  if(context->peerCertType == TLS_CERT_ECDSA_SIGN)
970  {
971  Sha1Context *sha1Context;
972 
973  //Allocate a memory buffer to hold the SHA-1 context
974  sha1Context = tlsAllocMem(sizeof(Sha1Context));
975 
976  //Successful memory allocation?
977  if(sha1Context != NULL)
978  {
979  //Compute SHA(ClientHello.random + ServerHello.random +
980  //ServerKeyExchange.params)
981  sha1Init(sha1Context);
982  sha1Update(sha1Context, context->clientRandom, TLS_RANDOM_SIZE);
983  sha1Update(sha1Context, context->serverRandom, TLS_RANDOM_SIZE);
984  sha1Update(sha1Context, params, paramsLen);
985  sha1Final(sha1Context, context->serverVerifyData);
986 
987  //Release previously allocated memory
988  tlsFreeMem(sha1Context);
989  }
990 
991  //Check status code
992  if(!error)
993  {
994  //ECDSA signature verification
995  error = tlsVerifyEcdsaSignature(context, context->serverVerifyData,
996  SHA1_DIGEST_SIZE, signature->value, ntohs(signature->length));
997  }
998  }
999  else
1000 #endif
1001  //Invalid signature algorithm?
1002  {
1003  //Report an error
1004  error = ERROR_INVALID_SIGNATURE;
1005  }
1006 
1007  //Total number of bytes that have been consumed
1008  *consumed = sizeof(TlsDigitalSignature) + ntohs(signature->length);
1009 #else
1010  //Not implemented
1011  error = ERROR_NOT_IMPLEMENTED;
1012 #endif
1013 
1014  //Return status code
1015  return error;
1016 }
1017 
1018 
1019 /**
1020  * @brief Verify server's key exchange parameters signature (TLS 1.2)
1021  * @param[in] context Pointer to the TLS context
1022  * @param[in] signature Pointer to the digital signature
1023  * @param[in] length Number of bytes available in the input stream
1024  * @param[in] params Pointer to the server's key exchange parameters
1025  * @param[in] paramsLen Length of the server's key exchange parameters
1026  * @param[out] consumed Total number of bytes that have been consumed
1027  * @return Error code
1028  **/
1029 
1031  const Tls12DigitalSignature *signature, size_t length,
1032  const uint8_t *params, size_t paramsLen, size_t *consumed)
1033 {
1034 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1035  error_t error;
1036  TlsSignatureScheme signScheme;
1037 
1038  //Initialize status code
1039  error = NO_ERROR;
1040 
1041  //Check the length of the digitally-signed element
1042  if(length < sizeof(Tls12DigitalSignature))
1043  return ERROR_DECODING_FAILED;
1044  if(length < (sizeof(Tls12DigitalSignature) + ntohs(signature->length)))
1045  return ERROR_DECODING_FAILED;
1046 
1047  //The algorithm field specifies the signature scheme
1048  signScheme = (TlsSignatureScheme) ntohs(signature->algorithm);
1049 
1050  //If the client has offered the SignatureAlgorithms extension, the signature
1051  //algorithm and hash algorithm must be a pair listed in that extension (refer
1052  //to RFC 5246, section 7.4.3)
1053  if(!tlsIsSignAlgoSupported(context, signScheme))
1054  return ERROR_ILLEGAL_PARAMETER;
1055 
1056 #if (TLS_RSA_SIGN_SUPPORT == ENABLED || TLS_RSA_PSS_SIGN_SUPPORT == ENABLED || \
1057  TLS_DSA_SIGN_SUPPORT == ENABLED || TLS_ECDSA_SIGN_SUPPORT == ENABLED)
1058  //RSA, DSA or ECDSA signature scheme?
1059  if(TLS_SIGN_ALGO(signScheme) == TLS_SIGN_ALGO_RSA ||
1060  TLS_SIGN_ALGO(signScheme) == TLS_SIGN_ALGO_DSA ||
1061  TLS_SIGN_ALGO(signScheme) == TLS_SIGN_ALGO_ECDSA ||
1062  signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA256 ||
1063  signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA384 ||
1064  signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA512 ||
1065  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256 ||
1066  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384 ||
1067  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512)
1068  {
1069  const HashAlgo *hashAlgo;
1070  HashContext *hashContext;
1071 
1072  //Check signature scheme
1073  if(signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA256 ||
1074  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256)
1075  {
1076  //The hashing is intrinsic to the signature algorithm
1078  }
1079  else if(signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA384 ||
1080  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384)
1081  {
1082  //The hashing is intrinsic to the signature algorithm
1084  }
1085  else if(signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA512 ||
1086  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512)
1087  {
1088  //The hashing is intrinsic to the signature algorithm
1090  }
1091  else
1092  {
1093  //Retrieve the hash algorithm used for signing
1094  hashAlgo = tlsGetHashAlgo(TLS_HASH_ALGO(signScheme));
1095  }
1096 
1097  //Make sure the hash algorithm is supported
1098  if(hashAlgo != NULL)
1099  {
1100  //Allocate a memory buffer to hold the hash context
1101  hashContext = tlsAllocMem(hashAlgo->contextSize);
1102 
1103  //Successful memory allocation?
1104  if(hashContext != NULL)
1105  {
1106  //Compute hash(ClientHello.random + ServerHello.random +
1107  //ServerKeyExchange.params)
1108  hashAlgo->init(hashContext);
1109  hashAlgo->update(hashContext, context->clientRandom, TLS_RANDOM_SIZE);
1110  hashAlgo->update(hashContext, context->serverRandom, TLS_RANDOM_SIZE);
1111  hashAlgo->update(hashContext, params, paramsLen);
1112  hashAlgo->final(hashContext, NULL);
1113 
1114 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
1115  //RSASSA-PKCS1-v1_5 signature scheme?
1116  if(TLS_SIGN_ALGO(signScheme) == TLS_SIGN_ALGO_RSA &&
1117  context->peerCertType == TLS_CERT_RSA_SIGN)
1118  {
1119  //Verify RSA signature (RSASSA-PKCS1-v1_5 signature scheme)
1120  error = rsassaPkcs1v15Verify(&context->peerRsaPublicKey,
1121  hashAlgo, hashContext->digest, signature->value,
1122  ntohs(signature->length));
1123  }
1124  else
1125 #endif
1126 #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
1127  //RSASSA-PSS signature scheme (with public key OID rsaEncryption)?
1128  if(signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA256 ||
1129  signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA384 ||
1131  {
1132  //The signature algorithm must be compatible with the key in the
1133  //server's end-entity certificate (refer to RFC 5246, section 7.4.3)
1134  if(context->peerCertType == TLS_CERT_RSA_SIGN)
1135  {
1136  //Verify RSA signature (RSASSA-PSS signature scheme)
1137  error = rsassaPssVerify(&context->peerRsaPublicKey, hashAlgo,
1138  hashAlgo->digestSize, hashContext->digest,
1139  signature->value, ntohs(signature->length));
1140  }
1141  else
1142  {
1143  //Invalid certificate
1144  error = ERROR_INVALID_SIGNATURE;
1145  }
1146  }
1147  else
1148 #endif
1149 #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
1150  //RSASSA-PSS signature scheme (with public key OID RSASSA-PSS)?
1151  if(signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256 ||
1152  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384 ||
1153  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512)
1154  {
1155  //The signature algorithm must be compatible with the key in the
1156  //server's end-entity certificate (refer to RFC 5246, section 7.4.3)
1157  if(context->peerCertType == TLS_CERT_RSA_PSS_SIGN)
1158  {
1159  //Verify RSA signature (RSASSA-PSS signature scheme)
1160  error = rsassaPssVerify(&context->peerRsaPublicKey, hashAlgo,
1161  hashAlgo->digestSize, hashContext->digest,
1162  signature->value, ntohs(signature->length));
1163  }
1164  else
1165  {
1166  //Invalid certificate
1167  error = ERROR_INVALID_SIGNATURE;
1168  }
1169  }
1170  else
1171 #endif
1172 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
1173  //DSA signature scheme?
1174  if(TLS_SIGN_ALGO(signScheme) == TLS_SIGN_ALGO_DSA &&
1175  context->peerCertType == TLS_CERT_DSS_SIGN)
1176  {
1177  //Verify DSA signature
1178  error = tlsVerifyDsaSignature(context, hashContext->digest,
1179  hashAlgo->digestSize, signature->value,
1180  ntohs(signature->length));
1181  }
1182  else
1183 #endif
1184 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
1185  //ECDSA signature scheme?
1186  if(TLS_SIGN_ALGO(signScheme) == TLS_SIGN_ALGO_ECDSA &&
1187  context->peerCertType == TLS_CERT_ECDSA_SIGN)
1188  {
1189  //Verify ECDSA signature
1190  error = tlsVerifyEcdsaSignature(context, hashContext->digest,
1191  hashAlgo->digestSize, signature->value,
1192  ntohs(signature->length));
1193  }
1194  else
1195 #endif
1196  //Invalid signature scheme?
1197  {
1198  //Report an error
1199  error = ERROR_INVALID_SIGNATURE;
1200  }
1201 
1202  //Release previously allocated memory
1203  tlsFreeMem(hashContext);
1204  }
1205  else
1206  {
1207  //Failed to allocate memory
1208  error = ERROR_OUT_OF_MEMORY;
1209  }
1210  }
1211  else
1212  {
1213  //Hash algorithm not supported
1214  error = ERROR_INVALID_SIGNATURE;
1215  }
1216  }
1217  else
1218 #endif
1219 #if (TLS_ED25519_SIGN_SUPPORT == ENABLED)
1220  //Ed25519 signature scheme?
1221  if(signScheme == TLS_SIGN_SCHEME_ED25519 &&
1222  context->peerCertType == TLS_CERT_ED25519_SIGN)
1223  {
1224  DataChunk messageChunks[4];
1225 
1226  //Data to be verified is run through the EdDSA algorithm without
1227  //pre-hashing
1228  messageChunks[0].buffer = context->clientRandom;
1229  messageChunks[0].length = TLS_RANDOM_SIZE;
1230  messageChunks[1].buffer = context->serverRandom;
1231  messageChunks[1].length = TLS_RANDOM_SIZE;
1232  messageChunks[2].buffer = params;
1233  messageChunks[2].length = paramsLen;
1234  messageChunks[3].buffer = NULL;
1235  messageChunks[3].length = 0;
1236 
1237  //Verify Ed25519 signature (PureEdDSA mode)
1238  error = tlsVerifyEd25519Signature(context, messageChunks,
1239  signature->value, ntohs(signature->length));
1240  }
1241  else
1242 #endif
1243 #if (TLS_ED448_SIGN_SUPPORT == ENABLED)
1244  //Ed448 signature scheme?
1245  if(signScheme == TLS_SIGN_SCHEME_ED448 &&
1246  context->peerCertType == TLS_CERT_ED448_SIGN)
1247  {
1248  DataChunk messageChunks[4];
1249 
1250  //Data to be verified is run through the EdDSA algorithm without
1251  //pre-hashing
1252  messageChunks[0].buffer = context->clientRandom;
1253  messageChunks[0].length = TLS_RANDOM_SIZE;
1254  messageChunks[1].buffer = context->serverRandom;
1255  messageChunks[1].length = TLS_RANDOM_SIZE;
1256  messageChunks[2].buffer = params;
1257  messageChunks[2].length = paramsLen;
1258  messageChunks[3].buffer = NULL;
1259  messageChunks[3].length = 0;
1260 
1261  //Verify Ed448 signature (PureEdDSA mode)
1262  error = tlsVerifyEd448Signature(context, messageChunks,
1263  signature->value, ntohs(signature->length));
1264  }
1265  else
1266 #endif
1267  //Invalid signature algorithm?
1268  {
1269  //Report an error
1270  error = ERROR_INVALID_SIGNATURE;
1271  }
1272 
1273  //Total number of bytes that have been consumed
1274  *consumed = sizeof(Tls12DigitalSignature) + ntohs(signature->length);
1275 
1276  //Return status code
1277  return error;
1278 #else
1279  //Not implemented
1280  return ERROR_NOT_IMPLEMENTED;
1281 #endif
1282 }
1283 
1284 
1285 /**
1286  * @brief Version selection
1287  * @param[in] context Pointer to the TLS context
1288  * @param[in] message Pointer to the received ServerHello message
1289  * @param[in] extensions ServerHello extensions offered by the server
1290  * @return Error code
1291  **/
1292 
1295 {
1296  error_t error;
1297  uint16_t selectedVersion;
1298 
1299 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1300  //Clients must check for the SupportedVersions extension prior to
1301  //processing the rest of the ServerHello
1302  if(extensions->selectedVersion != NULL)
1303  {
1304  //If a client receives an extension type in the ServerHello that it did
1305  //not request in the associated ClientHello, it must abort the handshake
1306  //with an unsupported_extension fatal alert
1307  if(context->versionMax <= TLS_VERSION_1_2)
1309 
1310  //The legacy_version field must be set to 0x0303, which is the version
1311  //number for TLS 1.2
1312  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1313  {
1314  if(ntohs(message->serverVersion) != DTLS_VERSION_1_2)
1316  }
1317  else
1318  {
1319  if(ntohs(message->serverVersion) != TLS_VERSION_1_2)
1321  }
1322 
1323  //If this extension is present, clients must ignore the legacy_version
1324  //value and must use only the SupportedVersions extension to determine
1325  //the selected version
1326  selectedVersion = LOAD16BE(extensions->selectedVersion->value);
1327 
1328 #if (DTLS_SUPPORT == ENABLED)
1329  //DTLS protocol?
1330  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1331  {
1332  //If the SupportedVersions extension contains a version prior to DTLS
1333  //1.3, the client must abort the handshake with an illegal_parameter
1334  //alert (refer to RFC 8446, section 4.2.1)
1335  if(selectedVersion >= DTLS_VERSION_1_2)
1336  return ERROR_ILLEGAL_PARAMETER;
1337 
1338  //Check whether the ServerHello message is received in response to an
1339  //updated ClientHello?
1340  if(context->state == TLS_STATE_SERVER_HELLO_2)
1341  {
1342  //The value of selected_version in the SupportedVersions extension
1343  //of the HelloRetryRequest must be retained in the ServerHello. A
1344  //client must abort the handshake with an illegal_parameter alert if
1345  //the value changes (refer to RFC 8446, section 4.1.4)
1346  if(selectedVersion != dtlsTranslateVersion(context->version))
1347  return ERROR_ILLEGAL_PARAMETER;
1348  }
1349  }
1350  else
1351 #endif
1352  //TLS protocol?
1353  {
1354  //If the SupportedVersions extension contains a version prior to TLS
1355  //1.3, the client must abort the handshake with an illegal_parameter
1356  //alert (refer to RFC 8446, section 4.2.1)
1357  if(selectedVersion <= TLS_VERSION_1_2)
1358  return ERROR_ILLEGAL_PARAMETER;
1359 
1360  //Check whether the ServerHello message is received in response to an
1361  //updated ClientHello?
1362  if(context->state == TLS_STATE_SERVER_HELLO_2)
1363  {
1364  //The value of selected_version in the SupportedVersions extension
1365  //of the HelloRetryRequest must be retained in the ServerHello. A
1366  //client must abort the handshake with an illegal_parameter alert if
1367  //the value changes (refer to RFC 8446, section 4.1.4)
1368  if(selectedVersion != context->version)
1369  return ERROR_ILLEGAL_PARAMETER;
1370  }
1371  }
1372  }
1373  else
1374 #endif
1375  {
1376  //In previous versions of TLS, this field was used for version negotiation
1377  //and represented the selected version number for the connection
1378  selectedVersion = ntohs(message->serverVersion);
1379 
1380 #if (DTLS_SUPPORT == ENABLED)
1381  //DTLS protocol?
1382  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1383  {
1384  //A server which negotiates DTLS 1.3 must set the legacy_version field
1385  //to 0xFEFD (DTLS 1.2) and use the SupportedVersions extension instead
1386  if(selectedVersion < DTLS_VERSION_1_2)
1387  return ERROR_ILLEGAL_PARAMETER;
1388  }
1389  else
1390 #endif
1391  //TLS protocol?
1392  {
1393  //A server which negotiates TLS 1.3 must set the legacy_version field
1394  //to 0x0303 (TLS 1.2) and use the SupportedVersions extension instead
1395  if(selectedVersion > TLS_VERSION_1_2)
1396  return ERROR_ILLEGAL_PARAMETER;
1397  }
1398  }
1399 
1400 #if (DTLS_SUPPORT == ENABLED)
1401  //DTLS protocol?
1402  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1403  {
1404  //Set the DTLS version to be used
1405  error = dtlsSelectVersion(context, selectedVersion);
1406  }
1407  else
1408 #endif
1409  //TLS protocol?
1410  {
1411  //Set the TLS version to be used
1412  error = tlsSelectVersion(context, selectedVersion);
1413  }
1414 
1415  //Specified TLS/DTLS version not supported?
1416  if(error)
1417  return error;
1418 
1419 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1420  //If the ServerHello indicates TLS 1.1 or below, TLS 1.3 client must and
1421  //1.2 clients should check that the last 8 bytes are not equal to the
1422  //bytes 44 4F 57 4E 47 52 44 00
1423  if(context->version <= TLS_VERSION_1_1 &&
1424  context->versionMax >= TLS_VERSION_1_2)
1425  {
1426  //If a match is found, the client must abort the handshake with an
1427  //illegal_parameter alert
1428  if(osMemcmp(message->random + 24, tls11DowngradeRandom, 8) == 0)
1429  return ERROR_ILLEGAL_PARAMETER;
1430  }
1431 
1432  //If the ServerHello indicates TLS 1.2 or below, TLS 1.3 client must check
1433  //that the last 8 bytes are not equal to the bytes 44 4F 57 4E 47 52 44 00
1434  if(context->version <= TLS_VERSION_1_2 &&
1435  context->versionMax >= TLS_VERSION_1_3)
1436  {
1437  //If a match is found, the client must abort the handshake with an
1438  //illegal_parameter alert
1439  if(osMemcmp(message->random + 24, tls12DowngradeRandom, 8) == 0)
1440  return ERROR_ILLEGAL_PARAMETER;
1441  }
1442 #endif
1443 
1444  //Successful processing
1445  return NO_ERROR;
1446 }
1447 
1448 
1449 /**
1450  * @brief Resume TLS session via session ID
1451  * @param[in] context Pointer to the TLS context
1452  * @param[in] sessionId Pointer to the session ID provided by the server
1453  * @param[in] sessionIdLen Length of the session ID, in bytes
1454  * @param[in] cipherSuite Cipher suite selected by the server
1455  * @return Error code
1456  **/
1457 
1459  size_t sessionIdLen, uint16_t cipherSuite)
1460 {
1461  error_t error;
1462 
1463  //Initialize status code
1464  error = NO_ERROR;
1465 
1466 #if (TLS_SESSION_RESUME_SUPPORT == ENABLED)
1467  //Check whether the session ID matches the value that was supplied by the
1468  //client
1469  if(sessionIdLen != 0 && sessionIdLen == context->sessionIdLen &&
1470  osMemcmp(sessionId, context->sessionId, sessionIdLen) == 0)
1471  {
1472  //For resumed sessions, the selected cipher suite shall be the same as
1473  //the session being resumed
1474  if(cipherSuite != 0 && cipherSuite == context->cipherSuite.identifier)
1475  {
1476  //Perform abbreviated handshake
1477  context->resume = TRUE;
1478  }
1479  else
1480  {
1481  //The session ID is no more valid
1482  context->sessionIdLen = 0;
1483 
1484  //When renegotiating, if the server tries to use another version or
1485  //compression method than previously, abort
1486  error = ERROR_ILLEGAL_PARAMETER;
1487  }
1488  }
1489  else
1490 #endif
1491  {
1492  //Perform a full handshake
1493  context->resume = FALSE;
1494  }
1495 
1496  //Return status code
1497  return error;
1498 }
1499 
1500 
1501 /**
1502  * @brief Check whether a session ticket is valid
1503  * @param[in] context Pointer to the TLS context
1504  * @return TRUE is the session ticket is valid, else FALSE
1505  **/
1506 
1508 {
1509  bool_t valid = FALSE;
1510 
1511  //TLS 1.3 tickets cannot be used to resume a TLS 1.2 session
1512  if(context->version <= TLS_VERSION_1_2)
1513  {
1514  //Valid ticket?
1515  if(context->ticket != NULL && context->ticketLen > 0)
1516  {
1517  valid = TRUE;
1518  }
1519  }
1520 
1521  //Return TRUE is the ticket is valid, else FALSE
1522  return valid;
1523 }
1524 
1525 #endif
@ TLS_GROUP_BRAINPOOLP512R1_TLS13
Definition: tls.h:1403
#define tlsAllocMem(size)
Definition: tls.h:853
#define htons(value)
Definition: cpu_endian.h:413
Parsing and checking of TLS extensions.
@ TLS_SIGN_ALGO_DSA
Definition: tls.h:1233
TLS helper functions.
const uint8_t tls11DowngradeRandom[8]
Definition: tls13_misc.c:53
@ ERROR_UNKNOWN_IDENTITY
Definition: error.h:260
HashAlgoInit init
Definition: crypto.h:1056
@ ERROR_UNSUPPORTED_ELLIPTIC_CURVE
Definition: error.h:133
uint8_t extensions[]
Definition: ntp_common.h:207
@ TLS_GROUP_BRAINPOOLP256R1_TLS13
Definition: tls.h:1401
Generic hash algorithm context.
int bool_t
Definition: compiler_port.h:53
uint8_t sessionId[]
Definition: tls.h:1773
TLS cipher suites.
uint16_t cipherSuite
Cipher suite identifier.
Definition: tls.h:1883
error_t dtlsSelectVersion(TlsContext *context, uint16_t version)
Set the DTLS version to be used.
Definition: dtls_misc.c:53
const HashAlgo * tlsGetHashAlgo(TlsHashAlgo hashAlgoId)
Get the hash algorithm that matches the specified identifier.
Definition: tls_misc.c:1173
TlsDigitalSignature
Definition: tls.h:1717
@ TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA256
Definition: tls.h:1253
#define TLS_MAX_DH_MODULUS_SIZE
Definition: tls.h:766
void sha1Update(Sha1Context *context, const void *data, size_t length)
Update the SHA-1 context with a portion of the message being hashed.
@ TLS_COMPRESSION_METHOD_NULL
Definition: tls.h:1128
error_t tlsVerifyServerKeySignature(TlsContext *context, const TlsDigitalSignature *signature, size_t length, const uint8_t *params, size_t paramsLen, size_t *consumed)
Verify server's key exchange parameters signature (TLS 1.0 and TLS 1.1)
@ ERROR_VERSION_NOT_SUPPORTED
Definition: error.h:67
@ ERROR_NOT_IMPLEMENTED
Definition: error.h:66
@ ERROR_ILLEGAL_PARAMETER
Definition: error.h:243
@ ERROR_UNEXPECTED_MESSAGE
Definition: error.h:194
error_t tlsFormatCipherSuites(TlsContext *context, uint8_t *p, size_t *written)
Format the list of cipher suites supported by the client.
uint8_t p
Definition: ndp.h:300
Helper functions for TLS client.
uint8_t message[]
Definition: chap.h:154
error_t tlsSelectVersion(TlsContext *context, uint16_t version)
Set the TLS version to be used.
Definition: tls_misc.c:305
error_t dhCheckPublicKey(DhParameters *params, const Mpi *publicKey)
Check Diffie-Hellman public value.
Definition: dh.c:183
#define TRUE
Definition: os_port.h:50
@ TLS_GROUP_CURVE_SM2
Definition: tls.h:1411
size_t digestSize
Definition: crypto.h:1052
error_t tlsResumeSession(TlsContext *context, const uint8_t *sessionId, size_t sessionIdLen, uint16_t cipherSuite)
Resume TLS session via session ID.
const void * buffer
Definition: crypto.h:982
@ TLS_TRANSPORT_PROTOCOL_DATAGRAM
Definition: tls.h:957
HashAlgoUpdate update
Definition: crypto.h:1057
void md5Final(Md5Context *context, uint8_t *digest)
Finish the MD5 message digest.
Session cache management.
TlsPskIdentity
Definition: tls.h:1695
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512
Definition: tls.h:1258
error_t tlsWriteMpi(const Mpi *a, uint8_t *data, size_t *length)
Encode a multiple precision integer to an opaque vector.
Definition: tls_misc.c:958
#define osMemcmp(p1, p2, length)
Definition: os_port.h:153
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
error_t tlsFormatSessionId(TlsContext *context, uint8_t *p, size_t *written)
Format session ID.
const uint8_t tls12DowngradeRandom[8]
Definition: tls13_misc.c:59
@ TLS_CERT_DSS_SIGN
Definition: tls.h:1189
@ TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA512
Definition: tls.h:1255
@ TLS_SIGN_SCHEME_ED25519
Definition: tls.h:1267
#define osStrlen(s)
Definition: os_port.h:165
#define TLS_RANDOM_SIZE
Definition: tls.h:938
#define TLS_HASH_ALGO(signScheme)
Definition: tls_sign_misc.h:41
TlsPskIdentityHint
Definition: tls.h:1706
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384
Definition: tls.h:1257
@ TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA384
Definition: tls.h:1254
error_t tlsParsePskIdentityHint(TlsContext *context, const uint8_t *p, size_t length, size_t *consumed)
Parse PSK identity hint.
size_t contextSize
Definition: crypto.h:1050
uint8_t sessionIdLen
Definition: tls.h:1772
@ TLS_KEY_EXCH_RSA
Definition: tls.h:1140
void md5Init(Md5Context *context)
Initialize MD5 message digest context.
TlsCipherSuites
Definition: tls.h:1517
@ TLS_HASH_ALGO_SHA512
Definition: tls.h:1219
@ TLS_KEY_EXCH_ECDHE_ECDSA
Definition: tls.h:1149
error_t ecLoadDomainParameters(EcDomainParameters *params, const EcCurveInfo *curveInfo)
Load EC domain parameters.
Definition: ec.c:90
@ TLS_KEY_EXCH_ECDHE_RSA
Definition: tls.h:1147
TlsHandshake
Definition: tls.h:1754
#define FALSE
Definition: os_port.h:46
error_t dhComputeSharedSecret(DhContext *context, uint8_t *output, size_t outputSize, size_t *outputLen)
Compute Diffie-Hellman shared secret.
Definition: dh.c:223
@ TLS_KEY_EXCH_ECDH_ANON
Definition: tls.h:1150
Elliptic curve parameters.
Definition: ec_curves.h:302
bool_t tlsIsSignAlgoSupported(TlsContext *context, uint16_t signScheme)
Check whether a signature algorithm can be used for digital signatures.
error_t tlsVerifyRsaSignature(const RsaPublicKey *key, const uint8_t *digest, const uint8_t *signature, size_t signatureLen)
Verify RSA signature (TLS 1.0 and TLS 1.1)
void sha1Init(Sha1Context *context)
Initialize SHA-1 message digest context.
#define osMemcpy(dest, src, length)
Definition: os_port.h:141
@ ERROR_UNSUPPORTED_EXTENSION
Definition: error.h:245
#define TlsContext
Definition: tls.h:36
error_t
Error codes.
Definition: error.h:43
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256
Definition: tls.h:1256
@ TLS_CERT_ED25519_SIGN
Definition: tls.h:1202
error_t rsaesPkcs1v15Encrypt(const PrngAlgo *prngAlgo, void *prngContext, const RsaPublicKey *key, const uint8_t *message, size_t messageLen, uint8_t *ciphertext, size_t *ciphertextLen)
RSAES-PKCS1-v1_5 encryption operation.
Definition: rsa.c:179
error_t tlsVerifyDsaSignature(TlsContext *context, const uint8_t *digest, size_t digestLen, const uint8_t *signature, size_t signatureLen)
Verify DSA signature.
#define TLS_VERSION_1_2
Definition: tls.h:96
#define TLS_PREMASTER_SECRET_SIZE
Definition: tls.h:808
@ TLS_KEY_EXCH_DH_ANON
Definition: tls.h:1145
#define TLS_MAX_VERSION
Definition: tls.h:129
#define STORE16BE(a, p)
Definition: cpu_endian.h:262
@ TLS_TYPE_CLIENT_HELLO
Definition: tls.h:1041
error_t tlsSelectClientVersion(TlsContext *context, const TlsServerHello *message, const TlsHelloExtensions *extensions)
Version selection.
Tls12DigitalSignature
Definition: tls.h:1729
uint16_t identifier
Definition: tls.h:2017
@ TLS_CIPHER_SUITE_TYPE_UNKNOWN
uint8_t digest[MAX_HASH_DIGEST_SIZE]
#define TLS_VERSION_1_3
Definition: tls.h:97
Handshake message processing (TLS client and server)
@ TLS_HASH_ALGO_SHA384
Definition: tls.h:1218
@ TLS_CERT_RSA_PSS_SIGN
Definition: tls.h:1200
__weak_func error_t tls12VerifyServerKeySignature(TlsContext *context, const Tls12DigitalSignature *signature, size_t length, const uint8_t *params, size_t paramsLen, size_t *consumed)
Verify server's key exchange parameters signature (TLS 1.2)
@ TLS_EMPTY_RENEGOTIATION_INFO_SCSV
TLS record protocol.
error_t tlsWriteEcPoint(const EcDomainParameters *params, const EcPoint *a, uint8_t *data, size_t *length)
Encode an EC point to an opaque vector.
Definition: tls_misc.c:1029
MD5 algorithm context.
Definition: md5.h:62
@ TLS_TRANSPORT_PROTOCOL_EAP
Definition: tls.h:958
@ TLS_HASH_ALGO_SHA256
Definition: tls.h:1217
@ TLS_CERT_ED448_SIGN
Definition: tls.h:1203
error_t tlsFormatInitialClientHello(TlsContext *context)
Format initial ClientHello message.
@ TLS_CERT_RSA_SIGN
Definition: tls.h:1188
uint8_t length
Definition: tcp.h:368
@ TLS_KEY_EXCH_DHE_PSK
Definition: tls.h:1153
TlsCompressMethods
Definition: tls.h:1528
uint16_t dtlsTranslateVersion(uint16_t version)
Translate TLS version into DTLS version.
Definition: dtls_misc.c:112
#define MD5_DIGEST_SIZE
Definition: md5.h:45
RSA/DSA/ECDSA/EdDSA signature verification.
Hello extensions.
Definition: tls.h:2098
@ TLS_FALLBACK_SCSV
uint_t mpiGetBitLength(const Mpi *a)
Get the actual length in bits.
Definition: mpi.c:234
@ TLS_GROUP_BRAINPOOLP384R1_TLS13
Definition: tls.h:1402
error_t ecdhComputeSharedSecret(EcdhContext *context, uint8_t *output, size_t outputSize, size_t *outputLen)
Compute ECDH shared secret.
Definition: ecdh.c:340
@ ERROR_UNSUPPORTED_KEY_EXCH_ALGO
Definition: error.h:131
@ TLS_KEY_EXCH_RSA_PSK
Definition: tls.h:1152
bool_t tlsIsCipherSuiteAcceptable(const TlsCipherSuiteInfo *cipherSuite, uint16_t minVersion, uint16_t maxVersion, TlsTransportProtocol transportProtocol)
Check whether a cipher suite can be used with a given protocol version.
HashAlgoFinal final
Definition: crypto.h:1058
Data chunk descriptor.
Definition: crypto.h:981
#define ntohs(value)
Definition: cpu_endian.h:421
TlsRecord
Definition: tls.h:1742
error_t tlsVerifyEcdsaSignature(TlsContext *context, const uint8_t *digest, size_t digestLen, const uint8_t *signature, size_t signatureLen)
Verify ECDSA signature.
@ TLS_EC_CURVE_TYPE_NAMED_CURVE
Definition: tls.h:1445
#define TRACE_DEBUG(...)
Definition: debug.h:107
error_t rsassaPkcs1v15Verify(const RsaPublicKey *key, const HashAlgo *hash, const uint8_t *digest, const uint8_t *signature, size_t signatureLen)
RSASSA-PKCS1-v1_5 signature verification operation.
Definition: rsa.c:838
#define TLS_VERSION_1_1
Definition: tls.h:95
#define SHA1_DIGEST_SIZE
Definition: sha1.h:45
__weak_func error_t tlsFormatClientKeyParams(TlsContext *context, uint8_t *p, size_t *written)
Format client's key exchange parameters.
error_t tlsReadMpi(Mpi *a, const uint8_t *data, size_t size, size_t *length)
Read a multiple precision integer from an opaque vector.
Definition: tls_misc.c:991
const char_t * tlsGetCipherSuiteName(uint16_t identifier)
Convert cipher suite identifier to string representation.
TlsServerHello
Definition: tls.h:1787
error_t tlsVerifyEd25519Signature(TlsContext *context, const DataChunk *messageChunks, const uint8_t *signature, size_t signatureLen)
Verify Ed25519 signature.
#define HTONS(value)
Definition: cpu_endian.h:410
uint8_t n
error_t rsassaPssVerify(const RsaPublicKey *key, const HashAlgo *hash, size_t saltLen, const uint8_t *digest, const uint8_t *signature, size_t signatureLen)
RSASSA-PSS signature verification operation.
Definition: rsa.c:1079
@ TLS_SIGN_SCHEME_ED448
Definition: tls.h:1268
const TlsCipherSuiteInfo tlsSupportedCipherSuites[]
@ TLS_KEY_EXCH_ECDHE_PSK
Definition: tls.h:1154
TlsClientHello
Definition: tls.h:1774
Helper functions for signature generation and verification.
const EcCurveInfo * tlsGetCurveInfo(TlsContext *context, uint16_t namedCurve)
Get the EC domain parameters that match the specified named curve.
Definition: tls_misc.c:1240
TLS (Transport Layer Security)
uint8_t identifier[]
@ TLS_SIGN_ALGO_RSA
Definition: tls.h:1232
#define STORE24BE(a, p)
Definition: cpu_endian.h:273
SHA-1 algorithm context.
Definition: sha1.h:62
@ TLS_CERT_ECDSA_SIGN
Definition: tls.h:1195
@ TLS_KEY_EXCH_DHE_DSS
Definition: tls.h:1144
size_t length
Definition: crypto.h:983
@ TLS_TRANSPORT_PROTOCOL_STREAM
Definition: tls.h:956
Common interface for hash algorithms.
Definition: crypto.h:1046
#define TLS_SIGN_ALGO(signScheme)
Definition: tls_sign_misc.h:38
FFDHE key exchange.
error_t tlsParseServerKeyParams(TlsContext *context, const uint8_t *p, size_t length, size_t *consumed)
Parse server's key exchange parameters.
uint_t tlsGetNumSupportedCipherSuites(void)
Determine the number of cipher suites supported.
error_t dhGenerateKeyPair(DhContext *context, const PrngAlgo *prngAlgo, void *prngContext)
Diffie-Hellman key pair generation.
Definition: dh.c:119
TlsSignatureScheme
Signature schemes.
Definition: tls.h:1247
@ ERROR_DECODING_FAILED
Definition: error.h:241
error_t tlsFormatPskIdentity(TlsContext *context, uint8_t *p, size_t *written)
Format PSK identity.
unsigned int uint_t
Definition: compiler_port.h:50
#define TRACE_DEBUG_MPI(p, a)
Definition: debug.h:110
#define LOAD16BE(p)
Definition: cpu_endian.h:186
Handshake message processing (TLS client)
void sha1Final(Sha1Context *context, uint8_t *digest)
Finish the SHA-1 message digest.
#define tlsFreeMem(p)
Definition: tls.h:858
@ TLS_STATE_SERVER_HELLO_2
Definition: tls.h:1462
@ ERROR_INVALID_SIGNATURE
Definition: error.h:227
@ TLS_SIGN_ALGO_ECDSA
Definition: tls.h:1234
error_t ecdhCheckPublicKey(const EcDomainParameters *params, EcPoint *publicKey)
Check ECDH public key.
Definition: ecdh.c:227
@ TLS_KEY_EXCH_DHE_RSA
Definition: tls.h:1142
#define DTLS_VERSION_1_2
Definition: dtls_misc.h:36
error_t tlsVerifyEd448Signature(TlsContext *context, const DataChunk *messageChunks, const uint8_t *signature, size_t signatureLen)
Verify Ed448 signature.
void md5Update(Md5Context *context, const void *data, size_t length)
Update the MD5 context with a portion of the message being hashed.
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
error_t tlsFormatClientHello(TlsContext *context, TlsClientHello *message, size_t *length)
Format ClientHello message.
Definition: tls_client.c:312
#define osMemmove(dest, src, length)
Definition: os_port.h:147
error_t tlsReadEcPoint(const EcDomainParameters *params, EcPoint *a, const uint8_t *data, size_t size, size_t *length)
Read an EC point from an opaque vector.
Definition: tls_misc.c:1066
uint_t tlsGetCipherSuiteType(uint16_t identifier)
Retrieve the cipher suite type for a given identifier.
error_t ecdhGenerateKeyPair(EcdhContext *context, const PrngAlgo *prngAlgo, void *prngContext)
ECDH key pair generation.
Definition: ecdh.c:85
error_t tlsFormatCompressMethods(TlsContext *context, uint8_t *p, size_t *written)
Format the list of compression methods supported by the client.
bool_t tlsIsTicketValid(TlsContext *context)
Check whether a session ticket is valid.