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