xref: /freebsd/crypto/openssl/apps/x509.c (revision 3c5ba95ad12285ad37c182a4bfc1b240ec6d18a7)
1 /* apps/x509.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 
59 #include <assert.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
63 #ifdef OPENSSL_NO_STDIO
64 # define APPS_WIN16
65 #endif
66 #include "apps.h"
67 #include <openssl/bio.h>
68 #include <openssl/asn1.h>
69 #include <openssl/err.h>
70 #include <openssl/bn.h>
71 #include <openssl/evp.h>
72 #include <openssl/x509.h>
73 #include <openssl/x509v3.h>
74 #include <openssl/objects.h>
75 #include <openssl/pem.h>
76 #ifndef OPENSSL_NO_RSA
77 # include <openssl/rsa.h>
78 #endif
79 #ifndef OPENSSL_NO_DSA
80 # include <openssl/dsa.h>
81 #endif
82 
83 #undef PROG
84 #define PROG x509_main
85 
86 #undef POSTFIX
87 #define POSTFIX ".srl"
88 #define DEF_DAYS        30
89 
90 static const char *x509_usage[] = {
91     "usage: x509 args\n",
92     " -inform arg     - input format - default PEM (one of DER, NET or PEM)\n",
93     " -outform arg    - output format - default PEM (one of DER, NET or PEM)\n",
94     " -keyform arg    - private key format - default PEM\n",
95     " -CAform arg     - CA format - default PEM\n",
96     " -CAkeyform arg  - CA key format - default PEM\n",
97     " -in arg         - input file - default stdin\n",
98     " -out arg        - output file - default stdout\n",
99     " -passin arg     - private key password source\n",
100     " -serial         - print serial number value\n",
101     " -subject_hash   - print subject hash value\n",
102 #ifndef OPENSSL_NO_MD5
103     " -subject_hash_old   - print old-style (MD5) subject hash value\n",
104 #endif
105     " -issuer_hash    - print issuer hash value\n",
106 #ifndef OPENSSL_NO_MD5
107     " -issuer_hash_old    - print old-style (MD5) issuer hash value\n",
108 #endif
109     " -hash           - synonym for -subject_hash\n",
110     " -subject        - print subject DN\n",
111     " -issuer         - print issuer DN\n",
112     " -email          - print email address(es)\n",
113     " -startdate      - notBefore field\n",
114     " -enddate        - notAfter field\n",
115     " -purpose        - print out certificate purposes\n",
116     " -dates          - both Before and After dates\n",
117     " -modulus        - print the RSA key modulus\n",
118     " -pubkey         - output the public key\n",
119     " -fingerprint    - print the certificate fingerprint\n",
120     " -alias          - output certificate alias\n",
121     " -noout          - no certificate output\n",
122     " -ocspid         - print OCSP hash values for the subject name and public key\n",
123     " -ocsp_uri       - print OCSP Responder URL(s)\n",
124     " -trustout       - output a \"trusted\" certificate\n",
125     " -clrtrust       - clear all trusted purposes\n",
126     " -clrreject      - clear all rejected purposes\n",
127     " -addtrust arg   - trust certificate for a given purpose\n",
128     " -addreject arg  - reject certificate for a given purpose\n",
129     " -setalias arg   - set certificate alias\n",
130     " -days arg       - How long till expiry of a signed certificate - def 30 days\n",
131     " -checkend arg   - check whether the cert expires in the next arg seconds\n",
132     "                   exit 1 if so, 0 if not\n",
133     " -signkey arg    - self sign cert with arg\n",
134     " -x509toreq      - output a certification request object\n",
135     " -req            - input is a certificate request, sign and output.\n",
136     " -CA arg         - set the CA certificate, must be PEM format.\n",
137     " -CAkey arg      - set the CA key, must be PEM format\n",
138     "                   missing, it is assumed to be in the CA file.\n",
139     " -CAcreateserial - create serial number file if it does not exist\n",
140     " -CAserial arg   - serial file\n",
141     " -set_serial     - serial number to use\n",
142     " -text           - print the certificate in text form\n",
143     " -C              - print out C code forms\n",
144     " -md2/-md5/-sha1/-mdc2 - digest to use\n",
145     " -extfile        - configuration file with X509V3 extensions to add\n",
146     " -extensions     - section from config file with X509V3 extensions to add\n",
147     " -clrext         - delete extensions before signing and input certificate\n",
148     " -nameopt arg    - various certificate name options\n",
149 #ifndef OPENSSL_NO_ENGINE
150     " -engine e       - use engine e, possibly a hardware device.\n",
151 #endif
152     " -certopt arg    - various certificate text options\n",
153     " -checkhost host - check certificate matches \"host\"\n",
154     " -checkemail email - check certificate matches \"email\"\n",
155     " -checkip ipaddr - check certificate matches \"ipaddr\"\n",
156     NULL
157 };
158 
159 static int MS_CALLBACK callb(int ok, X509_STORE_CTX *ctx);
160 static int sign(X509 *x, EVP_PKEY *pkey, int days, int clrext,
161                 const EVP_MD *digest, CONF *conf, char *section);
162 static int x509_certify(X509_STORE *ctx, char *CAfile, const EVP_MD *digest,
163                         X509 *x, X509 *xca, EVP_PKEY *pkey,
164                         STACK_OF(OPENSSL_STRING) *sigopts, char *serial,
165                         int create, int days, int clrext, CONF *conf,
166                         char *section, ASN1_INTEGER *sno);
167 static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt);
168 static int reqfile = 0;
169 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
170 static int force_version = 2;
171 #endif
172 
173 int MAIN(int, char **);
174 
175 int MAIN(int argc, char **argv)
176 {
177     ENGINE *e = NULL;
178     int ret = 1;
179     X509_REQ *req = NULL;
180     X509 *x = NULL, *xca = NULL;
181     ASN1_OBJECT *objtmp;
182     STACK_OF(OPENSSL_STRING) *sigopts = NULL;
183     EVP_PKEY *Upkey = NULL, *CApkey = NULL, *fkey = NULL;
184     ASN1_INTEGER *sno = NULL;
185     int i, num, badops = 0, badsig = 0;
186     BIO *out = NULL;
187     BIO *STDout = NULL;
188     STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL;
189     int informat, outformat, keyformat, CAformat, CAkeyformat;
190     char *infile = NULL, *outfile = NULL, *keyfile = NULL, *CAfile = NULL;
191     char *CAkeyfile = NULL, *CAserial = NULL;
192     char *fkeyfile = NULL;
193     char *alias = NULL;
194     int text = 0, serial = 0, subject = 0, issuer = 0, startdate =
195         0, enddate = 0;
196     int next_serial = 0;
197     int subject_hash = 0, issuer_hash = 0, ocspid = 0;
198 #ifndef OPENSSL_NO_MD5
199     int subject_hash_old = 0, issuer_hash_old = 0;
200 #endif
201     int noout = 0, sign_flag = 0, CA_flag = 0, CA_createserial = 0, email = 0;
202     int ocsp_uri = 0;
203     int trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0, clrext = 0;
204     int C = 0;
205     int x509req = 0, days = DEF_DAYS, modulus = 0, pubkey = 0;
206     int pprint = 0;
207     const char **pp;
208     X509_STORE *ctx = NULL;
209     X509_REQ *rq = NULL;
210     int fingerprint = 0;
211     char buf[256];
212     const EVP_MD *md_alg, *digest = NULL;
213     CONF *extconf = NULL;
214     char *extsect = NULL, *extfile = NULL, *passin = NULL, *passargin = NULL;
215     int need_rand = 0;
216     int checkend = 0, checkoffset = 0;
217     unsigned long nmflag = 0, certflag = 0;
218     char *checkhost = NULL;
219     char *checkemail = NULL;
220     char *checkip = NULL;
221     char *engine = NULL;
222 
223     reqfile = 0;
224 
225     apps_startup();
226 
227     if (bio_err == NULL)
228         bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);
229 
230     if (!load_config(bio_err, NULL))
231         goto end;
232     STDout = BIO_new_fp(stdout, BIO_NOCLOSE);
233 #ifdef OPENSSL_SYS_VMS
234     {
235         BIO *tmpbio = BIO_new(BIO_f_linebuffer());
236         STDout = BIO_push(tmpbio, STDout);
237     }
238 #endif
239 
240     informat = FORMAT_PEM;
241     outformat = FORMAT_PEM;
242     keyformat = FORMAT_PEM;
243     CAformat = FORMAT_PEM;
244     CAkeyformat = FORMAT_PEM;
245 
246     ctx = X509_STORE_new();
247     if (ctx == NULL)
248         goto end;
249     X509_STORE_set_verify_cb(ctx, callb);
250 
251     argc--;
252     argv++;
253     num = 0;
254     while (argc >= 1) {
255         if (strcmp(*argv, "-inform") == 0) {
256             if (--argc < 1)
257                 goto bad;
258             informat = str2fmt(*(++argv));
259         } else if (strcmp(*argv, "-outform") == 0) {
260             if (--argc < 1)
261                 goto bad;
262             outformat = str2fmt(*(++argv));
263         } else if (strcmp(*argv, "-keyform") == 0) {
264             if (--argc < 1)
265                 goto bad;
266             keyformat = str2fmt(*(++argv));
267         } else if (strcmp(*argv, "-req") == 0) {
268             reqfile = 1;
269             need_rand = 1;
270         } else if (strcmp(*argv, "-CAform") == 0) {
271             if (--argc < 1)
272                 goto bad;
273             CAformat = str2fmt(*(++argv));
274         } else if (strcmp(*argv, "-CAkeyform") == 0) {
275             if (--argc < 1)
276                 goto bad;
277             CAkeyformat = str2fmt(*(++argv));
278         } else if (strcmp(*argv, "-sigopt") == 0) {
279             if (--argc < 1)
280                 goto bad;
281             if (!sigopts)
282                 sigopts = sk_OPENSSL_STRING_new_null();
283             if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
284                 goto bad;
285         }
286 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
287         else if (strcmp(*argv, "-force_version") == 0) {
288             if (--argc < 1)
289                 goto bad;
290             force_version = atoi(*(++argv)) - 1;
291         }
292 #endif
293         else if (strcmp(*argv, "-days") == 0) {
294             if (--argc < 1)
295                 goto bad;
296             days = atoi(*(++argv));
297             if (days == 0) {
298                 BIO_printf(bio_err, "bad number of days\n");
299                 goto bad;
300             }
301         } else if (strcmp(*argv, "-passin") == 0) {
302             if (--argc < 1)
303                 goto bad;
304             passargin = *(++argv);
305         } else if (strcmp(*argv, "-extfile") == 0) {
306             if (--argc < 1)
307                 goto bad;
308             extfile = *(++argv);
309         } else if (strcmp(*argv, "-extensions") == 0) {
310             if (--argc < 1)
311                 goto bad;
312             extsect = *(++argv);
313         } else if (strcmp(*argv, "-in") == 0) {
314             if (--argc < 1)
315                 goto bad;
316             infile = *(++argv);
317         } else if (strcmp(*argv, "-out") == 0) {
318             if (--argc < 1)
319                 goto bad;
320             outfile = *(++argv);
321         } else if (strcmp(*argv, "-signkey") == 0) {
322             if (--argc < 1)
323                 goto bad;
324             keyfile = *(++argv);
325             sign_flag = ++num;
326             need_rand = 1;
327         } else if (strcmp(*argv, "-CA") == 0) {
328             if (--argc < 1)
329                 goto bad;
330             CAfile = *(++argv);
331             CA_flag = ++num;
332             need_rand = 1;
333         } else if (strcmp(*argv, "-CAkey") == 0) {
334             if (--argc < 1)
335                 goto bad;
336             CAkeyfile = *(++argv);
337         } else if (strcmp(*argv, "-CAserial") == 0) {
338             if (--argc < 1)
339                 goto bad;
340             CAserial = *(++argv);
341         } else if (strcmp(*argv, "-set_serial") == 0) {
342             if (--argc < 1)
343                 goto bad;
344             if (!(sno = s2i_ASN1_INTEGER(NULL, *(++argv))))
345                 goto bad;
346         } else if (strcmp(*argv, "-force_pubkey") == 0) {
347             if (--argc < 1)
348                 goto bad;
349             fkeyfile = *(++argv);
350         } else if (strcmp(*argv, "-addtrust") == 0) {
351             if (--argc < 1)
352                 goto bad;
353             if (!(objtmp = OBJ_txt2obj(*(++argv), 0))) {
354                 BIO_printf(bio_err, "Invalid trust object value %s\n", *argv);
355                 goto bad;
356             }
357             if (!trust)
358                 trust = sk_ASN1_OBJECT_new_null();
359             sk_ASN1_OBJECT_push(trust, objtmp);
360             trustout = 1;
361         } else if (strcmp(*argv, "-addreject") == 0) {
362             if (--argc < 1)
363                 goto bad;
364             if (!(objtmp = OBJ_txt2obj(*(++argv), 0))) {
365                 BIO_printf(bio_err,
366                            "Invalid reject object value %s\n", *argv);
367                 goto bad;
368             }
369             if (!reject)
370                 reject = sk_ASN1_OBJECT_new_null();
371             sk_ASN1_OBJECT_push(reject, objtmp);
372             trustout = 1;
373         } else if (strcmp(*argv, "-setalias") == 0) {
374             if (--argc < 1)
375                 goto bad;
376             alias = *(++argv);
377             trustout = 1;
378         } else if (strcmp(*argv, "-certopt") == 0) {
379             if (--argc < 1)
380                 goto bad;
381             if (!set_cert_ex(&certflag, *(++argv)))
382                 goto bad;
383         } else if (strcmp(*argv, "-nameopt") == 0) {
384             if (--argc < 1)
385                 goto bad;
386             if (!set_name_ex(&nmflag, *(++argv)))
387                 goto bad;
388         }
389 #ifndef OPENSSL_NO_ENGINE
390         else if (strcmp(*argv, "-engine") == 0) {
391             if (--argc < 1)
392                 goto bad;
393             engine = *(++argv);
394         }
395 #endif
396         else if (strcmp(*argv, "-C") == 0)
397             C = ++num;
398         else if (strcmp(*argv, "-email") == 0)
399             email = ++num;
400         else if (strcmp(*argv, "-ocsp_uri") == 0)
401             ocsp_uri = ++num;
402         else if (strcmp(*argv, "-serial") == 0)
403             serial = ++num;
404         else if (strcmp(*argv, "-next_serial") == 0)
405             next_serial = ++num;
406         else if (strcmp(*argv, "-modulus") == 0)
407             modulus = ++num;
408         else if (strcmp(*argv, "-pubkey") == 0)
409             pubkey = ++num;
410         else if (strcmp(*argv, "-x509toreq") == 0)
411             x509req = ++num;
412         else if (strcmp(*argv, "-text") == 0)
413             text = ++num;
414         else if (strcmp(*argv, "-hash") == 0
415                  || strcmp(*argv, "-subject_hash") == 0)
416             subject_hash = ++num;
417 #ifndef OPENSSL_NO_MD5
418         else if (strcmp(*argv, "-subject_hash_old") == 0)
419             subject_hash_old = ++num;
420 #endif
421         else if (strcmp(*argv, "-issuer_hash") == 0)
422             issuer_hash = ++num;
423 #ifndef OPENSSL_NO_MD5
424         else if (strcmp(*argv, "-issuer_hash_old") == 0)
425             issuer_hash_old = ++num;
426 #endif
427         else if (strcmp(*argv, "-subject") == 0)
428             subject = ++num;
429         else if (strcmp(*argv, "-issuer") == 0)
430             issuer = ++num;
431         else if (strcmp(*argv, "-fingerprint") == 0)
432             fingerprint = ++num;
433         else if (strcmp(*argv, "-dates") == 0) {
434             startdate = ++num;
435             enddate = ++num;
436         } else if (strcmp(*argv, "-purpose") == 0)
437             pprint = ++num;
438         else if (strcmp(*argv, "-startdate") == 0)
439             startdate = ++num;
440         else if (strcmp(*argv, "-enddate") == 0)
441             enddate = ++num;
442         else if (strcmp(*argv, "-checkend") == 0) {
443             if (--argc < 1)
444                 goto bad;
445             checkoffset = atoi(*(++argv));
446             checkend = 1;
447         } else if (strcmp(*argv, "-checkhost") == 0) {
448             if (--argc < 1)
449                 goto bad;
450             checkhost = *(++argv);
451         } else if (strcmp(*argv, "-checkemail") == 0) {
452             if (--argc < 1)
453                 goto bad;
454             checkemail = *(++argv);
455         } else if (strcmp(*argv, "-checkip") == 0) {
456             if (--argc < 1)
457                 goto bad;
458             checkip = *(++argv);
459         } else if (strcmp(*argv, "-noout") == 0)
460             noout = ++num;
461         else if (strcmp(*argv, "-trustout") == 0)
462             trustout = 1;
463         else if (strcmp(*argv, "-clrtrust") == 0)
464             clrtrust = ++num;
465         else if (strcmp(*argv, "-clrreject") == 0)
466             clrreject = ++num;
467         else if (strcmp(*argv, "-alias") == 0)
468             aliasout = ++num;
469         else if (strcmp(*argv, "-CAcreateserial") == 0)
470             CA_createserial = ++num;
471         else if (strcmp(*argv, "-clrext") == 0)
472             clrext = 1;
473 #if 1                           /* stay backwards-compatible with 0.9.5; this
474                                  * should go away soon */
475         else if (strcmp(*argv, "-crlext") == 0) {
476             BIO_printf(bio_err, "use -clrext instead of -crlext\n");
477             clrext = 1;
478         }
479 #endif
480         else if (strcmp(*argv, "-ocspid") == 0)
481             ocspid = ++num;
482         else if (strcmp(*argv, "-badsig") == 0)
483             badsig = 1;
484         else if ((md_alg = EVP_get_digestbyname(*argv + 1))) {
485             /* ok */
486             digest = md_alg;
487         } else {
488             BIO_printf(bio_err, "unknown option %s\n", *argv);
489             badops = 1;
490             break;
491         }
492         argc--;
493         argv++;
494     }
495 
496     if (badops) {
497  bad:
498         for (pp = x509_usage; (*pp != NULL); pp++)
499             BIO_printf(bio_err, "%s", *pp);
500         goto end;
501     }
502     e = setup_engine(bio_err, engine, 0);
503 
504     if (need_rand)
505         app_RAND_load_file(NULL, bio_err, 0);
506 
507     ERR_load_crypto_strings();
508 
509     if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) {
510         BIO_printf(bio_err, "Error getting password\n");
511         goto end;
512     }
513 
514     if (!X509_STORE_set_default_paths(ctx)) {
515         ERR_print_errors(bio_err);
516         goto end;
517     }
518 
519     if (fkeyfile) {
520         fkey = load_pubkey(bio_err, fkeyfile, keyformat, 0,
521                            NULL, e, "Forced key");
522         if (fkey == NULL)
523             goto end;
524     }
525 
526     if ((CAkeyfile == NULL) && (CA_flag) && (CAformat == FORMAT_PEM)) {
527         CAkeyfile = CAfile;
528     } else if ((CA_flag) && (CAkeyfile == NULL)) {
529         BIO_printf(bio_err,
530                    "need to specify a CAkey if using the CA command\n");
531         goto end;
532     }
533 
534     if (extfile) {
535         long errorline = -1;
536         X509V3_CTX ctx2;
537         extconf = NCONF_new(NULL);
538         if (!NCONF_load(extconf, extfile, &errorline)) {
539             if (errorline <= 0)
540                 BIO_printf(bio_err,
541                            "error loading the config file '%s'\n", extfile);
542             else
543                 BIO_printf(bio_err,
544                            "error on line %ld of config file '%s'\n",
545                            errorline, extfile);
546             goto end;
547         }
548         if (!extsect) {
549             extsect = NCONF_get_string(extconf, "default", "extensions");
550             if (!extsect) {
551                 ERR_clear_error();
552                 extsect = "default";
553             }
554         }
555         X509V3_set_ctx_test(&ctx2);
556         X509V3_set_nconf(&ctx2, extconf);
557         if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL)) {
558             BIO_printf(bio_err,
559                        "Error Loading extension section %s\n", extsect);
560             ERR_print_errors(bio_err);
561             goto end;
562         }
563     }
564 
565     if (reqfile) {
566         EVP_PKEY *pkey;
567         BIO *in;
568 
569         if (!sign_flag && !CA_flag) {
570             BIO_printf(bio_err, "We need a private key to sign with\n");
571             goto end;
572         }
573         in = BIO_new(BIO_s_file());
574         if (in == NULL) {
575             ERR_print_errors(bio_err);
576             goto end;
577         }
578 
579         if (infile == NULL)
580             BIO_set_fp(in, stdin, BIO_NOCLOSE | BIO_FP_TEXT);
581         else {
582             if (BIO_read_filename(in, infile) <= 0) {
583                 perror(infile);
584                 BIO_free(in);
585                 goto end;
586             }
587         }
588         req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL);
589         BIO_free(in);
590 
591         if (req == NULL) {
592             ERR_print_errors(bio_err);
593             goto end;
594         }
595 
596         if ((req->req_info == NULL) ||
597             (req->req_info->pubkey == NULL) ||
598             (req->req_info->pubkey->public_key == NULL) ||
599             (req->req_info->pubkey->public_key->data == NULL)) {
600             BIO_printf(bio_err,
601                        "The certificate request appears to corrupted\n");
602             BIO_printf(bio_err, "It does not contain a public key\n");
603             goto end;
604         }
605         if ((pkey = X509_REQ_get_pubkey(req)) == NULL) {
606             BIO_printf(bio_err, "error unpacking public key\n");
607             goto end;
608         }
609         i = X509_REQ_verify(req, pkey);
610         EVP_PKEY_free(pkey);
611         if (i < 0) {
612             BIO_printf(bio_err, "Signature verification error\n");
613             ERR_print_errors(bio_err);
614             goto end;
615         }
616         if (i == 0) {
617             BIO_printf(bio_err,
618                        "Signature did not match the certificate request\n");
619             goto end;
620         } else
621             BIO_printf(bio_err, "Signature ok\n");
622 
623         print_name(bio_err, "subject=", X509_REQ_get_subject_name(req),
624                    nmflag);
625 
626         if ((x = X509_new()) == NULL)
627             goto end;
628 
629         if (sno == NULL) {
630             sno = ASN1_INTEGER_new();
631             if (!sno || !rand_serial(NULL, sno))
632                 goto end;
633             if (!X509_set_serialNumber(x, sno))
634                 goto end;
635             ASN1_INTEGER_free(sno);
636             sno = NULL;
637         } else if (!X509_set_serialNumber(x, sno))
638             goto end;
639 
640         if (!X509_set_issuer_name(x, req->req_info->subject))
641             goto end;
642         if (!X509_set_subject_name(x, req->req_info->subject))
643             goto end;
644 
645         X509_gmtime_adj(X509_get_notBefore(x), 0);
646         X509_time_adj_ex(X509_get_notAfter(x), days, 0, NULL);
647         if (fkey)
648             X509_set_pubkey(x, fkey);
649         else {
650             pkey = X509_REQ_get_pubkey(req);
651             X509_set_pubkey(x, pkey);
652             EVP_PKEY_free(pkey);
653         }
654     } else
655         x = load_cert(bio_err, infile, informat, NULL, e, "Certificate");
656 
657     if (x == NULL)
658         goto end;
659     if (CA_flag) {
660         xca = load_cert(bio_err, CAfile, CAformat, NULL, e, "CA Certificate");
661         if (xca == NULL)
662             goto end;
663     }
664 
665     if (!noout || text || next_serial) {
666         OBJ_create("2.99999.3", "SET.ex3", "SET x509v3 extension 3");
667 
668         out = BIO_new(BIO_s_file());
669         if (out == NULL) {
670             ERR_print_errors(bio_err);
671             goto end;
672         }
673         if (outfile == NULL) {
674             BIO_set_fp(out, stdout, BIO_NOCLOSE);
675 #ifdef OPENSSL_SYS_VMS
676             {
677                 BIO *tmpbio = BIO_new(BIO_f_linebuffer());
678                 out = BIO_push(tmpbio, out);
679             }
680 #endif
681         } else {
682             if (BIO_write_filename(out, outfile) <= 0) {
683                 perror(outfile);
684                 goto end;
685             }
686         }
687     }
688 
689     if (alias)
690         X509_alias_set1(x, (unsigned char *)alias, -1);
691 
692     if (clrtrust)
693         X509_trust_clear(x);
694     if (clrreject)
695         X509_reject_clear(x);
696 
697     if (trust) {
698         for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) {
699             objtmp = sk_ASN1_OBJECT_value(trust, i);
700             X509_add1_trust_object(x, objtmp);
701         }
702     }
703 
704     if (reject) {
705         for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) {
706             objtmp = sk_ASN1_OBJECT_value(reject, i);
707             X509_add1_reject_object(x, objtmp);
708         }
709     }
710 
711     if (num) {
712         for (i = 1; i <= num; i++) {
713             if (issuer == i) {
714                 print_name(STDout, "issuer= ",
715                            X509_get_issuer_name(x), nmflag);
716             } else if (subject == i) {
717                 print_name(STDout, "subject= ",
718                            X509_get_subject_name(x), nmflag);
719             } else if (serial == i) {
720                 BIO_printf(STDout, "serial=");
721                 i2a_ASN1_INTEGER(STDout, X509_get_serialNumber(x));
722                 BIO_printf(STDout, "\n");
723             } else if (next_serial == i) {
724                 BIGNUM *bnser;
725                 ASN1_INTEGER *ser;
726                 ser = X509_get_serialNumber(x);
727                 bnser = ASN1_INTEGER_to_BN(ser, NULL);
728                 if (!bnser)
729                     goto end;
730                 if (!BN_add_word(bnser, 1))
731                     goto end;
732                 ser = BN_to_ASN1_INTEGER(bnser, NULL);
733                 if (!ser)
734                     goto end;
735                 BN_free(bnser);
736                 i2a_ASN1_INTEGER(out, ser);
737                 ASN1_INTEGER_free(ser);
738                 BIO_puts(out, "\n");
739             } else if ((email == i) || (ocsp_uri == i)) {
740                 int j;
741                 STACK_OF(OPENSSL_STRING) *emlst;
742                 if (email == i)
743                     emlst = X509_get1_email(x);
744                 else
745                     emlst = X509_get1_ocsp(x);
746                 for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++)
747                     BIO_printf(STDout, "%s\n",
748                                sk_OPENSSL_STRING_value(emlst, j));
749                 X509_email_free(emlst);
750             } else if (aliasout == i) {
751                 unsigned char *alstr;
752                 alstr = X509_alias_get0(x, NULL);
753                 if (alstr)
754                     BIO_printf(STDout, "%s\n", alstr);
755                 else
756                     BIO_puts(STDout, "<No Alias>\n");
757             } else if (subject_hash == i) {
758                 BIO_printf(STDout, "%08lx\n", X509_subject_name_hash(x));
759             }
760 #ifndef OPENSSL_NO_MD5
761             else if (subject_hash_old == i) {
762                 BIO_printf(STDout, "%08lx\n", X509_subject_name_hash_old(x));
763             }
764 #endif
765             else if (issuer_hash == i) {
766                 BIO_printf(STDout, "%08lx\n", X509_issuer_name_hash(x));
767             }
768 #ifndef OPENSSL_NO_MD5
769             else if (issuer_hash_old == i) {
770                 BIO_printf(STDout, "%08lx\n", X509_issuer_name_hash_old(x));
771             }
772 #endif
773             else if (pprint == i) {
774                 X509_PURPOSE *ptmp;
775                 int j;
776                 BIO_printf(STDout, "Certificate purposes:\n");
777                 for (j = 0; j < X509_PURPOSE_get_count(); j++) {
778                     ptmp = X509_PURPOSE_get0(j);
779                     purpose_print(STDout, x, ptmp);
780                 }
781             } else if (modulus == i) {
782                 EVP_PKEY *pkey;
783 
784                 pkey = X509_get_pubkey(x);
785                 if (pkey == NULL) {
786                     BIO_printf(bio_err, "Modulus=unavailable\n");
787                     ERR_print_errors(bio_err);
788                     goto end;
789                 }
790                 BIO_printf(STDout, "Modulus=");
791 #ifndef OPENSSL_NO_RSA
792                 if (pkey->type == EVP_PKEY_RSA)
793                     BN_print(STDout, pkey->pkey.rsa->n);
794                 else
795 #endif
796 #ifndef OPENSSL_NO_DSA
797                 if (pkey->type == EVP_PKEY_DSA)
798                     BN_print(STDout, pkey->pkey.dsa->pub_key);
799                 else
800 #endif
801                     BIO_printf(STDout, "Wrong Algorithm type");
802                 BIO_printf(STDout, "\n");
803                 EVP_PKEY_free(pkey);
804             } else if (pubkey == i) {
805                 EVP_PKEY *pkey;
806 
807                 pkey = X509_get_pubkey(x);
808                 if (pkey == NULL) {
809                     BIO_printf(bio_err, "Error getting public key\n");
810                     ERR_print_errors(bio_err);
811                     goto end;
812                 }
813                 PEM_write_bio_PUBKEY(STDout, pkey);
814                 EVP_PKEY_free(pkey);
815             } else if (C == i) {
816                 unsigned char *d;
817                 char *m;
818                 int y, z;
819 
820                 X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof(buf));
821                 BIO_printf(STDout, "/* subject:%s */\n", buf);
822                 m = X509_NAME_oneline(X509_get_issuer_name(x), buf,
823                                       sizeof(buf));
824                 BIO_printf(STDout, "/* issuer :%s */\n", buf);
825 
826                 z = i2d_X509(x, NULL);
827                 m = OPENSSL_malloc(z);
828                 if (!m) {
829                     BIO_printf(bio_err, "Out of memory\n");
830                     ERR_print_errors(bio_err);
831                     goto end;
832                 }
833 
834                 d = (unsigned char *)m;
835                 z = i2d_X509_NAME(X509_get_subject_name(x), &d);
836                 BIO_printf(STDout, "unsigned char XXX_subject_name[%d]={\n",
837                            z);
838                 d = (unsigned char *)m;
839                 for (y = 0; y < z; y++) {
840                     BIO_printf(STDout, "0x%02X,", d[y]);
841                     if ((y & 0x0f) == 0x0f)
842                         BIO_printf(STDout, "\n");
843                 }
844                 if (y % 16 != 0)
845                     BIO_printf(STDout, "\n");
846                 BIO_printf(STDout, "};\n");
847 
848                 z = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &d);
849                 BIO_printf(STDout, "unsigned char XXX_public_key[%d]={\n", z);
850                 d = (unsigned char *)m;
851                 for (y = 0; y < z; y++) {
852                     BIO_printf(STDout, "0x%02X,", d[y]);
853                     if ((y & 0x0f) == 0x0f)
854                         BIO_printf(STDout, "\n");
855                 }
856                 if (y % 16 != 0)
857                     BIO_printf(STDout, "\n");
858                 BIO_printf(STDout, "};\n");
859 
860                 z = i2d_X509(x, &d);
861                 BIO_printf(STDout, "unsigned char XXX_certificate[%d]={\n",
862                            z);
863                 d = (unsigned char *)m;
864                 for (y = 0; y < z; y++) {
865                     BIO_printf(STDout, "0x%02X,", d[y]);
866                     if ((y & 0x0f) == 0x0f)
867                         BIO_printf(STDout, "\n");
868                 }
869                 if (y % 16 != 0)
870                     BIO_printf(STDout, "\n");
871                 BIO_printf(STDout, "};\n");
872 
873                 OPENSSL_free(m);
874             } else if (text == i) {
875                 X509_print_ex(STDout, x, nmflag, certflag);
876             } else if (startdate == i) {
877                 BIO_puts(STDout, "notBefore=");
878                 ASN1_TIME_print(STDout, X509_get_notBefore(x));
879                 BIO_puts(STDout, "\n");
880             } else if (enddate == i) {
881                 BIO_puts(STDout, "notAfter=");
882                 ASN1_TIME_print(STDout, X509_get_notAfter(x));
883                 BIO_puts(STDout, "\n");
884             } else if (fingerprint == i) {
885                 int j;
886                 unsigned int n;
887                 unsigned char md[EVP_MAX_MD_SIZE];
888                 const EVP_MD *fdig = digest;
889 
890                 if (!fdig)
891                     fdig = EVP_sha1();
892 
893                 if (!X509_digest(x, fdig, md, &n)) {
894                     BIO_printf(bio_err, "out of memory\n");
895                     goto end;
896                 }
897                 BIO_printf(STDout, "%s Fingerprint=",
898                            OBJ_nid2sn(EVP_MD_type(fdig)));
899                 for (j = 0; j < (int)n; j++) {
900                     BIO_printf(STDout, "%02X%c", md[j], (j + 1 == (int)n)
901                                ? '\n' : ':');
902                 }
903             }
904 
905             /* should be in the library */
906             else if ((sign_flag == i) && (x509req == 0)) {
907                 BIO_printf(bio_err, "Getting Private key\n");
908                 if (Upkey == NULL) {
909                     Upkey = load_key(bio_err,
910                                      keyfile, keyformat, 0,
911                                      passin, e, "Private key");
912                     if (Upkey == NULL)
913                         goto end;
914                 }
915 
916                 assert(need_rand);
917                 if (!sign(x, Upkey, days, clrext, digest, extconf, extsect))
918                     goto end;
919             } else if (CA_flag == i) {
920                 BIO_printf(bio_err, "Getting CA Private Key\n");
921                 if (CAkeyfile != NULL) {
922                     CApkey = load_key(bio_err,
923                                       CAkeyfile, CAkeyformat,
924                                       0, passin, e, "CA Private Key");
925                     if (CApkey == NULL)
926                         goto end;
927                 }
928 
929                 assert(need_rand);
930                 if (!x509_certify(ctx, CAfile, digest, x, xca,
931                                   CApkey, sigopts,
932                                   CAserial, CA_createserial, days, clrext,
933                                   extconf, extsect, sno))
934                     goto end;
935             } else if (x509req == i) {
936                 EVP_PKEY *pk;
937 
938                 BIO_printf(bio_err, "Getting request Private Key\n");
939                 if (keyfile == NULL) {
940                     BIO_printf(bio_err, "no request key file specified\n");
941                     goto end;
942                 } else {
943                     pk = load_key(bio_err,
944                                   keyfile, keyformat, 0,
945                                   passin, e, "request key");
946                     if (pk == NULL)
947                         goto end;
948                 }
949 
950                 BIO_printf(bio_err, "Generating certificate request\n");
951 
952                 rq = X509_to_X509_REQ(x, pk, digest);
953                 EVP_PKEY_free(pk);
954                 if (rq == NULL) {
955                     ERR_print_errors(bio_err);
956                     goto end;
957                 }
958                 if (!noout) {
959                     X509_REQ_print(out, rq);
960                     PEM_write_bio_X509_REQ(out, rq);
961                 }
962                 noout = 1;
963             } else if (ocspid == i) {
964                 X509_ocspid_print(out, x);
965             }
966         }
967     }
968 
969     if (checkend) {
970         time_t tcheck = time(NULL) + checkoffset;
971 
972         if (X509_cmp_time(X509_get_notAfter(x), &tcheck) < 0) {
973             BIO_printf(out, "Certificate will expire\n");
974             ret = 1;
975         } else {
976             BIO_printf(out, "Certificate will not expire\n");
977             ret = 0;
978         }
979         goto end;
980     }
981 
982     print_cert_checks(STDout, x, checkhost, checkemail, checkip);
983 
984     if (noout) {
985         ret = 0;
986         goto end;
987     }
988 
989     if (badsig)
990         x->signature->data[x->signature->length - 1] ^= 0x1;
991 
992     if (outformat == FORMAT_ASN1)
993         i = i2d_X509_bio(out, x);
994     else if (outformat == FORMAT_PEM) {
995         if (trustout)
996             i = PEM_write_bio_X509_AUX(out, x);
997         else
998             i = PEM_write_bio_X509(out, x);
999     } else if (outformat == FORMAT_NETSCAPE) {
1000         NETSCAPE_X509 nx;
1001         ASN1_OCTET_STRING hdr;
1002 
1003         hdr.data = (unsigned char *)NETSCAPE_CERT_HDR;
1004         hdr.length = strlen(NETSCAPE_CERT_HDR);
1005         nx.header = &hdr;
1006         nx.cert = x;
1007 
1008         i = ASN1_item_i2d_bio(ASN1_ITEM_rptr(NETSCAPE_X509), out, &nx);
1009     } else {
1010         BIO_printf(bio_err, "bad output format specified for outfile\n");
1011         goto end;
1012     }
1013     if (!i) {
1014         BIO_printf(bio_err, "unable to write certificate\n");
1015         ERR_print_errors(bio_err);
1016         goto end;
1017     }
1018     ret = 0;
1019  end:
1020     if (need_rand)
1021         app_RAND_write_file(NULL, bio_err);
1022     OBJ_cleanup();
1023     NCONF_free(extconf);
1024     BIO_free_all(out);
1025     BIO_free_all(STDout);
1026     X509_STORE_free(ctx);
1027     X509_REQ_free(req);
1028     X509_free(x);
1029     X509_free(xca);
1030     EVP_PKEY_free(Upkey);
1031     EVP_PKEY_free(CApkey);
1032     EVP_PKEY_free(fkey);
1033     if (sigopts)
1034         sk_OPENSSL_STRING_free(sigopts);
1035     X509_REQ_free(rq);
1036     ASN1_INTEGER_free(sno);
1037     sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free);
1038     sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free);
1039     release_engine(e);
1040     if (passin)
1041         OPENSSL_free(passin);
1042     apps_shutdown();
1043     OPENSSL_EXIT(ret);
1044 }
1045 
1046 static ASN1_INTEGER *x509_load_serial(char *CAfile, char *serialfile,
1047                                       int create)
1048 {
1049     char *buf = NULL, *p;
1050     ASN1_INTEGER *bs = NULL;
1051     BIGNUM *serial = NULL;
1052     size_t len;
1053 
1054     len = ((serialfile == NULL)
1055            ? (strlen(CAfile) + strlen(POSTFIX) + 1)
1056            : (strlen(serialfile))) + 1;
1057     buf = OPENSSL_malloc(len);
1058     if (buf == NULL) {
1059         BIO_printf(bio_err, "out of mem\n");
1060         goto end;
1061     }
1062     if (serialfile == NULL) {
1063         BUF_strlcpy(buf, CAfile, len);
1064         for (p = buf; *p; p++)
1065             if (*p == '.') {
1066                 *p = '\0';
1067                 break;
1068             }
1069         BUF_strlcat(buf, POSTFIX, len);
1070     } else
1071         BUF_strlcpy(buf, serialfile, len);
1072 
1073     serial = load_serial(buf, create, NULL);
1074     if (serial == NULL)
1075         goto end;
1076 
1077     if (!BN_add_word(serial, 1)) {
1078         BIO_printf(bio_err, "add_word failure\n");
1079         goto end;
1080     }
1081 
1082     if (!save_serial(buf, NULL, serial, &bs))
1083         goto end;
1084 
1085  end:
1086     if (buf)
1087         OPENSSL_free(buf);
1088     BN_free(serial);
1089     return bs;
1090 }
1091 
1092 static int x509_certify(X509_STORE *ctx, char *CAfile, const EVP_MD *digest,
1093                         X509 *x, X509 *xca, EVP_PKEY *pkey,
1094                         STACK_OF(OPENSSL_STRING) *sigopts,
1095                         char *serialfile, int create,
1096                         int days, int clrext, CONF *conf, char *section,
1097                         ASN1_INTEGER *sno)
1098 {
1099     int ret = 0;
1100     ASN1_INTEGER *bs = NULL;
1101     X509_STORE_CTX xsc;
1102     EVP_PKEY *upkey;
1103 
1104     upkey = X509_get_pubkey(xca);
1105     if (upkey == NULL)  {
1106         BIO_printf(bio_err, "Error obtaining CA X509 public key\n");
1107         goto end;
1108     }
1109     EVP_PKEY_copy_parameters(upkey, pkey);
1110     EVP_PKEY_free(upkey);
1111 
1112     if (!X509_STORE_CTX_init(&xsc, ctx, x, NULL)) {
1113         BIO_printf(bio_err, "Error initialising X509 store\n");
1114         goto end;
1115     }
1116     if (sno)
1117         bs = sno;
1118     else if (!(bs = x509_load_serial(CAfile, serialfile, create)))
1119         goto end;
1120 
1121 /*      if (!X509_STORE_add_cert(ctx,x)) goto end;*/
1122 
1123     /*
1124      * NOTE: this certificate can/should be self signed, unless it was a
1125      * certificate request in which case it is not.
1126      */
1127     X509_STORE_CTX_set_cert(&xsc, x);
1128     X509_STORE_CTX_set_flags(&xsc, X509_V_FLAG_CHECK_SS_SIGNATURE);
1129     if (!reqfile && X509_verify_cert(&xsc) <= 0)
1130         goto end;
1131 
1132     if (!X509_check_private_key(xca, pkey)) {
1133         BIO_printf(bio_err,
1134                    "CA certificate and CA private key do not match\n");
1135         goto end;
1136     }
1137 
1138     if (!X509_set_issuer_name(x, X509_get_subject_name(xca)))
1139         goto end;
1140     if (!X509_set_serialNumber(x, bs))
1141         goto end;
1142 
1143     if (X509_gmtime_adj(X509_get_notBefore(x), 0L) == NULL)
1144         goto end;
1145 
1146     /* hardwired expired */
1147     if (X509_time_adj_ex(X509_get_notAfter(x), days, 0, NULL) == NULL)
1148         goto end;
1149 
1150     if (clrext) {
1151         while (X509_get_ext_count(x) > 0)
1152             X509_delete_ext(x, 0);
1153     }
1154 
1155     if (conf) {
1156         X509V3_CTX ctx2;
1157 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
1158         X509_set_version(x, force_version);
1159 #else
1160         X509_set_version(x, 2); /* version 3 certificate */
1161 #endif
1162         X509V3_set_ctx(&ctx2, xca, x, NULL, NULL, 0);
1163         X509V3_set_nconf(&ctx2, conf);
1164         if (!X509V3_EXT_add_nconf(conf, &ctx2, section, x))
1165             goto end;
1166     }
1167 
1168     if (!do_X509_sign(bio_err, x, pkey, digest, sigopts))
1169         goto end;
1170     ret = 1;
1171  end:
1172     X509_STORE_CTX_cleanup(&xsc);
1173     if (!ret)
1174         ERR_print_errors(bio_err);
1175     if (!sno)
1176         ASN1_INTEGER_free(bs);
1177     return ret;
1178 }
1179 
1180 static int MS_CALLBACK callb(int ok, X509_STORE_CTX *ctx)
1181 {
1182     int err;
1183     X509 *err_cert;
1184 
1185     /*
1186      * it is ok to use a self signed certificate This case will catch both
1187      * the initial ok == 0 and the final ok == 1 calls to this function
1188      */
1189     err = X509_STORE_CTX_get_error(ctx);
1190     if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT)
1191         return 1;
1192 
1193     /*
1194      * BAD we should have gotten an error.  Normally if everything worked
1195      * X509_STORE_CTX_get_error(ctx) will still be set to
1196      * DEPTH_ZERO_SELF_....
1197      */
1198     if (ok) {
1199         BIO_printf(bio_err,
1200                    "error with certificate to be certified - should be self signed\n");
1201         return 0;
1202     } else {
1203         err_cert = X509_STORE_CTX_get_current_cert(ctx);
1204         print_name(bio_err, NULL, X509_get_subject_name(err_cert), 0);
1205         BIO_printf(bio_err,
1206                    "error with certificate - error %d at depth %d\n%s\n", err,
1207                    X509_STORE_CTX_get_error_depth(ctx),
1208                    X509_verify_cert_error_string(err));
1209         return 1;
1210     }
1211 }
1212 
1213 /* self sign */
1214 static int sign(X509 *x, EVP_PKEY *pkey, int days, int clrext,
1215                 const EVP_MD *digest, CONF *conf, char *section)
1216 {
1217 
1218     EVP_PKEY *pktmp;
1219 
1220     pktmp = X509_get_pubkey(x);
1221     if (pktmp == NULL)
1222         goto err;
1223     EVP_PKEY_copy_parameters(pktmp, pkey);
1224     EVP_PKEY_save_parameters(pktmp, 1);
1225     EVP_PKEY_free(pktmp);
1226 
1227     if (!X509_set_issuer_name(x, X509_get_subject_name(x)))
1228         goto err;
1229     if (X509_gmtime_adj(X509_get_notBefore(x), 0) == NULL)
1230         goto err;
1231 
1232     if (X509_time_adj_ex(X509_get_notAfter(x), days, 0, NULL) == NULL)
1233         goto err;
1234 
1235     if (!X509_set_pubkey(x, pkey))
1236         goto err;
1237     if (clrext) {
1238         while (X509_get_ext_count(x) > 0)
1239             X509_delete_ext(x, 0);
1240     }
1241     if (conf) {
1242         X509V3_CTX ctx;
1243 #ifdef OPENSSL_SSL_DEBUG_BROKEN_PROTOCOL
1244         X509_set_version(x, force_version);
1245 #else
1246         X509_set_version(x, 2); /* version 3 certificate */
1247 #endif
1248         X509V3_set_ctx(&ctx, x, x, NULL, NULL, 0);
1249         X509V3_set_nconf(&ctx, conf);
1250         if (!X509V3_EXT_add_nconf(conf, &ctx, section, x))
1251             goto err;
1252     }
1253     if (!X509_sign(x, pkey, digest))
1254         goto err;
1255     return 1;
1256  err:
1257     ERR_print_errors(bio_err);
1258     return 0;
1259 }
1260 
1261 static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt)
1262 {
1263     int id, i, idret;
1264     char *pname;
1265     id = X509_PURPOSE_get_id(pt);
1266     pname = X509_PURPOSE_get0_name(pt);
1267     for (i = 0; i < 2; i++) {
1268         idret = X509_check_purpose(cert, id, i);
1269         BIO_printf(bio, "%s%s : ", pname, i ? " CA" : "");
1270         if (idret == 1)
1271             BIO_printf(bio, "Yes\n");
1272         else if (idret == 0)
1273             BIO_printf(bio, "No\n");
1274         else
1275             BIO_printf(bio, "Yes (WARNING code=%d)\n", idret);
1276     }
1277     return 1;
1278 }
1279