• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  X.509 certificate writing
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 /*
8  * References:
9  * - certificates: RFC 5280, updated by RFC 6818
10  * - CSRs: PKCS#10 v1.7 aka RFC 2986
11  * - attributes: PKCS#9 v2.0 aka RFC 2985
12  */
13 
14 #include "common.h"
15 
16 #if defined(MBEDTLS_X509_CRT_WRITE_C)
17 
18 #include "mbedtls/x509_crt.h"
19 #include "x509_internal.h"
20 #include "mbedtls/asn1write.h"
21 #include "mbedtls/error.h"
22 #include "mbedtls/oid.h"
23 #include "mbedtls/platform.h"
24 #include "mbedtls/platform_util.h"
25 #include "mbedtls/md.h"
26 
27 #include <string.h>
28 #include <stdint.h>
29 
30 #if defined(MBEDTLS_PEM_WRITE_C)
31 #include "mbedtls/pem.h"
32 #endif /* MBEDTLS_PEM_WRITE_C */
33 
34 #if defined(MBEDTLS_USE_PSA_CRYPTO)
35 #include "psa/crypto.h"
36 #include "psa_util_internal.h"
37 #include "mbedtls/psa_util.h"
38 #endif /* MBEDTLS_USE_PSA_CRYPTO */
39 
mbedtls_x509write_crt_init(mbedtls_x509write_cert * ctx)40 void mbedtls_x509write_crt_init(mbedtls_x509write_cert *ctx)
41 {
42     memset(ctx, 0, sizeof(mbedtls_x509write_cert));
43 
44     ctx->version = MBEDTLS_X509_CRT_VERSION_3;
45 }
46 
mbedtls_x509write_crt_free(mbedtls_x509write_cert * ctx)47 void mbedtls_x509write_crt_free(mbedtls_x509write_cert *ctx)
48 {
49     mbedtls_asn1_free_named_data_list(&ctx->subject);
50     mbedtls_asn1_free_named_data_list(&ctx->issuer);
51     mbedtls_asn1_free_named_data_list(&ctx->extensions);
52 
53     mbedtls_platform_zeroize(ctx, sizeof(mbedtls_x509write_cert));
54 }
55 
mbedtls_x509write_crt_set_version(mbedtls_x509write_cert * ctx,int version)56 void mbedtls_x509write_crt_set_version(mbedtls_x509write_cert *ctx,
57                                        int version)
58 {
59     ctx->version = version;
60 }
61 
mbedtls_x509write_crt_set_md_alg(mbedtls_x509write_cert * ctx,mbedtls_md_type_t md_alg)62 void mbedtls_x509write_crt_set_md_alg(mbedtls_x509write_cert *ctx,
63                                       mbedtls_md_type_t md_alg)
64 {
65     ctx->md_alg = md_alg;
66 }
67 
mbedtls_x509write_crt_set_subject_key(mbedtls_x509write_cert * ctx,mbedtls_pk_context * key)68 void mbedtls_x509write_crt_set_subject_key(mbedtls_x509write_cert *ctx,
69                                            mbedtls_pk_context *key)
70 {
71     ctx->subject_key = key;
72 }
73 
mbedtls_x509write_crt_set_issuer_key(mbedtls_x509write_cert * ctx,mbedtls_pk_context * key)74 void mbedtls_x509write_crt_set_issuer_key(mbedtls_x509write_cert *ctx,
75                                           mbedtls_pk_context *key)
76 {
77     ctx->issuer_key = key;
78 }
79 
mbedtls_x509write_crt_set_subject_name(mbedtls_x509write_cert * ctx,const char * subject_name)80 int mbedtls_x509write_crt_set_subject_name(mbedtls_x509write_cert *ctx,
81                                            const char *subject_name)
82 {
83     mbedtls_asn1_free_named_data_list(&ctx->subject);
84     return mbedtls_x509_string_to_names(&ctx->subject, subject_name);
85 }
86 
mbedtls_x509write_crt_set_issuer_name(mbedtls_x509write_cert * ctx,const char * issuer_name)87 int mbedtls_x509write_crt_set_issuer_name(mbedtls_x509write_cert *ctx,
88                                           const char *issuer_name)
89 {
90     mbedtls_asn1_free_named_data_list(&ctx->issuer);
91     return mbedtls_x509_string_to_names(&ctx->issuer, issuer_name);
92 }
93 
94 #if defined(MBEDTLS_BIGNUM_C) && !defined(MBEDTLS_DEPRECATED_REMOVED)
mbedtls_x509write_crt_set_serial(mbedtls_x509write_cert * ctx,const mbedtls_mpi * serial)95 int mbedtls_x509write_crt_set_serial(mbedtls_x509write_cert *ctx,
96                                      const mbedtls_mpi *serial)
97 {
98     int ret;
99     size_t tmp_len;
100 
101     /* Ensure that the MPI value fits into the buffer */
102     tmp_len = mbedtls_mpi_size(serial);
103     if (tmp_len > MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN) {
104         return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
105     }
106 
107     ctx->serial_len = tmp_len;
108 
109     ret = mbedtls_mpi_write_binary(serial, ctx->serial, tmp_len);
110     if (ret < 0) {
111         return ret;
112     }
113 
114     return 0;
115 }
116 #endif // MBEDTLS_BIGNUM_C && !MBEDTLS_DEPRECATED_REMOVED
117 
mbedtls_x509write_crt_set_serial_raw(mbedtls_x509write_cert * ctx,unsigned char * serial,size_t serial_len)118 int mbedtls_x509write_crt_set_serial_raw(mbedtls_x509write_cert *ctx,
119                                          unsigned char *serial, size_t serial_len)
120 {
121     if (serial_len > MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN) {
122         return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
123     }
124 
125     ctx->serial_len = serial_len;
126     memcpy(ctx->serial, serial, serial_len);
127 
128     return 0;
129 }
130 
mbedtls_x509write_crt_set_validity(mbedtls_x509write_cert * ctx,const char * not_before,const char * not_after)131 int mbedtls_x509write_crt_set_validity(mbedtls_x509write_cert *ctx,
132                                        const char *not_before,
133                                        const char *not_after)
134 {
135     if (strlen(not_before) != MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1 ||
136         strlen(not_after)  != MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1) {
137         return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
138     }
139     strncpy(ctx->not_before, not_before, MBEDTLS_X509_RFC5280_UTC_TIME_LEN);
140     strncpy(ctx->not_after, not_after, MBEDTLS_X509_RFC5280_UTC_TIME_LEN);
141     ctx->not_before[MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1] = 'Z';
142     ctx->not_after[MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1] = 'Z';
143 
144     return 0;
145 }
146 
mbedtls_x509write_crt_set_subject_alternative_name(mbedtls_x509write_cert * ctx,const mbedtls_x509_san_list * san_list)147 int mbedtls_x509write_crt_set_subject_alternative_name(mbedtls_x509write_cert *ctx,
148                                                        const mbedtls_x509_san_list *san_list)
149 {
150     return mbedtls_x509_write_set_san_common(&ctx->extensions, san_list);
151 }
152 
153 
mbedtls_x509write_crt_set_extension(mbedtls_x509write_cert * ctx,const char * oid,size_t oid_len,int critical,const unsigned char * val,size_t val_len)154 int mbedtls_x509write_crt_set_extension(mbedtls_x509write_cert *ctx,
155                                         const char *oid, size_t oid_len,
156                                         int critical,
157                                         const unsigned char *val, size_t val_len)
158 {
159     return mbedtls_x509_set_extension(&ctx->extensions, oid, oid_len,
160                                       critical, val, val_len);
161 }
162 
mbedtls_x509write_crt_set_basic_constraints(mbedtls_x509write_cert * ctx,int is_ca,int max_pathlen)163 int mbedtls_x509write_crt_set_basic_constraints(mbedtls_x509write_cert *ctx,
164                                                 int is_ca, int max_pathlen)
165 {
166     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
167     unsigned char buf[9];
168     unsigned char *c = buf + sizeof(buf);
169     size_t len = 0;
170 
171     memset(buf, 0, sizeof(buf));
172 
173     if (is_ca && max_pathlen > 127) {
174         return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
175     }
176 
177     if (is_ca) {
178         if (max_pathlen >= 0) {
179             MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_int(&c, buf,
180                                                              max_pathlen));
181         }
182         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_bool(&c, buf, 1));
183     }
184 
185     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
186     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(&c, buf,
187                                                      MBEDTLS_ASN1_CONSTRUCTED |
188                                                      MBEDTLS_ASN1_SEQUENCE));
189 
190     return
191         mbedtls_x509write_crt_set_extension(ctx, MBEDTLS_OID_BASIC_CONSTRAINTS,
192                                             MBEDTLS_OID_SIZE(MBEDTLS_OID_BASIC_CONSTRAINTS),
193                                             is_ca, buf + sizeof(buf) - len, len);
194 }
195 
196 #if defined(MBEDTLS_MD_CAN_SHA1)
mbedtls_x509write_crt_set_key_identifier(mbedtls_x509write_cert * ctx,int is_ca,unsigned char tag)197 static int mbedtls_x509write_crt_set_key_identifier(mbedtls_x509write_cert *ctx,
198                                                     int is_ca,
199                                                     unsigned char tag)
200 {
201     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
202     unsigned char buf[MBEDTLS_MPI_MAX_SIZE * 2 + 20]; /* tag, length + 2xMPI */
203     unsigned char *c = buf + sizeof(buf);
204     size_t len = 0;
205 #if defined(MBEDTLS_USE_PSA_CRYPTO)
206     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
207     size_t hash_length;
208 #endif /* MBEDTLS_USE_PSA_CRYPTO */
209 
210     memset(buf, 0, sizeof(buf));
211     MBEDTLS_ASN1_CHK_ADD(len,
212                          mbedtls_pk_write_pubkey(&c,
213                                                  buf,
214                                                  is_ca ?
215                                                  ctx->issuer_key :
216                                                  ctx->subject_key));
217 
218 
219 #if defined(MBEDTLS_USE_PSA_CRYPTO)
220     status = psa_hash_compute(PSA_ALG_SHA_1,
221                               buf + sizeof(buf) - len,
222                               len,
223                               buf + sizeof(buf) - 20,
224                               20,
225                               &hash_length);
226     if (status != PSA_SUCCESS) {
227         return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
228     }
229 #else
230     ret = mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1),
231                      buf + sizeof(buf) - len, len,
232                      buf + sizeof(buf) - 20);
233     if (ret != 0) {
234         return ret;
235     }
236 #endif /* MBEDTLS_USE_PSA_CRYPTO */
237 
238     c = buf + sizeof(buf) - 20;
239     len = 20;
240 
241     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
242     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(&c, buf, tag));
243 
244     if (is_ca) { // writes AuthorityKeyIdentifier sequence
245         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
246         MBEDTLS_ASN1_CHK_ADD(len,
247                              mbedtls_asn1_write_tag(&c,
248                                                     buf,
249                                                     MBEDTLS_ASN1_CONSTRUCTED |
250                                                     MBEDTLS_ASN1_SEQUENCE));
251     }
252 
253     if (is_ca) {
254         return mbedtls_x509write_crt_set_extension(ctx,
255                                                    MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER,
256                                                    MBEDTLS_OID_SIZE(
257                                                        MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER),
258                                                    0, buf + sizeof(buf) - len, len);
259     } else {
260         return mbedtls_x509write_crt_set_extension(ctx,
261                                                    MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER,
262                                                    MBEDTLS_OID_SIZE(
263                                                        MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER),
264                                                    0, buf + sizeof(buf) - len, len);
265     }
266 }
267 
mbedtls_x509write_crt_set_subject_key_identifier(mbedtls_x509write_cert * ctx)268 int mbedtls_x509write_crt_set_subject_key_identifier(mbedtls_x509write_cert *ctx)
269 {
270     return mbedtls_x509write_crt_set_key_identifier(ctx,
271                                                     0,
272                                                     MBEDTLS_ASN1_OCTET_STRING);
273 }
274 
mbedtls_x509write_crt_set_authority_key_identifier(mbedtls_x509write_cert * ctx)275 int mbedtls_x509write_crt_set_authority_key_identifier(mbedtls_x509write_cert *ctx)
276 {
277     return mbedtls_x509write_crt_set_key_identifier(ctx,
278                                                     1,
279                                                     (MBEDTLS_ASN1_CONTEXT_SPECIFIC | 0));
280 }
281 #endif /* MBEDTLS_MD_CAN_SHA1 */
282 
mbedtls_x509write_crt_set_key_usage(mbedtls_x509write_cert * ctx,unsigned int key_usage)283 int mbedtls_x509write_crt_set_key_usage(mbedtls_x509write_cert *ctx,
284                                         unsigned int key_usage)
285 {
286     unsigned char buf[5] = { 0 }, ku[2] = { 0 };
287     unsigned char *c;
288     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
289     const unsigned int allowed_bits = MBEDTLS_X509_KU_DIGITAL_SIGNATURE |
290                                       MBEDTLS_X509_KU_NON_REPUDIATION   |
291                                       MBEDTLS_X509_KU_KEY_ENCIPHERMENT  |
292                                       MBEDTLS_X509_KU_DATA_ENCIPHERMENT |
293                                       MBEDTLS_X509_KU_KEY_AGREEMENT     |
294                                       MBEDTLS_X509_KU_KEY_CERT_SIGN     |
295                                       MBEDTLS_X509_KU_CRL_SIGN          |
296                                       MBEDTLS_X509_KU_ENCIPHER_ONLY     |
297                                       MBEDTLS_X509_KU_DECIPHER_ONLY;
298 
299     /* Check that nothing other than the allowed flags is set */
300     if ((key_usage & ~allowed_bits) != 0) {
301         return MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE;
302     }
303 
304     c = buf + 5;
305     MBEDTLS_PUT_UINT16_LE(key_usage, ku, 0);
306     ret = mbedtls_asn1_write_named_bitstring(&c, buf, ku, 9);
307 
308     if (ret < 0) {
309         return ret;
310     } else if (ret < 3 || ret > 5) {
311         return MBEDTLS_ERR_X509_INVALID_FORMAT;
312     }
313 
314     ret = mbedtls_x509write_crt_set_extension(ctx, MBEDTLS_OID_KEY_USAGE,
315                                               MBEDTLS_OID_SIZE(MBEDTLS_OID_KEY_USAGE),
316                                               1, c, (size_t) ret);
317     if (ret != 0) {
318         return ret;
319     }
320 
321     return 0;
322 }
323 
mbedtls_x509write_crt_set_ext_key_usage(mbedtls_x509write_cert * ctx,const mbedtls_asn1_sequence * exts)324 int mbedtls_x509write_crt_set_ext_key_usage(mbedtls_x509write_cert *ctx,
325                                             const mbedtls_asn1_sequence *exts)
326 {
327     unsigned char buf[256];
328     unsigned char *c = buf + sizeof(buf);
329     int ret;
330     size_t len = 0;
331     const mbedtls_asn1_sequence *last_ext = NULL;
332     const mbedtls_asn1_sequence *ext;
333 
334     memset(buf, 0, sizeof(buf));
335 
336     /* We need at least one extension: SEQUENCE SIZE (1..MAX) OF KeyPurposeId */
337     if (exts == NULL) {
338         return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
339     }
340 
341     /* Iterate over exts backwards, so we write them out in the requested order */
342     while (last_ext != exts) {
343         for (ext = exts; ext->next != last_ext; ext = ext->next) {
344         }
345         if (ext->buf.tag != MBEDTLS_ASN1_OID) {
346             return MBEDTLS_ERR_X509_BAD_INPUT_DATA;
347         }
348         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_raw_buffer(&c, buf, ext->buf.p, ext->buf.len));
349         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, ext->buf.len));
350         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_OID));
351         last_ext = ext;
352     }
353 
354     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
355     MBEDTLS_ASN1_CHK_ADD(len,
356                          mbedtls_asn1_write_tag(&c, buf,
357                                                 MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE));
358 
359     return mbedtls_x509write_crt_set_extension(ctx,
360                                                MBEDTLS_OID_EXTENDED_KEY_USAGE,
361                                                MBEDTLS_OID_SIZE(MBEDTLS_OID_EXTENDED_KEY_USAGE),
362                                                1, c, len);
363 }
364 
mbedtls_x509write_crt_set_ns_cert_type(mbedtls_x509write_cert * ctx,unsigned char ns_cert_type)365 int mbedtls_x509write_crt_set_ns_cert_type(mbedtls_x509write_cert *ctx,
366                                            unsigned char ns_cert_type)
367 {
368     unsigned char buf[4] = { 0 };
369     unsigned char *c;
370     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
371 
372     c = buf + 4;
373 
374     ret = mbedtls_asn1_write_named_bitstring(&c, buf, &ns_cert_type, 8);
375     if (ret < 3 || ret > 4) {
376         return ret;
377     }
378 
379     ret = mbedtls_x509write_crt_set_extension(ctx, MBEDTLS_OID_NS_CERT_TYPE,
380                                               MBEDTLS_OID_SIZE(MBEDTLS_OID_NS_CERT_TYPE),
381                                               0, c, (size_t) ret);
382     if (ret != 0) {
383         return ret;
384     }
385 
386     return 0;
387 }
388 
x509_write_time(unsigned char ** p,unsigned char * start,const char * t,size_t size)389 static int x509_write_time(unsigned char **p, unsigned char *start,
390                            const char *t, size_t size)
391 {
392     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
393     size_t len = 0;
394 
395     /*
396      * write MBEDTLS_ASN1_UTC_TIME if year < 2050 (2 bytes shorter)
397      */
398     if (t[0] < '2' || (t[0] == '2' && t[1] == '0' && t[2] < '5')) {
399         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_raw_buffer(p, start,
400                                                                 (const unsigned char *) t + 2,
401                                                                 size - 2));
402         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
403         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start,
404                                                          MBEDTLS_ASN1_UTC_TIME));
405     } else {
406         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_raw_buffer(p, start,
407                                                                 (const unsigned char *) t,
408                                                                 size));
409         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
410         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start,
411                                                          MBEDTLS_ASN1_GENERALIZED_TIME));
412     }
413 
414     return (int) len;
415 }
416 
mbedtls_x509write_crt_der(mbedtls_x509write_cert * ctx,unsigned char * buf,size_t size,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)417 int mbedtls_x509write_crt_der(mbedtls_x509write_cert *ctx,
418                               unsigned char *buf, size_t size,
419                               int (*f_rng)(void *, unsigned char *, size_t),
420                               void *p_rng)
421 {
422     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
423     const char *sig_oid;
424     size_t sig_oid_len = 0;
425     unsigned char *c, *c2;
426     unsigned char sig[MBEDTLS_PK_SIGNATURE_MAX_SIZE];
427     size_t hash_length = 0;
428     unsigned char hash[MBEDTLS_MD_MAX_SIZE];
429 #if defined(MBEDTLS_USE_PSA_CRYPTO)
430     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
431     psa_algorithm_t psa_algorithm;
432 #endif /* MBEDTLS_USE_PSA_CRYPTO */
433 
434     size_t sub_len = 0, pub_len = 0, sig_and_oid_len = 0, sig_len;
435     size_t len = 0;
436     mbedtls_pk_type_t pk_alg;
437     int write_sig_null_par;
438 
439     /*
440      * Prepare data to be signed at the end of the target buffer
441      */
442     c = buf + size;
443 
444     /* Signature algorithm needed in TBS, and later for actual signature */
445 
446     /* There's no direct way of extracting a signature algorithm
447      * (represented as an element of mbedtls_pk_type_t) from a PK instance. */
448     if (mbedtls_pk_can_do(ctx->issuer_key, MBEDTLS_PK_RSA)) {
449         pk_alg = MBEDTLS_PK_RSA;
450     } else if (mbedtls_pk_can_do(ctx->issuer_key, MBEDTLS_PK_ECDSA)) {
451         pk_alg = MBEDTLS_PK_ECDSA;
452     } else {
453         return MBEDTLS_ERR_X509_INVALID_ALG;
454     }
455 
456     if ((ret = mbedtls_oid_get_oid_by_sig_alg(pk_alg, ctx->md_alg,
457                                               &sig_oid, &sig_oid_len)) != 0) {
458         return ret;
459     }
460 
461     /*
462      *  Extensions  ::=  SEQUENCE SIZE (1..MAX) OF Extension
463      */
464 
465     /* Only for v3 */
466     if (ctx->version == MBEDTLS_X509_CRT_VERSION_3) {
467         MBEDTLS_ASN1_CHK_ADD(len,
468                              mbedtls_x509_write_extensions(&c,
469                                                            buf, ctx->extensions));
470         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
471         MBEDTLS_ASN1_CHK_ADD(len,
472                              mbedtls_asn1_write_tag(&c, buf,
473                                                     MBEDTLS_ASN1_CONSTRUCTED |
474                                                     MBEDTLS_ASN1_SEQUENCE));
475         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
476         MBEDTLS_ASN1_CHK_ADD(len,
477                              mbedtls_asn1_write_tag(&c, buf,
478                                                     MBEDTLS_ASN1_CONTEXT_SPECIFIC |
479                                                     MBEDTLS_ASN1_CONSTRUCTED | 3));
480     }
481 
482     /*
483      *  SubjectPublicKeyInfo
484      */
485     MBEDTLS_ASN1_CHK_ADD(pub_len,
486                          mbedtls_pk_write_pubkey_der(ctx->subject_key,
487                                                      buf, (size_t) (c - buf)));
488     c -= pub_len;
489     len += pub_len;
490 
491     /*
492      *  Subject  ::=  Name
493      */
494     MBEDTLS_ASN1_CHK_ADD(len,
495                          mbedtls_x509_write_names(&c, buf,
496                                                   ctx->subject));
497 
498     /*
499      *  Validity ::= SEQUENCE {
500      *       notBefore      Time,
501      *       notAfter       Time }
502      */
503     sub_len = 0;
504 
505     MBEDTLS_ASN1_CHK_ADD(sub_len,
506                          x509_write_time(&c, buf, ctx->not_after,
507                                          MBEDTLS_X509_RFC5280_UTC_TIME_LEN));
508 
509     MBEDTLS_ASN1_CHK_ADD(sub_len,
510                          x509_write_time(&c, buf, ctx->not_before,
511                                          MBEDTLS_X509_RFC5280_UTC_TIME_LEN));
512 
513     len += sub_len;
514     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, sub_len));
515     MBEDTLS_ASN1_CHK_ADD(len,
516                          mbedtls_asn1_write_tag(&c, buf,
517                                                 MBEDTLS_ASN1_CONSTRUCTED |
518                                                 MBEDTLS_ASN1_SEQUENCE));
519 
520     /*
521      *  Issuer  ::=  Name
522      */
523     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_x509_write_names(&c, buf,
524                                                        ctx->issuer));
525 
526     /*
527      *  Signature   ::=  AlgorithmIdentifier
528      */
529     if (pk_alg == MBEDTLS_PK_ECDSA) {
530         /*
531          * The AlgorithmIdentifier's parameters field must be absent for DSA/ECDSA signature
532          * algorithms, see https://www.rfc-editor.org/rfc/rfc5480#page-17 and
533          * https://www.rfc-editor.org/rfc/rfc5758#section-3.
534          */
535         write_sig_null_par = 0;
536     } else {
537         write_sig_null_par = 1;
538     }
539     MBEDTLS_ASN1_CHK_ADD(len,
540                          mbedtls_asn1_write_algorithm_identifier_ext(&c, buf,
541                                                                      sig_oid, strlen(sig_oid),
542                                                                      0, write_sig_null_par));
543 
544     /*
545      *  Serial   ::=  INTEGER
546      *
547      * Written data is:
548      * - "ctx->serial_len" bytes for the raw serial buffer
549      *   - if MSb of "serial" is 1, then prepend an extra 0x00 byte
550      * - 1 byte for the length
551      * - 1 byte for the TAG
552      */
553     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_raw_buffer(&c, buf,
554                                                             ctx->serial, ctx->serial_len));
555     if (*c & 0x80) {
556         if (c - buf < 1) {
557             return MBEDTLS_ERR_X509_BUFFER_TOO_SMALL;
558         }
559         *(--c) = 0x0;
560         len++;
561         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf,
562                                                          ctx->serial_len + 1));
563     } else {
564         MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf,
565                                                          ctx->serial_len));
566     }
567     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(&c, buf,
568                                                      MBEDTLS_ASN1_INTEGER));
569 
570     /*
571      *  Version  ::=  INTEGER  {  v1(0), v2(1), v3(2)  }
572      */
573 
574     /* Can be omitted for v1 */
575     if (ctx->version != MBEDTLS_X509_CRT_VERSION_1) {
576         sub_len = 0;
577         MBEDTLS_ASN1_CHK_ADD(sub_len,
578                              mbedtls_asn1_write_int(&c, buf, ctx->version));
579         len += sub_len;
580         MBEDTLS_ASN1_CHK_ADD(len,
581                              mbedtls_asn1_write_len(&c, buf, sub_len));
582         MBEDTLS_ASN1_CHK_ADD(len,
583                              mbedtls_asn1_write_tag(&c, buf,
584                                                     MBEDTLS_ASN1_CONTEXT_SPECIFIC |
585                                                     MBEDTLS_ASN1_CONSTRUCTED | 0));
586     }
587 
588     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
589     MBEDTLS_ASN1_CHK_ADD(len,
590                          mbedtls_asn1_write_tag(&c, buf, MBEDTLS_ASN1_CONSTRUCTED |
591                                                 MBEDTLS_ASN1_SEQUENCE));
592 
593     /*
594      * Make signature
595      */
596 
597     /* Compute hash of CRT. */
598 #if defined(MBEDTLS_USE_PSA_CRYPTO)
599     psa_algorithm = mbedtls_md_psa_alg_from_type(ctx->md_alg);
600 
601     status = psa_hash_compute(psa_algorithm,
602                               c,
603                               len,
604                               hash,
605                               sizeof(hash),
606                               &hash_length);
607     if (status != PSA_SUCCESS) {
608         return MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED;
609     }
610 #else
611     if ((ret = mbedtls_md(mbedtls_md_info_from_type(ctx->md_alg), c,
612                           len, hash)) != 0) {
613         return ret;
614     }
615 #endif /* MBEDTLS_USE_PSA_CRYPTO */
616 
617 
618     if ((ret = mbedtls_pk_sign(ctx->issuer_key, ctx->md_alg,
619                                hash, hash_length, sig, sizeof(sig), &sig_len,
620                                f_rng, p_rng)) != 0) {
621         return ret;
622     }
623 
624     /* Move CRT to the front of the buffer to have space
625      * for the signature. */
626     memmove(buf, c, len);
627     c = buf + len;
628 
629     /* Add signature at the end of the buffer,
630      * making sure that it doesn't underflow
631      * into the CRT buffer. */
632     c2 = buf + size;
633     MBEDTLS_ASN1_CHK_ADD(sig_and_oid_len, mbedtls_x509_write_sig(&c2, c,
634                                                                  sig_oid, sig_oid_len,
635                                                                  sig, sig_len, pk_alg));
636 
637     /*
638      * Memory layout after this step:
639      *
640      * buf       c=buf+len                c2            buf+size
641      * [CRT0,...,CRTn, UNUSED, ..., UNUSED, SIG0, ..., SIGm]
642      */
643 
644     /* Move raw CRT to just before the signature. */
645     c = c2 - len;
646     memmove(c, buf, len);
647 
648     len += sig_and_oid_len;
649     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(&c, buf, len));
650     MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(&c, buf,
651                                                      MBEDTLS_ASN1_CONSTRUCTED |
652                                                      MBEDTLS_ASN1_SEQUENCE));
653 
654     return (int) len;
655 }
656 
657 #define PEM_BEGIN_CRT           "-----BEGIN CERTIFICATE-----\n"
658 #define PEM_END_CRT             "-----END CERTIFICATE-----\n"
659 
660 #if defined(MBEDTLS_PEM_WRITE_C)
mbedtls_x509write_crt_pem(mbedtls_x509write_cert * crt,unsigned char * buf,size_t size,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)661 int mbedtls_x509write_crt_pem(mbedtls_x509write_cert *crt,
662                               unsigned char *buf, size_t size,
663                               int (*f_rng)(void *, unsigned char *, size_t),
664                               void *p_rng)
665 {
666     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
667     size_t olen;
668 
669     if ((ret = mbedtls_x509write_crt_der(crt, buf, size,
670                                          f_rng, p_rng)) < 0) {
671         return ret;
672     }
673 
674     if ((ret = mbedtls_pem_write_buffer(PEM_BEGIN_CRT, PEM_END_CRT,
675                                         buf + size - ret, ret,
676                                         buf, size, &olen)) != 0) {
677         return ret;
678     }
679 
680     return 0;
681 }
682 #endif /* MBEDTLS_PEM_WRITE_C */
683 
684 #endif /* MBEDTLS_X509_CRT_WRITE_C */
685