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