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-2019 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 1.9.6
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL TLS_TRACE_LEVEL
33 
34 //Dependencies
35 #include <string.h>
36 #include "tls.h"
37 #include "tls_cipher_suites.h"
38 #include "tls_client.h"
39 #include "tls_client_misc.h"
40 #include "tls_common.h"
41 #include "tls_extensions.h"
42 #include "tls_signature.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  {
112  //A client which has a cached session ID set by a pre-TLS 1.3 server
113  //should set this field to that value
114  memcpy(p, context->sessionId, context->sessionIdLen);
115  n = context->sessionIdLen;
116  }
117  else
118  {
119 #if (TLS_SESSION_RESUME_SUPPORT == ENABLED)
120  //The session ID value identifies a session the client wishes to reuse
121  //for this connection
122  memcpy(p, context->sessionId, context->sessionIdLen);
123  n = context->sessionIdLen;
124 #else
125  //Session resumption is not supported
126  n = 0;
127 #endif
128  }
129 
130 #if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
131  //Secure renegotiation?
132  if(context->secureRenegoEnabled && context->secureRenegoFlag)
133  {
134  //Do not offer a session ID when renegotiating
135  n = 0;
136  }
137 #endif
138 
139  //Total number of bytes that have been written
140  *written = n;
141 
142  //Successful processing
143  return NO_ERROR;
144 }
145 
146 
147 /**
148  * @brief Format the list of cipher suites supported by the client
149  * @param[in] context Pointer to the TLS context
150  * @param[out] cipherSuiteTypes Types of cipher suites proposed by the client
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 
156 error_t tlsFormatCipherSuites(TlsContext *context, uint_t *cipherSuiteTypes,
157  uint8_t *p, 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  *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  *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  *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 = strlen(context->pskIdentity);
337  //Copy PSK identity
338  memcpy(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 
367  size_t *written)
368 {
369 #if (TLS_MAX_VERSION >= SSL_VERSION_3_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  //Sanity check
380  return ERROR_BUFFER_OVERFLOW;
381 
382  //If RSA is being used for key agreement and authentication, the
383  //client generates a 48-byte premaster secret
384  context->premasterSecretLen = 48;
385 
386  //The first 2 bytes code the latest version supported by the client
387  STORE16BE(context->clientVersion, context->premasterSecret);
388 
389  //The last 46 bytes contain securely-generated random bytes
390  error = context->prngAlgo->read(context->prngContext,
391  context->premasterSecret + 2, 46);
392  //Any error to report?
393  if(error)
394  return error;
395 
396  //The RSA-encrypted premaster secret in a ClientKeyExchange is preceded by
397  //two length bytes. SSL 3.0 implementations do not include these bytes
398  if(context->version > SSL_VERSION_3_0)
399  {
400  //Encrypt the premaster secret using the server public key
401  error = rsaesPkcs1v15Encrypt(context->prngAlgo, context->prngContext,
402  &context->peerRsaPublicKey, context->premasterSecret, 48, p + 2, &n);
403  //RSA encryption failed?
404  if(error)
405  return error;
406 
407  //Write the length field
408  STORE16BE(n, p);
409 
410  //Length of the resulting octet string
411  n += 2;
412  }
413  else
414  {
415  //Encrypt the premaster secret using the server public key
416  error = rsaesPkcs1v15Encrypt(context->prngAlgo, context->prngContext,
417  &context->peerRsaPublicKey, context->premasterSecret, 48, p, &n);
418  //RSA encryption failed?
419  if(error)
420  return error;
421  }
422 
423  //Total number of bytes that have been written
424  *written = n;
425  }
426  else
427 #endif
428 #if (TLS_DH_ANON_KE_SUPPORT == ENABLED || TLS_DHE_RSA_KE_SUPPORT == ENABLED || \
429  TLS_DHE_DSS_KE_SUPPORT == ENABLED || TLS_DHE_PSK_KE_SUPPORT == ENABLED)
430  //Diffie-Hellman key exchange method?
431  if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
432  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
433  context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
434  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK)
435  {
436  //Generate an ephemeral key pair
437  error = dhGenerateKeyPair(&context->dhContext,
438  context->prngAlgo, context->prngContext);
439  //Any error to report?
440  if(error)
441  return error;
442 
443  //Encode the client's public value to an opaque vector
444  error = tlsWriteMpi(&context->dhContext.ya, p, &n);
445  //Any error to report?
446  if(error)
447  return error;
448 
449  //Total number of bytes that have been written
450  *written = n;
451 
452  //Calculate the negotiated key Z
453  error = dhComputeSharedSecret(&context->dhContext,
454  context->premasterSecret, TLS_PREMASTER_SECRET_SIZE,
455  &context->premasterSecretLen);
456  //Any error to report?
457  if(error)
458  return error;
459 
460  //Leading bytes of Z that contain all zero bits are stripped before
461  //it is used as the premaster secret (RFC 4346, section 8.2.1)
462  for(n = 0; n < context->premasterSecretLen; n++)
463  {
464  if(context->premasterSecret[n] != 0x00)
465  break;
466  }
467 
468  //Any leading zero bytes?
469  if(n > 0)
470  {
471  //Strip leading zero bytes from the negotiated key
472  memmove(context->premasterSecret, context->premasterSecret + n,
473  context->premasterSecretLen - n);
474 
475  //Adjust the length of the premaster secret
476  context->premasterSecretLen -= n;
477  }
478  }
479  else
480 #endif
481 #if (TLS_ECDH_ANON_KE_SUPPORT == ENABLED || TLS_ECDHE_RSA_KE_SUPPORT == ENABLED || \
482  TLS_ECDHE_ECDSA_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
483  //ECDH key exchange method?
484  if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
485  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
486  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
487  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
488  {
489 #if (TLS_ECC_CALLBACK_SUPPORT == ENABLED)
490  //Any registered callback?
491  if(context->ecdhCallback != NULL)
492  {
493  //Invoke user callback function
494  error = context->ecdhCallback(context);
495  }
496  else
497 #endif
498  {
499  //No callback function defined
501  }
502 
503  //Check status code
505  {
506  //Generate an ephemeral key pair
507  error = ecdhGenerateKeyPair(&context->ecdhContext,
508  context->prngAlgo, context->prngContext);
509  //Any error to report?
510  if(error)
511  return error;
512 
513  //Calculate the negotiated key Z
514  error = ecdhComputeSharedSecret(&context->ecdhContext,
515  context->premasterSecret, TLS_PREMASTER_SECRET_SIZE,
516  &context->premasterSecretLen);
517  //Any error to report?
518  if(error)
519  return error;
520  }
521  else if(error != NO_ERROR)
522  {
523  //Report an error
524  return error;
525  }
526 
527  //Encode the client's public key to an opaque vector
528  error = tlsWriteEcPoint(&context->ecdhContext.params,
529  &context->ecdhContext.qa, p, &n);
530  //Any error to report?
531  if(error)
532  return error;
533 
534  //Total number of bytes that have been written
535  *written = n;
536  }
537  else
538 #endif
539  //Invalid key exchange method?
540  {
541  //Just for sanity
542  (void) error;
543  (void) n;
544 
545  //The specified key exchange method is not supported
547  }
548 
549  //Successful processing
550  return NO_ERROR;
551 #else
552  //Not implemented
553  return ERROR_NOT_IMPLEMENTED;
554 #endif
555 }
556 
557 
558 /**
559  * @brief Parse PSK identity hint
560  * @param[in] context Pointer to the TLS context
561  * @param[in] p Input stream where to read the PSK identity hint
562  * @param[in] length Number of bytes available in the input stream
563  * @param[out] consumed Total number of bytes that have been consumed
564  * @return Error code
565  **/
566 
567 error_t tlsParsePskIdentityHint(TlsContext *context, const uint8_t *p,
568  size_t length, size_t *consumed)
569 {
570  size_t n;
571  TlsPskIdentityHint *pskIdentityHint;
572 
573  //Point to the PSK identity hint
574  pskIdentityHint = (TlsPskIdentityHint *) p;
575 
576  //Malformed ServerKeyExchange message?
577  if(length < sizeof(TlsPskIdentityHint))
578  return ERROR_DECODING_FAILED;
579  if(length < (sizeof(TlsPskIdentityHint) + ntohs(pskIdentityHint->length)))
580  return ERROR_DECODING_FAILED;
581 
582  //Retrieve the length of the PSK identity hint
583  n = ntohs(pskIdentityHint->length);
584 
585 #if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
586  TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
587  //Any registered callback?
588  if(context->pskCallback != NULL)
589  {
590  error_t error;
591 
592  //The client selects which identity to use depending on the PSK identity
593  //hint provided by the server
594  error = context->pskCallback(context, pskIdentityHint->value, n);
595  //Any error to report?
596  if(error)
597  return ERROR_UNKNOWN_IDENTITY;
598  }
599 #endif
600 
601  //Total number of bytes that have been consumed
602  *consumed = sizeof(TlsPskIdentityHint) + n;
603 
604  //Successful processing
605  return NO_ERROR;
606 }
607 
608 
609 /**
610  * @brief Parse server's key exchange parameters
611  * @param[in] context Pointer to the TLS context
612  * @param[in] p Input stream where to read the server's key exchange parameters
613  * @param[in] length Number of bytes available in the input stream
614  * @param[out] consumed Total number of bytes that have been consumed
615  * @return Error code
616  **/
617 
618 error_t tlsParseServerKeyParams(TlsContext *context, const uint8_t *p,
619  size_t length, size_t *consumed)
620 {
621 #if (TLS_MAX_VERSION >= SSL_VERSION_3_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
622  error_t error;
623  const uint8_t *params;
624 
625  //Initialize status code
626  error = NO_ERROR;
627 
628  //Point to the server's key exchange parameters
629  params = p;
630 
631 #if (TLS_DH_ANON_KE_SUPPORT == ENABLED || TLS_DHE_RSA_KE_SUPPORT == ENABLED || \
632  TLS_DHE_DSS_KE_SUPPORT == ENABLED || TLS_DHE_PSK_KE_SUPPORT == ENABLED)
633  //Diffie-Hellman key exchange method?
634  if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
635  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
636  context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
637  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK)
638  {
639  uint_t k;
640  size_t n;
641 
642  //Convert the prime modulus to a multiple precision integer
643  error = tlsReadMpi(&context->dhContext.params.p, p, length, &n);
644 
645  //Check status code
646  if(!error)
647  {
648  //Get the length of the prime modulus, in bits
649  k = mpiGetBitLength(&context->dhContext.params.p);
650 
651  //Make sure the prime modulus is acceptable
652  if(k < TLS_MIN_DH_MODULUS_SIZE || k > TLS_MAX_DH_MODULUS_SIZE)
653  error = ERROR_ILLEGAL_PARAMETER;
654  }
655 
656  //Check status code
657  if(!error)
658  {
659  //Advance data pointer
660  p += n;
661  //Remaining bytes to process
662  length -= n;
663 
664  //Convert the generator to a multiple precision integer
665  error = tlsReadMpi(&context->dhContext.params.g, p, length, &n);
666  }
667 
668  //Check status code
669  if(!error)
670  {
671  //Advance data pointer
672  p += n;
673  //Remaining bytes to process
674  length -= n;
675 
676  //Convert the server's public value to a multiple precision integer
677  error = tlsReadMpi(&context->dhContext.yb, p, length, &n);
678  }
679 
680  //Check status code
681  if(!error)
682  {
683  //Advance data pointer
684  p += n;
685  //Remaining bytes to process
686  length -= n;
687 
688  //Verify peer's public value
689  error = dhCheckPublicKey(&context->dhContext.params,
690  &context->dhContext.yb);
691  }
692 
693  //Check status code
694  if(!error)
695  {
696  //Debug message
697  TRACE_DEBUG("Diffie-Hellman parameters:\r\n");
698  TRACE_DEBUG(" Prime modulus:\r\n");
699  TRACE_DEBUG_MPI(" ", &context->dhContext.params.p);
700  TRACE_DEBUG(" Generator:\r\n");
701  TRACE_DEBUG_MPI(" ", &context->dhContext.params.g);
702  TRACE_DEBUG(" Server public value:\r\n");
703  TRACE_DEBUG_MPI(" ", &context->dhContext.yb);
704  }
705  }
706  else
707 #endif
708 #if (TLS_ECDH_ANON_KE_SUPPORT == ENABLED || TLS_ECDHE_RSA_KE_SUPPORT == ENABLED || \
709  TLS_ECDHE_ECDSA_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
710  //ECDH key exchange method?
711  if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
712  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
713  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
714  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
715  {
716  size_t n;
717  uint8_t curveType;
718  const EcCurveInfo *curveInfo;
719 
720  //Initialize curve parameters
721  curveInfo = NULL;
722 
723  //Malformed ServerKeyExchange message?
724  if(length < sizeof(curveType))
725  error = ERROR_DECODING_FAILED;
726 
727  //Check status code
728  if(!error)
729  {
730  //Retrieve the type of the elliptic curve domain parameters
731  curveType = *p;
732 
733  //Advance data pointer
734  p += sizeof(curveType);
735  //Remaining bytes to process
736  length -= sizeof(curveType);
737 
738  //Only named curves are supported
739  if(curveType != TLS_EC_CURVE_TYPE_NAMED_CURVE)
740  error = ERROR_ILLEGAL_PARAMETER;
741  }
742 
743  //Check status code
744  if(!error)
745  {
746  //Malformed ServerKeyExchange message?
747  if(length < sizeof(uint16_t))
748  error = ERROR_DECODING_FAILED;
749  }
750 
751  //Check status code
752  if(!error)
753  {
754  //Get elliptic curve identifier
755  context->namedGroup = LOAD16BE(p);
756 
757  //Advance data pointer
758  p += sizeof(uint16_t);
759  //Remaining bytes to process
760  length -= sizeof(uint16_t);
761 
762  //Retrieve the corresponding EC domain parameters
763  curveInfo = tlsGetCurveInfo(context, context->namedGroup);
764 
765  //Make sure the elliptic curve is supported
766  if(curveInfo == NULL)
767  {
768  //The elliptic curve is not supported
769  error = ERROR_ILLEGAL_PARAMETER;
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, 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);
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.x);
808  TRACE_DEBUG(" Server public key Y:\r\n");
809  TRACE_DEBUG_MPI(" ", &context->ecdhContext.qb.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 (SSL 3.0, 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 >= SSL_VERSION_3_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  error_t error;
1035 
1036 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1037  //Initialize status code
1038  error = NO_ERROR;
1039 
1040  //Check the length of the digitally-signed element
1041  if(length < sizeof(Tls12DigitalSignature))
1042  return ERROR_DECODING_FAILED;
1043  if(length < (sizeof(Tls12DigitalSignature) + ntohs(signature->length)))
1044  return ERROR_DECODING_FAILED;
1045 
1046 #if (TLS_RSA_SIGN_SUPPORT == ENABLED || TLS_RSA_PSS_SIGN_SUPPORT == ENABLED || \
1047  TLS_DSA_SIGN_SUPPORT == ENABLED || TLS_ECDSA_SIGN_SUPPORT == ENABLED)
1048  //RSA, DSA or ECDSA signature scheme?
1049  if(signature->algorithm.signature == TLS_SIGN_ALGO_RSA ||
1050  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA256 ||
1051  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA384 ||
1052  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA512 ||
1053  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_PSS_SHA256 ||
1054  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_PSS_SHA384 ||
1055  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_PSS_SHA512 ||
1056  signature->algorithm.signature == TLS_SIGN_ALGO_DSA ||
1057  signature->algorithm.signature == TLS_SIGN_ALGO_ECDSA)
1058  {
1059  const HashAlgo *hashAlgo;
1060  HashContext *hashContext;
1061 
1062  //Retrieve the hash algorithm used for signing
1063  if(signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA256 ||
1064  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_PSS_SHA256)
1065  {
1066  //The hashing is intrinsic to the signature algorithm
1067  if(signature->algorithm.hash == TLS_HASH_ALGO_INTRINSIC)
1069  else
1070  hashAlgo = NULL;
1071  }
1072  else if(signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA384 ||
1073  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_PSS_SHA384)
1074  {
1075  //The hashing is intrinsic to the signature algorithm
1076  if(signature->algorithm.hash == TLS_HASH_ALGO_INTRINSIC)
1078  else
1079  hashAlgo = NULL;
1080  }
1081  else if(signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA512 ||
1082  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_PSS_SHA512)
1083  {
1084  //The hashing is intrinsic to the signature algorithm
1085  if(signature->algorithm.hash == TLS_HASH_ALGO_INTRINSIC)
1087  else
1088  hashAlgo = NULL;
1089  }
1090  else
1091  {
1092  //This field indicates the hash algorithm that is used
1093  hashAlgo = tlsGetHashAlgo(signature->algorithm.hash);
1094  }
1095 
1096  //Make sure the hash algorithm is supported
1097  if(hashAlgo != NULL)
1098  {
1099  //Allocate a memory buffer to hold the hash context
1100  hashContext = tlsAllocMem(hashAlgo->contextSize);
1101 
1102  //Successful memory allocation?
1103  if(hashContext != NULL)
1104  {
1105  //Compute hash(ClientHello.random + ServerHello.random +
1106  //ServerKeyExchange.params)
1107  hashAlgo->init(hashContext);
1108  hashAlgo->update(hashContext, context->clientRandom, TLS_RANDOM_SIZE);
1109  hashAlgo->update(hashContext, context->serverRandom, TLS_RANDOM_SIZE);
1110  hashAlgo->update(hashContext, params, paramsLen);
1111  hashAlgo->final(hashContext, NULL);
1112 
1113 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
1114  //RSASSA-PKCS1-v1_5 signature scheme?
1115  if(signature->algorithm.signature == TLS_SIGN_ALGO_RSA &&
1116  context->peerCertType == TLS_CERT_RSA_SIGN)
1117  {
1118  //Verify RSA signature (RSASSA-PKCS1-v1_5 signature scheme)
1119  error = rsassaPkcs1v15Verify(&context->peerRsaPublicKey,
1120  hashAlgo, hashContext->digest, signature->value,
1121  ntohs(signature->length));
1122  }
1123  else
1124 #endif
1125 #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
1126  //RSASSA-PSS signature scheme (with public key OID rsaEncryption)?
1127  if(signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA256 ||
1128  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA384 ||
1129  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA512)
1130  {
1131  //Enforce the type of the certificate provided by the peer
1132  if(context->peerCertType == TLS_CERT_RSA_SIGN)
1133  {
1134  //Verify RSA signature (RSASSA-PSS signature scheme)
1135  error = rsassaPssVerify(&context->peerRsaPublicKey, hashAlgo,
1136  hashAlgo->digestSize, hashContext->digest,
1137  signature->value, ntohs(signature->length));
1138  }
1139  else
1140  {
1141  //Invalid certificate
1142  error = ERROR_INVALID_SIGNATURE;
1143  }
1144  }
1145  else
1146 #endif
1147 #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
1148  //RSASSA-PSS signature scheme (with public key OID RSASSA-PSS)?
1149  if(signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_PSS_SHA256 ||
1150  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_PSS_SHA384 ||
1151  signature->algorithm.signature == TLS_SIGN_ALGO_RSA_PSS_PSS_SHA512)
1152  {
1153  //Enforce the type of the certificate provided by the peer
1154  if(context->peerCertType == TLS_CERT_RSA_PSS_SIGN)
1155  {
1156  //Verify RSA signature (RSASSA-PSS signature scheme)
1157  error = rsassaPssVerify(&context->peerRsaPublicKey, hashAlgo,
1158  hashAlgo->digestSize, hashContext->digest,
1159  signature->value, ntohs(signature->length));
1160  }
1161  else
1162  {
1163  //Invalid certificate
1164  error = ERROR_INVALID_SIGNATURE;
1165  }
1166  }
1167  else
1168 #endif
1169 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
1170  //DSA signature scheme?
1171  if(signature->algorithm.signature == TLS_SIGN_ALGO_DSA &&
1172  context->peerCertType == TLS_CERT_DSS_SIGN)
1173  {
1174  //DSA signature verification
1175  error = tlsVerifyDsaSignature(context, hashContext->digest,
1176  hashAlgo->digestSize, signature->value,
1177  ntohs(signature->length));
1178  }
1179  else
1180 #endif
1181 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
1182  //ECDSA signature scheme?
1183  if(signature->algorithm.signature == TLS_SIGN_ALGO_ECDSA &&
1184  context->peerCertType == TLS_CERT_ECDSA_SIGN)
1185  {
1186  //ECDSA signature verification
1187  error = tlsVerifyEcdsaSignature(context, hashContext->digest,
1188  hashAlgo->digestSize, signature->value,
1189  ntohs(signature->length));
1190  }
1191  else
1192 #endif
1193  //Invalid signature scheme?
1194  {
1195  //Report an error
1196  error = ERROR_INVALID_SIGNATURE;
1197  }
1198 
1199  //Release previously allocated memory
1200  tlsFreeMem(hashContext);
1201  }
1202  else
1203  {
1204  //Failed to allocate memory
1205  error = ERROR_OUT_OF_MEMORY;
1206  }
1207  }
1208  else
1209  {
1210  //Hash algorithm not supported
1211  error = ERROR_INVALID_SIGNATURE;
1212  }
1213  }
1214  else
1215 #endif
1216 #if (TLS_EDDSA_SIGN_SUPPORT == ENABLED)
1217  //EdDSA signature scheme?
1218  if(signature->algorithm.signature == TLS_SIGN_ALGO_ED25519 ||
1219  signature->algorithm.signature == TLS_SIGN_ALGO_ED448)
1220  {
1221  uint8_t *buffer;
1222 
1223  //A temporary buffer is needed to concatenate ClientHello.random +
1224  //ServerHello.random + ServerKeyExchange.params
1225  buffer = tlsAllocMem(paramsLen + 2 * TLS_RANDOM_SIZE);
1226 
1227  //Successful memory allocation?
1228  if(buffer != NULL)
1229  {
1230  //Data to be verified is run through the EdDSA algorithm with no
1231  //hashing
1232  memcpy(buffer, context->clientRandom, TLS_RANDOM_SIZE);
1233  memcpy(buffer + 32, context->serverRandom, TLS_RANDOM_SIZE);
1234  memcpy(buffer + 64, params, paramsLen);
1235 
1236 #if (TLS_ED25519_SUPPORT == ENABLED)
1237  //Ed25519 signature scheme?
1238  if(signature->algorithm.signature == TLS_SIGN_ALGO_ED25519 &&
1239  context->peerCertType == TLS_CERT_ED25519_SIGN)
1240  {
1241  //EdDSA signature verification
1242  error = tlsVerifyEddsaSignature(context, buffer, paramsLen + 64,
1243  signature->value, ntohs(signature->length));
1244  }
1245  else
1246 #endif
1247 #if (TLS_ED448_SUPPORT == ENABLED)
1248  //Ed448 signature scheme?
1249  if(signature->algorithm.signature == TLS_SIGN_ALGO_ED448 &&
1250  context->peerCertType == TLS_CERT_ED448_SIGN)
1251  {
1252  //EdDSA signature verification
1253  error = tlsVerifyEddsaSignature(context, buffer, paramsLen + 64,
1254  signature->value, ntohs(signature->length));
1255  }
1256  else
1257 #endif
1258  //Invalid signature scheme?
1259  {
1260  error = ERROR_INVALID_SIGNATURE;
1261  }
1262 
1263  //Release previously allocated memory
1264  tlsFreeMem(buffer);
1265  }
1266  else
1267  {
1268  //Failed to allocate memory
1269  error = ERROR_OUT_OF_MEMORY;
1270  }
1271  }
1272  else
1273 #endif
1274  //Invalid signature algorithm?
1275  {
1276  //Report an error
1277  error = ERROR_INVALID_SIGNATURE;
1278  }
1279 
1280  //Total number of bytes that have been consumed
1281  *consumed = sizeof(Tls12DigitalSignature) + ntohs(signature->length);
1282 #else
1283  //Not implemented
1284  error = ERROR_NOT_IMPLEMENTED;
1285 #endif
1286 
1287  //Return status code
1288  return error;
1289 }
1290 
1291 
1292 /**
1293  * @brief Version selection
1294  * @param[in] context Pointer to the TLS context
1295  * @param[in] message Pointer to the received ServerHello message
1296  * @param[in] extensions ServerHello extensions offered by the server
1297  * @return Error code
1298  **/
1299 
1302 {
1303  error_t error;
1304  uint16_t selectedVersion;
1305 
1306 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1307  //Clients must check for the SupportedVersions extension prior to
1308  //processing the rest of the ServerHello
1309  if(extensions->selectedVersion != NULL)
1310  {
1311  //If a client receives an extension type in the ServerHello that it did
1312  //not request in the associated ClientHello, it must abort the handshake
1313  //with an unsupported_extension fatal alert
1314  if(context->versionMax <= TLS_VERSION_1_2)
1316 
1317  //The legacy_version field must be set to 0x0303, which is the version
1318  //number for TLS 1.2
1319  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1320  {
1321  if(ntohs(message->serverVersion) != DTLS_VERSION_1_2)
1323  }
1324  else
1325  {
1326  if(ntohs(message->serverVersion) != TLS_VERSION_1_2)
1328  }
1329 
1330  //If this extension is present, clients must ignore the legacy_version
1331  //value and must use only the SupportedVersions extension to determine
1332  //the selected version
1333  selectedVersion = LOAD16BE(extensions->selectedVersion);
1334 
1335 #if (DTLS_SUPPORT == ENABLED)
1336  //DTLS protocol?
1337  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1338  {
1339  //If the SupportedVersions extension contains a version prior to DTLS
1340  //1.3, the client must abort the handshake with an illegal_parameter
1341  //alert (refer to RFC 8446, section 4.2.1)
1342  if(selectedVersion >= DTLS_VERSION_1_2)
1343  return ERROR_ILLEGAL_PARAMETER;
1344 
1345  //Check whether the ServerHello message is received in response to an
1346  //updated ClientHello?
1347  if(context->state == TLS_STATE_SERVER_HELLO_2)
1348  {
1349  //The value of selected_version in the SupportedVersions extension
1350  //of the HelloRetryRequest must be retained in the ServerHello. A
1351  //client must abort the handshake with an illegal_parameter alert if
1352  //the value changes (refer to RFC 8446, section 4.1.4)
1353  if(selectedVersion != dtlsTranslateVersion(context->version))
1354  return ERROR_ILLEGAL_PARAMETER;
1355  }
1356  }
1357  else
1358 #endif
1359  //TLS protocol?
1360  {
1361  //If the SupportedVersions extension contains a version prior to TLS
1362  //1.3, the client must abort the handshake with an illegal_parameter
1363  //alert (refer to RFC 8446, section 4.2.1)
1364  if(selectedVersion <= TLS_VERSION_1_2)
1365  return ERROR_ILLEGAL_PARAMETER;
1366 
1367  //Check whether the ServerHello message is received in response to an
1368  //updated ClientHello?
1369  if(context->state == TLS_STATE_SERVER_HELLO_2)
1370  {
1371  //The value of selected_version in the SupportedVersions extension
1372  //of the HelloRetryRequest must be retained in the ServerHello. A
1373  //client must abort the handshake with an illegal_parameter alert if
1374  //the value changes (refer to RFC 8446, section 4.1.4)
1375  if(selectedVersion != context->version)
1376  return ERROR_ILLEGAL_PARAMETER;
1377  }
1378  }
1379  }
1380  else
1381 #endif
1382  {
1383  //In previous versions of TLS, this field was used for version negotiation
1384  //and represented the selected version number for the connection
1385  selectedVersion = ntohs(message->serverVersion);
1386 
1387 #if (DTLS_SUPPORT == ENABLED)
1388  //DTLS protocol?
1389  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1390  {
1391  //A server which negotiates DTLS 1.3 must set the legacy_version field
1392  //to 0xFEFD (DTLS 1.2) and use the SupportedVersions extension instead
1393  if(selectedVersion < DTLS_VERSION_1_2)
1394  return ERROR_ILLEGAL_PARAMETER;
1395  }
1396  else
1397 #endif
1398  //TLS protocol?
1399  {
1400  //A server which negotiates TLS 1.3 must set the legacy_version field
1401  //to 0x0303 (TLS 1.2) and use the SupportedVersions extension instead
1402  if(selectedVersion > TLS_VERSION_1_2)
1403  return ERROR_ILLEGAL_PARAMETER;
1404  }
1405  }
1406 
1407 #if (DTLS_SUPPORT == ENABLED)
1408  //DTLS protocol?
1409  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1410  {
1411  //Set the DTLS version to be used
1412  error = dtlsSelectVersion(context, selectedVersion);
1413  }
1414  else
1415 #endif
1416  //TLS protocol?
1417  {
1418  //Set the TLS version to be used
1419  error = tlsSelectVersion(context, selectedVersion);
1420  }
1421 
1422  //Specified TLS/DTLS version not supported?
1423  if(error)
1424  return error;
1425 
1426 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1427  //If the ServerHello indicates TLS 1.1 or below, TLS 1.3 client must and
1428  //1.2 clients should check that the last 8 bytes are not equal to the
1429  //bytes 44 4F 57 4E 47 52 44 00
1430  if(context->version <= TLS_VERSION_1_1 &&
1431  context->versionMax >= TLS_VERSION_1_2)
1432  {
1433  //If a match is found, the client must abort the handshake with an
1434  //illegal_parameter alert
1435  if(!memcmp(message->random + 24, tls11DowngradeRandom, 8))
1436  return ERROR_ILLEGAL_PARAMETER;
1437  }
1438 
1439  //If the ServerHello indicates TLS 1.2 or below, TLS 1.3 client must check
1440  //that the last 8 bytes are not equal to the bytes 44 4F 57 4E 47 52 44 00
1441  if(context->version <= TLS_VERSION_1_2 &&
1442  context->versionMax >= TLS_VERSION_1_3)
1443  {
1444  //If a match is found, the client must abort the handshake with an
1445  //illegal_parameter alert
1446  if(!memcmp(message->random + 24, tls12DowngradeRandom, 8))
1447  return ERROR_ILLEGAL_PARAMETER;
1448  }
1449 #endif
1450 
1451  //Successful processing
1452  return NO_ERROR;
1453 }
1454 
1455 
1456 /**
1457  * @brief Resume TLS session via session ID
1458  * @param[in] context Pointer to the TLS context
1459  * @param[in] sessionId Pointer to the session ID provided by the server
1460  * @param[in] sessionIdLen Length of the session ID, in bytes
1461  * @param[in] cipherSuite Cipher suite selected by the server
1462  * @return Error code
1463  **/
1464 
1466  size_t sessionIdLen, uint16_t cipherSuite)
1467 {
1468  error_t error;
1469 
1470  //Initialize status code
1471  error = NO_ERROR;
1472 
1473 #if (TLS_SESSION_RESUME_SUPPORT == ENABLED)
1474  //Check whether the session ID matches the value that was supplied by the
1475  //client
1476  if(sessionIdLen != 0 && sessionIdLen == context->sessionIdLen &&
1477  !memcmp(sessionId, context->sessionId, sessionIdLen))
1478  {
1479  //For resumed sessions, the selected cipher suite shall be the same as
1480  //the session being resumed
1481  if(cipherSuite != 0 && cipherSuite == context->cipherSuite.identifier)
1482  {
1483  //Perform abbreviated handshake
1484  context->resume = TRUE;
1485  }
1486  else
1487  {
1488  //The session ID is no more valid
1489  context->sessionIdLen = 0;
1490 
1491  //When renegotiating, if the server tries to use another version or
1492  //compression method than previously, abort
1493  error = ERROR_ILLEGAL_PARAMETER;
1494  }
1495  }
1496  else
1497 #endif
1498  {
1499  //Perform a full handshake
1500  context->resume = FALSE;
1501  }
1502 
1503  //Return status code
1504  return error;
1505 }
1506 
1507 #endif
#define tlsAllocMem(size)
Definition: tls.h:757
@ TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA256
Definition: tls.h:1115
#define htons(value)
Definition: cpu_endian.h:392
Parsing and checking of TLS extensions.
@ TLS_SIGN_ALGO_DSA
Definition: tls.h:1113
void sha1Update(Sha1Context *context, const void *data, size_t length)
Update the SHA-1 context with a portion of the message being hashed.
Definition: sha1.c:152
TLS helper functions.
uint8_t length
Definition: dtls_misc.h:149
@ ERROR_UNKNOWN_IDENTITY
Definition: error.h:254
HashAlgoInit init
Definition: crypto.h:1139
@ ERROR_UNSUPPORTED_ELLIPTIC_CURVE
Definition: error.h:131
__start_packed struct @82 Tls12DigitalSignature
Digitally-signed element (TLS 1.2)
TLS cipher suites.
error_t dtlsSelectVersion(TlsContext *context, uint16_t version)
Set the DTLS version to be used.
Definition: dtls_misc.c:54
#define TLS_MAX_DH_MODULUS_SIZE
Definition: tls.h:687
@ TLS_COMPRESSION_METHOD_NULL
Definition: tls.h:1015
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 (SSL 3.0, TLS 1.0 and TLS 1.1)
@ ERROR_BUFFER_OVERFLOW
Definition: error.h:140
@ ERROR_VERSION_NOT_SUPPORTED
Definition: error.h:67
@ ERROR_NOT_IMPLEMENTED
Definition: error.h:66
@ ERROR_ILLEGAL_PARAMETER
Definition: error.h:237
RSA/DSA/ECDSA/EdDSA signature generation and verification.
@ ERROR_UNEXPECTED_MESSAGE
Definition: error.h:192
uint8_t p
Definition: ndp.h:298
Helper functions for TLS client.
error_t tlsSelectVersion(TlsContext *context, uint16_t version)
Set the TLS version to be used.
Definition: tls_misc.c:225
error_t dhCheckPublicKey(DhParameters *params, const Mpi *publicKey)
Check Diffie-Hellman public value.
Definition: dh.c:154
#define TRUE
Definition: os_port.h:50
@ TLS_SIGN_ALGO_RSA_PSS_PSS_SHA384
Definition: tls.h:1121
size_t digestSize
Definition: crypto.h:1135
void md5Init(Md5Context *context)
Initialize MD5 message digest context.
Definition: md5.c:136
@ TLS_TRANSPORT_PROTOCOL_DATAGRAM
Definition: tls.h:851
HashAlgoUpdate update
Definition: crypto.h:1140
__start_packed struct @81 TlsDigitalSignature
Digitally-signed element (SSL 3.0, TLS 1.0 and TLS 1.1)
uint8_t signature
Definition: tls.h:1370
Session cache management.
error_t tlsFormatClientKeyParams(TlsContext *context, uint8_t *p, size_t *written)
Format client's key exchange parameters.
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:634
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
error_t tlsFormatSessionId(TlsContext *context, uint8_t *p, size_t *written)
Format session ID.
@ TLS_CERT_DSS_SIGN
Definition: tls.h:1073
@ TLS_SIGN_ALGO_RSA_PSS_PSS_SHA512
Definition: tls.h:1122
error_t tlsFormatCipherSuites(TlsContext *context, uint_t *cipherSuiteTypes, uint8_t *p, size_t *written)
Format the list of cipher suites supported by the client.
#define TLS_RANDOM_SIZE
Definition: tls.h:834
error_t tlsParsePskIdentityHint(TlsContext *context, const uint8_t *p, size_t length, size_t *consumed)
Parse PSK identity hint.
@ TLS_SIGN_ALGO_ED448
Definition: tls.h:1119
size_t contextSize
Definition: crypto.h:1133
uint8_t sessionIdLen
Definition: tls.h:1615
void md5Final(Md5Context *context, uint8_t *digest)
Finish the MD5 message digest.
Definition: md5.c:197
@ TLS_KEY_EXCH_RSA
Definition: tls.h:1027
void md5Update(Md5Context *context, const void *data, size_t length)
Update the MD5 context with a portion of the message being hashed.
Definition: md5.c:158
@ TLS_HASH_ALGO_SHA512
Definition: tls.h:1100
@ TLS_KEY_EXCH_ECDHE_ECDSA
Definition: tls.h:1036
error_t ecLoadDomainParameters(EcDomainParameters *params, const EcCurveInfo *curveInfo)
Load EC domain parameters.
Definition: ec.c:93
@ TLS_KEY_EXCH_ECDHE_RSA
Definition: tls.h:1034
#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:190
__start_packed struct @62 TlsCipherSuites
Cipher suites.
@ TLS_KEY_EXCH_ECDH_ANON
Definition: tls.h:1037
Elliptic curve parameters.
Definition: ec_curves.h:292
void sha1Init(Sha1Context *context)
Initialize SHA-1 message digest context.
Definition: sha1.c:129
@ ERROR_UNSUPPORTED_EXTENSION
Definition: error.h:239
#define TlsContext
Definition: tls.h:36
@ ERROR_UNSUPPORTED_KEY_EXCH_METHOD
Definition: error.h:129
error_t
Error codes.
Definition: error.h:42
@ TLS_CERT_ED25519_SIGN
Definition: tls.h:1083
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:176
const HashAlgo * tlsGetHashAlgo(uint8_t hashAlgoId)
Get the hash algorithm that matches the specified identifier.
Definition: tls_misc.c:829
#define TLS_VERSION_1_2
Definition: tls.h:94
#define TLS_PREMASTER_SECRET_SIZE
Definition: tls.h:722
@ TLS_KEY_EXCH_DH_ANON
Definition: tls.h:1032
uint8_t identifier[]
#define TLS_MAX_VERSION
Definition: tls.h:127
@ TLS_HASH_ALGO_INTRINSIC
Definition: tls.h:1101
#define STORE16BE(a, p)
Definition: cpu_endian.h:246
@ TLS_TYPE_CLIENT_HELLO
Definition: tls.h:933
error_t tlsSelectClientVersion(TlsContext *context, const TlsServerHello *message, const TlsHelloExtensions *extensions)
Version selection.
uint16_t identifier
Definition: tls.h:1814
@ TLS_CIPHER_SUITE_TYPE_UNKNOWN
#define TLS_VERSION_1_3
Definition: tls.h:95
Handshake message processing (TLS client and server)
@ TLS_HASH_ALGO_SHA384
Definition: tls.h:1099
@ TLS_CERT_RSA_PSS_SIGN
Definition: tls.h:1082
@ 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:705
@ TLS_SIGN_ALGO_ED25519
Definition: tls.h:1118
MD5 algorithm context.
Definition: md5.h:58
__start_packed struct @84 TlsHandshake
TLS handshake message.
@ TLS_HASH_ALGO_SHA256
Definition: tls.h:1098
#define SSL_VERSION_3_0
Definition: tls.h:91
@ TLS_CERT_ED448_SIGN
Definition: tls.h:1084
error_t tlsFormatInitialClientHello(TlsContext *context)
Format initial ClientHello message.
@ TLS_CERT_RSA_SIGN
Definition: tls.h:1072
@ TLS_KEY_EXCH_DHE_PSK
Definition: tls.h:1040
uint16_t dtlsTranslateVersion(uint16_t version)
Translate TLS version into DTLS version.
Definition: dtls_misc.c:113
#define MD5_DIGEST_SIZE
Definition: md5.h:40
Hello extensions.
Definition: tls.h:1894
@ TLS_FALLBACK_SCSV
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)
uint_t mpiGetBitLength(const Mpi *a)
Get the actual length in bits.
Definition: mpi.c:195
error_t ecdhComputeSharedSecret(EcdhContext *context, uint8_t *output, size_t outputSize, size_t *outputLen)
Compute ECDH shared secret.
Definition: ecdh.c:385
@ TLS_KEY_EXCH_RSA_PSK
Definition: tls.h:1039
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:1141
__start_packed struct @85 TlsClientHello
ClientHello message.
#define ntohs(value)
Definition: cpu_endian.h:398
@ TLS_EC_CURVE_TYPE_NAMED_CURVE
Definition: tls.h:1279
#define TRACE_DEBUG(...)
Definition: debug.h:106
error_t tlsVerifyEddsaSignature(TlsContext *context, const uint8_t *message, size_t messageLen, const uint8_t *signature, size_t signatureLen)
Verify EdDSA signature.
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:811
#define TLS_VERSION_1_1
Definition: tls.h:93
#define SHA1_DIGEST_SIZE
Definition: sha1.h:40
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:667
const char_t * tlsGetCipherSuiteName(uint16_t identifier)
Convert cipher suite identifier to string representation.
uint8_t digest[1]
Definition: crypto.h:1120
#define HTONS(value)
Definition: cpu_endian.h:390
uint8_t n
uint8_t extensions[]
Definition: tls13_misc.h:327
uint16_t cipherSuite
Cipher suite identifier.
Definition: tls13_misc.h:372
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:1040
@ TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA512
Definition: tls.h:1117
@ TLS_SIGN_ALGO_RSA_PSS_PSS_SHA256
Definition: tls.h:1120
const TlsCipherSuiteInfo tlsSupportedCipherSuites[]
__start_packed struct @86 TlsServerHello
ServerHello message.
@ TLS_KEY_EXCH_ECDHE_PSK
Definition: tls.h:1041
uint8_t sessionId[]
Definition: tls.h:1616
error_t tlsResumeClientSession(TlsContext *context, const uint8_t *sessionId, size_t sessionIdLen, uint16_t cipherSuite)
Resume TLS session via session ID.
__start_packed struct @80 TlsPskIdentityHint
PSK identity hint.
uint8_t message[]
Definition: chap.h:152
const EcCurveInfo * tlsGetCurveInfo(TlsContext *context, uint16_t namedCurve)
Get the EC domain parameters that match the specified named curve.
Definition: tls_misc.c:890
__start_packed struct @83 TlsRecord
TLS record.
error_t tlsVerifyRsaSignature(const RsaPublicKey *key, const uint8_t *digest, const uint8_t *signature, size_t signatureLen)
Verify RSA signature (SSL 3.0, TLS 1.0 and TLS 1.1)
TLS (Transport Layer Security)
@ TLS_SIGN_ALGO_RSA
Definition: tls.h:1112
const uint8_t tls11DowngradeRandom[8]
const uint8_t tls12DowngradeRandom[8]
error_t tlsVerifyDsaSignature(TlsContext *context, const uint8_t *digest, size_t digestLen, const uint8_t *signature, size_t signatureLen)
Verify DSA signature.
#define STORE24BE(a, p)
Definition: cpu_endian.h:257
SHA-1 algorithm context.
Definition: sha1.h:58
@ TLS_CERT_ECDSA_SIGN
Definition: tls.h:1079
__start_packed struct @63 TlsCompressMethods
Compression methods.
@ TLS_KEY_EXCH_DHE_DSS
Definition: tls.h:1031
@ TLS_TRANSPORT_PROTOCOL_STREAM
Definition: tls.h:850
__start_packed struct @79 TlsPskIdentity
PSK identity.
Common interface for hash algorithms.
Definition: crypto.h:1128
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:91
@ ERROR_DECODING_FAILED
Definition: error.h:235
error_t tlsFormatPskIdentity(TlsContext *context, uint8_t *p, size_t *written)
Format PSK identity.
unsigned int uint_t
Definition: compiler_port.h:45
#define TRACE_DEBUG_MPI(p, a)
Definition: debug.h:109
#define LOAD16BE(p)
Definition: cpu_endian.h:170
TlsCipherSuiteType tlsGetCipherSuiteType(uint16_t identifier)
Check whether the specified identifier matches an ECC or FFDHE cipher suite.
Handshake message processing (TLS client)
#define tlsFreeMem(p)
Definition: tls.h:762
@ TLS_STATE_SERVER_HELLO_2
Definition: tls.h:1296
@ ERROR_INVALID_SIGNATURE
Definition: error.h:223
@ TLS_SIGN_ALGO_ECDSA
Definition: tls.h:1114
error_t ecdhCheckPublicKey(const EcDomainParameters *params, EcPoint *publicKey)
Check ECDH public key.
Definition: ecdh.c:272
@ TLS_KEY_EXCH_DHE_RSA
Definition: tls.h:1029
#define DTLS_VERSION_1_2
Definition: dtls_misc.h:36
void sha1Final(Sha1Context *context, uint8_t *digest)
Finish the SHA-1 message digest.
Definition: sha1.c:191
Generic hash algorithm context.
Definition: crypto.h:1118
@ TLS_SIGN_ALGO_RSA_PSS_RSAE_SHA384
Definition: tls.h:1116
@ NO_ERROR
Success.
Definition: error.h:44
error_t tlsVerifyEcdsaSignature(TlsContext *context, const uint8_t *digest, size_t digestLen, const uint8_t *signature, size_t signatureLen)
Verify ECDSA signature.
Debugging facilities.
error_t tlsFormatClientHello(TlsContext *context, TlsClientHello *message, size_t *length)
Format ClientHello message.
Definition: tls_client.c:284
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:742
error_t ecdhGenerateKeyPair(EcdhContext *context, const PrngAlgo *prngAlgo, void *prngContext)
ECDH key pair generation.
Definition: ecdh.c:87
error_t tlsFormatCompressMethods(TlsContext *context, uint8_t *p, size_t *written)
Format the list of compression methods supported by the client.