1 /*
2  *  Certificate request generation
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0
6  *
7  *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8  *  not use this file except in compliance with the License.
9  *  You may obtain a copy of the License at
10  *
11  *  http://www.apache.org/licenses/LICENSE-2.0
12  *
13  *  Unless required by applicable law or agreed to in writing, software
14  *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15  *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  *  See the License for the specific language governing permissions and
17  *  limitations under the License.
18  */
19 
20 #include "mbedtls/build_info.h"
21 
22 #include "mbedtls/platform.h"
23 
24 #if !defined(MBEDTLS_X509_CSR_WRITE_C) || !defined(MBEDTLS_FS_IO) ||  \
25     !defined(MBEDTLS_PK_PARSE_C) || !defined(MBEDTLS_SHA256_C) || \
26     !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) || \
27     !defined(MBEDTLS_PEM_WRITE_C)
main(void)28 int main(void)
29 {
30     mbedtls_printf("MBEDTLS_X509_CSR_WRITE_C and/or MBEDTLS_FS_IO and/or "
31                    "MBEDTLS_PK_PARSE_C and/or MBEDTLS_SHA256_C and/or "
32                    "MBEDTLS_ENTROPY_C and/or MBEDTLS_CTR_DRBG_C "
33                    "not defined.\n");
34     mbedtls_exit(0);
35 }
36 #else
37 
38 #include "mbedtls/x509_csr.h"
39 #include "mbedtls/entropy.h"
40 #include "mbedtls/ctr_drbg.h"
41 #include "mbedtls/error.h"
42 
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 
47 #define DFL_FILENAME            "keyfile.key"
48 #define DFL_PASSWORD            NULL
49 #define DFL_DEBUG_LEVEL         0
50 #define DFL_OUTPUT_FILENAME     "cert.req"
51 #define DFL_SUBJECT_NAME        "CN=Cert,O=mbed TLS,C=UK"
52 #define DFL_KEY_USAGE           0
53 #define DFL_FORCE_KEY_USAGE     0
54 #define DFL_NS_CERT_TYPE        0
55 #define DFL_FORCE_NS_CERT_TYPE  0
56 #define DFL_MD_ALG              MBEDTLS_MD_SHA256
57 
58 #define USAGE \
59     "\n usage: cert_req param=<>...\n"                  \
60     "\n acceptable parameters:\n"                       \
61     "    filename=%%s         default: keyfile.key\n"   \
62     "    password=%%s         default: NULL\n"          \
63     "    debug_level=%%d      default: 0 (disabled)\n"  \
64     "    output_file=%%s      default: cert.req\n"      \
65     "    subject_name=%%s     default: CN=Cert,O=mbed TLS,C=UK\n"   \
66     "    san=%%s              default: (none)\n"       \
67     "                        Comma-separated-list of values:\n"     \
68     "                          DNS:value\n"            \
69     "                          URI:value\n"            \
70     "                          IP:value (Only IPv4 is supported)\n"             \
71     "    key_usage=%%s        default: (empty)\n"       \
72     "                        Comma-separated-list of values:\n"     \
73     "                          digital_signature\n"     \
74     "                          non_repudiation\n"       \
75     "                          key_encipherment\n"      \
76     "                          data_encipherment\n"     \
77     "                          key_agreement\n"         \
78     "                          key_cert_sign\n"  \
79     "                          crl_sign\n"              \
80     "    force_key_usage=0/1  default: off\n"           \
81     "                          Add KeyUsage even if it is empty\n"  \
82     "    ns_cert_type=%%s     default: (empty)\n"       \
83     "                        Comma-separated-list of values:\n"     \
84     "                          ssl_client\n"            \
85     "                          ssl_server\n"            \
86     "                          email\n"                 \
87     "                          object_signing\n"        \
88     "                          ssl_ca\n"                \
89     "                          email_ca\n"              \
90     "                          object_signing_ca\n"     \
91     "    force_ns_cert_type=0/1 default: off\n"         \
92     "                          Add NsCertType even if it is empty\n"    \
93     "    md=%%s               default: SHA256\n"       \
94     "                          possible values:\n"     \
95     "                          MD5, RIPEMD160, SHA1,\n" \
96     "                          SHA224, SHA256, SHA384, SHA512\n" \
97     "\n"
98 
99 
100 /*
101  * global options
102  */
103 struct options {
104     const char *filename;             /* filename of the key file             */
105     const char *password;             /* password for the key file            */
106     int debug_level;                  /* level of debugging                   */
107     const char *output_file;          /* where to store the constructed key file  */
108     const char *subject_name;         /* subject name for certificate request   */
109     mbedtls_x509_san_list *san_list;  /* subjectAltName for certificate request */
110     unsigned char key_usage;          /* key usage flags                      */
111     int force_key_usage;              /* Force adding the KeyUsage extension  */
112     unsigned char ns_cert_type;       /* NS cert type                         */
113     int force_ns_cert_type;           /* Force adding NsCertType extension    */
114     mbedtls_md_type_t md_alg;         /* Hash algorithm used for signature.   */
115 } opt;
116 
ip_string_to_bytes(const char * str,uint8_t * bytes,int maxBytes)117 static void ip_string_to_bytes(const char *str, uint8_t *bytes, int maxBytes)
118 {
119     for (int i = 0; i < maxBytes; i++) {
120         bytes[i] = (uint8_t) strtoul(str, NULL, 16);
121         str = strchr(str, '.');
122         if (str == NULL || *str == '\0') {
123             break;
124         }
125         str++;
126     }
127 }
128 
write_certificate_request(mbedtls_x509write_csr * req,const char * output_file,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)129 int write_certificate_request(mbedtls_x509write_csr *req, const char *output_file,
130                               int (*f_rng)(void *, unsigned char *, size_t),
131                               void *p_rng)
132 {
133     int ret;
134     FILE *f;
135     unsigned char output_buf[4096];
136     size_t len = 0;
137 
138     memset(output_buf, 0, 4096);
139     if ((ret = mbedtls_x509write_csr_pem(req, output_buf, 4096, f_rng, p_rng)) < 0) {
140         return ret;
141     }
142 
143     len = strlen((char *) output_buf);
144 
145     if ((f = fopen(output_file, "w")) == NULL) {
146         return -1;
147     }
148 
149     if (fwrite(output_buf, 1, len, f) != len) {
150         fclose(f);
151         return -1;
152     }
153 
154     fclose(f);
155 
156     return 0;
157 }
158 
main(int argc,char * argv[])159 int main(int argc, char *argv[])
160 {
161     int ret = 1;
162     int exit_code = MBEDTLS_EXIT_FAILURE;
163     mbedtls_pk_context key;
164     char buf[1024];
165     int i;
166     char *p, *q, *r, *r2;
167     mbedtls_x509write_csr req;
168     mbedtls_entropy_context entropy;
169     mbedtls_ctr_drbg_context ctr_drbg;
170     const char *pers = "csr example app";
171     mbedtls_x509_san_list *cur, *prev;
172 
173     /*
174      * Set to sane values
175      */
176     mbedtls_x509write_csr_init(&req);
177     mbedtls_pk_init(&key);
178     mbedtls_ctr_drbg_init(&ctr_drbg);
179     memset(buf, 0, sizeof(buf));
180 
181     if (argc < 2) {
182 usage:
183         mbedtls_printf(USAGE);
184         goto exit;
185     }
186 
187     opt.filename            = DFL_FILENAME;
188     opt.password            = DFL_PASSWORD;
189     opt.debug_level         = DFL_DEBUG_LEVEL;
190     opt.output_file         = DFL_OUTPUT_FILENAME;
191     opt.subject_name        = DFL_SUBJECT_NAME;
192     opt.key_usage           = DFL_KEY_USAGE;
193     opt.force_key_usage     = DFL_FORCE_KEY_USAGE;
194     opt.ns_cert_type        = DFL_NS_CERT_TYPE;
195     opt.force_ns_cert_type  = DFL_FORCE_NS_CERT_TYPE;
196     opt.md_alg              = DFL_MD_ALG;
197     opt.san_list            = NULL;
198 
199     for (i = 1; i < argc; i++) {
200         p = argv[i];
201         if ((q = strchr(p, '=')) == NULL) {
202             goto usage;
203         }
204         *q++ = '\0';
205         if (strcmp(p, "filename") == 0) {
206             opt.filename = q;
207         } else if (strcmp(p, "password") == 0) {
208             opt.password = q;
209         } else if (strcmp(p, "output_file") == 0) {
210             opt.output_file = q;
211         } else if (strcmp(p, "debug_level") == 0) {
212             opt.debug_level = atoi(q);
213             if (opt.debug_level < 0 || opt.debug_level > 65535) {
214                 goto usage;
215             }
216         } else if (strcmp(p, "subject_name") == 0) {
217             opt.subject_name = q;
218         } else if (strcmp(p, "san") == 0) {
219             prev = NULL;
220 
221             while (q != NULL) {
222                 uint8_t ip[4] = { 0 };
223 
224                 if ((r = strchr(q, ';')) != NULL) {
225                     *r++ = '\0';
226                 }
227 
228                 cur = mbedtls_calloc(1, sizeof(mbedtls_x509_san_list));
229                 if (cur == NULL) {
230                     mbedtls_printf("Not enough memory for subjectAltName list\n");
231                     goto usage;
232                 }
233 
234                 cur->next = NULL;
235 
236                 if ((r2 = strchr(q, ':')) != NULL) {
237                     *r2++ = '\0';
238                 }
239 
240                 if (strcmp(q, "URI") == 0) {
241                     cur->node.type = MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER;
242                 } else if (strcmp(q, "DNS") == 0) {
243                     cur->node.type = MBEDTLS_X509_SAN_DNS_NAME;
244                 } else if (strcmp(q, "IP") == 0) {
245                     cur->node.type = MBEDTLS_X509_SAN_IP_ADDRESS;
246                     ip_string_to_bytes(r2, ip, 4);
247                 } else {
248                     mbedtls_free(cur);
249                     goto usage;
250                 }
251 
252                 if (strcmp(q, "IP") == 0) {
253                     cur->node.san.unstructured_name.p = (unsigned char *) ip;
254                     cur->node.san.unstructured_name.len = sizeof(ip);
255                 } else {
256                     q = r2;
257                     cur->node.san.unstructured_name.p = (unsigned char *) q;
258                     cur->node.san.unstructured_name.len = strlen(q);
259                 }
260 
261                 if (prev == NULL) {
262                     opt.san_list = cur;
263                 } else {
264                     prev->next = cur;
265                 }
266 
267                 prev = cur;
268                 q = r;
269             }
270 
271         } else if (strcmp(p, "md") == 0) {
272             const mbedtls_md_info_t *md_info =
273                 mbedtls_md_info_from_string(q);
274             if (md_info == NULL) {
275                 mbedtls_printf("Invalid argument for option %s\n", p);
276                 goto usage;
277             }
278             opt.md_alg = mbedtls_md_get_type(md_info);
279         } else if (strcmp(p, "key_usage") == 0) {
280             while (q != NULL) {
281                 if ((r = strchr(q, ',')) != NULL) {
282                     *r++ = '\0';
283                 }
284 
285                 if (strcmp(q, "digital_signature") == 0) {
286                     opt.key_usage |= MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
287                 } else if (strcmp(q, "non_repudiation") == 0) {
288                     opt.key_usage |= MBEDTLS_X509_KU_NON_REPUDIATION;
289                 } else if (strcmp(q, "key_encipherment") == 0) {
290                     opt.key_usage |= MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
291                 } else if (strcmp(q, "data_encipherment") == 0) {
292                     opt.key_usage |= MBEDTLS_X509_KU_DATA_ENCIPHERMENT;
293                 } else if (strcmp(q, "key_agreement") == 0) {
294                     opt.key_usage |= MBEDTLS_X509_KU_KEY_AGREEMENT;
295                 } else if (strcmp(q, "key_cert_sign") == 0) {
296                     opt.key_usage |= MBEDTLS_X509_KU_KEY_CERT_SIGN;
297                 } else if (strcmp(q, "crl_sign") == 0) {
298                     opt.key_usage |= MBEDTLS_X509_KU_CRL_SIGN;
299                 } else {
300                     goto usage;
301                 }
302 
303                 q = r;
304             }
305         } else if (strcmp(p, "force_key_usage") == 0) {
306             switch (atoi(q)) {
307                 case 0: opt.force_key_usage = 0; break;
308                 case 1: opt.force_key_usage = 1; break;
309                 default: goto usage;
310             }
311         } else if (strcmp(p, "ns_cert_type") == 0) {
312             while (q != NULL) {
313                 if ((r = strchr(q, ',')) != NULL) {
314                     *r++ = '\0';
315                 }
316 
317                 if (strcmp(q, "ssl_client") == 0) {
318                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT;
319                 } else if (strcmp(q, "ssl_server") == 0) {
320                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER;
321                 } else if (strcmp(q, "email") == 0) {
322                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_EMAIL;
323                 } else if (strcmp(q, "object_signing") == 0) {
324                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING;
325                 } else if (strcmp(q, "ssl_ca") == 0) {
326                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_CA;
327                 } else if (strcmp(q, "email_ca") == 0) {
328                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA;
329                 } else if (strcmp(q, "object_signing_ca") == 0) {
330                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA;
331                 } else {
332                     goto usage;
333                 }
334 
335                 q = r;
336             }
337         } else if (strcmp(p, "force_ns_cert_type") == 0) {
338             switch (atoi(q)) {
339                 case 0: opt.force_ns_cert_type = 0; break;
340                 case 1: opt.force_ns_cert_type = 1; break;
341                 default: goto usage;
342             }
343         } else {
344             goto usage;
345         }
346     }
347 
348     /* Set the MD algorithm to use for the signature in the CSR */
349     mbedtls_x509write_csr_set_md_alg(&req, opt.md_alg);
350 
351     /* Set the Key Usage Extension flags in the CSR */
352     if (opt.key_usage || opt.force_key_usage == 1) {
353         ret = mbedtls_x509write_csr_set_key_usage(&req, opt.key_usage);
354 
355         if (ret != 0) {
356             mbedtls_printf(" failed\n  !  mbedtls_x509write_csr_set_key_usage returned %d", ret);
357             goto exit;
358         }
359     }
360 
361     /* Set the Cert Type flags in the CSR */
362     if (opt.ns_cert_type || opt.force_ns_cert_type == 1) {
363         ret = mbedtls_x509write_csr_set_ns_cert_type(&req, opt.ns_cert_type);
364 
365         if (ret != 0) {
366             mbedtls_printf(" failed\n  !  mbedtls_x509write_csr_set_ns_cert_type returned %d", ret);
367             goto exit;
368         }
369     }
370 
371     /* Set the SubjectAltName in the CSR */
372     if (opt.san_list != NULL) {
373         ret = mbedtls_x509write_csr_set_subject_alternative_name(&req, opt.san_list);
374 
375         if (ret != 0) {
376             mbedtls_printf(
377                 " failed\n  !  mbedtls_x509write_csr_set_subject_alternative_name returned %d",
378                 ret);
379             goto exit;
380         }
381     }
382 
383     /*
384      * 0. Seed the PRNG
385      */
386     mbedtls_printf("  . Seeding the random number generator...");
387     fflush(stdout);
388 
389     mbedtls_entropy_init(&entropy);
390     if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
391                                      (const unsigned char *) pers,
392                                      strlen(pers))) != 0) {
393         mbedtls_printf(" failed\n  !  mbedtls_ctr_drbg_seed returned %d", ret);
394         goto exit;
395     }
396 
397     mbedtls_printf(" ok\n");
398 
399     /*
400      * 1.0. Check the subject name for validity
401      */
402     mbedtls_printf("  . Checking subject name...");
403     fflush(stdout);
404 
405     if ((ret = mbedtls_x509write_csr_set_subject_name(&req, opt.subject_name)) != 0) {
406         mbedtls_printf(" failed\n  !  mbedtls_x509write_csr_set_subject_name returned %d", ret);
407         goto exit;
408     }
409 
410     mbedtls_printf(" ok\n");
411 
412     /*
413      * 1.1. Load the key
414      */
415     mbedtls_printf("  . Loading the private key ...");
416     fflush(stdout);
417 
418     ret = mbedtls_pk_parse_keyfile(&key, opt.filename, opt.password,
419                                    mbedtls_ctr_drbg_random, &ctr_drbg);
420 
421     if (ret != 0) {
422         mbedtls_printf(" failed\n  !  mbedtls_pk_parse_keyfile returned %d", ret);
423         goto exit;
424     }
425 
426     mbedtls_x509write_csr_set_key(&req, &key);
427 
428     mbedtls_printf(" ok\n");
429 
430     /*
431      * 1.2. Writing the request
432      */
433     mbedtls_printf("  . Writing the certificate request ...");
434     fflush(stdout);
435 
436     if ((ret = write_certificate_request(&req, opt.output_file,
437                                          mbedtls_ctr_drbg_random, &ctr_drbg)) != 0) {
438         mbedtls_printf(" failed\n  !  write_certificate_request %d", ret);
439         goto exit;
440     }
441 
442     mbedtls_printf(" ok\n");
443 
444     exit_code = MBEDTLS_EXIT_SUCCESS;
445 
446 exit:
447 
448     if (exit_code != MBEDTLS_EXIT_SUCCESS) {
449 #ifdef MBEDTLS_ERROR_C
450         mbedtls_strerror(ret, buf, sizeof(buf));
451         mbedtls_printf(" - %s\n", buf);
452 #else
453         mbedtls_printf("\n");
454 #endif
455     }
456 
457     mbedtls_x509write_csr_free(&req);
458     mbedtls_pk_free(&key);
459     mbedtls_ctr_drbg_free(&ctr_drbg);
460     mbedtls_entropy_free(&entropy);
461 
462     cur = opt.san_list;
463     while (cur != NULL) {
464         prev = cur;
465         cur = cur->next;
466         mbedtls_free(prev);
467     }
468 
469 
470     mbedtls_exit(exit_code);
471 }
472 #endif /* MBEDTLS_X509_CSR_WRITE_C && MBEDTLS_PK_PARSE_C && MBEDTLS_FS_IO &&
473           MBEDTLS_ENTROPY_C && MBEDTLS_CTR_DRBG_C && MBEDTLS_PEM_WRITE_C */
474