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     mbedtls_x509_buf raw;               /**< The raw certificate data (DER). */
56     mbedtls_x509_buf tbs;               /**< The raw certificate body (DER). The part that is To Be Signed. */
57 
58     int version;                /**< The X.509 version. (1=v1, 2=v2, 3=v3) */
59     mbedtls_x509_buf serial;            /**< Unique id for certificate issued by a specific CA. */
60     mbedtls_x509_buf sig_oid;           /**< Signature algorithm, e.g. sha1RSA */
61 
62     mbedtls_x509_buf issuer_raw;        /**< The raw issuer data (DER). Used for quick comparison. */
63     mbedtls_x509_buf subject_raw;       /**< The raw subject data (DER). Used for quick comparison. */
64 
65     mbedtls_x509_name issuer;           /**< The parsed issuer data (named information object). */
66     mbedtls_x509_name subject;          /**< The parsed subject data (named information object). */
67 
68     mbedtls_x509_time valid_from;       /**< Start time of certificate validity. */
69     mbedtls_x509_time valid_to;         /**< End time of certificate validity. */
70 
71     mbedtls_pk_context pk;              /**< Container for the public key context. */
72 
73     mbedtls_x509_buf issuer_id;         /**< Optional X.509 v2/v3 issuer unique identifier. */
74     mbedtls_x509_buf subject_id;        /**< Optional X.509 v2/v3 subject unique identifier. */
75     mbedtls_x509_buf v3_ext;            /**< Optional X.509 v3 extensions.  */
76     mbedtls_x509_sequence subject_alt_names;    /**< Optional list of Subject Alternative Names (Only dNSName supported). */
77 
78     int ext_types;              /**< Bit string containing detected and parsed extensions */
79     int ca_istrue;              /**< Optional Basic Constraint extension value: 1 if this certificate belongs to a CA, 0 otherwise. */
80     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+ */
81 
82     unsigned int key_usage;     /**< Optional key usage extension value: See the values in x509.h */
83 
84     mbedtls_x509_sequence ext_key_usage; /**< Optional list of extended key usage OIDs. */
85 
86     unsigned char ns_cert_type; /**< Optional Netscape certificate type extension value: See the values in x509.h */
87 
88     mbedtls_x509_buf sig;               /**< Signature: hash of the tbs part signed with the private key. */
89     mbedtls_md_type_t sig_md;           /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */
90     mbedtls_pk_type_t sig_pk;           /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */
91     void *sig_opts;             /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */
92 
93     struct mbedtls_x509_crt *next;     /**< Next certificate in the CA-chain. */
94 }
95 mbedtls_x509_crt;
96 
97 /**
98  * Build flag from an algorithm/curve identifier (pk, md, ecp)
99  * Since 0 is always XXX_NONE, ignore it.
100  */
101 #define MBEDTLS_X509_ID_FLAG( id )   ( 1 << ( id - 1 ) )
102 
103 /**
104  * Security profile for certificate verification.
105  *
106  * All lists are bitfields, built by ORing flags from MBEDTLS_X509_ID_FLAG().
107  */
108 typedef struct mbedtls_x509_crt_profile
109 {
110     uint32_t allowed_mds;       /**< MDs for signatures         */
111     uint32_t allowed_pks;       /**< PK algs for signatures     */
112     uint32_t allowed_curves;    /**< Elliptic curves for ECDSA  */
113     uint32_t rsa_min_bitlen;    /**< Minimum size for RSA keys  */
114 }
115 mbedtls_x509_crt_profile;
116 
117 #define MBEDTLS_X509_CRT_VERSION_1              0
118 #define MBEDTLS_X509_CRT_VERSION_2              1
119 #define MBEDTLS_X509_CRT_VERSION_3              2
120 
121 #define MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN 32
122 #define MBEDTLS_X509_RFC5280_UTC_TIME_LEN   15
123 
124 #if !defined( MBEDTLS_X509_MAX_FILE_PATH_LEN )
125 #define MBEDTLS_X509_MAX_FILE_PATH_LEN 512
126 #endif
127 
128 /**
129  * Container for writing a certificate (CRT)
130  */
131 typedef struct mbedtls_x509write_cert
132 {
133     int version;
134     mbedtls_mpi serial;
135     mbedtls_pk_context *subject_key;
136     mbedtls_pk_context *issuer_key;
137     mbedtls_asn1_named_data *subject;
138     mbedtls_asn1_named_data *issuer;
139     mbedtls_md_type_t md_alg;
140     char not_before[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1];
141     char not_after[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1];
142     mbedtls_asn1_named_data *extensions;
143 }
144 mbedtls_x509write_cert;
145 
146 /**
147  * Item in a verification chain: cert and flags for it
148  */
149 typedef struct {
150     mbedtls_x509_crt *crt;
151     uint32_t flags;
152 } mbedtls_x509_crt_verify_chain_item;
153 
154 /**
155  * Max size of verification chain: end-entity + intermediates + trusted root
156  */
157 #define MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE  ( MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2 )
158 
159 /**
160  * Verification chain as built by \c mbedtls_crt_verify_chain()
161  */
162 typedef struct
163 {
164     mbedtls_x509_crt_verify_chain_item items[MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE];
165     unsigned len;
166 } mbedtls_x509_crt_verify_chain;
167 
168 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
169 
170 /**
171  * \brief       Context for resuming X.509 verify operations
172  */
173 typedef struct
174 {
175     /* for check_signature() */
176     mbedtls_pk_restart_ctx pk;
177 
178     /* for find_parent_in() */
179     mbedtls_x509_crt *parent; /* non-null iff parent_in in progress */
180     mbedtls_x509_crt *fallback_parent;
181     int fallback_signature_is_good;
182 
183     /* for find_parent() */
184     int parent_is_trusted; /* -1 if find_parent is not in progress */
185 
186     /* for verify_chain() */
187     enum {
188         x509_crt_rs_none,
189         x509_crt_rs_find_parent,
190     } in_progress;  /* none if no operation is in progress */
191     int self_cnt;
192     mbedtls_x509_crt_verify_chain ver_chain;
193 
194 } mbedtls_x509_crt_restart_ctx;
195 
196 #else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
197 
198 /* Now we can declare functions that take a pointer to that */
199 typedef void mbedtls_x509_crt_restart_ctx;
200 
201 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
202 
203 #if defined(MBEDTLS_X509_CRT_PARSE_C)
204 /**
205  * Default security profile. Should provide a good balance between security
206  * and compatibility with current deployments.
207  */
208 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default;
209 
210 /**
211  * Expected next default profile. Recommended for new deployments.
212  * Currently targets a 128-bit security level, except for RSA-2048.
213  */
214 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next;
215 
216 /**
217  * NSA Suite B profile.
218  */
219 extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb;
220 
221 /**
222  * \brief          Parse a single DER formatted certificate and add it
223  *                 to the chained list.
224  *
225  * \param chain    points to the start of the chain
226  * \param buf      buffer holding the certificate DER data
227  * \param buflen   size of the buffer
228  *
229  * \return         0 if successful, or a specific X509 or PEM error code
230  */
231 int mbedtls_x509_crt_parse_der( mbedtls_x509_crt *chain, const unsigned char *buf,
232                         size_t buflen );
233 
234 /**
235  * \brief          Parse one DER-encoded or one or more concatenated PEM-encoded
236  *                 certificates and add them to the chained list.
237  *
238  *                 For CRTs in PEM encoding, the function parses permissively:
239  *                 if at least one certificate can be parsed, the function
240  *                 returns the number of certificates for which parsing failed
241  *                 (hence \c 0 if all certificates were parsed successfully).
242  *                 If no certificate could be parsed, the function returns
243  *                 the first (negative) error encountered during parsing.
244  *
245  *                 PEM encoded certificates may be interleaved by other data
246  *                 such as human readable descriptions of their content, as
247  *                 long as the certificates are enclosed in the PEM specific
248  *                 '-----{BEGIN/END} CERTIFICATE-----' delimiters.
249  *
250  * \param chain    The chain to which to add the parsed certificates.
251  * \param buf      The buffer holding the certificate data in PEM or DER format.
252  *                 For certificates in PEM encoding, this may be a concatenation
253  *                 of multiple certificates; for DER encoding, the buffer must
254  *                 comprise exactly one certificate.
255  * \param buflen   The size of \p buf, including the terminating \c NULL byte
256  *                 in case of PEM encoded data.
257  *
258  * \return         \c 0 if all certificates were parsed successfully.
259  * \return         The (positive) number of certificates that couldn't
260  *                 be parsed if parsing was partly successful (see above).
261  * \return         A negative X509 or PEM error code otherwise.
262  *
263  */
264 int mbedtls_x509_crt_parse( mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen );
265 
266 #if defined(MBEDTLS_FS_IO)
267 /**
268  * \brief          Load one or more certificates and add them
269  *                 to the chained list. Parses permissively. If some
270  *                 certificates can be parsed, the result is the number
271  *                 of failed certificates it encountered. If none complete
272  *                 correctly, the first error is returned.
273  *
274  * \param chain    points to the start of the chain
275  * \param path     filename to read the certificates from
276  *
277  * \return         0 if all certificates parsed successfully, a positive number
278  *                 if partly successful or a specific X509 or PEM error code
279  */
280 int mbedtls_x509_crt_parse_file( mbedtls_x509_crt *chain, const char *path );
281 
282 /**
283  * \brief          Load one or more certificate files from a path and add them
284  *                 to the chained list. Parses permissively. If some
285  *                 certificates can be parsed, the result is the number
286  *                 of failed certificates it encountered. If none complete
287  *                 correctly, the first error is returned.
288  *
289  * \param chain    points to the start of the chain
290  * \param path     directory / folder to read the certificate files from
291  *
292  * \return         0 if all certificates parsed successfully, a positive number
293  *                 if partly successful or a specific X509 or PEM error code
294  */
295 int mbedtls_x509_crt_parse_path( mbedtls_x509_crt *chain, const char *path );
296 #endif /* MBEDTLS_FS_IO */
297 
298 /* Modify for AliOS Things begin. 2019-06-17 */
299 
300 /**
301  * \brief          Returns an informational string about the
302  *                 subject identifier of the certificate.
303  *
304  * \param buf      Buffer to write to
305  * \param size     Maximum size of buffer
306  * \param crt      The X509 certificate to represent
307  *
308  * \return         The length of the string written (not including the
309  *                 terminated nul byte), or a negative error code.
310  */
311 int mbedtls_x509_subjectid_gets( char *buf, size_t size,
312                                  const mbedtls_x509_crt *crt );
313 
314 /* Modify for AliOS Things end. 2019-06-17 */
315 
316 /**
317  * \brief          Returns an informational string about the
318  *                 certificate.
319  *
320  * \param buf      Buffer to write to
321  * \param size     Maximum size of buffer
322  * \param prefix   A line prefix
323  * \param crt      The X509 certificate to represent
324  *
325  * \return         The length of the string written (not including the
326  *                 terminated nul byte), or a negative error code.
327  */
328 int mbedtls_x509_crt_info( char *buf, size_t size, const char *prefix,
329                    const mbedtls_x509_crt *crt );
330 
331 /**
332  * \brief          Returns an informational string about the
333  *                 verification status of a certificate.
334  *
335  * \param buf      Buffer to write to
336  * \param size     Maximum size of buffer
337  * \param prefix   A line prefix
338  * \param flags    Verification flags created by mbedtls_x509_crt_verify()
339  *
340  * \return         The length of the string written (not including the
341  *                 terminated nul byte), or a negative error code.
342  */
343 int mbedtls_x509_crt_verify_info( char *buf, size_t size, const char *prefix,
344                           uint32_t flags );
345 
346 /**
347  * \brief          Verify the certificate signature
348  *
349  *                 The verify callback is a user-supplied callback that
350  *                 can clear / modify / add flags for a certificate. If set,
351  *                 the verification callback is called for each
352  *                 certificate in the chain (from the trust-ca down to the
353  *                 presented crt). The parameters for the callback are:
354  *                 (void *parameter, mbedtls_x509_crt *crt, int certificate_depth,
355  *                 int *flags). With the flags representing current flags for
356  *                 that specific certificate and the certificate depth from
357  *                 the bottom (Peer cert depth = 0).
358  *
359  *                 All flags left after returning from the callback
360  *                 are also returned to the application. The function should
361  *                 return 0 for anything (including invalid certificates)
362  *                 other than fatal error, as a non-zero return code
363  *                 immediately aborts the verification process. For fatal
364  *                 errors, a specific error code should be used (different
365  *                 from MBEDTLS_ERR_X509_CERT_VERIFY_FAILED which should not
366  *                 be returned at this point), or MBEDTLS_ERR_X509_FATAL_ERROR
367  *                 can be used if no better code is available.
368  *
369  * \note           In case verification failed, the results can be displayed
370  *                 using \c mbedtls_x509_crt_verify_info()
371  *
372  * \note           Same as \c mbedtls_x509_crt_verify_with_profile() with the
373  *                 default security profile.
374  *
375  * \note           It is your responsibility to provide up-to-date CRLs for
376  *                 all trusted CAs. If no CRL is provided for the CA that was
377  *                 used to sign the certificate, CRL verification is skipped
378  *                 silently, that is *without* setting any flag.
379  *
380  * \note           The \c trust_ca list can contain two types of certificates:
381  *                 (1) those of trusted root CAs, so that certificates
382  *                 chaining up to those CAs will be trusted, and (2)
383  *                 self-signed end-entity certificates to be trusted (for
384  *                 specific peers you know) - in that case, the self-signed
385  *                 certificate doesn't need to have the CA bit set.
386  *
387  * \param crt      a certificate (chain) to be verified
388  * \param trust_ca the list of trusted CAs (see note above)
389  * \param ca_crl   the list of CRLs for trusted CAs (see note above)
390  * \param cn       expected Common Name (can be set to
391  *                 NULL if the CN must not be verified)
392  * \param flags    result of the verification
393  * \param f_vrfy   verification function
394  * \param p_vrfy   verification parameter
395  *
396  * \return         0 (and flags set to 0) if the chain was verified and valid,
397  *                 MBEDTLS_ERR_X509_CERT_VERIFY_FAILED if the chain was verified
398  *                 but found to be invalid, in which case *flags will have one
399  *                 or more MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX
400  *                 flags set, or another error (and flags set to 0xffffffff)
401  *                 in case of a fatal error encountered during the
402  *                 verification process.
403  */
404 int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
405                      mbedtls_x509_crt *trust_ca,
406                      mbedtls_x509_crl *ca_crl,
407                      const char *cn, uint32_t *flags,
408                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
409                      void *p_vrfy );
410 
411 /**
412  * \brief          Verify the certificate signature according to profile
413  *
414  * \note           Same as \c mbedtls_x509_crt_verify(), but with explicit
415  *                 security profile.
416  *
417  * \note           The restrictions on keys (RSA minimum size, allowed curves
418  *                 for ECDSA) apply to all certificates: trusted root,
419  *                 intermediate CAs if any, and end entity certificate.
420  *
421  * \param crt      a certificate (chain) to be verified
422  * \param trust_ca the list of trusted CAs
423  * \param ca_crl   the list of CRLs for trusted CAs
424  * \param profile  security profile for verification
425  * \param cn       expected Common Name (can be set to
426  *                 NULL if the CN must not be verified)
427  * \param flags    result of the verification
428  * \param f_vrfy   verification function
429  * \param p_vrfy   verification parameter
430  *
431  * \return         0 if successful or MBEDTLS_ERR_X509_CERT_VERIFY_FAILED
432  *                 in which case *flags will have one or more
433  *                 MBEDTLS_X509_BADCERT_XXX or MBEDTLS_X509_BADCRL_XXX flags
434  *                 set,
435  *                 or another error in case of a fatal error encountered
436  *                 during the verification process.
437  */
438 int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
439                      mbedtls_x509_crt *trust_ca,
440                      mbedtls_x509_crl *ca_crl,
441                      const mbedtls_x509_crt_profile *profile,
442                      const char *cn, uint32_t *flags,
443                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
444                      void *p_vrfy );
445 
446 /**
447  * \brief          Restartable version of \c mbedtls_crt_verify_with_profile()
448  *
449  * \note           Performs the same job as \c mbedtls_crt_verify_with_profile()
450  *                 but can return early and restart according to the limit
451  *                 set with \c mbedtls_ecp_set_max_ops() to reduce blocking.
452  *
453  * \param crt      a certificate (chain) to be verified
454  * \param trust_ca the list of trusted CAs
455  * \param ca_crl   the list of CRLs for trusted CAs
456  * \param profile  security profile for verification
457  * \param cn       expected Common Name (can be set to
458  *                 NULL if the CN must not be verified)
459  * \param flags    result of the verification
460  * \param f_vrfy   verification function
461  * \param p_vrfy   verification parameter
462  * \param rs_ctx   restart context (NULL to disable restart)
463  *
464  * \return         See \c mbedtls_crt_verify_with_profile(), or
465  * \return         #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
466  *                 operations was reached: see \c mbedtls_ecp_set_max_ops().
467  */
468 int mbedtls_x509_crt_verify_restartable( mbedtls_x509_crt *crt,
469                      mbedtls_x509_crt *trust_ca,
470                      mbedtls_x509_crl *ca_crl,
471                      const mbedtls_x509_crt_profile *profile,
472                      const char *cn, uint32_t *flags,
473                      int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
474                      void *p_vrfy,
475                      mbedtls_x509_crt_restart_ctx *rs_ctx );
476 
477 #if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
478 /**
479  * \brief          Check usage of certificate against keyUsage extension.
480  *
481  * \param crt      Leaf certificate used.
482  * \param usage    Intended usage(s) (eg MBEDTLS_X509_KU_KEY_ENCIPHERMENT
483  *                 before using the certificate to perform an RSA key
484  *                 exchange).
485  *
486  * \note           Except for decipherOnly and encipherOnly, a bit set in the
487  *                 usage argument means this bit MUST be set in the
488  *                 certificate. For decipherOnly and encipherOnly, it means
489  *                 that bit MAY be set.
490  *
491  * \return         0 is these uses of the certificate are allowed,
492  *                 MBEDTLS_ERR_X509_BAD_INPUT_DATA if the keyUsage extension
493  *                 is present but does not match the usage argument.
494  *
495  * \note           You should only call this function on leaf certificates, on
496  *                 (intermediate) CAs the keyUsage extension is automatically
497  *                 checked by \c mbedtls_x509_crt_verify().
498  */
499 int mbedtls_x509_crt_check_key_usage( const mbedtls_x509_crt *crt,
500                                       unsigned int usage );
501 #endif /* MBEDTLS_X509_CHECK_KEY_USAGE) */
502 
503 #if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
504 /**
505  * \brief           Check usage of certificate against extendedKeyUsage.
506  *
507  * \param crt       Leaf certificate used.
508  * \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or
509  *                  MBEDTLS_OID_CLIENT_AUTH).
510  * \param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()).
511  *
512  * \return          0 if this use of the certificate is allowed,
513  *                  MBEDTLS_ERR_X509_BAD_INPUT_DATA if not.
514  *
515  * \note            Usually only makes sense on leaf certificates.
516  */
517 int mbedtls_x509_crt_check_extended_key_usage( const mbedtls_x509_crt *crt,
518                                                const char *usage_oid,
519                                                size_t usage_len );
520 #endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
521 
522 #if defined(MBEDTLS_X509_CRL_PARSE_C)
523 /**
524  * \brief          Verify the certificate revocation status
525  *
526  * \param crt      a certificate to be verified
527  * \param crl      the CRL to verify against
528  *
529  * \return         1 if the certificate is revoked, 0 otherwise
530  *
531  */
532 int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl );
533 #endif /* MBEDTLS_X509_CRL_PARSE_C */
534 
535 /**
536  * \brief          Initialize a certificate (chain)
537  *
538  * \param crt      Certificate chain to initialize
539  */
540 void mbedtls_x509_crt_init( mbedtls_x509_crt *crt );
541 
542 /**
543  * \brief          Unallocate all certificate data
544  *
545  * \param crt      Certificate chain to free
546  */
547 void mbedtls_x509_crt_free( mbedtls_x509_crt *crt );
548 
549 #if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
550 /**
551  * \brief           Initialize a restart context
552  */
553 void mbedtls_x509_crt_restart_init( mbedtls_x509_crt_restart_ctx *ctx );
554 
555 /**
556  * \brief           Free the components of a restart context
557  */
558 void mbedtls_x509_crt_restart_free( mbedtls_x509_crt_restart_ctx *ctx );
559 #endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
560 #endif /* MBEDTLS_X509_CRT_PARSE_C */
561 
562 /* \} name */
563 /* \} addtogroup x509_module */
564 
565 #if defined(MBEDTLS_X509_CRT_WRITE_C)
566 /**
567  * \brief           Initialize a CRT writing context
568  *
569  * \param ctx       CRT context to initialize
570  */
571 void mbedtls_x509write_crt_init( mbedtls_x509write_cert *ctx );
572 
573 /**
574  * \brief           Set the verion for a Certificate
575  *                  Default: MBEDTLS_X509_CRT_VERSION_3
576  *
577  * \param ctx       CRT context to use
578  * \param version   version to set (MBEDTLS_X509_CRT_VERSION_1, MBEDTLS_X509_CRT_VERSION_2 or
579  *                                  MBEDTLS_X509_CRT_VERSION_3)
580  */
581 void mbedtls_x509write_crt_set_version( mbedtls_x509write_cert *ctx, int version );
582 
583 /**
584  * \brief           Set the serial number for a Certificate.
585  *
586  * \param ctx       CRT context to use
587  * \param serial    serial number to set
588  *
589  * \return          0 if successful
590  */
591 int mbedtls_x509write_crt_set_serial( mbedtls_x509write_cert *ctx, const mbedtls_mpi *serial );
592 
593 /**
594  * \brief           Set the validity period for a Certificate
595  *                  Timestamps should be in string format for UTC timezone
596  *                  i.e. "YYYYMMDDhhmmss"
597  *                  e.g. "20131231235959" for December 31st 2013
598  *                       at 23:59:59
599  *
600  * \param ctx       CRT context to use
601  * \param not_before    not_before timestamp
602  * \param not_after     not_after timestamp
603  *
604  * \return          0 if timestamp was parsed successfully, or
605  *                  a specific error code
606  */
607 int mbedtls_x509write_crt_set_validity( mbedtls_x509write_cert *ctx, const char *not_before,
608                                 const char *not_after );
609 
610 /**
611  * \brief           Set the issuer name for a Certificate
612  *                  Issuer names should contain a comma-separated list
613  *                  of OID types and values:
614  *                  e.g. "C=UK,O=ARM,CN=mbed TLS CA"
615  *
616  * \param ctx           CRT context to use
617  * \param issuer_name   issuer name to set
618  *
619  * \return          0 if issuer name was parsed successfully, or
620  *                  a specific error code
621  */
622 int mbedtls_x509write_crt_set_issuer_name( mbedtls_x509write_cert *ctx,
623                                    const char *issuer_name );
624 
625 /**
626  * \brief           Set the subject name for a Certificate
627  *                  Subject names should contain a comma-separated list
628  *                  of OID types and values:
629  *                  e.g. "C=UK,O=ARM,CN=mbed TLS Server 1"
630  *
631  * \param ctx           CRT context to use
632  * \param subject_name  subject name to set
633  *
634  * \return          0 if subject name was parsed successfully, or
635  *                  a specific error code
636  */
637 int mbedtls_x509write_crt_set_subject_name( mbedtls_x509write_cert *ctx,
638                                     const char *subject_name );
639 
640 /**
641  * \brief           Set the subject public key for the certificate
642  *
643  * \param ctx       CRT context to use
644  * \param key       public key to include
645  */
646 void mbedtls_x509write_crt_set_subject_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key );
647 
648 /**
649  * \brief           Set the issuer key used for signing the certificate
650  *
651  * \param ctx       CRT context to use
652  * \param key       private key to sign with
653  */
654 void mbedtls_x509write_crt_set_issuer_key( mbedtls_x509write_cert *ctx, mbedtls_pk_context *key );
655 
656 /**
657  * \brief           Set the MD algorithm to use for the signature
658  *                  (e.g. MBEDTLS_MD_SHA1)
659  *
660  * \param ctx       CRT context to use
661  * \param md_alg    MD algorithm to use
662  */
663 void mbedtls_x509write_crt_set_md_alg( mbedtls_x509write_cert *ctx, mbedtls_md_type_t md_alg );
664 
665 /**
666  * \brief           Generic function to add to or replace an extension in the
667  *                  CRT
668  *
669  * \param ctx       CRT context to use
670  * \param oid       OID of the extension
671  * \param oid_len   length of the OID
672  * \param critical  if the extension is critical (per the RFC's definition)
673  * \param val       value of the extension OCTET STRING
674  * \param val_len   length of the value data
675  *
676  * \return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
677  */
678 int mbedtls_x509write_crt_set_extension( mbedtls_x509write_cert *ctx,
679                                  const char *oid, size_t oid_len,
680                                  int critical,
681                                  const unsigned char *val, size_t val_len );
682 
683 /**
684  * \brief           Set the basicConstraints extension for a CRT
685  *
686  * \param ctx       CRT context to use
687  * \param is_ca     is this a CA certificate
688  * \param max_pathlen   maximum length of certificate chains below this
689  *                      certificate (only for CA certificates, -1 is
690  *                      inlimited)
691  *
692  * \return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
693  */
694 int mbedtls_x509write_crt_set_basic_constraints( mbedtls_x509write_cert *ctx,
695                                          int is_ca, int max_pathlen );
696 
697 #if defined(MBEDTLS_SHA1_C)
698 /**
699  * \brief           Set the subjectKeyIdentifier extension for a CRT
700  *                  Requires that mbedtls_x509write_crt_set_subject_key() has been
701  *                  called before
702  *
703  * \param ctx       CRT context to use
704  *
705  * \return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
706  */
707 int mbedtls_x509write_crt_set_subject_key_identifier( mbedtls_x509write_cert *ctx );
708 
709 /**
710  * \brief           Set the authorityKeyIdentifier extension for a CRT
711  *                  Requires that mbedtls_x509write_crt_set_issuer_key() has been
712  *                  called before
713  *
714  * \param ctx       CRT context to use
715  *
716  * \return          0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
717  */
718 int mbedtls_x509write_crt_set_authority_key_identifier( mbedtls_x509write_cert *ctx );
719 #endif /* MBEDTLS_SHA1_C */
720 
721 /**
722  * \brief           Set the Key Usage Extension flags
723  *                  (e.g. MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_CERT_SIGN)
724  *
725  * \param ctx       CRT context to use
726  * \param key_usage key usage flags to set
727  *
728  * \return          0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
729  */
730 int mbedtls_x509write_crt_set_key_usage( mbedtls_x509write_cert *ctx,
731                                          unsigned int key_usage );
732 
733 /**
734  * \brief           Set the Netscape Cert Type flags
735  *                  (e.g. MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT | MBEDTLS_X509_NS_CERT_TYPE_EMAIL)
736  *
737  * \param ctx           CRT context to use
738  * \param ns_cert_type  Netscape Cert Type flags to set
739  *
740  * \return          0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
741  */
742 int mbedtls_x509write_crt_set_ns_cert_type( mbedtls_x509write_cert *ctx,
743                                     unsigned char ns_cert_type );
744 
745 /**
746  * \brief           Free the contents of a CRT write context
747  *
748  * \param ctx       CRT context to free
749  */
750 void mbedtls_x509write_crt_free( mbedtls_x509write_cert *ctx );
751 
752 /**
753  * \brief           Write a built up certificate to a X509 DER structure
754  *                  Note: data is written at the end of the buffer! Use the
755  *                        return value to determine where you should start
756  *                        using the buffer
757  *
758  * \param ctx       certificate to write away
759  * \param buf       buffer to write to
760  * \param size      size of the buffer
761  * \param f_rng     RNG function (for signature, see note)
762  * \param p_rng     RNG parameter
763  *
764  * \return          length of data written if successful, or a specific
765  *                  error code
766  *
767  * \note            f_rng may be NULL if RSA is used for signature and the
768  *                  signature is made offline (otherwise f_rng is desirable
769  *                  for countermeasures against timing attacks).
770  *                  ECDSA signatures always require a non-NULL f_rng.
771  */
772 int mbedtls_x509write_crt_der( mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size,
773                        int (*f_rng)(void *, unsigned char *, size_t),
774                        void *p_rng );
775 
776 #if defined(MBEDTLS_PEM_WRITE_C)
777 /**
778  * \brief           Write a built up certificate to a X509 PEM string
779  *
780  * \param ctx       certificate to write away
781  * \param buf       buffer to write to
782  * \param size      size of the buffer
783  * \param f_rng     RNG function (for signature, see note)
784  * \param p_rng     RNG parameter
785  *
786  * \return          0 if successful, or a specific error code
787  *
788  * \note            f_rng may be NULL if RSA is used for signature and the
789  *                  signature is made offline (otherwise f_rng is desirable
790  *                  for countermeasures against timing attacks).
791  *                  ECDSA signatures always require a non-NULL f_rng.
792  */
793 int mbedtls_x509write_crt_pem( mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size,
794                        int (*f_rng)(void *, unsigned char *, size_t),
795                        void *p_rng );
796 #endif /* MBEDTLS_PEM_WRITE_C */
797 #endif /* MBEDTLS_X509_CRT_WRITE_C */
798 
799 #ifdef __cplusplus
800 }
801 #endif
802 
803 #endif /* mbedtls_x509_crt.h */
804