1 /*
2  *  Certificate generation and signing
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_CRT_WRITE_C) || \
25     !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_FS_IO) || \
26     !defined(MBEDTLS_ENTROPY_C) || !defined(MBEDTLS_CTR_DRBG_C) || \
27     !defined(MBEDTLS_ERROR_C) || !defined(MBEDTLS_SHA256_C) || \
28     !defined(MBEDTLS_PEM_WRITE_C)
main(void)29 int main( void )
30 {
31     mbedtls_printf( "MBEDTLS_X509_CRT_WRITE_C and/or MBEDTLS_X509_CRT_PARSE_C and/or "
32             "MBEDTLS_FS_IO and/or MBEDTLS_SHA256_C and/or "
33             "MBEDTLS_ENTROPY_C and/or MBEDTLS_CTR_DRBG_C and/or "
34             "MBEDTLS_ERROR_C not defined.\n");
35     mbedtls_exit( 0 );
36 }
37 #else
38 
39 #include "mbedtls/x509_crt.h"
40 #include "mbedtls/x509_csr.h"
41 #include "mbedtls/oid.h"
42 #include "mbedtls/entropy.h"
43 #include "mbedtls/ctr_drbg.h"
44 #include "mbedtls/md.h"
45 #include "mbedtls/error.h"
46 
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 
51 #define SET_OID(x, oid) \
52     do { x.len = MBEDTLS_OID_SIZE(oid); x.p = (unsigned char*)oid; } while( 0 )
53 
54 #if defined(MBEDTLS_X509_CSR_PARSE_C)
55 #define USAGE_CSR                                                           \
56     "    request_file=%%s         default: (empty)\n"                           \
57     "                            If request_file is specified, subject_key,\n"  \
58     "                            subject_pwd and subject_name are ignored!\n"
59 #else
60 #define USAGE_CSR ""
61 #endif /* MBEDTLS_X509_CSR_PARSE_C */
62 
63 #define FORMAT_PEM              0
64 #define FORMAT_DER              1
65 
66 #define DFL_ISSUER_CRT          ""
67 #define DFL_REQUEST_FILE        ""
68 #define DFL_SUBJECT_KEY         "subject.key"
69 #define DFL_ISSUER_KEY          "ca.key"
70 #define DFL_SUBJECT_PWD         ""
71 #define DFL_ISSUER_PWD          ""
72 #define DFL_OUTPUT_FILENAME     "cert.crt"
73 #define DFL_SUBJECT_NAME        "CN=Cert,O=mbed TLS,C=UK"
74 #define DFL_ISSUER_NAME         "CN=CA,O=mbed TLS,C=UK"
75 #define DFL_NOT_BEFORE          "20010101000000"
76 #define DFL_NOT_AFTER           "20301231235959"
77 #define DFL_SERIAL              "1"
78 #define DFL_SELFSIGN            0
79 #define DFL_IS_CA               0
80 #define DFL_MAX_PATHLEN         -1
81 #define DFL_SIG_ALG             MBEDTLS_MD_SHA256
82 #define DFL_KEY_USAGE           0
83 #define DFL_EXT_KEY_USAGE       NULL
84 #define DFL_NS_CERT_TYPE        0
85 #define DFL_VERSION             3
86 #define DFL_AUTH_IDENT          1
87 #define DFL_SUBJ_IDENT          1
88 #define DFL_CONSTRAINTS         1
89 #define DFL_DIGEST              MBEDTLS_MD_SHA256
90 #define DFL_FORMAT              FORMAT_PEM
91 
92 #define USAGE \
93     "\n usage: cert_write param=<>...\n"                \
94     "\n acceptable parameters:\n"                       \
95     USAGE_CSR                                           \
96     "    subject_key=%%s          default: subject.key\n"   \
97     "    subject_pwd=%%s          default: (empty)\n"       \
98     "    subject_name=%%s         default: CN=Cert,O=mbed TLS,C=UK\n"   \
99     "\n"                                                \
100     "    issuer_crt=%%s           default: (empty)\n"       \
101     "                            If issuer_crt is specified, issuer_name is\n"  \
102     "                            ignored!\n"                \
103     "    issuer_name=%%s          default: CN=CA,O=mbed TLS,C=UK\n"     \
104     "\n"                                                \
105     "    selfsign=%%d             default: 0 (false)\n"     \
106     "                            If selfsign is enabled, issuer_name and\n" \
107     "                            issuer_key are required (issuer_crt and\n" \
108     "                            subject_* are ignored\n"   \
109     "    issuer_key=%%s           default: ca.key\n"        \
110     "    issuer_pwd=%%s           default: (empty)\n"       \
111     "    output_file=%%s          default: cert.crt\n"      \
112     "    serial=%%s               default: 1\n"             \
113     "    not_before=%%s           default: 20010101000000\n"\
114     "    not_after=%%s            default: 20301231235959\n"\
115     "    is_ca=%%d                default: 0 (disabled)\n"  \
116     "    max_pathlen=%%d          default: -1 (none)\n"     \
117     "    md=%%s                   default: SHA256\n"        \
118     "                            Supported values (if enabled):\n"      \
119     "                            MD5, RIPEMD160, SHA1,\n" \
120     "                            SHA224, SHA256, SHA384, SHA512\n" \
121     "    version=%%d              default: 3\n"            \
122     "                            Possible values: 1, 2, 3\n"\
123     "    subject_identifier=%%s   default: 1\n"             \
124     "                            Possible values: 0, 1\n"   \
125     "                            (Considered for v3 only)\n"\
126     "    authority_identifier=%%s default: 1\n"             \
127     "                            Possible values: 0, 1\n"   \
128     "                            (Considered for v3 only)\n"\
129     "    basic_constraints=%%d    default: 1\n"             \
130     "                            Possible values: 0, 1\n"   \
131     "                            (Considered for v3 only)\n"\
132     "    key_usage=%%s            default: (empty)\n"       \
133     "                            Comma-separated-list of values:\n"     \
134     "                            digital_signature\n"     \
135     "                            non_repudiation\n"       \
136     "                            key_encipherment\n"      \
137     "                            data_encipherment\n"     \
138     "                            key_agreement\n"         \
139     "                            key_cert_sign\n"  \
140     "                            crl_sign\n"              \
141     "                            (Considered for v3 only)\n"\
142     "    ext_key_usage=%%s        default: (empty)\n"      \
143     "                            Comma-separated-list of values:\n"     \
144     "                            serverAuth\n"             \
145     "                            clientAuth\n"             \
146     "                            codeSigning\n"            \
147     "                            emailProtection\n"        \
148     "                            timeStamping\n"           \
149     "                            OCSPSigning\n"            \
150     "    ns_cert_type=%%s         default: (empty)\n"       \
151     "                            Comma-separated-list of values:\n"     \
152     "                            ssl_client\n"            \
153     "                            ssl_server\n"            \
154     "                            email\n"                 \
155     "                            object_signing\n"        \
156     "                            ssl_ca\n"                \
157     "                            email_ca\n"              \
158     "                            object_signing_ca\n"     \
159     "   format=pem|der           default: pem\n"         \
160     "\n"
161 
162 
163 /*
164  * global options
165  */
166 struct options
167 {
168     const char *issuer_crt;     /* filename of the issuer certificate   */
169     const char *request_file;   /* filename of the certificate request  */
170     const char *subject_key;    /* filename of the subject key file     */
171     const char *issuer_key;     /* filename of the issuer key file      */
172     const char *subject_pwd;    /* password for the subject key file    */
173     const char *issuer_pwd;     /* password for the issuer key file     */
174     const char *output_file;    /* where to store the constructed CRT   */
175     const char *subject_name;   /* subject name for certificate         */
176     const char *issuer_name;    /* issuer name for certificate          */
177     const char *not_before;     /* validity period not before           */
178     const char *not_after;      /* validity period not after            */
179     const char *serial;         /* serial number string                 */
180     int selfsign;               /* selfsign the certificate             */
181     int is_ca;                  /* is a CA certificate                  */
182     int max_pathlen;            /* maximum CA path length               */
183     int authority_identifier;   /* add authority identifier to CRT      */
184     int subject_identifier;     /* add subject identifier to CRT        */
185     int basic_constraints;      /* add basic constraints ext to CRT     */
186     int version;                /* CRT version                          */
187     mbedtls_md_type_t md;       /* Hash used for signing                */
188     unsigned char key_usage;    /* key usage flags                      */
189     mbedtls_asn1_sequence *ext_key_usage; /* extended key usages        */
190     unsigned char ns_cert_type; /* NS cert type                         */
191     int format;                 /* format                               */
192 } opt;
193 
write_certificate(mbedtls_x509write_cert * crt,const char * output_file,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)194 int write_certificate( mbedtls_x509write_cert *crt, const char *output_file,
195                        int (*f_rng)(void *, unsigned char *, size_t),
196                        void *p_rng )
197 {
198     int ret;
199     FILE *f;
200     unsigned char output_buf[4096];
201     unsigned char *output_start;
202     size_t len = 0;
203 
204     memset( output_buf, 0, 4096 );
205     if ( opt.format == FORMAT_DER )
206     {
207         ret = mbedtls_x509write_crt_der( crt, output_buf, 4096,
208                                            f_rng, p_rng );
209         if( ret < 0 )
210             return( ret );
211 
212         len = ret;
213         output_start = output_buf + 4096 - len;
214     } else {
215         ret = mbedtls_x509write_crt_pem( crt, output_buf, 4096,
216                                            f_rng, p_rng );
217         if( ret < 0 )
218             return( ret );
219 
220         len = strlen( (char *) output_buf );
221         output_start = output_buf;
222     }
223 
224     if( ( f = fopen( output_file, "w" ) ) == NULL )
225         return( -1 );
226 
227     if( fwrite( output_start, 1, len, f ) != len )
228     {
229         fclose( f );
230         return( -1 );
231     }
232 
233     fclose( f );
234 
235     return( 0 );
236 }
237 
main(int argc,char * argv[])238 int main( int argc, char *argv[] )
239 {
240     int ret = 1;
241     int exit_code = MBEDTLS_EXIT_FAILURE;
242     mbedtls_x509_crt issuer_crt;
243     mbedtls_pk_context loaded_issuer_key, loaded_subject_key;
244     mbedtls_pk_context *issuer_key = &loaded_issuer_key,
245                 *subject_key = &loaded_subject_key;
246     char buf[1024];
247     char issuer_name[256];
248     int i;
249     char *p, *q, *r;
250 #if defined(MBEDTLS_X509_CSR_PARSE_C)
251     char subject_name[256];
252     mbedtls_x509_csr csr;
253 #endif
254     mbedtls_x509write_cert crt;
255     mbedtls_mpi serial;
256     mbedtls_asn1_sequence *ext_key_usage;
257     mbedtls_entropy_context entropy;
258     mbedtls_ctr_drbg_context ctr_drbg;
259     const char *pers = "crt example app";
260 
261     /*
262      * Set to sane values
263      */
264     mbedtls_x509write_crt_init( &crt );
265     mbedtls_pk_init( &loaded_issuer_key );
266     mbedtls_pk_init( &loaded_subject_key );
267     mbedtls_mpi_init( &serial );
268     mbedtls_ctr_drbg_init( &ctr_drbg );
269     mbedtls_entropy_init( &entropy );
270 #if defined(MBEDTLS_X509_CSR_PARSE_C)
271     mbedtls_x509_csr_init( &csr );
272 #endif
273     mbedtls_x509_crt_init( &issuer_crt );
274     memset( buf, 0, sizeof(buf) );
275 
276     if( argc == 0 )
277     {
278     usage:
279         mbedtls_printf( USAGE );
280         goto exit;
281     }
282 
283     opt.issuer_crt          = DFL_ISSUER_CRT;
284     opt.request_file        = DFL_REQUEST_FILE;
285     opt.subject_key         = DFL_SUBJECT_KEY;
286     opt.issuer_key          = DFL_ISSUER_KEY;
287     opt.subject_pwd         = DFL_SUBJECT_PWD;
288     opt.issuer_pwd          = DFL_ISSUER_PWD;
289     opt.output_file         = DFL_OUTPUT_FILENAME;
290     opt.subject_name        = DFL_SUBJECT_NAME;
291     opt.issuer_name         = DFL_ISSUER_NAME;
292     opt.not_before          = DFL_NOT_BEFORE;
293     opt.not_after           = DFL_NOT_AFTER;
294     opt.serial              = DFL_SERIAL;
295     opt.selfsign            = DFL_SELFSIGN;
296     opt.is_ca               = DFL_IS_CA;
297     opt.max_pathlen         = DFL_MAX_PATHLEN;
298     opt.key_usage           = DFL_KEY_USAGE;
299     opt.ext_key_usage       = DFL_EXT_KEY_USAGE;
300     opt.ns_cert_type        = DFL_NS_CERT_TYPE;
301     opt.version             = DFL_VERSION - 1;
302     opt.md                  = DFL_DIGEST;
303     opt.subject_identifier   = DFL_SUBJ_IDENT;
304     opt.authority_identifier = DFL_AUTH_IDENT;
305     opt.basic_constraints    = DFL_CONSTRAINTS;
306     opt.format              = DFL_FORMAT;
307 
308     for( i = 1; i < argc; i++ )
309     {
310 
311         p = argv[i];
312         if( ( q = strchr( p, '=' ) ) == NULL )
313             goto usage;
314         *q++ = '\0';
315 
316         if( strcmp( p, "request_file" ) == 0 )
317             opt.request_file = q;
318         else if( strcmp( p, "subject_key" ) == 0 )
319             opt.subject_key = q;
320         else if( strcmp( p, "issuer_key" ) == 0 )
321             opt.issuer_key = q;
322         else if( strcmp( p, "subject_pwd" ) == 0 )
323             opt.subject_pwd = q;
324         else if( strcmp( p, "issuer_pwd" ) == 0 )
325             opt.issuer_pwd = q;
326         else if( strcmp( p, "issuer_crt" ) == 0 )
327             opt.issuer_crt = q;
328         else if( strcmp( p, "output_file" ) == 0 )
329             opt.output_file = q;
330         else if( strcmp( p, "subject_name" ) == 0 )
331         {
332             opt.subject_name = q;
333         }
334         else if( strcmp( p, "issuer_name" ) == 0 )
335         {
336             opt.issuer_name = q;
337         }
338         else if( strcmp( p, "not_before" ) == 0 )
339         {
340             opt.not_before = q;
341         }
342         else if( strcmp( p, "not_after" ) == 0 )
343         {
344             opt.not_after = q;
345         }
346         else if( strcmp( p, "serial" ) == 0 )
347         {
348             opt.serial = q;
349         }
350         else if( strcmp( p, "authority_identifier" ) == 0 )
351         {
352             opt.authority_identifier = atoi( q );
353             if( opt.authority_identifier != 0 &&
354                 opt.authority_identifier != 1 )
355             {
356                 mbedtls_printf( "Invalid argument for option %s\n", p );
357                 goto usage;
358             }
359         }
360         else if( strcmp( p, "subject_identifier" ) == 0 )
361         {
362             opt.subject_identifier = atoi( q );
363             if( opt.subject_identifier != 0 &&
364                 opt.subject_identifier != 1 )
365             {
366                 mbedtls_printf( "Invalid argument for option %s\n", p );
367                 goto usage;
368             }
369         }
370         else if( strcmp( p, "basic_constraints" ) == 0 )
371         {
372             opt.basic_constraints = atoi( q );
373             if( opt.basic_constraints != 0 &&
374                 opt.basic_constraints != 1 )
375             {
376                 mbedtls_printf( "Invalid argument for option %s\n", p );
377                 goto usage;
378             }
379         }
380         else if( strcmp( p, "md" ) == 0 )
381         {
382             const mbedtls_md_info_t *md_info =
383                 mbedtls_md_info_from_string( q );
384             if( md_info == NULL )
385             {
386                 mbedtls_printf( "Invalid argument for option %s\n", p );
387                 goto usage;
388             }
389             opt.md = mbedtls_md_get_type( md_info );
390         }
391         else if( strcmp( p, "version" ) == 0 )
392         {
393             opt.version = atoi( q );
394             if( opt.version < 1 || opt.version > 3 )
395             {
396                 mbedtls_printf( "Invalid argument for option %s\n", p );
397                 goto usage;
398             }
399             opt.version--;
400         }
401         else if( strcmp( p, "selfsign" ) == 0 )
402         {
403             opt.selfsign = atoi( q );
404             if( opt.selfsign < 0 || opt.selfsign > 1 )
405             {
406                 mbedtls_printf( "Invalid argument for option %s\n", p );
407                 goto usage;
408             }
409         }
410         else if( strcmp( p, "is_ca" ) == 0 )
411         {
412             opt.is_ca = atoi( q );
413             if( opt.is_ca < 0 || opt.is_ca > 1 )
414             {
415                 mbedtls_printf( "Invalid argument for option %s\n", p );
416                 goto usage;
417             }
418         }
419         else if( strcmp( p, "max_pathlen" ) == 0 )
420         {
421             opt.max_pathlen = atoi( q );
422             if( opt.max_pathlen < -1 || opt.max_pathlen > 127 )
423             {
424                 mbedtls_printf( "Invalid argument for option %s\n", p );
425                 goto usage;
426             }
427         }
428         else if( strcmp( p, "key_usage" ) == 0 )
429         {
430             while( q != NULL )
431             {
432                 if( ( r = strchr( q, ',' ) ) != NULL )
433                     *r++ = '\0';
434 
435                 if( strcmp( q, "digital_signature" ) == 0 )
436                     opt.key_usage |= MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
437                 else if( strcmp( q, "non_repudiation" ) == 0 )
438                     opt.key_usage |= MBEDTLS_X509_KU_NON_REPUDIATION;
439                 else if( strcmp( q, "key_encipherment" ) == 0 )
440                     opt.key_usage |= MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
441                 else if( strcmp( q, "data_encipherment" ) == 0 )
442                     opt.key_usage |= MBEDTLS_X509_KU_DATA_ENCIPHERMENT;
443                 else if( strcmp( q, "key_agreement" ) == 0 )
444                     opt.key_usage |= MBEDTLS_X509_KU_KEY_AGREEMENT;
445                 else if( strcmp( q, "key_cert_sign" ) == 0 )
446                     opt.key_usage |= MBEDTLS_X509_KU_KEY_CERT_SIGN;
447                 else if( strcmp( q, "crl_sign" ) == 0 )
448                     opt.key_usage |= MBEDTLS_X509_KU_CRL_SIGN;
449                 else
450                 {
451                     mbedtls_printf( "Invalid argument for option %s\n", p );
452                     goto usage;
453                 }
454 
455                 q = r;
456             }
457         }
458         else if( strcmp( p, "ext_key_usage" ) == 0 )
459         {
460             mbedtls_asn1_sequence **tail = &opt.ext_key_usage;
461 
462             while( q != NULL )
463             {
464                 if( ( r = strchr( q, ',' ) ) != NULL )
465                     *r++ = '\0';
466 
467                 ext_key_usage = mbedtls_calloc( 1, sizeof(mbedtls_asn1_sequence) );
468                 ext_key_usage->buf.tag = MBEDTLS_ASN1_OID;
469                 if( strcmp( q, "serverAuth" ) == 0 )
470                     SET_OID( ext_key_usage->buf, MBEDTLS_OID_SERVER_AUTH );
471                 else if( strcmp( q, "clientAuth" ) == 0 )
472                     SET_OID( ext_key_usage->buf, MBEDTLS_OID_CLIENT_AUTH );
473                 else if( strcmp( q, "codeSigning" ) == 0 )
474                     SET_OID( ext_key_usage->buf, MBEDTLS_OID_CODE_SIGNING );
475                 else if( strcmp( q, "emailProtection" ) == 0 )
476                     SET_OID( ext_key_usage->buf, MBEDTLS_OID_EMAIL_PROTECTION );
477                 else if( strcmp( q, "timeStamping" ) == 0 )
478                     SET_OID( ext_key_usage->buf, MBEDTLS_OID_TIME_STAMPING );
479                 else if( strcmp( q, "OCSPSigning" ) == 0 )
480                     SET_OID( ext_key_usage->buf, MBEDTLS_OID_OCSP_SIGNING );
481                 else
482                 {
483                     mbedtls_printf( "Invalid argument for option %s\n", p );
484                     goto usage;
485                 }
486 
487                 *tail = ext_key_usage;
488                 tail = &ext_key_usage->next;
489 
490                 q = r;
491             }
492         }
493         else if( strcmp( p, "ns_cert_type" ) == 0 )
494         {
495             while( q != NULL )
496             {
497                 if( ( r = strchr( q, ',' ) ) != NULL )
498                     *r++ = '\0';
499 
500                 if( strcmp( q, "ssl_client" ) == 0 )
501                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT;
502                 else if( strcmp( q, "ssl_server" ) == 0 )
503                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER;
504                 else if( strcmp( q, "email" ) == 0 )
505                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_EMAIL;
506                 else if( strcmp( q, "object_signing" ) == 0 )
507                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING;
508                 else if( strcmp( q, "ssl_ca" ) == 0 )
509                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_SSL_CA;
510                 else if( strcmp( q, "email_ca" ) == 0 )
511                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA;
512                 else if( strcmp( q, "object_signing_ca" ) == 0 )
513                     opt.ns_cert_type |= MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA;
514                 else
515                 {
516                     mbedtls_printf( "Invalid argument for option %s\n", p );
517                     goto usage;
518                 }
519 
520                 q = r;
521             }
522         }
523         else if( strcmp( p, "format" ) == 0 )
524         {
525             if      ( strcmp(q, "der" ) == 0 ) opt.format = FORMAT_DER;
526             else if ( strcmp(q, "pem" ) == 0 ) opt.format = FORMAT_PEM;
527             else
528             {
529                 mbedtls_printf( "Invalid argument for option %s\n", p );
530                 goto usage;
531             }
532         }
533         else
534             goto usage;
535     }
536 
537     mbedtls_printf("\n");
538 
539     /*
540      * 0. Seed the PRNG
541      */
542     mbedtls_printf( "  . Seeding the random number generator..." );
543     fflush( stdout );
544 
545     if( ( ret = mbedtls_ctr_drbg_seed( &ctr_drbg, mbedtls_entropy_func, &entropy,
546                                (const unsigned char *) pers,
547                                strlen( pers ) ) ) != 0 )
548     {
549         mbedtls_strerror( ret, buf, sizeof(buf) );
550         mbedtls_printf( " failed\n  !  mbedtls_ctr_drbg_seed returned %d - %s\n",
551                         ret, buf );
552         goto exit;
553     }
554 
555     mbedtls_printf( " ok\n" );
556 
557     // Parse serial to MPI
558     //
559     mbedtls_printf( "  . Reading serial number..." );
560     fflush( stdout );
561 
562     if( ( ret = mbedtls_mpi_read_string( &serial, 10, opt.serial ) ) != 0 )
563     {
564         mbedtls_strerror( ret, buf, sizeof(buf) );
565         mbedtls_printf( " failed\n  !  mbedtls_mpi_read_string "
566                         "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
567         goto exit;
568     }
569 
570     mbedtls_printf( " ok\n" );
571 
572     // Parse issuer certificate if present
573     //
574     if( !opt.selfsign && strlen( opt.issuer_crt ) )
575     {
576         /*
577          * 1.0.a. Load the certificates
578          */
579         mbedtls_printf( "  . Loading the issuer certificate ..." );
580         fflush( stdout );
581 
582         if( ( ret = mbedtls_x509_crt_parse_file( &issuer_crt, opt.issuer_crt ) ) != 0 )
583         {
584             mbedtls_strerror( ret, buf, sizeof(buf) );
585             mbedtls_printf( " failed\n  !  mbedtls_x509_crt_parse_file "
586                             "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
587             goto exit;
588         }
589 
590         ret = mbedtls_x509_dn_gets( issuer_name, sizeof(issuer_name),
591                                  &issuer_crt.subject );
592         if( ret < 0 )
593         {
594             mbedtls_strerror( ret, buf, sizeof(buf) );
595             mbedtls_printf( " failed\n  !  mbedtls_x509_dn_gets "
596                             "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
597             goto exit;
598         }
599 
600         opt.issuer_name = issuer_name;
601 
602         mbedtls_printf( " ok\n" );
603     }
604 
605 #if defined(MBEDTLS_X509_CSR_PARSE_C)
606     // Parse certificate request if present
607     //
608     if( !opt.selfsign && strlen( opt.request_file ) )
609     {
610         /*
611          * 1.0.b. Load the CSR
612          */
613         mbedtls_printf( "  . Loading the certificate request ..." );
614         fflush( stdout );
615 
616         if( ( ret = mbedtls_x509_csr_parse_file( &csr, opt.request_file ) ) != 0 )
617         {
618             mbedtls_strerror( ret, buf, sizeof(buf) );
619             mbedtls_printf( " failed\n  !  mbedtls_x509_csr_parse_file "
620                             "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
621             goto exit;
622         }
623 
624         ret = mbedtls_x509_dn_gets( subject_name, sizeof(subject_name),
625                                  &csr.subject );
626         if( ret < 0 )
627         {
628             mbedtls_strerror( ret, buf, sizeof(buf) );
629             mbedtls_printf( " failed\n  !  mbedtls_x509_dn_gets "
630                             "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
631             goto exit;
632         }
633 
634         opt.subject_name = subject_name;
635         subject_key = &csr.pk;
636 
637         mbedtls_printf( " ok\n" );
638     }
639 #endif /* MBEDTLS_X509_CSR_PARSE_C */
640 
641     /*
642      * 1.1. Load the keys
643      */
644     if( !opt.selfsign && !strlen( opt.request_file ) )
645     {
646         mbedtls_printf( "  . Loading the subject key ..." );
647         fflush( stdout );
648 
649         ret = mbedtls_pk_parse_keyfile( &loaded_subject_key, opt.subject_key,
650                 opt.subject_pwd, mbedtls_ctr_drbg_random, &ctr_drbg );
651         if( ret != 0 )
652         {
653             mbedtls_strerror( ret, buf, sizeof(buf) );
654             mbedtls_printf( " failed\n  !  mbedtls_pk_parse_keyfile "
655                             "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
656             goto exit;
657         }
658 
659         mbedtls_printf( " ok\n" );
660     }
661 
662     mbedtls_printf( "  . Loading the issuer key ..." );
663     fflush( stdout );
664 
665     ret = mbedtls_pk_parse_keyfile( &loaded_issuer_key, opt.issuer_key,
666             opt.issuer_pwd, mbedtls_ctr_drbg_random, &ctr_drbg );
667     if( ret != 0 )
668     {
669         mbedtls_strerror( ret, buf, sizeof(buf) );
670         mbedtls_printf( " failed\n  !  mbedtls_pk_parse_keyfile "
671                         "returned -x%02x - %s\n\n", (unsigned int) -ret, buf );
672         goto exit;
673     }
674 
675     // Check if key and issuer certificate match
676     //
677     if( strlen( opt.issuer_crt ) )
678     {
679         if( mbedtls_pk_check_pair( &issuer_crt.pk, issuer_key,
680                                    mbedtls_ctr_drbg_random, &ctr_drbg ) != 0 )
681         {
682             mbedtls_printf( " failed\n  !  issuer_key does not match "
683                             "issuer certificate\n\n" );
684             goto exit;
685         }
686     }
687 
688     mbedtls_printf( " ok\n" );
689 
690     if( opt.selfsign )
691     {
692         opt.subject_name = opt.issuer_name;
693         subject_key = issuer_key;
694     }
695 
696     mbedtls_x509write_crt_set_subject_key( &crt, subject_key );
697     mbedtls_x509write_crt_set_issuer_key( &crt, issuer_key );
698 
699     /*
700      * 1.0. Check the names for validity
701      */
702     if( ( ret = mbedtls_x509write_crt_set_subject_name( &crt, opt.subject_name ) ) != 0 )
703     {
704         mbedtls_strerror( ret, buf, sizeof(buf) );
705         mbedtls_printf( " failed\n  !  mbedtls_x509write_crt_set_subject_name "
706                         "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
707         goto exit;
708     }
709 
710     if( ( ret = mbedtls_x509write_crt_set_issuer_name( &crt, opt.issuer_name ) ) != 0 )
711     {
712         mbedtls_strerror( ret, buf, sizeof(buf) );
713         mbedtls_printf( " failed\n  !  mbedtls_x509write_crt_set_issuer_name "
714                         "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
715         goto exit;
716     }
717 
718     mbedtls_printf( "  . Setting certificate values ..." );
719     fflush( stdout );
720 
721     mbedtls_x509write_crt_set_version( &crt, opt.version );
722     mbedtls_x509write_crt_set_md_alg( &crt, opt.md );
723 
724     ret = mbedtls_x509write_crt_set_serial( &crt, &serial );
725     if( ret != 0 )
726     {
727         mbedtls_strerror( ret, buf, sizeof(buf) );
728         mbedtls_printf( " failed\n  !  mbedtls_x509write_crt_set_serial "
729                         "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
730         goto exit;
731     }
732 
733     ret = mbedtls_x509write_crt_set_validity( &crt, opt.not_before, opt.not_after );
734     if( ret != 0 )
735     {
736         mbedtls_strerror( ret, buf, sizeof(buf) );
737         mbedtls_printf( " failed\n  !  mbedtls_x509write_crt_set_validity "
738                         "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
739         goto exit;
740     }
741 
742     mbedtls_printf( " ok\n" );
743 
744     if( opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
745         opt.basic_constraints != 0 )
746     {
747         mbedtls_printf( "  . Adding the Basic Constraints extension ..." );
748         fflush( stdout );
749 
750         ret = mbedtls_x509write_crt_set_basic_constraints( &crt, opt.is_ca,
751                                                            opt.max_pathlen );
752         if( ret != 0 )
753         {
754             mbedtls_strerror( ret, buf, sizeof(buf) );
755             mbedtls_printf( " failed\n  !  x509write_crt_set_basic_constraints "
756                             "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
757             goto exit;
758         }
759 
760         mbedtls_printf( " ok\n" );
761     }
762 
763 #if defined(MBEDTLS_SHA1_C)
764     if( opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
765         opt.subject_identifier != 0 )
766     {
767         mbedtls_printf( "  . Adding the Subject Key Identifier ..." );
768         fflush( stdout );
769 
770         ret = mbedtls_x509write_crt_set_subject_key_identifier( &crt );
771         if( ret != 0 )
772         {
773             mbedtls_strerror( ret, buf, sizeof(buf) );
774             mbedtls_printf( " failed\n  !  mbedtls_x509write_crt_set_subject"
775                             "_key_identifier returned -0x%04x - %s\n\n",
776                             (unsigned int) -ret, buf );
777             goto exit;
778         }
779 
780         mbedtls_printf( " ok\n" );
781     }
782 
783     if( opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
784         opt.authority_identifier != 0 )
785     {
786         mbedtls_printf( "  . Adding the Authority Key Identifier ..." );
787         fflush( stdout );
788 
789         ret = mbedtls_x509write_crt_set_authority_key_identifier( &crt );
790         if( ret != 0 )
791         {
792             mbedtls_strerror( ret, buf, sizeof(buf) );
793             mbedtls_printf( " failed\n  !  mbedtls_x509write_crt_set_authority_"
794                             "key_identifier returned -0x%04x - %s\n\n",
795                             (unsigned int) -ret, buf );
796             goto exit;
797         }
798 
799         mbedtls_printf( " ok\n" );
800     }
801 #endif /* MBEDTLS_SHA1_C */
802 
803     if( opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
804         opt.key_usage != 0 )
805     {
806         mbedtls_printf( "  . Adding the Key Usage extension ..." );
807         fflush( stdout );
808 
809         ret = mbedtls_x509write_crt_set_key_usage( &crt, opt.key_usage );
810         if( ret != 0 )
811         {
812             mbedtls_strerror( ret, buf, sizeof(buf) );
813             mbedtls_printf( " failed\n  !  mbedtls_x509write_crt_set_key_usage "
814                             "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
815             goto exit;
816         }
817 
818         mbedtls_printf( " ok\n" );
819     }
820 
821     if( opt.ext_key_usage )
822     {
823         mbedtls_printf( "  . Adding the Extended Key Usage extension ..." );
824         fflush( stdout );
825 
826         ret = mbedtls_x509write_crt_set_ext_key_usage( &crt, opt.ext_key_usage );
827         if( ret != 0 )
828         {
829             mbedtls_strerror( ret, buf, sizeof(buf) );
830             mbedtls_printf( " failed\n  !  mbedtls_x509write_crt_set_ext_key_usage returned -0x%02x - %s\n\n", (unsigned int) -ret, buf );
831             goto exit;
832         }
833 
834         mbedtls_printf( " ok\n" );
835     }
836 
837     if( opt.version == MBEDTLS_X509_CRT_VERSION_3 &&
838         opt.ns_cert_type != 0 )
839     {
840         mbedtls_printf( "  . Adding the NS Cert Type extension ..." );
841         fflush( stdout );
842 
843         ret = mbedtls_x509write_crt_set_ns_cert_type( &crt, opt.ns_cert_type );
844         if( ret != 0 )
845         {
846             mbedtls_strerror( ret, buf, sizeof(buf) );
847             mbedtls_printf( " failed\n  !  mbedtls_x509write_crt_set_ns_cert_type "
848                             "returned -0x%04x - %s\n\n", (unsigned int) -ret, buf );
849             goto exit;
850         }
851 
852         mbedtls_printf( " ok\n" );
853     }
854 
855     /*
856      * 1.2. Writing the certificate
857      */
858     mbedtls_printf( "  . Writing the certificate..." );
859     fflush( stdout );
860 
861     if( ( ret = write_certificate( &crt, opt.output_file,
862                                    mbedtls_ctr_drbg_random, &ctr_drbg ) ) != 0 )
863     {
864         mbedtls_strerror( ret, buf, sizeof(buf) );
865         mbedtls_printf( " failed\n  !  write_certificate -0x%04x - %s\n\n",
866                         (unsigned int) -ret, buf );
867         goto exit;
868     }
869 
870     mbedtls_printf( " ok\n" );
871 
872     exit_code = MBEDTLS_EXIT_SUCCESS;
873 
874 exit:
875 #if defined(MBEDTLS_X509_CSR_PARSE_C)
876     mbedtls_x509_csr_free( &csr );
877 #endif /* MBEDTLS_X509_CSR_PARSE_C */
878     mbedtls_x509_crt_free( &issuer_crt );
879     mbedtls_x509write_crt_free( &crt );
880     mbedtls_pk_free( &loaded_subject_key );
881     mbedtls_pk_free( &loaded_issuer_key );
882     mbedtls_mpi_free( &serial );
883     mbedtls_ctr_drbg_free( &ctr_drbg );
884     mbedtls_entropy_free( &entropy );
885 
886     mbedtls_exit( exit_code );
887 }
888 #endif /* MBEDTLS_X509_CRT_WRITE_C && MBEDTLS_X509_CRT_PARSE_C &&
889           MBEDTLS_FS_IO && MBEDTLS_ENTROPY_C && MBEDTLS_CTR_DRBG_C &&
890           MBEDTLS_ERROR_C && MBEDTLS_PEM_WRITE_C */
891