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-2025 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.5.0
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.da.q, p, &n);
509  //Any error to report?
510  if(error)
511  return error;
512 
513  //Total number of bytes that have been written
514  *written = n;
515  }
516  else
517 #endif
518  //Invalid key exchange method?
519  {
520  //Just for sanity
521  (void) error;
522  (void) n;
523 
524  //The specified key exchange method is not supported
526  }
527 
528  //Successful processing
529  return NO_ERROR;
530 #else
531  //Not implemented
532  return ERROR_NOT_IMPLEMENTED;
533 #endif
534 }
535 
536 
537 /**
538  * @brief Parse PSK identity hint
539  * @param[in] context Pointer to the TLS context
540  * @param[in] p Input stream where to read the PSK identity hint
541  * @param[in] length Number of bytes available in the input stream
542  * @param[out] consumed Total number of bytes that have been consumed
543  * @return Error code
544  **/
545 
546 error_t tlsParsePskIdentityHint(TlsContext *context, const uint8_t *p,
547  size_t length, size_t *consumed)
548 {
549  size_t n;
550  TlsPskIdentityHint *pskIdentityHint;
551 
552  //Point to the PSK identity hint
553  pskIdentityHint = (TlsPskIdentityHint *) p;
554 
555  //Malformed ServerKeyExchange message?
556  if(length < sizeof(TlsPskIdentityHint))
557  return ERROR_DECODING_FAILED;
558  if(length < (sizeof(TlsPskIdentityHint) + ntohs(pskIdentityHint->length)))
559  return ERROR_DECODING_FAILED;
560 
561  //Retrieve the length of the PSK identity hint
562  n = ntohs(pskIdentityHint->length);
563 
564 #if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
565  TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
566  //Any registered callback?
567  if(context->pskCallback != NULL)
568  {
569  error_t error;
570 
571  //The client selects which identity to use depending on the PSK identity
572  //hint provided by the server
573  error = context->pskCallback(context, pskIdentityHint->value, n);
574  //Any error to report?
575  if(error)
576  return ERROR_UNKNOWN_IDENTITY;
577  }
578 #endif
579 
580  //Total number of bytes that have been consumed
581  *consumed = sizeof(TlsPskIdentityHint) + n;
582 
583  //Successful processing
584  return NO_ERROR;
585 }
586 
587 
588 /**
589  * @brief Parse server's key exchange parameters
590  * @param[in] context Pointer to the TLS context
591  * @param[in] p Input stream where to read the server's key exchange parameters
592  * @param[in] length Number of bytes available in the input stream
593  * @param[out] consumed Total number of bytes that have been consumed
594  * @return Error code
595  **/
596 
597 error_t tlsParseServerKeyParams(TlsContext *context, const uint8_t *p,
598  size_t length, size_t *consumed)
599 {
600 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
601  error_t error;
602  const uint8_t *params;
603 
604  //Initialize status code
605  error = NO_ERROR;
606 
607  //Point to the server's key exchange parameters
608  params = p;
609 
610 #if (TLS_DH_ANON_KE_SUPPORT == ENABLED || TLS_DHE_RSA_KE_SUPPORT == ENABLED || \
611  TLS_DHE_DSS_KE_SUPPORT == ENABLED || TLS_DHE_PSK_KE_SUPPORT == ENABLED)
612  //Diffie-Hellman key exchange method?
613  if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
614  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
615  context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
616  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK)
617  {
618  uint_t k;
619  size_t n;
620 
621  //Convert the prime modulus to a multiple precision integer
622  error = tlsReadMpi(&context->dhContext.params.p, p, length, &n);
623 
624  //Check status code
625  if(!error)
626  {
627  //Get the length of the prime modulus, in bits
628  k = mpiGetBitLength(&context->dhContext.params.p);
629 
630  //Make sure the prime modulus is acceptable
631  if(k < TLS_MIN_DH_MODULUS_SIZE || k > TLS_MAX_DH_MODULUS_SIZE)
632  {
633  error = ERROR_ILLEGAL_PARAMETER;
634  }
635  }
636 
637  //Check status code
638  if(!error)
639  {
640  //Advance data pointer
641  p += n;
642  //Remaining bytes to process
643  length -= n;
644 
645  //Convert the generator to a multiple precision integer
646  error = tlsReadMpi(&context->dhContext.params.g, p, length, &n);
647  }
648 
649  //Check status code
650  if(!error)
651  {
652  //Advance data pointer
653  p += n;
654  //Remaining bytes to process
655  length -= n;
656 
657  //Convert the server's public value to a multiple precision integer
658  error = tlsReadMpi(&context->dhContext.yb, p, length, &n);
659  }
660 
661  //Check status code
662  if(!error)
663  {
664  //Advance data pointer
665  p += n;
666  //Remaining bytes to process
667  length -= n;
668 
669  //Verify peer's public value
670  error = dhCheckPublicKey(&context->dhContext,
671  &context->dhContext.yb);
672  }
673 
674  //Check status code
675  if(!error)
676  {
677  //Debug message
678  TRACE_DEBUG("Diffie-Hellman parameters:\r\n");
679  TRACE_DEBUG(" Prime modulus:\r\n");
680  TRACE_DEBUG_MPI(" ", &context->dhContext.params.p);
681  TRACE_DEBUG(" Generator:\r\n");
682  TRACE_DEBUG_MPI(" ", &context->dhContext.params.g);
683  TRACE_DEBUG(" Server public value:\r\n");
684  TRACE_DEBUG_MPI(" ", &context->dhContext.yb);
685  }
686  }
687  else
688 #endif
689 #if (TLS_ECDH_ANON_KE_SUPPORT == ENABLED || TLS_ECDHE_RSA_KE_SUPPORT == ENABLED || \
690  TLS_ECDHE_ECDSA_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
691  //ECDH key exchange method?
692  if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
693  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
694  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
695  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
696  {
697  size_t n;
698  uint8_t curveType;
699  const EcCurve *curve;
700 
701  //Initialize curve parameters
702  curve = NULL;
703 
704  //Malformed ServerKeyExchange message?
705  if(length < sizeof(curveType))
706  {
707  error = ERROR_DECODING_FAILED;
708  }
709 
710  //Check status code
711  if(!error)
712  {
713  //Retrieve the type of the elliptic curve domain parameters
714  curveType = *p;
715 
716  //Advance data pointer
717  p += sizeof(curveType);
718  //Remaining bytes to process
719  length -= sizeof(curveType);
720 
721  //Only named curves are supported
722  if(curveType != TLS_EC_CURVE_TYPE_NAMED_CURVE)
723  {
724  error = ERROR_ILLEGAL_PARAMETER;
725  }
726  }
727 
728  //Check status code
729  if(!error)
730  {
731  //Malformed ServerKeyExchange message?
732  if(length < sizeof(uint16_t))
733  {
734  error = ERROR_DECODING_FAILED;
735  }
736  }
737 
738  //Check status code
739  if(!error)
740  {
741  //Get elliptic curve identifier
742  context->namedGroup = LOAD16BE(p);
743 
744  //Advance data pointer
745  p += sizeof(uint16_t);
746  //Remaining bytes to process
747  length -= sizeof(uint16_t);
748 
749  //TLS 1.3 group?
750  if(context->namedGroup == TLS_GROUP_BRAINPOOLP256R1_TLS13 ||
751  context->namedGroup == TLS_GROUP_BRAINPOOLP384R1_TLS13 ||
752  context->namedGroup == TLS_GROUP_BRAINPOOLP512R1_TLS13 ||
753  context->namedGroup == TLS_GROUP_CURVE_SM2)
754  {
755  //These elliptic curves do not apply to any older versions of TLS
756  error = ERROR_ILLEGAL_PARAMETER;
757  }
758  else
759  {
760  //Retrieve the corresponding EC domain parameters
761  curve = tlsGetCurve(context, context->namedGroup);
762 
763  //Make sure the elliptic curve is supported
764  if(curve == NULL)
765  {
766  //The elliptic curve is not supported
767  error = ERROR_ILLEGAL_PARAMETER;
768  }
769  }
770  }
771 
772  //Check status code
773  if(!error)
774  {
775  //Save elliptic curve parameters
776  context->ecdhContext.curve = curve;
777 
778  //Read server's public key
779  error = tlsReadEcPoint(&context->ecdhContext.qb, curve, p, length, &n);
780  }
781 
782  //Check status code
783  if(!error)
784  {
785  //Advance data pointer
786  p += n;
787  //Remaining bytes to process
788  length -= n;
789 
790  //Verify peer's public key
791  error = ecdhCheckPublicKey(&context->ecdhContext,
792  &context->ecdhContext.qb);
793  }
794 
795  //Check status code
796  if(!error)
797  {
798  //Debug message
799  TRACE_DEBUG(" Server public key X:\r\n");
800  TRACE_DEBUG_MPI(" ", &context->ecdhContext.qb.q.x);
801  TRACE_DEBUG(" Server public key Y:\r\n");
802  TRACE_DEBUG_MPI(" ", &context->ecdhContext.qb.q.y);
803  }
804  }
805  else
806 #endif
807  //Invalid key exchange method?
808  {
809  //It is not legal to send the ServerKeyExchange message when a key
810  //exchange method other than DHE_DSS, DHE_RSA, DH_anon, ECDHE_RSA,
811  //ECDHE_ECDSA or ECDH_anon is selected
812  error = ERROR_UNEXPECTED_MESSAGE;
813  }
814 
815  //Total number of bytes that have been consumed
816  *consumed = p - params;
817 
818  //Return status code
819  return error;
820 #else
821  //Not implemented
822  return ERROR_NOT_IMPLEMENTED;
823 #endif
824 }
825 
826 
827 /**
828  * @brief Verify server's key exchange parameters signature (TLS 1.0 and TLS 1.1)
829  * @param[in] context Pointer to the TLS context
830  * @param[in] signature Pointer to the digital signature
831  * @param[in] length Number of bytes available in the input stream
832  * @param[in] params Pointer to the server's key exchange parameters
833  * @param[in] paramsLen Length of the server's key exchange parameters
834  * @param[out] consumed Total number of bytes that have been consumed
835  * @return Error code
836  **/
837 
839  const TlsDigitalSignature *signature, size_t length,
840  const uint8_t *params, size_t paramsLen, size_t *consumed)
841 {
842  error_t error;
843 
844 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
845  //Initialize status code
846  error = NO_ERROR;
847 
848  //Check the length of the digitally-signed element
849  if(length < sizeof(TlsDigitalSignature))
850  return ERROR_DECODING_FAILED;
851  if(length < (sizeof(TlsDigitalSignature) + ntohs(signature->length)))
852  return ERROR_DECODING_FAILED;
853 
854 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
855  //RSA signature algorithm?
856  if(context->peerCertType == TLS_CERT_RSA_SIGN)
857  {
858  Md5Context *md5Context;
859  Sha1Context *sha1Context;
860 
861  //Allocate a memory buffer to hold the MD5 context
862  md5Context = tlsAllocMem(sizeof(Md5Context));
863 
864  //Successful memory allocation?
865  if(md5Context != NULL)
866  {
867  //Compute MD5(ClientHello.random + ServerHello.random +
868  //ServerKeyExchange.params)
869  md5Init(md5Context);
870  md5Update(md5Context, context->clientRandom, TLS_RANDOM_SIZE);
871  md5Update(md5Context, context->serverRandom, TLS_RANDOM_SIZE);
872  md5Update(md5Context, params, paramsLen);
873  md5Final(md5Context, context->serverVerifyData);
874 
875  //Release previously allocated memory
876  tlsFreeMem(md5Context);
877  }
878  else
879  {
880  //Failed to allocate memory
881  error = ERROR_OUT_OF_MEMORY;
882  }
883 
884  //Check status code
885  if(!error)
886  {
887  //Allocate a memory buffer to hold the SHA-1 context
888  sha1Context = tlsAllocMem(sizeof(Sha1Context));
889 
890  //Successful memory allocation?
891  if(sha1Context != NULL)
892  {
893  //Compute SHA(ClientHello.random + ServerHello.random +
894  //ServerKeyExchange.params)
895  sha1Init(sha1Context);
896  sha1Update(sha1Context, context->clientRandom, TLS_RANDOM_SIZE);
897  sha1Update(sha1Context, context->serverRandom, TLS_RANDOM_SIZE);
898  sha1Update(sha1Context, params, paramsLen);
899  sha1Final(sha1Context, context->serverVerifyData + MD5_DIGEST_SIZE);
900 
901  //Release previously allocated memory
902  tlsFreeMem(sha1Context);
903  }
904  else
905  {
906  //Failed to allocate memory
907  error = ERROR_OUT_OF_MEMORY;
908  }
909  }
910 
911  //Check status code
912  if(!error)
913  {
914  //RSA signature verification
915  error = tlsVerifyRsaSignature(&context->peerRsaPublicKey,
916  context->serverVerifyData, signature->value, ntohs(signature->length));
917  }
918  }
919  else
920 #endif
921 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
922  //DSA signature algorithm?
923  if(context->peerCertType == TLS_CERT_DSS_SIGN)
924  {
925  Sha1Context *sha1Context;
926 
927  //Allocate a memory buffer to hold the SHA-1 context
928  sha1Context = tlsAllocMem(sizeof(Sha1Context));
929 
930  //Successful memory allocation?
931  if(sha1Context != NULL)
932  {
933  //Compute SHA(ClientHello.random + ServerHello.random +
934  //ServerKeyExchange.params)
935  sha1Init(sha1Context);
936  sha1Update(sha1Context, context->clientRandom, TLS_RANDOM_SIZE);
937  sha1Update(sha1Context, context->serverRandom, TLS_RANDOM_SIZE);
938  sha1Update(sha1Context, params, paramsLen);
939  sha1Final(sha1Context, context->serverVerifyData);
940 
941  //Release previously allocated memory
942  tlsFreeMem(sha1Context);
943  }
944  else
945  {
946  //Failed to allocate memory
947  error = ERROR_OUT_OF_MEMORY;
948  }
949 
950  //Check status code
951  if(!error)
952  {
953  //DSA signature verification
954  error = tlsVerifyDsaSignature(context, context->serverVerifyData,
955  SHA1_DIGEST_SIZE, signature->value, ntohs(signature->length));
956  }
957  }
958  else
959 #endif
960 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
961  //ECDSA signature algorithm?
962  if(context->peerCertType == TLS_CERT_ECDSA_SIGN)
963  {
964  Sha1Context *sha1Context;
965 
966  //Allocate a memory buffer to hold the SHA-1 context
967  sha1Context = tlsAllocMem(sizeof(Sha1Context));
968 
969  //Successful memory allocation?
970  if(sha1Context != NULL)
971  {
972  //Compute SHA(ClientHello.random + ServerHello.random +
973  //ServerKeyExchange.params)
974  sha1Init(sha1Context);
975  sha1Update(sha1Context, context->clientRandom, TLS_RANDOM_SIZE);
976  sha1Update(sha1Context, context->serverRandom, TLS_RANDOM_SIZE);
977  sha1Update(sha1Context, params, paramsLen);
978  sha1Final(sha1Context, context->serverVerifyData);
979 
980  //Release previously allocated memory
981  tlsFreeMem(sha1Context);
982  }
983 
984  //Check status code
985  if(!error)
986  {
987  //ECDSA signature verification
988  error = tlsVerifyEcdsaSignature(context, context->serverVerifyData,
989  SHA1_DIGEST_SIZE, signature->value, ntohs(signature->length));
990  }
991  }
992  else
993 #endif
994  //Invalid signature algorithm?
995  {
996  //Report an error
997  error = ERROR_INVALID_SIGNATURE;
998  }
999 
1000  //Total number of bytes that have been consumed
1001  *consumed = sizeof(TlsDigitalSignature) + ntohs(signature->length);
1002 #else
1003  //Not implemented
1004  error = ERROR_NOT_IMPLEMENTED;
1005 #endif
1006 
1007  //Return status code
1008  return error;
1009 }
1010 
1011 
1012 /**
1013  * @brief Verify server's key exchange parameters signature (TLS 1.2)
1014  * @param[in] context Pointer to the TLS context
1015  * @param[in] signature Pointer to the digital signature
1016  * @param[in] length Number of bytes available in the input stream
1017  * @param[in] params Pointer to the server's key exchange parameters
1018  * @param[in] paramsLen Length of the server's key exchange parameters
1019  * @param[out] consumed Total number of bytes that have been consumed
1020  * @return Error code
1021  **/
1022 
1024  const Tls12DigitalSignature *signature, size_t length,
1025  const uint8_t *params, size_t paramsLen, size_t *consumed)
1026 {
1027 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1028  error_t error;
1029  TlsSignatureScheme signScheme;
1030 
1031  //Initialize status code
1032  error = NO_ERROR;
1033 
1034  //Check the length of the digitally-signed element
1035  if(length < sizeof(Tls12DigitalSignature))
1036  return ERROR_DECODING_FAILED;
1037  if(length < (sizeof(Tls12DigitalSignature) + ntohs(signature->length)))
1038  return ERROR_DECODING_FAILED;
1039 
1040  //The algorithm field specifies the signature scheme
1041  signScheme = (TlsSignatureScheme) ntohs(signature->algorithm);
1042 
1043  //If the client has offered the SignatureAlgorithms extension, the signature
1044  //algorithm and hash algorithm must be a pair listed in that extension (refer
1045  //to RFC 5246, section 7.4.3)
1046  if(!tlsIsSignAlgoSupported(context, signScheme))
1047  return ERROR_ILLEGAL_PARAMETER;
1048 
1049 #if (TLS_RSA_SIGN_SUPPORT == ENABLED || TLS_RSA_PSS_SIGN_SUPPORT == ENABLED || \
1050  TLS_DSA_SIGN_SUPPORT == ENABLED || TLS_ECDSA_SIGN_SUPPORT == ENABLED)
1051  //RSA, DSA or ECDSA signature scheme?
1052  if(TLS_SIGN_ALGO(signScheme) == TLS_SIGN_ALGO_RSA ||
1053  TLS_SIGN_ALGO(signScheme) == TLS_SIGN_ALGO_DSA ||
1054  TLS_SIGN_ALGO(signScheme) == TLS_SIGN_ALGO_ECDSA ||
1055  signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA256 ||
1056  signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA384 ||
1057  signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA512 ||
1058  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256 ||
1059  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384 ||
1060  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512)
1061  {
1062  const HashAlgo *hashAlgo;
1063  HashContext *hashContext;
1064  uint8_t digest[MAX_HASH_DIGEST_SIZE];
1065 
1066  //Check signature scheme
1067  if(signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA256 ||
1068  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256)
1069  {
1070  //The hashing is intrinsic to the signature algorithm
1072  }
1073  else if(signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA384 ||
1074  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384)
1075  {
1076  //The hashing is intrinsic to the signature algorithm
1078  }
1079  else if(signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA512 ||
1080  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512)
1081  {
1082  //The hashing is intrinsic to the signature algorithm
1084  }
1085  else
1086  {
1087  //Retrieve the hash algorithm used for signing
1088  hashAlgo = tlsGetHashAlgo(TLS_HASH_ALGO(signScheme));
1089  }
1090 
1091  //Make sure the hash algorithm is supported
1092  if(hashAlgo != NULL)
1093  {
1094  //Allocate a memory buffer to hold the hash context
1095  hashContext = tlsAllocMem(hashAlgo->contextSize);
1096 
1097  //Successful memory allocation?
1098  if(hashContext != NULL)
1099  {
1100  //Compute hash(ClientHello.random + ServerHello.random +
1101  //ServerKeyExchange.params)
1102  hashAlgo->init(hashContext);
1103  hashAlgo->update(hashContext, context->clientRandom, TLS_RANDOM_SIZE);
1104  hashAlgo->update(hashContext, context->serverRandom, TLS_RANDOM_SIZE);
1105  hashAlgo->update(hashContext, params, paramsLen);
1106  hashAlgo->final(hashContext, digest);
1107 
1108 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
1109  //RSASSA-PKCS1-v1_5 signature scheme?
1110  if(TLS_SIGN_ALGO(signScheme) == TLS_SIGN_ALGO_RSA &&
1111  context->peerCertType == TLS_CERT_RSA_SIGN)
1112  {
1113  //Verify RSA signature (RSASSA-PKCS1-v1_5 signature scheme)
1114  error = rsassaPkcs1v15Verify(&context->peerRsaPublicKey,
1115  hashAlgo, digest, signature->value, ntohs(signature->length));
1116  }
1117  else
1118 #endif
1119 #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
1120  //RSASSA-PSS signature scheme (with public key OID rsaEncryption)?
1121  if(signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA256 ||
1122  signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA384 ||
1124  {
1125  //The signature algorithm must be compatible with the key in the
1126  //server's end-entity certificate (refer to RFC 5246, section 7.4.3)
1127  if(context->peerCertType == TLS_CERT_RSA_SIGN)
1128  {
1129  //Verify RSA signature (RSASSA-PSS signature scheme)
1130  error = rsassaPssVerify(&context->peerRsaPublicKey, hashAlgo,
1131  hashAlgo->digestSize, digest, signature->value,
1132  ntohs(signature->length));
1133  }
1134  else
1135  {
1136  //Invalid certificate
1137  error = ERROR_INVALID_SIGNATURE;
1138  }
1139  }
1140  else
1141 #endif
1142 #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
1143  //RSASSA-PSS signature scheme (with public key OID RSASSA-PSS)?
1144  if(signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256 ||
1145  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384 ||
1146  signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512)
1147  {
1148  //The signature algorithm must be compatible with the key in the
1149  //server's end-entity certificate (refer to RFC 5246, section 7.4.3)
1150  if(context->peerCertType == TLS_CERT_RSA_PSS_SIGN)
1151  {
1152  //Verify RSA signature (RSASSA-PSS signature scheme)
1153  error = rsassaPssVerify(&context->peerRsaPublicKey, hashAlgo,
1154  hashAlgo->digestSize, digest, signature->value,
1155  ntohs(signature->length));
1156  }
1157  else
1158  {
1159  //Invalid certificate
1160  error = ERROR_INVALID_SIGNATURE;
1161  }
1162  }
1163  else
1164 #endif
1165 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
1166  //DSA signature scheme?
1167  if(TLS_SIGN_ALGO(signScheme) == TLS_SIGN_ALGO_DSA &&
1168  context->peerCertType == TLS_CERT_DSS_SIGN)
1169  {
1170  //Verify DSA signature
1171  error = tlsVerifyDsaSignature(context, digest,
1172  hashAlgo->digestSize, signature->value,
1173  ntohs(signature->length));
1174  }
1175  else
1176 #endif
1177 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
1178  //ECDSA signature scheme?
1179  if(TLS_SIGN_ALGO(signScheme) == TLS_SIGN_ALGO_ECDSA &&
1180  context->peerCertType == TLS_CERT_ECDSA_SIGN)
1181  {
1182  //Verify ECDSA signature
1183  error = tlsVerifyEcdsaSignature(context, digest,
1184  hashAlgo->digestSize, signature->value,
1185  ntohs(signature->length));
1186  }
1187  else
1188 #endif
1189  //Invalid signature scheme?
1190  {
1191  //Report an error
1192  error = ERROR_INVALID_SIGNATURE;
1193  }
1194 
1195  //Release previously allocated memory
1196  tlsFreeMem(hashContext);
1197  }
1198  else
1199  {
1200  //Failed to allocate memory
1201  error = ERROR_OUT_OF_MEMORY;
1202  }
1203  }
1204  else
1205  {
1206  //Hash algorithm not supported
1207  error = ERROR_INVALID_SIGNATURE;
1208  }
1209  }
1210  else
1211 #endif
1212 #if (TLS_ED25519_SIGN_SUPPORT == ENABLED)
1213  //Ed25519 signature scheme?
1214  if(signScheme == TLS_SIGN_SCHEME_ED25519 &&
1215  context->peerCertType == TLS_CERT_ED25519_SIGN)
1216  {
1217  DataChunk messageChunks[3];
1218 
1219  //Data to be verified is run through the EdDSA algorithm without
1220  //pre-hashing
1221  messageChunks[0].buffer = context->clientRandom;
1222  messageChunks[0].length = TLS_RANDOM_SIZE;
1223  messageChunks[1].buffer = context->serverRandom;
1224  messageChunks[1].length = TLS_RANDOM_SIZE;
1225  messageChunks[2].buffer = params;
1226  messageChunks[2].length = paramsLen;
1227 
1228  //Verify Ed25519 signature (PureEdDSA mode)
1229  error = tlsVerifyEd25519Signature(context, messageChunks,
1230  arraysize(messageChunks), signature->value, ntohs(signature->length));
1231  }
1232  else
1233 #endif
1234 #if (TLS_ED448_SIGN_SUPPORT == ENABLED)
1235  //Ed448 signature scheme?
1236  if(signScheme == TLS_SIGN_SCHEME_ED448 &&
1237  context->peerCertType == TLS_CERT_ED448_SIGN)
1238  {
1239  DataChunk messageChunks[3];
1240 
1241  //Data to be verified is run through the EdDSA algorithm without
1242  //pre-hashing
1243  messageChunks[0].buffer = context->clientRandom;
1244  messageChunks[0].length = TLS_RANDOM_SIZE;
1245  messageChunks[1].buffer = context->serverRandom;
1246  messageChunks[1].length = TLS_RANDOM_SIZE;
1247  messageChunks[2].buffer = params;
1248  messageChunks[2].length = paramsLen;
1249 
1250  //Verify Ed448 signature (PureEdDSA mode)
1251  error = tlsVerifyEd448Signature(context, messageChunks,
1252  arraysize(messageChunks), signature->value, ntohs(signature->length));
1253  }
1254  else
1255 #endif
1256  //Invalid signature algorithm?
1257  {
1258  //Report an error
1259  error = ERROR_INVALID_SIGNATURE;
1260  }
1261 
1262  //Total number of bytes that have been consumed
1263  *consumed = sizeof(Tls12DigitalSignature) + ntohs(signature->length);
1264 
1265  //Return status code
1266  return error;
1267 #else
1268  //Not implemented
1269  return ERROR_NOT_IMPLEMENTED;
1270 #endif
1271 }
1272 
1273 
1274 /**
1275  * @brief Version selection
1276  * @param[in] context Pointer to the TLS context
1277  * @param[in] message Pointer to the received ServerHello message
1278  * @param[in] extensions ServerHello extensions offered by the server
1279  * @return Error code
1280  **/
1281 
1284 {
1285  error_t error;
1286  uint16_t selectedVersion;
1287 
1288 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1289  //Clients must check for the SupportedVersions extension prior to
1290  //processing the rest of the ServerHello
1291  if(extensions->selectedVersion != NULL)
1292  {
1293  //If a client receives an extension type in the ServerHello that it did
1294  //not request in the associated ClientHello, it must abort the handshake
1295  //with an unsupported_extension fatal alert
1296  if(context->versionMax <= TLS_VERSION_1_2)
1298 
1299  //The legacy_version field must be set to 0x0303, which is the version
1300  //number for TLS 1.2
1301  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1302  {
1303  if(ntohs(message->serverVersion) != DTLS_VERSION_1_2)
1305  }
1306  else
1307  {
1308  if(ntohs(message->serverVersion) != TLS_VERSION_1_2)
1310  }
1311 
1312  //If this extension is present, clients must ignore the legacy_version
1313  //value and must use only the SupportedVersions extension to determine
1314  //the selected version
1315  selectedVersion = LOAD16BE(extensions->selectedVersion->value);
1316 
1317 #if (DTLS_SUPPORT == ENABLED)
1318  //DTLS protocol?
1319  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1320  {
1321  //If the SupportedVersions extension contains a version prior to DTLS
1322  //1.3, the client must abort the handshake with an illegal_parameter
1323  //alert (refer to RFC 8446, section 4.2.1)
1324  if(selectedVersion >= DTLS_VERSION_1_2)
1325  return ERROR_ILLEGAL_PARAMETER;
1326 
1327  //Check whether the ServerHello message is received in response to an
1328  //updated ClientHello?
1329  if(context->state == TLS_STATE_SERVER_HELLO_2)
1330  {
1331  //The value of selected_version in the SupportedVersions extension
1332  //of the HelloRetryRequest must be retained in the ServerHello. A
1333  //client must abort the handshake with an illegal_parameter alert if
1334  //the value changes (refer to RFC 8446, section 4.1.4)
1335  if(selectedVersion != dtlsTranslateVersion(context->version))
1336  return ERROR_ILLEGAL_PARAMETER;
1337  }
1338  }
1339  else
1340 #endif
1341  //TLS protocol?
1342  {
1343  //If the SupportedVersions extension contains a version prior to TLS
1344  //1.3, the client must abort the handshake with an illegal_parameter
1345  //alert (refer to RFC 8446, section 4.2.1)
1346  if(selectedVersion <= TLS_VERSION_1_2)
1347  return ERROR_ILLEGAL_PARAMETER;
1348 
1349  //Check whether the ServerHello message is received in response to an
1350  //updated ClientHello?
1351  if(context->state == TLS_STATE_SERVER_HELLO_2)
1352  {
1353  //The value of selected_version in the SupportedVersions extension
1354  //of the HelloRetryRequest must be retained in the ServerHello. A
1355  //client must abort the handshake with an illegal_parameter alert if
1356  //the value changes (refer to RFC 8446, section 4.1.4)
1357  if(selectedVersion != context->version)
1358  return ERROR_ILLEGAL_PARAMETER;
1359  }
1360  }
1361  }
1362  else
1363 #endif
1364  {
1365  //In previous versions of TLS, this field was used for version negotiation
1366  //and represented the selected version number for the connection
1367  selectedVersion = ntohs(message->serverVersion);
1368 
1369 #if (DTLS_SUPPORT == ENABLED)
1370  //DTLS protocol?
1371  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1372  {
1373  //A server which negotiates DTLS 1.3 must set the legacy_version field
1374  //to 0xFEFD (DTLS 1.2) and use the SupportedVersions extension instead
1375  if(selectedVersion < DTLS_VERSION_1_2)
1376  return ERROR_ILLEGAL_PARAMETER;
1377  }
1378  else
1379 #endif
1380  //TLS protocol?
1381  {
1382  //A server which negotiates TLS 1.3 must set the legacy_version field
1383  //to 0x0303 (TLS 1.2) and use the SupportedVersions extension instead
1384  if(selectedVersion > TLS_VERSION_1_2)
1385  return ERROR_ILLEGAL_PARAMETER;
1386  }
1387  }
1388 
1389 #if (DTLS_SUPPORT == ENABLED)
1390  //DTLS protocol?
1391  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1392  {
1393  //Set the DTLS version to be used
1394  error = dtlsSelectVersion(context, selectedVersion);
1395  }
1396  else
1397 #endif
1398  //TLS protocol?
1399  {
1400  //Set the TLS version to be used
1401  error = tlsSelectVersion(context, selectedVersion);
1402  }
1403 
1404  //Specified TLS/DTLS version not supported?
1405  if(error)
1406  return error;
1407 
1408 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1409  //If the ServerHello indicates TLS 1.1 or below, TLS 1.3 client must and
1410  //1.2 clients should check that the last 8 bytes are not equal to the
1411  //bytes 44 4F 57 4E 47 52 44 00
1412  if(context->version <= TLS_VERSION_1_1 &&
1413  context->versionMax >= TLS_VERSION_1_2)
1414  {
1415  //If a match is found, the client must abort the handshake with an
1416  //illegal_parameter alert
1417  if(osMemcmp(message->random + 24, tls11DowngradeRandom, 8) == 0)
1418  return ERROR_ILLEGAL_PARAMETER;
1419  }
1420 
1421  //If the ServerHello indicates TLS 1.2 or below, TLS 1.3 client must check
1422  //that the last 8 bytes are not equal to the bytes 44 4F 57 4E 47 52 44 01
1423  if(context->version <= TLS_VERSION_1_2 &&
1424  context->versionMax >= TLS_VERSION_1_3 &&
1425  (context->transportProtocol == TLS_TRANSPORT_PROTOCOL_STREAM ||
1426  context->transportProtocol == TLS_TRANSPORT_PROTOCOL_EAP))
1427  {
1428  //If a match is found, the client must abort the handshake with an
1429  //illegal_parameter alert
1430  if(osMemcmp(message->random + 24, tls12DowngradeRandom, 8) == 0)
1431  return ERROR_ILLEGAL_PARAMETER;
1432  }
1433 #endif
1434 
1435  //Successful processing
1436  return NO_ERROR;
1437 }
1438 
1439 
1440 /**
1441  * @brief Resume TLS session via session ID
1442  * @param[in] context Pointer to the TLS context
1443  * @param[in] sessionId Pointer to the session ID provided by the server
1444  * @param[in] sessionIdLen Length of the session ID, in bytes
1445  * @param[in] cipherSuite Cipher suite selected by the server
1446  * @return Error code
1447  **/
1448 
1450  size_t sessionIdLen, uint16_t cipherSuite)
1451 {
1452  error_t error;
1453 
1454  //Initialize status code
1455  error = NO_ERROR;
1456 
1457 #if (TLS_SESSION_RESUME_SUPPORT == ENABLED)
1458  //Check whether the session ID matches the value that was supplied by the
1459  //client
1460  if(sessionIdLen != 0 && sessionIdLen == context->sessionIdLen &&
1461  osMemcmp(sessionId, context->sessionId, sessionIdLen) == 0)
1462  {
1463  //For resumed sessions, the selected cipher suite shall be the same as
1464  //the session being resumed
1465  if(cipherSuite != 0 && cipherSuite == context->cipherSuite.identifier)
1466  {
1467  //Perform abbreviated handshake
1468  context->resume = TRUE;
1469  }
1470  else
1471  {
1472  //The session ID is no more valid
1473  context->sessionIdLen = 0;
1474 
1475  //When renegotiating, if the server tries to use another version or
1476  //compression method than previously, abort
1477  error = ERROR_ILLEGAL_PARAMETER;
1478  }
1479  }
1480  else
1481 #endif
1482  {
1483  //Perform a full handshake
1484  context->resume = FALSE;
1485  }
1486 
1487  //Return status code
1488  return error;
1489 }
1490 
1491 
1492 /**
1493  * @brief Check whether a session ticket is valid
1494  * @param[in] context Pointer to the TLS context
1495  * @return TRUE is the session ticket is valid, else FALSE
1496  **/
1497 
1499 {
1500  bool_t valid = FALSE;
1501 
1502  //TLS 1.3 tickets cannot be used to resume a TLS 1.2 session
1503  if(context->version <= TLS_VERSION_1_2)
1504  {
1505  //Valid ticket?
1506  if(context->ticket != NULL && context->ticketLen > 0)
1507  {
1508  valid = TRUE;
1509  }
1510  }
1511 
1512  //Return TRUE is the ticket is valid, else FALSE
1513  return valid;
1514 }
1515 
1516 #endif
@ TLS_GROUP_BRAINPOOLP512R1_TLS13
Definition: tls.h:1437
#define tlsAllocMem(size)
Definition: tls.h:867
#define htons(value)
Definition: cpu_endian.h:413
Parsing and checking of TLS extensions.
@ TLS_SIGN_ALGO_DSA
Definition: tls.h:1257
TLS helper functions.
const uint8_t tls11DowngradeRandom[8]
Definition: tls13_misc.c:53
@ ERROR_UNKNOWN_IDENTITY
Definition: error.h:261
HashAlgoInit init
Definition: crypto.h:1092
@ ERROR_UNSUPPORTED_ELLIPTIC_CURVE
Definition: error.h:133
uint8_t extensions[]
Definition: ntp_common.h:207
@ TLS_GROUP_BRAINPOOLP256R1_TLS13
Definition: tls.h:1435
Generic hash algorithm context.
int bool_t
Definition: compiler_port.h:61
uint8_t sessionId[]
Definition: tls.h:1811
TLS cipher suites.
uint16_t cipherSuite
Cipher suite identifier.
Definition: tls.h:1921
error_t dtlsSelectVersion(TlsContext *context, uint16_t version)
Set the DTLS version to be used.
Definition: dtls_misc.c:53
error_t tlsVerifyEd448Signature(TlsContext *context, const DataChunk *message, uint_t messageLen, const uint8_t *signature, size_t signatureLen)
Verify Ed448 signature.
const HashAlgo * tlsGetHashAlgo(TlsHashAlgo hashAlgoId)
Get the hash algorithm that matches the specified identifier.
Definition: tls_misc.c:1184
TlsDigitalSignature
Definition: tls.h:1755
@ TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA256
Definition: tls.h:1277
#define TLS_MAX_DH_MODULUS_SIZE
Definition: tls.h:780
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:1150
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:244
const EcCurve * tlsGetCurve(TlsContext *context, uint16_t namedCurve)
Get the EC domain parameters that match the specified named curve.
Definition: tls_misc.c:1251
@ ERROR_UNEXPECTED_MESSAGE
Definition: error.h:195
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:307
#define TRUE
Definition: os_port.h:50
@ TLS_GROUP_CURVE_SM2
Definition: tls.h:1445
size_t digestSize
Definition: crypto.h:1088
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:1018
@ TLS_TRANSPORT_PROTOCOL_DATAGRAM
Definition: tls.h:979
HashAlgoUpdate update
Definition: crypto.h:1093
void md5Final(Md5Context *context, uint8_t *digest)
Finish the MD5 message digest.
Session cache management.
TlsPskIdentity
Definition: tls.h:1733
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512
Definition: tls.h:1282
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:960
#define osMemcmp(p1, p2, length)
Definition: os_port.h:156
@ 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:1213
@ TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA512
Definition: tls.h:1279
@ TLS_SIGN_SCHEME_ED25519
Definition: tls.h:1291
#define osStrlen(s)
Definition: os_port.h:168
#define TLS_RANDOM_SIZE
Definition: tls.h:960
#define TLS_HASH_ALGO(signScheme)
Definition: tls_sign_misc.h:41
TlsPskIdentityHint
Definition: tls.h:1744
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384
Definition: tls.h:1281
@ TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA384
Definition: tls.h:1278
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:1086
uint8_t sessionIdLen
Definition: tls.h:1810
@ TLS_KEY_EXCH_RSA
Definition: tls.h:1162
void md5Init(Md5Context *context)
Initialize MD5 message digest context.
TlsCipherSuites
Definition: tls.h:1555
#define MAX_HASH_DIGEST_SIZE
@ TLS_HASH_ALGO_SHA512
Definition: tls.h:1243
@ TLS_KEY_EXCH_ECDHE_ECDSA
Definition: tls.h:1171
@ TLS_KEY_EXCH_ECDHE_RSA
Definition: tls.h:1169
TlsHandshake
Definition: tls.h:1792
#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:226
@ TLS_KEY_EXCH_ECDH_ANON
Definition: tls.h:1172
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:144
@ ERROR_UNSUPPORTED_EXTENSION
Definition: error.h:246
error_t ecdhCheckPublicKey(EcdhContext *context, const EcPublicKey *publicKey)
Check ECDH public key.
Definition: ecdh.c:224
#define TlsContext
Definition: tls.h:36
error_t
Error codes.
Definition: error.h:43
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256
Definition: tls.h:1280
@ TLS_CERT_ED25519_SIGN
Definition: tls.h:1226
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:409
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:822
error_t tlsVerifyEd25519Signature(TlsContext *context, const DataChunk *message, uint_t messageLen, const uint8_t *signature, size_t signatureLen)
Verify Ed25519 signature.
@ TLS_KEY_EXCH_DH_ANON
Definition: tls.h:1167
#define TLS_MAX_VERSION
Definition: tls.h:129
#define STORE16BE(a, p)
Definition: cpu_endian.h:262
@ TLS_TYPE_CLIENT_HELLO
Definition: tls.h:1063
error_t tlsSelectClientVersion(TlsContext *context, const TlsServerHello *message, const TlsHelloExtensions *extensions)
Version selection.
Tls12DigitalSignature
Definition: tls.h:1767
uint16_t identifier
Definition: tls.h:2055
@ TLS_CIPHER_SUITE_TYPE_UNKNOWN
#define TLS_VERSION_1_3
Definition: tls.h:97
Handshake message processing (TLS client and server)
@ TLS_HASH_ALGO_SHA384
Definition: tls.h:1242
@ TLS_CERT_RSA_PSS_SIGN
Definition: tls.h:1224
__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.
MD5 algorithm context.
Definition: md5.h:62
@ TLS_TRANSPORT_PROTOCOL_EAP
Definition: tls.h:980
@ TLS_HASH_ALGO_SHA256
Definition: tls.h:1241
@ TLS_CERT_ED448_SIGN
Definition: tls.h:1227
error_t dhCheckPublicKey(DhContext *context, const Mpi *publicKey)
Check Diffie-Hellman public value.
Definition: dh.c:183
error_t tlsFormatInitialClientHello(TlsContext *context)
Format initial ClientHello message.
@ TLS_CERT_RSA_SIGN
Definition: tls.h:1212
uint8_t length
Definition: tcp.h:375
@ TLS_KEY_EXCH_DHE_PSK
Definition: tls.h:1175
TlsCompressMethods
Definition: tls.h:1566
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:2136
@ TLS_FALLBACK_SCSV
uint_t mpiGetBitLength(const Mpi *a)
Get the actual length in bits.
Definition: mpi.c:254
@ TLS_GROUP_BRAINPOOLP384R1_TLS13
Definition: tls.h:1436
error_t ecdhComputeSharedSecret(EcdhContext *context, uint8_t *output, size_t outputSize, size_t *outputLen)
Compute ECDH shared secret.
Definition: ecdh.c:338
@ ERROR_UNSUPPORTED_KEY_EXCH_ALGO
Definition: error.h:131
@ TLS_KEY_EXCH_RSA_PSK
Definition: tls.h:1174
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:1094
Data chunk descriptor.
Definition: crypto.h:1017
#define ntohs(value)
Definition: cpu_endian.h:421
error_t tlsWriteEcPoint(const EcPublicKey *publicKey, uint8_t *data, size_t *length)
Encode an EC point to an opaque vector.
Definition: tls_misc.c:1036
TlsRecord
Definition: tls.h:1780
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:1483
#define TRACE_DEBUG(...)
Definition: debug.h:119
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:1068
#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:994
const char_t * tlsGetCipherSuiteName(uint16_t identifier)
Convert cipher suite identifier to string representation.
TlsServerHello
Definition: tls.h:1825
#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:1309
@ TLS_SIGN_SCHEME_ED448
Definition: tls.h:1292
const TlsCipherSuiteInfo tlsSupportedCipherSuites[]
@ TLS_KEY_EXCH_ECDHE_PSK
Definition: tls.h:1176
TlsClientHello
Definition: tls.h:1812
Helper functions for signature generation and verification.
TLS (Transport Layer Security)
uint8_t identifier[]
@ TLS_SIGN_ALGO_RSA
Definition: tls.h:1256
error_t tlsReadEcPoint(EcPublicKey *publicKey, const EcCurve *curve, const uint8_t *data, size_t size, size_t *length)
Read an EC point from an opaque vector.
Definition: tls_misc.c:1075
#define STORE24BE(a, p)
Definition: cpu_endian.h:273
SHA-1 algorithm context.
Definition: sha1.h:62
@ TLS_CERT_ECDSA_SIGN
Definition: tls.h:1219
@ TLS_KEY_EXCH_DHE_DSS
Definition: tls.h:1166
size_t length
Definition: crypto.h:1019
@ TLS_TRANSPORT_PROTOCOL_STREAM
Definition: tls.h:978
Common interface for hash algorithms.
Definition: crypto.h:1082
#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.
#define EcCurve
Definition: ec.h:346
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:1271
@ ERROR_DECODING_FAILED
Definition: error.h:242
error_t tlsFormatPskIdentity(TlsContext *context, uint8_t *p, size_t *written)
Format PSK identity.
unsigned int uint_t
Definition: compiler_port.h:57
#define TRACE_DEBUG_MPI(p, a)
Definition: debug.h:122
#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:872
@ TLS_STATE_SERVER_HELLO_2
Definition: tls.h:1500
@ ERROR_INVALID_SIGNATURE
Definition: error.h:228
@ TLS_SIGN_ALGO_ECDSA
Definition: tls.h:1258
@ TLS_KEY_EXCH_DHE_RSA
Definition: tls.h:1164
#define DTLS_VERSION_1_2
Definition: dtls_misc.h:36
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:290
#define osMemmove(dest, src, length)
Definition: os_port.h:150
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:84
#define arraysize(a)
Definition: os_port.h:71
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.