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