tls_server_misc.c
Go to the documentation of this file.
1 /**
2  * @file tls_server_misc.c
3  * @brief Helper functions for TLS server
4  *
5  * @section License
6  *
7  * SPDX-License-Identifier: GPL-2.0-or-later
8  *
9  * Copyright (C) 2010-2024 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneSSL Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.4.4
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL TLS_TRACE_LEVEL
33 
34 //Dependencies
35 #include "tls.h"
36 #include "tls_cipher_suites.h"
37 #include "tls_server.h"
38 #include "tls_server_extensions.h"
39 #include "tls_server_misc.h"
40 #include "tls_common.h"
41 #include "tls_extensions.h"
42 #include "tls_certificate.h"
43 #include "tls_sign_generate.h"
44 #include "tls_sign_misc.h"
45 #include "tls_cache.h"
46 #include "tls_ffdhe.h"
47 #include "tls_record.h"
48 #include "tls_misc.h"
49 #include "pkix/pem_import.h"
50 #include "debug.h"
51 
52 //Check TLS library configuration
53 #if (TLS_SUPPORT == ENABLED && TLS_SERVER_SUPPORT == ENABLED)
54 
55 
56 /**
57  * @brief Format PSK identity hint
58  * @param[in] context Pointer to the TLS context
59  * @param[in] p Output stream where to write the PSK identity hint
60  * @param[out] written Total number of bytes that have been written
61  * @return Error code
62  **/
63 
65  uint8_t *p, size_t *written)
66 {
67  size_t n;
68  TlsPskIdentityHint *pskIdentityHint;
69 
70  //Point to the PSK identity hint
71  pskIdentityHint = (TlsPskIdentityHint *) p;
72 
73 #if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
74  TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
75  //Any PSK identity hint defined?
76  if(context->pskIdentityHint != NULL)
77  {
78  //Determine the length of the PSK identity hint
79  n = osStrlen(context->pskIdentityHint);
80  //Copy PSK identity hint
81  osMemcpy(pskIdentityHint->value, context->pskIdentityHint, n);
82  }
83  else
84 #endif
85  {
86  //No PSK identity hint is provided
87  n = 0;
88  }
89 
90  //The PSK identity hint is preceded by a 2-byte length field
91  pskIdentityHint->length = htons(n);
92 
93  //Total number of bytes that have been written
94  *written = sizeof(TlsPskIdentityHint) + n;
95 
96  //Successful processing
97  return NO_ERROR;
98 }
99 
100 
101 /**
102  * @brief Format server's key exchange parameters
103  * @param[in] context Pointer to the TLS context
104  * @param[in] p Output stream where to write the server's key exchange parameters
105  * @param[out] written Total number of bytes that have been written
106  * @return Error code
107  **/
108 
110  uint8_t *p, size_t *written)
111 {
112  error_t error;
113 
114 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
115  //Initialize status code
116  error = NO_ERROR;
117 
118  //Total number of bytes that have been written
119  *written = 0;
120 
121 #if (TLS_DH_ANON_KE_SUPPORT == ENABLED || TLS_DHE_RSA_KE_SUPPORT == ENABLED || \
122  TLS_DHE_DSS_KE_SUPPORT == ENABLED || TLS_DHE_PSK_KE_SUPPORT == ENABLED)
123  //Diffie-Hellman key exchange method?
124  if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
125  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
126  context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
127  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK)
128  {
129  size_t n;
130 
131 #if (TLS_FFDHE_SUPPORT == ENABLED)
132  const TlsFfdheGroup *ffdheGroup;
133 
134  //Get the FFDHE parameters that match the specified named group
135  ffdheGroup = tlsGetFfdheGroup(context, context->namedGroup);
136 
137  //Valid FFDHE group?
138  if(ffdheGroup != NULL)
139  {
140  //Load FFDHE parameters
141  error = tlsLoadFfdheParameters(&context->dhContext.params, ffdheGroup);
142  }
143 #endif
144 
145  //Check status code
146  if(!error)
147  {
148  //Generate an ephemeral key pair
149  error = dhGenerateKeyPair(&context->dhContext, context->prngAlgo,
150  context->prngContext);
151  }
152 
153  //Check status code
154  if(!error)
155  {
156  //Debug message
157  TRACE_DEBUG("Diffie-Hellman parameters:\r\n");
158  TRACE_DEBUG(" Prime modulus:\r\n");
159  TRACE_DEBUG_MPI(" ", &context->dhContext.params.p);
160  TRACE_DEBUG(" Generator:\r\n");
161  TRACE_DEBUG_MPI(" ", &context->dhContext.params.g);
162  TRACE_DEBUG(" Server public value:\r\n");
163  TRACE_DEBUG_MPI(" ", &context->dhContext.ya);
164 
165  //Encode the prime modulus to an opaque vector
166  error = tlsWriteMpi(&context->dhContext.params.p, p, &n);
167  }
168 
169  //Check status code
170  if(!error)
171  {
172  //Advance data pointer
173  p += n;
174  //Total number of bytes that have been written
175  *written += n;
176 
177  //Encode the generator to an opaque vector
178  error = tlsWriteMpi(&context->dhContext.params.g, p, &n);
179  }
180 
181  //Check status code
182  if(!error)
183  {
184  //Advance data pointer
185  p += n;
186  //Total number of bytes that have been written
187  *written += n;
188 
189  //Encode the server's public value to an opaque vector
190  error = tlsWriteMpi(&context->dhContext.ya, p, &n);
191  }
192 
193  //Check status code
194  if(!error)
195  {
196  //Advance data pointer
197  p += n;
198  //Adjust the length of the key exchange parameters
199  *written += n;
200  }
201  }
202  else
203 #endif
204 #if (TLS_ECDH_ANON_KE_SUPPORT == ENABLED || TLS_ECDHE_RSA_KE_SUPPORT == ENABLED || \
205  TLS_ECDHE_ECDSA_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
206  //ECDH key exchange method?
207  if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
208  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
209  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
210  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
211  {
212  size_t n;
213  const EcCurveInfo *curveInfo;
214 
215  //Retrieve the elliptic curve to be used
216  curveInfo = tlsGetCurveInfo(context, context->namedGroup);
217 
218  //Make sure the elliptic curve is supported
219  if(curveInfo != NULL)
220  {
221  //Load EC domain parameters
222  error = ecLoadDomainParameters(&context->ecdhContext.params,
223  curveInfo);
224 
225  //Check status code
226  if(!error)
227  {
228 #if (TLS_ECC_CALLBACK_SUPPORT == ENABLED)
229  //Any registered callback?
230  if(context->ecdhCallback != NULL)
231  {
232  //Invoke user callback function
233  error = context->ecdhCallback(context);
234  }
235  else
236 #endif
237  {
238  //No callback function defined
240  }
241 
242  //Check status code
244  {
245  //Generate an ephemeral key pair
246  error = ecdhGenerateKeyPair(&context->ecdhContext,
247  context->prngAlgo, context->prngContext);
248  }
249  }
250 
251  //Check status code
252  if(!error)
253  {
254  //Debug message
255  TRACE_DEBUG(" Server public key X:\r\n");
256  TRACE_DEBUG_MPI(" ", &context->ecdhContext.qa.q.x);
257  TRACE_DEBUG(" Server public key Y:\r\n");
258  TRACE_DEBUG_MPI(" ", &context->ecdhContext.qa.q.y);
259 
260  //Set the type of the elliptic curve domain parameters
262 
263  //Advance data pointer
264  p += sizeof(uint8_t);
265  //Total number of bytes that have been written
266  *written += sizeof(uint8_t);
267 
268  //Write elliptic curve identifier
269  STORE16BE(context->namedGroup, p);
270 
271  //Advance data pointer
272  p += sizeof(uint16_t);
273  //Total number of bytes that have been written
274  *written += sizeof(uint16_t);
275 
276  //Write server's public key
277  error = tlsWriteEcPoint(&context->ecdhContext.params,
278  &context->ecdhContext.qa.q, p, &n);
279  }
280 
281  //Check status code
282  if(!error)
283  {
284  //Advance data pointer
285  p +=n;
286  //Total number of bytes that have been written
287  *written += n;
288  }
289  }
290  else
291  {
292  //The specified elliptic curve is not supported
293  error = ERROR_FAILURE;
294  }
295  }
296  else
297 #endif
298  //Any other exchange method?
299  {
300  //It is not legal to send the ServerKeyExchange message when a key
301  //exchange method other than DHE_DSS, DHE_RSA, DH_anon, ECDHE_RSA,
302  //ECDHE_ECDSA or ECDH_anon is selected
303  error = ERROR_FAILURE;
304  }
305 #else
306  //Not implemented
307  error = ERROR_NOT_IMPLEMENTED;
308 #endif
309 
310  //Return status code
311  return error;
312 }
313 
314 
315 /**
316  * @brief Sign server's key exchange parameters (TLS 1.0 and TLS 1.1)
317  * @param[in] context Pointer to the TLS context
318  * @param[in] signature Output stream where to write the digital signature
319  * @param[in] params Pointer to the server's key exchange parameters
320  * @param[in] paramsLen Length of the server's key exchange parameters
321  * @param[out] written Total number of bytes that have been written
322  * @return Error code
323  **/
324 
326  TlsDigitalSignature *signature, const uint8_t *params,
327  size_t paramsLen, size_t *written)
328 {
329  error_t error;
330 
331 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
332  //Initialize status code
333  error = NO_ERROR;
334 
335  //Total number of bytes that have been written
336  *written = 0;
337 
338 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
339  //RSA certificate?
340  if(context->cert->type == TLS_CERT_RSA_SIGN)
341  {
342  Md5Context *md5Context;
343  Sha1Context *sha1Context;
344  RsaPrivateKey privateKey;
345 
346  //Initialize RSA private key
347  rsaInitPrivateKey(&privateKey);
348 
349  //Allocate a memory buffer to hold the MD5 context
350  md5Context = tlsAllocMem(sizeof(Md5Context));
351 
352  //Successful memory allocation?
353  if(md5Context != NULL)
354  {
355  //Compute MD5(ClientHello.random + ServerHello.random +
356  //ServerKeyExchange.params)
357  md5Init(md5Context);
358  md5Update(md5Context, context->clientRandom, TLS_RANDOM_SIZE);
359  md5Update(md5Context, context->serverRandom, TLS_RANDOM_SIZE);
360  md5Update(md5Context, params, paramsLen);
361  md5Final(md5Context, context->serverVerifyData);
362 
363  //Release previously allocated memory
364  tlsFreeMem(md5Context);
365  }
366  else
367  {
368  //Failed to allocate memory
369  error = ERROR_OUT_OF_MEMORY;
370  }
371 
372  //Check status code
373  if(!error)
374  {
375  //Allocate a memory buffer to hold the SHA-1 context
376  sha1Context = tlsAllocMem(sizeof(Sha1Context));
377 
378  //Successful memory allocation?
379  if(sha1Context != NULL)
380  {
381  //Compute SHA(ClientHello.random + ServerHello.random +
382  //ServerKeyExchange.params)
383  sha1Init(sha1Context);
384  sha1Update(sha1Context, context->clientRandom, TLS_RANDOM_SIZE);
385  sha1Update(sha1Context, context->serverRandom, TLS_RANDOM_SIZE);
386  sha1Update(sha1Context, params, paramsLen);
387  sha1Final(sha1Context, context->serverVerifyData + MD5_DIGEST_SIZE);
388 
389  //Release previously allocated memory
390  tlsFreeMem(sha1Context);
391  }
392  else
393  {
394  //Failed to allocate memory
395  error = ERROR_OUT_OF_MEMORY;
396  }
397  }
398 
399  //Check status code
400  if(!error)
401  {
402  //Decode the PEM structure that holds the RSA private key
403  error = pemImportRsaPrivateKey(context->cert->privateKey,
404  context->cert->privateKeyLen, context->cert->password, &privateKey);
405  }
406 
407  //Check status code
408  if(!error)
409  {
410  //Sign the key exchange parameters using RSA
411  error = tlsGenerateRsaSignature(&privateKey,
412  context->serverVerifyData, signature->value, written);
413  }
414 
415  //Release previously allocated resources
416  rsaFreePrivateKey(&privateKey);
417  }
418  else
419 #endif
420 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
421  //DSA certificate?
422  if(context->cert->type == TLS_CERT_DSS_SIGN)
423  {
424  Sha1Context *sha1Context;
425 
426  //Allocate a memory buffer to hold the SHA-1 context
427  sha1Context = tlsAllocMem(sizeof(Sha1Context));
428 
429  //Successful memory allocation?
430  if(sha1Context != NULL)
431  {
432  //Compute SHA(ClientHello.random + ServerHello.random +
433  //ServerKeyExchange.params)
434  sha1Init(sha1Context);
435  sha1Update(sha1Context, context->clientRandom, TLS_RANDOM_SIZE);
436  sha1Update(sha1Context, context->serverRandom, TLS_RANDOM_SIZE);
437  sha1Update(sha1Context, params, paramsLen);
438  sha1Final(sha1Context, context->serverVerifyData);
439 
440  //Release previously allocated memory
441  tlsFreeMem(sha1Context);
442  }
443  else
444  {
445  //Failed to allocate memory
446  error = ERROR_OUT_OF_MEMORY;
447  }
448 
449  //Check status code
450  if(!error)
451  {
452  //Sign the key exchange parameters using DSA
453  error = tlsGenerateDsaSignature(context, context->serverVerifyData,
454  SHA1_DIGEST_SIZE, signature->value, written);
455  }
456  }
457  else
458 #endif
459 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
460  //ECDSA certificate?
461  if(context->cert->type == TLS_CERT_ECDSA_SIGN)
462  {
463  Sha1Context *sha1Context;
464 
465  //Allocate a memory buffer to hold the SHA-1 context
466  sha1Context = tlsAllocMem(sizeof(Sha1Context));
467 
468  //Successful memory allocation?
469  if(sha1Context != NULL)
470  {
471  //Compute SHA(ClientHello.random + ServerHello.random +
472  //ServerKeyExchange.params)
473  sha1Init(sha1Context);
474  sha1Update(sha1Context, context->clientRandom, TLS_RANDOM_SIZE);
475  sha1Update(sha1Context, context->serverRandom, TLS_RANDOM_SIZE);
476  sha1Update(sha1Context, params, paramsLen);
477  sha1Final(sha1Context, context->serverVerifyData);
478 
479  //Release previously allocated memory
480  tlsFreeMem(sha1Context);
481  }
482  else
483  {
484  //Failed to allocate memory
485  error = ERROR_OUT_OF_MEMORY;
486  }
487 
488  //Check status code
489  if(!error)
490  {
491  //Sign the key exchange parameters using ECDSA
492  error = tlsGenerateEcdsaSignature(context, context->serverVerifyData,
493  SHA1_DIGEST_SIZE, signature->value, written);
494  }
495  }
496  else
497 #endif
498  //Invalid certificate?
499  {
500  //Report an error
502  }
503 
504  //Check status code
505  if(!error)
506  {
507  //Fix the length of the digitally-signed element
508  signature->length = htons(*written);
509  //Adjust the length of the signature
510  *written += sizeof(TlsDigitalSignature);
511  }
512 #else
513  //Not implemented
514  error = ERROR_NOT_IMPLEMENTED;
515 #endif
516 
517  //Return status code
518  return error;
519 }
520 
521 
522 /**
523  * @brief Sign server's key exchange parameters (TLS 1.2)
524  * @param[in] context Pointer to the TLS context
525  * @param[in] signature Output stream where to write the digital signature
526  * @param[in] params Pointer to the server's key exchange parameters
527  * @param[in] paramsLen Length of the server's key exchange parameters
528  * @param[out] written Total number of bytes that have been written
529  * @return Error code
530  **/
531 
533  Tls12DigitalSignature *signature, const uint8_t *params,
534  size_t paramsLen, size_t *written)
535 {
536  error_t error;
537 
538 #if (TLS_MAX_VERSION >= TLS_VERSION_1_2 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
539  //Initialize status code
540  error = NO_ERROR;
541 
542  //Total number of bytes that have been written
543  *written = 0;
544 
545  //The algorithm field specifies the signature scheme
546  signature->algorithm = htons(context->signScheme);
547 
548 #if (TLS_RSA_SIGN_SUPPORT == ENABLED || TLS_RSA_PSS_SIGN_SUPPORT == ENABLED || \
549  TLS_DSA_SIGN_SUPPORT == ENABLED || TLS_ECDSA_SIGN_SUPPORT == ENABLED)
550  //RSA, DSA or ECDSA signature scheme?
551  if(TLS_SIGN_ALGO(context->signScheme) == TLS_SIGN_ALGO_RSA ||
552  TLS_SIGN_ALGO(context->signScheme) == TLS_SIGN_ALGO_DSA ||
553  TLS_SIGN_ALGO(context->signScheme) == TLS_SIGN_ALGO_ECDSA ||
554  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA256 ||
555  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA384 ||
556  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA512 ||
557  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256 ||
558  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384 ||
559  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512)
560  {
561  const HashAlgo *hashAlgo;
562  HashContext *hashContext;
563 
564  //Retrieve the hash algorithm used for signing
565  if(context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA256 ||
566  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256)
567  {
568  //The hashing is intrinsic to the signature algorithm
570  }
571  else if(context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA384 ||
572  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384)
573  {
574  //The hashing is intrinsic to the signature algorithm
576  }
577  else if(context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA512 ||
578  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512)
579  {
580  //The hashing is intrinsic to the signature algorithm
582  }
583  else
584  {
585  //Select the relevant hash algorithm
586  hashAlgo = tlsGetHashAlgo(TLS_HASH_ALGO(context->signScheme));
587  }
588 
589  //Make sure the hash algorithm is supported
590  if(hashAlgo != NULL)
591  {
592  //Allocate a memory buffer to hold the hash context
593  hashContext = tlsAllocMem(hashAlgo->contextSize);
594 
595  //Successful memory allocation?
596  if(hashContext != NULL)
597  {
598  //Compute hash(ClientHello.random + ServerHello.random +
599  //ServerKeyExchange.params)
600  hashAlgo->init(hashContext);
601  hashAlgo->update(hashContext, context->clientRandom, TLS_RANDOM_SIZE);
602  hashAlgo->update(hashContext, context->serverRandom, TLS_RANDOM_SIZE);
603  hashAlgo->update(hashContext, params, paramsLen);
604  hashAlgo->final(hashContext, NULL);
605 
606 #if (TLS_RSA_SIGN_SUPPORT == ENABLED)
607  //RSA signature scheme?
608  if(TLS_SIGN_ALGO(context->signScheme) == TLS_SIGN_ALGO_RSA)
609  {
610  //Sign the key exchange parameters using RSA
611  error = tlsGenerateRsaPkcs1Signature(context, hashAlgo,
612  hashContext->digest, signature->value, written);
613  }
614  else
615 #endif
616 #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
617  //RSA-PSS signature scheme?
618  if(context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA256 ||
619  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA384 ||
620  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA512 ||
621  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256 ||
622  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384 ||
623  context->signScheme == TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512)
624  {
625  //Sign the key exchange parameters using RSA-PSS
626  error = tlsGenerateRsaPssSignature(context, hashAlgo,
627  hashContext->digest, signature->value, written);
628  }
629  else
630 #endif
631 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
632  //DSA signature scheme?
633  if(TLS_SIGN_ALGO(context->signScheme) == TLS_SIGN_ALGO_DSA)
634  {
635  //Sign the key exchange parameters using DSA
636  error = tlsGenerateDsaSignature(context, hashContext->digest,
637  hashAlgo->digestSize, signature->value, written);
638  }
639  else
640 #endif
641 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED)
642  //ECDSA signature scheme?
643  if(TLS_SIGN_ALGO(context->signScheme) == TLS_SIGN_ALGO_ECDSA)
644  {
645  //Sign the key exchange parameters using ECDSA
646  error = tlsGenerateEcdsaSignature(context, hashContext->digest,
647  hashAlgo->digestSize, signature->value, written);
648  }
649  else
650 #endif
651  //Invalid signature scheme?
652  {
653  //Report an error
655  }
656 
657  //Release previously allocated memory
658  tlsFreeMem(hashContext);
659  }
660  else
661  {
662  //Failed to allocate memory
663  error = ERROR_OUT_OF_MEMORY;
664  }
665  }
666  else
667  {
668  //Hash algorithm not supported
670  }
671  }
672  else
673 #endif
674 #if (TLS_ED25519_SIGN_SUPPORT == ENABLED)
675  //Ed25519 signature scheme?
676  if(context->signScheme == TLS_SIGN_SCHEME_ED25519)
677  {
678  DataChunk messageChunks[4];
679 
680  //Data to be signed is run through the EdDSA algorithm without pre-hashing
681  messageChunks[0].buffer = context->clientRandom;
682  messageChunks[0].length = TLS_RANDOM_SIZE;
683  messageChunks[1].buffer = context->serverRandom;
684  messageChunks[1].length = TLS_RANDOM_SIZE;
685  messageChunks[2].buffer = params;
686  messageChunks[2].length = paramsLen;
687  messageChunks[3].buffer = NULL;
688  messageChunks[3].length = 0;
689 
690  //Sign the key exchange parameters using Ed25519
691  error = tlsGenerateEd25519Signature(context, messageChunks,
692  signature->value, written);
693  }
694  else
695 #endif
696 #if (TLS_ED448_SIGN_SUPPORT == ENABLED)
697  //Ed448 signature scheme?
698  if(context->signScheme == TLS_SIGN_SCHEME_ED448)
699  {
700  DataChunk messageChunks[4];
701 
702  //Data to be signed is run through the EdDSA algorithm without pre-hashing
703  messageChunks[0].buffer = context->clientRandom;
704  messageChunks[0].length = TLS_RANDOM_SIZE;
705  messageChunks[1].buffer = context->serverRandom;
706  messageChunks[1].length = TLS_RANDOM_SIZE;
707  messageChunks[2].buffer = params;
708  messageChunks[2].length = paramsLen;
709  messageChunks[3].buffer = NULL;
710  messageChunks[3].length = 0;
711 
712  //Sign the key exchange parameters using Ed448
713  error = tlsGenerateEd448Signature(context, messageChunks,
714  signature->value, written);
715  }
716  else
717 #endif
718  //Invalid signature scheme?
719  {
720  //Report an error
722  }
723 
724  //Check status code
725  if(!error)
726  {
727  //Fix the length of the digitally-signed element
728  signature->length = htons(*written);
729  //Adjust the length of the message
730  *written += sizeof(Tls12DigitalSignature);
731  }
732 #else
733  //Not implemented
734  error = ERROR_NOT_IMPLEMENTED;
735 #endif
736 
737  //Return status code
738  return error;
739 }
740 
741 
742 /**
743  * @brief Check whether the ClientHello includes any SCSV cipher suites
744  * @param[in] context Pointer to the TLS context
745  * @param[in] cipherSuites List of cipher suites offered by the client
746  * @return Error code
747  **/
748 
750  const TlsCipherSuites *cipherSuites)
751 {
752  error_t error;
753  uint_t i;
754  uint_t n;
755  uint16_t serverVersion;
756 
757  //Initialize status code
758  error = NO_ERROR;
759 
760  //Get the highest version supported by the implementation (legacy version)
761  serverVersion = MIN(context->versionMax, TLS_VERSION_1_2);
762 
763 #if (DTLS_SUPPORT == ENABLED)
764  //DTLS protocol?
765  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
766  {
767  //Translate TLS version into DTLS version
768  serverVersion = dtlsTranslateVersion(serverVersion);
769  }
770 #endif
771 
772  //Get the number of cipher suite identifiers present in the list
773  n = ntohs(cipherSuites->length) / 2;
774 
775  //Debug message
776  TRACE_DEBUG("Cipher suites:\r\n");
777 
778  //Loop through the list of cipher suite identifiers
779  for(i = 0; i < n; i++)
780  {
781  //Debug message
782  TRACE_DEBUG(" 0x%04" PRIX16 " (%s)\r\n", ntohs(cipherSuites->value[i]),
783  tlsGetCipherSuiteName(ntohs(cipherSuites->value[i])));
784 
785 #if (TLS_SECURE_RENEGOTIATION_SUPPORT == ENABLED)
786  //TLS_EMPTY_RENEGOTIATION_INFO_SCSV signaling cipher suite?
787  if(ntohs(cipherSuites->value[i]) == TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
788  {
789  //Initial handshake?
790  if(context->clientVerifyDataLen == 0)
791  {
792  //Set the secure_renegotiation flag to TRUE
793  context->secureRenegoFlag = TRUE;
794  }
795  //Secure renegotiation?
796  else
797  {
798  //When a ClientHello is received, the server must verify that it
799  //does not contain the TLS_EMPTY_RENEGOTIATION_INFO_SCSV SCSV. If
800  //the SCSV is present, the server must abort the handshake
801  error = ERROR_HANDSHAKE_FAILED;
802  break;
803  }
804  }
805  else
806 #endif
807  //TLS_FALLBACK_SCSV signaling cipher suite?
808  if(ntohs(cipherSuites->value[i]) == TLS_FALLBACK_SCSV)
809  {
810 #if (DTLS_SUPPORT == ENABLED)
811  //DTLS protocol?
812  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
813  {
814  //Test if the highest protocol version supported by the server is
815  //higher than the version indicated by the client
816  if(serverVersion < context->clientVersion)
817  {
818  //The server must respond with a fatal inappropriate_fallback alert
820  break;
821  }
822  }
823  else
824 #endif
825  //TLS protocol?
826  {
827  //Test if the highest protocol version supported by the server is
828  //higher than the version indicated by the client
829  if(serverVersion > context->clientVersion)
830  {
831  //The server must respond with a fatal inappropriate_fallback alert
833  break;
834  }
835  }
836  }
837  }
838 
839  //Return status code
840  return error;
841 }
842 
843 
844 /**
845  * @brief Resume TLS session via session ID
846  * @param[in] context Pointer to the TLS context
847  * @param[in] sessionId Pointer to the session ID offered by the client
848  * @param[in] sessionIdLen Length of the session ID, in bytes
849  * @param[in] cipherSuites List of cipher suites offered by the client
850  * @param[in] extensions ClientHello extensions offered by the client
851  * @return Error code
852  **/
853 
855  size_t sessionIdLen, const TlsCipherSuites *cipherSuites,
857 {
858  error_t error;
859 
860  //Initialize status code
861  error = NO_ERROR;
862 
863 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2 && \
864  TLS_SESSION_RESUME_SUPPORT == ENABLED)
865  //Check whether session caching is supported
866  if(context->cache != NULL)
867  {
868  uint_t i;
869  uint_t n;
870  TlsSessionState *session;
871 
872  //If the session ID was non-empty, the server will look in its session
873  //cache for a match
874  session = tlsFindCache(context->cache, sessionId, sessionIdLen);
875 
876  //Matching session found?
877  if(session != NULL)
878  {
879  //Whenever a client already knows the highest protocol version known
880  //to a server (for example, when resuming a session), it should
881  //initiate the connection in that native protocol
882  if(session->version != context->version)
883  {
884  session = NULL;
885  }
886  }
887 
888  //Matching session found?
889  if(session != NULL)
890  {
891  //Get the total number of cipher suites offered by the client
892  n = ntohs(cipherSuites->length) / 2;
893 
894  //Loop through the list of cipher suite identifiers
895  for(i = 0; i < n; i++)
896  {
897  //Matching cipher suite?
898  if(ntohs(cipherSuites->value[i]) == session->cipherSuite)
899  {
900  break;
901  }
902  }
903 
904  //If the cipher suite is not present in the list cipher suites offered
905  //by the client, the server must not perform the abbreviated handshake
906  if(i >= n)
907  {
908  session = NULL;
909  }
910  }
911 
912 #if (TLS_SNI_SUPPORT == ENABLED)
913  //Matching session found?
914  if(session != NULL)
915  {
916  //ServerName extension found?
917  if(session->serverName != NULL && context->serverName != NULL)
918  {
919  //A server that implements this extension must not accept the
920  //request to resume the session if the ServerName extension contains
921  //a different name (refer to RFC 6066, section 3)
922  if(osStrcmp(session->serverName, context->serverName) != 0)
923  {
924  //Instead, the server proceeds with a full handshake to establish
925  //a new session
926  session = NULL;
927  }
928  }
929  else if(session->serverName == NULL && context->serverName == NULL)
930  {
931  //The ServerName extension is not present
932  }
933  else
934  {
935  //The server proceeds with a full handshake to establish a new
936  //session
937  session = NULL;
938  }
939  }
940 #endif
941 
942 #if (TLS_EXT_MASTER_SECRET_SUPPORT == ENABLED)
943  //Matching session found?
944  if(session != NULL)
945  {
946  //ExtendedMasterSecret extension found?
947  if(extensions->extendedMasterSecret != NULL)
948  {
949  //If the original session did not use the ExtendedMasterSecret
950  //extension but the new ClientHello contains the extension, then
951  //the server must not perform the abbreviated handshake
952  if(!session->extendedMasterSecret)
953  {
954  session = NULL;
955  }
956  }
957  }
958 #endif
959 
960  //Check whether the server has decided to resume a previous session
961  if(session != NULL)
962  {
963  //Perform abbreviated handshake
964  context->resume = TRUE;
965 
966  //Restore cached session parameters
967  error = tlsRestoreSessionId(context, session);
968 
969  //Check status code
970  if(!error)
971  {
972  //Select the relevant cipher suite
973  error = tlsSelectCipherSuite(context, session->cipherSuite);
974  }
975 
976  //Check status code
977  if(!error)
978  {
979  //Retrieve the type of the cipher suite presented by the client
980  context->cipherSuiteTypes = tlsGetCipherSuiteType(
981  session->cipherSuite);
982  }
983  }
984  else
985  {
986  //Perform a full handshake
987  context->resume = FALSE;
988 
989  //Generate a new random session ID
990  error = tlsGenerateSessionId(context, 32);
991  }
992  }
993  else
994 #endif
995  {
996  //Perform a full handshake
997  context->resume = FALSE;
998  //The session cannot be resumed
999  context->sessionIdLen = 0;
1000  }
1001 
1002  //Return status code
1003  return error;
1004 }
1005 
1006 
1007 /**
1008  * @brief Resume TLS session via session ticket
1009  * @param[in] context Pointer to the TLS context
1010  * @param[in] sessionId Pointer to the session ID offered by the client
1011  * @param[in] sessionIdLen Length of the session ID, in bytes
1012  * @param[in] cipherSuites List of cipher suites offered by the client
1013  * @param[in] extensions ClientHello extensions offered by the client
1014  * @return Error code
1015  **/
1016 
1018  size_t sessionIdLen, const TlsCipherSuites *cipherSuites,
1020 {
1021  error_t error;
1022 
1023 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2 && \
1024  TLS_TICKET_SUPPORT == ENABLED)
1025  //The client indicates that it supports the ticket mechanism by including
1026  //a SessionTicket extension in the ClientHello message
1027  if(context->sessionTicketExtReceived)
1028  {
1029  uint_t i;
1030  uint_t n;
1031  size_t length;
1032  systime_t serverTicketAge;
1033  TlsPlaintextSessionState *state;
1034 
1035  //Retrieve the length of the ticket
1036  length = ntohs(extensions->sessionTicket->length);
1037 
1038  //Check the length of the ticket
1039  if(length > 0 && length <= TLS_MAX_TICKET_SIZE)
1040  {
1041  //Allocate a buffer to store the decrypted state information
1042  state = tlsAllocMem(length);
1043 
1044  //Successful memory allocation?
1045  if(state != NULL)
1046  {
1047  //Make sure a valid callback has been registered
1048  if(context->ticketDecryptCallback != NULL)
1049  {
1050  //Decrypt the received ticket
1051  error = context->ticketDecryptCallback(context,
1052  extensions->sessionTicket->value, length, (uint8_t *) state,
1053  &length, context->ticketParam);
1054  }
1055  else
1056  {
1057  //Report an error
1058  error = ERROR_FAILURE;
1059  }
1060 
1061  //Valid ticket?
1062  if(!error)
1063  {
1064  //Check the length of the decrypted ticket
1065  if(length == sizeof(TlsPlaintextSessionState))
1066  {
1067  //The ticket mechanism applies to TLS 1.0, TLS 1.1 and TLS 1.2
1068  if(state->version != context->version)
1069  {
1070  //The ticket is not valid
1071  error = ERROR_INVALID_TICKET;
1072  }
1073 
1074  //Compute the time since the ticket was issued
1075  serverTicketAge = osGetSystemTime() - state->ticketTimestamp;
1076 
1077  //Verify ticket's validity
1078  if(serverTicketAge >= (state->ticketLifetime * 1000))
1079  {
1080  //The ticket is not valid
1081  error = ERROR_INVALID_TICKET;
1082  }
1083 
1084  //Get the total number of cipher suites offered by the client
1085  n = ntohs(cipherSuites->length) / 2;
1086 
1087  //Loop through the list of cipher suite identifiers
1088  for(i = 0; i < n; i++)
1089  {
1090  //Matching cipher suite?
1091  if(ntohs(cipherSuites->value[i]) == state->cipherSuite)
1092  {
1093  break;
1094  }
1095  }
1096 
1097  //If the cipher suite is not present in the list cipher suites
1098  //offered by the client, the server must not perform the
1099  //abbreviated handshake
1100  if(i >= n)
1101  {
1102  //The ticket is not valid
1103  error = ERROR_INVALID_TICKET;
1104  }
1105 
1106 #if (TLS_EXT_MASTER_SECRET_SUPPORT == ENABLED)
1107  //ExtendedMasterSecret extension found?
1108  if(extensions->extendedMasterSecret != NULL)
1109  {
1110  //If the original session did not use the ExtendedMasterSecret
1111  //extension but the new ClientHello contains the extension,
1112  //then the server must not perform the abbreviated handshake
1113  if(!state->extendedMasterSecret)
1114  {
1115  //The ticket is not valid
1116  error = ERROR_INVALID_TICKET;
1117  }
1118  }
1119 #endif
1120  }
1121  else
1122  {
1123  //The ticket is malformed
1124  error = ERROR_INVALID_TICKET;
1125  }
1126  }
1127 
1128  //Check status code
1129  if(!error)
1130  {
1131  //The ticket mechanism may be used with any TLS ciphersuite
1132  error = tlsSelectCipherSuite(context, state->cipherSuite);
1133  }
1134 
1135  //Check status code
1136  if(!error)
1137  {
1138  //Retrieve the type of the cipher suite presented by the client
1139  context->cipherSuiteTypes = tlsGetCipherSuiteType(
1140  state->cipherSuite);
1141 
1142  //Restore master secret
1143  osMemcpy(context->masterSecret, state->secret,
1145 
1146 #if (TLS_EXT_MASTER_SECRET_SUPPORT == ENABLED)
1147  //Extended master secret computation
1148  context->emsExtReceived = state->extendedMasterSecret;
1149 #endif
1150  }
1151 
1152  //Release state information
1153  osMemset(state, 0, length);
1154  tlsFreeMem(state);
1155  }
1156  else
1157  {
1158  //Failed to allocate memory
1159  error = ERROR_OUT_OF_MEMORY;
1160  }
1161  }
1162  else
1163  {
1164  //The extension will be empty if the client does not already possess
1165  //a ticket for the server (refer to RFC 5077, section 3.1)
1166  error = ERROR_INVALID_TICKET;
1167  }
1168 
1169  //Valid ticket?
1170  if(!error)
1171  {
1172  //Perform abbreviated handshake
1173  context->resume = TRUE;
1174 
1175  //If the server accepts the ticket and the session ID is not empty,
1176  //then it must respond with the same session ID present in the
1177  //ClientHello. This allows the client to easily differentiate when
1178  //the server is resuming a session from when it is falling back to
1179  //a full handshake (refer to RFC 5077, section 3.4)
1180  osMemcpy(context->sessionId, sessionId, sessionIdLen);
1181  context->sessionIdLen = sessionIdLen;
1182 
1183  //If the server successfully verifies the client's ticket, then it may
1184  //renew the ticket by including a NewSessionTicket handshake message
1185  //after the ServerHello
1186  context->sessionTicketExtSent = TRUE;
1187  }
1188  else
1189  {
1190  //If a server is planning on issuing a session ticket to a client that
1191  //does not present one, it should include an empty Session ID in the
1192  //ServerHello
1193  context->sessionIdLen = 0;
1194 
1195  //The server uses a zero-length SessionTicket extension to indicate to the
1196  //client that it will send a new session ticket using the NewSessionTicket
1197  //handshake message
1198  context->sessionTicketExtSent = TRUE;
1199  }
1200  }
1201  else
1202 #endif
1203  {
1204  //No valid ticket received
1205  error = ERROR_NO_TICKET;
1206  }
1207 
1208  //Return status code
1209  return error;
1210 }
1211 
1212 
1213 /**
1214  * @brief Version negotiation
1215  * @param[in] context Pointer to the TLS context
1216  * @param[in] clientVersion Highest version number supported by the client (legacy version)
1217  * @param[in] supportedVersionList Pointer to the SupportedVersions extensions
1218  * @return Error code
1219  **/
1220 
1221 error_t tlsNegotiateVersion(TlsContext *context, uint16_t clientVersion,
1222  const TlsSupportedVersionList *supportedVersionList)
1223 {
1224  error_t error;
1225  uint16_t serverVersion;
1226 
1227  //Get the highest version supported by the implementation
1228  serverVersion = context->versionMax;
1229 
1230 #if (DTLS_SUPPORT == ENABLED)
1231  //DTLS protocol?
1232  if(context->transportProtocol == TLS_TRANSPORT_PROTOCOL_DATAGRAM)
1233  {
1234  //In DTLS 1.2, the client can indicate its version preferences in the
1235  //SupportedVersions extension
1236  if(supportedVersionList != NULL && context->versionMax >= TLS_VERSION_1_2)
1237  {
1238  //If the SupportedVersions extension is present in the ClientHello,
1239  //servers must only select a version of DTLS present in that extension
1241  (DtlsSupportedVersionList *) supportedVersionList);
1242  }
1243  else
1244  {
1245  //If the SupportedVersions extension is not present, servers must
1246  //negotiate DTLS 1.2 or prior
1247  serverVersion = MIN(serverVersion, TLS_VERSION_1_2);
1248 
1249  //Translate TLS version into DTLS version
1250  serverVersion = dtlsTranslateVersion(serverVersion);
1251 
1252  //If a DTLS server receives a ClientHello containing a version number
1253  //greater than the highest version supported by the server, it must
1254  //reply according to the highest version supported by the server
1255  serverVersion = MAX(serverVersion, clientVersion);
1256 
1257  //Set the DTLS version to be used
1258  error = dtlsSelectVersion(context, serverVersion);
1259  }
1260  }
1261  else
1262 #endif
1263  //TLS protocol?
1264  {
1265  //In TLS 1.2, the client can indicate its version preferences in the
1266  //SupportedVersions extension
1267  if(supportedVersionList != NULL && context->versionMax >= TLS_VERSION_1_2)
1268  {
1269  //If the SupportedVersions extension is present in the ClientHello,
1270  //servers must only select a version of TLS present in that extension
1272  supportedVersionList);
1273 
1274  //Check status code
1275  if(!error)
1276  {
1277  //Check whether TLS 1.3 has been negotiated
1278  if(context->version == TLS_VERSION_1_3)
1279  {
1280  //The legacy_version field must be set to 0x0303, which is the
1281  //version number for TLS 1.2
1282  if(clientVersion < TLS_VERSION_1_2)
1283  {
1285  }
1286  }
1287  }
1288  }
1289  else
1290  {
1291  //If the SupportedVersions extension is not present, servers must
1292  //negotiate TLS 1.2 or prior, even if the legacy_version of the
1293  //ClientHello is 0x0304 or later (refer to RFC 8446, section 4.2.1)
1294  serverVersion = MIN(serverVersion, TLS_VERSION_1_2);
1295 
1296  //If a TLS server receives a ClientHello containing a version number
1297  //greater than the highest version supported by the server, it must
1298  //reply according to the highest version supported by the server
1299  serverVersion = MIN(serverVersion, clientVersion);
1300 
1301  //Set the TLS version to be used
1302  error = tlsSelectVersion(context, serverVersion);
1303  }
1304  }
1305 
1306  //Return status code
1307  return error;
1308 }
1309 
1310 
1311 /**
1312  * @brief Cipher suite negotiation
1313  * @param[in] context Pointer to the TLS context
1314  * @param[in] hashAlgo Desired KDF hash algorithm
1315  * @param[in] cipherSuites List of cipher suites offered by the client
1316  * @param[in] extensions ClientHello extensions offered by the client
1317  * @return Error code
1318  **/
1319 
1321  const TlsCipherSuites *cipherSuites, TlsHelloExtensions *extensions)
1322 {
1323  error_t error;
1324  uint_t i;
1325  uint_t j;
1326  uint_t k;
1327  uint_t n;
1328 
1329  //Initialize status code
1330  error = ERROR_HANDSHAKE_FAILED;
1331 
1332  //If no SignatureAlgorithmsCert extension is present in the ClientHello
1333  //message, then the SignatureAlgorithms extension also applies to signatures
1334  //appearing in certificates (RFC 8446, section 4.2.3)
1335  if(extensions->certSignAlgoList == NULL)
1336  {
1337  extensions->certSignAlgoList = extensions->signAlgoList;
1338  }
1339 
1340  //Get the total number of cipher suites offered by the client
1341  n = ntohs(cipherSuites->length) / 2;
1342 
1343  //Select the most appropriate cipher suite (2-pass process)
1344  for(k = 0; k < 2 && error; k++)
1345  {
1346  //Any preferred cipher suites?
1347  if(context->numCipherSuites > 0)
1348  {
1349  //Loop through the list of allowed cipher suites (most preferred first)
1350  for(i = 0; i < context->numCipherSuites && error; i++)
1351  {
1352  //Loop through the list of cipher suites offered by the client
1353  for(j = 0; j < n && error; j++)
1354  {
1355  //If the list contains cipher suites the server does not
1356  //recognize, support, or wish to use, the server must ignore
1357  //those cipher suites, and process the remaining ones as usual
1358  if(context->cipherSuites[i] == ntohs(cipherSuites->value[j]))
1359  {
1360  //Select current cipher suite
1361  error = tlsSelectCipherSuite(context, context->cipherSuites[i]);
1362 
1363  //If a KDF hash algorithm has been specified, the server must
1364  //select a compatible cipher suite
1365  if(!error && hashAlgo != NULL)
1366  {
1367  //Make sure the selected cipher suite is compatible
1368  if(context->cipherSuite.prfHashAlgo != hashAlgo)
1369  {
1370  error = ERROR_HANDSHAKE_FAILED;
1371  }
1372  }
1373 
1374  //Check status code
1375  if(!error)
1376  {
1377  //Retrieve the type of the cipher suite presented by the
1378  //client
1379  context->cipherSuiteTypes = tlsGetCipherSuiteType(
1380  context->cipherSuite.identifier);
1381 
1382  //Select the group to be used when performing (EC)DHE key
1383  //exchange
1384  error = tlsSelectGroup(context, extensions->supportedGroupList);
1385  }
1386 
1387  //Check status code
1388  if(!error)
1389  {
1390  //Select the appropriate certificate
1391  error = tlsSelectCertificate(context, extensions);
1392  }
1393  }
1394  }
1395  }
1396  }
1397  else
1398  {
1399  //The cipher suite list contains the combinations of cryptographic
1400  //algorithms supported by the client in order of the client's preference
1401  for(j = 0; j < n && error; j++)
1402  {
1403  //If the list contains cipher suites the server does not recognize,
1404  //support, or wish to use, the server must ignore those cipher suites,
1405  //and process the remaining ones as usual
1406  error = tlsSelectCipherSuite(context, ntohs(cipherSuites->value[j]));
1407 
1408  //If a KDF hash algorithm has been specified, the server must select
1409  //a compatible cipher suite
1410  if(!error && hashAlgo != NULL)
1411  {
1412  //Make sure the selected cipher suite is compatible
1413  if(context->cipherSuite.prfHashAlgo != hashAlgo)
1414  {
1415  error = ERROR_HANDSHAKE_FAILED;
1416  }
1417  }
1418 
1419  //Check status code
1420  if(!error)
1421  {
1422  //Retrieve the type of the cipher suite presented by the client
1423  context->cipherSuiteTypes = tlsGetCipherSuiteType(
1424  context->cipherSuite.identifier);
1425 
1426  //Select the group to be used when performing (EC)DHE key exchange
1427  error = tlsSelectGroup(context, extensions->supportedGroupList);
1428  }
1429 
1430  //Check status code
1431  if(!error)
1432  {
1433  //Select the appropriate certificate
1434  error = tlsSelectCertificate(context, extensions);
1435  }
1436  }
1437  }
1438 
1439  //The second pass relaxes the constraints
1440  extensions->certSignAlgoList = NULL;
1441  }
1442 
1443  //Return status code
1444  return error;
1445 }
1446 
1447 
1448 /**
1449  * @brief Select the group to be used when performing (EC)DHE key exchange
1450  * @param[in] context Pointer to the TLS context
1451  * @param[in] groupList List of named groups supported by the client
1452  * @return Error code
1453  **/
1454 
1456  const TlsSupportedGroupList *groupList)
1457 {
1458  error_t error;
1459 
1460  //Initialize status code
1461  error = NO_ERROR;
1462 
1463 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1464  //TLS 1.0, TLS 1.1 or TLS 1.2 currently selected?
1465  if(context->version <= TLS_VERSION_1_2)
1466  {
1467  //ECC cipher suite?
1468  if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
1469  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
1470  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
1471  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
1472  {
1473  //One of the proposed ECC cipher suites must be negotiated only if the
1474  //server can successfully complete the handshake while using the curves
1475  //and point formats supported by the client
1476  error = tlsSelectEcdheGroup(context, groupList);
1477  }
1478 #if (TLS_FFDHE_SUPPORT == ENABLED)
1479  //FFDHE cipher suite?
1480  else if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
1481  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
1482  context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
1483  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK)
1484  {
1485  //If none of the client-proposed FFDHE groups are known and acceptable
1486  //to the server, then the server must not select an FFDHE cipher suite
1487  error = tlsSelectFfdheGroup(context, groupList);
1488  }
1489 #endif
1490  else
1491  {
1492  //The selected cipher suite does not provide forward secrecy
1493  }
1494  }
1495 #endif
1496 
1497  //Return status code
1498  return error;
1499 }
1500 
1501 
1502 /**
1503  * @brief Select the named curve to be used when performing ECDHE key exchange
1504  * @param[in] context Pointer to the TLS context
1505  * @param[in] groupList List of named groups supported by the peer
1506  * @return Error code
1507  **/
1508 
1510  const TlsSupportedGroupList *groupList)
1511 {
1512  error_t error;
1513  uint_t i;
1514  uint_t j;
1515  uint_t n;
1516  uint16_t namedGroup;
1517 
1518  //Initialize status code
1519  error = ERROR_HANDSHAKE_FAILED;
1520 
1521  //Reset the named group to its default value
1522  context->namedGroup = TLS_GROUP_NONE;
1523 
1524  //Check whether a list of named groups is offered by the client
1525  if(groupList != NULL)
1526  {
1527  //Get the number of named groups present in the list
1528  n = ntohs(groupList->length) / sizeof(uint16_t);
1529 
1530  //Any preferred groups?
1531  if(context->numSupportedGroups > 0)
1532  {
1533  //Loop through the list of allowed groups (most preferred first)
1534  for(i = 0; i < context->numSupportedGroups && error; i++)
1535  {
1536  //Loop through the list of named groups the client supports
1537  for(j = 0; j < n && error; j++)
1538  {
1539  //Convert the named group to host byte order
1540  namedGroup = ntohs(groupList->value[j]);
1541 
1542  //The named group to be used when performing ECDH key exchange
1543  //must be one of those present in the SupportedGroups extension
1544  if(context->supportedGroups[i] == namedGroup)
1545  {
1546  //Acceptable elliptic curve found?
1547  if(tlsGetCurveInfo(context, namedGroup) != NULL &&
1548  namedGroup != TLS_GROUP_BRAINPOOLP256R1_TLS13 &&
1549  namedGroup != TLS_GROUP_BRAINPOOLP384R1_TLS13 &&
1550  namedGroup != TLS_GROUP_BRAINPOOLP512R1_TLS13 &&
1551  namedGroup != TLS_GROUP_CURVE_SM2)
1552  {
1553  //Save the named curve
1554  context->namedGroup = namedGroup;
1555  error = NO_ERROR;
1556  }
1557  }
1558  }
1559  }
1560  }
1561  else
1562  {
1563  //The named group to be used when performing ECDH key exchange must
1564  //be one of those present in the SupportedGroups extension
1565  for(j = 0; j < n && error; j++)
1566  {
1567  //Convert the named group to host byte order
1568  namedGroup = ntohs(groupList->value[j]);
1569 
1570  //Acceptable elliptic curve found?
1571  if(tlsGetCurveInfo(context, namedGroup) != NULL &&
1572  namedGroup != TLS_GROUP_BRAINPOOLP256R1_TLS13 &&
1573  namedGroup != TLS_GROUP_BRAINPOOLP384R1_TLS13 &&
1574  namedGroup != TLS_GROUP_BRAINPOOLP512R1_TLS13 &&
1575  namedGroup != TLS_GROUP_CURVE_SM2)
1576  {
1577  //Save the named curve
1578  context->namedGroup = namedGroup;
1579  error = NO_ERROR;
1580  }
1581  }
1582  }
1583  }
1584  else
1585  {
1586  //A client that proposes ECC cipher suites may choose not to include
1587  //the SupportedGroups extension. In this case, the server is free to
1588  //choose any one of the elliptic curves it supports
1589  if(tlsGetCurveInfo(context, TLS_GROUP_SECP256R1) != NULL)
1590  {
1591  //Select secp256r1 elliptic curve
1592  context->namedGroup = TLS_GROUP_SECP256R1;
1593  error = NO_ERROR;
1594  }
1595  else if(tlsGetCurveInfo(context, TLS_GROUP_SECP384R1) != NULL)
1596  {
1597  //Select secp384r1 elliptic curve
1598  context->namedGroup = TLS_GROUP_SECP384R1;
1599  error = NO_ERROR;
1600  }
1601  else
1602  {
1603  //Just for sanity
1604  context->namedGroup = TLS_GROUP_NONE;
1605  }
1606  }
1607 
1608  //Return status code
1609  return error;
1610 }
1611 
1612 
1613 /**
1614  * @brief Certificate selection process
1615  * @param[in] context Pointer to the TLS context
1616  * @param[in] extensions ClientHello extensions offered by the client
1617  * @return Error code
1618  **/
1619 
1622 {
1623  error_t error;
1624  uint_t i;
1625  uint_t j;
1626  uint_t n;
1627  bool_t acceptable;
1628  uint8_t certTypes[2];
1629  const TlsCertAuthorities *certAuthorities;
1630  const TlsSignSchemeList *certSignAlgoList;
1631 
1632  //Initialize status code
1633  error = NO_ERROR;
1634 
1635  //Number of certificate types
1636  n = 0;
1637 
1638 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1639  //TLS 1.0, TLS 1.1 or TLS 1.2 currently selected?
1640  if(context->version <= TLS_VERSION_1_2)
1641  {
1642  //The server requires a valid certificate whenever the agreed-upon key
1643  //exchange method uses certificates for authentication
1644  if(context->keyExchMethod == TLS_KEY_EXCH_RSA ||
1645  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
1646  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
1647  context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
1648  {
1649  //RSA, DHE_RSA, ECDHE_RSA and RSA_PSK key exchange methods require
1650  //an RSA certificate
1651  certTypes[n++] = TLS_CERT_RSA_SIGN;
1652  }
1653  else if(context->keyExchMethod == TLS_KEY_EXCH_DH_RSA)
1654  {
1655  //In DH_RSA, the server's certificate must contain a Diffie-Hellman
1656  //public key and be signed with RSA
1657  certTypes[n++] = TLS_CERT_RSA_FIXED_DH;
1658  }
1659  else if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_RSA)
1660  {
1661  //In ECDH_RSA, the server's certificate must contain an ECDH-capable
1662  //public key and be signed with RSA
1663  certTypes[n++] = TLS_CERT_RSA_FIXED_ECDH;
1664  }
1665  else if(context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS)
1666  {
1667  //DHE_DSS key exchange method requires a DSA certificate
1668  certTypes[n++] = TLS_CERT_DSS_SIGN;
1669  }
1670  else if(context->keyExchMethod == TLS_KEY_EXCH_DH_DSS)
1671  {
1672  //In DH_DSS, the server's certificate must contain a Diffie-Hellman
1673  //public key and be signed with DSA
1674  certTypes[n++] = TLS_CERT_DSS_FIXED_DH;
1675  }
1676  else if(context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA)
1677  {
1678  //ECDHE_ECDSA key exchange method requires an ECDSA certificate
1679  certTypes[n++] = TLS_CERT_ECDSA_SIGN;
1680  }
1681  else if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_ECDSA)
1682  {
1683  //In ECDH_ECDSA, the server's certificate must contain an ECDH-capable
1684  //public key and be signed with ECDSA
1685  certTypes[n++] = TLS_CERT_ECDSA_FIXED_ECDH;
1686  }
1687  else
1688  {
1689  //DH_anon and ECDH_anon key exchange methods do not require any
1690  //certificate
1691  }
1692 
1693  //The CertificateAuthorities extension is not supported
1694  certAuthorities = NULL;
1695  }
1696  else
1697 #endif
1698 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
1699  //TLS 1.3 currently selected?
1700  if(context->version == TLS_VERSION_1_3)
1701  {
1702  //If PSK is not being used, then (EC)DHE and certificate-based
1703  //authentication are always used
1704  if(context->selectedIdentity < 0)
1705  {
1706  //TLS 1.3 removes support for DSA certificates
1707  certTypes[n++] = TLS_CERT_RSA_SIGN;
1708  certTypes[n++] = TLS_CERT_ECDSA_SIGN;
1709  }
1710 
1711  //The CertificateAuthorities extension is used to indicate the CAs which
1712  //an endpoint supports and which should be used by the receiving endpoint
1713  //to guide certificate selection
1714  certAuthorities = extensions->certAuthorities;
1715  }
1716  else
1717 #endif
1718  //Invalid TLS version?
1719  {
1720  //Abort certificate selection process
1721  error = ERROR_INVALID_VERSION;
1722  }
1723 
1724  //If no SignatureAlgorithmsCert extension is present, then the
1725  //SignatureAlgorithms extension also applies to signatures appearing
1726  //in certificates (RFC 8446, section 4.2.3)
1727  if(extensions->certSignAlgoList != NULL)
1728  {
1729  certSignAlgoList = extensions->certSignAlgoList;
1730  }
1731  else
1732  {
1733  certSignAlgoList = extensions->signAlgoList;
1734  }
1735 
1736  //Check whether a certificate is required
1737  if(n > 0)
1738  {
1739  //Reset currently selected certificate
1740  context->cert = NULL;
1741 
1742  //Select the most appropriate certificate (2-pass process)
1743  for(i = 0; i < 2 && context->cert == NULL; i++)
1744  {
1745  //Loop through the list of available certificates
1746  for(j = 0; j < TLS_MAX_CERTIFICATES && context->cert == NULL; j++)
1747  {
1748  //Check whether the current certificate is suitable
1749  acceptable = tlsIsCertificateAcceptable(context, &context->certs[j],
1750  certTypes, n, extensions->supportedGroupList, certSignAlgoList,
1751  certAuthorities);
1752 
1753  //The certificate must be appropriate for the negotiated cipher
1754  //suite and any negotiated extensions
1755  if(acceptable)
1756  {
1757  //The hash algorithm to be used when generating signatures must
1758  //be one of those present in the SignatureAlgorithms extension
1759  error = tlsSelectSignAlgo(context, &context->certs[j],
1760  extensions->signAlgoList);
1761 
1762  //Check status code
1763  if(!error)
1764  {
1765  //If all the requirements were met, the certificate can be
1766  //used in conjunction with the selected cipher suite
1767  context->cert = &context->certs[j];
1768  }
1769  }
1770  }
1771 
1772  //The second pass relaxes the constraints
1773  certSignAlgoList = NULL;
1774  certAuthorities = NULL;
1775  }
1776 
1777  //Do not accept the specified cipher suite unless a suitable certificate
1778  //has been found
1779  if(context->cert == NULL)
1780  {
1781  error = ERROR_NO_CERTIFICATE;
1782  }
1783  }
1784 
1785  //Return status code
1786  return error;
1787 }
1788 
1789 
1790 /**
1791  * @brief Parse the list of compression methods supported by the client
1792  * @param[in] context Pointer to the TLS context
1793  * @param[in] compressMethods List of compression methods
1794  * @return Error code
1795  **/
1796 
1798  const TlsCompressMethods *compressMethods)
1799 {
1800  error_t error;
1801  uint_t i;
1802 
1803  //Initialize status code
1804  error = ERROR_ILLEGAL_PARAMETER;
1805 
1806  //Version of TLS prior to TLS 1.3?
1807  if(context->version <= TLS_VERSION_1_2)
1808  {
1809  //The list of the compression methods supported by the client is sorted
1810  //by client preference
1811  for(i = 0; i < compressMethods->length && error; i++)
1812  {
1813  //The CRIME exploit takes advantage of TLS compression, so conservative
1814  //implementations do not accept compression at the TLS level
1815  if(compressMethods->value[i] == TLS_COMPRESSION_METHOD_NULL)
1816  {
1817  error = NO_ERROR;
1818  }
1819  }
1820  }
1821  else
1822  {
1823  //For every TLS 1.3 ClientHello, this vector must contain exactly one
1824  //byte, set to zero which corresponds to the null compression method
1825  if(compressMethods->length == 1)
1826  {
1827  //If a ClientHello is received with any other value in this field,
1828  //the server must abort the handshake with an illegal_parameter alert
1829  if(compressMethods->value[0] == TLS_COMPRESSION_METHOD_NULL)
1830  {
1831  error = NO_ERROR;
1832  }
1833  }
1834  }
1835 
1836  //Return status code
1837  return error;
1838 }
1839 
1840 
1841 /**
1842  * @brief Parse PSK identity
1843  * @param[in] context Pointer to the TLS context
1844  * @param[in] p Input stream where to read the PSK identity hint
1845  * @param[in] length Number of bytes available in the input stream
1846  * @param[out] consumed Total number of bytes that have been consumed
1847  * @return Error code
1848  **/
1849 
1851  const uint8_t *p, size_t length, size_t *consumed)
1852 {
1853  size_t n;
1854  TlsPskIdentity *pskIdentity;
1855 
1856  //Point to the PSK identity
1857  pskIdentity = (TlsPskIdentity *) p;
1858 
1859  //Malformed ClientKeyExchange message?
1860  if(length < sizeof(TlsPskIdentity))
1861  return ERROR_DECODING_FAILED;
1862  if(length < (sizeof(TlsPskIdentity) + ntohs(pskIdentity->length)))
1863  return ERROR_DECODING_FAILED;
1864 
1865  //Retrieve the length of the PSK identity
1866  n = ntohs(pskIdentity->length);
1867 
1868 #if (TLS_PSK_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED || \
1869  TLS_DHE_PSK_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
1870  //Any registered callback?
1871  if(context->pskCallback != NULL)
1872  {
1873  error_t error;
1874 
1875  //The server selects which key to use depending on the PSK identity
1876  //provided by the client
1877  error = context->pskCallback(context, pskIdentity->value, n);
1878  //Any error to report?
1879  if(error)
1880  return ERROR_UNKNOWN_IDENTITY;
1881  }
1882 #endif
1883 
1884  //Total number of bytes that have been consumed
1885  *consumed = sizeof(TlsPskIdentity) + n;
1886 
1887  //Successful processing
1888  return NO_ERROR;
1889 }
1890 
1891 
1892 /**
1893  * @brief Parse client's key exchange parameters
1894  * @param[in] context Pointer to the TLS context
1895  * @param[in] p Input stream where to read the client's key exchange parameters
1896  * @param[in] length Number of bytes available in the input stream
1897  * @param[out] consumed Total number of bytes that have been consumed
1898  * @return Error code
1899  **/
1900 
1902  const uint8_t *p, size_t length, size_t *consumed)
1903 {
1904  error_t error;
1905 
1906 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
1907  //Initialize status code
1908  error = NO_ERROR;
1909 
1910 #if (TLS_RSA_KE_SUPPORT == ENABLED || TLS_RSA_PSK_KE_SUPPORT == ENABLED)
1911  //RSA key exchange method?
1912  if(context->keyExchMethod == TLS_KEY_EXCH_RSA ||
1913  context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
1914  {
1915  size_t n;
1916  uint32_t bad;
1917  uint16_t version;
1918  RsaPrivateKey privateKey;
1919  uint8_t randPremasterSecret[48];
1920 
1921  //Malformed ClientKeyExchange message?
1922  if(length < 2)
1923  return ERROR_DECODING_FAILED;
1924 
1925  //The RSA-encrypted premaster secret in a ClientKeyExchange is preceded by
1926  //two length bytes
1927  n = LOAD16BE(p);
1928 
1929  //Check the length of the RSA-encrypted premaster secret
1930  if(n > (length - 2))
1931  return ERROR_DECODING_FAILED;
1932 
1933  //Save the length of the RSA-encrypted premaster secret
1934  length = n;
1935  //Advance the pointer over the length field
1936  p += 2;
1937  //Total number of bytes that have been consumed
1938  *consumed = length + 2;
1939 
1940  //Initialize RSA private key
1941  rsaInitPrivateKey(&privateKey);
1942 
1943  //Decode the PEM structure that holds the RSA private key
1944  error = pemImportRsaPrivateKey(context->cert->privateKey,
1945  context->cert->privateKeyLen, context->cert->password, &privateKey);
1946 
1947  //Check status code
1948  if(!error)
1949  {
1950  //Decrypt the premaster secret using the server private key
1951  error = rsaesPkcs1v15Decrypt(&privateKey, p, length,
1952  context->premasterSecret, TLS_PREMASTER_SECRET_SIZE,
1953  &context->premasterSecretLen);
1954  }
1955 
1956  //Release RSA private key
1957  rsaFreePrivateKey(&privateKey);
1958 
1959  //Retrieve the latest version supported by the client. This is used
1960  //to detect version roll-back attacks
1961  version = LOAD16BE(context->premasterSecret);
1962 
1963  //The best way to avoid vulnerability to the Bleichenbacher attack is to
1964  //treat incorrectly formatted messages in a manner indistinguishable from
1965  //correctly formatted RSA blocks
1966  bad = CRYPTO_TEST_NZ_32(error);
1967  bad |= CRYPTO_TEST_NEQ_32(context->premasterSecretLen, 48);
1968  bad |= CRYPTO_TEST_NEQ_16(version, context->clientVersion);
1969 
1970  //Generate a random 48-byte value
1971  error = context->prngAlgo->read(context->prngContext,
1972  randPremasterSecret, 48);
1973 
1974  //When it receives an incorrectly formatted RSA block, the server should
1975  //proceed using the random 48-byte value as the premaster secret
1976  for(n = 0; n < 48; n++)
1977  {
1978  context->premasterSecret[n] = CRYPTO_SELECT_8(
1979  context->premasterSecret[n], randPremasterSecret[n], bad);
1980  }
1981 
1982  //Fix the length of the premaster secret
1983  context->premasterSecretLen = 48;
1984  }
1985  else
1986 #endif
1987 #if (TLS_DH_ANON_KE_SUPPORT == ENABLED || TLS_DHE_RSA_KE_SUPPORT == ENABLED || \
1988  TLS_DHE_DSS_KE_SUPPORT == ENABLED || TLS_DHE_PSK_KE_SUPPORT == ENABLED)
1989  //Diffie-Hellman key exchange method?
1990  if(context->keyExchMethod == TLS_KEY_EXCH_DH_ANON ||
1991  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
1992  context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
1993  context->keyExchMethod == TLS_KEY_EXCH_DHE_PSK)
1994  {
1995  size_t n;
1996 
1997  //Convert the client's public value to a multiple precision integer
1998  error = tlsReadMpi(&context->dhContext.yb, p, length, &n);
1999 
2000  //Check status code
2001  if(!error)
2002  {
2003  //Total number of bytes that have been consumed
2004  *consumed = n;
2005 
2006  //Verify client's public value
2007  error = dhCheckPublicKey(&context->dhContext.params,
2008  &context->dhContext.yb);
2009  }
2010 
2011  //Check status code
2012  if(!error)
2013  {
2014  //Calculate the negotiated key Z
2015  error = dhComputeSharedSecret(&context->dhContext,
2016  context->premasterSecret, TLS_PREMASTER_SECRET_SIZE,
2017  &context->premasterSecretLen);
2018  }
2019 
2020  //Check status code
2021  if(!error)
2022  {
2023  //Leading bytes of Z that contain all zero bits are stripped before
2024  //it is used as the premaster secret (RFC 4346, section 8.2.1)
2025  for(n = 0; n < context->premasterSecretLen; n++)
2026  {
2027  if(context->premasterSecret[n] != 0x00)
2028  break;
2029  }
2030 
2031  //Any leading zero bytes?
2032  if(n > 0)
2033  {
2034  //Strip leading zero bytes from the negotiated key
2035  osMemmove(context->premasterSecret, context->premasterSecret + n,
2036  context->premasterSecretLen - n);
2037 
2038  //Adjust the length of the premaster secret
2039  context->premasterSecretLen -= n;
2040  }
2041  }
2042  }
2043  else
2044 #endif
2045 #if (TLS_ECDH_ANON_KE_SUPPORT == ENABLED || TLS_ECDHE_RSA_KE_SUPPORT == ENABLED || \
2046  TLS_ECDHE_ECDSA_KE_SUPPORT == ENABLED || TLS_ECDHE_PSK_KE_SUPPORT == ENABLED)
2047  //ECDH key exchange method?
2048  if(context->keyExchMethod == TLS_KEY_EXCH_ECDH_ANON ||
2049  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
2050  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
2051  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_PSK)
2052  {
2053  size_t n;
2054 
2055  //Decode client's public key
2056  error = tlsReadEcPoint(&context->ecdhContext.params,
2057  &context->ecdhContext.qb.q, p, length, &n);
2058 
2059  //Check status code
2060  if(!error)
2061  {
2062  //Total number of bytes that have been consumed
2063  *consumed = n;
2064 
2065  //Verify client's public key and make sure that it is on the same
2066  //elliptic curve as the server's ECDH key
2067  error = ecdhCheckPublicKey(&context->ecdhContext.params,
2068  &context->ecdhContext.qb.q);
2069  }
2070 
2071  //Check status code
2072  if(!error)
2073  {
2074 #if (TLS_ECC_CALLBACK_SUPPORT == ENABLED)
2075  //Any registered callback?
2076  if(context->ecdhCallback != NULL)
2077  {
2078  //Invoke user callback function
2079  error = context->ecdhCallback(context);
2080  }
2081  else
2082 #endif
2083  {
2084  //No callback function defined
2086  }
2087 
2088  //Check status code
2090  {
2091  //Calculate the shared secret Z. Leading zeros found in this octet
2092  //string must not be truncated (see RFC 4492, section 5.10)
2093  error = ecdhComputeSharedSecret(&context->ecdhContext,
2094  context->premasterSecret, TLS_PREMASTER_SECRET_SIZE,
2095  &context->premasterSecretLen);
2096  }
2097  }
2098  }
2099  else
2100 #endif
2101  //Invalid key exchange method?
2102  {
2103  //The specified key exchange method is not supported
2105  }
2106 #else
2107  //Not implemented
2108  error = ERROR_NOT_IMPLEMENTED;
2109 #endif
2110 
2111  //Return status code
2112  return error;
2113 }
2114 
2115 #endif
@ TLS_CERT_ECDSA_FIXED_ECDH
Definition: tls.h:1197
@ TLS_GROUP_BRAINPOOLP512R1_TLS13
Definition: tls.h:1403
#define tlsAllocMem(size)
Definition: tls.h:853
#define htons(value)
Definition: cpu_endian.h:413
Parsing and checking of TLS extensions.
@ TLS_SIGN_ALGO_DSA
Definition: tls.h:1233
TLS helper functions.
@ ERROR_UNKNOWN_IDENTITY
Definition: error.h:260
HashAlgoInit init
Definition: crypto.h:1056
@ ERROR_UNSUPPORTED_ELLIPTIC_CURVE
Definition: error.h:133
uint8_t extensions[]
Definition: ntp_common.h:207
@ TLS_GROUP_BRAINPOOLP256R1_TLS13
Definition: tls.h:1401
Generic hash algorithm context.
error_t tlsParsePskIdentity(TlsContext *context, const uint8_t *p, size_t length, size_t *consumed)
Parse PSK identity.
int bool_t
Definition: compiler_port.h:53
uint8_t sessionId[]
Definition: tls.h:1773
TLS cipher suites.
error_t tlsParseClientSupportedVersionsExtension(TlsContext *context, const TlsSupportedVersionList *supportedVersionList)
Parse SupportedVersions extension.
error_t tlsParseClientKeyParams(TlsContext *context, const uint8_t *p, size_t length, size_t *consumed)
Parse client's key exchange parameters.
error_t dtlsSelectVersion(TlsContext *context, uint16_t version)
Set the DTLS version to be used.
Definition: dtls_misc.c:53
const HashAlgo * tlsGetHashAlgo(TlsHashAlgo hashAlgoId)
Get the hash algorithm that matches the specified identifier.
Definition: tls_misc.c:1173
error_t tlsFormatPskIdentityHint(TlsContext *context, uint8_t *p, size_t *written)
Format PSK identity hint.
TlsDigitalSignature
Definition: tls.h:1717
@ TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA256
Definition: tls.h:1253
error_t tlsGenerateSessionId(TlsContext *context, size_t length)
Generate a random session identifier.
Definition: tls_misc.c:268
void sha1Update(Sha1Context *context, const void *data, size_t length)
Update the SHA-1 context with a portion of the message being hashed.
error_t tls12GenerateServerKeySignature(TlsContext *context, Tls12DigitalSignature *signature, const uint8_t *params, size_t paramsLen, size_t *written)
Sign server's key exchange parameters (TLS 1.2)
@ TLS_COMPRESSION_METHOD_NULL
Definition: tls.h:1128
@ ERROR_VERSION_NOT_SUPPORTED
Definition: error.h:67
@ ERROR_NOT_IMPLEMENTED
Definition: error.h:66
@ ERROR_ILLEGAL_PARAMETER
Definition: error.h:243
error_t tlsNegotiateVersion(TlsContext *context, uint16_t clientVersion, const TlsSupportedVersionList *supportedVersionList)
Version negotiation.
uint8_t p
Definition: ndp.h:300
error_t tlsGenerateEd25519Signature(TlsContext *context, const DataChunk *messageChunks, uint8_t *signature, size_t *signatureLen)
Generate Ed25519 signature.
error_t tlsSelectVersion(TlsContext *context, uint16_t version)
Set the TLS version to be used.
Definition: tls_misc.c:305
error_t dhCheckPublicKey(DhParameters *params, const Mpi *publicKey)
Check Diffie-Hellman public value.
Definition: dh.c:183
#define TRUE
Definition: os_port.h:50
bool_t tlsIsCertificateAcceptable(TlsContext *context, const TlsCertDesc *cert, const uint8_t *certTypes, size_t numCertTypes, const TlsSupportedGroupList *curveList, const TlsSignSchemeList *certSignAlgoList, const TlsCertAuthorities *certAuthorities)
Check whether a certificate is acceptable.
@ TLS_GROUP_SECP256R1
Definition: tls.h:1393
@ TLS_GROUP_CURVE_SM2
Definition: tls.h:1411
size_t digestSize
Definition: crypto.h:1052
const void * buffer
Definition: crypto.h:982
@ TLS_TRANSPORT_PROTOCOL_DATAGRAM
Definition: tls.h:957
HashAlgoUpdate update
Definition: crypto.h:1057
void md5Final(Md5Context *context, uint8_t *digest)
Finish the MD5 message digest.
Session cache management.
TlsPskIdentity
Definition: tls.h:1695
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512
Definition: tls.h:1258
error_t tlsSelectEcdheGroup(TlsContext *context, const TlsSupportedGroupList *groupList)
Select the named curve to be used when performing ECDHE key exchange.
#define CRYPTO_TEST_NEQ_16(a, b)
Definition: crypto.h:873
@ TLS_KEY_EXCH_DH_DSS
Definition: tls.h:1143
error_t tlsWriteMpi(const Mpi *a, uint8_t *data, size_t *length)
Encode a multiple precision integer to an opaque vector.
Definition: tls_misc.c:958
@ ERROR_HANDSHAKE_FAILED
Definition: error.h:233
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
error_t pemImportRsaPrivateKey(const char_t *input, size_t length, const char_t *password, RsaPrivateKey *privateKey)
Decode a PEM file containing an RSA private key.
Definition: pem_import.c:389
FFDHE parameters.
Definition: tls_ffdhe.h:49
@ TLS_CERT_DSS_SIGN
Definition: tls.h:1189
@ TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA512
Definition: tls.h:1255
#define osStrcmp(s1, s2)
Definition: os_port.h:171
@ TLS_SIGN_SCHEME_ED25519
Definition: tls.h:1267
#define osStrlen(s)
Definition: os_port.h:165
uint8_t version
Definition: coap_common.h:177
@ TLS_KEY_EXCH_ECDH_RSA
Definition: tls.h:1146
error_t tlsGenerateRsaPkcs1Signature(TlsContext *context, const HashAlgo *hashAlgo, const uint8_t *digest, uint8_t *signature, size_t *signatureLen)
Generate RSA signature (TLS 1.2)
@ ERROR_INVALID_VERSION
Definition: error.h:118
error_t rsaesPkcs1v15Decrypt(const RsaPrivateKey *key, const uint8_t *ciphertext, size_t ciphertextLen, uint8_t *message, size_t messageSize, size_t *messageLen)
RSAES-PKCS1-v1_5 decryption operation.
Definition: rsa.c:277
#define TLS_RANDOM_SIZE
Definition: tls.h:938
#define TLS_HASH_ALGO(signScheme)
Definition: tls_sign_misc.h:41
error_t dtlsParseClientSupportedVersionsExtension(TlsContext *context, const DtlsSupportedVersionList *supportedVersionList)
Parse SupportedVersions extension.
Definition: dtls_misc.c:401
void rsaInitPrivateKey(RsaPrivateKey *key)
Initialize an RSA private key.
Definition: rsa.c:131
TlsPskIdentityHint
Definition: tls.h:1706
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384
Definition: tls.h:1257
@ TLS_SIGN_SCHEME_RSA_PSS_RSAE_SHA384
Definition: tls.h:1254
size_t contextSize
Definition: crypto.h:1050
TlsSessionState * tlsFindCache(TlsCache *cache, const uint8_t *sessionId, size_t sessionIdLen)
Search the session cache for a given session ID.
Definition: tls_cache.c:97
error_t tlsFormatServerKeyParams(TlsContext *context, uint8_t *p, size_t *written)
Format server's key exchange parameters.
uint8_t sessionIdLen
Definition: tls.h:1772
error_t tlsGenerateEcdsaSignature(TlsContext *context, const uint8_t *digest, size_t digestLen, uint8_t *signature, size_t *signatureLen)
Generate ECDSA signature.
@ TLS_KEY_EXCH_RSA
Definition: tls.h:1140
void md5Init(Md5Context *context)
Initialize MD5 message digest context.
TlsCipherSuites
Definition: tls.h:1517
@ TLS_HASH_ALGO_SHA512
Definition: tls.h:1219
uint16_t cipherSuite
Cipher suite identifier.
Definition: tls.h:2040
@ TLS_KEY_EXCH_ECDHE_ECDSA
Definition: tls.h:1149
error_t ecLoadDomainParameters(EcDomainParameters *params, const EcCurveInfo *curveInfo)
Load EC domain parameters.
Definition: ec.c:90
@ ERROR_NO_TICKET
Definition: error.h:229
@ TLS_KEY_EXCH_ECDHE_RSA
Definition: tls.h:1147
#define FALSE
Definition: os_port.h:46
error_t dhComputeSharedSecret(DhContext *context, uint8_t *output, size_t outputSize, size_t *outputLen)
Compute Diffie-Hellman shared secret.
Definition: dh.c:223
@ TLS_KEY_EXCH_ECDH_ANON
Definition: tls.h:1150
Elliptic curve parameters.
Definition: ec_curves.h:302
PEM file import functions.
void sha1Init(Sha1Context *context)
Initialize SHA-1 message digest context.
TlsCertAuthorities
Definition: tls.h:1561
#define osMemcpy(dest, src, length)
Definition: os_port.h:141
#define TlsContext
Definition: tls.h:36
error_t
Error codes.
Definition: error.h:43
#define CRYPTO_TEST_NZ_32(a)
Definition: crypto.h:901
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256
Definition: tls.h:1256
void rsaFreePrivateKey(RsaPrivateKey *key)
Release an RSA private key.
Definition: rsa.c:153
error_t tlsGenerateEd448Signature(TlsContext *context, const DataChunk *messageChunks, uint8_t *signature, size_t *signatureLen)
Generate Ed448 signature.
#define TLS_VERSION_1_2
Definition: tls.h:96
#define TLS_PREMASTER_SECRET_SIZE
Definition: tls.h:808
@ TLS_GROUP_NONE
Definition: tls.h:1370
@ TLS_KEY_EXCH_DH_ANON
Definition: tls.h:1145
@ ERROR_FAILURE
Generic error code.
Definition: error.h:45
error_t tlsSelectCipherSuite(TlsContext *context, uint16_t identifier)
Set cipher suite.
Definition: tls_misc.c:333
#define STORE16BE(a, p)
Definition: cpu_endian.h:262
@ TLS_KEY_EXCH_ECDH_ECDSA
Definition: tls.h:1148
error_t tlsResumeStatelessSession(TlsContext *context, const uint8_t *sessionId, size_t sessionIdLen, const TlsCipherSuites *cipherSuites, const TlsHelloExtensions *extensions)
Resume TLS session via session ticket.
Tls12DigitalSignature
Definition: tls.h:1729
uint8_t digest[MAX_HASH_DIGEST_SIZE]
#define TLS_VERSION_1_3
Definition: tls.h:97
Handshake message processing (TLS client and server)
@ TLS_HASH_ALGO_SHA384
Definition: tls.h:1218
error_t tlsSelectSignAlgo(TlsContext *context, const TlsCertDesc *cert, const TlsSignSchemeList *signAlgoList)
Select the algorithm to be used when generating digital signatures.
Definition: tls_sign_misc.c:85
@ TLS_EMPTY_RENEGOTIATION_INFO_SCSV
error_t tlsNegotiateCipherSuite(TlsContext *context, const HashAlgo *hashAlgo, const TlsCipherSuites *cipherSuites, TlsHelloExtensions *extensions)
Cipher suite negotiation.
@ TLS_GROUP_SECP384R1
Definition: tls.h:1394
TLS record protocol.
error_t tlsWriteEcPoint(const EcDomainParameters *params, const EcPoint *a, uint8_t *data, size_t *length)
Encode an EC point to an opaque vector.
Definition: tls_misc.c:1029
#define CRYPTO_SELECT_8(a, b, c)
Definition: crypto.h:857
#define TLS_MAX_CERTIFICATES
Definition: tls.h:262
TlsSignSchemeList
Definition: tls.h:1539
MD5 algorithm context.
Definition: md5.h:62
@ ERROR_NO_CERTIFICATE
Definition: error.h:234
@ TLS_HASH_ALGO_SHA256
Definition: tls.h:1217
@ TLS_CERT_RSA_SIGN
Definition: tls.h:1188
uint8_t length
Definition: tcp.h:368
const TlsFfdheGroup * tlsGetFfdheGroup(TlsContext *context, uint16_t namedGroup)
Get the FFDHE parameters that match the specified named group.
Definition: tls_ffdhe.c:314
error_t tlsLoadFfdheParameters(DhParameters *params, const TlsFfdheGroup *ffdheGroup)
Load FFDHE parameters.
Definition: tls_ffdhe.c:374
#define MIN(a, b)
Definition: os_port.h:63
error_t tlsSelectFfdheGroup(TlsContext *context, const TlsSupportedGroupList *groupList)
Select the named group to be used when performing FFDHE key exchange.
Definition: tls_ffdhe.c:174
@ TLS_KEY_EXCH_DHE_PSK
Definition: tls.h:1153
TlsCompressMethods
Definition: tls.h:1528
uint16_t dtlsTranslateVersion(uint16_t version)
Translate TLS version into DTLS version.
Definition: dtls_misc.c:112
#define MD5_DIGEST_SIZE
Definition: md5.h:45
Hello extensions.
Definition: tls.h:2098
@ TLS_FALLBACK_SCSV
#define TLS_MASTER_SECRET_SIZE
Definition: tls.h:801
@ TLS_GROUP_BRAINPOOLP384R1_TLS13
Definition: tls.h:1402
error_t ecdhComputeSharedSecret(EcdhContext *context, uint8_t *output, size_t outputSize, size_t *outputLen)
Compute ECDH shared secret.
Definition: ecdh.c:340
@ ERROR_UNSUPPORTED_KEY_EXCH_ALGO
Definition: error.h:131
error_t tlsGenerateDsaSignature(TlsContext *context, const uint8_t *digest, size_t digestLen, uint8_t *signature, size_t *signatureLen)
Generate DSA signature.
@ TLS_KEY_EXCH_RSA_PSK
Definition: tls.h:1152
HashAlgoFinal final
Definition: crypto.h:1058
Data chunk descriptor.
Definition: crypto.h:981
error_t tlsRestoreSessionId(TlsContext *context, const TlsSessionState *session)
Restore a TLS session using session ID.
Definition: tls_misc.c:554
char_t * serverName
ServerName extension.
Definition: tls.h:2059
uint32_t systime_t
System time.
#define ntohs(value)
Definition: cpu_endian.h:421
@ TLS_EC_CURVE_TYPE_NAMED_CURVE
Definition: tls.h:1445
#define TRACE_DEBUG(...)
Definition: debug.h:107
#define MAX(a, b)
Definition: os_port.h:67
#define SHA1_DIGEST_SIZE
Definition: sha1.h:45
error_t tlsReadMpi(Mpi *a, const uint8_t *data, size_t size, size_t *length)
Read a multiple precision integer from an opaque vector.
Definition: tls_misc.c:991
const char_t * tlsGetCipherSuiteName(uint16_t identifier)
Convert cipher suite identifier to string representation.
TlsPlaintextSessionState
Definition: tls.h:1890
error_t tlsParseCompressMethods(TlsContext *context, const TlsCompressMethods *compressMethods)
Parse the list of compression methods supported by the client.
TLS session state.
Definition: tls.h:2038
uint8_t n
RSA private key.
Definition: rsa.h:68
error_t tlsSelectCertificate(TlsContext *context, const TlsHelloExtensions *extensions)
Certificate selection process.
#define CRYPTO_TEST_NEQ_32(a, b)
Definition: crypto.h:909
@ ERROR_INAPPROPRIATE_FALLBACK
Definition: error.h:246
@ TLS_SIGN_SCHEME_ED448
Definition: tls.h:1268
Handshake message processing (TLS server)
@ TLS_KEY_EXCH_ECDHE_PSK
Definition: tls.h:1154
@ TLS_CERT_RSA_FIXED_ECDH
Definition: tls.h:1196
error_t tlsGenerateRsaSignature(const RsaPrivateKey *key, const uint8_t *digest, uint8_t *signature, size_t *signatureLen)
Generate RSA signature (TLS 1.0 and TLS 1.1)
X.509 certificate handling.
error_t tlsResumeStatefulSession(TlsContext *context, const uint8_t *sessionId, size_t sessionIdLen, const TlsCipherSuites *cipherSuites, const TlsHelloExtensions *extensions)
Resume TLS session via session ID.
Helper functions for signature generation and verification.
const EcCurveInfo * tlsGetCurveInfo(TlsContext *context, uint16_t namedCurve)
Get the EC domain parameters that match the specified named curve.
Definition: tls_misc.c:1240
error_t tlsSelectGroup(TlsContext *context, const TlsSupportedGroupList *groupList)
Select the group to be used when performing (EC)DHE key exchange.
TLS (Transport Layer Security)
@ TLS_SIGN_ALGO_RSA
Definition: tls.h:1232
error_t tlsCheckSignalingCipherSuiteValues(TlsContext *context, const TlsCipherSuites *cipherSuites)
Check whether the ClientHello includes any SCSV cipher suites.
uint16_t version
TLS protocol version.
Definition: tls.h:2039
SHA-1 algorithm context.
Definition: sha1.h:62
@ TLS_CERT_ECDSA_SIGN
Definition: tls.h:1195
@ TLS_KEY_EXCH_DHE_DSS
Definition: tls.h:1144
size_t length
Definition: crypto.h:983
Common interface for hash algorithms.
Definition: crypto.h:1046
DtlsSupportedVersionList
Definition: dtls_misc.h:165
#define TLS_SIGN_ALGO(signScheme)
Definition: tls_sign_misc.h:38
FFDHE key exchange.
Helper functions for TLS server.
Formatting and parsing of extensions (TLS server)
@ ERROR_UNSUPPORTED_SIGNATURE_ALGO
Definition: error.h:132
error_t dhGenerateKeyPair(DhContext *context, const PrngAlgo *prngAlgo, void *prngContext)
Diffie-Hellman key pair generation.
Definition: dh.c:119
error_t tlsGenerateServerKeySignature(TlsContext *context, TlsDigitalSignature *signature, const uint8_t *params, size_t paramsLen, size_t *written)
Sign server's key exchange parameters (TLS 1.0 and TLS 1.1)
@ ERROR_DECODING_FAILED
Definition: error.h:241
unsigned int uint_t
Definition: compiler_port.h:50
#define TRACE_DEBUG_MPI(p, a)
Definition: debug.h:110
#define LOAD16BE(p)
Definition: cpu_endian.h:186
#define osMemset(p, value, length)
Definition: os_port.h:135
TlsSupportedGroupList
Definition: tls.h:1651
void sha1Final(Sha1Context *context, uint8_t *digest)
Finish the SHA-1 message digest.
#define tlsFreeMem(p)
Definition: tls.h:858
@ TLS_CERT_DSS_FIXED_DH
Definition: tls.h:1191
TlsSupportedVersionList
Definition: tls.h:1595
@ TLS_CERT_RSA_FIXED_DH
Definition: tls.h:1190
@ TLS_SIGN_ALGO_ECDSA
Definition: tls.h:1234
error_t tlsGenerateRsaPssSignature(TlsContext *context, const HashAlgo *hashAlgo, const uint8_t *digest, uint8_t *signature, size_t *signatureLen)
Generate RSA-PSS signature.
error_t ecdhCheckPublicKey(const EcDomainParameters *params, EcPoint *publicKey)
Check ECDH public key.
Definition: ecdh.c:227
@ TLS_KEY_EXCH_DHE_RSA
Definition: tls.h:1142
RSA/DSA/ECDSA/EdDSA signature generation.
bool_t extendedMasterSecret
Extended master secret computation.
Definition: tls.h:2046
@ ERROR_INVALID_TICKET
Definition: error.h:228
#define TLS_MAX_TICKET_SIZE
Definition: tls.h:157
void md5Update(Md5Context *context, const void *data, size_t length)
Update the MD5 context with a portion of the message being hashed.
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
#define osMemmove(dest, src, length)
Definition: os_port.h:147
@ TLS_KEY_EXCH_DH_RSA
Definition: tls.h:1141
error_t tlsReadEcPoint(const EcDomainParameters *params, EcPoint *a, const uint8_t *data, size_t size, size_t *length)
Read an EC point from an opaque vector.
Definition: tls_misc.c:1066
uint_t tlsGetCipherSuiteType(uint16_t identifier)
Retrieve the cipher suite type for a given identifier.
error_t ecdhGenerateKeyPair(EcdhContext *context, const PrngAlgo *prngAlgo, void *prngContext)
ECDH key pair generation.
Definition: ecdh.c:85
systime_t osGetSystemTime(void)
Retrieve system time.