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