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