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