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