• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #if !defined(MBEDTLS_CONFIG_FILE)
9 #include "mbedtls/config.h"
10 #else
11 #include MBEDTLS_CONFIG_FILE
12 #endif
13 
14 #include "mbedtls/platform.h"
15 
16 #if !defined(MBEDTLS_X509_CSR_WRITE_C) || !defined(MBEDTLS_FS_IO) ||  \
17     !defined(MBEDTLS_PK_PARSE_C) || !defined(MBEDTLS_SHA256_C) || \
18     !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) || \
19     !defined(MBEDTLS_PEM_WRITE_C)
main(void)20 int main(void)
21 {
22     mbedtls_printf("MBEDTLS_X509_CSR_WRITE_C and/or MBEDTLS_FS_IO and/or "
23                    "MBEDTLS_PK_PARSE_C and/or MBEDTLS_SHA256_C and/or "
24                    "MBEDTLS_ENTROPY_C and/or MBEDTLS_CTR_DRBG_C "
25                    "not defined.\n");
26     mbedtls_exit(0);
27 }
28 #else
29 
30 #include "mbedtls/x509_csr.h"
31 #include "mbedtls/entropy.h"
32 #include "mbedtls/ctr_drbg.h"
33 #include "mbedtls/error.h"
34 
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 
39 #define DFL_FILENAME            "keyfile.key"
40 #define DFL_PASSWORD            NULL
41 #define DFL_DEBUG_LEVEL         0
42 #define DFL_OUTPUT_FILENAME     "cert.req"
43 #define DFL_SUBJECT_NAME        "CN=Cert,O=mbed TLS,C=UK"
44 #define DFL_KEY_USAGE           0
45 #define DFL_FORCE_KEY_USAGE     0
46 #define DFL_NS_CERT_TYPE        0
47 #define DFL_FORCE_NS_CERT_TYPE  0
48 #define DFL_MD_ALG              MBEDTLS_MD_SHA256
49 
50 #define USAGE \
51     "\n usage: cert_req param=<>...\n"                  \
52     "\n acceptable parameters:\n"                       \
53     "    filename=%%s         default: keyfile.key\n"   \
54     "    password=%%s         default: NULL\n"          \
55     "    debug_level=%%d      default: 0 (disabled)\n"  \
56     "    output_file=%%s      default: cert.req\n"      \
57     "    subject_name=%%s     default: CN=Cert,O=mbed TLS,C=UK\n"   \
58     "    key_usage=%%s        default: (empty)\n"       \
59     "                        Comma-separated-list of values:\n"     \
60     "                          digital_signature\n"     \
61     "                          non_repudiation\n"       \
62     "                          key_encipherment\n"      \
63     "                          data_encipherment\n"     \
64     "                          key_agreement\n"         \
65     "                          key_cert_sign\n"  \
66     "                          crl_sign\n"              \
67     "    force_key_usage=0/1  default: off\n"           \
68     "                          Add KeyUsage even if it is empty\n"  \
69     "    ns_cert_type=%%s     default: (empty)\n"       \
70     "                        Comma-separated-list of values:\n"     \
71     "                          ssl_client\n"            \
72     "                          ssl_server\n"            \
73     "                          email\n"                 \
74     "                          object_signing\n"        \
75     "                          ssl_ca\n"                \
76     "                          email_ca\n"              \
77     "                          object_signing_ca\n"     \
78     "    force_ns_cert_type=0/1 default: off\n"         \
79     "                          Add NsCertType even if it is empty\n"    \
80     "    md=%%s               default: SHA256\n"       \
81     "                          possible values:\n"     \
82     "                          MD2, MD4, MD5, RIPEMD160, SHA1,\n" \
83     "                          SHA224, SHA256, SHA384, SHA512\n" \
84     "\n"
85 
86 
87 /*
88  * global options
89  */
90 struct options {
91     const char *filename;       /* filename of the key file             */
92     const char *password;       /* password for the key file            */
93     int debug_level;            /* level of debugging                   */
94     const char *output_file;    /* where to store the constructed key file  */
95     const char *subject_name;   /* subject name for certificate request */
96     unsigned char key_usage;    /* key usage flags                      */
97     int force_key_usage;        /* Force adding the KeyUsage extension  */
98     unsigned char ns_cert_type; /* NS cert type                         */
99     int force_ns_cert_type;     /* Force adding NsCertType extension    */
100     mbedtls_md_type_t md_alg;   /* Hash algorithm used for signature.   */
101 } opt;
102 
write_certificate_request(mbedtls_x509write_csr * req,const char * output_file,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)103 int write_certificate_request(mbedtls_x509write_csr *req, const char *output_file,
104                               int (*f_rng)(void *, unsigned char *, size_t),
105                               void *p_rng)
106 {
107     int ret;
108     FILE *f;
109     unsigned char output_buf[4096];
110     size_t len = 0;
111 
112     memset(output_buf, 0, 4096);
113     if ((ret = mbedtls_x509write_csr_pem(req, output_buf, 4096, f_rng, p_rng)) < 0) {
114         return ret;
115     }
116 
117     len = strlen((char *) output_buf);
118 
119     if ((f = fopen(output_file, "w")) == NULL) {
120         return -1;
121     }
122 
123     if (fwrite(output_buf, 1, len, f) != len) {
124         fclose(f);
125         return -1;
126     }
127 
128     fclose(f);
129 
130     return 0;
131 }
132 
main(int argc,char * argv[])133 int main(int argc, char *argv[])
134 {
135     int ret = 1;
136     int exit_code = MBEDTLS_EXIT_FAILURE;
137     mbedtls_pk_context key;
138     char buf[1024];
139     int i;
140     char *p, *q, *r;
141     mbedtls_x509write_csr req;
142     mbedtls_entropy_context entropy;
143     mbedtls_ctr_drbg_context ctr_drbg;
144     const char *pers = "csr example app";
145 
146     /*
147      * Set to sane values
148      */
149     mbedtls_x509write_csr_init(&req);
150     mbedtls_pk_init(&key);
151     mbedtls_ctr_drbg_init(&ctr_drbg);
152     memset(buf, 0, sizeof(buf));
153     mbedtls_entropy_init(&entropy);
154 
155 #if defined(MBEDTLS_USE_PSA_CRYPTO)
156     psa_status_t status = psa_crypto_init();
157     if (status != PSA_SUCCESS) {
158         mbedtls_fprintf(stderr, "Failed to initialize PSA Crypto implementation: %d\n",
159                         (int) status);
160         goto exit;
161     }
162 #endif /* MBEDTLS_USE_PSA_CRYPTO */
163 
164     if (argc < 2) {
165 usage:
166         mbedtls_printf(USAGE);
167         goto exit;
168     }
169 
170     opt.filename            = DFL_FILENAME;
171     opt.password            = DFL_PASSWORD;
172     opt.debug_level         = DFL_DEBUG_LEVEL;
173     opt.output_file         = DFL_OUTPUT_FILENAME;
174     opt.subject_name        = DFL_SUBJECT_NAME;
175     opt.key_usage           = DFL_KEY_USAGE;
176     opt.force_key_usage     = DFL_FORCE_KEY_USAGE;
177     opt.ns_cert_type        = DFL_NS_CERT_TYPE;
178     opt.force_ns_cert_type  = DFL_FORCE_NS_CERT_TYPE;
179     opt.md_alg              = DFL_MD_ALG;
180 
181     for (i = 1; i < argc; i++) {
182 
183         p = argv[i];
184         if ((q = strchr(p, '=')) == NULL) {
185             goto usage;
186         }
187         *q++ = '\0';
188 
189         if (strcmp(p, "filename") == 0) {
190             opt.filename = q;
191         } else if (strcmp(p, "password") == 0) {
192             opt.password = q;
193         } else if (strcmp(p, "output_file") == 0) {
194             opt.output_file = q;
195         } else if (strcmp(p, "debug_level") == 0) {
196             opt.debug_level = atoi(q);
197             if (opt.debug_level < 0 || opt.debug_level > 65535) {
198                 goto usage;
199             }
200         } else if (strcmp(p, "subject_name") == 0) {
201             opt.subject_name = q;
202         } else if (strcmp(p, "md") == 0) {
203             const mbedtls_md_info_t *md_info =
204                 mbedtls_md_info_from_string(q);
205             if (md_info == NULL) {
206                 mbedtls_printf("Invalid argument for option %s\n", p);
207                 goto usage;
208             }
209             opt.md_alg = mbedtls_md_get_type(md_info);
210         } else if (strcmp(p, "key_usage") == 0) {
211             while (q != NULL) {
212                 if ((r = strchr(q, ',')) != NULL) {
213                     *r++ = '\0';
214                 }
215 
216                 if (strcmp(q, "digital_signature") == 0) {
217                     opt.key_usage |= MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
218                 } else if (strcmp(q, "non_repudiation") == 0) {
219                     opt.key_usage |= MBEDTLS_X509_KU_NON_REPUDIATION;
220                 } else if (strcmp(q, "key_encipherment") == 0) {
221                     opt.key_usage |= MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
222                 } else if (strcmp(q, "data_encipherment") == 0) {
223                     opt.key_usage |= MBEDTLS_X509_KU_DATA_ENCIPHERMENT;
224                 } else if (strcmp(q, "key_agreement") == 0) {
225                     opt.key_usage |= MBEDTLS_X509_KU_KEY_AGREEMENT;
226                 } else if (strcmp(q, "key_cert_sign") == 0) {
227                     opt.key_usage |= MBEDTLS_X509_KU_KEY_CERT_SIGN;
228                 } else if (strcmp(q, "crl_sign") == 0) {
229                     opt.key_usage |= MBEDTLS_X509_KU_CRL_SIGN;
230                 } else {
231                     goto usage;
232                 }
233 
234                 q = r;
235             }
236         } else if (strcmp(p, "force_key_usage") == 0) {
237             switch (atoi(q)) {
238                 case 0: opt.force_key_usage = 0; break;
239                 case 1: opt.force_key_usage = 1; break;
240                 default: goto usage;
241             }
242         } else if (strcmp(p, "ns_cert_type") == 0) {
243             while (q != NULL) {
244                 if ((r = strchr(q, ',')) != NULL) {
245                     *r++ = '\0';
246                 }
247 
248                 if (strcmp(q, "ssl_client") == 0) {
249                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT;
250                 } else if (strcmp(q, "ssl_server") == 0) {
251                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER;
252                 } else if (strcmp(q, "email") == 0) {
253                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_EMAIL;
254                 } else if (strcmp(q, "object_signing") == 0) {
255                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING;
256                 } else if (strcmp(q, "ssl_ca") == 0) {
257                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_CA;
258                 } else if (strcmp(q, "email_ca") == 0) {
259                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA;
260                 } else if (strcmp(q, "object_signing_ca") == 0) {
261                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA;
262                 } else {
263                     goto usage;
264                 }
265 
266                 q = r;
267             }
268         } else if (strcmp(p, "force_ns_cert_type") == 0) {
269             switch (atoi(q)) {
270                 case 0: opt.force_ns_cert_type = 0; break;
271                 case 1: opt.force_ns_cert_type = 1; break;
272                 default: goto usage;
273             }
274         } else {
275             goto usage;
276         }
277     }
278 
279     mbedtls_x509write_csr_set_md_alg(&req, opt.md_alg);
280 
281     if (opt.key_usage || opt.force_key_usage == 1) {
282         mbedtls_x509write_csr_set_key_usage(&req, opt.key_usage);
283     }
284 
285     if (opt.ns_cert_type || opt.force_ns_cert_type == 1) {
286         mbedtls_x509write_csr_set_ns_cert_type(&req, opt.ns_cert_type);
287     }
288 
289     /*
290      * 0. Seed the PRNG
291      */
292     mbedtls_printf("  . Seeding the random number generator...");
293     fflush(stdout);
294 
295     if ((ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
296                                      (const unsigned char *) pers,
297                                      strlen(pers))) != 0) {
298         mbedtls_printf(" failed\n  !  mbedtls_ctr_drbg_seed returned %d", ret);
299         goto exit;
300     }
301 
302     mbedtls_printf(" ok\n");
303 
304     /*
305      * 1.0. Check the subject name for validity
306      */
307     mbedtls_printf("  . Checking subject name...");
308     fflush(stdout);
309 
310     if ((ret = mbedtls_x509write_csr_set_subject_name(&req, opt.subject_name)) != 0) {
311         mbedtls_printf(" failed\n  !  mbedtls_x509write_csr_set_subject_name returned %d", ret);
312         goto exit;
313     }
314 
315     mbedtls_printf(" ok\n");
316 
317     /*
318      * 1.1. Load the key
319      */
320     mbedtls_printf("  . Loading the private key ...");
321     fflush(stdout);
322 
323     ret = mbedtls_pk_parse_keyfile(&key, opt.filename, opt.password);
324 
325     if (ret != 0) {
326         mbedtls_printf(" failed\n  !  mbedtls_pk_parse_keyfile returned %d", ret);
327         goto exit;
328     }
329 
330     mbedtls_x509write_csr_set_key(&req, &key);
331 
332     mbedtls_printf(" ok\n");
333 
334     /*
335      * 1.2. Writing the request
336      */
337     mbedtls_printf("  . Writing the certificate request ...");
338     fflush(stdout);
339 
340     if ((ret = write_certificate_request(&req, opt.output_file,
341                                          mbedtls_ctr_drbg_random, &ctr_drbg)) != 0) {
342         mbedtls_printf(" failed\n  !  write_certificate_request %d", ret);
343         goto exit;
344     }
345 
346     mbedtls_printf(" ok\n");
347 
348     exit_code = MBEDTLS_EXIT_SUCCESS;
349 
350 exit:
351 
352     if (exit_code != MBEDTLS_EXIT_SUCCESS) {
353 #ifdef MBEDTLS_ERROR_C
354         mbedtls_strerror(ret, buf, sizeof(buf));
355         mbedtls_printf(" - %s\n", buf);
356 #else
357         mbedtls_printf("\n");
358 #endif
359     }
360 
361     mbedtls_x509write_csr_free(&req);
362     mbedtls_pk_free(&key);
363     mbedtls_ctr_drbg_free(&ctr_drbg);
364     mbedtls_entropy_free(&entropy);
365 #if defined(MBEDTLS_USE_PSA_CRYPTO)
366     mbedtls_psa_crypto_free();
367 #endif /* MBEDTLS_USE_PSA_CRYPTO */
368 
369 #if defined(_WIN32)
370     mbedtls_printf("  + Press Enter to exit this program.\n");
371     fflush(stdout); getchar();
372 #endif
373 
374     mbedtls_exit(exit_code);
375 }
376 #endif /* MBEDTLS_X509_CSR_WRITE_C && MBEDTLS_PK_PARSE_C && MBEDTLS_FS_IO &&
377           MBEDTLS_ENTROPY_C && MBEDTLS_CTR_DRBG_C && MBEDTLS_PEM_WRITE_C */
378