1 /*
2  *  Key generation application
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 #if defined(MBEDTLS_PLATFORM_C)
23 #include "mbedtls/platform.h"
24 #else
25 #include <stdio.h>
26 #include <stdlib.h>
27 #define mbedtls_printf          printf
28 #define mbedtls_exit            exit
29 #define MBEDTLS_EXIT_SUCCESS    EXIT_SUCCESS
30 #define MBEDTLS_EXIT_FAILURE    EXIT_FAILURE
31 #endif /* MBEDTLS_PLATFORM_C */
32 
33 #if defined(MBEDTLS_PK_WRITE_C) && defined(MBEDTLS_FS_IO) && \
34     defined(MBEDTLS_ENTROPY_C) && defined(MBEDTLS_CTR_DRBG_C)
35 #include "mbedtls/error.h"
36 #include "mbedtls/pk.h"
37 #include "mbedtls/ecdsa.h"
38 #include "mbedtls/rsa.h"
39 #include "mbedtls/error.h"
40 #include "mbedtls/entropy.h"
41 #include "mbedtls/ctr_drbg.h"
42 
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <string.h>
46 
47 #if !defined(_WIN32)
48 #include <unistd.h>
49 
50 #define DEV_RANDOM_THRESHOLD        32
51 
dev_random_entropy_poll(void * data,unsigned char * output,size_t len,size_t * olen)52 int dev_random_entropy_poll( void *data, unsigned char *output,
53                              size_t len, size_t *olen )
54 {
55     FILE *file;
56     size_t ret, left = len;
57     unsigned char *p = output;
58     ((void) data);
59 
60     *olen = 0;
61 
62     file = fopen( "/dev/random", "rb" );
63     if( file == NULL )
64         return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
65 
66     while( left > 0 )
67     {
68         /* /dev/random can return much less than requested. If so, try again */
69         ret = fread( p, 1, left, file );
70         if( ret == 0 && ferror( file ) )
71         {
72             fclose( file );
73             return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
74         }
75 
76         p += ret;
77         left -= ret;
78         sleep( 1 );
79     }
80     fclose( file );
81     *olen = len;
82 
83     return( 0 );
84 }
85 #endif /* !_WIN32 */
86 #endif
87 
88 #if defined(MBEDTLS_ECP_C)
89 #define DFL_EC_CURVE            mbedtls_ecp_curve_list()->grp_id
90 #else
91 #define DFL_EC_CURVE            0
92 #endif
93 
94 #if !defined(_WIN32) && defined(MBEDTLS_FS_IO)
95 #define USAGE_DEV_RANDOM \
96     "    use_dev_random=0|1    default: 0\n"
97 #else
98 #define USAGE_DEV_RANDOM ""
99 #endif /* !_WIN32 && MBEDTLS_FS_IO */
100 
101 #define FORMAT_PEM              0
102 #define FORMAT_DER              1
103 
104 #define DFL_TYPE                MBEDTLS_PK_RSA
105 #define DFL_RSA_KEYSIZE         4096
106 #define DFL_FILENAME            "keyfile.key"
107 #define DFL_FORMAT              FORMAT_PEM
108 #define DFL_USE_DEV_RANDOM      0
109 
110 #define USAGE \
111     "\n usage: gen_key param=<>...\n"                   \
112     "\n acceptable parameters:\n"                       \
113     "    type=rsa|ec           default: rsa\n"          \
114     "    rsa_keysize=%%d        default: 4096\n"        \
115     "    ec_curve=%%s           see below\n"            \
116     "    filename=%%s           default: keyfile.key\n" \
117     "    format=pem|der        default: pem\n"          \
118     USAGE_DEV_RANDOM                                    \
119     "\n"
120 
121 #if !defined(MBEDTLS_PK_WRITE_C) || !defined(MBEDTLS_PEM_WRITE_C) || \
122     !defined(MBEDTLS_FS_IO) || !defined(MBEDTLS_ENTROPY_C) || \
123     !defined(MBEDTLS_CTR_DRBG_C)
main(void)124 int main( void )
125 {
126     mbedtls_printf( "MBEDTLS_PK_WRITE_C and/or MBEDTLS_FS_IO and/or "
127             "MBEDTLS_ENTROPY_C and/or MBEDTLS_CTR_DRBG_C and/or "
128             "MBEDTLS_PEM_WRITE_C"
129             "not defined.\n" );
130     mbedtls_exit( 0 );
131 }
132 #else
133 
134 
135 /*
136  * global options
137  */
138 struct options
139 {
140     int type;                   /* the type of key to generate          */
141     int rsa_keysize;            /* length of key in bits                */
142     int ec_curve;               /* curve identifier for EC keys         */
143     const char *filename;       /* filename of the key file             */
144     int format;                 /* the output format to use             */
145     int use_dev_random;         /* use /dev/random as entropy source    */
146 } opt;
147 
write_private_key(mbedtls_pk_context * key,const char * output_file)148 static int write_private_key( mbedtls_pk_context *key, const char *output_file )
149 {
150     int ret;
151     FILE *f;
152     unsigned char output_buf[16000];
153     unsigned char *c = output_buf;
154     size_t len = 0;
155 
156     memset(output_buf, 0, 16000);
157     if( opt.format == FORMAT_PEM )
158     {
159         if( ( ret = mbedtls_pk_write_key_pem( key, output_buf, 16000 ) ) != 0 )
160             return( ret );
161 
162         len = strlen( (char *) output_buf );
163     }
164     else
165     {
166         if( ( ret = mbedtls_pk_write_key_der( key, output_buf, 16000 ) ) < 0 )
167             return( ret );
168 
169         len = ret;
170         c = output_buf + sizeof(output_buf) - len;
171     }
172 
173     if( ( f = fopen( output_file, "wb" ) ) == NULL )
174         return( -1 );
175 
176     if( fwrite( c, 1, len, f ) != len )
177     {
178         fclose( f );
179         return( -1 );
180     }
181 
182     fclose( f );
183 
184     return( 0 );
185 }
186 
main(int argc,char * argv[])187 int main( int argc, char *argv[] )
188 {
189     int ret = 1;
190     int exit_code = MBEDTLS_EXIT_FAILURE;
191     mbedtls_pk_context key;
192     char buf[1024];
193     int i;
194     char *p, *q;
195     mbedtls_mpi N, P, Q, D, E, DP, DQ, QP;
196     mbedtls_entropy_context entropy;
197     mbedtls_ctr_drbg_context ctr_drbg;
198     const char *pers = "gen_key";
199 #if defined(MBEDTLS_ECP_C)
200     const mbedtls_ecp_curve_info *curve_info;
201 #endif
202 
203     /*
204      * Set to sane values
205      */
206 
207     mbedtls_mpi_init( &N ); mbedtls_mpi_init( &P ); mbedtls_mpi_init( &Q );
208     mbedtls_mpi_init( &D ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &DP );
209     mbedtls_mpi_init( &DQ ); mbedtls_mpi_init( &QP );
210 
211     mbedtls_pk_init( &key );
212     mbedtls_ctr_drbg_init( &ctr_drbg );
213     memset( buf, 0, sizeof( buf ) );
214 
215     if( argc == 0 )
216     {
217     usage:
218         mbedtls_printf( USAGE );
219 #if defined(MBEDTLS_ECP_C)
220         mbedtls_printf( " available ec_curve values:\n" );
221         curve_info = mbedtls_ecp_curve_list();
222         mbedtls_printf( "    %s (default)\n", curve_info->name );
223         while( ( ++curve_info )->name != NULL )
224             mbedtls_printf( "    %s\n", curve_info->name );
225 #endif /* MBEDTLS_ECP_C */
226         goto exit;
227     }
228 
229     opt.type                = DFL_TYPE;
230     opt.rsa_keysize         = DFL_RSA_KEYSIZE;
231     opt.ec_curve            = DFL_EC_CURVE;
232     opt.filename            = DFL_FILENAME;
233     opt.format              = DFL_FORMAT;
234     opt.use_dev_random      = DFL_USE_DEV_RANDOM;
235 
236     for( i = 1; i < argc; i++ )
237     {
238         p = argv[i];
239         if( ( q = strchr( p, '=' ) ) == NULL )
240             goto usage;
241         *q++ = '\0';
242 
243         if( strcmp( p, "type" ) == 0 )
244         {
245             if( strcmp( q, "rsa" ) == 0 )
246                 opt.type = MBEDTLS_PK_RSA;
247             else if( strcmp( q, "ec" ) == 0 )
248                 opt.type = MBEDTLS_PK_ECKEY;
249             else
250                 goto usage;
251         }
252         else if( strcmp( p, "format" ) == 0 )
253         {
254             if( strcmp( q, "pem" ) == 0 )
255                 opt.format = FORMAT_PEM;
256             else if( strcmp( q, "der" ) == 0 )
257                 opt.format = FORMAT_DER;
258             else
259                 goto usage;
260         }
261         else if( strcmp( p, "rsa_keysize" ) == 0 )
262         {
263             opt.rsa_keysize = atoi( q );
264             if( opt.rsa_keysize < 1024 ||
265                 opt.rsa_keysize > MBEDTLS_MPI_MAX_BITS )
266                 goto usage;
267         }
268 #if defined(MBEDTLS_ECP_C)
269         else if( strcmp( p, "ec_curve" ) == 0 )
270         {
271             if( ( curve_info = mbedtls_ecp_curve_info_from_name( q ) ) == NULL )
272                 goto usage;
273             opt.ec_curve = curve_info->grp_id;
274         }
275 #endif
276         else if( strcmp( p, "filename" ) == 0 )
277             opt.filename = q;
278         else if( strcmp( p, "use_dev_random" ) == 0 )
279         {
280             opt.use_dev_random = atoi( q );
281             if( opt.use_dev_random < 0 || opt.use_dev_random > 1 )
282                 goto usage;
283         }
284         else
285             goto usage;
286     }
287 
288     mbedtls_printf( "\n  . Seeding the random number generator..." );
289     fflush( stdout );
290 
291     mbedtls_entropy_init( &entropy );
292 #if !defined(_WIN32) && defined(MBEDTLS_FS_IO)
293     if( opt.use_dev_random )
294     {
295         if( ( ret = mbedtls_entropy_add_source( &entropy, dev_random_entropy_poll,
296                                         NULL, DEV_RANDOM_THRESHOLD,
297                                         MBEDTLS_ENTROPY_SOURCE_STRONG ) ) != 0 )
298         {
299             mbedtls_printf( " failed\n  ! mbedtls_entropy_add_source returned -0x%04x\n", (unsigned int) -ret );
300             goto exit;
301         }
302 
303         mbedtls_printf("\n    Using /dev/random, so can take a long time! " );
304         fflush( stdout );
305     }
306 #endif /* !_WIN32 && MBEDTLS_FS_IO */
307 
308     if( ( ret = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy,
309                                (const unsigned char *) pers,
310                                strlen( pers ) ) ) != 0 )
311     {
312         mbedtls_printf( " failed\n  ! mbedtls_ctr_drbg_seed returned -0x%04x\n", (unsigned int) -ret );
313         goto exit;
314     }
315 
316     /*
317      * 1.1. Generate the key
318      */
319     mbedtls_printf( "\n  . Generating the private key ..." );
320     fflush( stdout );
321 
322     if( ( ret = mbedtls_pk_setup( &key,
323             mbedtls_pk_info_from_type( (mbedtls_pk_type_t) opt.type ) ) ) != 0 )
324     {
325         mbedtls_printf( " failed\n  !  mbedtls_pk_setup returned -0x%04x", (unsigned int) -ret );
326         goto exit;
327     }
328 
329 #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_GENPRIME)
330     if( opt.type == MBEDTLS_PK_RSA )
331     {
332         ret = mbedtls_rsa_gen_key( mbedtls_pk_rsa( key ), mbedtls_ctr_drbg_random, &ctr_drbg,
333                                    opt.rsa_keysize, 65537 );
334         if( ret != 0 )
335         {
336             mbedtls_printf( " failed\n  !  mbedtls_rsa_gen_key returned -0x%04x", (unsigned int) -ret );
337             goto exit;
338         }
339     }
340     else
341 #endif /* MBEDTLS_RSA_C */
342 #if defined(MBEDTLS_ECP_C)
343     if( opt.type == MBEDTLS_PK_ECKEY )
344     {
345         ret = mbedtls_ecp_gen_key( (mbedtls_ecp_group_id) opt.ec_curve,
346                                    mbedtls_pk_ec( key ),
347                                    mbedtls_ctr_drbg_random, &ctr_drbg );
348         if( ret != 0 )
349         {
350             mbedtls_printf( " failed\n  !  mbedtls_ecp_gen_key returned -0x%04x", (unsigned int) -ret );
351             goto exit;
352         }
353     }
354     else
355 #endif /* MBEDTLS_ECP_C */
356     {
357         mbedtls_printf( " failed\n  !  key type not supported\n" );
358         goto exit;
359     }
360 
361     /*
362      * 1.2 Print the key
363      */
364     mbedtls_printf( " ok\n  . Key information:\n" );
365 
366 #if defined(MBEDTLS_RSA_C)
367     if( mbedtls_pk_get_type( &key ) == MBEDTLS_PK_RSA )
368     {
369         mbedtls_rsa_context *rsa = mbedtls_pk_rsa( key );
370 
371         if( ( ret = mbedtls_rsa_export    ( rsa, &N, &P, &Q, &D, &E ) ) != 0 ||
372             ( ret = mbedtls_rsa_export_crt( rsa, &DP, &DQ, &QP ) )      != 0 )
373         {
374             mbedtls_printf( " failed\n  ! could not export RSA parameters\n\n" );
375             goto exit;
376         }
377 
378         mbedtls_mpi_write_file( "N:  ",  &N,  16, NULL );
379         mbedtls_mpi_write_file( "E:  ",  &E,  16, NULL );
380         mbedtls_mpi_write_file( "D:  ",  &D,  16, NULL );
381         mbedtls_mpi_write_file( "P:  ",  &P,  16, NULL );
382         mbedtls_mpi_write_file( "Q:  ",  &Q,  16, NULL );
383         mbedtls_mpi_write_file( "DP: ",  &DP, 16, NULL );
384         mbedtls_mpi_write_file( "DQ:  ", &DQ, 16, NULL );
385         mbedtls_mpi_write_file( "QP:  ", &QP, 16, NULL );
386     }
387     else
388 #endif
389 #if defined(MBEDTLS_ECP_C)
390     if( mbedtls_pk_get_type( &key ) == MBEDTLS_PK_ECKEY )
391     {
392         mbedtls_ecp_keypair *ecp = mbedtls_pk_ec( key );
393         mbedtls_printf( "curve: %s\n",
394                 mbedtls_ecp_curve_info_from_grp_id( ecp->MBEDTLS_PRIVATE(grp).id )->name );
395         mbedtls_mpi_write_file( "X_Q:   ", &ecp->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(X), 16, NULL );
396         mbedtls_mpi_write_file( "Y_Q:   ", &ecp->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(Y), 16, NULL );
397         mbedtls_mpi_write_file( "D:     ", &ecp->MBEDTLS_PRIVATE(d)  , 16, NULL );
398     }
399     else
400 #endif
401         mbedtls_printf("  ! key type not supported\n");
402 
403     /*
404      * 1.3 Export key
405      */
406     mbedtls_printf( "  . Writing key to file..." );
407 
408     if( ( ret = write_private_key( &key, opt.filename ) ) != 0 )
409     {
410         mbedtls_printf( " failed\n" );
411         goto exit;
412     }
413 
414     mbedtls_printf( " ok\n" );
415 
416     exit_code = MBEDTLS_EXIT_SUCCESS;
417 
418 exit:
419 
420     if( exit_code != MBEDTLS_EXIT_SUCCESS )
421     {
422 #ifdef MBEDTLS_ERROR_C
423         mbedtls_strerror( ret, buf, sizeof( buf ) );
424         mbedtls_printf( " - %s\n", buf );
425 #else
426         mbedtls_printf("\n");
427 #endif
428     }
429 
430     mbedtls_mpi_free( &N ); mbedtls_mpi_free( &P ); mbedtls_mpi_free( &Q );
431     mbedtls_mpi_free( &D ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &DP );
432     mbedtls_mpi_free( &DQ ); mbedtls_mpi_free( &QP );
433 
434     mbedtls_pk_free( &key );
435     mbedtls_ctr_drbg_free( &ctr_drbg );
436     mbedtls_entropy_free( &entropy );
437 
438 #if defined(_WIN32)
439     mbedtls_printf( "  + Press Enter to exit this program.\n" );
440     fflush( stdout ); getchar();
441 #endif
442 
443     mbedtls_exit( exit_code );
444 }
445 #endif /* MBEDTLS_PK_WRITE_C && MBEDTLS_PEM_WRITE_C && MBEDTLS_FS_IO &&
446         * MBEDTLS_ENTROPY_C && MBEDTLS_CTR_DRBG_C */
447