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