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
124 * Container for writing a certificate (CRT)
126 typedef struct mbedtls_x509write_cert
130 mbedtls_pk_context *subject_key;
131 mbedtls_pk_context *issuer_key;
132 mbedtls_asn1_named_data *subject;
133 mbedtls_asn1_named_data *issuer;
134 mbedtls_md_type_t md_alg;
135 char not_before[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1];
136 char not_after[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1];
137 mbedtls_asn1_named_data *extensions;
139 mbedtls_x509write_cert;
141 #if defined(MBEDTLS_X509_CRT_PARSE_C)
143 * Default security profile. Should provide a good balance between security
144 * and compatibility with current deployments.
146 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default;
149 * Expected next default profile. Recommended for new deployments.
150 * Currently targets a 128-bit security level, except for RSA-2048.
152 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next;
155 * NSA Suite B profile.
157 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb;
160 * \brief Parse a single DER formatted certificate and add it
161 * to the chained list.
163 * \param chain points to the start of the chain
164 * \param buf buffer holding the certificate DER data
165 * \param buflen size of the buffer
167 * \return 0 if successful, or a specific X509 or PEM error code
169 int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,
173 * \brief Parse one or more certificates and add them
174 * to the chained list. Parses permissively. If some
175 * certificates can be parsed, the result is the number
176 * of failed certificates it encountered. If none complete
177 * correctly, the first error is returned.
179 * \param chain points to the start of the chain
180 * \param buf buffer holding the certificate data in PEM or DER format
181 * \param buflen size of the buffer
182 * (including the terminating null byte for PEM data)
184 * \return 0 if all certificates parsed successfully, a positive number
185 * if partly successful or a specific X509 or PEM error code
187 int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen );
189 #if defined(MBEDTLS_FS_IO)
191 * \brief Load one or more certificates and add them
192 * to the chained list. Parses permissively. If some
193 * certificates can be parsed, the result is the number
194 * of failed certificates it encountered. If none complete
195 * correctly, the first error is returned.
197 * \param chain points to the start of the chain
198 * \param path filename to read the certificates from
200 * \return 0 if all certificates parsed successfully, a positive number
201 * if partly successful or a specific X509 or PEM error code
203 int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path );
206 * \brief Load one or more certificate files from a path and add them
207 * to the chained list. Parses permissively. If some
208 * certificates can be parsed, the result is the number
209 * of failed certificates it encountered. If none complete
210 * correctly, the first error is returned.
212 * \param chain points to the start of the chain
213 * \param path directory / folder to read the certificate files from
215 * \return 0 if all certificates parsed successfully, a positive number
216 * if partly successful or a specific X509 or PEM error code
218 int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path );
219 #endif /* MBEDTLS_FS_IO */
222 * \brief Returns an informational string about the
225 * \param buf Buffer to write to
226 * \param size Maximum size of buffer
227 * \param prefix A line prefix
228 * \param crt The X509 certificate to represent
230 * \return The length of the string written (not including the
231 * terminated nul byte), or a negative error code.
233 int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,
234 const mbedtls_x509_crt *crt );
237 * \brief Returns an informational string about the
238 * verification status of a certificate.
240 * \param buf Buffer to write to
241 * \param size Maximum size of buffer
242 * \param prefix A line prefix
243 * \param flags Verification flags created by mbedtls_x509_crt_verify()
245 * \return The length of the string written (not including the
246 * terminated nul byte), or a negative error code.
248 int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
252 * \brief Verify the certificate signature
254 * The verify callback is a user-supplied callback that
255 * can clear / modify / add flags for a certificate. If set,
256 * the verification callback is called for each
257 * certificate in the chain (from the trust-ca down to the
258 * presented crt). The parameters for the callback are:
259 * (void *parameter, mbedtls_x509_crt *crt, int certificate_depth,
260 * int *flags). With the flags representing current flags for
261 * that specific certificate and the certificate depth from
262 * the bottom (Peer cert depth = 0).
264 * All flags left after returning from the callback
265 * are also returned to the application. The function should
266 * return 0 for anything but a fatal error.
268 * \note In case verification failed, the results can be displayed
269 * using \c mbedtls_x509_crt_verify_info()
271 * \note Same as \c mbedtls_x509_crt_verify_with_profile() with the
272 * default security profile.
274 * \note It is your responsibility to provide up-to-date CRLs for
275 * all trusted CAs. If no CRL is provided for the CA that was
276 * used to sign the certificate, CRL verification is skipped
277 * silently, that is *without* setting any flag.
279 * \param crt a certificate (chain) to be verified
280 * \param trust_ca the list of trusted CAs
281 * \param ca_crl the list of CRLs for trusted CAs (see note above)
282 * \param cn expected Common Name (can be set to
283 * NULL if the CN must not be verified)
284 * \param flags result of the verification
285 * \param f_vrfy verification function
286 * \param p_vrfy verification parameter
288 * \return 0 if successful or MBEDTLS_ERR_X509_CERT_VERIFY_FAILED
289 * in which case *flags will have one or more
290 * MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX flags
292 * or another error in case of a fatal error encountered
293 * during the verification process.
295 int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
296 mbedtls_x509_crt *trust_ca,
297 mbedtls_x509_crl *ca_crl,
298 const char *cn, uint32_t *flags,
299 int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
303 * \brief Verify the certificate signature according to profile
305 * \note Same as \c mbedtls_x509_crt_verify(), but with explicit
308 * \note The restrictions on keys (RSA minimum size, allowed curves
309 * for ECDSA) apply to all certificates: trusted root,
310 * intermediate CAs if any, and end entity certificate.
312 * \param crt a certificate (chain) to be verified
313 * \param trust_ca the list of trusted CAs
314 * \param ca_crl the list of CRLs for trusted CAs
315 * \param profile security profile for verification
316 * \param cn expected Common Name (can be set to
317 * NULL if the CN must not be verified)
318 * \param flags result of the verification
319 * \param f_vrfy verification function
320 * \param p_vrfy verification parameter
322 * \return 0 if successful or MBEDTLS_ERR_X509_CERT_VERIFY_FAILED
323 * in which case *flags will have one or more
324 * MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX flags
326 * or another error in case of a fatal error encountered
327 * during the verification process.
329 int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
330 mbedtls_x509_crt *trust_ca,
331 mbedtls_x509_crl *ca_crl,
332 const mbedtls_x509_crt_profile *profile,
333 const char *cn, uint32_t *flags,
334 int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
337 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
339 * \brief Check usage of certificate against keyUsage extension.
341 * \param crt Leaf certificate used.
342 * \param usage Intended usage(s) (eg MBEDTLS_X509_KU_KEY_ENCIPHERMENT
343 * before using the certificate to perform an RSA key
346 * \note Except for decipherOnly and encipherOnly, a bit set in the
347 * usage argument means this bit MUST be set in the
348 * certificate. For decipherOnly and encipherOnly, it means
349 * that bit MAY be set.
351 * \return 0 is these uses of the certificate are allowed,
352 * MBEDTLS_ERR_X509_BAD_INPUT_DATA if the keyUsage extension
353 * is present but does not match the usage argument.
355 * \note You should only call this function on leaf certificates, on
356 * (intermediate) CAs the keyUsage extension is automatically
357 * checked by \c mbedtls_x509_crt_verify().
359 int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
360 unsigned int usage );
361 #endif /* MBEDTLS_X509_CHECK_KEY_USAGE) */
363 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
365 * \brief Check usage of certificate against extentedJeyUsage.
367 * \param crt Leaf certificate used.
368 * \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or MBEDTLS_OID_CLIENT_AUTH).
369 * \param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()).
371 * \return 0 if this use of the certificate is allowed,
372 * MBEDTLS_ERR_X509_BAD_INPUT_DATA if not.
374 * \note Usually only makes sense on leaf certificates.
376 int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
377 const char *usage_oid,
379 #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE) */
381 #if defined(MBEDTLS_X509_CRL_PARSE_C)
383 * \brief Verify the certificate revocation status
385 * \param crt a certificate to be verified
386 * \param crl the CRL to verify against
388 * \return 1 if the certificate is revoked, 0 otherwise
391 int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl );
392 #endif /* MBEDTLS_X509_CRL_PARSE_C */
395 * \brief Initialize a certificate (chain)
397 * \param crt Certificate chain to initialize
399 void mbedtls_x509_crt_init( mbedtls_x509_crt *crt );
402 * \brief Unallocate all certificate data
404 * \param crt Certificate chain to free
406 void mbedtls_x509_crt_free( mbedtls_x509_crt *crt );
407 #endif /* MBEDTLS_X509_CRT_PARSE_C */
410 /* \} addtogroup x509_module */
412 #if defined(MBEDTLS_X509_CRT_WRITE_C)
414 * \brief Initialize a CRT writing context
416 * \param ctx CRT context to initialize
418 void mbedtls_x509write_crt_init( mbedtls_x509write_cert *ctx );
421 * \brief Set the verion for a Certificate
422 * Default: MBEDTLS_X509_CRT_VERSION_3
424 * \param ctx CRT context to use
425 * \param version version to set (MBEDTLS_X509_CRT_VERSION_1, MBEDTLS_X509_CRT_VERSION_2 or
426 * MBEDTLS_X509_CRT_VERSION_3)
428 void mbedtls_x509write_crt_set_version( mbedtls_x509write_cert *ctx, int version );
431 * \brief Set the serial number for a Certificate.
433 * \param ctx CRT context to use
434 * \param serial serial number to set
436 * \return 0 if successful
438 int mbedtls_x509write_crt_set_serial( mbedtls_x509write_cert *ctx, const mbedtls_mpi *serial );
441 * \brief Set the validity period for a Certificate
442 * Timestamps should be in string format for UTC timezone
443 * i.e. "YYYYMMDDhhmmss"
444 * e.g. "20131231235959" for December 31st 2013
447 * \param ctx CRT context to use
448 * \param not_before not_before timestamp
449 * \param not_after not_after timestamp
451 * \return 0 if timestamp was parsed successfully, or
452 * a specific error code
454 int mbedtls_x509write_crt_set_validity( mbedtls_x509write_cert *ctx, const char *not_before,
455 const char *not_after );
458 * \brief Set the issuer name for a Certificate
459 * Issuer names should contain a comma-separated list
460 * of OID types and values:
461 * e.g. "C=UK,O=ARM,CN=mbed TLS CA"
463 * \param ctx CRT context to use
464 * \param issuer_name issuer name to set
466 * \return 0 if issuer name was parsed successfully, or
467 * a specific error code
469 int mbedtls_x509write_crt_set_issuer_name( mbedtls_x509write_cert *ctx,
470 const char *issuer_name );
473 * \brief Set the subject name for a Certificate
474 * Subject names should contain a comma-separated list
475 * of OID types and values:
476 * e.g. "C=UK,O=ARM,CN=mbed TLS Server 1"
478 * \param ctx CRT context to use
479 * \param subject_name subject name to set
481 * \return 0 if subject name was parsed successfully, or
482 * a specific error code
484 int mbedtls_x509write_crt_set_subject_name( mbedtls_x509write_cert *ctx,
485 const char *subject_name );
488 * \brief Set the subject public key for the certificate
490 * \param ctx CRT context to use
491 * \param key public key to include
493 void mbedtls_x509write_crt_set_subject_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key );
496 * \brief Set the issuer key used for signing the certificate
498 * \param ctx CRT context to use
499 * \param key private key to sign with
501 void mbedtls_x509write_crt_set_issuer_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key );
504 * \brief Set the MD algorithm to use for the signature
505 * (e.g. MBEDTLS_MD_SHA1)
507 * \param ctx CRT context to use
508 * \param md_alg MD algorithm to use
510 void mbedtls_x509write_crt_set_md_alg( mbedtls_x509write_cert *ctx, mbedtls_md_type_t md_alg );
513 * \brief Generic function to add to or replace an extension in the
516 * \param ctx CRT context to use
517 * \param oid OID of the extension
518 * \param oid_len length of the OID
519 * \param critical if the extension is critical (per the RFC's definition)
520 * \param val value of the extension OCTET STRING
521 * \param val_len length of the value data
523 * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
525 int mbedtls_x509write_crt_set_extension( mbedtls_x509write_cert *ctx,
526 const char *oid, size_t oid_len,
528 const unsigned char *val, size_t val_len );
531 * \brief Set the basicConstraints extension for a CRT
533 * \param ctx CRT context to use
534 * \param is_ca is this a CA certificate
535 * \param max_pathlen maximum length of certificate chains below this
536 * certificate (only for CA certificates, -1 is
539 * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
541 int mbedtls_x509write_crt_set_basic_constraints( mbedtls_x509write_cert *ctx,
542 int is_ca, int max_pathlen );
544 #if defined(MBEDTLS_SHA1_C)
546 * \brief Set the subjectKeyIdentifier extension for a CRT
547 * Requires that mbedtls_x509write_crt_set_subject_key() has been
550 * \param ctx CRT context to use
552 * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
554 int mbedtls_x509write_crt_set_subject_key_identifier( mbedtls_x509write_cert *ctx );
557 * \brief Set the authorityKeyIdentifier extension for a CRT
558 * Requires that mbedtls_x509write_crt_set_issuer_key() has been
561 * \param ctx CRT context to use
563 * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
565 int mbedtls_x509write_crt_set_authority_key_identifier( mbedtls_x509write_cert *ctx );
566 #endif /* MBEDTLS_SHA1_C */
569 * \brief Set the Key Usage Extension flags
570 * (e.g. MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_CERT_SIGN)
572 * \param ctx CRT context to use
573 * \param key_usage key usage flags to set
575 * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
577 int mbedtls_x509write_crt_set_key_usage( mbedtls_x509write_cert *ctx,
578 unsigned int key_usage );
581 * \brief Set the Netscape Cert Type flags
582 * (e.g. MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT | MBEDTLS_X509_NS_CERT_TYPE_EMAIL)
584 * \param ctx CRT context to use
585 * \param ns_cert_type Netscape Cert Type flags to set
587 * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
589 int mbedtls_x509write_crt_set_ns_cert_type( mbedtls_x509write_cert *ctx,
590 unsigned char ns_cert_type );
593 * \brief Free the contents of a CRT write context
595 * \param ctx CRT context to free
597 void mbedtls_x509write_crt_free( mbedtls_x509write_cert *ctx );
600 * \brief Write a built up certificate to a X509 DER structure
601 * Note: data is written at the end of the buffer! Use the
602 * return value to determine where you should start
605 * \param ctx certificate to write away
606 * \param buf buffer to write to
607 * \param size size of the buffer
608 * \param f_rng RNG function (for signature, see note)
609 * \param p_rng RNG parameter
611 * \return length of data written if successful, or a specific
614 * \note f_rng may be NULL if RSA is used for signature and the
615 * signature is made offline (otherwise f_rng is desirable
616 * for countermeasures against timing attacks).
617 * ECDSA signatures always require a non-NULL f_rng.
619 int mbedtls_x509write_crt_der( mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size,
620 int (*f_rng)(void *, unsigned char *, size_t),
623 #if defined(MBEDTLS_PEM_WRITE_C)
625 * \brief Write a built up certificate to a X509 PEM string
627 * \param ctx certificate to write away
628 * \param buf buffer to write to
629 * \param size size of the buffer
630 * \param f_rng RNG function (for signature, see note)
631 * \param p_rng RNG parameter
633 * \return 0 if successful, or a specific error code
635 * \note f_rng may be NULL if RSA is used for signature and the
636 * signature is made offline (otherwise f_rng is desirable
637 * for countermeasures against timing attacks).
638 * ECDSA signatures always require a non-NULL f_rng.
640 int mbedtls_x509write_crt_pem( mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size,
641 int (*f_rng)(void *, unsigned char *, size_t),
643 #endif /* MBEDTLS_PEM_WRITE_C */
644 #endif /* MBEDTLS_X509_CRT_WRITE_C */
650 #endif /* mbedtls_x509_crt.h */