4 * \brief X.509 certificate parsing and writing
6 * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
7 * SPDX-License-Identifier: Apache-2.0
9 * Licensed under the Apache License, Version 2.0 (the "License"); you may
10 * not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
17 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * This file is part of mbed TLS (https://tls.mbed.org)
23 #ifndef MBEDTLS_X509_CRT_H
24 #define MBEDTLS_X509_CRT_H
26 #if !defined(MBEDTLS_CONFIG_FILE)
29 #include MBEDTLS_CONFIG_FILE
36 * \addtogroup x509_module
45 * \name Structures and functions for parsing and writing X.509 certificates
50 * Container for an X.509 certificate. The certificate may be chained.
52 typedef struct mbedtls_x509_crt
54 mbedtls_x509_buf raw; /**< The raw certificate data (DER). */
55 mbedtls_x509_buf tbs; /**< The raw certificate body (DER). The part that is To Be Signed. */
57 int version; /**< The X.509 version. (1=v1, 2=v2, 3=v3) */
58 mbedtls_x509_buf serial; /**< Unique id for certificate issued by a specific CA. */
59 mbedtls_x509_buf sig_oid; /**< Signature algorithm, e.g. sha1RSA */
61 mbedtls_x509_buf issuer_raw; /**< The raw issuer data (DER). Used for quick comparison. */
62 mbedtls_x509_buf subject_raw; /**< The raw subject data (DER). Used for quick comparison. */
64 mbedtls_x509_name issuer; /**< The parsed issuer data (named information object). */
65 mbedtls_x509_name subject; /**< The parsed subject data (named information object). */
67 mbedtls_x509_time valid_from; /**< Start time of certificate validity. */
68 mbedtls_x509_time valid_to; /**< End time of certificate validity. */
70 mbedtls_pk_context pk; /**< Container for the public key context. */
72 mbedtls_x509_buf issuer_id; /**< Optional X.509 v2/v3 issuer unique identifier. */
73 mbedtls_x509_buf subject_id; /**< Optional X.509 v2/v3 subject unique identifier. */
74 mbedtls_x509_buf v3_ext; /**< Optional X.509 v3 extensions. */
75 mbedtls_x509_sequence subject_alt_names; /**< Optional list of Subject Alternative Names (Only dNSName supported). */
77 int ext_types; /**< Bit string containing detected and parsed extensions */
78 int ca_istrue; /**< Optional Basic Constraint extension value: 1 if this certificate belongs to a CA, 0 otherwise. */
79 int max_pathlen; /**< Optional Basic Constraint extension value: The maximum path length to the root certificate. Path length is 1 higher than RFC 5280 'meaning', so 1+ */
81 unsigned int key_usage; /**< Optional key usage extension value: See the values in x509.h */
83 mbedtls_x509_sequence ext_key_usage; /**< Optional list of extended key usage OIDs. */
85 unsigned char ns_cert_type; /**< Optional Netscape certificate type extension value: See the values in x509.h */
87 mbedtls_x509_buf sig; /**< Signature: hash of the tbs part signed with the private key. */
88 mbedtls_md_type_t sig_md; /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */
89 mbedtls_pk_type_t sig_pk; /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */
90 void *sig_opts; /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */
92 struct mbedtls_x509_crt *next; /**< Next certificate in the CA-chain. */
97 * Build flag from an algorithm/curve identifier (pk, md, ecp)
98 * Since 0 is always XXX_NONE, ignore it.
100 #define MBEDTLS_X509_ID_FLAG( id ) ( 1 << ( id - 1 ) )
103 * Security profile for certificate verification.
105 * All lists are bitfields, built by ORing flags from MBEDTLS_X509_ID_FLAG().
109 uint32_t allowed_mds; /**< MDs for signatures */
110 uint32_t allowed_pks; /**< PK algs for signatures */
111 uint32_t allowed_curves; /**< Elliptic curves for ECDSA */
112 uint32_t rsa_min_bitlen; /**< Minimum size for RSA keys */
114 mbedtls_x509_crt_profile;
116 #define MBEDTLS_X509_CRT_VERSION_1 0
117 #define MBEDTLS_X509_CRT_VERSION_2 1
118 #define MBEDTLS_X509_CRT_VERSION_3 2
120 #define MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN 32
121 #define MBEDTLS_X509_RFC5280_UTC_TIME_LEN 15
123 #if !defined( MBEDTLS_X509_MAX_FILE_PATH_LEN )
124 #define MBEDTLS_X509_MAX_FILE_PATH_LEN 512
128 * Container for writing a certificate (CRT)
130 typedef struct mbedtls_x509write_cert
134 mbedtls_pk_context *subject_key;
135 mbedtls_pk_context *issuer_key;
136 mbedtls_asn1_named_data *subject;
137 mbedtls_asn1_named_data *issuer;
138 mbedtls_md_type_t md_alg;
139 char not_before[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1];
140 char not_after[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1];
141 mbedtls_asn1_named_data *extensions;
143 mbedtls_x509write_cert;
145 #if defined(MBEDTLS_X509_CRT_PARSE_C)
147 * Default security profile. Should provide a good balance between security
148 * and compatibility with current deployments.
150 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default;
153 * Expected next default profile. Recommended for new deployments.
154 * Currently targets a 128-bit security level, except for RSA-2048.
156 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next;
159 * NSA Suite B profile.
161 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb;
164 * \brief Parse a single DER formatted certificate and add it
165 * to the chained list.
167 * \param chain points to the start of the chain
168 * \param buf buffer holding the certificate DER data
169 * \param buflen size of the buffer
171 * \return 0 if successful, or a specific X509 or PEM error code
173 int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,
177 * \brief Parse one or more certificates and add them
178 * to the chained list. Parses permissively. If some
179 * certificates can be parsed, the result is the number
180 * of failed certificates it encountered. If none complete
181 * correctly, the first error is returned.
183 * \param chain points to the start of the chain
184 * \param buf buffer holding the certificate data in PEM or DER format
185 * \param buflen size of the buffer
186 * (including the terminating null byte for PEM data)
188 * \return 0 if all certificates parsed successfully, a positive number
189 * if partly successful or a specific X509 or PEM error code
191 int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen );
193 #if defined(MBEDTLS_FS_IO)
195 * \brief Load one or more certificates and add them
196 * to the chained list. Parses permissively. If some
197 * certificates can be parsed, the result is the number
198 * of failed certificates it encountered. If none complete
199 * correctly, the first error is returned.
201 * \param chain points to the start of the chain
202 * \param path filename to read the certificates from
204 * \return 0 if all certificates parsed successfully, a positive number
205 * if partly successful or a specific X509 or PEM error code
207 int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path );
210 * \brief Load one or more certificate files from a path and add them
211 * to the chained list. Parses permissively. If some
212 * certificates can be parsed, the result is the number
213 * of failed certificates it encountered. If none complete
214 * correctly, the first error is returned.
216 * \param chain points to the start of the chain
217 * \param path directory / folder to read the certificate files from
219 * \return 0 if all certificates parsed successfully, a positive number
220 * if partly successful or a specific X509 or PEM error code
222 int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path );
223 #endif /* MBEDTLS_FS_IO */
226 * \brief Returns an informational string about the
229 * \param buf Buffer to write to
230 * \param size Maximum size of buffer
231 * \param prefix A line prefix
232 * \param crt The X509 certificate to represent
234 * \return The length of the string written (not including the
235 * terminated nul byte), or a negative error code.
237 int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,
238 const mbedtls_x509_crt *crt );
241 * \brief Returns an informational string about the
242 * verification status of a certificate.
244 * \param buf Buffer to write to
245 * \param size Maximum size of buffer
246 * \param prefix A line prefix
247 * \param flags Verification flags created by mbedtls_x509_crt_verify()
249 * \return The length of the string written (not including the
250 * terminated nul byte), or a negative error code.
252 int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
256 * \brief Verify the certificate signature
258 * The verify callback is a user-supplied callback that
259 * can clear / modify / add flags for a certificate. If set,
260 * the verification callback is called for each
261 * certificate in the chain (from the trust-ca down to the
262 * presented crt). The parameters for the callback are:
263 * (void *parameter, mbedtls_x509_crt *crt, int certificate_depth,
264 * int *flags). With the flags representing current flags for
265 * that specific certificate and the certificate depth from
266 * the bottom (Peer cert depth = 0).
268 * All flags left after returning from the callback
269 * are also returned to the application. The function should
270 * return 0 for anything (including invalid certificates)
271 * other than fatal error, as a non-zero return code
272 * immediately aborts the verification process. For fatal
273 * errors, a specific error code should be used (different
274 * from MBEDTLS_ERR_X509_CERT_VERIFY_FAILED which should not
275 * be returned at this point), or MBEDTLS_ERR_X509_FATAL_ERROR
276 * can be used if no better code is available.
278 * \note In case verification failed, the results can be displayed
279 * using \c mbedtls_x509_crt_verify_info()
281 * \note Same as \c mbedtls_x509_crt_verify_with_profile() with the
282 * default security profile.
284 * \note It is your responsibility to provide up-to-date CRLs for
285 * all trusted CAs. If no CRL is provided for the CA that was
286 * used to sign the certificate, CRL verification is skipped
287 * silently, that is *without* setting any flag.
289 * \param crt a certificate (chain) to be verified
290 * \param trust_ca the list of trusted CAs
291 * \param ca_crl the list of CRLs for trusted CAs (see note above)
292 * \param cn expected Common Name (can be set to
293 * NULL if the CN must not be verified)
294 * \param flags result of the verification
295 * \param f_vrfy verification function
296 * \param p_vrfy verification parameter
298 * \return 0 if successful or MBEDTLS_ERR_X509_CERT_VERIFY_FAILED
299 * in which case *flags will have one or more
300 * MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX flags
302 * or another error in case of a fatal error encountered
303 * during the verification process.
305 int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
306 mbedtls_x509_crt *trust_ca,
307 mbedtls_x509_crl *ca_crl,
308 const char *cn, uint32_t *flags,
309 int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
313 * \brief Verify the certificate signature according to profile
315 * \note Same as \c mbedtls_x509_crt_verify(), but with explicit
318 * \note The restrictions on keys (RSA minimum size, allowed curves
319 * for ECDSA) apply to all certificates: trusted root,
320 * intermediate CAs if any, and end entity certificate.
322 * \param crt a certificate (chain) to be verified
323 * \param trust_ca the list of trusted CAs
324 * \param ca_crl the list of CRLs for trusted CAs
325 * \param profile security profile for verification
326 * \param cn expected Common Name (can be set to
327 * NULL if the CN must not be verified)
328 * \param flags result of the verification
329 * \param f_vrfy verification function
330 * \param p_vrfy verification parameter
332 * \return 0 if successful or MBEDTLS_ERR_X509_CERT_VERIFY_FAILED
333 * in which case *flags will have one or more
334 * MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX flags
336 * or another error in case of a fatal error encountered
337 * during the verification process.
339 int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
340 mbedtls_x509_crt *trust_ca,
341 mbedtls_x509_crl *ca_crl,
342 const mbedtls_x509_crt_profile *profile,
343 const char *cn, uint32_t *flags,
344 int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
347 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
349 * \brief Check usage of certificate against keyUsage extension.
351 * \param crt Leaf certificate used.
352 * \param usage Intended usage(s) (eg MBEDTLS_X509_KU_KEY_ENCIPHERMENT
353 * before using the certificate to perform an RSA key
356 * \note Except for decipherOnly and encipherOnly, a bit set in the
357 * usage argument means this bit MUST be set in the
358 * certificate. For decipherOnly and encipherOnly, it means
359 * that bit MAY be set.
361 * \return 0 is these uses of the certificate are allowed,
362 * MBEDTLS_ERR_X509_BAD_INPUT_DATA if the keyUsage extension
363 * is present but does not match the usage argument.
365 * \note You should only call this function on leaf certificates, on
366 * (intermediate) CAs the keyUsage extension is automatically
367 * checked by \c mbedtls_x509_crt_verify().
369 int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
370 unsigned int usage );
371 #endif /* MBEDTLS_X509_CHECK_KEY_USAGE) */
373 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
375 * \brief Check usage of certificate against extentedJeyUsage.
377 * \param crt Leaf certificate used.
378 * \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or MBEDTLS_OID_CLIENT_AUTH).
379 * \param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()).
381 * \return 0 if this use of the certificate is allowed,
382 * MBEDTLS_ERR_X509_BAD_INPUT_DATA if not.
384 * \note Usually only makes sense on leaf certificates.
386 int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
387 const char *usage_oid,
389 #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) */
391 #if defined(MBEDTLS_X509_CRL_PARSE_C)
393 * \brief Verify the certificate revocation status
395 * \param crt a certificate to be verified
396 * \param crl the CRL to verify against
398 * \return 1 if the certificate is revoked, 0 otherwise
401 int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl );
402 #endif /* MBEDTLS_X509_CRL_PARSE_C */
405 * \brief Initialize a certificate (chain)
407 * \param crt Certificate chain to initialize
409 void mbedtls_x509_crt_init( mbedtls_x509_crt *crt );
412 * \brief Unallocate all certificate data
414 * \param crt Certificate chain to free
416 void mbedtls_x509_crt_free( mbedtls_x509_crt *crt );
417 #endif /* MBEDTLS_X509_CRT_PARSE_C */
420 /* \} addtogroup x509_module */
422 #if defined(MBEDTLS_X509_CRT_WRITE_C)
424 * \brief Initialize a CRT writing context
426 * \param ctx CRT context to initialize
428 void mbedtls_x509write_crt_init( mbedtls_x509write_cert *ctx );
431 * \brief Set the verion for a Certificate
432 * Default: MBEDTLS_X509_CRT_VERSION_3
434 * \param ctx CRT context to use
435 * \param version version to set (MBEDTLS_X509_CRT_VERSION_1, MBEDTLS_X509_CRT_VERSION_2 or
436 * MBEDTLS_X509_CRT_VERSION_3)
438 void mbedtls_x509write_crt_set_version( mbedtls_x509write_cert *ctx, int version );
441 * \brief Set the serial number for a Certificate.
443 * \param ctx CRT context to use
444 * \param serial serial number to set
446 * \return 0 if successful
448 int mbedtls_x509write_crt_set_serial( mbedtls_x509write_cert *ctx, const mbedtls_mpi *serial );
451 * \brief Set the validity period for a Certificate
452 * Timestamps should be in string format for UTC timezone
453 * i.e. "YYYYMMDDhhmmss"
454 * e.g. "20131231235959" for December 31st 2013
457 * \param ctx CRT context to use
458 * \param not_before not_before timestamp
459 * \param not_after not_after timestamp
461 * \return 0 if timestamp was parsed successfully, or
462 * a specific error code
464 int mbedtls_x509write_crt_set_validity( mbedtls_x509write_cert *ctx, const char *not_before,
465 const char *not_after );
468 * \brief Set the issuer name for a Certificate
469 * Issuer names should contain a comma-separated list
470 * of OID types and values:
471 * e.g. "C=UK,O=ARM,CN=mbed TLS CA"
473 * \param ctx CRT context to use
474 * \param issuer_name issuer name to set
476 * \return 0 if issuer name was parsed successfully, or
477 * a specific error code
479 int mbedtls_x509write_crt_set_issuer_name( mbedtls_x509write_cert *ctx,
480 const char *issuer_name );
483 * \brief Set the subject name for a Certificate
484 * Subject names should contain a comma-separated list
485 * of OID types and values:
486 * e.g. "C=UK,O=ARM,CN=mbed TLS Server 1"
488 * \param ctx CRT context to use
489 * \param subject_name subject name to set
491 * \return 0 if subject name was parsed successfully, or
492 * a specific error code
494 int mbedtls_x509write_crt_set_subject_name( mbedtls_x509write_cert *ctx,
495 const char *subject_name );
498 * \brief Set the subject public key for the certificate
500 * \param ctx CRT context to use
501 * \param key public key to include
503 void mbedtls_x509write_crt_set_subject_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key );
506 * \brief Set the issuer key used for signing the certificate
508 * \param ctx CRT context to use
509 * \param key private key to sign with
511 void mbedtls_x509write_crt_set_issuer_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key );
514 * \brief Set the MD algorithm to use for the signature
515 * (e.g. MBEDTLS_MD_SHA1)
517 * \param ctx CRT context to use
518 * \param md_alg MD algorithm to use
520 void mbedtls_x509write_crt_set_md_alg( mbedtls_x509write_cert *ctx, mbedtls_md_type_t md_alg );
523 * \brief Generic function to add to or replace an extension in the
526 * \param ctx CRT context to use
527 * \param oid OID of the extension
528 * \param oid_len length of the OID
529 * \param critical if the extension is critical (per the RFC's definition)
530 * \param val value of the extension OCTET STRING
531 * \param val_len length of the value data
533 * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
535 int mbedtls_x509write_crt_set_extension( mbedtls_x509write_cert *ctx,
536 const char *oid, size_t oid_len,
538 const unsigned char *val, size_t val_len );
541 * \brief Set the basicConstraints extension for a CRT
543 * \param ctx CRT context to use
544 * \param is_ca is this a CA certificate
545 * \param max_pathlen maximum length of certificate chains below this
546 * certificate (only for CA certificates, -1 is
549 * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
551 int mbedtls_x509write_crt_set_basic_constraints( mbedtls_x509write_cert *ctx,
552 int is_ca, int max_pathlen );
554 #if defined(MBEDTLS_SHA1_C)
556 * \brief Set the subjectKeyIdentifier extension for a CRT
557 * Requires that mbedtls_x509write_crt_set_subject_key() has been
560 * \param ctx CRT context to use
562 * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
564 int mbedtls_x509write_crt_set_subject_key_identifier( mbedtls_x509write_cert *ctx );
567 * \brief Set the authorityKeyIdentifier extension for a CRT
568 * Requires that mbedtls_x509write_crt_set_issuer_key() has been
571 * \param ctx CRT context to use
573 * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
575 int mbedtls_x509write_crt_set_authority_key_identifier( mbedtls_x509write_cert *ctx );
576 #endif /* MBEDTLS_SHA1_C */
579 * \brief Set the Key Usage Extension flags
580 * (e.g. MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_CERT_SIGN)
582 * \param ctx CRT context to use
583 * \param key_usage key usage flags to set
585 * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
587 int mbedtls_x509write_crt_set_key_usage( mbedtls_x509write_cert *ctx,
588 unsigned int key_usage );
591 * \brief Set the Netscape Cert Type flags
592 * (e.g. MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT | MBEDTLS_X509_NS_CERT_TYPE_EMAIL)
594 * \param ctx CRT context to use
595 * \param ns_cert_type Netscape Cert Type flags to set
597 * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
599 int mbedtls_x509write_crt_set_ns_cert_type( mbedtls_x509write_cert *ctx,
600 unsigned char ns_cert_type );
603 * \brief Free the contents of a CRT write context
605 * \param ctx CRT context to free
607 void mbedtls_x509write_crt_free( mbedtls_x509write_cert *ctx );
610 * \brief Write a built up certificate to a X509 DER structure
611 * Note: data is written at the end of the buffer! Use the
612 * return value to determine where you should start
615 * \param ctx certificate to write away
616 * \param buf buffer to write to
617 * \param size size of the buffer
618 * \param f_rng RNG function (for signature, see note)
619 * \param p_rng RNG parameter
621 * \return length of data written if successful, or a specific
624 * \note f_rng may be NULL if RSA is used for signature and the
625 * signature is made offline (otherwise f_rng is desirable
626 * for countermeasures against timing attacks).
627 * ECDSA signatures always require a non-NULL f_rng.
629 int mbedtls_x509write_crt_der( mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size,
630 int (*f_rng)(void *, unsigned char *, size_t),
633 #if defined(MBEDTLS_PEM_WRITE_C)
635 * \brief Write a built up certificate to a X509 PEM string
637 * \param ctx certificate to write away
638 * \param buf buffer to write to
639 * \param size size of the buffer
640 * \param f_rng RNG function (for signature, see note)
641 * \param p_rng RNG parameter
643 * \return 0 if successful, or a specific error code
645 * \note f_rng may be NULL if RSA is used for signature and the
646 * signature is made offline (otherwise f_rng is desirable
647 * for countermeasures against timing attacks).
648 * ECDSA signatures always require a non-NULL f_rng.
650 int mbedtls_x509write_crt_pem( mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size,
651 int (*f_rng)(void *, unsigned char *, size_t),
653 #endif /* MBEDTLS_PEM_WRITE_C */
654 #endif /* MBEDTLS_X509_CRT_WRITE_C */
660 #endif /* mbedtls_x509_crt.h */