tls_certificate.c
Go to the documentation of this file.
1 /**
2  * @file tls_certificate.c
3  * @brief X.509 certificate handling
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_certificate.h"
38 #include "tls_sign_misc.h"
39 #include "tls_misc.h"
40 #include "encoding/asn1.h"
41 #include "encoding/oid.h"
42 #include "pkix/pem_import.h"
43 #include "pkix/x509_cert_parse.h"
45 #include "pkix/x509_key_parse.h"
46 #include "debug.h"
47 
48 //Check TLS library configuration
49 #if (TLS_SUPPORT == ENABLED)
50 
51 
52 /**
53  * @brief Format certificate chain
54  * @param[in] context Pointer to the TLS context
55  * @param[in] p Output stream where to write the certificate chain
56  * @param[out] written Total number of bytes that have been written
57  * @return Error code
58  **/
59 
61  size_t *written)
62 {
63  error_t error;
64  size_t m;
65  size_t n;
66  size_t certChainLen;
67  const char_t *certChain;
68 
69  //Initialize status code
70  error = NO_ERROR;
71 
72  //Length of the certificate list in bytes
73  *written = 0;
74 
75  //Check whether a certificate is available
76  if(context->cert != NULL)
77  {
78  //Point to the certificate chain
79  certChain = context->cert->certChain;
80  //Get the total length, in bytes, of the certificate chain
81  certChainLen = context->cert->certChainLen;
82  }
83  else
84  {
85  //If no suitable certificate is available, the message contains an
86  //empty certificate list
87  certChain = NULL;
88  certChainLen = 0;
89  }
90 
91  //Parse the certificate chain
92  while(certChainLen > 0)
93  {
94  //The first pass calculates the length of the DER-encoded certificate
95  error = pemImportCertificate(certChain, certChainLen, NULL, &n, NULL);
96 
97  //End of file detected?
98  if(error)
99  {
100  //Exit immediately
101  error = NO_ERROR;
102  break;
103  }
104 
105  //Buffer overflow?
106  if((*written + n + 3) > context->txBufferMaxLen)
107  {
108  //Report an error
109  error = ERROR_MESSAGE_TOO_LONG;
110  break;
111  }
112 
113  //Each certificate is preceded by a 3-byte length field
114  STORE24BE(n, p);
115 
116  //The second pass decodes the PEM certificate
117  error = pemImportCertificate(certChain, certChainLen, p + 3, &n, &m);
118  //Any error to report?
119  if(error)
120  break;
121 
122  //Advance read pointer
123  certChain += m;
124  certChainLen -= m;
125 
126  //Advance write pointer
127  p += n + 3;
128  *written += n + 3;
129 
130 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
131  //TLS 1.3 currently selected?
132  if(context->version == TLS_VERSION_1_3)
133  {
134  //Format the list of extensions for the current CertificateEntry
135  error = tls13FormatCertExtensions(p, &n);
136  //Any error to report?
137  if(error)
138  break;
139 
140  //Advance write pointer
141  p += n;
142  *written += n;
143  }
144 #endif
145  }
146 
147  //Return status code
148  return error;
149 }
150 
151 
152 /**
153  * @brief Format raw public key
154  * @param[in] context Pointer to the TLS context
155  * @param[in] p Output stream where to write the raw public key
156  * @param[out] written Total number of bytes that have been written
157  * @return Error code
158  **/
159 
161  size_t *written)
162 {
163  error_t error;
164 
165  //Initialize status code
166  error = NO_ERROR;
167 
168  //Length of the certificate list in bytes
169  *written = 0;
170 
171 #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED)
172  //Check whether a certificate is available
173  if(context->cert != NULL)
174  {
175  size_t n;
176  uint8_t *derCert;
177  size_t derCertLen;
178  X509CertInfo *certInfo;
179 
180  //Initialize variables
181  derCert = NULL;
182  certInfo = NULL;
183 
184  //Start of exception handling block
185  do
186  {
187  //The first pass calculates the length of the DER-encoded certificate
188  error = pemImportCertificate(context->cert->certChain,
189  context->cert->certChainLen, NULL, &derCertLen, NULL);
190  //Any error to report?
191  if(error)
192  break;
193 
194  //Allocate a memory buffer to hold the DER-encoded certificate
195  derCert = tlsAllocMem(derCertLen);
196  //Failed to allocate memory?
197  if(derCert == NULL)
198  {
199  error = ERROR_OUT_OF_MEMORY;
200  break;
201  }
202 
203  //The second pass decodes the PEM certificate
204  error = pemImportCertificate(context->cert->certChain,
205  context->cert->certChainLen, derCert, &derCertLen, NULL);
206  //Any error to report?
207  if(error)
208  break;
209 
210  //Allocate a memory buffer to store X.509 certificate info
211  certInfo = tlsAllocMem(sizeof(X509CertInfo));
212  //Failed to allocate memory?
213  if(certInfo == NULL)
214  {
215  error = ERROR_OUT_OF_MEMORY;
216  break;
217  }
218 
219  //Parse X.509 certificate
220  error = x509ParseCertificate(derCert, derCertLen, certInfo);
221  //Failed to parse the X.509 certificate?
222  if(error)
223  break;
224 
225  //Retrieve the length of the raw public key
227 
228 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
229  //TLS 1.3 currently selected?
230  if(context->version == TLS_VERSION_1_3)
231  {
232  //The raw public key is preceded by a 3-byte length field
233  STORE24BE(n, p);
234  //Copy the raw public key
235  osMemcpy(p + 3, certInfo->tbsCert.subjectPublicKeyInfo.raw.value, n);
236 
237  //Advance data pointer
238  p += n + 3;
239  //Adjust the length of the certificate list
240  *written += n + 3;
241 
242  //Format the list of extensions for the current CertificateEntry
243  error = tls13FormatCertExtensions(p, &n);
244  //Any error to report?
245  if(error)
246  break;
247 
248  //Advance data pointer
249  p += n;
250  //Adjust the length of the certificate list
251  *written += n;
252  }
253  else
254 #endif
255  {
256  //Copy the raw public key
258 
259  //Advance data pointer
260  p += n;
261  //Adjust the length of the certificate list
262  *written += n;
263  }
264 
265  //End of exception handling block
266  } while(0);
267 
268  //Release previously allocated memory
269  tlsFreeMem(derCert);
270  tlsFreeMem(certInfo);
271  }
272 #endif
273 
274  //Return status code
275  return error;
276 }
277 
278 
279 /**
280  * @brief Parse certificate chain
281  * @param[in] context Pointer to the TLS context
282  * @param[in] p Input stream where to read the certificate chain
283  * @param[in] length Number of bytes available in the input stream
284  * @return Error code
285  **/
286 
288  const uint8_t *p, size_t length)
289 {
290  error_t error;
291  error_t certValidResult;
292  uint_t i;
293  size_t n;
294  const char_t *subjectName;
295  X509CertInfo *certInfo;
296  X509CertInfo *issuerCertInfo;
297 
298  //Initialize X.509 certificates
299  certInfo = NULL;
300  issuerCertInfo = NULL;
301 
302  //Start of exception handling block
303  do
304  {
305  //Allocate a memory buffer to store X.509 certificate info
306  certInfo = tlsAllocMem(sizeof(X509CertInfo));
307  //Failed to allocate memory?
308  if(certInfo == NULL)
309  {
310  //Report an error
311  error = ERROR_OUT_OF_MEMORY;
312  break;
313  }
314 
315  //Allocate a memory buffer to store the parent certificate
316  issuerCertInfo = tlsAllocMem(sizeof(X509CertInfo));
317  //Failed to allocate memory?
318  if(issuerCertInfo == NULL)
319  {
320  //Report an error
321  error = ERROR_OUT_OF_MEMORY;
322  break;
323  }
324 
325  //The end-user certificate is preceded by a 3-byte length field
326  if(length < 3)
327  {
328  //Report an error
329  error = ERROR_DECODING_FAILED;
330  break;
331  }
332 
333  //Get the size occupied by the certificate
334  n = LOAD24BE(p);
335  //Jump to the beginning of the DER-encoded certificate
336  p += 3;
337  length -= 3;
338 
339  //Malformed Certificate message?
340  if(n == 0 || n > length)
341  {
342  //Report an error
343  error = ERROR_DECODING_FAILED;
344  break;
345  }
346 
347  //Display ASN.1 structure
348  error = asn1DumpObject(p, n, 0);
349  //Any error to report?
350  if(error)
351  break;
352 
353  //Parse end-user certificate
354  error = x509ParseCertificate(p, n, certInfo);
355  //Failed to parse the X.509 certificate?
356  if(error)
357  {
358  //Report an error
359 #if (TLS_MAX_EMPTY_RECORDS > 0)
360  error = ERROR_DECODING_FAILED;
361 #else
362  error = ERROR_BAD_CERTIFICATE;
363 #endif
364  break;
365  }
366 
367  //Check certificate key usage
368  error = tlsCheckKeyUsage(certInfo, context->entity,
369  context->keyExchMethod);
370  //Any error to report?
371  if(error)
372  break;
373 
374  //Extract the public key from the end-user certificate
375  error = tlsReadSubjectPublicKey(context,
376  &certInfo->tbsCert.subjectPublicKeyInfo);
377  //Any error to report?
378  if(error)
379  break;
380 
381 #if (TLS_CLIENT_SUPPORT == ENABLED)
382  //Client mode?
383  if(context->entity == TLS_CONNECTION_END_CLIENT)
384  {
385  TlsCertificateType certType;
386  TlsNamedGroup namedCurve;
387 
388  //Retrieve the type of the X.509 certificate
389  error = tlsGetCertificateType(certInfo, &certType, &namedCurve);
390  //Unsupported certificate?
391  if(error)
392  break;
393 
394  //Version of TLS prior to TLS 1.3?
395  if(context->version <= TLS_VERSION_1_2)
396  {
397  //ECDSA certificate?
398  if(certType == TLS_CERT_ECDSA_SIGN)
399  {
400  //Make sure the elliptic curve is supported
401  if(tlsGetCurve(context, namedCurve) == NULL)
402  {
403  error = ERROR_BAD_CERTIFICATE;
404  break;
405  }
406  }
407  }
408 
409  //Point to the subject name
410  subjectName = context->serverName;
411 
412  //Check the subject name in the server certificate against the actual
413  //FQDN name that is being requested
414  error = x509CheckSubjectName(certInfo, subjectName);
415  //Any error to report?
416  if(error)
417  {
418  //Debug message
419  TRACE_WARNING("Server name mismatch!\r\n");
420 
421  //Report an error
422  error = ERROR_BAD_CERTIFICATE;
423  break;
424  }
425  }
426  else
427 #endif
428  //Server mode?
429  {
430  //Do not check name constraints
431  subjectName = NULL;
432  }
433 
434  //Check if the end-user certificate can be matched with a trusted CA
435  certValidResult = tlsValidateCertificate(context, certInfo, 0,
436  subjectName);
437 
438  //Check validation result
439  if(certValidResult != NO_ERROR && certValidResult != ERROR_UNKNOWN_CA)
440  {
441  //The certificate is not valid
442  error = certValidResult;
443  break;
444  }
445 
446  //Next certificate
447  p += n;
448  length -= n;
449 
450 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
451  //TLS 1.3 currently selected?
452  if(context->version == TLS_VERSION_1_3)
453  {
454  //Parse the list of extensions for the current CertificateEntry
455  error = tls13ParseCertExtensions(p, length, &n);
456  //Any error to report?
457  if(error)
458  break;
459 
460  //Point to the next field
461  p += n;
462  //Remaining bytes to process
463  length -= n;
464  }
465 #endif
466 
467  //PKIX path validation
468  for(i = 0; length > 0; i++)
469  {
470  //Each intermediate certificate is preceded by a 3-byte length field
471  if(length < 3)
472  {
473  //Report an error
474  error = ERROR_DECODING_FAILED;
475  break;
476  }
477 
478  //Get the size occupied by the certificate
479  n = LOAD24BE(p);
480  //Jump to the beginning of the DER-encoded certificate
481  p += 3;
482  //Remaining bytes to process
483  length -= 3;
484 
485  //Malformed Certificate message?
486  if(n == 0 || n > length)
487  {
488  //Report an error
489  error = ERROR_DECODING_FAILED;
490  break;
491  }
492 
493  //Display ASN.1 structure
494  error = asn1DumpObject(p, n, 0);
495  //Any error to report?
496  if(error)
497  break;
498 
499  //Parse intermediate certificate
500  error = x509ParseCertificate(p, n, issuerCertInfo);
501  //Failed to parse the X.509 certificate?
502  if(error)
503  {
504  //Report an error
505  error = ERROR_DECODING_FAILED;
506  break;
507  }
508 
509  //Certificate chain validation in progress?
510  if(certValidResult == ERROR_UNKNOWN_CA)
511  {
512  //Validate current certificate
513  error = x509ValidateCertificate(certInfo, issuerCertInfo, i);
514  //Certificate validation failed?
515  if(error)
516  break;
517 
518  //Check name constraints
519  error = x509CheckNameConstraints(subjectName, issuerCertInfo);
520  //Should the application reject the certificate?
521  if(error)
522  {
523  //Report an error
524  error = ERROR_BAD_CERTIFICATE;
525  break;
526  }
527 
528  //Check the version of the certificate
529  if(issuerCertInfo->tbsCert.version < X509_VERSION_3)
530  {
531  //Conforming implementations may choose to reject all version 1
532  //and version 2 intermediate certificates (refer to RFC 5280,
533  //section 6.1.4)
534  error = ERROR_BAD_CERTIFICATE;
535  break;
536  }
537 
538  //Check if the intermediate certificate can be matched with a
539  //trusted CA
540  certValidResult = tlsValidateCertificate(context, issuerCertInfo,
541  i, subjectName);
542 
543  //Check validation result
544  if(certValidResult != NO_ERROR && certValidResult != ERROR_UNKNOWN_CA)
545  {
546  //The certificate is not valid
547  error = certValidResult;
548  break;
549  }
550  }
551 
552  //Keep track of the issuer certificate
553  *certInfo = *issuerCertInfo;
554 
555  //Next certificate
556  p += n;
557  length -= n;
558 
559 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
560  //TLS 1.3 currently selected?
561  if(context->version == TLS_VERSION_1_3)
562  {
563  //Parse the list of extensions for the current CertificateEntry
564  error = tls13ParseCertExtensions(p, length, &n);
565  //Any error to report?
566  if(error)
567  break;
568 
569  //Point to the next field
570  p += n;
571  //Remaining bytes to process
572  length -= n;
573  }
574 #endif
575  }
576 
577  //Certificate chain validation failed?
578  if(error == NO_ERROR && certValidResult != NO_ERROR)
579  {
580  //A valid certificate chain or partial chain was received, but the
581  //certificate was not accepted because the CA certificate could not
582  //be matched with a known, trusted CA
583  error = ERROR_UNKNOWN_CA;
584  }
585 
586  //End of exception handling block
587  } while(0);
588 
589  //Free previously allocated memory
590  tlsFreeMem(certInfo);
591  tlsFreeMem(issuerCertInfo);
592 
593  //Return status code
594  return error;
595 }
596 
597 
598 /**
599  * @brief Parse raw public key
600  * @param[in] context Pointer to the TLS context
601  * @param[in] p Input stream where to read the raw public key
602  * @param[in] length Number of bytes available in the input stream
603  * @return Error code
604  **/
605 
606 error_t tlsParseRawPublicKey(TlsContext *context, const uint8_t *p,
607  size_t length)
608 {
609  error_t error;
610 
611 #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED)
612  //Any registered callback?
613  if(context->rpkVerifyCallback != NULL)
614  {
615  size_t n;
616  size_t rawPublicKeyLen;
617  const uint8_t *rawPublicKey;
618  X509SubjectPublicKeyInfo subjectPublicKeyInfo;
619 
620 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
621  //TLS 1.3 currently selected?
622  if(context->version == TLS_VERSION_1_3)
623  {
624  //The raw public key is preceded by a 3-byte length field
625  if(length < 3)
626  return ERROR_DECODING_FAILED;
627 
628  //Get the size occupied by the raw public key
629  rawPublicKeyLen = LOAD24BE(p);
630  //Advance data pointer
631  p += 3;
632  //Remaining bytes to process
633  length -= 3;
634 
635  //Malformed Certificate message?
636  if(length < rawPublicKeyLen)
637  return ERROR_DECODING_FAILED;
638  }
639  else
640 #endif
641  {
642  //The payload of the Certificate message contains a SubjectPublicKeyInfo
643  //structure
644  rawPublicKeyLen = length;
645  }
646 
647  //Point to the raw public key
648  rawPublicKey = p;
649 
650  //Decode the SubjectPublicKeyInfo structure
651  error = x509ParseSubjectPublicKeyInfo(rawPublicKey, rawPublicKeyLen, &n,
652  &subjectPublicKeyInfo);
653  //Any error to report?
654  if(error)
655  return error;
656 
657  //Advance data pointer
658  p += rawPublicKeyLen;
659  //Remaining bytes to process
660  length -= rawPublicKeyLen;
661 
662 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
663  //TLS 1.3 currently selected?
664  if(context->version == TLS_VERSION_1_3)
665  {
666  //Parse the list of extensions for the current CertificateEntry
667  error = tls13ParseCertExtensions(p, length, &n);
668  //Any error to report?
669  if(error)
670  return error;
671 
672  //Advance data pointer
673  p += n;
674  //Remaining bytes to process
675  length -= n;
676  }
677 #endif
678 
679  //If the RawPublicKey certificate type was negotiated, the certificate
680  //list must contain no more than one CertificateEntry (refer to RFC 8446,
681  //section 4.4.2)
682  if(length != 0)
683  return ERROR_DECODING_FAILED;
684 
685  //Extract the public key from the SubjectPublicKeyInfo structure
686  error = tlsReadSubjectPublicKey(context, &subjectPublicKeyInfo);
687  //Any error to report?
688  if(error)
689  return error;
690 
691  //When raw public keys are used, authentication of the peer is supported
692  //only through authentication of the received SubjectPublicKeyInfo via an
693  //out-of-band method
694  error = context->rpkVerifyCallback(context, rawPublicKey,
695  rawPublicKeyLen);
696  }
697  else
698 #endif
699  {
700  //Report an error
701  error = ERROR_BAD_CERTIFICATE;
702  }
703 
704  //Return status code
705  return error;
706 }
707 
708 
709 /**
710  * @brief Check whether a certificate is acceptable
711  * @param[in] context Pointer to the TLS context
712  * @param[in] cert End entity certificate
713  * @param[in] certTypes List of supported certificate types
714  * @param[in] numCertTypes Size of the list that contains the supported
715  * certificate types
716  * @param[in] curveList List of supported elliptic curves
717  * @param[in] certSignAlgoList List of signature algorithms that may be used
718  * in X.509 certificates
719  * @param[in] certAuthorities List of trusted CA
720  * @return TRUE if the specified certificate conforms to the requirements,
721  * else FALSE
722  **/
723 
725  const TlsCertDesc *cert, const uint8_t *certTypes, size_t numCertTypes,
726  const TlsSupportedGroupList *curveList,
727  const TlsSignSchemeList *certSignAlgoList,
728  const TlsCertAuthorities *certAuthorities)
729 {
730  size_t i;
731  size_t n;
732  size_t length;
733  bool_t acceptable;
734 
735  //Make sure that a valid certificate has been loaded
736  if(cert->certChain == NULL || cert->certChainLen == 0)
737  return FALSE;
738 
739  //This flag tells whether the certificate is acceptable
740  acceptable = TRUE;
741 
742 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
743  //Version of TLS prior to TLS 1.2?
744  if(context->version <= TLS_VERSION_1_1)
745  {
746  //Server mode?
747  if(context->entity == TLS_CONNECTION_END_SERVER)
748  {
749  //The signing algorithm for the certificate must be the same as the
750  //algorithm for the certificate key (refer to RFC 4346, section 7.4.2)
751  if(cert->type == TLS_CERT_RSA_SIGN &&
753  {
754  acceptable = TRUE;
755  }
756  else if(cert->type == TLS_CERT_DSS_SIGN &&
758  {
759  acceptable = TRUE;
760  }
761  else if(cert->type == TLS_CERT_ECDSA_SIGN &&
763  {
764  acceptable = TRUE;
765  }
766  else
767  {
768  acceptable = FALSE;
769  }
770  }
771  }
772 #endif
773 
774 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
775  //Version of TLS prior to TLS 1.3?
776  if(context->version <= TLS_VERSION_1_2)
777  {
778  //Filter out certificates with unsupported type
779  if(acceptable && certTypes != NULL)
780  {
781  //Loop through the list of supported certificate types
782  for(i = 0, acceptable = FALSE; i < numCertTypes && !acceptable; i++)
783  {
784  //Check certificate type
785  if(certTypes[i] == TLS_CERT_RSA_SIGN)
786  {
787  //The certificate must contain an RSA public key
788  if(cert->type == TLS_CERT_RSA_SIGN ||
789  cert->type == TLS_CERT_RSA_PSS_SIGN)
790  {
791  acceptable = TRUE;
792  }
793  }
794  else if(certTypes[i] == TLS_CERT_DSS_SIGN)
795  {
796  //The certificate must contain a DSA public key
797  if(cert->type == TLS_CERT_DSS_SIGN)
798  {
799  acceptable = TRUE;
800  }
801  }
802  else if(certTypes[i] == TLS_CERT_ECDSA_SIGN)
803  {
804  //The certificate must contain an ECDSA or EdDSA public key
805  if(cert->type == TLS_CERT_ECDSA_SIGN ||
806  cert->type == TLS_CERT_ED25519_SIGN ||
807  cert->type == TLS_CERT_ED448_SIGN)
808  {
809  acceptable = TRUE;
810  }
811  }
812  else
813  {
814  //Unknown certificate type
815  }
816  }
817  }
818 
819  //ECDSA certificate?
820  if(cert->type == TLS_CERT_ECDSA_SIGN)
821  {
822  //In versions of TLS prior to TLS 1.3, the EllipticCurves extension is
823  //used to negotiate ECDSA curves (refer to RFC 8446, section 4.2.7)
824  if(acceptable && curveList != NULL)
825  {
826  //Retrieve the number of items in the list
827  n = ntohs(curveList->length) / sizeof(uint16_t);
828 
829  //Loop through the list of supported elliptic curves
830  for(i = 0, acceptable = FALSE; i < n && !acceptable; i++)
831  {
832  //Check whether the elliptic curve is supported
833  if(ntohs(curveList->value[i]) == cert->namedCurve)
834  {
835  acceptable = TRUE;
836  }
837  }
838  }
839  }
840  }
841 #endif
842 
843 #if (TLS_SM2_SIGN_SUPPORT == ENABLED)
844  //SM2 certificate?
845  if(cert->type == TLS_CERT_SM2_SIGN)
846  {
847  //The signature algorithm used by the CA to sign the current certificate
848  //must be sm2sig_sm3 (refer to RFC 8998, section 3.3.3)
850  {
851  acceptable = FALSE;
852  }
853  }
854 #endif
855 
856  //Filter out certificates that are signed with an unsupported algorithm
857  if(acceptable && certSignAlgoList != NULL)
858  {
859  //Retrieve the number of items in the list
860  n = ntohs(certSignAlgoList->length) / sizeof(uint16_t);
861 
862  //Loop through the list of supported signature algorithms
863  for(i = 0, acceptable = FALSE; i < n && !acceptable; i++)
864  {
865  //The certificate must be signed using a valid algorithm
866  if(ntohs(certSignAlgoList->value[i]) == cert->signScheme)
867  {
868  acceptable = TRUE;
869  }
870  }
871  }
872 
873  //Filter out certificates that are issued by a non trusted CA
874  if(acceptable && certAuthorities != NULL)
875  {
876  //Retrieve the length of the list
877  length = ntohs(certAuthorities->length);
878 
879  //If the certificate authorities list is empty, then the client
880  //may send any certificate of the appropriate type
881  if(length > 0)
882  {
883  error_t error;
884  size_t pemCertLen;
885  const char_t *certChain;
886  size_t certChainLen;
887  uint8_t *derCert;
888  size_t derCertLen;
889  X509CertInfo *certInfo;
890 
891  //The list of acceptable certificate authorities describes the
892  //known roots CA
893  acceptable = FALSE;
894 
895  //Point to the end entity certificate
896  certChain = cert->certChain;
897  //Get the total length, in bytes, of the certificate chain
898  certChainLen = cert->certChainLen;
899 
900  //Allocate a memory buffer to store X.509 certificate info
901  certInfo = tlsAllocMem(sizeof(X509CertInfo));
902 
903  //Successful memory allocation?
904  if(certInfo != NULL)
905  {
906  //Parse the certificate chain
907  while(certChainLen > 0 && !acceptable)
908  {
909  //The first pass calculates the length of the DER-encoded
910  //certificate
911  error = pemImportCertificate(certChain, certChainLen, NULL,
912  &derCertLen, &pemCertLen);
913 
914  //Check status code
915  if(!error)
916  {
917  //Allocate a memory buffer to hold the DER-encoded certificate
918  derCert = tlsAllocMem(derCertLen);
919 
920  //Successful memory allocation?
921  if(derCert != NULL)
922  {
923  //The second pass decodes the PEM certificate
924  error = pemImportCertificate(certChain, certChainLen,
925  derCert, &derCertLen, NULL);
926 
927  //Check status code
928  if(!error)
929  {
930  //Parse X.509 certificate
931  error = x509ParseCertificate(derCert, derCertLen,
932  certInfo);
933  }
934 
935  //Check status code
936  if(!error)
937  {
938  //Parse each distinguished name of the list
939  for(i = 0; i < length; i += n + 2)
940  {
941  //Sanity check
942  if((i + 2) > length)
943  break;
944 
945  //Each distinguished name is preceded by a 2-byte
946  //length field
947  n = LOAD16BE(certAuthorities->value + i);
948 
949  //Make sure the length field is valid
950  if((i + n + 2) > length)
951  break;
952 
953  //Check if the distinguished name matches the root CA
954  if(x509CompareName(certAuthorities->value + i + 2, n,
955  certInfo->tbsCert.issuer.raw.value,
956  certInfo->tbsCert.issuer.raw.length))
957  {
958  acceptable = TRUE;
959  break;
960  }
961  }
962  }
963 
964  //Free previously allocated memory
965  tlsFreeMem(derCert);
966  }
967 
968  //Advance read pointer
969  certChain += pemCertLen;
970  certChainLen -= pemCertLen;
971  }
972  else
973  {
974  //No more CA certificates in the list
975  break;
976  }
977  }
978 
979  //Free previously allocated memory
980  tlsFreeMem(certInfo);
981  }
982  }
983  }
984 
985  //The return value specifies whether all the criteria were matched
986  return acceptable;
987 }
988 
989 
990 /**
991  * @brief Verify certificate against root CAs
992  * @param[in] context Pointer to the TLS context
993  * @param[in] certInfo X.509 certificate to be verified
994  * @param[in] pathLen Certificate path length
995  * @param[in] subjectName Subject name (optional parameter)
996  * @return Error code
997  **/
998 
1000  const X509CertInfo *certInfo, uint_t pathLen, const char_t *subjectName)
1001 {
1002  error_t error;
1003  size_t pemCertLen;
1004  const char_t *trustedCaList;
1005  size_t trustedCaListLen;
1006  uint8_t *derCert;
1007  size_t derCertLen;
1008  X509CertInfo *caCertInfo;
1009 
1010  //Initialize status code
1011  error = ERROR_UNKNOWN_CA;
1012 
1013  //Any registered callback?
1014  if(context->certVerifyCallback != NULL)
1015  {
1016  //Invoke user callback function
1017  error = context->certVerifyCallback(context, certInfo, pathLen,
1018  context->certVerifyParam);
1019  }
1020 
1021  //Check status code
1022  if(error == NO_ERROR)
1023  {
1024  //The certificate is valid
1025  }
1026  else if(error == ERROR_UNKNOWN_CA)
1027  {
1028  //Check whether the certificate should be checked against root CAs
1029  if(context->trustedCaListLen > 0)
1030  {
1031  //Point to the first trusted CA certificate
1032  trustedCaList = context->trustedCaList;
1033  //Get the total length, in bytes, of the trusted CA list
1034  trustedCaListLen = context->trustedCaListLen;
1035 
1036  //Allocate a memory buffer to store X.509 certificate info
1037  caCertInfo = tlsAllocMem(sizeof(X509CertInfo));
1038 
1039  //Successful memory allocation?
1040  if(caCertInfo != NULL)
1041  {
1042  //Loop through the list of trusted CA certificates
1043  while(trustedCaListLen > 0 && error == ERROR_UNKNOWN_CA)
1044  {
1045  //The first pass calculates the length of the DER-encoded
1046  //certificate
1047  error = pemImportCertificate(trustedCaList, trustedCaListLen,
1048  NULL, &derCertLen, &pemCertLen);
1049 
1050  //Check status code
1051  if(!error)
1052  {
1053  //Allocate a memory buffer to hold the DER-encoded certificate
1054  derCert = tlsAllocMem(derCertLen);
1055 
1056  //Successful memory allocation?
1057  if(derCert != NULL)
1058  {
1059  //The second pass decodes the PEM certificate
1060  error = pemImportCertificate(trustedCaList,
1061  trustedCaListLen, derCert, &derCertLen, NULL);
1062 
1063  //Check status code
1064  if(!error)
1065  {
1066  //Parse X.509 certificate
1067  error = x509ParseCertificate(derCert, derCertLen,
1068  caCertInfo);
1069  }
1070 
1071  //Check status code
1072  if(!error)
1073  {
1074  //Validate the certificate with the current CA
1075  error = x509ValidateCertificate(certInfo, caCertInfo,
1076  pathLen);
1077  }
1078 
1079  //Check status code
1080  if(!error)
1081  {
1082  //Check name constraints
1083  error = x509CheckNameConstraints(subjectName, caCertInfo);
1084  }
1085 
1086  //Check status code
1087  if(!error)
1088  {
1089  //The certificate is issued by a trusted CA
1090  error = NO_ERROR;
1091  }
1092  else
1093  {
1094  //The certificate cannot be matched with the current CA
1095  error = ERROR_UNKNOWN_CA;
1096  }
1097 
1098  //Free previously allocated memory
1099  tlsFreeMem(derCert);
1100  }
1101  else
1102  {
1103  //Failed to allocate memory
1104  error = ERROR_OUT_OF_MEMORY;
1105  }
1106 
1107  //Advance read pointer
1108  trustedCaList += pemCertLen;
1109  trustedCaListLen -= pemCertLen;
1110  }
1111  else
1112  {
1113  //No more CA certificates in the list
1114  trustedCaListLen = 0;
1115  error = ERROR_UNKNOWN_CA;
1116  }
1117  }
1118 
1119  //Free previously allocated memory
1120  tlsFreeMem(caCertInfo);
1121  }
1122  else
1123  {
1124  //Failed to allocate memory
1125  error = ERROR_OUT_OF_MEMORY;
1126  }
1127  }
1128  else
1129  {
1130  //Do not check the certificate against root CAs
1131  error = NO_ERROR;
1132  }
1133  }
1134  else if(error == ERROR_BAD_CERTIFICATE ||
1135  error == ERROR_UNSUPPORTED_CERTIFICATE ||
1136  error == ERROR_UNKNOWN_CERTIFICATE ||
1137  error == ERROR_CERTIFICATE_REVOKED ||
1138  error == ERROR_CERTIFICATE_EXPIRED ||
1139  error == ERROR_HANDSHAKE_FAILED)
1140  {
1141  //The certificate is not valid
1142  }
1143  else
1144  {
1145  //Report an error
1146  error = ERROR_BAD_CERTIFICATE;
1147  }
1148 
1149  //Return status code
1150  return error;
1151 }
1152 
1153 
1154 /**
1155  * @brief Retrieve the certificate type
1156  * @param[in] certInfo X.509 certificate
1157  * @param[out] certType Certificate type
1158  * @param[out] namedCurve Elliptic curve (only for ECDSA certificates)
1159  * @return Error code
1160  **/
1161 
1163  TlsCertificateType *certType, TlsNamedGroup *namedCurve)
1164 {
1165  size_t oidLen;
1166  const uint8_t *oid;
1167 
1168  //Check parameters
1169  if(certInfo == NULL || certType == NULL || namedCurve == NULL)
1170  return ERROR_INVALID_PARAMETER;
1171 
1172  //Point to the public key identifier
1175 
1176 #if (TLS_RSA_SIGN_SUPPORT == ENABLED || TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
1177  //RSA public key?
1179  {
1180  //Save certificate type
1181  *certType = TLS_CERT_RSA_SIGN;
1182  //No named curve applicable
1183  *namedCurve = TLS_GROUP_NONE;
1184  }
1185  else
1186 #endif
1187 #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
1188  //RSA-PSS public key?
1189  if(OID_COMP(oid, oidLen, RSASSA_PSS_OID) == 0)
1190  {
1191  //Save certificate type
1192  *certType = TLS_CERT_RSA_PSS_SIGN;
1193  //No named curve applicable
1194  *namedCurve = TLS_GROUP_NONE;
1195  }
1196  else
1197 #endif
1198 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
1199  //DSA public key?
1200  if(OID_COMP(oid, oidLen, DSA_OID) == 0)
1201  {
1202  //Save certificate type
1203  *certType = TLS_CERT_DSS_SIGN;
1204  //No named curve applicable
1205  *namedCurve = TLS_GROUP_NONE;
1206  }
1207  else
1208 #endif
1209 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED || TLS_SM2_SIGN_SUPPORT == ENABLED)
1210  //EC public key?
1211  if(OID_COMP(oid, oidLen, EC_PUBLIC_KEY_OID) == 0)
1212  {
1213  const X509EcParameters *params;
1214 
1215  //Point to the EC parameters
1216  params = &certInfo->tbsCert.subjectPublicKeyInfo.ecParams;
1217 
1218  //SM2 elliptic curve?
1219  if(OID_COMP(params->namedCurve.value, params->namedCurve.length,
1220  SM2_OID) == 0)
1221  {
1222  //Save certificate type
1223  *certType = TLS_CERT_SM2_SIGN;
1224 
1225  //The only valid elliptic curve for the SM2 signature algorithm is
1226  //curveSM2 (refer to RFC 8446, section 3.2.1)
1227  *namedCurve = TLS_GROUP_CURVE_SM2;
1228  }
1229  else
1230  {
1231  //Save certificate type
1232  *certType = TLS_CERT_ECDSA_SIGN;
1233 
1234  //Retrieve the named curve that has been used to generate the EC
1235  //public key
1236  *namedCurve = tlsGetNamedCurve(params->namedCurve.value,
1237  params->namedCurve.length);
1238  }
1239  }
1240  else
1241 #endif
1242 #if (TLS_ED25519_SIGN_SUPPORT == ENABLED)
1243  //Ed25519 public key?
1244  if(OID_COMP(oid, oidLen, ED25519_OID) == 0)
1245  {
1246  //Save certificate type
1247  *certType = TLS_CERT_ED25519_SIGN;
1248  //No named curve applicable
1249  *namedCurve = TLS_GROUP_NONE;
1250  }
1251  else
1252 #endif
1253 #if (TLS_ED448_SIGN_SUPPORT == ENABLED)
1254  //Ed448 public key?
1255  if(OID_COMP(oid, oidLen, ED448_OID) == 0)
1256  {
1257  //Save certificate type
1258  *certType = TLS_CERT_ED448_SIGN;
1259  //No named curve applicable
1260  *namedCurve = TLS_GROUP_NONE;
1261  }
1262  else
1263 #endif
1264  //Invalid public key?
1265  {
1266  //The certificate does not contain any valid public key
1267  return ERROR_BAD_CERTIFICATE;
1268  }
1269 
1270  //Successful processing
1271  return NO_ERROR;
1272 }
1273 
1274 
1275 /**
1276  * @brief Retrieve the signature algorithm used to sign the certificate
1277  * @param[in] certInfo X.509 certificate
1278  * @param[out] signScheme Signature scheme
1279  * @return Error code
1280  **/
1281 
1283  TlsSignatureScheme *signScheme)
1284 {
1285  size_t oidLen;
1286  const uint8_t *oid;
1287 
1288  //Check parameters
1289  if(certInfo == NULL || signScheme == NULL)
1290  return ERROR_INVALID_PARAMETER;
1291 
1292  //Point to the signature algorithm
1293  oid = certInfo->signatureAlgo.oid.value;
1294  oidLen = certInfo->signatureAlgo.oid.length;
1295 
1296 #if (RSA_SUPPORT == ENABLED)
1297  //RSA signature algorithm?
1299  {
1300  //RSA with MD5 signature algorithm
1302  }
1304  {
1305  //RSA with SHA-1 signature algorithm
1307  }
1309  {
1310  //RSA with SHA-256 signature algorithm
1312  }
1314  {
1315  //RSA with SHA-384 signature algorithm
1317  }
1319  {
1320  //RSA with SHA-512 signature algorithm
1322  }
1323  else
1324 #endif
1325 #if (RSA_SUPPORT == ENABLED && X509_RSA_PSS_SUPPORT == ENABLED)
1326  //RSA-PSS signature algorithm?
1327  if(OID_COMP(oid, oidLen, RSASSA_PSS_OID) == 0)
1328  {
1329  //Get the OID of the hash algorithm
1332 
1333 #if (SHA256_SUPPORT == ENABLED)
1334  //SHA-256 hash algorithm identifier?
1335  if(OID_COMP(oid, oidLen, SHA256_OID) == 0)
1336  {
1337  //RSA-PSS with SHA-256 signature algorithm
1338  *signScheme = TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256;
1339  }
1340  else
1341 #endif
1342 #if (SHA384_SUPPORT == ENABLED)
1343  //SHA-384 hash algorithm identifier?
1344  if(OID_COMP(oid, oidLen, SHA384_OID) == 0)
1345  {
1346  //RSA-PSS with SHA-384 signature algorithm
1347  *signScheme = TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384;
1348  }
1349  else
1350 #endif
1351 #if (SHA512_SUPPORT == ENABLED)
1352  //SHA-512 hash algorithm identifier?
1353  if(OID_COMP(oid, oidLen, SHA512_OID) == 0)
1354  {
1355  //RSA-PSS with SHA-512 signature algorithm
1356  *signScheme = TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512;
1357  }
1358  else
1359 #endif
1360  //Unknown hash algorithm identifier?
1361  {
1362  //The signature algorithm is not supported
1363  return ERROR_BAD_CERTIFICATE;
1364  }
1365  }
1366  else
1367 #endif
1368 #if (DSA_SUPPORT == ENABLED)
1369  //DSA signature algorithm?
1370  if(OID_COMP(oid, oidLen, DSA_WITH_SHA1_OID) == 0)
1371  {
1372  //DSA with SHA-1 signature algorithm
1374  }
1375  else if(OID_COMP(oid, oidLen, DSA_WITH_SHA224_OID) == 0)
1376  {
1377  //DSA with SHA-224 signature algorithm
1379  }
1380  else if(OID_COMP(oid, oidLen, DSA_WITH_SHA256_OID) == 0)
1381  {
1382  //DSA with SHA-256 signature algorithm
1384  }
1385  else
1386 #endif
1387 #if (ECDSA_SUPPORT == ENABLED)
1388  //ECDSA signature algorithm?
1390  {
1391  //ECDSA with SHA-1 signature algorithm
1393  }
1394  else if(OID_COMP(oid, oidLen, ECDSA_WITH_SHA224_OID) == 0)
1395  {
1396  //ECDSA with SHA-224 signature algorithm
1398  }
1399  else if(OID_COMP(oid, oidLen, ECDSA_WITH_SHA256_OID) == 0)
1400  {
1401  //ECDSA with SHA-256 signature algorithm
1403  }
1404  else if(OID_COMP(oid, oidLen, ECDSA_WITH_SHA384_OID) == 0)
1405  {
1406  //ECDSA with SHA-384 signature algorithm
1408  }
1409  else if(OID_COMP(oid, oidLen, ECDSA_WITH_SHA512_OID) == 0)
1410  {
1411  //ECDSA with SHA-512 signature algorithm
1413  }
1414  else
1415 #endif
1416 #if (SM2_SUPPORT == ENABLED)
1417  //SM2 signature algorithm?
1418  if(OID_COMP(oid, oidLen, SM2_WITH_SM3_OID) == 0)
1419  {
1420  //SM2 with SM3 signature algorithm
1421  *signScheme = TLS_SIGN_SCHEME_SM2SIG_SM3;
1422  }
1423  else
1424 #endif
1425 #if (ED25519_SUPPORT == ENABLED)
1426  //Ed25519 signature algorithm?
1427  if(OID_COMP(oid, oidLen, ED25519_OID) == 0)
1428  {
1429  //Ed25519 signature algorithm
1430  *signScheme = TLS_SIGN_SCHEME_ED25519;
1431  }
1432  else
1433 #endif
1434 #if (ED448_SUPPORT == ENABLED)
1435  //Ed448 signature algorithm?
1436  if(OID_COMP(oid, oidLen, ED448_OID) == 0)
1437  {
1438  //Ed448 signature algorithm
1439  *signScheme = TLS_SIGN_SCHEME_ED448;
1440  }
1441  else
1442 #endif
1443  //Unknown signature algorithm?
1444  {
1445  //The signature algorithm is not supported
1446  return ERROR_BAD_CERTIFICATE;
1447  }
1448 
1449  //Successful processing
1450  return NO_ERROR;
1451 }
1452 
1453 
1454 /**
1455  * @brief Extract the subject public key from the received certificate
1456  * @param[in] context Pointer to the TLS context
1457  * @param[in] subjectPublicKeyInfo Pointer to the subject's public key
1458  * @return Error code
1459  **/
1460 
1462  const X509SubjectPublicKeyInfo *subjectPublicKeyInfo)
1463 {
1464  error_t error;
1465  size_t oidLen;
1466  const uint8_t *oid;
1467 
1468  //Retrieve public key identifier
1469  oid = subjectPublicKeyInfo->oid.value;
1470  oidLen = subjectPublicKeyInfo->oid.length;
1471 
1472 #if (TLS_RSA_SIGN_SUPPORT == ENABLED || TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
1473  //RSA public key?
1474  if(OID_COMP(oid, oidLen, RSA_ENCRYPTION_OID) == 0 ||
1476  {
1477  uint_t k;
1478 
1479  //Import the RSA public key
1480  error = x509ImportRsaPublicKey(&context->peerRsaPublicKey,
1481  subjectPublicKeyInfo);
1482 
1483  //Check status code
1484  if(!error)
1485  {
1486  //Get the length of the modulus, in bits
1487  k = mpiGetBitLength(&context->peerRsaPublicKey.n);
1488 
1489  //Applications should also enforce minimum and maximum key sizes (refer
1490  //to RFC 8446, appendix C.2)
1491  if(k < TLS_MIN_RSA_MODULUS_SIZE || k > TLS_MAX_RSA_MODULUS_SIZE)
1492  {
1493  //Report an error
1494  error = ERROR_BAD_CERTIFICATE;
1495  }
1496  }
1497 
1498  //Check status code
1499  if(!error)
1500  {
1501  //RSA or RSA-PSS certificate?
1503  {
1504  //The certificate contains a valid RSA public key
1505  context->peerCertType = TLS_CERT_RSA_SIGN;
1506  }
1507  else if(OID_COMP(oid, oidLen, RSASSA_PSS_OID) == 0)
1508  {
1509  //The certificate contains a valid RSA-PSS public key
1510  context->peerCertType = TLS_CERT_RSA_PSS_SIGN;
1511  }
1512  else
1513  {
1514  //Just for sanity
1515  error = ERROR_BAD_CERTIFICATE;
1516  }
1517  }
1518  }
1519  else
1520 #endif
1521 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
1522  //DSA public key?
1523  if(OID_COMP(oid, oidLen, DSA_OID) == 0)
1524  {
1525  uint_t k;
1526 
1527  //Import the DSA public key
1528  error = x509ImportDsaPublicKey(&context->peerDsaPublicKey,
1529  subjectPublicKeyInfo);
1530 
1531  //Check status code
1532  if(!error)
1533  {
1534  //Get the length of the prime modulus, in bits
1535  k = mpiGetBitLength(&context->peerDsaPublicKey.params.p);
1536 
1537  //Make sure the prime modulus is acceptable
1538  if(k < TLS_MIN_DSA_MODULUS_SIZE || k > TLS_MAX_DSA_MODULUS_SIZE)
1539  {
1540  //Report an error
1541  error = ERROR_BAD_CERTIFICATE;
1542  }
1543  }
1544 
1545  //Check status code
1546  if(!error)
1547  {
1548  //The certificate contains a valid DSA public key
1549  context->peerCertType = TLS_CERT_DSS_SIGN;
1550  }
1551  }
1552  else
1553 #endif
1554 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED || TLS_SM2_SIGN_SUPPORT == ENABLED)
1555  //EC public key?
1556  if(OID_COMP(oid, oidLen, EC_PUBLIC_KEY_OID) == 0)
1557  {
1558  //Import the EC public key
1559  error = x509ImportEcPublicKey(&context->peerEcPublicKey,
1560  subjectPublicKeyInfo);
1561 
1562  //Check status code
1563  if(!error)
1564  {
1565  //SM2 elliptic curve?
1566  if(OID_COMP(subjectPublicKeyInfo->ecParams.namedCurve.value,
1567  subjectPublicKeyInfo->ecParams.namedCurve.length, SM2_OID) == 0)
1568  {
1569  //The certificate contains a valid SM2 public key
1570  context->peerCertType = TLS_CERT_SM2_SIGN;
1571  }
1572  else
1573  {
1574  //The certificate contains a valid EC public key
1575  context->peerCertType = TLS_CERT_ECDSA_SIGN;
1576  }
1577  }
1578  }
1579  else
1580 #endif
1581 #if (TLS_ED25519_SIGN_SUPPORT == ENABLED || TLS_ED448_SIGN_SUPPORT == ENABLED)
1582  //Ed25519 or Ed448 public key?
1583  if(OID_COMP(oid, oidLen, ED25519_OID) == 0 ||
1584  OID_COMP(oid, oidLen, ED448_OID) == 0)
1585  {
1586  //Import the EdDSA public key
1587  error = x509ImportEddsaPublicKey(&context->peerEddsaPublicKey,
1588  subjectPublicKeyInfo);
1589 
1590  //Check status code
1591  if(!error)
1592  {
1593  //Ed25519 or Ed448 certificate?
1594  if(OID_COMP(oid, oidLen, ED25519_OID) == 0)
1595  {
1596  //The certificate contains a valid Ed25519 public key
1597  context->peerCertType = TLS_CERT_ED25519_SIGN;
1598  }
1599  else if(OID_COMP(oid, oidLen, ED448_OID) == 0)
1600  {
1601  //The certificate contains a valid Ed448 public key
1602  context->peerCertType = TLS_CERT_ED448_SIGN;
1603  }
1604  else
1605  {
1606  //Just for sanity
1607  error = ERROR_BAD_CERTIFICATE;
1608  }
1609  }
1610  }
1611  else
1612 #endif
1613  //Invalid public key?
1614  {
1615  //The certificate does not contain any valid public key
1617  }
1618 
1619 #if (TLS_CLIENT_SUPPORT == ENABLED)
1620  //Check status code
1621  if(!error)
1622  {
1623  //Client mode?
1624  if(context->entity == TLS_CONNECTION_END_CLIENT)
1625  {
1626  //Check key exchange method
1627  if(context->keyExchMethod == TLS_KEY_EXCH_RSA ||
1628  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
1629  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
1630  context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
1631  {
1632  //The client expects a valid RSA certificate whenever the agreed-
1633  //upon key exchange method uses RSA certificates for authentication
1634  if(context->peerCertType != TLS_CERT_RSA_SIGN &&
1635  context->peerCertType != TLS_CERT_RSA_PSS_SIGN)
1636  {
1638  }
1639  }
1640  else if(context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS)
1641  {
1642  //The client expects a valid DSA certificate whenever the agreed-
1643  //upon key exchange method uses DSA certificates for authentication
1644  if(context->peerCertType != TLS_CERT_DSS_SIGN)
1645  {
1647  }
1648  }
1649  else if(context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA)
1650  {
1651  //The client expects a valid ECDSA certificate whenever the agreed-
1652  //upon key exchange method uses ECDSA certificates for authentication
1653  if(context->peerCertType != TLS_CERT_ECDSA_SIGN &&
1654  context->peerCertType != TLS_CERT_ED25519_SIGN &&
1655  context->peerCertType != TLS_CERT_ED448_SIGN)
1656  {
1658  }
1659  }
1660  else if(context->keyExchMethod == TLS13_KEY_EXCH_DHE ||
1661  context->keyExchMethod == TLS13_KEY_EXCH_ECDHE ||
1662  context->keyExchMethod == TLS13_KEY_EXCH_MLKEM ||
1663  context->keyExchMethod == TLS13_KEY_EXCH_HYBRID)
1664  {
1665  //TLS 1.3 removes support for DSA certificates
1666  if(context->peerCertType != TLS_CERT_RSA_SIGN &&
1667  context->peerCertType != TLS_CERT_RSA_PSS_SIGN &&
1668  context->peerCertType != TLS_CERT_ECDSA_SIGN &&
1669  context->peerCertType != TLS_CERT_SM2_SIGN &&
1670  context->peerCertType != TLS_CERT_ED25519_SIGN &&
1671  context->peerCertType != TLS_CERT_ED448_SIGN)
1672  {
1674  }
1675  }
1676  else
1677  {
1678  //Just for sanity
1680  }
1681  }
1682  }
1683 #endif
1684 
1685  //Return status code
1686  return error;
1687 }
1688 
1689 
1690 /**
1691  * @brief Check certificate key usage
1692  * @param[in] certInfo Pointer to the X.509 certificate
1693  * @param[in] entity Specifies whether this entity is considered a client or a server
1694  * @param[in] keyExchMethod TLS key exchange method
1695  * @return Error code
1696  **/
1697 
1699  TlsConnectionEnd entity, TlsKeyExchMethod keyExchMethod)
1700 {
1701 #if (TLS_CERT_KEY_USAGE_SUPPORT == ENABLED)
1702  error_t error;
1703  const X509KeyUsage *keyUsage;
1704  const X509ExtendedKeyUsage *extKeyUsage;
1705 
1706  //Initialize status code
1707  error = NO_ERROR;
1708 
1709  //Point to the KeyUsage extension
1710  keyUsage = &certInfo->tbsCert.extensions.keyUsage;
1711 
1712  //Check if the KeyUsage extension is present
1713  if(keyUsage->bitmap != 0)
1714  {
1715  //Check whether TLS operates as a client or a server
1716  if(entity == TLS_CONNECTION_END_CLIENT)
1717  {
1718  //Check key exchange method
1719  if(keyExchMethod == TLS_KEY_EXCH_RSA ||
1720  keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
1721  {
1722  //The keyEncipherment bit must be asserted when the subject public
1723  //key is used for enciphering private or secret keys
1724  if((keyUsage->bitmap & X509_KEY_USAGE_KEY_ENCIPHERMENT) == 0)
1725  {
1726  error = ERROR_BAD_CERTIFICATE;
1727  }
1728  }
1729  else if(keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
1730  keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
1731  keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
1732  keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
1733  keyExchMethod == TLS13_KEY_EXCH_DHE ||
1734  keyExchMethod == TLS13_KEY_EXCH_ECDHE ||
1735  keyExchMethod == TLS13_KEY_EXCH_MLKEM ||
1736  keyExchMethod == TLS13_KEY_EXCH_HYBRID)
1737  {
1738  //The digitalSignature bit must be asserted when the subject public
1739  //key is used for verifying digital signatures, other than signatures
1740  //on certificates and CRLs
1741  if((keyUsage->bitmap & X509_KEY_USAGE_DIGITAL_SIGNATURE) == 0)
1742  {
1743  error = ERROR_BAD_CERTIFICATE;
1744  }
1745  }
1746  else
1747  {
1748  //Just for sanity
1749  }
1750  }
1751  else
1752  {
1753  //The digitalSignature bit must be asserted when the subject public
1754  //key is used for verifying digital signatures, other than signatures
1755  //on certificates and CRLs
1756  if((keyUsage->bitmap & X509_KEY_USAGE_DIGITAL_SIGNATURE) == 0)
1757  {
1758  error = ERROR_BAD_CERTIFICATE;
1759  }
1760  }
1761  }
1762 
1763  //Point to the ExtendedKeyUsage extension
1764  extKeyUsage = &certInfo->tbsCert.extensions.extKeyUsage;
1765 
1766  //Check if the ExtendedKeyUsage extension is present
1767  if(extKeyUsage->bitmap != 0)
1768  {
1769  //Check whether TLS operates as a client or a server
1770  if(entity == TLS_CONNECTION_END_CLIENT)
1771  {
1772  //Make sure the certificate can be used for server authentication
1773  if((extKeyUsage->bitmap & X509_EXT_KEY_USAGE_SERVER_AUTH) == 0)
1774  {
1775  error = ERROR_BAD_CERTIFICATE;
1776  }
1777  }
1778  else
1779  {
1780  //Make sure the certificate can be used for client authentication
1781  if((extKeyUsage->bitmap & X509_EXT_KEY_USAGE_CLIENT_AUTH) == 0)
1782  {
1783  error = ERROR_BAD_CERTIFICATE;
1784  }
1785  }
1786  }
1787 
1788  //Return status code
1789  return error;
1790 #else
1791  //Do not check key usage
1792  return NO_ERROR;
1793 #endif
1794 }
1795 
1796 #endif
#define tlsAllocMem(size)
Definition: tls.h:867
@ TLS_SIGN_ALGO_DSA
Definition: tls.h:1257
TLS helper functions.
X.509 certificate parsing.
error_t x509ImportEcPublicKey(EcPublicKey *publicKey, const X509SubjectPublicKeyInfo *publicKeyInfo)
Import an EC public key.
int bool_t
Definition: compiler_port.h:61
TLS cipher suites.
X509SignAlgoId signatureAlgo
Definition: x509_common.h:1121
error_t x509ValidateCertificate(const X509CertInfo *certInfo, const X509CertInfo *issuerCertInfo, uint_t pathLen)
X.509 certificate validation.
const uint8_t DSA_WITH_SHA224_OID[9]
Definition: dsa.c:55
X509TbsCertificate tbsCert
Definition: x509_common.h:1120
@ TLS13_KEY_EXCH_MLKEM
Definition: tls.h:1182
const uint8_t MD5_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:59
const uint8_t SHA512_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:69
#define TLS_MAX_DSA_MODULUS_SIZE
Definition: tls.h:808
__weak_func error_t tlsParseCertificateList(TlsContext *context, const uint8_t *p, size_t length)
Parse certificate chain.
@ ERROR_UNKNOWN_CERTIFICATE
Definition: error.h:238
const EcCurve * tlsGetCurve(TlsContext *context, uint16_t namedCurve)
Get the EC domain parameters that match the specified named curve.
Definition: tls_misc.c:1251
X509Extensions extensions
Definition: x509_common.h:1110
error_t x509ParseSubjectPublicKeyInfo(const uint8_t *data, size_t length, size_t *totalLength, X509SubjectPublicKeyInfo *publicKeyInfo)
Parse SubjectPublicKeyInfo structure.
X509OctetString hashAlgo
Definition: x509_common.h:1076
OID (Object Identifier)
uint8_t p
Definition: ndp.h:300
X509KeyUsage keyUsage
Definition: x509_common.h:1055
TlsConnectionEnd
TLS connection end.
Definition: tls.h:989
X509OctetString oid
Definition: x509_common.h:840
#define TRUE
Definition: os_port.h:50
error_t x509ParseCertificate(const uint8_t *data, size_t length, X509CertInfo *certInfo)
Parse a X.509 certificate.
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_CURVE_SM2
Definition: tls.h:1445
const uint8_t EC_PUBLIC_KEY_OID[7]
Definition: ec.c:44
TlsCertificateType type
End entity certificate type.
Definition: tls.h:2125
X509EcParameters ecParams
Definition: x509_common.h:850
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512
Definition: tls.h:1282
@ TLS_HASH_ALGO_SHA1
Definition: tls.h:1239
X509ExtendedKeyUsage extKeyUsage
Definition: x509_common.h:1056
error_t asn1DumpObject(const uint8_t *data, size_t length, uint_t level)
Display an ASN.1 data object.
Definition: asn1.c:856
@ ERROR_HANDSHAKE_FAILED
Definition: error.h:234
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
@ TLS13_KEY_EXCH_ECDHE
Definition: tls.h:1181
@ TLS_CERT_DSS_SIGN
Definition: tls.h:1213
@ X509_EXT_KEY_USAGE_CLIENT_AUTH
Definition: x509_common.h:545
@ ERROR_UNSUPPORTED_CERTIFICATE
Definition: error.h:237
@ TLS_SIGN_SCHEME_ED25519
Definition: tls.h:1291
error_t tlsReadSubjectPublicKey(TlsContext *context, const X509SubjectPublicKeyInfo *subjectPublicKeyInfo)
Extract the subject public key from the received certificate.
const uint8_t RSASSA_PSS_OID[9]
Definition: rsa.c:85
error_t x509ImportDsaPublicKey(DsaPublicKey *publicKey, const X509SubjectPublicKeyInfo *publicKeyInfo)
Import a DSA public key.
const uint8_t ECDSA_WITH_SHA256_OID[8]
Definition: ecdsa.c:49
@ ERROR_CERTIFICATE_REVOKED
Definition: error.h:240
uint8_t oid[]
Definition: lldp_tlv.h:300
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384
Definition: tls.h:1281
error_t tls13ParseCertExtensions(const uint8_t *p, size_t length, size_t *consumed)
Parse certificate extensions.
Definition: tls13_misc.c:1469
@ TLS_HASH_ALGO_SHA224
Definition: tls.h:1240
@ TLS_KEY_EXCH_RSA
Definition: tls.h:1162
const uint8_t DSA_OID[7]
Definition: dsa.c:51
bool_t x509CompareName(const uint8_t *name1, size_t nameLen1, const uint8_t *name2, size_t nameLen2)
Compare distinguished names.
const uint8_t SHA384_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:67
error_t tlsValidateCertificate(TlsContext *context, const X509CertInfo *certInfo, uint_t pathLen, const char_t *subjectName)
Verify certificate against root CAs.
@ TLS_HASH_ALGO_SHA512
Definition: tls.h:1243
@ TLS_KEY_EXCH_ECDHE_ECDSA
Definition: tls.h:1171
@ TLS_KEY_EXCH_ECDHE_RSA
Definition: tls.h:1169
size_t certChainLen
Length of the certificate chain.
Definition: tls.h:2121
#define FALSE
Definition: os_port.h:46
error_t pemImportCertificate(const char_t *input, size_t inputLen, uint8_t *output, size_t *outputLen, size_t *consumed)
Decode a PEM file containing a certificate.
Definition: pem_import.c:61
PEM file import functions.
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
TlsCertAuthorities
Definition: tls.h:1599
#define osMemcpy(dest, src, length)
Definition: os_port.h:144
X.509 certificate.
Definition: x509_common.h:1119
#define TlsContext
Definition: tls.h:36
error_t
Error codes.
Definition: error.h:43
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256
Definition: tls.h:1280
EC parameters.
Definition: x509_common.h:818
@ TLS_CERT_ED25519_SIGN
Definition: tls.h:1226
@ TLS_CONNECTION_END_SERVER
Definition: tls.h:991
TlsKeyExchMethod
Key exchange methods.
Definition: tls.h:1160
Extended Key Usage extension.
Definition: x509_common.h:896
#define TLS_VERSION_1_2
Definition: tls.h:96
@ TLS_GROUP_NONE
Definition: tls.h:1404
X509Version version
Definition: x509_common.h:1103
@ TLS13_KEY_EXCH_DHE
Definition: tls.h:1180
const uint8_t SHA256_OID[9]
Definition: sha256.c:80
#define TLS_VERSION_1_3
Definition: tls.h:97
@ TLS_HASH_ALGO_SHA384
Definition: tls.h:1242
error_t x509ImportEddsaPublicKey(EddsaPublicKey *publicKey, const X509SubjectPublicKeyInfo *publicKeyInfo)
Import an EdDSA public key.
@ TLS_CERT_RSA_PSS_SIGN
Definition: tls.h:1224
TlsSignatureScheme signScheme
Signature scheme used to sign the end entity certificate.
Definition: tls.h:2126
@ X509_VERSION_3
Definition: x509_common.h:516
const uint8_t ECDSA_WITH_SHA384_OID[8]
Definition: ecdsa.c:51
X509OctetString raw
Definition: x509_common.h:839
@ ERROR_BAD_CERTIFICATE
Definition: error.h:236
TlsSignSchemeList
Definition: tls.h:1577
@ TLS_HASH_ALGO_SHA256
Definition: tls.h:1241
@ TLS_CERT_ED448_SIGN
Definition: tls.h:1227
error_t tlsFormatRawPublicKey(TlsContext *context, uint8_t *p, size_t *written)
Format raw public key.
@ X509_EXT_KEY_USAGE_SERVER_AUTH
Definition: x509_common.h:544
@ TLS_CERT_RSA_SIGN
Definition: tls.h:1212
@ X509_KEY_USAGE_DIGITAL_SIGNATURE
Definition: x509_common.h:526
TlsNamedGroup tlsGetNamedCurve(const uint8_t *oid, size_t length)
Get the named curve that matches the specified OID.
Definition: tls_misc.c:1405
uint8_t length
Definition: tcp.h:375
const uint8_t SM2_WITH_SM3_OID[8]
Definition: sm2.c:45
X509OctetString oid
Definition: x509_common.h:1089
@ ERROR_MESSAGE_TOO_LONG
Definition: error.h:137
error_t tls13FormatCertExtensions(uint8_t *p, size_t *written)
Format certificate extensions.
Definition: tls13_misc.c:1440
uint16_t bitmap
Definition: x509_common.h:887
const uint8_t ECDSA_WITH_SHA1_OID[7]
Definition: ecdsa.c:45
@ TLS_CERT_SM2_SIGN
Definition: tls.h:1225
const uint8_t ECDSA_WITH_SHA224_OID[8]
Definition: ecdsa.c:47
error_t tlsCheckKeyUsage(const X509CertInfo *certInfo, TlsConnectionEnd entity, TlsKeyExchMethod keyExchMethod)
Check certificate key usage.
const uint8_t SHA256_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:65
X509OctetString namedCurve
Definition: x509_common.h:819
TlsCertificateType
Certificate types.
Definition: tls.h:1210
const uint8_t ED448_OID[3]
Definition: ec_curves.c:114
error_t tlsFormatCertificateList(TlsContext *context, uint8_t *p, size_t *written)
Format certificate chain.
error_t x509CheckNameConstraints(const char_t *subjectName, const X509CertInfo *certInfo)
Check name constraints.
uint_t mpiGetBitLength(const Mpi *a)
Get the actual length in bits.
Definition: mpi.c:254
@ TLS_HASH_ALGO_MD5
Definition: tls.h:1238
Certificate descriptor.
Definition: tls.h:2119
const uint8_t ECDSA_WITH_SHA512_OID[8]
Definition: ecdsa.c:53
const uint8_t ED25519_OID[3]
Definition: ec_curves.c:112
const uint8_t RSA_ENCRYPTION_OID[9]
Definition: rsa.c:54
@ TLS_KEY_EXCH_RSA_PSK
Definition: tls.h:1174
#define ntohs(value)
Definition: cpu_endian.h:421
#define TRACE_WARNING(...)
Definition: debug.h:93
char char_t
Definition: compiler_port.h:55
#define TLS_VERSION_1_1
Definition: tls.h:95
error_t tlsParseRawPublicKey(TlsContext *context, const uint8_t *p, size_t length)
Parse raw public key.
#define OID_COMP(oid1, oidLen1, oid2)
Definition: oid.h:42
error_t x509ImportRsaPublicKey(RsaPublicKey *publicKey, const X509SubjectPublicKeyInfo *publicKeyInfo)
Import an RSA public key.
uint8_t m
Definition: ndp.h:304
uint8_t n
Subject Public Key Information extension.
Definition: x509_common.h:838
@ TLS_SIGN_SCHEME_SM2SIG_SM3
Definition: tls.h:1290
@ TLS_SIGN_SCHEME_ED448
Definition: tls.h:1292
@ TLS13_KEY_EXCH_HYBRID
Definition: tls.h:1183
#define TLS_MAX_RSA_MODULUS_SIZE
Definition: tls.h:794
error_t tlsGetCertificateSignAlgo(const X509CertInfo *certInfo, TlsSignatureScheme *signScheme)
Retrieve the signature algorithm used to sign the certificate.
@ ERROR_CERTIFICATE_EXPIRED
Definition: error.h:239
#define LOAD24BE(p)
Definition: cpu_endian.h:197
const uint8_t DSA_WITH_SHA1_OID[7]
Definition: dsa.c:53
@ TLS_CONNECTION_END_CLIENT
Definition: tls.h:990
const uint8_t DSA_WITH_SHA256_OID[9]
Definition: dsa.c:57
X.509 certificate handling.
Helper functions for signature generation and verification.
uint8_t oidLen
Definition: lldp_tlv.h:299
TLS (Transport Layer Security)
const uint8_t SHA512_OID[9]
Definition: sha512.c:97
@ TLS_SIGN_ALGO_RSA
Definition: tls.h:1256
X.509 certificate validation.
#define STORE24BE(a, p)
Definition: cpu_endian.h:273
@ TLS_CERT_ECDSA_SIGN
Definition: tls.h:1219
@ TLS_KEY_EXCH_DHE_DSS
Definition: tls.h:1166
@ ERROR_UNKNOWN_CA
Definition: error.h:241
error_t x509CheckSubjectName(const X509CertInfo *certInfo, const char_t *fqdn)
Check whether the certificate matches the specified FQDN.
const char_t * certChain
End entity certificate chain (PEM format)
Definition: tls.h:2120
const uint8_t * value
Definition: x509_common.h:702
#define TLS_SIGN_ALGO(signScheme)
Definition: tls_sign_misc.h:38
error_t tlsGetCertificateType(const X509CertInfo *certInfo, TlsCertificateType *certType, TlsNamedGroup *namedCurve)
Retrieve the certificate type.
Parsing of ASN.1 encoded keys.
TlsNamedGroup
Named groups.
Definition: tls.h:1403
TlsSignatureScheme
Signature schemes.
Definition: tls.h:1271
@ ERROR_DECODING_FAILED
Definition: error.h:242
unsigned int uint_t
Definition: compiler_port.h:57
#define LOAD16BE(p)
Definition: cpu_endian.h:186
TlsSupportedGroupList
Definition: tls.h:1689
#define tlsFreeMem(p)
Definition: tls.h:872
@ X509_KEY_USAGE_KEY_ENCIPHERMENT
Definition: x509_common.h:528
X509SubjectPublicKeyInfo subjectPublicKeyInfo
Definition: x509_common.h:1109
const uint8_t SHA384_OID[9]
Definition: sha384.c:47
@ TLS_SIGN_ALGO_ECDSA
Definition: tls.h:1258
X509RsaPssParameters rsaPssParams
Definition: x509_common.h:1091
@ TLS_KEY_EXCH_DHE_RSA
Definition: tls.h:1164
#define TLS_SIGN_SCHEME(signAlgo, hashAlgo)
Definition: tls.h:963
const uint8_t SHA1_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:61
X509OctetString raw
Definition: x509_common.h:724
TlsNamedGroup namedCurve
Named curve used to generate the EC public key.
Definition: tls.h:2127
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
ASN.1 (Abstract Syntax Notation One)
Key Usage extension.
Definition: x509_common.h:885
const uint8_t SM2_OID[8]
Definition: ec_curves.c:106