2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
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.
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).
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.
23 * Redistribution and use in source and binary forms, with or without
24 * modification, are permitted provided that the following conditions
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)"
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
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.]
64 #include <openssl/bio.h>
65 #include <openssl/evp.h>
66 #include <openssl/conf.h>
67 #include <openssl/err.h>
68 #include <openssl/asn1.h>
69 #include <openssl/x509.h>
70 #include <openssl/x509v3.h>
71 #include <openssl/objects.h>
72 #include <openssl/pem.h>
73 #include <openssl/bn.h>
74 #ifndef OPENSSL_NO_RSA
75 #include <openssl/rsa.h>
77 #ifndef OPENSSL_NO_DSA
78 #include <openssl/dsa.h>
83 #define BITS "default_bits"
84 #define KEYFILE "default_keyfile"
85 #define PROMPT "prompt"
86 #define DISTINGUISHED_NAME "distinguished_name"
87 #define ATTRIBUTES "attributes"
88 #define V3_EXTENSIONS "x509_extensions"
89 #define REQ_EXTENSIONS "req_extensions"
90 #define STRING_MASK "string_mask"
91 #define UTF8_IN "utf8"
93 #define DEFAULT_KEY_LENGTH 512
94 #define MIN_KEY_LENGTH 384
100 * -inform arg - input format - default PEM (DER or PEM)
101 * -outform arg - output format - default PEM
102 * -in arg - input file - default stdin
103 * -out arg - output file - default stdout
104 * -verify - check request signature
105 * -noout - don't print stuff out.
106 * -text - print out human readable text.
107 * -nodes - no des encryption
108 * -config file - Load configuration file.
109 * -key file - make a request using key in file (or use it for verification).
110 * -keyform arg - key file format.
111 * -rand file(s) - load the file(s) into the PRNG.
112 * -newkey - make a key and a request.
113 * -modulus - print RSA modulus.
114 * -pubkey - output Public Key.
115 * -x509 - output a self signed X509 structure instead.
116 * -asn1-kludge - output new certificate request in a format that some CA's
117 * require. This format is wrong
120 static int make_REQ(X509_REQ *req,EVP_PKEY *pkey,char *dn,int mutlirdn,
121 int attribs,unsigned long chtype);
122 static int build_subject(X509_REQ *req, char *subj, unsigned long chtype,
124 static int prompt_info(X509_REQ *req,
125 STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
126 STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect, int attribs,
127 unsigned long chtype);
128 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk,
129 STACK_OF(CONF_VALUE) *attr, int attribs,
130 unsigned long chtype);
131 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
132 char *value, int nid, int n_min,
133 int n_max, unsigned long chtype);
134 static int add_DN_object(X509_NAME *n, char *text, const char *def, char *value,
135 int nid,int n_min,int n_max, unsigned long chtype, int mval);
136 static int genpkey_cb(EVP_PKEY_CTX *ctx);
137 static int req_check_len(int len,int n_min,int n_max);
138 static int check_end(const char *str, const char *end);
139 static EVP_PKEY_CTX *set_keygen_ctx(BIO *err, const char *gstr, int *pkey_type,
140 long *pkeylen, char **palgnam,
141 ENGINE *keygen_engine);
143 static char *default_config_file=NULL;
145 static CONF *req_conf=NULL;
148 int MAIN(int, char **);
150 int MAIN(int argc, char **argv)
152 ENGINE *e = NULL, *gen_eng = NULL;
153 unsigned long nmflag = 0, reqflag = 0;
154 int ex=1,x509=0,days=30;
157 EVP_PKEY_CTX *genctx = NULL;
158 const char *keyalg = NULL;
159 char *keyalgstr = NULL;
160 STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL;
162 int i=0,badops=0,newreq=0,verbose=0,pkey_type=-1;
164 BIO *in=NULL,*out=NULL;
165 int informat,outformat,verify=0,noout=0,text=0,keyform=FORMAT_PEM;
166 int nodes=0,kludge=0,newhdr=0,subject=0,pubkey=0;
167 char *infile,*outfile,*prog,*keyfile=NULL,*template=NULL,*keyout=NULL;
168 #ifndef OPENSSL_NO_ENGINE
171 char *extensions = NULL;
172 char *req_exts = NULL;
173 const EVP_CIPHER *cipher=NULL;
174 ASN1_INTEGER *serial = NULL;
177 char *passargin = NULL, *passargout = NULL;
178 char *passin = NULL, *passout = NULL;
182 const EVP_MD *md_alg=NULL,*digest=NULL;
183 unsigned long chtype = MBSTRING_ASC;
190 #ifndef OPENSSL_NO_DES
191 cipher=EVP_des_ede3_cbc();
196 if ((bio_err=BIO_new(BIO_s_file())) != NULL)
197 BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);
202 outformat=FORMAT_PEM;
209 if (strcmp(*argv,"-inform") == 0)
211 if (--argc < 1) goto bad;
212 informat=str2fmt(*(++argv));
214 else if (strcmp(*argv,"-outform") == 0)
216 if (--argc < 1) goto bad;
217 outformat=str2fmt(*(++argv));
219 #ifndef OPENSSL_NO_ENGINE
220 else if (strcmp(*argv,"-engine") == 0)
222 if (--argc < 1) goto bad;
225 else if (strcmp(*argv,"-keygen_engine") == 0)
227 if (--argc < 1) goto bad;
228 gen_eng = ENGINE_by_id(*(++argv));
231 BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv);
236 else if (strcmp(*argv,"-key") == 0)
238 if (--argc < 1) goto bad;
241 else if (strcmp(*argv,"-pubkey") == 0)
245 else if (strcmp(*argv,"-new") == 0)
249 else if (strcmp(*argv,"-config") == 0)
251 if (--argc < 1) goto bad;
254 else if (strcmp(*argv,"-keyform") == 0)
256 if (--argc < 1) goto bad;
257 keyform=str2fmt(*(++argv));
259 else if (strcmp(*argv,"-in") == 0)
261 if (--argc < 1) goto bad;
264 else if (strcmp(*argv,"-out") == 0)
266 if (--argc < 1) goto bad;
269 else if (strcmp(*argv,"-keyout") == 0)
271 if (--argc < 1) goto bad;
274 else if (strcmp(*argv,"-passin") == 0)
276 if (--argc < 1) goto bad;
277 passargin= *(++argv);
279 else if (strcmp(*argv,"-passout") == 0)
281 if (--argc < 1) goto bad;
282 passargout= *(++argv);
284 else if (strcmp(*argv,"-rand") == 0)
286 if (--argc < 1) goto bad;
289 else if (strcmp(*argv,"-newkey") == 0)
296 else if (strcmp(*argv,"-pkeyopt") == 0)
301 pkeyopts = sk_OPENSSL_STRING_new_null();
302 if (!pkeyopts || !sk_OPENSSL_STRING_push(pkeyopts, *(++argv)))
305 else if (strcmp(*argv,"-sigopt") == 0)
310 sigopts = sk_OPENSSL_STRING_new_null();
311 if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv)))
314 else if (strcmp(*argv,"-batch") == 0)
316 else if (strcmp(*argv,"-newhdr") == 0)
318 else if (strcmp(*argv,"-modulus") == 0)
320 else if (strcmp(*argv,"-verify") == 0)
322 else if (strcmp(*argv,"-nodes") == 0)
324 else if (strcmp(*argv,"-noout") == 0)
326 else if (strcmp(*argv,"-verbose") == 0)
328 else if (strcmp(*argv,"-utf8") == 0)
329 chtype = MBSTRING_UTF8;
330 else if (strcmp(*argv,"-nameopt") == 0)
332 if (--argc < 1) goto bad;
333 if (!set_name_ex(&nmflag, *(++argv))) goto bad;
335 else if (strcmp(*argv,"-reqopt") == 0)
337 if (--argc < 1) goto bad;
338 if (!set_cert_ex(&reqflag, *(++argv))) goto bad;
340 else if (strcmp(*argv,"-subject") == 0)
342 else if (strcmp(*argv,"-text") == 0)
344 else if (strcmp(*argv,"-x509") == 0)
346 else if (strcmp(*argv,"-asn1-kludge") == 0)
348 else if (strcmp(*argv,"-no-asn1-kludge") == 0)
350 else if (strcmp(*argv,"-subj") == 0)
352 if (--argc < 1) goto bad;
355 else if (strcmp(*argv,"-multivalue-rdn") == 0)
357 else if (strcmp(*argv,"-days") == 0)
359 if (--argc < 1) goto bad;
360 days= atoi(*(++argv));
361 if (days == 0) days=30;
363 else if (strcmp(*argv,"-set_serial") == 0)
365 if (--argc < 1) goto bad;
366 serial = s2i_ASN1_INTEGER(NULL, *(++argv));
367 if (!serial) goto bad;
369 else if (strcmp(*argv,"-extensions") == 0)
371 if (--argc < 1) goto bad;
372 extensions = *(++argv);
374 else if (strcmp(*argv,"-reqexts") == 0)
376 if (--argc < 1) goto bad;
377 req_exts = *(++argv);
379 else if ((md_alg=EVP_get_digestbyname(&((*argv)[1]))) != NULL)
386 BIO_printf(bio_err,"unknown option %s\n",*argv);
397 BIO_printf(bio_err,"%s [options] <infile >outfile\n",prog);
398 BIO_printf(bio_err,"where options are\n");
399 BIO_printf(bio_err," -inform arg input format - DER or PEM\n");
400 BIO_printf(bio_err," -outform arg output format - DER or PEM\n");
401 BIO_printf(bio_err," -in arg input file\n");
402 BIO_printf(bio_err," -out arg output file\n");
403 BIO_printf(bio_err," -text text form of request\n");
404 BIO_printf(bio_err," -pubkey output public key\n");
405 BIO_printf(bio_err," -noout do not output REQ\n");
406 BIO_printf(bio_err," -verify verify signature on REQ\n");
407 BIO_printf(bio_err," -modulus RSA modulus\n");
408 BIO_printf(bio_err," -nodes don't encrypt the output key\n");
409 #ifndef OPENSSL_NO_ENGINE
410 BIO_printf(bio_err," -engine e use engine e, possibly a hardware device\n");
412 BIO_printf(bio_err," -subject output the request's subject\n");
413 BIO_printf(bio_err," -passin private key password source\n");
414 BIO_printf(bio_err," -key file use the private key contained in file\n");
415 BIO_printf(bio_err," -keyform arg key file format\n");
416 BIO_printf(bio_err," -keyout arg file to send the key to\n");
417 BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
418 BIO_printf(bio_err," load the file (or the files in the directory) into\n");
419 BIO_printf(bio_err," the random number generator\n");
420 BIO_printf(bio_err," -newkey rsa:bits generate a new RSA key of 'bits' in size\n");
421 BIO_printf(bio_err," -newkey dsa:file generate a new DSA key, parameters taken from CA in 'file'\n");
422 #ifndef OPENSSL_NO_ECDSA
423 BIO_printf(bio_err," -newkey ec:file generate a new EC key, parameters taken from CA in 'file'\n");
425 BIO_printf(bio_err," -[digest] Digest to sign with (md5, sha1, md2, mdc2, md4)\n");
426 BIO_printf(bio_err," -config file request template file.\n");
427 BIO_printf(bio_err," -subj arg set or modify request subject\n");
428 BIO_printf(bio_err," -multivalue-rdn enable support for multivalued RDNs\n");
429 BIO_printf(bio_err," -new new request.\n");
430 BIO_printf(bio_err," -batch do not ask anything during request generation\n");
431 BIO_printf(bio_err," -x509 output a x509 structure instead of a cert. req.\n");
432 BIO_printf(bio_err," -days number of days a certificate generated by -x509 is valid for.\n");
433 BIO_printf(bio_err," -set_serial serial number to use for a certificate generated by -x509.\n");
434 BIO_printf(bio_err," -newhdr output \"NEW\" in the header lines\n");
435 BIO_printf(bio_err," -asn1-kludge Output the 'request' in a format that is wrong but some CA's\n");
436 BIO_printf(bio_err," have been reported as requiring\n");
437 BIO_printf(bio_err," -extensions .. specify certificate extension section (override value in config file)\n");
438 BIO_printf(bio_err," -reqexts .. specify request extension section (override value in config file)\n");
439 BIO_printf(bio_err," -utf8 input characters are UTF8 (default ASCII)\n");
440 BIO_printf(bio_err," -nameopt arg - various certificate name options\n");
441 BIO_printf(bio_err," -reqopt arg - various request text options\n\n");
445 ERR_load_crypto_strings();
446 if(!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
447 BIO_printf(bio_err, "Error getting passwords\n");
451 #ifndef MONOLITH /* else this has happened in openssl.c (global `config') */
452 /* Lets load up our environment a little */
453 p=getenv("OPENSSL_CONF");
455 p=getenv("SSLEAY_CONF");
457 p=to_free=make_config_name();
458 default_config_file=p;
459 config=NCONF_new(NULL);
460 i=NCONF_load(config, p, &errline);
463 if (template != NULL)
468 BIO_printf(bio_err,"Using configuration from %s\n",template);
469 req_conf=NCONF_new(NULL);
470 i=NCONF_load(req_conf,template,&errline);
473 BIO_printf(bio_err,"error on line %ld of %s\n",errline,template);
481 if (req_conf == NULL)
483 BIO_printf(bio_err,"Unable to load config info from %s\n", default_config_file);
488 BIO_printf(bio_err,"Using configuration from %s\n",
489 default_config_file);
492 if (req_conf != NULL)
494 if (!load_config(bio_err, req_conf))
496 p=NCONF_get_string(req_conf,NULL,"oid_file");
503 oid_bio=BIO_new_file(p,"r");
507 BIO_printf(bio_err,"problems opening %s for extra oid's\n",p);
508 ERR_print_errors(bio_err);
513 OBJ_create_objects(oid_bio);
518 if(!add_oid_section(bio_err, req_conf)) goto end;
522 p=NCONF_get_string(req_conf,SECTION,"default_md");
527 if ((md_alg=EVP_get_digestbyname(p)) != NULL)
534 extensions = NCONF_get_string(req_conf, SECTION, V3_EXTENSIONS);
539 /* Check syntax of file */
541 X509V3_set_ctx_test(&ctx);
542 X509V3_set_nconf(&ctx, req_conf);
543 if(!X509V3_EXT_add_nconf(req_conf, &ctx, extensions, NULL)) {
545 "Error Loading extension section %s\n", extensions);
552 passin = NCONF_get_string(req_conf, SECTION, "input_password");
559 passout = NCONF_get_string(req_conf, SECTION, "output_password");
564 p = NCONF_get_string(req_conf, SECTION, STRING_MASK);
568 if(p && !ASN1_STRING_set_default_mask_asc(p)) {
569 BIO_printf(bio_err, "Invalid global string mask setting %s\n", p);
573 if (chtype != MBSTRING_UTF8)
575 p = NCONF_get_string(req_conf, SECTION, UTF8_IN);
578 else if (!strcmp(p, "yes"))
579 chtype = MBSTRING_UTF8;
585 req_exts = NCONF_get_string(req_conf, SECTION, REQ_EXTENSIONS);
590 /* Check syntax of file */
592 X509V3_set_ctx_test(&ctx);
593 X509V3_set_nconf(&ctx, req_conf);
594 if(!X509V3_EXT_add_nconf(req_conf, &ctx, req_exts, NULL)) {
596 "Error Loading request extension section %s\n",
602 in=BIO_new(BIO_s_file());
603 out=BIO_new(BIO_s_file());
604 if ((in == NULL) || (out == NULL))
607 #ifndef OPENSSL_NO_ENGINE
608 e = setup_engine(bio_err, engine, 0);
613 pkey = load_key(bio_err, keyfile, keyform, 0, passin, e,
617 /* load_key() has already printed an appropriate
623 char *randfile = NCONF_get_string(req_conf,SECTION,"RANDFILE");
624 if (randfile == NULL)
626 app_RAND_load_file(randfile, bio_err, 0);
630 if (newreq && (pkey == NULL))
632 char *randfile = NCONF_get_string(req_conf,SECTION,"RANDFILE");
633 if (randfile == NULL)
635 app_RAND_load_file(randfile, bio_err, 0);
637 app_RAND_load_files(inrand);
639 if (!NCONF_get_number(req_conf,SECTION,BITS, &newkey))
641 newkey=DEFAULT_KEY_LENGTH;
646 genctx = set_keygen_ctx(bio_err, keyalg, &pkey_type, &newkey,
647 &keyalgstr, gen_eng);
652 if (newkey < MIN_KEY_LENGTH && (pkey_type == EVP_PKEY_RSA || pkey_type == EVP_PKEY_DSA))
654 BIO_printf(bio_err,"private key length is too short,\n");
655 BIO_printf(bio_err,"it needs to be at least %d bits, not %ld\n",MIN_KEY_LENGTH,newkey);
661 genctx = set_keygen_ctx(bio_err, NULL, &pkey_type, &newkey,
662 &keyalgstr, gen_eng);
670 for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++)
672 genopt = sk_OPENSSL_STRING_value(pkeyopts, i);
673 if (pkey_ctrl_string(genctx, genopt) <= 0)
676 "parameter error \"%s\"\n",
678 ERR_print_errors(bio_err);
684 BIO_printf(bio_err,"Generating a %ld bit %s private key\n",
687 EVP_PKEY_CTX_set_cb(genctx, genpkey_cb);
688 EVP_PKEY_CTX_set_app_data(genctx, bio_err);
690 if (EVP_PKEY_keygen(genctx, &pkey) <= 0)
692 BIO_puts(bio_err, "Error Generating Key\n");
696 EVP_PKEY_CTX_free(genctx);
699 app_RAND_write_file(randfile, bio_err);
703 keyout=NCONF_get_string(req_conf,SECTION,KEYFILE);
710 BIO_printf(bio_err,"writing new private key to stdout\n");
711 BIO_set_fp(out,stdout,BIO_NOCLOSE);
712 #ifdef OPENSSL_SYS_VMS
714 BIO *tmpbio = BIO_new(BIO_f_linebuffer());
715 out = BIO_push(tmpbio, out);
721 BIO_printf(bio_err,"writing new private key to '%s'\n",keyout);
722 if (BIO_write_filename(out,keyout) <= 0)
729 p=NCONF_get_string(req_conf,SECTION,"encrypt_rsa_key");
733 p=NCONF_get_string(req_conf,SECTION,"encrypt_key");
737 if ((p != NULL) && (strcmp(p,"no") == 0))
739 if (nodes) cipher=NULL;
743 if (!PEM_write_bio_PrivateKey(out,pkey,cipher,
744 NULL,0,NULL,passout))
746 if ((ERR_GET_REASON(ERR_peek_error()) ==
747 PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3))
755 BIO_printf(bio_err,"-----\n");
760 /* Since we are using a pre-existing certificate
761 * request, the kludge 'format' info should not be
765 BIO_set_fp(in,stdin,BIO_NOCLOSE);
768 if (BIO_read_filename(in,infile) <= 0)
775 if (informat == FORMAT_ASN1)
776 req=d2i_X509_REQ_bio(in,NULL);
777 else if (informat == FORMAT_PEM)
778 req=PEM_read_bio_X509_REQ(in,NULL,NULL,NULL);
781 BIO_printf(bio_err,"bad input format specified for X509 request\n");
786 BIO_printf(bio_err,"unable to load X509 request\n");
795 BIO_printf(bio_err,"you need to specify a private key\n");
807 i=make_REQ(req,pkey,subj,multirdn,!x509, chtype);
808 subj=NULL; /* done processing '-subj' option */
809 if ((kludge > 0) && !sk_X509_ATTRIBUTE_num(req->req_info->attributes))
811 sk_X509_ATTRIBUTE_free(req->req_info->attributes);
812 req->req_info->attributes = NULL;
816 BIO_printf(bio_err,"problems making Certificate Request\n");
824 if ((x509ss=X509_new()) == NULL) goto end;
826 /* Set version to V3 */
827 if(extensions && !X509_set_version(x509ss, 2)) goto end;
830 if (!X509_set_serialNumber(x509ss, serial)) goto end;
834 if (!rand_serial(NULL,
835 X509_get_serialNumber(x509ss)))
839 if (!X509_set_issuer_name(x509ss, X509_REQ_get_subject_name(req))) goto end;
840 if (!X509_gmtime_adj(X509_get_notBefore(x509ss),0)) goto end;
841 if (!X509_time_adj_ex(X509_get_notAfter(x509ss), days, 0, NULL)) goto end;
842 if (!X509_set_subject_name(x509ss, X509_REQ_get_subject_name(req))) goto end;
843 tmppkey = X509_REQ_get_pubkey(req);
844 if (!tmppkey || !X509_set_pubkey(x509ss,tmppkey)) goto end;
845 EVP_PKEY_free(tmppkey);
847 /* Set up V3 context struct */
849 X509V3_set_ctx(&ext_ctx, x509ss, x509ss, NULL, NULL, 0);
850 X509V3_set_nconf(&ext_ctx, req_conf);
853 if(extensions && !X509V3_EXT_add_nconf(req_conf,
854 &ext_ctx, extensions, x509ss))
857 "Error Loading extension section %s\n",
862 i=do_X509_sign(bio_err, x509ss, pkey, digest, sigopts);
865 ERR_print_errors(bio_err);
873 /* Set up V3 context struct */
875 X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, 0);
876 X509V3_set_nconf(&ext_ctx, req_conf);
879 if(req_exts && !X509V3_EXT_REQ_add_nconf(req_conf,
880 &ext_ctx, req_exts, req))
883 "Error Loading extension section %s\n",
887 i=do_X509_REQ_sign(bio_err, req, pkey, digest, sigopts);
890 ERR_print_errors(bio_err);
898 BIO_printf(bio_err, "Cannot modify certificate subject\n");
906 BIO_printf(bio_err, "Modifying Request's Subject\n");
907 print_name(bio_err, "old subject=", X509_REQ_get_subject_name(req), nmflag);
910 if (build_subject(req, subj, chtype, multirdn) == 0)
912 BIO_printf(bio_err, "ERROR: cannot modify subject\n");
917 req->req_info->enc.modified = 1;
921 print_name(bio_err, "new subject=", X509_REQ_get_subject_name(req), nmflag);
931 pkey=X509_REQ_get_pubkey(req);
933 if (pkey == NULL) goto end;
936 i=X509_REQ_verify(req,pkey);
948 BIO_printf(bio_err,"verify failure\n");
949 ERR_print_errors(bio_err);
951 else /* if (i > 0) */
952 BIO_printf(bio_err,"verify OK\n");
955 if (noout && !text && !modulus && !subject && !pubkey)
963 BIO_set_fp(out,stdout,BIO_NOCLOSE);
964 #ifdef OPENSSL_SYS_VMS
966 BIO *tmpbio = BIO_new(BIO_f_linebuffer());
967 out = BIO_push(tmpbio, out);
973 if ((keyout != NULL) && (strcmp(outfile,keyout) == 0))
974 i=(int)BIO_append_filename(out,outfile);
976 i=(int)BIO_write_filename(out,outfile);
987 tpubkey=X509_REQ_get_pubkey(req);
990 BIO_printf(bio_err,"Error getting public key\n");
991 ERR_print_errors(bio_err);
994 PEM_write_bio_PUBKEY(out, tpubkey);
995 EVP_PKEY_free(tpubkey);
1001 X509_print_ex(out, x509ss, nmflag, reqflag);
1003 X509_REQ_print_ex(out, req, nmflag, reqflag);
1009 print_name(out, "subject=", X509_get_subject_name(x509ss), nmflag);
1011 print_name(out, "subject=", X509_REQ_get_subject_name(req), nmflag);
1019 tpubkey=X509_get_pubkey(x509ss);
1021 tpubkey=X509_REQ_get_pubkey(req);
1022 if (tpubkey == NULL)
1024 fprintf(stdout,"Modulus=unavailable\n");
1027 fprintf(stdout,"Modulus=");
1028 #ifndef OPENSSL_NO_RSA
1029 if (EVP_PKEY_base_id(tpubkey) == EVP_PKEY_RSA)
1030 BN_print(out,tpubkey->pkey.rsa->n);
1033 fprintf(stdout,"Wrong Algorithm type");
1034 EVP_PKEY_free(tpubkey);
1035 fprintf(stdout,"\n");
1038 if (!noout && !x509)
1040 if (outformat == FORMAT_ASN1)
1041 i=i2d_X509_REQ_bio(out,req);
1042 else if (outformat == FORMAT_PEM) {
1043 if(newhdr) i=PEM_write_bio_X509_REQ_NEW(out,req);
1044 else i=PEM_write_bio_X509_REQ(out,req);
1046 BIO_printf(bio_err,"bad output format specified for outfile\n");
1051 BIO_printf(bio_err,"unable to write X509 request\n");
1055 if (!noout && x509 && (x509ss != NULL))
1057 if (outformat == FORMAT_ASN1)
1058 i=i2d_X509_bio(out,x509ss);
1059 else if (outformat == FORMAT_PEM)
1060 i=PEM_write_bio_X509(out,x509ss);
1062 BIO_printf(bio_err,"bad output format specified for outfile\n");
1067 BIO_printf(bio_err,"unable to write X509 certificate\n");
1075 OPENSSL_free(to_free);
1079 ERR_print_errors(bio_err);
1081 if ((req_conf != NULL) && (req_conf != config)) NCONF_free(req_conf);
1084 EVP_PKEY_free(pkey);
1086 EVP_PKEY_CTX_free(genctx);
1088 sk_OPENSSL_STRING_free(pkeyopts);
1090 sk_OPENSSL_STRING_free(sigopts);
1091 #ifndef OPENSSL_NO_ENGINE
1093 ENGINE_free(gen_eng);
1096 OPENSSL_free(keyalgstr);
1099 ASN1_INTEGER_free(serial);
1100 if(passargin && passin) OPENSSL_free(passin);
1101 if(passargout && passout) OPENSSL_free(passout);
1107 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, char *subj, int multirdn,
1108 int attribs, unsigned long chtype)
1112 STACK_OF(CONF_VALUE) *dn_sk, *attr_sk = NULL;
1113 char *tmp, *dn_sect,*attr_sect;
1115 tmp=NCONF_get_string(req_conf,SECTION,PROMPT);
1118 if((tmp != NULL) && !strcmp(tmp, "no")) no_prompt = 1;
1120 dn_sect=NCONF_get_string(req_conf,SECTION,DISTINGUISHED_NAME);
1121 if (dn_sect == NULL)
1123 BIO_printf(bio_err,"unable to find '%s' in config\n",
1124 DISTINGUISHED_NAME);
1127 dn_sk=NCONF_get_section(req_conf,dn_sect);
1130 BIO_printf(bio_err,"unable to get '%s' section\n",dn_sect);
1134 attr_sect=NCONF_get_string(req_conf,SECTION,ATTRIBUTES);
1135 if (attr_sect == NULL)
1142 attr_sk=NCONF_get_section(req_conf,attr_sect);
1143 if (attr_sk == NULL)
1145 BIO_printf(bio_err,"unable to get '%s' section\n",attr_sect);
1150 /* setup version number */
1151 if (!X509_REQ_set_version(req,0L)) goto err; /* version 1 */
1154 i = build_subject(req, subj, chtype, multirdn);
1156 i = auto_info(req, dn_sk, attr_sk, attribs, chtype);
1158 i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs, chtype);
1161 if (!X509_REQ_set_pubkey(req,pkey)) goto err;
1169 * subject is expected to be in the format /type0=value0/type1=value1/type2=...
1170 * where characters may be escaped by \
1172 static int build_subject(X509_REQ *req, char *subject, unsigned long chtype, int multirdn)
1176 if (!(n = parse_name(subject, chtype, multirdn)))
1179 if (!X509_REQ_set_subject_name(req, n))
1189 static int prompt_info(X509_REQ *req,
1190 STACK_OF(CONF_VALUE) *dn_sk, char *dn_sect,
1191 STACK_OF(CONF_VALUE) *attr_sk, char *attr_sect, int attribs,
1192 unsigned long chtype)
1203 subj = X509_REQ_get_subject_name(req);
1207 BIO_printf(bio_err,"You are about to be asked to enter information that will be incorporated\n");
1208 BIO_printf(bio_err,"into your certificate request.\n");
1209 BIO_printf(bio_err,"What you are about to enter is what is called a Distinguished Name or a DN.\n");
1210 BIO_printf(bio_err,"There are quite a few fields but you can leave some blank\n");
1211 BIO_printf(bio_err,"For some fields there will be a default value,\n");
1212 BIO_printf(bio_err,"If you enter '.', the field will be left blank.\n");
1213 BIO_printf(bio_err,"-----\n");
1217 if (sk_CONF_VALUE_num(dn_sk))
1223 if (sk_CONF_VALUE_num(dn_sk) <= i) break;
1225 v=sk_CONF_VALUE_value(dn_sk,i);
1228 if(!check_end(type,"_min") || !check_end(type,"_max") ||
1229 !check_end(type,"_default") ||
1230 !check_end(type,"_value")) continue;
1231 /* Skip past any leading X. X: X, etc to allow for
1232 * multiple instances
1234 for(p = v->name; *p ; p++)
1235 if ((*p == ':') || (*p == ',') ||
1248 /* If OBJ not recognised ignore it */
1249 if ((nid=OBJ_txt2nid(type)) == NID_undef) goto start;
1250 if (BIO_snprintf(buf,sizeof buf,"%s_default",v->name)
1251 >= (int)sizeof(buf))
1253 BIO_printf(bio_err,"Name '%s' too long\n",v->name);
1257 if ((def=NCONF_get_string(req_conf,dn_sect,buf)) == NULL)
1263 BIO_snprintf(buf,sizeof buf,"%s_value",v->name);
1264 if ((value=NCONF_get_string(req_conf,dn_sect,buf)) == NULL)
1270 BIO_snprintf(buf,sizeof buf,"%s_min",v->name);
1271 if (!NCONF_get_number(req_conf,dn_sect,buf, &n_min))
1277 BIO_snprintf(buf,sizeof buf,"%s_max",v->name);
1278 if (!NCONF_get_number(req_conf,dn_sect,buf, &n_max))
1284 if (!add_DN_object(subj,v->value,def,value,nid,
1285 n_min,n_max, chtype, mval))
1288 if (X509_NAME_entry_count(subj) == 0)
1290 BIO_printf(bio_err,"error, no objects specified in config file\n");
1296 if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0) && (!batch))
1298 BIO_printf(bio_err,"\nPlease enter the following 'extra' attributes\n");
1299 BIO_printf(bio_err,"to be sent with your certificate request\n");
1306 if ((attr_sk == NULL) ||
1307 (sk_CONF_VALUE_num(attr_sk) <= i))
1310 v=sk_CONF_VALUE_value(attr_sk,i);
1312 if ((nid=OBJ_txt2nid(type)) == NID_undef)
1315 if (BIO_snprintf(buf,sizeof buf,"%s_default",type)
1316 >= (int)sizeof(buf))
1318 BIO_printf(bio_err,"Name '%s' too long\n",v->name);
1322 if ((def=NCONF_get_string(req_conf,attr_sect,buf))
1330 BIO_snprintf(buf,sizeof buf,"%s_value",type);
1331 if ((value=NCONF_get_string(req_conf,attr_sect,buf))
1338 BIO_snprintf(buf,sizeof buf,"%s_min",type);
1339 if (!NCONF_get_number(req_conf,attr_sect,buf, &n_min))
1345 BIO_snprintf(buf,sizeof buf,"%s_max",type);
1346 if (!NCONF_get_number(req_conf,attr_sect,buf, &n_max))
1352 if (!add_attribute_object(req,
1353 v->value,def,value,nid,n_min,n_max, chtype))
1360 BIO_printf(bio_err,"No template, please set one up.\n");
1368 static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk,
1369 STACK_OF(CONF_VALUE) *attr_sk, int attribs, unsigned long chtype)
1377 subj = X509_REQ_get_subject_name(req);
1379 for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++)
1382 v=sk_CONF_VALUE_value(dn_sk,i);
1385 /* Skip past any leading X. X: X, etc to allow for
1386 * multiple instances
1388 for(p = v->name; *p ; p++)
1389 #ifndef CHARSET_EBCDIC
1390 if ((*p == ':') || (*p == ',') || (*p == '.')) {
1392 if ((*p == os_toascii[':']) || (*p == os_toascii[',']) || (*p == os_toascii['.'])) {
1398 #ifndef CHARSET_EBCDIC
1401 if (*p == os_toascii['+'])
1409 if (!X509_NAME_add_entry_by_txt(subj,type, chtype,
1410 (unsigned char *) v->value,-1,-1,mval)) return 0;
1414 if (!X509_NAME_entry_count(subj))
1416 BIO_printf(bio_err,"error, no objects specified in config file\n");
1421 for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++)
1423 v=sk_CONF_VALUE_value(attr_sk,i);
1424 if(!X509_REQ_add1_attr_by_txt(req, v->name, chtype,
1425 (unsigned char *)v->value, -1)) return 0;
1432 static int add_DN_object(X509_NAME *n, char *text, const char *def, char *value,
1433 int nid, int n_min, int n_max, unsigned long chtype, int mval)
1436 MS_STATIC char buf[1024];
1438 if (!batch) BIO_printf(bio_err,"%s [%s]:",text,def);
1439 (void)BIO_flush(bio_err);
1442 BUF_strlcpy(buf,value,sizeof buf);
1443 BUF_strlcat(buf,"\n",sizeof buf);
1444 BIO_printf(bio_err,"%s\n",value);
1451 if (!fgets(buf,sizeof buf,stdin))
1461 if (buf[0] == '\0') return(0);
1462 else if (buf[0] == '\n')
1464 if ((def == NULL) || (def[0] == '\0'))
1466 BUF_strlcpy(buf,def,sizeof buf);
1467 BUF_strlcat(buf,"\n",sizeof buf);
1469 else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1472 if (buf[i-1] != '\n')
1474 BIO_printf(bio_err,"weird input :-(\n");
1478 #ifdef CHARSET_EBCDIC
1479 ebcdic2ascii(buf, buf, i);
1481 if(!req_check_len(i, n_min, n_max))
1488 if (!X509_NAME_add_entry_by_NID(n,nid, chtype,
1489 (unsigned char *) buf, -1,-1,mval)) goto err;
1495 static int add_attribute_object(X509_REQ *req, char *text, const char *def,
1496 char *value, int nid, int n_min,
1497 int n_max, unsigned long chtype)
1500 static char buf[1024];
1503 if (!batch) BIO_printf(bio_err,"%s [%s]:",text,def);
1504 (void)BIO_flush(bio_err);
1507 BUF_strlcpy(buf,value,sizeof buf);
1508 BUF_strlcat(buf,"\n",sizeof buf);
1509 BIO_printf(bio_err,"%s\n",value);
1516 if (!fgets(buf,sizeof buf,stdin))
1526 if (buf[0] == '\0') return(0);
1527 else if (buf[0] == '\n')
1529 if ((def == NULL) || (def[0] == '\0'))
1531 BUF_strlcpy(buf,def,sizeof buf);
1532 BUF_strlcat(buf,"\n",sizeof buf);
1534 else if ((buf[0] == '.') && (buf[1] == '\n')) return(1);
1537 if (buf[i-1] != '\n')
1539 BIO_printf(bio_err,"weird input :-(\n");
1543 #ifdef CHARSET_EBCDIC
1544 ebcdic2ascii(buf, buf, i);
1546 if(!req_check_len(i, n_min, n_max))
1553 if(!X509_REQ_add1_attr_by_NID(req, nid, chtype,
1554 (unsigned char *)buf, -1)) {
1555 BIO_printf(bio_err, "Error adding attribute\n");
1556 ERR_print_errors(bio_err);
1565 static int req_check_len(int len, int n_min, int n_max)
1567 if ((n_min > 0) && (len < n_min))
1569 BIO_printf(bio_err,"string is too short, it needs to be at least %d bytes long\n",n_min);
1572 if ((n_max >= 0) && (len > n_max))
1574 BIO_printf(bio_err,"string is too long, it needs to be less than %d bytes long\n",n_max);
1580 /* Check if the end of a string matches 'end' */
1581 static int check_end(const char *str, const char *end)
1587 if(elen > slen) return 1;
1588 tmp = str + slen - elen;
1589 return strcmp(tmp, end);
1592 static EVP_PKEY_CTX *set_keygen_ctx(BIO *err, const char *gstr, int *pkey_type,
1593 long *pkeylen, char **palgnam,
1594 ENGINE *keygen_engine)
1596 EVP_PKEY_CTX *gctx = NULL;
1597 EVP_PKEY *param = NULL;
1600 const char *paramfile = NULL;
1604 *pkey_type = EVP_PKEY_RSA;
1607 else if (gstr[0] >= '0' && gstr[0] <= '9')
1609 *pkey_type = EVP_PKEY_RSA;
1610 keylen = atol(gstr);
1613 else if (!strncmp(gstr, "param:", 6))
1614 paramfile = gstr + 6;
1617 const char *p = strchr(gstr, ':');
1620 const EVP_PKEY_ASN1_METHOD *ameth;
1626 /* The lookup of a the string will cover all engines so
1627 * keep a note of the implementation.
1630 ameth = EVP_PKEY_asn1_find_str(&tmpeng, gstr, len);
1634 BIO_printf(err, "Unknown algorithm %.*s\n", len, gstr);
1638 EVP_PKEY_asn1_get0_info(NULL, pkey_type, NULL, NULL, NULL,
1640 #ifndef OPENSSL_NO_ENGINE
1642 ENGINE_finish(tmpeng);
1644 if (*pkey_type == EVP_PKEY_RSA)
1648 keylen = atol(p + 1);
1660 pbio = BIO_new_file(paramfile, "r");
1663 BIO_printf(err, "Can't open parameter file %s\n",
1667 param = PEM_read_bio_Parameters(pbio, NULL);
1672 (void)BIO_reset(pbio);
1673 x = PEM_read_bio_X509(pbio, NULL, NULL, NULL);
1676 param = X509_get_pubkey(x);
1685 BIO_printf(err, "Error reading parameter file %s\n",
1689 if (*pkey_type == -1)
1690 *pkey_type = EVP_PKEY_id(param);
1691 else if (*pkey_type != EVP_PKEY_base_id(param))
1693 BIO_printf(err, "Key Type does not match parameters\n");
1694 EVP_PKEY_free(param);
1701 const EVP_PKEY_ASN1_METHOD *ameth;
1704 ameth = EVP_PKEY_asn1_find(&tmpeng, *pkey_type);
1707 BIO_puts(err, "Internal error: can't find key algorithm\n");
1710 EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &anam, ameth);
1711 *palgnam = BUF_strdup(anam);
1712 #ifndef OPENSSL_NO_ENGINE
1714 ENGINE_finish(tmpeng);
1720 gctx = EVP_PKEY_CTX_new(param, keygen_engine);
1721 *pkeylen = EVP_PKEY_bits(param);
1722 EVP_PKEY_free(param);
1725 gctx = EVP_PKEY_CTX_new_id(*pkey_type, keygen_engine);
1729 BIO_puts(err, "Error allocating keygen context\n");
1730 ERR_print_errors(err);
1734 if (EVP_PKEY_keygen_init(gctx) <= 0)
1736 BIO_puts(err, "Error initializing keygen context\n");
1737 ERR_print_errors(err);
1740 #ifndef OPENSSL_NO_RSA
1741 if ((*pkey_type == EVP_PKEY_RSA) && (keylen != -1))
1743 if (EVP_PKEY_CTX_set_rsa_keygen_bits(gctx, keylen) <= 0)
1745 BIO_puts(err, "Error setting RSA keysize\n");
1746 ERR_print_errors(err);
1747 EVP_PKEY_CTX_free(gctx);
1756 static int genpkey_cb(EVP_PKEY_CTX *ctx)
1759 BIO *b = EVP_PKEY_CTX_get_app_data(ctx);
1761 p = EVP_PKEY_CTX_get_keygen_info(ctx, 0);
1771 static int do_sign_init(BIO *err, EVP_MD_CTX *ctx, EVP_PKEY *pkey,
1772 const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts)
1774 EVP_PKEY_CTX *pkctx = NULL;
1776 EVP_MD_CTX_init(ctx);
1777 if (!EVP_DigestSignInit(ctx, &pkctx, md, NULL, pkey))
1779 for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++)
1781 char *sigopt = sk_OPENSSL_STRING_value(sigopts, i);
1782 if (pkey_ctrl_string(pkctx, sigopt) <= 0)
1784 BIO_printf(err, "parameter error \"%s\"\n", sigopt);
1785 ERR_print_errors(bio_err);
1792 int do_X509_sign(BIO *err, X509 *x, EVP_PKEY *pkey, const EVP_MD *md,
1793 STACK_OF(OPENSSL_STRING) *sigopts)
1797 EVP_MD_CTX_init(&mctx);
1798 rv = do_sign_init(err, &mctx, pkey, md, sigopts);
1800 rv = X509_sign_ctx(x, &mctx);
1801 EVP_MD_CTX_cleanup(&mctx);
1802 return rv > 0 ? 1 : 0;
1806 int do_X509_REQ_sign(BIO *err, X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md,
1807 STACK_OF(OPENSSL_STRING) *sigopts)
1811 EVP_MD_CTX_init(&mctx);
1812 rv = do_sign_init(err, &mctx, pkey, md, sigopts);
1814 rv = X509_REQ_sign_ctx(x, &mctx);
1815 EVP_MD_CTX_cleanup(&mctx);
1816 return rv > 0 ? 1 : 0;
1821 int do_X509_CRL_sign(BIO *err, X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md,
1822 STACK_OF(OPENSSL_STRING) *sigopts)
1826 EVP_MD_CTX_init(&mctx);
1827 rv = do_sign_init(err, &mctx, pkey, md, sigopts);
1829 rv = X509_CRL_sign_ctx(x, &mctx);
1830 EVP_MD_CTX_cleanup(&mctx);
1831 return rv > 0 ? 1 : 0;