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