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-2024 Oryx Embedded SARL. All rights reserved.
10  *
11  * This file is part of CycloneSSL Open.
12  *
13  * This program is free software; you can redistribute it and/or
14  * modify it under the terms of the GNU General Public License
15  * as published by the Free Software Foundation; either version 2
16  * of the License, or (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software Foundation,
25  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26  *
27  * @author Oryx Embedded SARL (www.oryx-embedded.com)
28  * @version 2.4.4
29  **/
30 
31 //Switch to the appropriate trace level
32 #define TRACE_LEVEL TLS_TRACE_LEVEL
33 
34 //Dependencies
35 #include "tls.h"
36 #include "tls_cipher_suites.h"
37 #include "tls_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  error = ERROR_DECODING_FAILED;
360  break;
361  }
362 
363  //Check certificate key usage
364  error = tlsCheckKeyUsage(certInfo, context->entity,
365  context->keyExchMethod);
366  //Any error to report?
367  if(error)
368  break;
369 
370  //Extract the public key from the end-user certificate
371  error = tlsReadSubjectPublicKey(context,
372  &certInfo->tbsCert.subjectPublicKeyInfo);
373  //Any error to report?
374  if(error)
375  break;
376 
377 #if (TLS_CLIENT_SUPPORT == ENABLED)
378  //Client mode?
379  if(context->entity == TLS_CONNECTION_END_CLIENT)
380  {
381  TlsCertificateType certType;
382  TlsNamedGroup namedCurve;
383 
384  //Retrieve the type of the X.509 certificate
385  error = tlsGetCertificateType(certInfo, &certType, &namedCurve);
386  //Unsupported certificate?
387  if(error)
388  break;
389 
390  //Version of TLS prior to TLS 1.3?
391  if(context->version <= TLS_VERSION_1_2)
392  {
393  //ECDSA certificate?
394  if(certType == TLS_CERT_ECDSA_SIGN)
395  {
396  //Make sure the elliptic curve is supported
397  if(tlsGetCurveInfo(context, namedCurve) == NULL)
398  {
399  error = ERROR_BAD_CERTIFICATE;
400  break;
401  }
402  }
403  }
404 
405  //Point to the subject name
406  subjectName = context->serverName;
407 
408  //Check the subject name in the server certificate against the actual
409  //FQDN name that is being requested
410  error = x509CheckSubjectName(certInfo, subjectName);
411  //Any error to report?
412  if(error)
413  {
414  //Debug message
415  TRACE_WARNING("Server name mismatch!\r\n");
416 
417  //Report an error
418  error = ERROR_BAD_CERTIFICATE;
419  break;
420  }
421  }
422  else
423 #endif
424  //Server mode?
425  {
426  //Do not check name constraints
427  subjectName = NULL;
428  }
429 
430  //Check if the end-user certificate can be matched with a trusted CA
431  certValidResult = tlsValidateCertificate(context, certInfo, 0,
432  subjectName);
433 
434  //Check validation result
435  if(certValidResult != NO_ERROR && certValidResult != ERROR_UNKNOWN_CA)
436  {
437  //The certificate is not valid
438  error = certValidResult;
439  break;
440  }
441 
442  //Next certificate
443  p += n;
444  length -= n;
445 
446 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
447  //TLS 1.3 currently selected?
448  if(context->version == TLS_VERSION_1_3)
449  {
450  //Parse the list of extensions for the current CertificateEntry
451  error = tls13ParseCertExtensions(p, length, &n);
452  //Any error to report?
453  if(error)
454  break;
455 
456  //Point to the next field
457  p += n;
458  //Remaining bytes to process
459  length -= n;
460  }
461 #endif
462 
463  //PKIX path validation
464  for(i = 0; length > 0; i++)
465  {
466  //Each intermediate certificate is preceded by a 3-byte length field
467  if(length < 3)
468  {
469  //Report an error
470  error = ERROR_DECODING_FAILED;
471  break;
472  }
473 
474  //Get the size occupied by the certificate
475  n = LOAD24BE(p);
476  //Jump to the beginning of the DER-encoded certificate
477  p += 3;
478  //Remaining bytes to process
479  length -= 3;
480 
481  //Malformed Certificate message?
482  if(n == 0 || n > length)
483  {
484  //Report an error
485  error = ERROR_DECODING_FAILED;
486  break;
487  }
488 
489  //Display ASN.1 structure
490  error = asn1DumpObject(p, n, 0);
491  //Any error to report?
492  if(error)
493  break;
494 
495  //Parse intermediate certificate
496  error = x509ParseCertificate(p, n, issuerCertInfo);
497  //Failed to parse the X.509 certificate?
498  if(error)
499  {
500  //Report an error
501  error = ERROR_DECODING_FAILED;
502  break;
503  }
504 
505  //Certificate chain validation in progress?
506  if(certValidResult == ERROR_UNKNOWN_CA)
507  {
508  //Validate current certificate
509  error = x509ValidateCertificate(certInfo, issuerCertInfo, i);
510  //Certificate validation failed?
511  if(error)
512  break;
513 
514  //Check name constraints
515  error = x509CheckNameConstraints(subjectName, issuerCertInfo);
516  //Should the application reject the certificate?
517  if(error)
518  {
519  //Report an error
520  error = ERROR_BAD_CERTIFICATE;
521  break;
522  }
523 
524  //Check the version of the certificate
525  if(issuerCertInfo->tbsCert.version < X509_VERSION_3)
526  {
527  //Conforming implementations may choose to reject all version 1
528  //and version 2 intermediate certificates (refer to RFC 5280,
529  //section 6.1.4)
530  error = ERROR_BAD_CERTIFICATE;
531  break;
532  }
533 
534  //Check if the intermediate certificate can be matched with a
535  //trusted CA
536  certValidResult = tlsValidateCertificate(context, issuerCertInfo,
537  i, subjectName);
538 
539  //Check validation result
540  if(certValidResult != NO_ERROR && certValidResult != ERROR_UNKNOWN_CA)
541  {
542  //The certificate is not valid
543  error = certValidResult;
544  break;
545  }
546  }
547 
548  //Keep track of the issuer certificate
549  *certInfo = *issuerCertInfo;
550 
551  //Next certificate
552  p += n;
553  length -= n;
554 
555 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
556  //TLS 1.3 currently selected?
557  if(context->version == TLS_VERSION_1_3)
558  {
559  //Parse the list of extensions for the current CertificateEntry
560  error = tls13ParseCertExtensions(p, length, &n);
561  //Any error to report?
562  if(error)
563  break;
564 
565  //Point to the next field
566  p += n;
567  //Remaining bytes to process
568  length -= n;
569  }
570 #endif
571  }
572 
573  //Certificate chain validation failed?
574  if(error == NO_ERROR && certValidResult != NO_ERROR)
575  {
576  //A valid certificate chain or partial chain was received, but the
577  //certificate was not accepted because the CA certificate could not
578  //be matched with a known, trusted CA
579  error = ERROR_UNKNOWN_CA;
580  }
581 
582  //End of exception handling block
583  } while(0);
584 
585  //Free previously allocated memory
586  tlsFreeMem(certInfo);
587  tlsFreeMem(issuerCertInfo);
588 
589  //Return status code
590  return error;
591 }
592 
593 
594 /**
595  * @brief Parse raw public key
596  * @param[in] context Pointer to the TLS context
597  * @param[in] p Input stream where to read the raw public key
598  * @param[in] length Number of bytes available in the input stream
599  * @return Error code
600  **/
601 
602 error_t tlsParseRawPublicKey(TlsContext *context, const uint8_t *p,
603  size_t length)
604 {
605  error_t error;
606 
607 #if (TLS_RAW_PUBLIC_KEY_SUPPORT == ENABLED)
608  //Any registered callback?
609  if(context->rpkVerifyCallback != NULL)
610  {
611  size_t n;
612  size_t rawPublicKeyLen;
613  const uint8_t *rawPublicKey;
614  X509SubjectPublicKeyInfo subjectPublicKeyInfo;
615 
616 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
617  //TLS 1.3 currently selected?
618  if(context->version == TLS_VERSION_1_3)
619  {
620  //The raw public key is preceded by a 3-byte length field
621  if(length < 3)
622  return ERROR_DECODING_FAILED;
623 
624  //Get the size occupied by the raw public key
625  rawPublicKeyLen = LOAD24BE(p);
626  //Advance data pointer
627  p += 3;
628  //Remaining bytes to process
629  length -= 3;
630 
631  //Malformed Certificate message?
632  if(length < rawPublicKeyLen)
633  return ERROR_DECODING_FAILED;
634  }
635  else
636 #endif
637  {
638  //The payload of the Certificate message contains a SubjectPublicKeyInfo
639  //structure
640  rawPublicKeyLen = length;
641  }
642 
643  //Point to the raw public key
644  rawPublicKey = p;
645 
646  //Decode the SubjectPublicKeyInfo structure
647  error = x509ParseSubjectPublicKeyInfo(rawPublicKey, rawPublicKeyLen, &n,
648  &subjectPublicKeyInfo);
649  //Any error to report?
650  if(error)
651  return error;
652 
653  //Advance data pointer
654  p += rawPublicKeyLen;
655  //Remaining bytes to process
656  length -= rawPublicKeyLen;
657 
658 #if (TLS_MAX_VERSION >= TLS_VERSION_1_3 && TLS_MIN_VERSION <= TLS_VERSION_1_3)
659  //TLS 1.3 currently selected?
660  if(context->version == TLS_VERSION_1_3)
661  {
662  //Parse the list of extensions for the current CertificateEntry
663  error = tls13ParseCertExtensions(p, length, &n);
664  //Any error to report?
665  if(error)
666  return error;
667 
668  //Advance data pointer
669  p += n;
670  //Remaining bytes to process
671  length -= n;
672  }
673 #endif
674 
675  //If the RawPublicKey certificate type was negotiated, the certificate
676  //list must contain no more than one CertificateEntry (refer to RFC 8446,
677  //section 4.4.2)
678  if(length != 0)
679  return ERROR_DECODING_FAILED;
680 
681  //Extract the public key from the SubjectPublicKeyInfo structure
682  error = tlsReadSubjectPublicKey(context, &subjectPublicKeyInfo);
683  //Any error to report?
684  if(error)
685  return error;
686 
687  //When raw public keys are used, authentication of the peer is supported
688  //only through authentication of the received SubjectPublicKeyInfo via an
689  //out-of-band method
690  error = context->rpkVerifyCallback(context, rawPublicKey,
691  rawPublicKeyLen);
692  }
693  else
694 #endif
695  {
696  //Report an error
697  error = ERROR_BAD_CERTIFICATE;
698  }
699 
700  //Return status code
701  return error;
702 }
703 
704 
705 /**
706  * @brief Check whether a certificate is acceptable
707  * @param[in] context Pointer to the TLS context
708  * @param[in] cert End entity certificate
709  * @param[in] certTypes List of supported certificate types
710  * @param[in] numCertTypes Size of the list that contains the supported
711  * certificate types
712  * @param[in] curveList List of supported elliptic curves
713  * @param[in] certSignAlgoList List of signature algorithms that may be used
714  * in X.509 certificates
715  * @param[in] certAuthorities List of trusted CA
716  * @return TRUE if the specified certificate conforms to the requirements,
717  * else FALSE
718  **/
719 
721  const TlsCertDesc *cert, const uint8_t *certTypes, size_t numCertTypes,
722  const TlsSupportedGroupList *curveList,
723  const TlsSignSchemeList *certSignAlgoList,
724  const TlsCertAuthorities *certAuthorities)
725 {
726  size_t i;
727  size_t n;
728  size_t length;
729  bool_t acceptable;
730 
731  //Make sure that a valid certificate has been loaded
732  if(cert->certChain == NULL || cert->certChainLen == 0)
733  return FALSE;
734 
735  //This flag tells whether the certificate is acceptable
736  acceptable = TRUE;
737 
738 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_1)
739  //Version of TLS prior to TLS 1.2?
740  if(context->version <= TLS_VERSION_1_1)
741  {
742  //Server mode?
743  if(context->entity == TLS_CONNECTION_END_SERVER)
744  {
745  //The signing algorithm for the certificate must be the same as the
746  //algorithm for the certificate key (refer to RFC 4346, section 7.4.2)
747  if(cert->type == TLS_CERT_RSA_SIGN &&
749  {
750  acceptable = TRUE;
751  }
752  else if(cert->type == TLS_CERT_DSS_SIGN &&
754  {
755  acceptable = TRUE;
756  }
757  else if(cert->type == TLS_CERT_ECDSA_SIGN &&
759  {
760  acceptable = TRUE;
761  }
762  else
763  {
764  acceptable = FALSE;
765  }
766  }
767  }
768 #endif
769 
770 #if (TLS_MAX_VERSION >= TLS_VERSION_1_0 && TLS_MIN_VERSION <= TLS_VERSION_1_2)
771  //Version of TLS prior to TLS 1.3?
772  if(context->version <= TLS_VERSION_1_2)
773  {
774  //Filter out certificates with unsupported type
775  if(acceptable && certTypes != NULL)
776  {
777  //Loop through the list of supported certificate types
778  for(i = 0, acceptable = FALSE; i < numCertTypes && !acceptable; i++)
779  {
780  //Check certificate type
781  if(certTypes[i] == TLS_CERT_RSA_SIGN)
782  {
783  //The certificate must contain an RSA public key
784  if(cert->type == TLS_CERT_RSA_SIGN ||
785  cert->type == TLS_CERT_RSA_PSS_SIGN)
786  {
787  acceptable = TRUE;
788  }
789  }
790  else if(certTypes[i] == TLS_CERT_DSS_SIGN)
791  {
792  //The certificate must contain a DSA public key
793  if(cert->type == TLS_CERT_DSS_SIGN)
794  {
795  acceptable = TRUE;
796  }
797  }
798  else if(certTypes[i] == TLS_CERT_ECDSA_SIGN)
799  {
800  //The certificate must contain an ECDSA or EdDSA public key
801  if(cert->type == TLS_CERT_ECDSA_SIGN ||
802  cert->type == TLS_CERT_ED25519_SIGN ||
803  cert->type == TLS_CERT_ED448_SIGN)
804  {
805  acceptable = TRUE;
806  }
807  }
808  else
809  {
810  //Unknown certificate type
811  }
812  }
813  }
814 
815  //ECDSA certificate?
816  if(cert->type == TLS_CERT_ECDSA_SIGN)
817  {
818  //In versions of TLS prior to TLS 1.3, the EllipticCurves extension is
819  //used to negotiate ECDSA curves (refer to RFC 8446, section 4.2.7)
820  if(acceptable && curveList != NULL)
821  {
822  //Retrieve the number of items in the list
823  n = ntohs(curveList->length) / sizeof(uint16_t);
824 
825  //Loop through the list of supported elliptic curves
826  for(i = 0, acceptable = FALSE; i < n && !acceptable; i++)
827  {
828  //Check whether the elliptic curve is supported
829  if(ntohs(curveList->value[i]) == cert->namedCurve)
830  {
831  acceptable = TRUE;
832  }
833  }
834  }
835  }
836  }
837 #endif
838 
839 #if (TLS_SM2_SIGN_SUPPORT == ENABLED)
840  //SM2 certificate?
841  if(cert->type == TLS_CERT_SM2_SIGN)
842  {
843  //The signature algorithm used by the CA to sign the current certificate
844  //must be sm2sig_sm3 (refer to RFC 8998, section 3.3.3)
846  {
847  acceptable = FALSE;
848  }
849  }
850 #endif
851 
852  //Filter out certificates that are signed with an unsupported algorithm
853  if(acceptable && certSignAlgoList != NULL)
854  {
855  //Retrieve the number of items in the list
856  n = ntohs(certSignAlgoList->length) / sizeof(uint16_t);
857 
858  //Loop through the list of supported signature algorithms
859  for(i = 0, acceptable = FALSE; i < n && !acceptable; i++)
860  {
861  //The certificate must be signed using a valid algorithm
862  if(ntohs(certSignAlgoList->value[i]) == cert->signScheme)
863  {
864  acceptable = TRUE;
865  }
866  }
867  }
868 
869  //Filter out certificates that are issued by a non trusted CA
870  if(acceptable && certAuthorities != NULL)
871  {
872  //Retrieve the length of the list
873  length = ntohs(certAuthorities->length);
874 
875  //If the certificate authorities list is empty, then the client
876  //may send any certificate of the appropriate type
877  if(length > 0)
878  {
879  error_t error;
880  size_t pemCertLen;
881  const char_t *certChain;
882  size_t certChainLen;
883  uint8_t *derCert;
884  size_t derCertLen;
885  X509CertInfo *certInfo;
886 
887  //The list of acceptable certificate authorities describes the
888  //known roots CA
889  acceptable = FALSE;
890 
891  //Point to the end entity certificate
892  certChain = cert->certChain;
893  //Get the total length, in bytes, of the certificate chain
894  certChainLen = cert->certChainLen;
895 
896  //Allocate a memory buffer to store X.509 certificate info
897  certInfo = tlsAllocMem(sizeof(X509CertInfo));
898 
899  //Successful memory allocation?
900  if(certInfo != NULL)
901  {
902  //Parse the certificate chain
903  while(certChainLen > 0 && !acceptable)
904  {
905  //The first pass calculates the length of the DER-encoded
906  //certificate
907  error = pemImportCertificate(certChain, certChainLen, NULL,
908  &derCertLen, &pemCertLen);
909 
910  //Check status code
911  if(!error)
912  {
913  //Allocate a memory buffer to hold the DER-encoded certificate
914  derCert = tlsAllocMem(derCertLen);
915 
916  //Successful memory allocation?
917  if(derCert != NULL)
918  {
919  //The second pass decodes the PEM certificate
920  error = pemImportCertificate(certChain, certChainLen,
921  derCert, &derCertLen, NULL);
922 
923  //Check status code
924  if(!error)
925  {
926  //Parse X.509 certificate
927  error = x509ParseCertificate(derCert, derCertLen,
928  certInfo);
929  }
930 
931  //Check status code
932  if(!error)
933  {
934  //Parse each distinguished name of the list
935  for(i = 0; i < length; i += n + 2)
936  {
937  //Sanity check
938  if((i + 2) > length)
939  break;
940 
941  //Each distinguished name is preceded by a 2-byte
942  //length field
943  n = LOAD16BE(certAuthorities->value + i);
944 
945  //Make sure the length field is valid
946  if((i + n + 2) > length)
947  break;
948 
949  //Check if the distinguished name matches the root CA
950  if(x509CompareName(certAuthorities->value + i + 2, n,
951  certInfo->tbsCert.issuer.raw.value,
952  certInfo->tbsCert.issuer.raw.length))
953  {
954  acceptable = TRUE;
955  break;
956  }
957  }
958  }
959 
960  //Free previously allocated memory
961  tlsFreeMem(derCert);
962  }
963 
964  //Advance read pointer
965  certChain += pemCertLen;
966  certChainLen -= pemCertLen;
967  }
968  else
969  {
970  //No more CA certificates in the list
971  break;
972  }
973  }
974 
975  //Free previously allocated memory
976  tlsFreeMem(certInfo);
977  }
978  }
979  }
980 
981  //The return value specifies whether all the criteria were matched
982  return acceptable;
983 }
984 
985 
986 /**
987  * @brief Verify certificate against root CAs
988  * @param[in] context Pointer to the TLS context
989  * @param[in] certInfo X.509 certificate to be verified
990  * @param[in] pathLen Certificate path length
991  * @param[in] subjectName Subject name (optional parameter)
992  * @return Error code
993  **/
994 
996  const X509CertInfo *certInfo, uint_t pathLen, const char_t *subjectName)
997 {
998  error_t error;
999  size_t pemCertLen;
1000  const char_t *trustedCaList;
1001  size_t trustedCaListLen;
1002  uint8_t *derCert;
1003  size_t derCertLen;
1004  X509CertInfo *caCertInfo;
1005 
1006  //Initialize status code
1007  error = ERROR_UNKNOWN_CA;
1008 
1009  //Any registered callback?
1010  if(context->certVerifyCallback != NULL)
1011  {
1012  //Invoke user callback function
1013  error = context->certVerifyCallback(context, certInfo, pathLen,
1014  context->certVerifyParam);
1015  }
1016 
1017  //Check status code
1018  if(error == NO_ERROR)
1019  {
1020  //The certificate is valid
1021  }
1022  else if(error == ERROR_UNKNOWN_CA)
1023  {
1024  //Check whether the certificate should be checked against root CAs
1025  if(context->trustedCaListLen > 0)
1026  {
1027  //Point to the first trusted CA certificate
1028  trustedCaList = context->trustedCaList;
1029  //Get the total length, in bytes, of the trusted CA list
1030  trustedCaListLen = context->trustedCaListLen;
1031 
1032  //Allocate a memory buffer to store X.509 certificate info
1033  caCertInfo = tlsAllocMem(sizeof(X509CertInfo));
1034 
1035  //Successful memory allocation?
1036  if(caCertInfo != NULL)
1037  {
1038  //Loop through the list of trusted CA certificates
1039  while(trustedCaListLen > 0 && error == ERROR_UNKNOWN_CA)
1040  {
1041  //The first pass calculates the length of the DER-encoded
1042  //certificate
1043  error = pemImportCertificate(trustedCaList, trustedCaListLen,
1044  NULL, &derCertLen, &pemCertLen);
1045 
1046  //Check status code
1047  if(!error)
1048  {
1049  //Allocate a memory buffer to hold the DER-encoded certificate
1050  derCert = tlsAllocMem(derCertLen);
1051 
1052  //Successful memory allocation?
1053  if(derCert != NULL)
1054  {
1055  //The second pass decodes the PEM certificate
1056  error = pemImportCertificate(trustedCaList,
1057  trustedCaListLen, derCert, &derCertLen, NULL);
1058 
1059  //Check status code
1060  if(!error)
1061  {
1062  //Parse X.509 certificate
1063  error = x509ParseCertificate(derCert, derCertLen,
1064  caCertInfo);
1065  }
1066 
1067  //Check status code
1068  if(!error)
1069  {
1070  //Validate the certificate with the current CA
1071  error = x509ValidateCertificate(certInfo, caCertInfo,
1072  pathLen);
1073  }
1074 
1075  //Check status code
1076  if(!error)
1077  {
1078  //Check name constraints
1079  error = x509CheckNameConstraints(subjectName, caCertInfo);
1080  }
1081 
1082  //Check status code
1083  if(!error)
1084  {
1085  //The certificate is issued by a trusted CA
1086  error = NO_ERROR;
1087  }
1088  else
1089  {
1090  //The certificate cannot be matched with the current CA
1091  error = ERROR_UNKNOWN_CA;
1092  }
1093 
1094  //Free previously allocated memory
1095  tlsFreeMem(derCert);
1096  }
1097  else
1098  {
1099  //Failed to allocate memory
1100  error = ERROR_OUT_OF_MEMORY;
1101  }
1102 
1103  //Advance read pointer
1104  trustedCaList += pemCertLen;
1105  trustedCaListLen -= pemCertLen;
1106  }
1107  else
1108  {
1109  //No more CA certificates in the list
1110  trustedCaListLen = 0;
1111  error = ERROR_UNKNOWN_CA;
1112  }
1113  }
1114 
1115  //Free previously allocated memory
1116  tlsFreeMem(caCertInfo);
1117  }
1118  else
1119  {
1120  //Failed to allocate memory
1121  error = ERROR_OUT_OF_MEMORY;
1122  }
1123  }
1124  else
1125  {
1126  //Do not check the certificate against root CAs
1127  error = NO_ERROR;
1128  }
1129  }
1130  else if(error == ERROR_BAD_CERTIFICATE ||
1131  error == ERROR_UNSUPPORTED_CERTIFICATE ||
1132  error == ERROR_UNKNOWN_CERTIFICATE ||
1133  error == ERROR_CERTIFICATE_REVOKED ||
1134  error == ERROR_CERTIFICATE_EXPIRED ||
1135  error == ERROR_HANDSHAKE_FAILED)
1136  {
1137  //The certificate is not valid
1138  }
1139  else
1140  {
1141  //Report an error
1142  error = ERROR_BAD_CERTIFICATE;
1143  }
1144 
1145  //Return status code
1146  return error;
1147 }
1148 
1149 
1150 /**
1151  * @brief Retrieve the certificate type
1152  * @param[in] certInfo X.509 certificate
1153  * @param[out] certType Certificate type
1154  * @param[out] namedCurve Elliptic curve (only for ECDSA certificates)
1155  * @return Error code
1156  **/
1157 
1159  TlsCertificateType *certType, TlsNamedGroup *namedCurve)
1160 {
1161  size_t oidLen;
1162  const uint8_t *oid;
1163 
1164  //Check parameters
1165  if(certInfo == NULL || certType == NULL || namedCurve == NULL)
1166  return ERROR_INVALID_PARAMETER;
1167 
1168  //Point to the public key identifier
1171 
1172 #if (TLS_RSA_SIGN_SUPPORT == ENABLED || TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
1173  //RSA public key?
1175  {
1176  //Save certificate type
1177  *certType = TLS_CERT_RSA_SIGN;
1178  //No named curve applicable
1179  *namedCurve = TLS_GROUP_NONE;
1180  }
1181  else
1182 #endif
1183 #if (TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
1184  //RSA-PSS public key?
1186  {
1187  //Save certificate type
1188  *certType = TLS_CERT_RSA_PSS_SIGN;
1189  //No named curve applicable
1190  *namedCurve = TLS_GROUP_NONE;
1191  }
1192  else
1193 #endif
1194 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
1195  //DSA public key?
1196  if(!oidComp(oid, oidLen, DSA_OID, sizeof(DSA_OID)))
1197  {
1198  //Save certificate type
1199  *certType = TLS_CERT_DSS_SIGN;
1200  //No named curve applicable
1201  *namedCurve = TLS_GROUP_NONE;
1202  }
1203  else
1204 #endif
1205 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED || TLS_SM2_SIGN_SUPPORT == ENABLED)
1206  //EC public key?
1208  {
1209  const X509EcParameters *params;
1210 
1211  //Point to the EC parameters
1212  params = &certInfo->tbsCert.subjectPublicKeyInfo.ecParams;
1213 
1214  //SM2 elliptic curve?
1215  if(!oidComp(params->namedCurve.value, params->namedCurve.length,
1216  SM2_OID, sizeof(SM2_OID)))
1217  {
1218  //Save certificate type
1219  *certType = TLS_CERT_SM2_SIGN;
1220 
1221  //The only valid elliptic curve for the SM2 signature algorithm is
1222  //curveSM2 (refer to RFC 8446, section 3.2.1)
1223  *namedCurve = TLS_GROUP_CURVE_SM2;
1224  }
1225  else
1226  {
1227  //Save certificate type
1228  *certType = TLS_CERT_ECDSA_SIGN;
1229 
1230  //Retrieve the named curve that has been used to generate the EC
1231  //public key
1232  *namedCurve = tlsGetNamedCurve(params->namedCurve.value,
1233  params->namedCurve.length);
1234  }
1235  }
1236  else
1237 #endif
1238 #if (TLS_ED25519_SIGN_SUPPORT == ENABLED)
1239  //Ed25519 public key?
1240  if(!oidComp(oid, oidLen, ED25519_OID, sizeof(ED25519_OID)))
1241  {
1242  //Save certificate type
1243  *certType = TLS_CERT_ED25519_SIGN;
1244  //No named curve applicable
1245  *namedCurve = TLS_GROUP_NONE;
1246  }
1247  else
1248 #endif
1249 #if (TLS_ED448_SIGN_SUPPORT == ENABLED)
1250  //Ed448 public key?
1251  if(!oidComp(oid, oidLen, ED448_OID, sizeof(ED448_OID)))
1252  {
1253  //Save certificate type
1254  *certType = TLS_CERT_ED448_SIGN;
1255  //No named curve applicable
1256  *namedCurve = TLS_GROUP_NONE;
1257  }
1258  else
1259 #endif
1260  //Invalid public key?
1261  {
1262  //The certificate does not contain any valid public key
1263  return ERROR_BAD_CERTIFICATE;
1264  }
1265 
1266  //Successful processing
1267  return NO_ERROR;
1268 }
1269 
1270 
1271 /**
1272  * @brief Retrieve the signature algorithm used to sign the certificate
1273  * @param[in] certInfo X.509 certificate
1274  * @param[out] signScheme Signature scheme
1275  * @return Error code
1276  **/
1277 
1279  TlsSignatureScheme *signScheme)
1280 {
1281  size_t oidLen;
1282  const uint8_t *oid;
1283 
1284  //Check parameters
1285  if(certInfo == NULL || signScheme == NULL)
1286  return ERROR_INVALID_PARAMETER;
1287 
1288  //Point to the signature algorithm
1289  oid = certInfo->signatureAlgo.oid.value;
1290  oidLen = certInfo->signatureAlgo.oid.length;
1291 
1292 #if (RSA_SUPPORT == ENABLED)
1293  //RSA signature algorithm?
1295  sizeof(MD5_WITH_RSA_ENCRYPTION_OID)))
1296  {
1297  //RSA with MD5 signature algorithm
1299  }
1302  {
1303  //RSA with SHA-1 signature algorithm
1305  }
1308  {
1309  //RSA with SHA-256 signature algorithm
1311  }
1314  {
1315  //RSA with SHA-384 signature algorithm
1317  }
1320  {
1321  //RSA with SHA-512 signature algorithm
1323  }
1324  else
1325 #endif
1326 #if (RSA_SUPPORT == ENABLED && X509_RSA_PSS_SUPPORT == ENABLED)
1327  //RSA-PSS signature algorithm?
1329  {
1330  //Get the OID of the hash algorithm
1333 
1334 #if (SHA256_SUPPORT == ENABLED)
1335  //SHA-256 hash algorithm identifier?
1336  if(!oidComp(oid, oidLen, SHA256_OID, sizeof(SHA256_OID)))
1337  {
1338  //RSA-PSS with SHA-256 signature algorithm
1339  *signScheme = TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256;
1340  }
1341  else
1342 #endif
1343 #if (SHA384_SUPPORT == ENABLED)
1344  //SHA-384 hash algorithm identifier?
1345  if(!oidComp(oid, oidLen, SHA384_OID, sizeof(SHA384_OID)))
1346  {
1347  //RSA-PSS with SHA-384 signature algorithm
1348  *signScheme = TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384;
1349  }
1350  else
1351 #endif
1352 #if (SHA512_SUPPORT == ENABLED)
1353  //SHA-512 hash algorithm identifier?
1354  if(!oidComp(oid, oidLen, SHA512_OID, sizeof(SHA512_OID)))
1355  {
1356  //RSA-PSS with SHA-512 signature algorithm
1357  *signScheme = TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512;
1358  }
1359  else
1360 #endif
1361  //Unknown hash algorithm identifier?
1362  {
1363  //The signature algorithm is not supported
1364  return ERROR_BAD_CERTIFICATE;
1365  }
1366  }
1367  else
1368 #endif
1369 #if (DSA_SUPPORT == ENABLED)
1370  //DSA signature algorithm?
1372  sizeof(DSA_WITH_SHA1_OID)))
1373  {
1374  //DSA with SHA-1 signature algorithm
1376  }
1378  sizeof(DSA_WITH_SHA224_OID)))
1379  {
1380  //DSA with SHA-224 signature algorithm
1382  }
1384  sizeof(DSA_WITH_SHA256_OID)))
1385  {
1386  //DSA with SHA-256 signature algorithm
1388  }
1389  else
1390 #endif
1391 #if (ECDSA_SUPPORT == ENABLED)
1392  //ECDSA signature algorithm?
1394  sizeof(ECDSA_WITH_SHA1_OID)))
1395  {
1396  //ECDSA with SHA-1 signature algorithm
1398  }
1400  sizeof(ECDSA_WITH_SHA224_OID)))
1401  {
1402  //ECDSA with SHA-224 signature algorithm
1404  }
1406  sizeof(ECDSA_WITH_SHA256_OID)))
1407  {
1408  //ECDSA with SHA-256 signature algorithm
1410  }
1412  sizeof(ECDSA_WITH_SHA384_OID)))
1413  {
1414  //ECDSA with SHA-384 signature algorithm
1416  }
1418  sizeof(ECDSA_WITH_SHA512_OID)))
1419  {
1420  //ECDSA with SHA-512 signature algorithm
1422  }
1423  else
1424 #endif
1425 #if (SM2_SUPPORT == ENABLED)
1426  //SM2 signature algorithm?
1428  {
1429  //SM2 with SM3 signature algorithm
1430  *signScheme = TLS_SIGN_SCHEME_SM2SIG_SM3;
1431  }
1432  else
1433 #endif
1434 #if (ED25519_SUPPORT == ENABLED)
1435  //Ed25519 signature algorithm?
1436  if(!oidComp(oid, oidLen, ED25519_OID, sizeof(ED25519_OID)))
1437  {
1438  //Ed25519 signature algorithm
1439  *signScheme = TLS_SIGN_SCHEME_ED25519;
1440  }
1441  else
1442 #endif
1443 #if (ED448_SUPPORT == ENABLED)
1444  //Ed448 signature algorithm?
1445  if(!oidComp(oid, oidLen, ED448_OID, sizeof(ED448_OID)))
1446  {
1447  //Ed448 signature algorithm
1448  *signScheme = TLS_SIGN_SCHEME_ED448;
1449  }
1450  else
1451 #endif
1452  //Unknown signature algorithm?
1453  {
1454  //The signature algorithm is not supported
1455  return ERROR_BAD_CERTIFICATE;
1456  }
1457 
1458  //Successful processing
1459  return NO_ERROR;
1460 }
1461 
1462 
1463 /**
1464  * @brief Extract the subject public key from the received certificate
1465  * @param[in] context Pointer to the TLS context
1466  * @param[in] subjectPublicKeyInfo Pointer to the subject's public key
1467  * @return Error code
1468  **/
1469 
1471  const X509SubjectPublicKeyInfo *subjectPublicKeyInfo)
1472 {
1473  error_t error;
1474  size_t oidLen;
1475  const uint8_t *oid;
1476 
1477  //Retrieve public key identifier
1478  oid = subjectPublicKeyInfo->oid.value;
1479  oidLen = subjectPublicKeyInfo->oid.length;
1480 
1481 #if (TLS_RSA_SIGN_SUPPORT == ENABLED || TLS_RSA_PSS_SIGN_SUPPORT == ENABLED)
1482  //RSA public key?
1485  {
1486  uint_t k;
1487 
1488  //Import the RSA public key
1489  error = x509ImportRsaPublicKey(subjectPublicKeyInfo,
1490  &context->peerRsaPublicKey);
1491 
1492  //Check status code
1493  if(!error)
1494  {
1495  //Get the length of the modulus, in bits
1496  k = mpiGetBitLength(&context->peerRsaPublicKey.n);
1497 
1498  //Applications should also enforce minimum and maximum key sizes (refer
1499  //to RFC 8446, appendix C.2)
1500  if(k < TLS_MIN_RSA_MODULUS_SIZE || k > TLS_MAX_RSA_MODULUS_SIZE)
1501  {
1502  //Report an error
1503  error = ERROR_BAD_CERTIFICATE;
1504  }
1505  }
1506 
1507  //Check status code
1508  if(!error)
1509  {
1510  //RSA or RSA-PSS certificate?
1512  {
1513  //The certificate contains a valid RSA public key
1514  context->peerCertType = TLS_CERT_RSA_SIGN;
1515  }
1516  else if(!oidComp(oid, oidLen, RSASSA_PSS_OID, sizeof(RSASSA_PSS_OID)))
1517  {
1518  //The certificate contains a valid RSA-PSS public key
1519  context->peerCertType = TLS_CERT_RSA_PSS_SIGN;
1520  }
1521  else
1522  {
1523  //Just for sanity
1524  error = ERROR_BAD_CERTIFICATE;
1525  }
1526  }
1527  }
1528  else
1529 #endif
1530 #if (TLS_DSA_SIGN_SUPPORT == ENABLED)
1531  //DSA public key?
1532  if(!oidComp(oid, oidLen, DSA_OID, sizeof(DSA_OID)))
1533  {
1534  uint_t k;
1535 
1536  //Import the DSA public key
1537  error = x509ImportDsaPublicKey(subjectPublicKeyInfo,
1538  &context->peerDsaPublicKey);
1539 
1540  //Check status code
1541  if(!error)
1542  {
1543  //Get the length of the prime modulus, in bits
1544  k = mpiGetBitLength(&context->peerDsaPublicKey.params.p);
1545 
1546  //Make sure the prime modulus is acceptable
1547  if(k < TLS_MIN_DSA_MODULUS_SIZE || k > TLS_MAX_DSA_MODULUS_SIZE)
1548  {
1549  //Report an error
1550  error = ERROR_BAD_CERTIFICATE;
1551  }
1552  }
1553 
1554  //Check status code
1555  if(!error)
1556  {
1557  //The certificate contains a valid DSA public key
1558  context->peerCertType = TLS_CERT_DSS_SIGN;
1559  }
1560  }
1561  else
1562 #endif
1563 #if (TLS_ECDSA_SIGN_SUPPORT == ENABLED || TLS_SM2_SIGN_SUPPORT == ENABLED)
1564  //EC public key?
1566  {
1567  const EcCurveInfo *curveInfo;
1568 
1569  //Retrieve EC domain parameters
1570  curveInfo = x509GetCurveInfo(subjectPublicKeyInfo->ecParams.namedCurve.value,
1571  subjectPublicKeyInfo->ecParams.namedCurve.length);
1572 
1573  //Make sure the specified elliptic curve is supported
1574  if(curveInfo != NULL)
1575  {
1576  //Load EC domain parameters
1577  error = ecLoadDomainParameters(&context->peerEcParams, curveInfo);
1578 
1579  //Check status code
1580  if(!error)
1581  {
1582  //Retrieve the EC public key
1583  error = ecImport(&context->peerEcParams, &context->peerEcPublicKey.q,
1584  subjectPublicKeyInfo->ecPublicKey.q.value,
1585  subjectPublicKeyInfo->ecPublicKey.q.length);
1586  }
1587  }
1588  else
1589  {
1590  //The specified elliptic curve is not supported
1591  error = ERROR_BAD_CERTIFICATE;
1592  }
1593 
1594  //Check status code
1595  if(!error)
1596  {
1597  //SM2 elliptic curve?
1598  if(!oidComp(subjectPublicKeyInfo->ecParams.namedCurve.value,
1599  subjectPublicKeyInfo->ecParams.namedCurve.length, SM2_OID,
1600  sizeof(SM2_OID)))
1601  {
1602  //The certificate contains a valid SM2 public key
1603  context->peerCertType = TLS_CERT_SM2_SIGN;
1604  }
1605  else
1606  {
1607  //The certificate contains a valid EC public key
1608  context->peerCertType = TLS_CERT_ECDSA_SIGN;
1609  }
1610  }
1611  }
1612  else
1613 #endif
1614 #if (TLS_ED25519_SIGN_SUPPORT == ENABLED || TLS_ED448_SIGN_SUPPORT == ENABLED)
1615  //Ed25519 or Ed448 public key?
1616  if(!oidComp(oid, oidLen, ED25519_OID, sizeof(ED25519_OID)) ||
1617  !oidComp(oid, oidLen, ED448_OID, sizeof(ED448_OID)))
1618  {
1619  const EcCurveInfo *curveInfo;
1620 
1621  //Retrieve EC domain parameters
1622  curveInfo = x509GetCurveInfo(oid, oidLen);
1623 
1624  //Make sure the specified elliptic curve is supported
1625  if(curveInfo != NULL)
1626  {
1627  //Load EC domain parameters
1628  error = ecLoadDomainParameters(&context->peerEcParams, curveInfo);
1629 
1630  //Check status code
1631  if(!error)
1632  {
1633  //Retrieve the EC public key
1634  error = ecImport(&context->peerEcParams, &context->peerEcPublicKey.q,
1635  subjectPublicKeyInfo->ecPublicKey.q.value,
1636  subjectPublicKeyInfo->ecPublicKey.q.length);
1637  }
1638  }
1639  else
1640  {
1641  //The specified elliptic curve is not supported
1642  error = ERROR_BAD_CERTIFICATE;
1643  }
1644 
1645  //Check status code
1646  if(!error)
1647  {
1648  //Ed25519 or Ed448 certificate?
1649  if(!oidComp(oid, oidLen, ED25519_OID, sizeof(ED25519_OID)))
1650  {
1651  //The certificate contains a valid Ed25519 public key
1652  context->peerCertType = TLS_CERT_ED25519_SIGN;
1653  }
1654  else if(!oidComp(oid, oidLen, ED448_OID, sizeof(ED448_OID)))
1655  {
1656  //The certificate contains a valid Ed448 public key
1657  context->peerCertType = TLS_CERT_ED448_SIGN;
1658  }
1659  else
1660  {
1661  //Just for sanity
1662  error = ERROR_BAD_CERTIFICATE;
1663  }
1664  }
1665  }
1666  else
1667 #endif
1668  //Invalid public key?
1669  {
1670  //The certificate does not contain any valid public key
1672  }
1673 
1674 #if (TLS_CLIENT_SUPPORT == ENABLED)
1675  //Check status code
1676  if(!error)
1677  {
1678  //Client mode?
1679  if(context->entity == TLS_CONNECTION_END_CLIENT)
1680  {
1681  //Check key exchange method
1682  if(context->keyExchMethod == TLS_KEY_EXCH_RSA ||
1683  context->keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
1684  context->keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
1685  context->keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
1686  {
1687  //The client expects a valid RSA certificate whenever the agreed-
1688  //upon key exchange method uses RSA certificates for authentication
1689  if(context->peerCertType != TLS_CERT_RSA_SIGN &&
1690  context->peerCertType != TLS_CERT_RSA_PSS_SIGN)
1691  {
1693  }
1694  }
1695  else if(context->keyExchMethod == TLS_KEY_EXCH_DHE_DSS)
1696  {
1697  //The client expects a valid DSA certificate whenever the agreed-
1698  //upon key exchange method uses DSA certificates for authentication
1699  if(context->peerCertType != TLS_CERT_DSS_SIGN)
1700  {
1702  }
1703  }
1704  else if(context->keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA)
1705  {
1706  //The client expects a valid ECDSA certificate whenever the agreed-
1707  //upon key exchange method uses ECDSA certificates for authentication
1708  if(context->peerCertType != TLS_CERT_ECDSA_SIGN &&
1709  context->peerCertType != TLS_CERT_ED25519_SIGN &&
1710  context->peerCertType != TLS_CERT_ED448_SIGN)
1711  {
1713  }
1714  }
1715  else if(context->keyExchMethod == TLS13_KEY_EXCH_DHE ||
1716  context->keyExchMethod == TLS13_KEY_EXCH_ECDHE ||
1717  context->keyExchMethod == TLS13_KEY_EXCH_HYBRID)
1718  {
1719  //TLS 1.3 removes support for DSA certificates
1720  if(context->peerCertType != TLS_CERT_RSA_SIGN &&
1721  context->peerCertType != TLS_CERT_RSA_PSS_SIGN &&
1722  context->peerCertType != TLS_CERT_ECDSA_SIGN &&
1723  context->peerCertType != TLS_CERT_SM2_SIGN &&
1724  context->peerCertType != TLS_CERT_ED25519_SIGN &&
1725  context->peerCertType != TLS_CERT_ED448_SIGN)
1726  {
1728  }
1729  }
1730  else
1731  {
1732  //Just for sanity
1734  }
1735  }
1736  }
1737 #endif
1738 
1739  //Return status code
1740  return error;
1741 }
1742 
1743 
1744 /**
1745  * @brief Check certificate key usage
1746  * @param[in] certInfo Pointer to the X.509 certificate
1747  * @param[in] entity Specifies whether this entity is considered a client or a server
1748  * @param[in] keyExchMethod TLS key exchange method
1749  * @return Error code
1750  **/
1751 
1753  TlsConnectionEnd entity, TlsKeyExchMethod keyExchMethod)
1754 {
1755 #if (TLS_CERT_KEY_USAGE_SUPPORT == ENABLED)
1756  error_t error;
1757  const X509KeyUsage *keyUsage;
1758  const X509ExtendedKeyUsage *extKeyUsage;
1759 
1760  //Initialize status code
1761  error = NO_ERROR;
1762 
1763  //Point to the KeyUsage extension
1764  keyUsage = &certInfo->tbsCert.extensions.keyUsage;
1765 
1766  //Check if the KeyUsage extension is present
1767  if(keyUsage->bitmap != 0)
1768  {
1769  //Check whether TLS operates as a client or a server
1770  if(entity == TLS_CONNECTION_END_CLIENT)
1771  {
1772  //Check key exchange method
1773  if(keyExchMethod == TLS_KEY_EXCH_RSA ||
1774  keyExchMethod == TLS_KEY_EXCH_RSA_PSK)
1775  {
1776  //The keyEncipherment bit must be asserted when the subject public
1777  //key is used for enciphering private or secret keys
1778  if((keyUsage->bitmap & X509_KEY_USAGE_KEY_ENCIPHERMENT) == 0)
1779  {
1780  error = ERROR_BAD_CERTIFICATE;
1781  }
1782  }
1783  else if(keyExchMethod == TLS_KEY_EXCH_DHE_RSA ||
1784  keyExchMethod == TLS_KEY_EXCH_DHE_DSS ||
1785  keyExchMethod == TLS_KEY_EXCH_ECDHE_RSA ||
1786  keyExchMethod == TLS_KEY_EXCH_ECDHE_ECDSA ||
1787  keyExchMethod == TLS13_KEY_EXCH_DHE ||
1788  keyExchMethod == TLS13_KEY_EXCH_ECDHE ||
1789  keyExchMethod == TLS13_KEY_EXCH_HYBRID)
1790  {
1791  //The digitalSignature bit must be asserted when the subject public
1792  //key is used for verifying digital signatures, other than signatures
1793  //on certificates and CRLs
1794  if((keyUsage->bitmap & X509_KEY_USAGE_DIGITAL_SIGNATURE) == 0)
1795  {
1796  error = ERROR_BAD_CERTIFICATE;
1797  }
1798  }
1799  else
1800  {
1801  //Just for sanity
1802  }
1803  }
1804  else
1805  {
1806  //The digitalSignature bit must be asserted when the subject public
1807  //key is used for verifying digital signatures, other than signatures
1808  //on certificates and CRLs
1809  if((keyUsage->bitmap & X509_KEY_USAGE_DIGITAL_SIGNATURE) == 0)
1810  {
1811  error = ERROR_BAD_CERTIFICATE;
1812  }
1813  }
1814  }
1815 
1816  //Point to the ExtendedKeyUsage extension
1817  extKeyUsage = &certInfo->tbsCert.extensions.extKeyUsage;
1818 
1819  //Check if the ExtendedKeyUsage extension is present
1820  if(extKeyUsage->bitmap != 0)
1821  {
1822  //Check whether TLS operates as a client or a server
1823  if(entity == TLS_CONNECTION_END_CLIENT)
1824  {
1825  //Make sure the certificate can be used for server authentication
1826  if((extKeyUsage->bitmap & X509_EXT_KEY_USAGE_SERVER_AUTH) == 0)
1827  {
1828  error = ERROR_BAD_CERTIFICATE;
1829  }
1830  }
1831  else
1832  {
1833  //Make sure the certificate can be used for client authentication
1834  if((extKeyUsage->bitmap & X509_EXT_KEY_USAGE_CLIENT_AUTH) == 0)
1835  {
1836  error = ERROR_BAD_CERTIFICATE;
1837  }
1838  }
1839  }
1840 
1841  //Return status code
1842  return error;
1843 #else
1844  //Do not check key usage
1845  return NO_ERROR;
1846 #endif
1847 }
1848 
1849 #endif
#define tlsAllocMem(size)
Definition: tls.h:853
@ TLS_SIGN_ALGO_DSA
Definition: tls.h:1233
TLS helper functions.
X.509 certificate parsing.
int bool_t
Definition: compiler_port.h:53
TLS cipher suites.
X509SignAlgoId signatureAlgo
Definition: x509_common.h:1073
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:1072
const EcCurveInfo * x509GetCurveInfo(const uint8_t *oid, size_t length)
Get the elliptic curve that matches the specified OID.
Definition: x509_common.c:910
const uint8_t MD5_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:62
const uint8_t SHA512_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:72
error_t x509ImportRsaPublicKey(const X509SubjectPublicKeyInfo *publicKeyInfo, RsaPublicKey *publicKey)
Import an RSA public key.
#define TLS_MAX_DSA_MODULUS_SIZE
Definition: tls.h:794
__weak_func error_t tlsParseCertificateList(TlsContext *context, const uint8_t *p, size_t length)
Parse certificate chain.
@ ERROR_UNKNOWN_CERTIFICATE
Definition: error.h:237
error_t ecImport(const EcDomainParameters *params, EcPoint *r, const uint8_t *data, size_t length)
Convert an octet string to an EC point.
Definition: ec.c:365
X509Extensions extensions
Definition: x509_common.h:1062
error_t x509ParseSubjectPublicKeyInfo(const uint8_t *data, size_t length, size_t *totalLength, X509SubjectPublicKeyInfo *publicKeyInfo)
Parse SubjectPublicKeyInfo structure.
X509OctetString hashAlgo
Definition: x509_common.h:1028
OID (Object Identifier)
uint8_t p
Definition: ndp.h:300
X509KeyUsage keyUsage
Definition: x509_common.h:1007
TlsConnectionEnd
TLS connection end.
Definition: tls.h:967
X509OctetString oid
Definition: x509_common.h:792
#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:1411
const uint8_t EC_PUBLIC_KEY_OID[7]
Definition: ec.c:43
TlsCertificateType type
End entity certificate type.
Definition: tls.h:2087
X509EcParameters ecParams
Definition: x509_common.h:802
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA512
Definition: tls.h:1258
@ TLS_HASH_ALGO_SHA1
Definition: tls.h:1215
X509ExtendedKeyUsage extKeyUsage
Definition: x509_common.h:1008
error_t asn1DumpObject(const uint8_t *data, size_t length, uint_t level)
Display an ASN.1 data object.
Definition: asn1.c:706
@ ERROR_HANDSHAKE_FAILED
Definition: error.h:233
@ ERROR_OUT_OF_MEMORY
Definition: error.h:63
@ TLS13_KEY_EXCH_ECDHE
Definition: tls.h:1159
@ TLS_CERT_DSS_SIGN
Definition: tls.h:1189
@ X509_EXT_KEY_USAGE_CLIENT_AUTH
Definition: x509_common.h:497
@ ERROR_UNSUPPORTED_CERTIFICATE
Definition: error.h:236
@ TLS_SIGN_SCHEME_ED25519
Definition: tls.h:1267
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:88
const uint8_t ECDSA_WITH_SHA256_OID[8]
Definition: ecdsa.c:49
@ ERROR_CERTIFICATE_REVOKED
Definition: error.h:239
int_t oidComp(const uint8_t *oid1, size_t oidLen1, const uint8_t *oid2, size_t oidLen2)
Compare object identifiers.
Definition: oid.c:103
uint8_t oid[]
Definition: lldp_tlv.h:300
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA384
Definition: tls.h:1257
error_t tls13ParseCertExtensions(const uint8_t *p, size_t length, size_t *consumed)
Parse certificate extensions.
Definition: tls13_misc.c:1181
@ TLS_HASH_ALGO_SHA224
Definition: tls.h:1216
@ TLS_KEY_EXCH_RSA
Definition: tls.h:1140
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:70
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:1219
@ TLS_KEY_EXCH_ECDHE_ECDSA
Definition: tls.h:1149
error_t ecLoadDomainParameters(EcDomainParameters *params, const EcCurveInfo *curveInfo)
Load EC domain parameters.
Definition: ec.c:90
@ TLS_KEY_EXCH_ECDHE_RSA
Definition: tls.h:1147
size_t certChainLen
Length of the certificate chain.
Definition: tls.h:2083
#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
Elliptic curve parameters.
Definition: ec_curves.h:302
PEM file import functions.
@ ERROR_INVALID_PARAMETER
Invalid parameter.
Definition: error.h:47
TlsCertAuthorities
Definition: tls.h:1561
#define osMemcpy(dest, src, length)
Definition: os_port.h:141
error_t x509ImportDsaPublicKey(const X509SubjectPublicKeyInfo *publicKeyInfo, DsaPublicKey *publicKey)
Import a DSA public key.
X.509 certificate.
Definition: x509_common.h:1071
#define TlsContext
Definition: tls.h:36
error_t
Error codes.
Definition: error.h:43
@ TLS_SIGN_SCHEME_RSA_PSS_PSS_SHA256
Definition: tls.h:1256
EC parameters.
Definition: x509_common.h:770
@ TLS_CERT_ED25519_SIGN
Definition: tls.h:1202
@ TLS_CONNECTION_END_SERVER
Definition: tls.h:969
TlsKeyExchMethod
Key exchange methods.
Definition: tls.h:1138
Extended Key Usage extension.
Definition: x509_common.h:848
#define TLS_VERSION_1_2
Definition: tls.h:96
@ TLS_GROUP_NONE
Definition: tls.h:1370
X509Version version
Definition: x509_common.h:1055
@ TLS13_KEY_EXCH_DHE
Definition: tls.h:1158
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:1218
@ TLS_CERT_RSA_PSS_SIGN
Definition: tls.h:1200
TlsSignatureScheme signScheme
Signature scheme used to sign the end entity certificate.
Definition: tls.h:2088
@ X509_VERSION_3
Definition: x509_common.h:468
const uint8_t ECDSA_WITH_SHA384_OID[8]
Definition: ecdsa.c:51
X509OctetString raw
Definition: x509_common.h:791
@ ERROR_BAD_CERTIFICATE
Definition: error.h:235
TlsSignSchemeList
Definition: tls.h:1539
@ TLS_HASH_ALGO_SHA256
Definition: tls.h:1217
@ TLS_CERT_ED448_SIGN
Definition: tls.h:1203
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:496
@ TLS_CERT_RSA_SIGN
Definition: tls.h:1188
@ X509_KEY_USAGE_DIGITAL_SIGNATURE
Definition: x509_common.h:478
TlsNamedGroup tlsGetNamedCurve(const uint8_t *oid, size_t length)
Get the named curve that matches the specified OID.
Definition: tls_misc.c:1394
uint8_t length
Definition: tcp.h:368
const uint8_t SM2_WITH_SM3_OID[8]
Definition: sm2.c:44
X509OctetString oid
Definition: x509_common.h:1041
@ ERROR_MESSAGE_TOO_LONG
Definition: error.h:136
error_t tls13FormatCertExtensions(uint8_t *p, size_t *written)
Format certificate extensions.
Definition: tls13_misc.c:1152
uint16_t bitmap
Definition: x509_common.h:839
const uint8_t ECDSA_WITH_SHA1_OID[7]
Definition: ecdsa.c:45
@ TLS_CERT_SM2_SIGN
Definition: tls.h:1201
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:68
X509OctetString namedCurve
Definition: x509_common.h:771
TlsCertificateType
Certificate types.
Definition: tls.h:1186
const uint8_t ED448_OID[3]
Definition: ec_curves.c:102
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:234
@ TLS_HASH_ALGO_MD5
Definition: tls.h:1214
Certificate descriptor.
Definition: tls.h:2081
const uint8_t ECDSA_WITH_SHA512_OID[8]
Definition: ecdsa.c:53
const uint8_t ED25519_OID[3]
Definition: ec_curves.c:100
const uint8_t RSA_ENCRYPTION_OID[9]
Definition: rsa.c:57
@ TLS_KEY_EXCH_RSA_PSK
Definition: tls.h:1152
#define ntohs(value)
Definition: cpu_endian.h:421
#define TRACE_WARNING(...)
Definition: debug.h:85
char char_t
Definition: compiler_port.h:48
#define TLS_VERSION_1_1
Definition: tls.h:95
X509OctetString q
Definition: x509_common.h:781
error_t tlsParseRawPublicKey(TlsContext *context, const uint8_t *p, size_t length)
Parse raw public key.
uint8_t m
Definition: ndp.h:304
uint8_t n
Subject Public Key Information extension.
Definition: x509_common.h:790
@ TLS_SIGN_SCHEME_SM2SIG_SM3
Definition: tls.h:1266
@ TLS_SIGN_SCHEME_ED448
Definition: tls.h:1268
@ TLS13_KEY_EXCH_HYBRID
Definition: tls.h:1160
#define TLS_MAX_RSA_MODULUS_SIZE
Definition: tls.h:780
error_t tlsGetCertificateSignAlgo(const X509CertInfo *certInfo, TlsSignatureScheme *signScheme)
Retrieve the signature algorithm used to sign the certificate.
@ ERROR_CERTIFICATE_EXPIRED
Definition: error.h:238
#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:968
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
const EcCurveInfo * tlsGetCurveInfo(TlsContext *context, uint16_t namedCurve)
Get the EC domain parameters that match the specified named curve.
Definition: tls_misc.c:1240
TLS (Transport Layer Security)
const uint8_t SHA512_OID[9]
Definition: sha512.c:97
@ TLS_SIGN_ALGO_RSA
Definition: tls.h:1232
X.509 certificate validation.
#define STORE24BE(a, p)
Definition: cpu_endian.h:273
@ TLS_CERT_ECDSA_SIGN
Definition: tls.h:1195
@ TLS_KEY_EXCH_DHE_DSS
Definition: tls.h:1144
@ ERROR_UNKNOWN_CA
Definition: error.h:240
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:2082
const uint8_t * value
Definition: x509_common.h:654
#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:1369
TlsSignatureScheme
Signature schemes.
Definition: tls.h:1247
@ ERROR_DECODING_FAILED
Definition: error.h:241
unsigned int uint_t
Definition: compiler_port.h:50
#define LOAD16BE(p)
Definition: cpu_endian.h:186
TlsSupportedGroupList
Definition: tls.h:1651
#define tlsFreeMem(p)
Definition: tls.h:858
@ X509_KEY_USAGE_KEY_ENCIPHERMENT
Definition: x509_common.h:480
X509EcPublicKey ecPublicKey
Definition: x509_common.h:803
X509SubjectPublicKeyInfo subjectPublicKeyInfo
Definition: x509_common.h:1061
const uint8_t SHA384_OID[9]
Definition: sha384.c:47
@ TLS_SIGN_ALGO_ECDSA
Definition: tls.h:1234
X509RsaPssParameters rsaPssParams
Definition: x509_common.h:1043
@ TLS_KEY_EXCH_DHE_RSA
Definition: tls.h:1142
#define TLS_SIGN_SCHEME(signAlgo, hashAlgo)
Definition: tls.h:941
const uint8_t SHA1_WITH_RSA_ENCRYPTION_OID[9]
Definition: rsa.c:64
X509OctetString raw
Definition: x509_common.h:676
TlsNamedGroup namedCurve
Named curve used to generate the EC public key.
Definition: tls.h:2089
@ NO_ERROR
Success.
Definition: error.h:44
Debugging facilities.
ASN.1 (Abstract Syntax Notation One)
Key Usage extension.
Definition: x509_common.h:837
const uint8_t SM2_OID[8]
Definition: ec_curves.c:94