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