1 /*
2  *  Certificate generation and signing
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 #define MBEDTLS_DECLARE_PRIVATE_IDENTIFIERS
9 
10 #include "mbedtls/build_info.h"
11 
12 #include "mbedtls/platform.h"
13 /* md.h is included this early since MD_CAN_XXX macros are defined there. */
14 #include "mbedtls/md.h"
15 
16 #if !defined(MBEDTLS_X509_CRT_WRITE_C) || \
17     !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_FS_IO) || \
18     !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) || \
19     !defined(MBEDTLS_ERROR_C) || !defined(PSA_WANT_ALG_SHA_256) || \
20     !defined(MBEDTLS_PEM_WRITE_C) || !defined(MBEDTLS_MD_C)
main(void)21 int main(void)
22 {
23     mbedtls_printf("MBEDTLS_X509_CRT_WRITE_C and/or MBEDTLS_X509_CRT_PARSE_C and/or "
24                    "MBEDTLS_FS_IO and/or PSA_WANT_ALG_SHA_256 and/or "
25                    "MBEDTLS_ENTROPY_C and/or MBEDTLS_CTR_DRBG_C and/or "
26                    "MBEDTLS_ERROR_C not defined.\n");
27     mbedtls_exit(0);
28 }
29 #else
30 
31 #include "mbedtls/x509_crt.h"
32 #include "mbedtls/x509_csr.h"
33 #include "mbedtls/oid.h"
34 #include "mbedtls/entropy.h"
35 #include "mbedtls/ctr_drbg.h"
36 #include "mbedtls/error.h"
37 #include "test/helpers.h"
38 
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <errno.h>
43 
44 #define SET_OID(x, oid) \
45     do { x.len = MBEDTLS_OID_SIZE(oid); x.p = (unsigned char *) oid; } while (0)
46 
47 #if defined(MBEDTLS_X509_CSR_PARSE_C)
48 #define USAGE_CSR                                                           \
49     "    request_file=%%s         default: (empty)\n"                           \
50     "                            If request_file is specified, subject_key,\n"  \
51     "                            subject_pwd and subject_name are ignored!\n"
52 #else
53 #define USAGE_CSR ""
54 #endif /* MBEDTLS_X509_CSR_PARSE_C */
55 
56 #define FORMAT_PEM              0
57 #define FORMAT_DER              1
58 
59 #define DFL_ISSUER_CRT          ""
60 #define DFL_REQUEST_FILE        ""
61 #define DFL_SUBJECT_KEY         "subject.key"
62 #define DFL_ISSUER_KEY          "ca.key"
63 #define DFL_SUBJECT_PWD         ""
64 #define DFL_ISSUER_PWD          ""
65 #define DFL_OUTPUT_FILENAME     "cert.crt"
66 #define DFL_SUBJECT_NAME        "CN=Cert,O=mbed TLS,C=UK"
67 #define DFL_ISSUER_NAME         "CN=CA,O=mbed TLS,C=UK"
68 #define DFL_NOT_BEFORE          "20010101000000"
69 #define DFL_NOT_AFTER           "20301231235959"
70 #define DFL_SERIAL              "1"
71 #define DFL_SERIAL_HEX          "1"
72 #define DFL_EXT_SUBJECTALTNAME  ""
73 #define DFL_SELFSIGN            0
74 #define DFL_IS_CA               0
75 #define DFL_MAX_PATHLEN         -1
76 #define DFL_SIG_ALG             MBEDTLS_MD_SHA256
77 #define DFL_KEY_USAGE           0
78 #define DFL_EXT_KEY_USAGE       NULL
79 #define DFL_NS_CERT_TYPE        0
80 #define DFL_VERSION             3
81 #define DFL_AUTH_IDENT          1
82 #define DFL_SUBJ_IDENT          1
83 #define DFL_CONSTRAINTS         1
84 #define DFL_DIGEST              MBEDTLS_MD_SHA256
85 #define DFL_FORMAT              FORMAT_PEM
86 
87 #define USAGE \
88     "\n usage: cert_write param=<>...\n"                \
89     "\n acceptable parameters:\n"                       \
90     USAGE_CSR                                           \
91     "    subject_key=%%s          default: subject.key\n"   \
92     "    subject_pwd=%%s          default: (empty)\n"       \
93     "    subject_name=%%s         default: CN=Cert,O=mbed TLS,C=UK\n"   \
94     "\n"                                                \
95     "    issuer_crt=%%s           default: (empty)\n"       \
96     "                            If issuer_crt is specified, issuer_name is\n"  \
97     "                            ignored!\n"                \
98     "    issuer_name=%%s          default: CN=CA,O=mbed TLS,C=UK\n"     \
99     "\n"                                                \
100     "    selfsign=%%d             default: 0 (false)\n"     \
101     "                            If selfsign is enabled, issuer_name and\n" \
102     "                            issuer_key are required (issuer_crt and\n" \
103     "                            subject_* are ignored\n"   \
104     "    issuer_key=%%s           default: ca.key\n"        \
105     "    issuer_pwd=%%s           default: (empty)\n"       \
106     "    output_file=%%s          default: cert.crt\n"      \
107     "    serial=%%s               default: 1\n"             \
108     "                            In decimal format; it can be used as\n"     \
109     "                            alternative to serial_hex, but it's\n"      \
110     "                            limited in max length to\n"                 \
111     "                            unsigned long long int\n"                   \
112     "    serial_hex=%%s           default: 1\n"             \
113     "                            In hex format; it can be used as\n"         \
114     "                            alternative to serial\n"                    \
115     "    not_before=%%s           default: 20010101000000\n" \
116     "    not_after=%%s            default: 20301231235959\n" \
117     "    is_ca=%%d                default: 0 (disabled)\n"  \
118     "    max_pathlen=%%d          default: -1 (none)\n"     \
119     "    md=%%s                   default: SHA256\n"        \
120     "                            Supported values (if enabled):\n"      \
121     "                            MD5, RIPEMD160, SHA1,\n" \
122     "                            SHA224, SHA256, SHA384, SHA512\n" \
123     "    version=%%d              default: 3\n"            \
124     "                            Possible values: 1, 2, 3\n" \
125     "    subject_identifier=%%s   default: 1\n"             \
126     "                            Possible values: 0, 1\n"   \
127     "                            (Considered for v3 only)\n" \
128     "    san=%%s                   default: (none)\n"       \
129     "                            Semicolon-separated-list of values:\n" \
130     "                             DNS:value\n"            \
131     "                             URI:value\n"            \
132     "                             RFC822:value\n"         \
133     "                             IP:value (Only IPv4 is supported)\n" \
134     "                             DN:list of comma separated key=value pairs\n" \
135     "    authority_identifier=%%s default: 1\n"             \
136     "                            Possible values: 0, 1\n"   \
137     "                            (Considered for v3 only)\n" \
138     "    basic_constraints=%%d    default: 1\n"             \
139     "                            Possible values: 0, 1\n"   \
140     "                            (Considered for v3 only)\n" \
141     "    key_usage=%%s            default: (empty)\n"       \
142     "                            Comma-separated-list of values:\n"     \
143     "                            digital_signature\n"     \
144     "                            non_repudiation\n"       \
145     "                            key_encipherment\n"      \
146     "                            data_encipherment\n"     \
147     "                            key_agreement\n"         \
148     "                            key_cert_sign\n"  \
149     "                            crl_sign\n"              \
150     "                            (Considered for v3 only)\n" \
151     "    ext_key_usage=%%s        default: (empty)\n"      \
152     "                            Comma-separated-list of values:\n"     \
153     "                            serverAuth\n"             \
154     "                            clientAuth\n"             \
155     "                            codeSigning\n"            \
156     "                            emailProtection\n"        \
157     "                            timeStamping\n"           \
158     "                            OCSPSigning\n"            \
159     "    ns_cert_type=%%s         default: (empty)\n"       \
160     "                            Comma-separated-list of values:\n"     \
161     "                            ssl_client\n"            \
162     "                            ssl_server\n"            \
163     "                            email\n"                 \
164     "                            object_signing\n"        \
165     "                            ssl_ca\n"                \
166     "                            email_ca\n"              \
167     "                            object_signing_ca\n"     \
168     "   format=pem|der           default: pem\n"         \
169     "\n"
170 
171 typedef enum {
172     SERIAL_FRMT_UNSPEC,
173     SERIAL_FRMT_DEC,
174     SERIAL_FRMT_HEX
175 } serial_format_t;
176 
177 /*
178  * global options
179  */
180 struct options {
181     const char *issuer_crt;     /* filename of the issuer certificate   */
182     const char *request_file;   /* filename of the certificate request  */
183     const char *subject_key;    /* filename of the subject key file     */
184     const char *issuer_key;     /* filename of the issuer key file      */
185     const char *subject_pwd;    /* password for the subject key file    */
186     const char *issuer_pwd;     /* password for the issuer key file     */
187     const char *output_file;    /* where to store the constructed CRT   */
188     const char *subject_name;   /* subject name for certificate         */
189     mbedtls_x509_san_list *san_list; /* subjectAltName for certificate  */
190     const char *issuer_name;    /* issuer name for certificate          */
191     const char *not_before;     /* validity period not before           */
192     const char *not_after;      /* validity period not after            */
193     const char *serial;         /* serial number string (decimal)       */
194     const char *serial_hex;     /* serial number string (hex)           */
195     int selfsign;               /* selfsign the certificate             */
196     int is_ca;                  /* is a CA certificate                  */
197     int max_pathlen;            /* maximum CA path length               */
198     int authority_identifier;   /* add authority identifier to CRT      */
199     int subject_identifier;     /* add subject identifier to CRT        */
200     int basic_constraints;      /* add basic constraints ext to CRT     */
201     int version;                /* CRT version                          */
202     mbedtls_md_type_t md;       /* Hash used for signing                */
203     unsigned char key_usage;    /* key usage flags                      */
204     mbedtls_asn1_sequence *ext_key_usage; /* extended key usages        */
205     unsigned char ns_cert_type; /* NS cert type                         */
206     int format;                 /* format                               */
207 } opt;
208 
write_certificate(mbedtls_x509write_cert * crt,const char * output_file)209 static int write_certificate(mbedtls_x509write_cert *crt, const char *output_file)
210 {
211     int ret;
212     FILE *f;
213     unsigned char output_buf[4096];
214     unsigned char *output_start;
215     size_t len = 0;
216 
217     memset(output_buf, 0, 4096);
218     if (opt.format == FORMAT_DER) {
219         ret = mbedtls_x509write_crt_der(crt, output_buf, 4096);
220         if (ret < 0) {
221             return ret;
222         }
223 
224         len = ret;
225         output_start = output_buf + 4096 - len;
226     } else {
227         ret = mbedtls_x509write_crt_pem(crt, output_buf, 4096);
228         if (ret < 0) {
229             return ret;
230         }
231 
232         len = strlen((char *) output_buf);
233         output_start = output_buf;
234     }
235 
236     if ((f = fopen(output_file, "w")) == NULL) {
237         return -1;
238     }
239 
240     if (fwrite(output_start, 1, len, f) != len) {
241         fclose(f);
242         return -1;
243     }
244 
245     fclose(f);
246 
247     return 0;
248 }
249 
parse_serial_decimal_format(unsigned char * obuf,size_t obufmax,const char * ibuf,size_t * len)250 static int parse_serial_decimal_format(unsigned char *obuf, size_t obufmax,
251                                        const char *ibuf, size_t *len)
252 {
253     unsigned long long int dec;
254     unsigned int remaining_bytes = sizeof(dec);
255     unsigned char *p = obuf;
256     unsigned char val;
257     char *end_ptr = NULL;
258 
259     errno = 0;
260     dec = strtoull(ibuf, &end_ptr, 10);
261 
262     if ((errno != 0) || (end_ptr == ibuf)) {
263         return -1;
264     }
265 
266     *len = 0;
267 
268     while (remaining_bytes > 0) {
269         if (obufmax < (*len + 1)) {
270             return -1;
271         }
272 
273         val = (dec >> ((remaining_bytes - 1) * 8)) & 0xFF;
274 
275         /* Skip leading zeros */
276         if ((val != 0) || (*len != 0)) {
277             *p = val;
278             (*len)++;
279             p++;
280         }
281 
282         remaining_bytes--;
283     }
284 
285     return 0;
286 }
287 
main(int argc,char * argv[])288 int main(int argc, char *argv[])
289 {
290     int ret = 1;
291     int exit_code = MBEDTLS_EXIT_FAILURE;
292     mbedtls_x509_crt issuer_crt;
293     mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
294     mbedtls_pk_context *issuer_key = &loaded_issuer_key,
295                        *subject_key = &loaded_subject_key;
296     char buf[1024];
297     char issuer_name[256];
298     int i;
299     char *p, *q, *r;
300 #if defined(MBEDTLS_X509_CSR_PARSE_C)
301     char subject_name[256];
302     mbedtls_x509_csr csr;
303 #endif
304     mbedtls_x509write_cert crt;
305     serial_format_t serial_frmt = SERIAL_FRMT_UNSPEC;
306     unsigned char serial[MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN];
307     size_t serial_len;
308     mbedtls_asn1_sequence *ext_key_usage;
309     mbedtls_entropy_context entropy;
310     mbedtls_ctr_drbg_context ctr_drbg;
311     const char *pers = "crt example app";
312     mbedtls_x509_san_list *cur, *prev;
313     uint8_t ip[4] = { 0 };
314     /*
315      * Set to sane values
316      */
317     mbedtls_x509write_crt_init(&crt);
318     mbedtls_pk_init(&loaded_issuer_key);
319     mbedtls_pk_init(&loaded_subject_key);
320     mbedtls_ctr_drbg_init(&ctr_drbg);
321     mbedtls_entropy_init(&entropy);
322 #if defined(MBEDTLS_X509_CSR_PARSE_C)
323     mbedtls_x509_csr_init(&csr);
324 #endif
325     mbedtls_x509_crt_init(&issuer_crt);
326     memset(buf, 0, sizeof(buf));
327     memset(serial, 0, sizeof(serial));
328 
329     psa_status_t status = psa_crypto_init();
330     if (status != PSA_SUCCESS) {
331         mbedtls_fprintf(stderr, "Failed to initialize PSA Crypto implementation: %d\n",
332                         (int) status);
333         goto exit;
334     }
335 
336     if (argc < 2) {
337 usage:
338         mbedtls_printf(USAGE);
339         goto exit;
340     }
341 
342     opt.issuer_crt          = DFL_ISSUER_CRT;
343     opt.request_file        = DFL_REQUEST_FILE;
344     opt.subject_key         = DFL_SUBJECT_KEY;
345     opt.issuer_key          = DFL_ISSUER_KEY;
346     opt.subject_pwd         = DFL_SUBJECT_PWD;
347     opt.issuer_pwd          = DFL_ISSUER_PWD;
348     opt.output_file         = DFL_OUTPUT_FILENAME;
349     opt.subject_name        = DFL_SUBJECT_NAME;
350     opt.issuer_name         = DFL_ISSUER_NAME;
351     opt.not_before          = DFL_NOT_BEFORE;
352     opt.not_after           = DFL_NOT_AFTER;
353     opt.serial              = DFL_SERIAL;
354     opt.serial_hex          = DFL_SERIAL_HEX;
355     opt.selfsign            = DFL_SELFSIGN;
356     opt.is_ca               = DFL_IS_CA;
357     opt.max_pathlen         = DFL_MAX_PATHLEN;
358     opt.key_usage           = DFL_KEY_USAGE;
359     opt.ext_key_usage       = DFL_EXT_KEY_USAGE;
360     opt.ns_cert_type        = DFL_NS_CERT_TYPE;
361     opt.version             = DFL_VERSION - 1;
362     opt.md                  = DFL_DIGEST;
363     opt.subject_identifier   = DFL_SUBJ_IDENT;
364     opt.authority_identifier = DFL_AUTH_IDENT;
365     opt.basic_constraints    = DFL_CONSTRAINTS;
366     opt.format              = DFL_FORMAT;
367     opt.san_list            = NULL;
368 
369     for (i = 1; i < argc; i++) {
370 
371         p = argv[i];
372         if ((q = strchr(p, '=')) == NULL) {
373             goto usage;
374         }
375         *q++ = '\0';
376 
377         if (strcmp(p, "request_file") == 0) {
378             opt.request_file = q;
379         } else if (strcmp(p, "subject_key") == 0) {
380             opt.subject_key = q;
381         } else if (strcmp(p, "issuer_key") == 0) {
382             opt.issuer_key = q;
383         } else if (strcmp(p, "subject_pwd") == 0) {
384             opt.subject_pwd = q;
385         } else if (strcmp(p, "issuer_pwd") == 0) {
386             opt.issuer_pwd = q;
387         } else if (strcmp(p, "issuer_crt") == 0) {
388             opt.issuer_crt = q;
389         } else if (strcmp(p, "output_file") == 0) {
390             opt.output_file = q;
391         } else if (strcmp(p, "subject_name") == 0) {
392             opt.subject_name = q;
393         } else if (strcmp(p, "issuer_name") == 0) {
394             opt.issuer_name = q;
395         } else if (strcmp(p, "not_before") == 0) {
396             opt.not_before = q;
397         } else if (strcmp(p, "not_after") == 0) {
398             opt.not_after = q;
399         } else if (strcmp(p, "serial") == 0) {
400             if (serial_frmt != SERIAL_FRMT_UNSPEC) {
401                 mbedtls_printf("Invalid attempt to set the serial more than once\n");
402                 goto usage;
403             }
404             serial_frmt = SERIAL_FRMT_DEC;
405             opt.serial = q;
406         } else if (strcmp(p, "serial_hex") == 0) {
407             if (serial_frmt != SERIAL_FRMT_UNSPEC) {
408                 mbedtls_printf("Invalid attempt to set the serial more than once\n");
409                 goto usage;
410             }
411             serial_frmt = SERIAL_FRMT_HEX;
412             opt.serial_hex = q;
413         } else if (strcmp(p, "authority_identifier") == 0) {
414             opt.authority_identifier = atoi(q);
415             if (opt.authority_identifier != 0 &&
416                 opt.authority_identifier != 1) {
417                 mbedtls_printf("Invalid argument for option %s\n", p);
418                 goto usage;
419             }
420         } else if (strcmp(p, "subject_identifier") == 0) {
421             opt.subject_identifier = atoi(q);
422             if (opt.subject_identifier != 0 &&
423                 opt.subject_identifier != 1) {
424                 mbedtls_printf("Invalid argument for option %s\n", p);
425                 goto usage;
426             }
427         } else if (strcmp(p, "basic_constraints") == 0) {
428             opt.basic_constraints = atoi(q);
429             if (opt.basic_constraints != 0 &&
430                 opt.basic_constraints != 1) {
431                 mbedtls_printf("Invalid argument for option %s\n", p);
432                 goto usage;
433             }
434         } else if (strcmp(p, "md") == 0) {
435             const mbedtls_md_info_t *md_info =
436                 mbedtls_md_info_from_string(q);
437             if (md_info == NULL) {
438                 mbedtls_printf("Invalid argument for option %s\n", p);
439                 goto usage;
440             }
441             opt.md = mbedtls_md_get_type(md_info);
442         } else if (strcmp(p, "version") == 0) {
443             opt.version = atoi(q);
444             if (opt.version < 1 || opt.version > 3) {
445                 mbedtls_printf("Invalid argument for option %s\n", p);
446                 goto usage;
447             }
448             opt.version--;
449         } else if (strcmp(p, "selfsign") == 0) {
450             opt.selfsign = atoi(q);
451             if (opt.selfsign < 0 || opt.selfsign > 1) {
452                 mbedtls_printf("Invalid argument for option %s\n", p);
453                 goto usage;
454             }
455         } else if (strcmp(p, "is_ca") == 0) {
456             opt.is_ca = atoi(q);
457             if (opt.is_ca < 0 || opt.is_ca > 1) {
458                 mbedtls_printf("Invalid argument for option %s\n", p);
459                 goto usage;
460             }
461         } else if (strcmp(p, "max_pathlen") == 0) {
462             opt.max_pathlen = atoi(q);
463             if (opt.max_pathlen < -1 || opt.max_pathlen > 127) {
464                 mbedtls_printf("Invalid argument for option %s\n", p);
465                 goto usage;
466             }
467         } else if (strcmp(p, "key_usage") == 0) {
468             while (q != NULL) {
469                 if ((r = strchr(q, ',')) != NULL) {
470                     *r++ = '\0';
471                 }
472 
473                 if (strcmp(q, "digital_signature") == 0) {
474                     opt.key_usage |= MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
475                 } else if (strcmp(q, "non_repudiation") == 0) {
476                     opt.key_usage |= MBEDTLS_X509_KU_NON_REPUDIATION;
477                 } else if (strcmp(q, "key_encipherment") == 0) {
478                     opt.key_usage |= MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
479                 } else if (strcmp(q, "data_encipherment") == 0) {
480                     opt.key_usage |= MBEDTLS_X509_KU_DATA_ENCIPHERMENT;
481                 } else if (strcmp(q, "key_agreement") == 0) {
482                     opt.key_usage |= MBEDTLS_X509_KU_KEY_AGREEMENT;
483                 } else if (strcmp(q, "key_cert_sign") == 0) {
484                     opt.key_usage |= MBEDTLS_X509_KU_KEY_CERT_SIGN;
485                 } else if (strcmp(q, "crl_sign") == 0) {
486                     opt.key_usage |= MBEDTLS_X509_KU_CRL_SIGN;
487                 } else {
488                     mbedtls_printf("Invalid argument for option %s\n", p);
489                     goto usage;
490                 }
491 
492                 q = r;
493             }
494         } else if (strcmp(p, "ext_key_usage") == 0) {
495             mbedtls_asn1_sequence **tail = &opt.ext_key_usage;
496 
497             while (q != NULL) {
498                 if ((r = strchr(q, ',')) != NULL) {
499                     *r++ = '\0';
500                 }
501 
502                 ext_key_usage = mbedtls_calloc(1, sizeof(mbedtls_asn1_sequence));
503                 ext_key_usage->buf.tag = MBEDTLS_ASN1_OID;
504                 if (strcmp(q, "serverAuth") == 0) {
505                     SET_OID(ext_key_usage->buf, MBEDTLS_OID_SERVER_AUTH);
506                 } else if (strcmp(q, "clientAuth") == 0) {
507                     SET_OID(ext_key_usage->buf, MBEDTLS_OID_CLIENT_AUTH);
508                 } else if (strcmp(q, "codeSigning") == 0) {
509                     SET_OID(ext_key_usage->buf, MBEDTLS_OID_CODE_SIGNING);
510                 } else if (strcmp(q, "emailProtection") == 0) {
511                     SET_OID(ext_key_usage->buf, MBEDTLS_OID_EMAIL_PROTECTION);
512                 } else if (strcmp(q, "timeStamping") == 0) {
513                     SET_OID(ext_key_usage->buf, MBEDTLS_OID_TIME_STAMPING);
514                 } else if (strcmp(q, "OCSPSigning") == 0) {
515                     SET_OID(ext_key_usage->buf, MBEDTLS_OID_OCSP_SIGNING);
516                 } else if (strcmp(q, "any") == 0) {
517                     SET_OID(ext_key_usage->buf, MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE);
518                 } else {
519                     mbedtls_printf("Invalid argument for option %s\n", p);
520                     goto usage;
521                 }
522 
523                 *tail = ext_key_usage;
524                 tail = &ext_key_usage->next;
525 
526                 q = r;
527             }
528         } else if (strcmp(p, "san") == 0) {
529             char *subtype_value;
530             prev = NULL;
531 
532             while (q != NULL) {
533                 char *semicolon;
534                 r = q;
535 
536                 /* Find the first non-escaped ; occurrence and remove escaped ones */
537                 do {
538                     if ((semicolon = strchr(r, ';')) != NULL) {
539                         if (*(semicolon-1) != '\\') {
540                             r = semicolon;
541                             break;
542                         }
543                         /* Remove the escape character */
544                         size_t size_left = strlen(semicolon);
545                         memmove(semicolon-1, semicolon, size_left);
546                         *(semicolon + size_left - 1) = '\0';
547                         /* r will now point at the character after the semicolon */
548                         r = semicolon;
549                     }
550 
551                 } while (semicolon != NULL);
552 
553                 if (semicolon != NULL) {
554                     *r++ = '\0';
555                 } else {
556                     r = NULL;
557                 }
558 
559                 cur = mbedtls_calloc(1, sizeof(mbedtls_x509_san_list));
560                 if (cur == NULL) {
561                     mbedtls_printf("Not enough memory for subjectAltName list\n");
562                     goto usage;
563                 }
564 
565                 cur->next = NULL;
566 
567                 if ((subtype_value = strchr(q, ':')) != NULL) {
568                     *subtype_value++ = '\0';
569                 } else {
570                     mbedtls_printf(
571                         "Invalid argument for option SAN: Entry must be of the form TYPE:value\n");
572                     goto usage;
573                 }
574                 if (strcmp(q, "RFC822") == 0) {
575                     cur->node.type = MBEDTLS_X509_SAN_RFC822_NAME;
576                 } else if (strcmp(q, "URI") == 0) {
577                     cur->node.type = MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER;
578                 } else if (strcmp(q, "DNS") == 0) {
579                     cur->node.type = MBEDTLS_X509_SAN_DNS_NAME;
580                 } else if (strcmp(q, "IP") == 0) {
581                     size_t ip_addr_len = 0;
582                     cur->node.type = MBEDTLS_X509_SAN_IP_ADDRESS;
583                     ip_addr_len = mbedtls_x509_crt_parse_cn_inet_pton(subtype_value, ip);
584                     if (ip_addr_len == 0) {
585                         mbedtls_printf("mbedtls_x509_crt_parse_cn_inet_pton failed to parse %s\n",
586                                        subtype_value);
587                         goto exit;
588                     }
589                     cur->node.san.unstructured_name.p = (unsigned char *) ip;
590                     cur->node.san.unstructured_name.len = sizeof(ip);
591                 } else if (strcmp(q, "DN") == 0) {
592                     cur->node.type = MBEDTLS_X509_SAN_DIRECTORY_NAME;
593                     /* Work around an API mismatch between string_to_names() and
594                      * mbedtls_x509_subject_alternative_name, which holds an
595                      * actual mbedtls_x509_name while a pointer to one would be
596                      * more convenient here. (Note mbedtls_x509_name and
597                      * mbedtls_asn1_named_data are synonymous, again
598                      * string_to_names() uses one while
599                      * cur->node.san.directory_name is nominally the other.) */
600                     mbedtls_asn1_named_data *tmp_san_dirname = NULL;
601                     if ((ret = mbedtls_x509_string_to_names(&tmp_san_dirname,
602                                                             subtype_value)) != 0) {
603                         mbedtls_strerror(ret, buf, sizeof(buf));
604                         mbedtls_printf(
605                             " failed\n  !  mbedtls_x509_string_to_names "
606                             "returned -0x%04x - %s\n\n",
607                             (unsigned int) -ret, buf);
608                         goto exit;
609                     }
610                     cur->node.san.directory_name = *tmp_san_dirname;
611                     mbedtls_free(tmp_san_dirname);
612                     tmp_san_dirname = NULL;
613                 } else {
614                     mbedtls_free(cur);
615                     goto usage;
616                 }
617 
618                 if (cur->node.type == MBEDTLS_X509_SAN_RFC822_NAME ||
619                     cur->node.type == MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER ||
620                     cur->node.type == MBEDTLS_X509_SAN_DNS_NAME) {
621                     q = subtype_value;
622                     cur->node.san.unstructured_name.p = (unsigned char *) q;
623                     cur->node.san.unstructured_name.len = strlen(q);
624                 }
625 
626                 if (prev == NULL) {
627                     opt.san_list = cur;
628                 } else {
629                     prev->next = cur;
630                 }
631 
632                 prev = cur;
633                 q = r;
634             }
635         } else if (strcmp(p, "ns_cert_type") == 0) {
636             while (q != NULL) {
637                 if ((r = strchr(q, ',')) != NULL) {
638                     *r++ = '\0';
639                 }
640 
641                 if (strcmp(q, "ssl_client") == 0) {
642                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT;
643                 } else if (strcmp(q, "ssl_server") == 0) {
644                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER;
645                 } else if (strcmp(q, "email") == 0) {
646                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_EMAIL;
647                 } else if (strcmp(q, "object_signing") == 0) {
648                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING;
649                 } else if (strcmp(q, "ssl_ca") == 0) {
650                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_CA;
651                 } else if (strcmp(q, "email_ca") == 0) {
652                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA;
653                 } else if (strcmp(q, "object_signing_ca") == 0) {
654                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA;
655                 } else {
656                     mbedtls_printf("Invalid argument for option %s\n", p);
657                     goto usage;
658                 }
659 
660                 q = r;
661             }
662         } else if (strcmp(p, "format") == 0) {
663             if (strcmp(q, "der") == 0) {
664                 opt.format = FORMAT_DER;
665             } else if (strcmp(q, "pem") == 0) {
666                 opt.format = FORMAT_PEM;
667             } else {
668                 mbedtls_printf("Invalid argument for option %s\n", p);
669                 goto usage;
670             }
671         } else {
672             goto usage;
673         }
674     }
675 
676     mbedtls_printf("\n");
677 
678     /*
679      * 0. Seed the PRNG
680      */
681     mbedtls_printf("  . Seeding the random number generator...");
682     fflush(stdout);
683 
684     if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
685                                      (const unsigned char *) pers,
686                                      strlen(pers))) != 0) {
687         mbedtls_strerror(ret, buf, sizeof(buf));
688         mbedtls_printf(" failed\n  !  mbedtls_ctr_drbg_seed returned %d - %s\n",
689                        ret, buf);
690         goto exit;
691     }
692 
693     mbedtls_printf(" ok\n");
694 
695     // Parse serial to MPI
696     //
697     mbedtls_printf("  . Reading serial number...");
698     fflush(stdout);
699 
700     if (serial_frmt == SERIAL_FRMT_HEX) {
701         ret = mbedtls_test_unhexify(serial, sizeof(serial),
702                                     opt.serial_hex, &serial_len);
703     } else { // SERIAL_FRMT_DEC || SERIAL_FRMT_UNSPEC
704         ret = parse_serial_decimal_format(serial, sizeof(serial),
705                                           opt.serial, &serial_len);
706     }
707 
708     if (ret != 0) {
709         mbedtls_printf(" failed\n  !  Unable to parse serial\n");
710         goto exit;
711     }
712 
713     mbedtls_printf(" ok\n");
714 
715     // Parse issuer certificate if present
716     //
717     if (!opt.selfsign && strlen(opt.issuer_crt)) {
718         /*
719          * 1.0.a. Load the certificates
720          */
721         mbedtls_printf("  . Loading the issuer certificate ...");
722         fflush(stdout);
723 
724         if ((ret = mbedtls_x509_crt_parse_file(&issuer_crt, opt.issuer_crt)) != 0) {
725             mbedtls_strerror(ret, buf, sizeof(buf));
726             mbedtls_printf(" failed\n  !  mbedtls_x509_crt_parse_file "
727                            "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf);
728             goto exit;
729         }
730 
731         ret = mbedtls_x509_dn_gets(issuer_name, sizeof(issuer_name),
732                                    &issuer_crt.subject);
733         if (ret < 0) {
734             mbedtls_strerror(ret, buf, sizeof(buf));
735             mbedtls_printf(" failed\n  !  mbedtls_x509_dn_gets "
736                            "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf);
737             goto exit;
738         }
739 
740         opt.issuer_name = issuer_name;
741 
742         mbedtls_printf(" ok\n");
743     }
744 
745 #if defined(MBEDTLS_X509_CSR_PARSE_C)
746     // Parse certificate request if present
747     //
748     if (!opt.selfsign && strlen(opt.request_file)) {
749         /*
750          * 1.0.b. Load the CSR
751          */
752         mbedtls_printf("  . Loading the certificate request ...");
753         fflush(stdout);
754 
755         if ((ret = mbedtls_x509_csr_parse_file(&csr, opt.request_file)) != 0) {
756             mbedtls_strerror(ret, buf, sizeof(buf));
757             mbedtls_printf(" failed\n  !  mbedtls_x509_csr_parse_file "
758                            "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf);
759             goto exit;
760         }
761 
762         ret = mbedtls_x509_dn_gets(subject_name, sizeof(subject_name),
763                                    &csr.subject);
764         if (ret < 0) {
765             mbedtls_strerror(ret, buf, sizeof(buf));
766             mbedtls_printf(" failed\n  !  mbedtls_x509_dn_gets "
767                            "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf);
768             goto exit;
769         }
770 
771         opt.subject_name = subject_name;
772         subject_key = &csr.pk;
773 
774         mbedtls_printf(" ok\n");
775     }
776 #endif /* MBEDTLS_X509_CSR_PARSE_C */
777 
778     /*
779      * 1.1. Load the keys
780      */
781     if (!opt.selfsign && !strlen(opt.request_file)) {
782         mbedtls_printf("  . Loading the subject key ...");
783         fflush(stdout);
784 
785         ret = mbedtls_pk_parse_keyfile(&loaded_subject_key, opt.subject_key,
786                                        opt.subject_pwd);
787         if (ret != 0) {
788             mbedtls_strerror(ret, buf, sizeof(buf));
789             mbedtls_printf(" failed\n  !  mbedtls_pk_parse_keyfile "
790                            "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf);
791             goto exit;
792         }
793 
794         mbedtls_printf(" ok\n");
795     }
796 
797     mbedtls_printf("  . Loading the issuer key ...");
798     fflush(stdout);
799 
800     ret = mbedtls_pk_parse_keyfile(&loaded_issuer_key, opt.issuer_key,
801                                    opt.issuer_pwd);
802     if (ret != 0) {
803         mbedtls_strerror(ret, buf, sizeof(buf));
804         mbedtls_printf(" failed\n  !  mbedtls_pk_parse_keyfile "
805                        "returned -x%02x - %s\n\n", (unsigned int) -ret, buf);
806         goto exit;
807     }
808 
809     // Check if key and issuer certificate match
810     //
811     if (strlen(opt.issuer_crt)) {
812         if (mbedtls_pk_check_pair(&issuer_crt.pk, issuer_key) != 0) {
813             mbedtls_printf(" failed\n  !  issuer_key does not match "
814                            "issuer certificate\n\n");
815             goto exit;
816         }
817     }
818 
819     mbedtls_printf(" ok\n");
820 
821     if (opt.selfsign) {
822         opt.subject_name = opt.issuer_name;
823         subject_key = issuer_key;
824     }
825 
826     mbedtls_x509write_crt_set_subject_key(&crt, subject_key);
827     mbedtls_x509write_crt_set_issuer_key(&crt, issuer_key);
828 
829     /*
830      * 1.0. Check the names for validity
831      */
832     if ((ret = mbedtls_x509write_crt_set_subject_name(&crt, opt.subject_name)) != 0) {
833         mbedtls_strerror(ret, buf, sizeof(buf));
834         mbedtls_printf(" failed\n  !  mbedtls_x509write_crt_set_subject_name "
835                        "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf);
836         goto exit;
837     }
838 
839     if ((ret = mbedtls_x509write_crt_set_issuer_name(&crt, opt.issuer_name)) != 0) {
840         mbedtls_strerror(ret, buf, sizeof(buf));
841         mbedtls_printf(" failed\n  !  mbedtls_x509write_crt_set_issuer_name "
842                        "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf);
843         goto exit;
844     }
845 
846     mbedtls_printf("  . Setting certificate values ...");
847     fflush(stdout);
848 
849     mbedtls_x509write_crt_set_version(&crt, opt.version);
850     mbedtls_x509write_crt_set_md_alg(&crt, opt.md);
851 
852     ret = mbedtls_x509write_crt_set_serial_raw(&crt, serial, serial_len);
853     if (ret != 0) {
854         mbedtls_strerror(ret, buf, sizeof(buf));
855         mbedtls_printf(" failed\n  !  mbedtls_x509write_crt_set_serial_raw "
856                        "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf);
857         goto exit;
858     }
859 
860     ret = mbedtls_x509write_crt_set_validity(&crt, opt.not_before, opt.not_after);
861     if (ret != 0) {
862         mbedtls_strerror(ret, buf, sizeof(buf));
863         mbedtls_printf(" failed\n  !  mbedtls_x509write_crt_set_validity "
864                        "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf);
865         goto exit;
866     }
867 
868     mbedtls_printf(" ok\n");
869 
870     if (opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
871         opt.basic_constraints != 0) {
872         mbedtls_printf("  . Adding the Basic Constraints extension ...");
873         fflush(stdout);
874 
875         ret = mbedtls_x509write_crt_set_basic_constraints(&crt, opt.is_ca,
876                                                           opt.max_pathlen);
877         if (ret != 0) {
878             mbedtls_strerror(ret, buf, sizeof(buf));
879             mbedtls_printf(" failed\n  !  x509write_crt_set_basic_constraints "
880                            "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf);
881             goto exit;
882         }
883 
884         mbedtls_printf(" ok\n");
885     }
886 
887 #if defined(PSA_WANT_ALG_SHA_1)
888     if (opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
889         opt.subject_identifier != 0) {
890         mbedtls_printf("  . Adding the Subject Key Identifier ...");
891         fflush(stdout);
892 
893         ret = mbedtls_x509write_crt_set_subject_key_identifier(&crt);
894         if (ret != 0) {
895             mbedtls_strerror(ret, buf, sizeof(buf));
896             mbedtls_printf(" failed\n  !  mbedtls_x509write_crt_set_subject"
897                            "_key_identifier returned -0x%04x - %s\n\n",
898                            (unsigned int) -ret, buf);
899             goto exit;
900         }
901 
902         mbedtls_printf(" ok\n");
903     }
904 
905     if (opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
906         opt.authority_identifier != 0) {
907         mbedtls_printf("  . Adding the Authority Key Identifier ...");
908         fflush(stdout);
909 
910         ret = mbedtls_x509write_crt_set_authority_key_identifier(&crt);
911         if (ret != 0) {
912             mbedtls_strerror(ret, buf, sizeof(buf));
913             mbedtls_printf(" failed\n  !  mbedtls_x509write_crt_set_authority_"
914                            "key_identifier returned -0x%04x - %s\n\n",
915                            (unsigned int) -ret, buf);
916             goto exit;
917         }
918 
919         mbedtls_printf(" ok\n");
920     }
921 #endif /* PSA_WANT_ALG_SHA_1 */
922 
923     if (opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
924         opt.key_usage != 0) {
925         mbedtls_printf("  . Adding the Key Usage extension ...");
926         fflush(stdout);
927 
928         ret = mbedtls_x509write_crt_set_key_usage(&crt, opt.key_usage);
929         if (ret != 0) {
930             mbedtls_strerror(ret, buf, sizeof(buf));
931             mbedtls_printf(" failed\n  !  mbedtls_x509write_crt_set_key_usage "
932                            "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf);
933             goto exit;
934         }
935 
936         mbedtls_printf(" ok\n");
937     }
938 
939     if (opt.san_list != NULL) {
940         ret = mbedtls_x509write_crt_set_subject_alternative_name(&crt, opt.san_list);
941 
942         if (ret != 0) {
943             mbedtls_printf(
944                 " failed\n  !  mbedtls_x509write_crt_set_subject_alternative_name returned %d",
945                 ret);
946             goto exit;
947         }
948     }
949 
950     if (opt.ext_key_usage) {
951         mbedtls_printf("  . Adding the Extended Key Usage extension ...");
952         fflush(stdout);
953 
954         ret = mbedtls_x509write_crt_set_ext_key_usage(&crt, opt.ext_key_usage);
955         if (ret != 0) {
956             mbedtls_strerror(ret, buf, sizeof(buf));
957             mbedtls_printf(
958                 " failed\n  !  mbedtls_x509write_crt_set_ext_key_usage returned -0x%02x - %s\n\n",
959                 (unsigned int) -ret,
960                 buf);
961             goto exit;
962         }
963 
964         mbedtls_printf(" ok\n");
965     }
966 
967     if (opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
968         opt.ns_cert_type != 0) {
969         mbedtls_printf("  . Adding the NS Cert Type extension ...");
970         fflush(stdout);
971 
972         ret = mbedtls_x509write_crt_set_ns_cert_type(&crt, opt.ns_cert_type);
973         if (ret != 0) {
974             mbedtls_strerror(ret, buf, sizeof(buf));
975             mbedtls_printf(" failed\n  !  mbedtls_x509write_crt_set_ns_cert_type "
976                            "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf);
977             goto exit;
978         }
979 
980         mbedtls_printf(" ok\n");
981     }
982 
983     /*
984      * 1.2. Writing the certificate
985      */
986     mbedtls_printf("  . Writing the certificate...");
987     fflush(stdout);
988 
989     if ((ret = write_certificate(&crt, opt.output_file)) != 0) {
990         mbedtls_strerror(ret, buf, sizeof(buf));
991         mbedtls_printf(" failed\n  !  write_certificate -0x%04x - %s\n\n",
992                        (unsigned int) -ret, buf);
993         goto exit;
994     }
995 
996     mbedtls_printf(" ok\n");
997 
998     exit_code = MBEDTLS_EXIT_SUCCESS;
999 
1000 exit:
1001     cur = opt.san_list;
1002     while (cur != NULL) {
1003         mbedtls_x509_san_list *next = cur->next;
1004         /* Note: mbedtls_x509_free_subject_alt_name() is not what we want here.
1005          * It's the right thing for entries that were parsed from a certificate,
1006          * where pointers are to the raw certificate, but here all the
1007          * pointers were allocated while parsing from a user-provided string. */
1008         if (cur->node.type == MBEDTLS_X509_SAN_DIRECTORY_NAME) {
1009             mbedtls_x509_name *dn = &cur->node.san.directory_name;
1010             mbedtls_free(dn->oid.p);
1011             mbedtls_free(dn->val.p);
1012             mbedtls_asn1_free_named_data_list(&dn->next);
1013         }
1014         mbedtls_free(cur);
1015         cur = next;
1016     }
1017 
1018 #if defined(MBEDTLS_X509_CSR_PARSE_C)
1019     mbedtls_x509_csr_free(&csr);
1020 #endif /* MBEDTLS_X509_CSR_PARSE_C */
1021     mbedtls_x509_crt_free(&issuer_crt);
1022     mbedtls_x509write_crt_free(&crt);
1023     mbedtls_pk_free(&loaded_subject_key);
1024     mbedtls_pk_free(&loaded_issuer_key);
1025     mbedtls_ctr_drbg_free(&ctr_drbg);
1026     mbedtls_entropy_free(&entropy);
1027     mbedtls_psa_crypto_free();
1028 
1029     mbedtls_exit(exit_code);
1030 }
1031 #endif /* MBEDTLS_X509_CRT_WRITE_C && MBEDTLS_X509_CRT_PARSE_C &&
1032           MBEDTLS_FS_IO && MBEDTLS_ENTROPY_C && MBEDTLS_CTR_DRBG_C &&
1033           MBEDTLS_ERROR_C && MBEDTLS_PEM_WRITE_C */
1034