1 /*
2 * Certificate request generation
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_CSR_WRITE_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \
17 !defined(MBEDTLS_PK_PARSE_C) || !defined(PSA_WANT_ALG_SHA_256) || \
18 !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) || \
19 !defined(MBEDTLS_PEM_WRITE_C) || !defined(MBEDTLS_FS_IO) || \
20 !defined(MBEDTLS_MD_C)
main(void)21 int main(void)
22 {
23 mbedtls_printf("MBEDTLS_X509_CSR_WRITE_C and/or MBEDTLS_FS_IO and/or "
24 "MBEDTLS_PK_PARSE_C and/or PSA_WANT_ALG_SHA_256 and/or "
25 "MBEDTLS_ENTROPY_C and/or MBEDTLS_CTR_DRBG_C "
26 "not defined.\n");
27 mbedtls_exit(0);
28 }
29 #else
30
31 #include "mbedtls/x509_csr.h"
32 #include "mbedtls/entropy.h"
33 #include "mbedtls/ctr_drbg.h"
34 #include "mbedtls/error.h"
35
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39
40 #define DFL_FILENAME "keyfile.key"
41 #define DFL_PASSWORD NULL
42 #define DFL_DEBUG_LEVEL 0
43 #define DFL_OUTPUT_FILENAME "cert.req"
44 #define DFL_SUBJECT_NAME "CN=Cert,O=mbed TLS,C=UK"
45 #define DFL_KEY_USAGE 0
46 #define DFL_FORCE_KEY_USAGE 0
47 #define DFL_NS_CERT_TYPE 0
48 #define DFL_FORCE_NS_CERT_TYPE 0
49 #define DFL_MD_ALG MBEDTLS_MD_SHA256
50
51 #define USAGE \
52 "\n usage: cert_req param=<>...\n" \
53 "\n acceptable parameters:\n" \
54 " filename=%%s default: keyfile.key\n" \
55 " password=%%s default: NULL\n" \
56 " debug_level=%%d default: 0 (disabled)\n" \
57 " output_file=%%s default: cert.req\n" \
58 " subject_name=%%s default: CN=Cert,O=mbed TLS,C=UK\n" \
59 " san=%%s default: (none)\n" \
60 " Semicolon-separated-list of values:\n" \
61 " DNS:value\n" \
62 " URI:value\n" \
63 " RFC822:value\n" \
64 " IP:value (Only IPv4 is supported)\n" \
65 " DN:list of comma separated key=value pairs\n" \
66 " key_usage=%%s default: (empty)\n" \
67 " Comma-separated-list of values:\n" \
68 " digital_signature\n" \
69 " non_repudiation\n" \
70 " key_encipherment\n" \
71 " data_encipherment\n" \
72 " key_agreement\n" \
73 " key_cert_sign\n" \
74 " crl_sign\n" \
75 " force_key_usage=0/1 default: off\n" \
76 " Add KeyUsage even if it is empty\n" \
77 " ns_cert_type=%%s default: (empty)\n" \
78 " Comma-separated-list of values:\n" \
79 " ssl_client\n" \
80 " ssl_server\n" \
81 " email\n" \
82 " object_signing\n" \
83 " ssl_ca\n" \
84 " email_ca\n" \
85 " object_signing_ca\n" \
86 " force_ns_cert_type=0/1 default: off\n" \
87 " Add NsCertType even if it is empty\n" \
88 " md=%%s default: SHA256\n" \
89 " possible values:\n" \
90 " MD5, RIPEMD160, SHA1,\n" \
91 " SHA224, SHA256, SHA384, SHA512\n" \
92 "\n"
93
94
95 /*
96 * global options
97 */
98 struct options {
99 const char *filename; /* filename of the key file */
100 const char *password; /* password for the key file */
101 int debug_level; /* level of debugging */
102 const char *output_file; /* where to store the constructed key file */
103 const char *subject_name; /* subject name for certificate request */
104 mbedtls_x509_san_list *san_list; /* subjectAltName for certificate request */
105 unsigned char key_usage; /* key usage flags */
106 int force_key_usage; /* Force adding the KeyUsage extension */
107 unsigned char ns_cert_type; /* NS cert type */
108 int force_ns_cert_type; /* Force adding NsCertType extension */
109 mbedtls_md_type_t md_alg; /* Hash algorithm used for signature. */
110 } opt;
111
write_certificate_request(mbedtls_x509write_csr * req,const char * output_file)112 static int write_certificate_request(mbedtls_x509write_csr *req, const char *output_file)
113 {
114 int ret;
115 FILE *f;
116 unsigned char output_buf[4096];
117 size_t len = 0;
118
119 memset(output_buf, 0, 4096);
120 if ((ret = mbedtls_x509write_csr_pem(req, output_buf, 4096)) < 0) {
121 return ret;
122 }
123
124 len = strlen((char *) output_buf);
125
126 if ((f = fopen(output_file, "w")) == NULL) {
127 return -1;
128 }
129
130 if (fwrite(output_buf, 1, len, f) != len) {
131 fclose(f);
132 return -1;
133 }
134
135 fclose(f);
136
137 return 0;
138 }
139
main(int argc,char * argv[])140 int main(int argc, char *argv[])
141 {
142 int ret = 1;
143 int exit_code = MBEDTLS_EXIT_FAILURE;
144 mbedtls_pk_context key;
145 char buf[1024];
146 int i;
147 char *p, *q, *r;
148 mbedtls_x509write_csr req;
149 mbedtls_entropy_context entropy;
150 mbedtls_ctr_drbg_context ctr_drbg;
151 const char *pers = "csr example app";
152 mbedtls_x509_san_list *cur, *prev;
153 #if defined(MBEDTLS_X509_CRT_PARSE_C)
154 uint8_t ip[4] = { 0 };
155 #endif
156 /*
157 * Set to sane values
158 */
159 mbedtls_x509write_csr_init(&req);
160 mbedtls_pk_init(&key);
161 mbedtls_ctr_drbg_init(&ctr_drbg);
162 memset(buf, 0, sizeof(buf));
163 mbedtls_entropy_init(&entropy);
164
165 psa_status_t status = psa_crypto_init();
166 if (status != PSA_SUCCESS) {
167 mbedtls_fprintf(stderr, "Failed to initialize PSA Crypto implementation: %d\n",
168 (int) status);
169 goto exit;
170 }
171
172 if (argc < 2) {
173 usage:
174 mbedtls_printf(USAGE);
175 goto exit;
176 }
177
178 opt.filename = DFL_FILENAME;
179 opt.password = DFL_PASSWORD;
180 opt.debug_level = DFL_DEBUG_LEVEL;
181 opt.output_file = DFL_OUTPUT_FILENAME;
182 opt.subject_name = DFL_SUBJECT_NAME;
183 opt.key_usage = DFL_KEY_USAGE;
184 opt.force_key_usage = DFL_FORCE_KEY_USAGE;
185 opt.ns_cert_type = DFL_NS_CERT_TYPE;
186 opt.force_ns_cert_type = DFL_FORCE_NS_CERT_TYPE;
187 opt.md_alg = DFL_MD_ALG;
188 opt.san_list = NULL;
189
190 for (i = 1; i < argc; i++) {
191 p = argv[i];
192 if ((q = strchr(p, '=')) == NULL) {
193 goto usage;
194 }
195 *q++ = '\0';
196 if (strcmp(p, "filename") == 0) {
197 opt.filename = q;
198 } else if (strcmp(p, "password") == 0) {
199 opt.password = q;
200 } else if (strcmp(p, "output_file") == 0) {
201 opt.output_file = q;
202 } else if (strcmp(p, "debug_level") == 0) {
203 opt.debug_level = atoi(q);
204 if (opt.debug_level < 0 || opt.debug_level > 65535) {
205 goto usage;
206 }
207 } else if (strcmp(p, "subject_name") == 0) {
208 opt.subject_name = q;
209 } else if (strcmp(p, "san") == 0) {
210 char *subtype_value;
211 prev = NULL;
212
213 while (q != NULL) {
214 char *semicolon;
215 r = q;
216
217 /* Find the first non-escaped ; occurrence and remove escaped ones */
218 do {
219 if ((semicolon = strchr(r, ';')) != NULL) {
220 if (*(semicolon-1) != '\\') {
221 r = semicolon;
222 break;
223 }
224 /* Remove the escape character */
225 size_t size_left = strlen(semicolon);
226 memmove(semicolon-1, semicolon, size_left);
227 *(semicolon + size_left - 1) = '\0';
228 /* r will now point at the character after the semicolon */
229 r = semicolon;
230 }
231
232 } while (semicolon != NULL);
233
234 if (semicolon != NULL) {
235 *r++ = '\0';
236 } else {
237 r = NULL;
238 }
239
240 cur = mbedtls_calloc(1, sizeof(mbedtls_x509_san_list));
241 if (cur == NULL) {
242 mbedtls_printf("Not enough memory for subjectAltName list\n");
243 goto usage;
244 }
245
246 cur->next = NULL;
247
248 if ((subtype_value = strchr(q, ':')) != NULL) {
249 *subtype_value++ = '\0';
250 } else {
251 mbedtls_printf(
252 "Invalid argument for option SAN: Entry must be of the form TYPE:value\n");
253 goto usage;
254 }
255 if (strcmp(q, "RFC822") == 0) {
256 cur->node.type = MBEDTLS_X509_SAN_RFC822_NAME;
257 } else if (strcmp(q, "URI") == 0) {
258 cur->node.type = MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER;
259 } else if (strcmp(q, "DNS") == 0) {
260 cur->node.type = MBEDTLS_X509_SAN_DNS_NAME;
261 } else if (strcmp(q, "IP") == 0) {
262 size_t ip_addr_len = 0;
263 cur->node.type = MBEDTLS_X509_SAN_IP_ADDRESS;
264 ip_addr_len = mbedtls_x509_crt_parse_cn_inet_pton(subtype_value, ip);
265 if (ip_addr_len == 0) {
266 mbedtls_printf("mbedtls_x509_crt_parse_cn_inet_pton failed to parse %s\n",
267 subtype_value);
268 goto exit;
269 }
270 cur->node.san.unstructured_name.p = (unsigned char *) ip;
271 cur->node.san.unstructured_name.len = sizeof(ip);
272 } else if (strcmp(q, "DN") == 0) {
273 cur->node.type = MBEDTLS_X509_SAN_DIRECTORY_NAME;
274 /* Work around an API mismatch between string_to_names() and
275 * mbedtls_x509_subject_alternative_name, which holds an
276 * actual mbedtls_x509_name while a pointer to one would be
277 * more convenient here. (Note mbedtls_x509_name and
278 * mbedtls_asn1_named_data are synonymous, again
279 * string_to_names() uses one while
280 * cur->node.san.directory_name is nominally the other.) */
281 mbedtls_asn1_named_data *tmp_san_dirname = NULL;
282 if ((ret = mbedtls_x509_string_to_names(&tmp_san_dirname,
283 subtype_value)) != 0) {
284 mbedtls_strerror(ret, buf, sizeof(buf));
285 mbedtls_printf(
286 " failed\n ! mbedtls_x509_string_to_names "
287 "returned -0x%04x - %s\n\n",
288 (unsigned int) -ret, buf);
289 goto exit;
290 }
291 cur->node.san.directory_name = *tmp_san_dirname;
292 mbedtls_free(tmp_san_dirname);
293 tmp_san_dirname = NULL;
294 } else {
295 mbedtls_free(cur);
296 goto usage;
297 }
298
299 if (cur->node.type == MBEDTLS_X509_SAN_RFC822_NAME ||
300 cur->node.type == MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER ||
301 cur->node.type == MBEDTLS_X509_SAN_DNS_NAME) {
302 q = subtype_value;
303 cur->node.san.unstructured_name.p = (unsigned char *) q;
304 cur->node.san.unstructured_name.len = strlen(q);
305 }
306
307 if (prev == NULL) {
308 opt.san_list = cur;
309 } else {
310 prev->next = cur;
311 }
312
313 prev = cur;
314 q = r;
315 }
316 } else if (strcmp(p, "md") == 0) {
317 const mbedtls_md_info_t *md_info =
318 mbedtls_md_info_from_string(q);
319 if (md_info == NULL) {
320 mbedtls_printf("Invalid argument for option %s\n", p);
321 goto usage;
322 }
323 opt.md_alg = mbedtls_md_get_type(md_info);
324 } else if (strcmp(p, "key_usage") == 0) {
325 while (q != NULL) {
326 if ((r = strchr(q, ',')) != NULL) {
327 *r++ = '\0';
328 }
329
330 if (strcmp(q, "digital_signature") == 0) {
331 opt.key_usage |= MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
332 } else if (strcmp(q, "non_repudiation") == 0) {
333 opt.key_usage |= MBEDTLS_X509_KU_NON_REPUDIATION;
334 } else if (strcmp(q, "key_encipherment") == 0) {
335 opt.key_usage |= MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
336 } else if (strcmp(q, "data_encipherment") == 0) {
337 opt.key_usage |= MBEDTLS_X509_KU_DATA_ENCIPHERMENT;
338 } else if (strcmp(q, "key_agreement") == 0) {
339 opt.key_usage |= MBEDTLS_X509_KU_KEY_AGREEMENT;
340 } else if (strcmp(q, "key_cert_sign") == 0) {
341 opt.key_usage |= MBEDTLS_X509_KU_KEY_CERT_SIGN;
342 } else if (strcmp(q, "crl_sign") == 0) {
343 opt.key_usage |= MBEDTLS_X509_KU_CRL_SIGN;
344 } else {
345 goto usage;
346 }
347
348 q = r;
349 }
350 } else if (strcmp(p, "force_key_usage") == 0) {
351 switch (atoi(q)) {
352 case 0: opt.force_key_usage = 0; break;
353 case 1: opt.force_key_usage = 1; break;
354 default: goto usage;
355 }
356 } else if (strcmp(p, "ns_cert_type") == 0) {
357 while (q != NULL) {
358 if ((r = strchr(q, ',')) != NULL) {
359 *r++ = '\0';
360 }
361
362 if (strcmp(q, "ssl_client") == 0) {
363 opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT;
364 } else if (strcmp(q, "ssl_server") == 0) {
365 opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER;
366 } else if (strcmp(q, "email") == 0) {
367 opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_EMAIL;
368 } else if (strcmp(q, "object_signing") == 0) {
369 opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING;
370 } else if (strcmp(q, "ssl_ca") == 0) {
371 opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_CA;
372 } else if (strcmp(q, "email_ca") == 0) {
373 opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA;
374 } else if (strcmp(q, "object_signing_ca") == 0) {
375 opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA;
376 } else {
377 goto usage;
378 }
379
380 q = r;
381 }
382 } else if (strcmp(p, "force_ns_cert_type") == 0) {
383 switch (atoi(q)) {
384 case 0: opt.force_ns_cert_type = 0; break;
385 case 1: opt.force_ns_cert_type = 1; break;
386 default: goto usage;
387 }
388 } else {
389 goto usage;
390 }
391 }
392
393 /* Set the MD algorithm to use for the signature in the CSR */
394 mbedtls_x509write_csr_set_md_alg(&req, opt.md_alg);
395
396 /* Set the Key Usage Extension flags in the CSR */
397 if (opt.key_usage || opt.force_key_usage == 1) {
398 ret = mbedtls_x509write_csr_set_key_usage(&req, opt.key_usage);
399
400 if (ret != 0) {
401 mbedtls_printf(" failed\n ! mbedtls_x509write_csr_set_key_usage returned %d", ret);
402 goto exit;
403 }
404 }
405
406 /* Set the Cert Type flags in the CSR */
407 if (opt.ns_cert_type || opt.force_ns_cert_type == 1) {
408 ret = mbedtls_x509write_csr_set_ns_cert_type(&req, opt.ns_cert_type);
409
410 if (ret != 0) {
411 mbedtls_printf(" failed\n ! mbedtls_x509write_csr_set_ns_cert_type returned %d", ret);
412 goto exit;
413 }
414 }
415
416 /* Set the SubjectAltName in the CSR */
417 if (opt.san_list != NULL) {
418 ret = mbedtls_x509write_csr_set_subject_alternative_name(&req, opt.san_list);
419
420 if (ret != 0) {
421 mbedtls_printf(
422 " failed\n ! mbedtls_x509write_csr_set_subject_alternative_name returned %d",
423 ret);
424 goto exit;
425 }
426 }
427
428 /*
429 * 0. Seed the PRNG
430 */
431 mbedtls_printf(" . Seeding the random number generator...");
432 fflush(stdout);
433
434 if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
435 (const unsigned char *) pers,
436 strlen(pers))) != 0) {
437 mbedtls_printf(" failed\n ! mbedtls_ctr_drbg_seed returned %d", ret);
438 goto exit;
439 }
440
441 mbedtls_printf(" ok\n");
442
443 /*
444 * 1.0. Check the subject name for validity
445 */
446 mbedtls_printf(" . Checking subject name...");
447 fflush(stdout);
448
449 if ((ret = mbedtls_x509write_csr_set_subject_name(&req, opt.subject_name)) != 0) {
450 mbedtls_printf(" failed\n ! mbedtls_x509write_csr_set_subject_name returned %d", ret);
451 goto exit;
452 }
453
454 mbedtls_printf(" ok\n");
455
456 /*
457 * 1.1. Load the key
458 */
459 mbedtls_printf(" . Loading the private key ...");
460 fflush(stdout);
461
462 ret = mbedtls_pk_parse_keyfile(&key, opt.filename, opt.password);
463
464 if (ret != 0) {
465 mbedtls_printf(" failed\n ! mbedtls_pk_parse_keyfile returned %d", ret);
466 goto exit;
467 }
468
469 mbedtls_x509write_csr_set_key(&req, &key);
470
471 mbedtls_printf(" ok\n");
472
473 /*
474 * 1.2. Writing the request
475 */
476 mbedtls_printf(" . Writing the certificate request ...");
477 fflush(stdout);
478
479 if ((ret = write_certificate_request(&req, opt.output_file)) != 0) {
480 mbedtls_printf(" failed\n ! write_certificate_request %d", ret);
481 goto exit;
482 }
483
484 mbedtls_printf(" ok\n");
485
486 exit_code = MBEDTLS_EXIT_SUCCESS;
487
488 exit:
489
490 if (exit_code != MBEDTLS_EXIT_SUCCESS) {
491 #ifdef MBEDTLS_ERROR_C
492 mbedtls_strerror(ret, buf, sizeof(buf));
493 mbedtls_printf(" - %s\n", buf);
494 #else
495 mbedtls_printf("\n");
496 #endif
497 }
498
499 mbedtls_x509write_csr_free(&req);
500 mbedtls_pk_free(&key);
501 mbedtls_ctr_drbg_free(&ctr_drbg);
502 mbedtls_entropy_free(&entropy);
503 mbedtls_psa_crypto_free();
504
505 cur = opt.san_list;
506 while (cur != NULL) {
507 mbedtls_x509_san_list *next = cur->next;
508 /* Note: mbedtls_x509_free_subject_alt_name() is not what we want here.
509 * It's the right thing for entries that were parsed from a certificate,
510 * where pointers are to the raw certificate, but here all the
511 * pointers were allocated while parsing from a user-provided string. */
512 if (cur->node.type == MBEDTLS_X509_SAN_DIRECTORY_NAME) {
513 mbedtls_x509_name *dn = &cur->node.san.directory_name;
514 mbedtls_free(dn->oid.p);
515 mbedtls_free(dn->val.p);
516 mbedtls_asn1_free_named_data_list(&dn->next);
517 }
518 mbedtls_free(cur);
519 cur = next;
520 }
521
522 mbedtls_exit(exit_code);
523 }
524 #endif /* MBEDTLS_X509_CSR_WRITE_C && MBEDTLS_PK_PARSE_C && MBEDTLS_FS_IO &&
525 MBEDTLS_ENTROPY_C && MBEDTLS_CTR_DRBG_C && MBEDTLS_PEM_WRITE_C */
526