1 /**
2  * \file x509_crt.h
3  *
4  * \brief X.509 certificate parsing and writing
5  */
6 /*
7  *  Copyright The Mbed TLS Contributors
8  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
9  */
10 #ifndef MBEDTLS_X509_CRT_H
11 #define MBEDTLS_X509_CRT_H
12 #include "mbedtls/private_access.h"
13 
14 #include "mbedtls/build_info.h"
15 
16 #include "mbedtls/x509.h"
17 #include "mbedtls/x509_crl.h"
18 #include "mbedtls/bignum.h"
19 
20 /**
21  * \addtogroup x509_module
22  * \{
23  */
24 
25 #ifdef __cplusplus
26 extern "C" {
27 #endif
28 
29 /**
30  * \name Structures and functions for parsing and writing X.509 certificates
31  * \{
32  */
33 
34 /**
35  * Container for an X.509 certificate. The certificate may be chained.
36  *
37  * Some fields of this structure are publicly readable. Do not modify
38  * them except via Mbed TLS library functions: the effect of modifying
39  * those fields or the data that those fields points to is unspecified.
40  */
41 typedef struct mbedtls_x509_crt {
42     int MBEDTLS_PRIVATE(own_buffer);                     /**< Indicates if \c raw is owned
43                                                           *   by the structure or not.        */
44     mbedtls_x509_buf raw;               /**< The raw certificate data (DER). */
45     mbedtls_x509_buf tbs;               /**< The raw certificate body (DER). The part that is To Be Signed. */
46 
47     int version;                /**< The X.509 version. (1=v1, 2=v2, 3=v3) */
48     mbedtls_x509_buf serial;            /**< Unique id for certificate issued by a specific CA. */
49     mbedtls_x509_buf sig_oid;           /**< Signature algorithm, e.g. sha1RSA */
50 
51     mbedtls_x509_buf issuer_raw;        /**< The raw issuer data (DER). Used for quick comparison. */
52     mbedtls_x509_buf subject_raw;       /**< The raw subject data (DER). Used for quick comparison. */
53 
54     mbedtls_x509_name issuer;           /**< The parsed issuer data (named information object). */
55     mbedtls_x509_name subject;          /**< The parsed subject data (named information object). */
56 
57     mbedtls_x509_time valid_from;       /**< Start time of certificate validity. */
58     mbedtls_x509_time valid_to;         /**< End time of certificate validity. */
59 
60     mbedtls_x509_buf pk_raw;
61     mbedtls_pk_context pk;              /**< Container for the public key context. */
62 
63     mbedtls_x509_buf issuer_id;         /**< Optional X.509 v2/v3 issuer unique identifier. */
64     mbedtls_x509_buf subject_id;        /**< Optional X.509 v2/v3 subject unique identifier. */
65     mbedtls_x509_buf v3_ext;            /**< Optional X.509 v3 extensions.  */
66     mbedtls_x509_sequence subject_alt_names; /**< Optional list of raw entries of Subject Alternative Names extension. These can be later parsed by mbedtls_x509_parse_subject_alt_name. */
67     mbedtls_x509_buf subject_key_id;    /**< Optional X.509 v3 extension subject key identifier. */
68     mbedtls_x509_authority authority_key_id;    /**< Optional X.509 v3 extension authority key identifier. */
69 
70     mbedtls_x509_sequence certificate_policies; /**< Optional list of certificate policies (Only anyPolicy is printed and enforced, however the rest of the policies are still listed). */
71 
72     int MBEDTLS_PRIVATE(ext_types);              /**< Bit string containing detected and parsed extensions */
73     int MBEDTLS_PRIVATE(ca_istrue);              /**< Optional Basic Constraint extension value: 1 if this certificate belongs to a CA, 0 otherwise. */
74     int MBEDTLS_PRIVATE(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+ */
75 
76     unsigned int MBEDTLS_PRIVATE(key_usage);     /**< Optional key usage extension value: See the values in x509.h */
77 
78     mbedtls_x509_sequence ext_key_usage; /**< Optional list of extended key usage OIDs. */
79 
80     unsigned char MBEDTLS_PRIVATE(ns_cert_type); /**< Optional Netscape certificate type extension value: See the values in x509.h */
81 
82     mbedtls_x509_buf MBEDTLS_PRIVATE(sig);               /**< Signature: hash of the tbs part signed with the private key. */
83     mbedtls_md_type_t MBEDTLS_PRIVATE(sig_md);           /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */
84     mbedtls_pk_sigalg_t MBEDTLS_PRIVATE(sig_pk);           /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */
85 
86     /** Next certificate in the linked list that constitutes the CA chain.
87      * \p NULL indicates the end of the list.
88      * Do not modify this field directly. */
89     struct mbedtls_x509_crt *next;
90 }
91 mbedtls_x509_crt;
92 
93 /**
94  * Build flag from an algorithm/curve identifier (pk, md, ecp)
95  * Since 0 is always XXX_NONE, ignore it.
96  */
97 #define MBEDTLS_X509_ID_FLAG(id)   (1 << ((id) - 1))
98 
99 /**
100  * Security profile for certificate verification.
101  *
102  * All lists are bitfields, built by ORing flags from MBEDTLS_X509_ID_FLAG().
103  *
104  * The fields of this structure are part of the public API and can be
105  * manipulated directly by applications. Future versions of the library may
106  * add extra fields or reorder existing fields.
107  *
108  * You can create custom profiles by starting from a copy of
109  * an existing profile, such as mbedtls_x509_crt_profile_default or
110  * mbedtls_x509_ctr_profile_none and then tune it to your needs.
111  *
112  * For example to allow SHA-224 in addition to the default:
113  *
114  *  mbedtls_x509_crt_profile my_profile = mbedtls_x509_crt_profile_default;
115  *  my_profile.allowed_mds |= MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 );
116  *
117  * Or to allow only RSA-3072+ with SHA-256:
118  *
119  *  mbedtls_x509_crt_profile my_profile = mbedtls_x509_crt_profile_none;
120  *  my_profile.allowed_mds = MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 );
121  *  my_profile.allowed_pks = MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_RSA );
122  *  my_profile.rsa_min_bitlen = 3072;
123  */
124 typedef struct mbedtls_x509_crt_profile {
125     uint32_t allowed_mds;       /**< MDs for signatures         */
126     uint32_t allowed_pks;       /**< PK algs for public keys;
127                                  *   this applies to all certificates
128                                  *   in the provided chain.     */
129     uint32_t allowed_curves;    /**< Elliptic curves for ECDSA  */
130     uint32_t rsa_min_bitlen;    /**< Minimum size for RSA keys  */
131 }
132 mbedtls_x509_crt_profile;
133 
134 #define MBEDTLS_X509_CRT_VERSION_1              0
135 #define MBEDTLS_X509_CRT_VERSION_2              1
136 #define MBEDTLS_X509_CRT_VERSION_3              2
137 
138 #define MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN 20
139 #define MBEDTLS_X509_RFC5280_UTC_TIME_LEN   15
140 
141 #if !defined(MBEDTLS_X509_MAX_FILE_PATH_LEN)
142 #define MBEDTLS_X509_MAX_FILE_PATH_LEN 512
143 #endif
144 
145 /* This macro unfolds to the concatenation of macro invocations
146  * X509_CRT_ERROR_INFO( error code,
147  *                             error code as string,
148  *                             human readable description )
149  * where X509_CRT_ERROR_INFO is defined by the user.
150  * See x509_crt.c for an example of how to use this. */
151 #define MBEDTLS_X509_CRT_ERROR_INFO_LIST                                  \
152     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_EXPIRED,            \
153                         "MBEDTLS_X509_BADCERT_EXPIRED",          \
154                         "The certificate validity has expired") \
155     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_REVOKED,            \
156                         "MBEDTLS_X509_BADCERT_REVOKED",          \
157                         "The certificate has been revoked (is on a CRL)") \
158     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_CN_MISMATCH,                  \
159                         "MBEDTLS_X509_BADCERT_CN_MISMATCH",                \
160                         "The certificate Common Name (CN) does not match with the expected CN") \
161     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_NOT_TRUSTED,                             \
162                         "MBEDTLS_X509_BADCERT_NOT_TRUSTED",                           \
163                         "The certificate is not correctly signed by the trusted CA") \
164     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCRL_NOT_TRUSTED,                      \
165                         "MBEDTLS_X509_BADCRL_NOT_TRUSTED",                    \
166                         "The CRL is not correctly signed by the trusted CA") \
167     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCRL_EXPIRED,    \
168                         "MBEDTLS_X509_BADCRL_EXPIRED",  \
169                         "The CRL is expired")          \
170     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_MISSING,   \
171                         "MBEDTLS_X509_BADCERT_MISSING", \
172                         "Certificate was missing")     \
173     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_SKIP_VERIFY,         \
174                         "MBEDTLS_X509_BADCERT_SKIP_VERIFY",       \
175                         "Certificate verification was skipped")  \
176     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_OTHER,                          \
177                         "MBEDTLS_X509_BADCERT_OTHER",                        \
178                         "Other reason (can be used by verify callback)")    \
179     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_FUTURE,                         \
180                         "MBEDTLS_X509_BADCERT_FUTURE",                       \
181                         "The certificate validity starts in the future")    \
182     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCRL_FUTURE,     \
183                         "MBEDTLS_X509_BADCRL_FUTURE",   \
184                         "The CRL is from the future")  \
185     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_KEY_USAGE,                      \
186                         "MBEDTLS_X509_BADCERT_KEY_USAGE",                    \
187                         "Usage does not match the keyUsage extension")      \
188     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_EXT_KEY_USAGE,                       \
189                         "MBEDTLS_X509_BADCERT_EXT_KEY_USAGE",                     \
190                         "Usage does not match the extendedKeyUsage extension")   \
191     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_NS_CERT_TYPE,                        \
192                         "MBEDTLS_X509_BADCERT_NS_CERT_TYPE",                      \
193                         "Usage does not match the nsCertType extension")         \
194     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_BAD_MD,                              \
195                         "MBEDTLS_X509_BADCERT_BAD_MD",                            \
196                         "The certificate is signed with an unacceptable hash.")  \
197     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_BAD_PK,                                                  \
198                         "MBEDTLS_X509_BADCERT_BAD_PK",                                                \
199                         "The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA).")  \
200     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_BAD_KEY,                                                            \
201                         "MBEDTLS_X509_BADCERT_BAD_KEY",                                                          \
202                         "The certificate is signed with an unacceptable key (eg bad curve, RSA too short).")    \
203     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCRL_BAD_MD,                          \
204                         "MBEDTLS_X509_BADCRL_BAD_MD",                        \
205                         "The CRL is signed with an unacceptable hash.")     \
206     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCRL_BAD_PK,                                            \
207                         "MBEDTLS_X509_BADCRL_BAD_PK",                                          \
208                         "The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA).")   \
209     X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCRL_BAD_KEY,                                                    \
210                         "MBEDTLS_X509_BADCRL_BAD_KEY",                                                  \
211                         "The CRL is signed with an unacceptable key (eg bad curve, RSA too short).")
212 
213 /**
214  * Container for writing a certificate (CRT)
215  */
216 typedef struct mbedtls_x509write_cert {
217     int MBEDTLS_PRIVATE(version);
218     unsigned char MBEDTLS_PRIVATE(serial)[MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN];
219     size_t MBEDTLS_PRIVATE(serial_len);
220     mbedtls_pk_context *MBEDTLS_PRIVATE(subject_key);
221     mbedtls_pk_context *MBEDTLS_PRIVATE(issuer_key);
222     mbedtls_asn1_named_data *MBEDTLS_PRIVATE(subject);
223     mbedtls_asn1_named_data *MBEDTLS_PRIVATE(issuer);
224     mbedtls_md_type_t MBEDTLS_PRIVATE(md_alg);
225     char MBEDTLS_PRIVATE(not_before)[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1];
226     char MBEDTLS_PRIVATE(not_after)[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1];
227     mbedtls_asn1_named_data *MBEDTLS_PRIVATE(extensions);
228 }
229 mbedtls_x509write_cert;
230 
231 /**
232  * \brief           Set Subject Alternative Name
233  *
234  * \param ctx       Certificate context to use
235  * \param san_list  List of SAN values
236  *
237  * \return          0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
238  *
239  * \note            "dnsName", "uniformResourceIdentifier", "IP address",
240  *                  "otherName", and "DirectoryName", as defined in RFC 5280,
241  *                  are supported.
242  */
243 int mbedtls_x509write_crt_set_subject_alternative_name(mbedtls_x509write_cert *ctx,
244                                                        const mbedtls_x509_san_list *san_list);
245 
246 /**
247  * Item in a verification chain: cert and flags for it
248  */
249 typedef struct {
250     mbedtls_x509_crt *MBEDTLS_PRIVATE(crt);
251     uint32_t MBEDTLS_PRIVATE(flags);
252 } mbedtls_x509_crt_verify_chain_item;
253 
254 /**
255  * Max size of verification chain: end-entity + intermediates + trusted root
256  */
257 #define MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE  (MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2)
258 
259 /**
260  * Verification chain as built by \c mbedtls_crt_verify_chain()
261  */
262 typedef struct {
263     mbedtls_x509_crt_verify_chain_item MBEDTLS_PRIVATE(items)[MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE];
264     unsigned MBEDTLS_PRIVATE(len);
265 
266 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
267     /* This stores the list of potential trusted signers obtained from
268      * the CA callback used for the CRT verification, if configured.
269      * We must track it somewhere because the callback passes its
270      * ownership to the caller. */
271     mbedtls_x509_crt *MBEDTLS_PRIVATE(trust_ca_cb_result);
272 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
273 } mbedtls_x509_crt_verify_chain;
274 
275 #if defined(MBEDTLS_ECP_RESTARTABLE)
276 
277 /**
278  * \brief       Context for resuming X.509 verify operations
279  */
280 typedef struct {
281     /* for check_signature() */
282     mbedtls_pk_restart_ctx MBEDTLS_PRIVATE(pk);
283 
284     /* for find_parent_in() */
285     mbedtls_x509_crt *MBEDTLS_PRIVATE(parent); /* non-null iff parent_in in progress */
286     mbedtls_x509_crt *MBEDTLS_PRIVATE(fallback_parent);
287     int MBEDTLS_PRIVATE(fallback_signature_is_good);
288 
289     /* for find_parent() */
290     int MBEDTLS_PRIVATE(parent_is_trusted); /* -1 if find_parent is not in progress */
291 
292     /* for verify_chain() */
293     enum {
294         x509_crt_rs_none,
295         x509_crt_rs_find_parent,
296     } MBEDTLS_PRIVATE(in_progress);  /* none if no operation is in progress */
297     int MBEDTLS_PRIVATE(self_cnt);
298     mbedtls_x509_crt_verify_chain MBEDTLS_PRIVATE(ver_chain);
299 
300 } mbedtls_x509_crt_restart_ctx;
301 
302 #else /* MBEDTLS_ECP_RESTARTABLE */
303 
304 /* Now we can declare functions that take a pointer to that */
305 typedef void mbedtls_x509_crt_restart_ctx;
306 
307 #endif /* MBEDTLS_ECP_RESTARTABLE */
308 
309 #if defined(MBEDTLS_X509_CRT_PARSE_C)
310 /**
311  * Default security profile. Should provide a good balance between security
312  * and compatibility with current deployments.
313  *
314  * This profile permits:
315  * - SHA2 hashes with at least 256 bits: SHA-256, SHA-384, SHA-512.
316  * - Elliptic curves with 255 bits and above except secp256k1.
317  * - RSA with 2048 bits and above.
318  *
319  * New minor versions of Mbed TLS may extend this profile, for example if
320  * new algorithms are added to the library. New minor versions of Mbed TLS will
321  * not reduce this profile unless serious security concerns require it.
322  */
323 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default;
324 
325 /**
326  * Expected next default profile. Recommended for new deployments.
327  * Currently targets a 128-bit security level, except for allowing RSA-2048.
328  * This profile may change at any time.
329  */
330 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next;
331 
332 /**
333  * NSA Suite B profile.
334  */
335 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb;
336 
337 /**
338  * Empty profile that allows nothing. Useful as a basis for constructing
339  * custom profiles.
340  */
341 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_none;
342 
343 /**
344  * \brief          Parse a single DER formatted certificate and add it
345  *                 to the end of the provided chained list.
346  *
347  * \note           The PSA crypto subsystem must have been initialized by
348  *                 calling psa_crypto_init() before calling this function.
349  *
350  * \param chain    The pointer to the start of the CRT chain to attach to.
351  *                 When parsing the first CRT in a chain, this should point
352  *                 to an instance of ::mbedtls_x509_crt initialized through
353  *                 mbedtls_x509_crt_init().
354  * \param buf      The buffer holding the DER encoded certificate.
355  * \param buflen   The size in Bytes of \p buf.
356  *
357  * \note           This function makes an internal copy of the CRT buffer
358  *                 \p buf. In particular, \p buf may be destroyed or reused
359  *                 after this call returns. To avoid duplicating the CRT
360  *                 buffer (at the cost of stricter lifetime constraints),
361  *                 use mbedtls_x509_crt_parse_der_nocopy() instead.
362  *
363  * \return         \c 0 if successful.
364  * \return         A negative error code on failure.
365  */
366 int mbedtls_x509_crt_parse_der(mbedtls_x509_crt *chain,
367                                const unsigned char *buf,
368                                size_t buflen);
369 
370 /**
371  * \brief          The type of certificate extension callbacks.
372  *
373  *                 Callbacks of this type are passed to and used by the
374  *                 mbedtls_x509_crt_parse_der_with_ext_cb() routine when
375  *                 it encounters either an unsupported extension or a
376  *                 "certificate policies" extension containing any
377  *                 unsupported certificate policies.
378  *                 Future versions of the library may invoke the callback
379  *                 in other cases, if and when the need arises.
380  *
381  * \param p_ctx    An opaque context passed to the callback.
382  * \param crt      The certificate being parsed.
383  * \param oid      The OID of the extension.
384  * \param critical Whether the extension is critical.
385  * \param p        Pointer to the start of the extension value
386  *                 (the content of the OCTET STRING).
387  * \param end      End of extension value.
388  *
389  * \note           The callback must fail and return a negative error code
390  *                 if it can not parse or does not support the extension.
391  *                 When the callback fails to parse a critical extension
392  *                 mbedtls_x509_crt_parse_der_with_ext_cb() also fails.
393  *                 When the callback fails to parse a non critical extension
394  *                 mbedtls_x509_crt_parse_der_with_ext_cb() simply skips
395  *                 the extension and continues parsing.
396  *
397  * \return         \c 0 on success.
398  * \return         A negative error code on failure.
399  */
400 typedef int (*mbedtls_x509_crt_ext_cb_t)(void *p_ctx,
401                                          mbedtls_x509_crt const *crt,
402                                          mbedtls_x509_buf const *oid,
403                                          int critical,
404                                          const unsigned char *p,
405                                          const unsigned char *end);
406 
407 /**
408  * \brief            Parse a single DER formatted certificate and add it
409  *                   to the end of the provided chained list.
410  *
411  * \note             The PSA crypto subsystem must have been initialized by
412  *                   calling psa_crypto_init() before calling this function.
413  *
414  * \param chain      The pointer to the start of the CRT chain to attach to.
415  *                   When parsing the first CRT in a chain, this should point
416  *                   to an instance of ::mbedtls_x509_crt initialized through
417  *                   mbedtls_x509_crt_init().
418  * \param buf        The buffer holding the DER encoded certificate.
419  * \param buflen     The size in Bytes of \p buf.
420  * \param make_copy  When not zero this function makes an internal copy of the
421  *                   CRT buffer \p buf. In particular, \p buf may be destroyed
422  *                   or reused after this call returns.
423  *                   When zero this function avoids duplicating the CRT buffer
424  *                   by taking temporary ownership thereof until the CRT
425  *                   is destroyed (like mbedtls_x509_crt_parse_der_nocopy())
426  * \param cb         A callback invoked for every unsupported certificate
427  *                   extension.
428  * \param p_ctx      An opaque context passed to the callback.
429  *
430  * \note             This call is functionally equivalent to
431  *                   mbedtls_x509_crt_parse_der(), and/or
432  *                   mbedtls_x509_crt_parse_der_nocopy()
433  *                   but it calls the callback with every unsupported
434  *                   certificate extension and additionally the
435  *                   "certificate policies" extension if it contains any
436  *                   unsupported certificate policies.
437  *                   The callback must return a negative error code if it
438  *                   does not know how to handle such an extension.
439  *                   When the callback fails to parse a critical extension
440  *                   mbedtls_x509_crt_parse_der_with_ext_cb() also fails.
441  *                   When the callback fails to parse a non critical extension
442  *                   mbedtls_x509_crt_parse_der_with_ext_cb() simply skips
443  *                   the extension and continues parsing.
444  *                   Future versions of the library may invoke the callback
445  *                   in other cases, if and when the need arises.
446  *
447  * \return           \c 0 if successful.
448  * \return           A negative error code on failure.
449  */
450 int mbedtls_x509_crt_parse_der_with_ext_cb(mbedtls_x509_crt *chain,
451                                            const unsigned char *buf,
452                                            size_t buflen,
453                                            int make_copy,
454                                            mbedtls_x509_crt_ext_cb_t cb,
455                                            void *p_ctx);
456 
457 /**
458  * \brief          Parse a single DER formatted certificate and add it
459  *                 to the end of the provided chained list. This is a
460  *                 variant of mbedtls_x509_crt_parse_der() which takes
461  *                 temporary ownership of the CRT buffer until the CRT
462  *                 is destroyed.
463  *
464  * \note           The PSA crypto subsystem must have been initialized by
465  *                 calling psa_crypto_init() before calling this function.
466  *
467  * \param chain    The pointer to the start of the CRT chain to attach to.
468  *                 When parsing the first CRT in a chain, this should point
469  *                 to an instance of ::mbedtls_x509_crt initialized through
470  *                 mbedtls_x509_crt_init().
471  * \param buf      The address of the readable buffer holding the DER encoded
472  *                 certificate to use. On success, this buffer must be
473  *                 retained and not be changed for the lifetime of the
474  *                 CRT chain \p chain, that is, until \p chain is destroyed
475  *                 through a call to mbedtls_x509_crt_free().
476  * \param buflen   The size in Bytes of \p buf.
477  *
478  * \note           This call is functionally equivalent to
479  *                 mbedtls_x509_crt_parse_der(), but it avoids creating a
480  *                 copy of the input buffer at the cost of stronger lifetime
481  *                 constraints. This is useful in constrained environments
482  *                 where duplication of the CRT cannot be tolerated.
483  *
484  * \return         \c 0 if successful.
485  * \return         A negative error code on failure.
486  */
487 int mbedtls_x509_crt_parse_der_nocopy(mbedtls_x509_crt *chain,
488                                       const unsigned char *buf,
489                                       size_t buflen);
490 
491 /**
492  * \brief          Parse one DER-encoded or one or more concatenated PEM-encoded
493  *                 certificates and add them to the chained list.
494  *
495  *                 For CRTs in PEM encoding, the function parses permissively:
496  *                 if at least one certificate can be parsed, the function
497  *                 returns the number of certificates for which parsing failed
498  *                 (hence \c 0 if all certificates were parsed successfully).
499  *                 If no certificate could be parsed, the function returns
500  *                 the first (negative) error encountered during parsing.
501  *
502  *                 PEM encoded certificates may be interleaved by other data
503  *                 such as human readable descriptions of their content, as
504  *                 long as the certificates are enclosed in the PEM specific
505  *                 '-----{BEGIN/END} CERTIFICATE-----' delimiters.
506  *
507  * \note           The PSA crypto subsystem must have been initialized by
508  *                 calling psa_crypto_init() before calling this function.
509  *
510  * \param chain    The chain to which to add the parsed certificates.
511  * \param buf      The buffer holding the certificate data in PEM or DER format.
512  *                 For certificates in PEM encoding, this may be a concatenation
513  *                 of multiple certificates; for DER encoding, the buffer must
514  *                 comprise exactly one certificate.
515  * \param buflen   The size of \p buf, including the terminating \c NULL byte
516  *                 in case of PEM encoded data.
517  *
518  * \return         \c 0 if all certificates were parsed successfully.
519  * \return         The (positive) number of certificates that couldn't
520  *                 be parsed if parsing was partly successful (see above).
521  * \return         A negative X509 or PEM error code otherwise.
522  *
523  */
524 int mbedtls_x509_crt_parse(mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen);
525 
526 #if defined(MBEDTLS_FS_IO)
527 /**
528  * \brief          Load one or more certificates and add them
529  *                 to the chained list. Parses permissively. If some
530  *                 certificates can be parsed, the result is the number
531  *                 of failed certificates it encountered. If none complete
532  *                 correctly, the first error is returned.
533  *
534  * \note           The PSA crypto subsystem must have been initialized by
535  *                 calling psa_crypto_init() before calling this function.
536  *
537  * \param chain    points to the start of the chain
538  * \param path     filename to read the certificates from
539  *
540  * \return         0 if all certificates parsed successfully, a positive number
541  *                 if partly successful or a specific X509 or PEM error code
542  */
543 int mbedtls_x509_crt_parse_file(mbedtls_x509_crt *chain, const char *path);
544 
545 /**
546  * \brief          Load one or more certificate files from a path and add them
547  *                 to the chained list. Parses permissively. If some
548  *                 certificates can be parsed, the result is the number
549  *                 of failed certificates it encountered. If none complete
550  *                 correctly, the first error is returned.
551  *
552  * \param chain    points to the start of the chain
553  * \param path     directory / folder to read the certificate files from
554  *
555  * \return         0 if all certificates parsed successfully, a positive number
556  *                 if partly successful or a specific X509 or PEM error code
557  */
558 int mbedtls_x509_crt_parse_path(mbedtls_x509_crt *chain, const char *path);
559 
560 #endif /* MBEDTLS_FS_IO */
561 
562 #if !defined(MBEDTLS_X509_REMOVE_INFO)
563 /**
564  * \brief          Returns an informational string about the
565  *                 certificate.
566  *
567  * \param buf      Buffer to write to
568  * \param size     Maximum size of buffer
569  * \param prefix   A line prefix
570  * \param crt      The X509 certificate to represent
571  *
572  * \return         The length of the string written (not including the
573  *                 terminated nul byte), or a negative error code.
574  */
575 int mbedtls_x509_crt_info(char *buf, size_t size, const char *prefix,
576                           const mbedtls_x509_crt *crt);
577 
578 /**
579  * \brief          Returns an informational string about the
580  *                 verification status of a certificate.
581  *
582  * \param buf      Buffer to write to
583  * \param size     Maximum size of buffer
584  * \param prefix   A line prefix
585  * \param flags    Verification flags created by mbedtls_x509_crt_verify()
586  *
587  * \return         The length of the string written (not including the
588  *                 terminated nul byte), or a negative error code.
589  */
590 int mbedtls_x509_crt_verify_info(char *buf, size_t size, const char *prefix,
591                                  uint32_t flags);
592 #endif /* !MBEDTLS_X509_REMOVE_INFO */
593 
594 /**
595  * \brief          Verify a chain of certificates.
596  *
597  *                 The verify callback is a user-supplied callback that
598  *                 can clear / modify / add flags for a certificate. If set,
599  *                 the verification callback is called for each
600  *                 certificate in the chain (from the trust-ca down to the
601  *                 presented crt). The parameters for the callback are:
602  *                 (void *parameter, mbedtls_x509_crt *crt, int certificate_depth,
603  *                 int *flags). With the flags representing current flags for
604  *                 that specific certificate and the certificate depth from
605  *                 the bottom (Peer cert depth = 0).
606  *
607  *                 All flags left after returning from the callback
608  *                 are also returned to the application. The function should
609  *                 return 0 for anything (including invalid certificates)
610  *                 other than fatal error, as a non-zero return code
611  *                 immediately aborts the verification process. For fatal
612  *                 errors, a specific error code should be used (different
613  *                 from MBEDTLS_ERR_X509_CERT_VERIFY_FAILED which should not
614  *                 be returned at this point), or MBEDTLS_ERR_X509_FATAL_ERROR
615  *                 can be used if no better code is available.
616  *
617  * \note           In case verification failed, the results can be displayed
618  *                 using \c mbedtls_x509_crt_verify_info()
619  *
620  * \note           Same as \c mbedtls_x509_crt_verify_with_profile() with the
621  *                 default security profile.
622  *
623  * \note           It is your responsibility to provide up-to-date CRLs for
624  *                 all trusted CAs. If no CRL is provided for the CA that was
625  *                 used to sign the certificate, CRL verification is skipped
626  *                 silently, that is *without* setting any flag.
627  *
628  * \note           The \c trust_ca list can contain two types of certificates:
629  *                 (1) those of trusted root CAs, so that certificates
630  *                 chaining up to those CAs will be trusted, and (2)
631  *                 self-signed end-entity certificates to be trusted (for
632  *                 specific peers you know) - in that case, the self-signed
633  *                 certificate doesn't need to have the CA bit set.
634  *
635  * \param crt      The certificate chain to be verified.
636  * \param trust_ca The list of trusted CAs.
637  * \param ca_crl   The list of CRLs for trusted CAs.
638  * \param cn       The expected Common Name. This will be checked to be
639  *                 present in the certificate's subjectAltNames extension or,
640  *                 if this extension is absent, as a CN component in its
641  *                 Subject name. DNS names and IP addresses are fully
642  *                 supported, while the URI subtype is partially supported:
643  *                 only exact matching, without any normalization procedures
644  *                 described in 7.4 of RFC5280, will result in a positive
645  *                 URI verification.
646  *                 This may be \c NULL if the CN need not be verified.
647  * \param flags    The address at which to store the result of the verification.
648  *                 If the verification couldn't be completed, the flag value is
649  *                 set to (uint32_t) -1.
650  * \param f_vrfy   The verification callback to use. See the documentation
651  *                 of mbedtls_x509_crt_verify() for more information.
652  * \param p_vrfy   The context to be passed to \p f_vrfy.
653  *
654  * \return         \c 0 if the chain is valid with respect to the
655  *                 passed CN, CAs, CRLs and security profile.
656  * \return         #MBEDTLS_ERR_X509_CERT_VERIFY_FAILED in case the
657  *                 certificate chain verification failed. In this case,
658  *                 \c *flags will have one or more
659  *                 \c MBEDTLS_X509_BADCERT_XXX or \c MBEDTLS_X509_BADCRL_XXX
660  *                 flags set.
661  * \return         Another negative error code in case of a fatal error
662  *                 encountered during the verification process.
663  */
664 int mbedtls_x509_crt_verify(mbedtls_x509_crt *crt,
665                             mbedtls_x509_crt *trust_ca,
666                             mbedtls_x509_crl *ca_crl,
667                             const char *cn, uint32_t *flags,
668                             int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
669                             void *p_vrfy);
670 
671 /**
672  * \brief          Verify a chain of certificates with respect to
673  *                 a configurable security profile.
674  *
675  * \note           Same as \c mbedtls_x509_crt_verify(), but with explicit
676  *                 security profile.
677  *
678  * \note           The restrictions on keys (RSA minimum size, allowed curves
679  *                 for ECDSA) apply to all certificates: trusted root,
680  *                 intermediate CAs if any, and end entity certificate.
681  *
682  * \param crt      The certificate chain to be verified.
683  * \param trust_ca The list of trusted CAs.
684  * \param ca_crl   The list of CRLs for trusted CAs.
685  * \param profile  The security profile to use for the verification.
686  * \param cn       The expected Common Name. This may be \c NULL if the
687  *                 CN need not be verified.
688  * \param flags    The address at which to store the result of the verification.
689  *                 If the verification couldn't be completed, the flag value is
690  *                 set to (uint32_t) -1.
691  * \param f_vrfy   The verification callback to use. See the documentation
692  *                 of mbedtls_x509_crt_verify() for more information.
693  * \param p_vrfy   The context to be passed to \p f_vrfy.
694  *
695  * \return         \c 0 if the chain is valid with respect to the
696  *                 passed CN, CAs, CRLs and security profile.
697  * \return         #MBEDTLS_ERR_X509_CERT_VERIFY_FAILED in case the
698  *                 certificate chain verification failed. In this case,
699  *                 \c *flags will have one or more
700  *                 \c MBEDTLS_X509_BADCERT_XXX or \c MBEDTLS_X509_BADCRL_XXX
701  *                 flags set.
702  * \return         Another negative error code in case of a fatal error
703  *                 encountered during the verification process.
704  */
705 int mbedtls_x509_crt_verify_with_profile(mbedtls_x509_crt *crt,
706                                          mbedtls_x509_crt *trust_ca,
707                                          mbedtls_x509_crl *ca_crl,
708                                          const mbedtls_x509_crt_profile *profile,
709                                          const char *cn, uint32_t *flags,
710                                          int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
711                                          void *p_vrfy);
712 
713 /**
714  * \brief          Restartable version of \c mbedtls_crt_verify_with_profile()
715  *
716  * \note           Performs the same job as \c mbedtls_crt_verify_with_profile()
717  *                 but can return early and restart according to the limit
718  *                 set with \c mbedtls_ecp_set_max_ops() to reduce blocking.
719  *
720  * \param crt      The certificate chain to be verified.
721  * \param trust_ca The list of trusted CAs.
722  * \param ca_crl   The list of CRLs for trusted CAs.
723  * \param profile  The security profile to use for the verification.
724  * \param cn       The expected Common Name. This may be \c NULL if the
725  *                 CN need not be verified.
726  * \param flags    The address at which to store the result of the verification.
727  *                 If the verification couldn't be completed, the flag value is
728  *                 set to (uint32_t) -1.
729  * \param f_vrfy   The verification callback to use. See the documentation
730  *                 of mbedtls_x509_crt_verify() for more information.
731  * \param p_vrfy   The context to be passed to \p f_vrfy.
732  * \param rs_ctx   The restart context to use. This may be set to \c NULL
733  *                 to disable restartable ECC.
734  *
735  * \return         See \c mbedtls_crt_verify_with_profile(), or
736  * \return         #PSA_OPERATION_INCOMPLETE if maximum number of
737  *                 operations was reached: see \c mbedtls_ecp_set_max_ops().
738  */
739 int mbedtls_x509_crt_verify_restartable(mbedtls_x509_crt *crt,
740                                         mbedtls_x509_crt *trust_ca,
741                                         mbedtls_x509_crl *ca_crl,
742                                         const mbedtls_x509_crt_profile *profile,
743                                         const char *cn, uint32_t *flags,
744                                         int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
745                                         void *p_vrfy,
746                                         mbedtls_x509_crt_restart_ctx *rs_ctx);
747 
748 /**
749  * \brief               The type of trusted certificate callbacks.
750  *
751  *                      Callbacks of this type are passed to and used by the CRT
752  *                      verification routine mbedtls_x509_crt_verify_with_ca_cb()
753  *                      when looking for trusted signers of a given certificate.
754  *
755  *                      On success, the callback returns a list of trusted
756  *                      certificates to be considered as potential signers
757  *                      for the input certificate.
758  *
759  * \param p_ctx         An opaque context passed to the callback.
760  * \param child         The certificate for which to search a potential signer.
761  *                      This will point to a readable certificate.
762  * \param candidate_cas The address at which to store the address of the first
763  *                      entry in the generated linked list of candidate signers.
764  *                      This will not be \c NULL.
765  *
766  * \note                The callback must only return a non-zero value on a
767  *                      fatal error. If, in contrast, the search for a potential
768  *                      signer completes without a single candidate, the
769  *                      callback must return \c 0 and set \c *candidate_cas
770  *                      to \c NULL.
771  *
772  * \return              \c 0 on success. In this case, \c *candidate_cas points
773  *                      to a heap-allocated linked list of instances of
774  *                      ::mbedtls_x509_crt, and ownership of this list is passed
775  *                      to the caller.
776  * \return              A negative error code on failure.
777  */
778 typedef int (*mbedtls_x509_crt_ca_cb_t)(void *p_ctx,
779                                         mbedtls_x509_crt const *child,
780                                         mbedtls_x509_crt **candidate_cas);
781 
782 #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
783 /**
784  * \brief          Version of \c mbedtls_x509_crt_verify_with_profile() which
785  *                 uses a callback to acquire the list of trusted CA
786  *                 certificates.
787  *
788  * \param crt      The certificate chain to be verified.
789  * \param f_ca_cb  The callback to be used to query for potential signers
790  *                 of a given child certificate. See the documentation of
791  *                 ::mbedtls_x509_crt_ca_cb_t for more information.
792  * \param p_ca_cb  The opaque context to be passed to \p f_ca_cb.
793  * \param profile  The security profile for the verification.
794  * \param cn       The expected Common Name. This may be \c NULL if the
795  *                 CN need not be verified.
796  * \param flags    The address at which to store the result of the verification.
797  *                 If the verification couldn't be completed, the flag value is
798  *                 set to (uint32_t) -1.
799  * \param f_vrfy   The verification callback to use. See the documentation
800  *                 of mbedtls_x509_crt_verify() for more information.
801  * \param p_vrfy   The context to be passed to \p f_vrfy.
802  *
803  * \return         See \c mbedtls_crt_verify_with_profile().
804  */
805 int mbedtls_x509_crt_verify_with_ca_cb(mbedtls_x509_crt *crt,
806                                        mbedtls_x509_crt_ca_cb_t f_ca_cb,
807                                        void *p_ca_cb,
808                                        const mbedtls_x509_crt_profile *profile,
809                                        const char *cn, uint32_t *flags,
810                                        int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
811                                        void *p_vrfy);
812 
813 #endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
814 
815 /**
816  * \brief          Check usage of certificate against keyUsage extension.
817  *
818  * \param crt      Leaf certificate used.
819  * \param usage    Intended usage(s) (eg MBEDTLS_X509_KU_KEY_ENCIPHERMENT
820  *                 before using the certificate to perform an RSA key
821  *                 exchange).
822  *
823  * \note           Except for decipherOnly and encipherOnly, a bit set in the
824  *                 usage argument means this bit MUST be set in the
825  *                 certificate. For decipherOnly and encipherOnly, it means
826  *                 that bit MAY be set.
827  *
828  * \return         0 is these uses of the certificate are allowed,
829  *                 MBEDTLS_ERR_X509_BAD_INPUT_DATA if the keyUsage extension
830  *                 is present but does not match the usage argument.
831  *
832  * \note           You should only call this function on leaf certificates, on
833  *                 (intermediate) CAs the keyUsage extension is automatically
834  *                 checked by \c mbedtls_x509_crt_verify().
835  */
836 int mbedtls_x509_crt_check_key_usage(const mbedtls_x509_crt *crt,
837                                      unsigned int usage);
838 
839 /**
840  * \brief           Check usage of certificate against extendedKeyUsage.
841  *
842  * \param crt       Leaf certificate used.
843  * \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or
844  *                  MBEDTLS_OID_CLIENT_AUTH).
845  * \param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()).
846  *
847  * \return          0 if this use of the certificate is allowed,
848  *                  MBEDTLS_ERR_X509_BAD_INPUT_DATA if not.
849  *
850  * \note            Usually only makes sense on leaf certificates.
851  */
852 int mbedtls_x509_crt_check_extended_key_usage(const mbedtls_x509_crt *crt,
853                                               const char *usage_oid,
854                                               size_t usage_len);
855 
856 #if defined(MBEDTLS_X509_CRL_PARSE_C)
857 /**
858  * \brief          Verify the certificate revocation status
859  *
860  * \param crt      a certificate to be verified
861  * \param crl      the CRL to verify against
862  *
863  * \return         1 if the certificate is revoked, 0 otherwise
864  *
865  */
866 int mbedtls_x509_crt_is_revoked(const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl);
867 #endif /* MBEDTLS_X509_CRL_PARSE_C */
868 
869 /**
870  * \brief          Initialize a certificate (chain)
871  *
872  * \param crt      Certificate chain to initialize
873  */
874 void mbedtls_x509_crt_init(mbedtls_x509_crt *crt);
875 
876 /**
877  * \brief          Unallocate all certificate data
878  *
879  * \param crt      Certificate chain to free
880  */
881 void mbedtls_x509_crt_free(mbedtls_x509_crt *crt);
882 
883 #if defined(MBEDTLS_ECP_RESTARTABLE)
884 /**
885  * \brief           Initialize a restart context
886  */
887 void mbedtls_x509_crt_restart_init(mbedtls_x509_crt_restart_ctx *ctx);
888 
889 /**
890  * \brief           Free the components of a restart context
891  */
892 void mbedtls_x509_crt_restart_free(mbedtls_x509_crt_restart_ctx *ctx);
893 #endif /* MBEDTLS_ECP_RESTARTABLE */
894 #endif /* MBEDTLS_X509_CRT_PARSE_C */
895 
896 /**
897  * \brief               Query certificate for given extension type
898  *
899  * \param[in] ctx       Certificate context to be queried, must not be \c NULL
900  * \param ext_type      Extension type being queried for, must be a valid
901  *                      extension type. Must be one of the MBEDTLS_X509_EXT_XXX
902  *                      values
903  *
904  * \return              0 if the given extension type is not present,
905  *                      non-zero otherwise
906  */
mbedtls_x509_crt_has_ext_type(const mbedtls_x509_crt * ctx,int ext_type)907 static inline int mbedtls_x509_crt_has_ext_type(const mbedtls_x509_crt *ctx,
908                                                 int ext_type)
909 {
910     return ctx->MBEDTLS_PRIVATE(ext_types) & ext_type;
911 }
912 
913 /**
914  * \brief               Access the ca_istrue field
915  *
916  * \param[in] crt       Certificate to be queried, must not be \c NULL
917  *
918  * \return              \c 1 if this a CA certificate \c 0 otherwise.
919  * \return              MBEDTLS_ERR_X509_INVALID_EXTENSIONS if the certificate does not contain
920  *                      the Optional Basic Constraint extension.
921  *
922  */
923 int mbedtls_x509_crt_get_ca_istrue(const mbedtls_x509_crt *crt);
924 
925 /** \} name Structures and functions for parsing and writing X.509 certificates */
926 
927 #if defined(MBEDTLS_X509_CRT_WRITE_C)
928 /**
929  * \brief           Initialize a CRT writing context
930  *
931  * \param ctx       CRT context to initialize
932  */
933 void mbedtls_x509write_crt_init(mbedtls_x509write_cert *ctx);
934 
935 /**
936  * \brief           Set the version for a Certificate
937  *                  Default: MBEDTLS_X509_CRT_VERSION_3
938  *
939  * \param ctx       CRT context to use
940  * \param version   version to set (MBEDTLS_X509_CRT_VERSION_1, MBEDTLS_X509_CRT_VERSION_2 or
941  *                                  MBEDTLS_X509_CRT_VERSION_3)
942  */
943 void mbedtls_x509write_crt_set_version(mbedtls_x509write_cert *ctx, int version);
944 
945 /**
946  * \brief           Set the serial number for a Certificate.
947  *
948  * \param ctx          CRT context to use
949  * \param serial       A raw array of bytes containing the serial number in big
950  *                     endian format
951  * \param serial_len   Length of valid bytes (expressed in bytes) in \p serial
952  *                     input buffer
953  *
954  * \return          0 if successful, or
955  *                  MBEDTLS_ERR_X509_BAD_INPUT_DATA if the provided input buffer
956  *                  is too big (longer than MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN)
957  */
958 int mbedtls_x509write_crt_set_serial_raw(mbedtls_x509write_cert *ctx,
959                                          const unsigned char *serial, size_t serial_len);
960 
961 /**
962  * \brief           Set the validity period for a Certificate
963  *                  Timestamps should be in string format for UTC timezone
964  *                  i.e. "YYYYMMDDhhmmss"
965  *                  e.g. "20131231235959" for December 31st 2013
966  *                       at 23:59:59
967  *
968  * \param ctx       CRT context to use
969  * \param not_before    not_before timestamp
970  * \param not_after     not_after timestamp
971  *
972  * \return          0 if timestamp was parsed successfully, or
973  *                  a specific error code
974  */
975 int mbedtls_x509write_crt_set_validity(mbedtls_x509write_cert *ctx, const char *not_before,
976                                        const char *not_after);
977 
978 /**
979  * \brief           Set the issuer name for a Certificate
980  *                  Issuer names should contain a comma-separated list
981  *                  of OID types and values:
982  *                  e.g. "C=UK,O=ARM,CN=Mbed TLS CA"
983  *
984  * \param ctx           CRT context to use
985  * \param issuer_name   issuer name to set
986  *
987  * \return          0 if issuer name was parsed successfully, or
988  *                  a specific error code
989  */
990 int mbedtls_x509write_crt_set_issuer_name(mbedtls_x509write_cert *ctx,
991                                           const char *issuer_name);
992 
993 /**
994  * \brief           Set the subject name for a Certificate
995  *                  Subject names should contain a comma-separated list
996  *                  of OID types and values:
997  *                  e.g. "C=UK,O=ARM,CN=Mbed TLS Server 1"
998  *
999  * \param ctx           CRT context to use
1000  * \param subject_name  subject name to set
1001  *
1002  * \return          0 if subject name was parsed successfully, or
1003  *                  a specific error code
1004  */
1005 int mbedtls_x509write_crt_set_subject_name(mbedtls_x509write_cert *ctx,
1006                                            const char *subject_name);
1007 
1008 /**
1009  * \brief           Set the subject public key for the certificate
1010  *
1011  * \param ctx       CRT context to use
1012  * \param key       public key to include
1013  */
1014 void mbedtls_x509write_crt_set_subject_key(mbedtls_x509write_cert *ctx, mbedtls_pk_context *key);
1015 
1016 /**
1017  * \brief           Set the issuer key used for signing the certificate
1018  *
1019  * \param ctx       CRT context to use
1020  * \param key       private key to sign with
1021  */
1022 void mbedtls_x509write_crt_set_issuer_key(mbedtls_x509write_cert *ctx, mbedtls_pk_context *key);
1023 
1024 /**
1025  * \brief           Set the MD algorithm to use for the signature
1026  *                  (e.g. MBEDTLS_MD_SHA1)
1027  *
1028  * \param ctx       CRT context to use
1029  * \param md_alg    MD algorithm to use
1030  */
1031 void mbedtls_x509write_crt_set_md_alg(mbedtls_x509write_cert *ctx, mbedtls_md_type_t md_alg);
1032 
1033 /**
1034  * \brief           Generic function to add to or replace an extension in the
1035  *                  CRT
1036  *
1037  * \param ctx       CRT context to use
1038  * \param oid       OID of the extension
1039  * \param oid_len   length of the OID
1040  * \param critical  if the extension is critical (per the RFC's definition)
1041  * \param val       value of the extension OCTET STRING
1042  * \param val_len   length of the value data
1043  *
1044  * \return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
1045  */
1046 int mbedtls_x509write_crt_set_extension(mbedtls_x509write_cert *ctx,
1047                                         const char *oid, size_t oid_len,
1048                                         int critical,
1049                                         const unsigned char *val, size_t val_len);
1050 
1051 /**
1052  * \brief           Set the basicConstraints extension for a CRT
1053  *
1054  * \param ctx       CRT context to use
1055  * \param is_ca     is this a CA certificate
1056  * \param max_pathlen   maximum length of certificate chains below this
1057  *                      certificate (only for CA certificates, -1 is
1058  *                      unlimited)
1059  *
1060  * \return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
1061  */
1062 int mbedtls_x509write_crt_set_basic_constraints(mbedtls_x509write_cert *ctx,
1063                                                 int is_ca, int max_pathlen);
1064 
1065 #if defined(PSA_WANT_ALG_SHA_1)
1066 /**
1067  * \brief           Set the subjectKeyIdentifier extension for a CRT
1068  *                  Requires that mbedtls_x509write_crt_set_subject_key() has been
1069  *                  called before
1070  *
1071  * \param ctx       CRT context to use
1072  *
1073  * \return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
1074  */
1075 int mbedtls_x509write_crt_set_subject_key_identifier(mbedtls_x509write_cert *ctx);
1076 
1077 /**
1078  * \brief           Set the authorityKeyIdentifier extension for a CRT
1079  *                  Requires that mbedtls_x509write_crt_set_issuer_key() has been
1080  *                  called before
1081  *
1082  * \param ctx       CRT context to use
1083  *
1084  * \return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
1085  */
1086 int mbedtls_x509write_crt_set_authority_key_identifier(mbedtls_x509write_cert *ctx);
1087 #endif /* PSA_WANT_ALG_SHA_1 */
1088 
1089 /**
1090  * \brief           Set the Key Usage Extension flags
1091  *                  (e.g. MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_CERT_SIGN)
1092  *
1093  * \param ctx       CRT context to use
1094  * \param key_usage key usage flags to set
1095  *
1096  * \return          0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
1097  */
1098 int mbedtls_x509write_crt_set_key_usage(mbedtls_x509write_cert *ctx,
1099                                         unsigned int key_usage);
1100 
1101 /**
1102  * \brief           Set the Extended Key Usage Extension
1103  *                  (e.g. MBEDTLS_OID_SERVER_AUTH)
1104  *
1105  * \param ctx       CRT context to use
1106  * \param exts      extended key usage extensions to set, a sequence of
1107  *                  MBEDTLS_ASN1_OID objects
1108  *
1109  * \return          0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
1110  */
1111 int mbedtls_x509write_crt_set_ext_key_usage(mbedtls_x509write_cert *ctx,
1112                                             const mbedtls_asn1_sequence *exts);
1113 
1114 /**
1115  * \brief           Set the Netscape Cert Type flags
1116  *                  (e.g. MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT | MBEDTLS_X509_NS_CERT_TYPE_EMAIL)
1117  *
1118  * \param ctx           CRT context to use
1119  * \param ns_cert_type  Netscape Cert Type flags to set
1120  *
1121  * \return          0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
1122  */
1123 int mbedtls_x509write_crt_set_ns_cert_type(mbedtls_x509write_cert *ctx,
1124                                            unsigned char ns_cert_type);
1125 
1126 /**
1127  * \brief           Free the contents of a CRT write context
1128  *
1129  * \param ctx       CRT context to free
1130  */
1131 void mbedtls_x509write_crt_free(mbedtls_x509write_cert *ctx);
1132 
1133 /**
1134  * \brief           Write a built up certificate to a X509 DER structure
1135  *                  Note: data is written at the end of the buffer! Use the
1136  *                        return value to determine where you should start
1137  *                        using the buffer
1138  *
1139  * \param ctx       certificate to write away
1140  * \param buf       buffer to write to
1141  * \param size      size of the buffer
1142  *
1143  * \return          length of data written if successful, or a specific
1144  *                  error code
1145  */
1146 int mbedtls_x509write_crt_der(mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size);
1147 
1148 #if defined(MBEDTLS_PEM_WRITE_C)
1149 /**
1150  * \brief           Write a built up certificate to a X509 PEM string
1151  *
1152  * \param ctx       certificate to write away
1153  * \param buf       buffer to write to
1154  * \param size      size of the buffer
1155  *
1156  * \return          0 if successful, or a specific error code
1157  *
1158  */
1159 int mbedtls_x509write_crt_pem(mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size);
1160 #endif /* MBEDTLS_PEM_WRITE_C */
1161 #endif /* MBEDTLS_X509_CRT_WRITE_C */
1162 
1163 /** \} addtogroup x509_module */
1164 
1165 #ifdef __cplusplus
1166 }
1167 #endif
1168 
1169 #endif /* mbedtls_x509_crt.h */
1170