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     "    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 {
100     const char *filename;       /* filename of the key file             */
101     const char *password;       /* password for the key file            */
102     int debug_level;            /* level of debugging                   */
103     const char *output_file;    /* where to store the constructed key file  */
104     const char *subject_name;   /* subject name 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,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)112 int write_certificate_request( mbedtls_x509write_csr *req, const char *output_file,
113                                int (*f_rng)(void *, unsigned char *, size_t),
114                                void *p_rng )
115 {
116     int ret;
117     FILE *f;
118     unsigned char output_buf[4096];
119     size_t len = 0;
120 
121     memset( output_buf, 0, 4096 );
122     if( ( ret = mbedtls_x509write_csr_pem( req, output_buf, 4096, f_rng, p_rng ) ) < 0 )
123         return( ret );
124 
125     len = strlen( (char *) output_buf );
126 
127     if( ( f = fopen( output_file, "w" ) ) == NULL )
128         return( -1 );
129 
130     if( fwrite( output_buf, 1, len, f ) != len )
131     {
132         fclose( f );
133         return( -1 );
134     }
135 
136     fclose( f );
137 
138     return( 0 );
139 }
140 
main(int argc,char * argv[])141 int main( int argc, char *argv[] )
142 {
143     int ret = 1;
144     int exit_code = MBEDTLS_EXIT_FAILURE;
145     mbedtls_pk_context key;
146     char buf[1024];
147     int i;
148     char *p, *q, *r;
149     mbedtls_x509write_csr req;
150     mbedtls_entropy_context entropy;
151     mbedtls_ctr_drbg_context ctr_drbg;
152     const char *pers = "csr example app";
153 
154     /*
155      * Set to sane values
156      */
157     mbedtls_x509write_csr_init( &req );
158     mbedtls_pk_init( &key );
159     mbedtls_ctr_drbg_init( &ctr_drbg );
160     memset( buf, 0, sizeof( buf ) );
161 
162     if( argc == 0 )
163     {
164     usage:
165         mbedtls_printf( USAGE );
166         goto exit;
167     }
168 
169     opt.filename            = DFL_FILENAME;
170     opt.password            = DFL_PASSWORD;
171     opt.debug_level         = DFL_DEBUG_LEVEL;
172     opt.output_file         = DFL_OUTPUT_FILENAME;
173     opt.subject_name        = DFL_SUBJECT_NAME;
174     opt.key_usage           = DFL_KEY_USAGE;
175     opt.force_key_usage     = DFL_FORCE_KEY_USAGE;
176     opt.ns_cert_type        = DFL_NS_CERT_TYPE;
177     opt.force_ns_cert_type  = DFL_FORCE_NS_CERT_TYPE;
178     opt.md_alg              = DFL_MD_ALG;
179 
180     for( i = 1; i < argc; i++ )
181     {
182 
183         p = argv[i];
184         if( ( q = strchr( p, '=' ) ) == NULL )
185             goto usage;
186         *q++ = '\0';
187 
188         if( strcmp( p, "filename" ) == 0 )
189             opt.filename = q;
190         else if( strcmp( p, "password" ) == 0 )
191             opt.password = q;
192         else if( strcmp( p, "output_file" ) == 0 )
193             opt.output_file = q;
194         else if( strcmp( p, "debug_level" ) == 0 )
195         {
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         {
202             opt.subject_name = q;
203         }
204         else if( strcmp( p, "md" ) == 0 )
205         {
206             const mbedtls_md_info_t *md_info =
207                 mbedtls_md_info_from_string( q );
208             if( md_info == NULL )
209             {
210                 mbedtls_printf( "Invalid argument for option %s\n", p );
211                 goto usage;
212             }
213             opt.md_alg = mbedtls_md_get_type( md_info );
214         }
215         else if( strcmp( p, "key_usage" ) == 0 )
216         {
217             while( q != NULL )
218             {
219                 if( ( r = strchr( q, ',' ) ) != NULL )
220                     *r++ = '\0';
221 
222                 if( strcmp( q, "digital_signature" ) == 0 )
223                     opt.key_usage |= MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
224                 else if( strcmp( q, "non_repudiation" ) == 0 )
225                     opt.key_usage |= MBEDTLS_X509_KU_NON_REPUDIATION;
226                 else if( strcmp( q, "key_encipherment" ) == 0 )
227                     opt.key_usage |= MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
228                 else if( strcmp( q, "data_encipherment" ) == 0 )
229                     opt.key_usage |= MBEDTLS_X509_KU_DATA_ENCIPHERMENT;
230                 else if( strcmp( q, "key_agreement" ) == 0 )
231                     opt.key_usage |= MBEDTLS_X509_KU_KEY_AGREEMENT;
232                 else if( strcmp( q, "key_cert_sign" ) == 0 )
233                     opt.key_usage |= MBEDTLS_X509_KU_KEY_CERT_SIGN;
234                 else if( strcmp( q, "crl_sign" ) == 0 )
235                     opt.key_usage |= MBEDTLS_X509_KU_CRL_SIGN;
236                 else
237                     goto usage;
238 
239                 q = r;
240             }
241         }
242         else if( strcmp( p, "force_key_usage" ) == 0 )
243         {
244             switch( atoi( q ) )
245             {
246                 case 0: opt.force_key_usage = 0; break;
247                 case 1: opt.force_key_usage = 1; break;
248                 default: goto usage;
249             }
250         }
251         else if( strcmp( p, "ns_cert_type" ) == 0 )
252         {
253             while( q != NULL )
254             {
255                 if( ( r = strchr( q, ',' ) ) != NULL )
256                     *r++ = '\0';
257 
258                 if( strcmp( q, "ssl_client" ) == 0 )
259                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT;
260                 else if( strcmp( q, "ssl_server" ) == 0 )
261                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER;
262                 else if( strcmp( q, "email" ) == 0 )
263                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_EMAIL;
264                 else if( strcmp( q, "object_signing" ) == 0 )
265                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING;
266                 else if( strcmp( q, "ssl_ca" ) == 0 )
267                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_CA;
268                 else if( strcmp( q, "email_ca" ) == 0 )
269                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA;
270                 else if( strcmp( q, "object_signing_ca" ) == 0 )
271                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA;
272                 else
273                     goto usage;
274 
275                 q = r;
276             }
277         }
278         else if( strcmp( p, "force_ns_cert_type" ) == 0 )
279         {
280             switch( atoi( q ) )
281             {
282                 case 0: opt.force_ns_cert_type = 0; break;
283                 case 1: opt.force_ns_cert_type = 1; break;
284                 default: goto usage;
285             }
286         }
287         else
288             goto usage;
289     }
290 
291     mbedtls_x509write_csr_set_md_alg( &req, opt.md_alg );
292 
293     if( opt.key_usage || opt.force_key_usage == 1 )
294         mbedtls_x509write_csr_set_key_usage( &req, opt.key_usage );
295 
296     if( opt.ns_cert_type || opt.force_ns_cert_type == 1 )
297         mbedtls_x509write_csr_set_ns_cert_type( &req, opt.ns_cert_type );
298 
299     /*
300      * 0. Seed the PRNG
301      */
302     mbedtls_printf( "  . Seeding the random number generator..." );
303     fflush( stdout );
304 
305     mbedtls_entropy_init( &entropy );
306     if( ( ret = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy,
307                                (const unsigned char *) pers,
308                                strlen( pers ) ) ) != 0 )
309     {
310         mbedtls_printf( " failed\n  !  mbedtls_ctr_drbg_seed returned %d", ret );
311         goto exit;
312     }
313 
314     mbedtls_printf( " ok\n" );
315 
316     /*
317      * 1.0. Check the subject name for validity
318      */
319     mbedtls_printf( "  . Checking subject name..." );
320     fflush( stdout );
321 
322     if( ( ret = mbedtls_x509write_csr_set_subject_name( &req, opt.subject_name ) ) != 0 )
323     {
324         mbedtls_printf( " failed\n  !  mbedtls_x509write_csr_set_subject_name returned %d", ret );
325         goto exit;
326     }
327 
328     mbedtls_printf( " ok\n" );
329 
330     /*
331      * 1.1. Load the key
332      */
333     mbedtls_printf( "  . Loading the private key ..." );
334     fflush( stdout );
335 
336     ret = mbedtls_pk_parse_keyfile( &key, opt.filename, opt.password,
337                                     mbedtls_ctr_drbg_random, &ctr_drbg );
338 
339     if( ret != 0 )
340     {
341         mbedtls_printf( " failed\n  !  mbedtls_pk_parse_keyfile returned %d", ret );
342         goto exit;
343     }
344 
345     mbedtls_x509write_csr_set_key( &req, &key );
346 
347     mbedtls_printf( " ok\n" );
348 
349     /*
350      * 1.2. Writing the request
351      */
352     mbedtls_printf( "  . Writing the certificate request ..." );
353     fflush( stdout );
354 
355     if( ( ret = write_certificate_request( &req, opt.output_file,
356                                            mbedtls_ctr_drbg_random, &ctr_drbg ) ) != 0 )
357     {
358         mbedtls_printf( " failed\n  !  write_certificate_request %d", ret );
359         goto exit;
360     }
361 
362     mbedtls_printf( " ok\n" );
363 
364     exit_code = MBEDTLS_EXIT_SUCCESS;
365 
366 exit:
367 
368     if( exit_code != MBEDTLS_EXIT_SUCCESS )
369     {
370 #ifdef MBEDTLS_ERROR_C
371         mbedtls_strerror( ret, buf, sizeof( buf ) );
372         mbedtls_printf( " - %s\n", buf );
373 #else
374         mbedtls_printf("\n");
375 #endif
376     }
377 
378     mbedtls_x509write_csr_free( &req );
379     mbedtls_pk_free( &key );
380     mbedtls_ctr_drbg_free( &ctr_drbg );
381     mbedtls_entropy_free( &entropy );
382 
383     mbedtls_exit( exit_code );
384 }
385 #endif /* MBEDTLS_X509_CSR_WRITE_C && MBEDTLS_PK_PARSE_C && MBEDTLS_FS_IO &&
386           MBEDTLS_ENTROPY_C && MBEDTLS_CTR_DRBG_C && MBEDTLS_PEM_WRITE_C */
387