int MAIN(int argc, char **argv) { ENGINE *e = NULL; unsigned char *buf=NULL; int i,err=1; const EVP_MD *md=NULL,*m; BIO *in=NULL,*inp; BIO *bmd=NULL; BIO *out = NULL; #define PROG_NAME_SIZE 39 char pname[PROG_NAME_SIZE+1]; int separator=0; int debug=0; int keyform=FORMAT_PEM; const char *outfile = NULL, *keyfile = NULL; const char *sigfile = NULL, *randfile = NULL; int out_bin = -1, want_pub = 0, do_verify = 0; EVP_PKEY *sigkey = NULL; unsigned char *sigbuf = NULL; int siglen = 0; char *passargin = NULL, *passin = NULL; #ifndef OPENSSL_NO_ENGINE char *engine=NULL; #endif char *hmac_key=NULL; char *mac_name=NULL; int non_fips_allow = 0; STACK_OF(OPENSSL_STRING) *sigopts = NULL, *macopts = NULL; apps_startup(); if ((buf=(unsigned char *)OPENSSL_malloc(BUFSIZE)) == NULL) { BIO_printf(bio_err,"out of memory\n"); goto end; } if (bio_err == NULL) if ((bio_err=BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; /* first check the program name */ program_name(argv[0],pname,sizeof pname); md=EVP_get_digestbyname(pname); argc--; argv++; while (argc > 0) { if ((*argv)[0] != '-') break; if (strcmp(*argv,"-c") == 0) separator=1; else if (strcmp(*argv,"-r") == 0) separator=2; else if (strcmp(*argv,"-rand") == 0) { if (--argc < 1) break; randfile=*(++argv); } else if (strcmp(*argv,"-out") == 0) { if (--argc < 1) break; outfile=*(++argv); } else if (strcmp(*argv,"-sign") == 0) { if (--argc < 1) break; keyfile=*(++argv); } else if (!strcmp(*argv,"-passin")) { if (--argc < 1) break; passargin=*++argv; } else if (strcmp(*argv,"-verify") == 0) { if (--argc < 1) break; keyfile=*(++argv); want_pub = 1; do_verify = 1; } else if (strcmp(*argv,"-prverify") == 0) { if (--argc < 1) break; keyfile=*(++argv); do_verify = 1; } else if (strcmp(*argv,"-signature") == 0) { if (--argc < 1) break; sigfile=*(++argv); } else if (strcmp(*argv,"-keyform") == 0) { if (--argc < 1) break; keyform=str2fmt(*(++argv)); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv,"-engine") == 0) { if (--argc < 1) break; engine= *(++argv); e = setup_engine(bio_err, engine, 0); } #endif else if (strcmp(*argv,"-hex") == 0) out_bin = 0; else if (strcmp(*argv,"-binary") == 0) out_bin = 1; else if (strcmp(*argv,"-d") == 0) debug=1; else if (!strcmp(*argv,"-fips-fingerprint")) hmac_key = "etaonrishdlcupfm"; else if (strcmp(*argv,"-non-fips-allow") == 0) non_fips_allow=1; else if (!strcmp(*argv,"-hmac")) { if (--argc < 1) break; hmac_key=*++argv; } else if (!strcmp(*argv,"-mac")) { if (--argc < 1) break; mac_name=*++argv; } else if (strcmp(*argv,"-sigopt") == 0) { if (--argc < 1) break; if (!sigopts) sigopts = sk_OPENSSL_STRING_new_null(); if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv))) break; } else if (strcmp(*argv,"-macopt") == 0) { if (--argc < 1) break; if (!macopts) macopts = sk_OPENSSL_STRING_new_null(); if (!macopts || !sk_OPENSSL_STRING_push(macopts, *(++argv))) break; } else if ((m=EVP_get_digestbyname(&((*argv)[1]))) != NULL) md=m; else break; argc--; argv++; } if(do_verify && !sigfile) { BIO_printf(bio_err, "No signature to verify: use the -signature option\n"); goto end; } if ((argc > 0) && (argv[0][0] == '-')) /* bad option */ { BIO_printf(bio_err,"unknown option '%s'\n",*argv); BIO_printf(bio_err,"options are\n"); BIO_printf(bio_err,"-c to output the digest with separating colons\n"); BIO_printf(bio_err,"-r to output the digest in coreutils format\n"); BIO_printf(bio_err,"-d to output debug info\n"); BIO_printf(bio_err,"-hex output as hex dump\n"); BIO_printf(bio_err,"-binary output in binary form\n"); BIO_printf(bio_err,"-sign file sign digest using private key in file\n"); BIO_printf(bio_err,"-verify file verify a signature using public key in file\n"); BIO_printf(bio_err,"-prverify file verify a signature using private key in file\n"); BIO_printf(bio_err,"-keyform arg key file format (PEM or ENGINE)\n"); BIO_printf(bio_err,"-out filename output to filename rather than stdout\n"); BIO_printf(bio_err,"-signature file signature to verify\n"); BIO_printf(bio_err,"-sigopt nm:v signature parameter\n"); BIO_printf(bio_err,"-hmac key create hashed MAC with key\n"); BIO_printf(bio_err,"-mac algorithm create MAC (not neccessarily HMAC)\n"); BIO_printf(bio_err,"-macopt nm:v MAC algorithm parameters or key\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err,"-engine e use engine e, possibly a hardware device.\n"); #endif EVP_MD_do_all_sorted(list_md_fn, bio_err); goto end; } in=BIO_new(BIO_s_file()); bmd=BIO_new(BIO_f_md()); if (debug) { BIO_set_callback(in,BIO_debug_callback); /* needed for windows 3.1 */ BIO_set_callback_arg(in,(char *)bio_err); } if(!app_passwd(bio_err, passargin, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if ((in == NULL) || (bmd == NULL)) { ERR_print_errors(bio_err); goto end; } if(out_bin == -1) { if(keyfile) out_bin = 1; else out_bin = 0; } if(randfile) app_RAND_load_file(randfile, bio_err, 0); if(outfile) { if(out_bin) out = BIO_new_file(outfile, "wb"); else out = BIO_new_file(outfile, "w"); } else { out = BIO_new_fp(stdout, BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } if(!out) { BIO_printf(bio_err, "Error opening output file %s\n", outfile ? outfile : "(stdout)"); ERR_print_errors(bio_err); goto end; } if ((!!mac_name + !!keyfile + !!hmac_key) > 1) { BIO_printf(bio_err, "MAC and Signing key cannot both be specified\n"); goto end; } if(keyfile) { if (want_pub) sigkey = load_pubkey(bio_err, keyfile, keyform, 0, NULL, e, "key file"); else sigkey = load_key(bio_err, keyfile, keyform, 0, passin, e, "key file"); if (!sigkey) { /* load_[pub]key() has already printed an appropriate message */ goto end; } } if (mac_name) { EVP_PKEY_CTX *mac_ctx = NULL; int r = 0; if (!init_gen_str(bio_err, &mac_ctx, mac_name,e, 0)) goto mac_end; if (macopts) { char *macopt; for (i = 0; i < sk_OPENSSL_STRING_num(macopts); i++) { macopt = sk_OPENSSL_STRING_value(macopts, i); if (pkey_ctrl_string(mac_ctx, macopt) <= 0) { BIO_printf(bio_err, "MAC parameter error \"%s\"\n", macopt); ERR_print_errors(bio_err); goto mac_end; } } } if (EVP_PKEY_keygen(mac_ctx, &sigkey) <= 0) { BIO_puts(bio_err, "Error generating key\n"); ERR_print_errors(bio_err); goto mac_end; } r = 1; mac_end: if (mac_ctx) EVP_PKEY_CTX_free(mac_ctx); if (r == 0) goto end; } if (non_fips_allow) { EVP_MD_CTX *md_ctx; BIO_get_md_ctx(bmd,&md_ctx); EVP_MD_CTX_set_flags(md_ctx, EVP_MD_CTX_FLAG_NON_FIPS_ALLOW); } if (hmac_key) { sigkey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, e, (unsigned char *)hmac_key, -1); if (!sigkey) goto end; } if (sigkey) { EVP_MD_CTX *mctx = NULL; EVP_PKEY_CTX *pctx = NULL; int r; if (!BIO_get_md_ctx(bmd, &mctx)) { BIO_printf(bio_err, "Error getting context\n"); ERR_print_errors(bio_err); goto end; } if (do_verify) r = EVP_DigestVerifyInit(mctx, &pctx, md, NULL, sigkey); else r = EVP_DigestSignInit(mctx, &pctx, md, NULL, sigkey); if (!r) { BIO_printf(bio_err, "Error setting context\n"); ERR_print_errors(bio_err); goto end; } if (sigopts) { char *sigopt; for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) { sigopt = sk_OPENSSL_STRING_value(sigopts, i); if (pkey_ctrl_string(pctx, sigopt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", sigopt); ERR_print_errors(bio_err); goto end; } } } } /* we use md as a filter, reading from 'in' */ else { if (md == NULL) md = EVP_md5(); if (!BIO_set_md(bmd,md)) { BIO_printf(bio_err, "Error setting digest %s\n", pname); ERR_print_errors(bio_err); goto end; } } if(sigfile && sigkey) { BIO *sigbio; sigbio = BIO_new_file(sigfile, "rb"); siglen = EVP_PKEY_size(sigkey); sigbuf = OPENSSL_malloc(siglen); if(!sigbio) { BIO_printf(bio_err, "Error opening signature file %s\n", sigfile); ERR_print_errors(bio_err); goto end; } siglen = BIO_read(sigbio, sigbuf, siglen); BIO_free(sigbio); if(siglen <= 0) { BIO_printf(bio_err, "Error reading signature file %s\n", sigfile); ERR_print_errors(bio_err); goto end; } } inp=BIO_push(bmd,in); if (md == NULL) { EVP_MD_CTX *tctx; BIO_get_md_ctx(bmd, &tctx); md = EVP_MD_CTX_md(tctx); } if (argc == 0) { BIO_set_fp(in,stdin,BIO_NOCLOSE); err=do_fp(out, buf,inp,separator, out_bin, sigkey, sigbuf, siglen,NULL,NULL,"stdin",bmd); } else { const char *md_name = NULL, *sig_name = NULL; if(!out_bin) { if (sigkey) { const EVP_PKEY_ASN1_METHOD *ameth; ameth = EVP_PKEY_get0_asn1(sigkey); if (ameth) EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &sig_name, ameth); } md_name = EVP_MD_name(md); } err = 0; for (i=0; i<argc; i++) { int r; if (BIO_read_filename(in,argv[i]) <= 0) { perror(argv[i]); err++; continue; } else r=do_fp(out,buf,inp,separator,out_bin,sigkey,sigbuf, siglen,sig_name,md_name, argv[i],bmd); if(r) err=r; (void)BIO_reset(bmd); } } end: if (buf != NULL) { OPENSSL_cleanse(buf,BUFSIZE); OPENSSL_free(buf); } if (in != NULL) BIO_free(in); if (passin) OPENSSL_free(passin); BIO_free_all(out); EVP_PKEY_free(sigkey); if (sigopts) sk_OPENSSL_STRING_free(sigopts); if (macopts) sk_OPENSSL_STRING_free(macopts); if(sigbuf) OPENSSL_free(sigbuf); if (bmd != NULL) BIO_free(bmd); apps_shutdown(); OPENSSL_EXIT(err); }
int cms_main(int argc, char **argv) { ASN1_OBJECT *econtent_type = NULL; BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL; CMS_ContentInfo *cms = NULL, *rcms = NULL; CMS_ReceiptRequest *rr = NULL; ENGINE *e = NULL; EVP_PKEY *key = NULL; const EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL; const EVP_MD *sign_md = NULL; STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL; STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL; STACK_OF(X509) *encerts = NULL, *other = NULL; X509 *cert = NULL, *recip = NULL, *signer = NULL; X509_STORE *store = NULL; X509_VERIFY_PARAM *vpm = NULL; char *certfile = NULL, *keyfile = NULL, *contfile = NULL; char *CAfile = NULL, *CApath = NULL, *certsoutfile = NULL; int noCAfile = 0, noCApath = 0; char *infile = NULL, *outfile = NULL, *rctfile = NULL, *inrand = NULL; char *passinarg = NULL, *passin = NULL, *signerfile = NULL, *recipfile = NULL; char *to = NULL, *from = NULL, *subject = NULL, *prog; cms_key_param *key_first = NULL, *key_param = NULL; int flags = CMS_DETACHED, noout = 0, print = 0, keyidx = -1, vpmtouched = 0; int informat = FORMAT_SMIME, outformat = FORMAT_SMIME; int need_rand = 0, operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1; int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_PEM; size_t secret_keylen = 0, secret_keyidlen = 0; unsigned char *pwri_pass = NULL, *pwri_tmp = NULL; unsigned char *secret_key = NULL, *secret_keyid = NULL; long ltmp; OPTION_CHOICE o; if ((vpm = X509_VERIFY_PARAM_new()) == NULL) return 1; prog = opt_init(argc, argv, cms_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(cms_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENCRYPT: operation = SMIME_ENCRYPT; break; case OPT_DECRYPT: operation = SMIME_DECRYPT; break; case OPT_SIGN: operation = SMIME_SIGN; break; case OPT_SIGN_RECEIPT: operation = SMIME_SIGN_RECEIPT; break; case OPT_RESIGN: operation = SMIME_RESIGN; break; case OPT_VERIFY: operation = SMIME_VERIFY; break; case OPT_VERIFY_RETCODE: verify_retcode = 1; break; case OPT_VERIFY_RECEIPT: operation = SMIME_VERIFY_RECEIPT; rctfile = opt_arg(); break; case OPT_CMSOUT: operation = SMIME_CMSOUT; break; case OPT_DATA_OUT: operation = SMIME_DATAOUT; break; case OPT_DATA_CREATE: operation = SMIME_DATA_CREATE; break; case OPT_DIGEST_VERIFY: operation = SMIME_DIGEST_VERIFY; break; case OPT_DIGEST_CREATE: operation = SMIME_DIGEST_CREATE; break; case OPT_COMPRESS: operation = SMIME_COMPRESS; break; case OPT_UNCOMPRESS: operation = SMIME_UNCOMPRESS; break; case OPT_ED_DECRYPT: operation = SMIME_ENCRYPTED_DECRYPT; break; case OPT_ED_ENCRYPT: operation = SMIME_ENCRYPTED_ENCRYPT; break; case OPT_DEBUG_DECRYPT: flags |= CMS_DEBUG_DECRYPT; break; case OPT_TEXT: flags |= CMS_TEXT; break; case OPT_ASCIICRLF: flags |= CMS_ASCIICRLF; break; case OPT_NOINTERN: flags |= CMS_NOINTERN; break; case OPT_NOVERIFY: flags |= CMS_NO_SIGNER_CERT_VERIFY; break; case OPT_NOCERTS: flags |= CMS_NOCERTS; break; case OPT_NOATTR: flags |= CMS_NOATTR; break; case OPT_NODETACH: flags &= ~CMS_DETACHED; break; case OPT_NOSMIMECAP: flags |= CMS_NOSMIMECAP; break; case OPT_BINARY: flags |= CMS_BINARY; break; case OPT_KEYID: flags |= CMS_USE_KEYID; break; case OPT_NOSIGS: flags |= CMS_NOSIGS; break; case OPT_NO_CONTENT_VERIFY: flags |= CMS_NO_CONTENT_VERIFY; break; case OPT_NO_ATTR_VERIFY: flags |= CMS_NO_ATTR_VERIFY; break; case OPT_INDEF: flags |= CMS_STREAM; break; case OPT_NOINDEF: flags &= ~CMS_STREAM; break; case OPT_NOOLDMIME: flags |= CMS_NOOLDMIMETYPE; break; case OPT_CRLFEOL: flags |= CMS_CRLFEOL; break; case OPT_NOOUT: noout = 1; break; case OPT_RR_PRINT: rr_print = 1; break; case OPT_RR_ALL: rr_allorfirst = 0; break; case OPT_RR_FIRST: rr_allorfirst = 1; break; case OPT_RCTFORM: if (rctformat == FORMAT_SMIME) rcms = SMIME_read_CMS(rctin, NULL); else if (rctformat == FORMAT_PEM) rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL); else if (rctformat == FORMAT_ASN1) if (!opt_format(opt_arg(), OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat)) goto opthelp; break; case OPT_CERTFILE: certfile = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_IN: infile = opt_arg(); break; case OPT_CONTENT: contfile = opt_arg(); break; case OPT_RR_FROM: if (rr_from == NULL && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(rr_from, opt_arg()); break; case OPT_RR_TO: if (rr_to == NULL && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(rr_to, opt_arg()); break; case OPT_PRINT: noout = print = 1; break; case OPT_SECRETKEY: secret_key = string_to_hex(opt_arg(), <mp); if (secret_key == NULL) { BIO_printf(bio_err, "Invalid key %s\n", opt_arg()); goto end; } secret_keylen = (size_t)ltmp; break; case OPT_SECRETKEYID: secret_keyid = string_to_hex(opt_arg(), <mp); if (secret_keyid == NULL) { BIO_printf(bio_err, "Invalid id %s\n", opt_arg()); goto opthelp; } secret_keyidlen = (size_t)ltmp; break; case OPT_PWRI_PASSWORD: pwri_pass = (unsigned char *)opt_arg(); break; case OPT_ECONTENT_TYPE: econtent_type = OBJ_txt2obj(opt_arg(), 0); if (econtent_type == NULL) { BIO_printf(bio_err, "Invalid OID %s\n", opt_arg()); goto opthelp; } break; case OPT_RAND: inrand = opt_arg(); need_rand = 1; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_TO: to = opt_arg(); break; case OPT_FROM: from = opt_arg(); break; case OPT_SUBJECT: subject = opt_arg(); break; case OPT_CERTSOUT: certsoutfile = opt_arg(); break; case OPT_MD: if (!opt_md(opt_arg(), &sign_md)) goto end; break; case OPT_SIGNER: /* If previous -signer argument add signer to list */ if (signerfile) { if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); if (keyfile == NULL) keyfile = signerfile; if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(skkeys, keyfile); keyfile = NULL; } signerfile = opt_arg(); break; case OPT_INKEY: /* If previous -inkey arument add signer to list */ if (keyfile) { if (signerfile == NULL) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto end; } if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); signerfile = NULL; if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(skkeys, keyfile); } keyfile = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform)) goto opthelp; break; case OPT_RECIP: if (operation == SMIME_ENCRYPT) { if (encerts == NULL && (encerts = sk_X509_new_null()) == NULL) goto end; cert = load_cert(opt_arg(), FORMAT_PEM, NULL, e, "recipient certificate file"); if (cert == NULL) goto end; sk_X509_push(encerts, cert); cert = NULL; } else recipfile = opt_arg(); break; case OPT_CIPHER: if (!opt_cipher(opt_unknown(), &cipher)) goto end; break; case OPT_KEYOPT: keyidx = -1; if (operation == SMIME_ENCRYPT) { if (encerts) keyidx += sk_X509_num(encerts); } else { if (keyfile || signerfile) keyidx++; if (skkeys) keyidx += sk_OPENSSL_STRING_num(skkeys); } if (keyidx < 0) { BIO_printf(bio_err, "No key specified\n"); goto opthelp; } if (key_param == NULL || key_param->idx != keyidx) { cms_key_param *nparam; nparam = app_malloc(sizeof(*nparam), "key param buffer"); nparam->idx = keyidx; if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL) goto end; nparam->next = NULL; if (key_first == NULL) key_first = nparam; else key_param->next = nparam; key_param = nparam; } sk_OPENSSL_STRING_push(key_param->param, opt_arg()); break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_3DES_WRAP: # ifndef OPENSSL_NO_DES wrap_cipher = EVP_des_ede3_wrap(); # endif break; # ifndef OPENSSL_NO_AES case OPT_AES128_WRAP: wrap_cipher = EVP_aes_128_wrap(); break; case OPT_AES192_WRAP: wrap_cipher = EVP_aes_192_wrap(); break; case OPT_AES256_WRAP: wrap_cipher = EVP_aes_256_wrap(); break; # else case OPT_AES128_WRAP: case OPT_AES192_WRAP: case OPT_AES256_WRAP: break; # endif } } argc = opt_num_rest(); argv = opt_rest(); if (((rr_allorfirst != -1) || rr_from) && !rr_to) { BIO_puts(bio_err, "No Signed Receipts Recipients\n"); goto opthelp; } if (!(operation & SMIME_SIGNERS) && (rr_to || rr_from)) { BIO_puts(bio_err, "Signed receipts only allowed with -sign\n"); goto opthelp; } if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) { BIO_puts(bio_err, "Multiple signers or keys not allowed\n"); goto opthelp; } if (operation & SMIME_SIGNERS) { if (keyfile && !signerfile) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto opthelp; } /* Check to see if any final signer needs to be appended */ if (signerfile) { if (!sksigners && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); if (!skkeys && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) goto end; if (!keyfile) keyfile = signerfile; sk_OPENSSL_STRING_push(skkeys, keyfile); } if (!sksigners) { BIO_printf(bio_err, "No signer certificate specified\n"); goto opthelp; } signerfile = NULL; keyfile = NULL; need_rand = 1; } else if (operation == SMIME_DECRYPT) { if (!recipfile && !keyfile && !secret_key && !pwri_pass) { BIO_printf(bio_err, "No recipient certificate or key specified\n"); goto opthelp; } } else if (operation == SMIME_ENCRYPT) { if (*argv == NULL && !secret_key && !pwri_pass && !encerts) { BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n"); goto opthelp; } need_rand = 1; } else if (!operation) goto opthelp; if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (need_rand) { app_RAND_load_file(NULL, (inrand != NULL)); if (inrand != NULL) BIO_printf(bio_err, "%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); } ret = 2; if (!(operation & SMIME_SIGNERS)) flags &= ~CMS_DETACHED; if (!(operation & SMIME_OP)) { if (flags & CMS_BINARY) outformat = FORMAT_BINARY; } if (!(operation & SMIME_IP)) { if (flags & CMS_BINARY) informat = FORMAT_BINARY; } if (operation == SMIME_ENCRYPT) { if (!cipher) { # ifndef OPENSSL_NO_DES cipher = EVP_des_ede3_cbc(); # else BIO_printf(bio_err, "No cipher selected\n"); goto end; # endif } if (secret_key && !secret_keyid) { BIO_printf(bio_err, "No secret key id\n"); goto end; } if (*argv && !encerts) if ((encerts = sk_X509_new_null()) == NULL) goto end; while (*argv) { if ((cert = load_cert(*argv, FORMAT_PEM, NULL, e, "recipient certificate file")) == NULL) goto end; sk_X509_push(encerts, cert); cert = NULL; argv++; } } if (certfile) { if ((other = load_certs(certfile, FORMAT_PEM, NULL, e, "certificate file")) == NULL) { ERR_print_errors(bio_err); goto end; } } if (recipfile && (operation == SMIME_DECRYPT)) { if ((recip = load_cert(recipfile, FORMAT_PEM, NULL, e, "recipient certificate file")) == NULL) { ERR_print_errors(bio_err); goto end; } } if (operation == SMIME_SIGN_RECEIPT) { if ((signer = load_cert(signerfile, FORMAT_PEM, NULL, e, "receipt signer certificate file")) == NULL) { ERR_print_errors(bio_err); goto end; } } if (operation == SMIME_DECRYPT) { if (!keyfile) keyfile = recipfile; } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) { if (!keyfile) keyfile = signerfile; } else keyfile = NULL; if (keyfile) { key = load_key(keyfile, keyform, 0, passin, e, "signing key file"); if (!key) goto end; } in = bio_open_default(infile, 'r', informat); if (in == NULL) goto end; if (operation & SMIME_IP) { if (informat == FORMAT_SMIME) cms = SMIME_read_CMS(in, &indata); else if (informat == FORMAT_PEM) cms = PEM_read_bio_CMS(in, NULL, NULL, NULL); else if (informat == FORMAT_ASN1) cms = d2i_CMS_bio(in, NULL); else { BIO_printf(bio_err, "Bad input format for CMS file\n"); goto end; } if (!cms) { BIO_printf(bio_err, "Error reading S/MIME message\n"); goto end; } if (contfile) { BIO_free(indata); if ((indata = BIO_new_file(contfile, "rb")) == NULL) { BIO_printf(bio_err, "Can't read content file %s\n", contfile); goto end; } } if (certsoutfile) { STACK_OF(X509) *allcerts; allcerts = CMS_get1_certs(cms); if (!save_certs(certsoutfile, allcerts)) { BIO_printf(bio_err, "Error writing certs to %s\n", certsoutfile); ret = 5; goto end; } sk_X509_pop_free(allcerts, X509_free); } } if (rctfile) { char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r"; if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) { BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile); goto end; } if (rctformat == FORMAT_SMIME) rcms = SMIME_read_CMS(rctin, NULL); else if (rctformat == FORMAT_PEM) rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL); else if (rctformat == FORMAT_ASN1) rcms = d2i_CMS_bio(rctin, NULL); else { BIO_printf(bio_err, "Bad input format for receipt\n"); goto end; } if (!rcms) { BIO_printf(bio_err, "Error reading receipt\n"); goto end; } } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) { if ((store = setup_verify(CAfile, CApath, noCAfile, noCApath)) == NULL) goto end; X509_STORE_set_verify_cb(store, cms_cb); if (vpmtouched) X509_STORE_set1_param(store, vpm); } ret = 3; if (operation == SMIME_DATA_CREATE) { cms = CMS_data_create(in, flags); } else if (operation == SMIME_DIGEST_CREATE) { cms = CMS_digest_create(in, sign_md, flags); } else if (operation == SMIME_COMPRESS) { cms = CMS_compress(in, -1, flags); } else if (operation == SMIME_ENCRYPT) { int i; flags |= CMS_PARTIAL; cms = CMS_encrypt(NULL, in, cipher, flags); if (!cms) goto end; for (i = 0; i < sk_X509_num(encerts); i++) { CMS_RecipientInfo *ri; cms_key_param *kparam; int tflags = flags; X509 *x = sk_X509_value(encerts, i); for (kparam = key_first; kparam; kparam = kparam->next) { if (kparam->idx == i) { tflags |= CMS_KEY_PARAM; break; } } ri = CMS_add1_recipient_cert(cms, x, tflags); if (!ri) goto end; if (kparam) { EVP_PKEY_CTX *pctx; pctx = CMS_RecipientInfo_get0_pkey_ctx(ri); if (!cms_set_pkey_param(pctx, kparam->param)) goto end; } if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE && wrap_cipher) { EVP_CIPHER_CTX *wctx; wctx = CMS_RecipientInfo_kari_get0_ctx(ri); EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL); } } if (secret_key) { if (!CMS_add0_recipient_key(cms, NID_undef, secret_key, secret_keylen, secret_keyid, secret_keyidlen, NULL, NULL, NULL)) goto end; /* NULL these because call absorbs them */ secret_key = NULL; secret_keyid = NULL; } if (pwri_pass) { pwri_tmp = (unsigned char *)BUF_strdup((char *)pwri_pass); if (!pwri_tmp) goto end; if (!CMS_add0_recipient_password(cms, -1, NID_undef, NID_undef, pwri_tmp, -1, NULL)) goto end; pwri_tmp = NULL; } if (!(flags & CMS_STREAM)) { if (!CMS_final(cms, in, NULL, flags)) goto end; } } else if (operation == SMIME_ENCRYPTED_ENCRYPT) { cms = CMS_EncryptedData_encrypt(in, cipher, secret_key, secret_keylen, flags); } else if (operation == SMIME_SIGN_RECEIPT) { CMS_ContentInfo *srcms = NULL; STACK_OF(CMS_SignerInfo) *sis; CMS_SignerInfo *si; sis = CMS_get0_SignerInfos(cms); if (!sis) goto end; si = sk_CMS_SignerInfo_value(sis, 0); srcms = CMS_sign_receipt(si, signer, key, other, flags); if (!srcms) goto end; CMS_ContentInfo_free(cms); cms = srcms; } else if (operation & SMIME_SIGNERS) { int i; /* * If detached data content we enable streaming if S/MIME output * format. */ if (operation == SMIME_SIGN) { if (flags & CMS_DETACHED) { if (outformat == FORMAT_SMIME) flags |= CMS_STREAM; } flags |= CMS_PARTIAL; cms = CMS_sign(NULL, NULL, other, in, flags); if (!cms) goto end; if (econtent_type) CMS_set1_eContentType(cms, econtent_type); if (rr_to) { rr = make_receipt_request(rr_to, rr_allorfirst, rr_from); if (!rr) { BIO_puts(bio_err, "Signed Receipt Request Creation Error\n"); goto end; } } } else flags |= CMS_REUSE_DIGEST; for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) { CMS_SignerInfo *si; cms_key_param *kparam; int tflags = flags; signerfile = sk_OPENSSL_STRING_value(sksigners, i); keyfile = sk_OPENSSL_STRING_value(skkeys, i); signer = load_cert(signerfile, FORMAT_PEM, NULL, e, "signer certificate"); if (!signer) goto end; key = load_key(keyfile, keyform, 0, passin, e, "signing key file"); if (!key) goto end; for (kparam = key_first; kparam; kparam = kparam->next) { if (kparam->idx == i) { tflags |= CMS_KEY_PARAM; break; } } si = CMS_add1_signer(cms, signer, key, sign_md, tflags); if (!si) goto end; if (kparam) { EVP_PKEY_CTX *pctx; pctx = CMS_SignerInfo_get0_pkey_ctx(si); if (!cms_set_pkey_param(pctx, kparam->param)) goto end; } if (rr && !CMS_add1_ReceiptRequest(si, rr)) goto end; X509_free(signer); signer = NULL; EVP_PKEY_free(key); key = NULL; } /* If not streaming or resigning finalize structure */ if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) { if (!CMS_final(cms, in, NULL, flags)) goto end; } } if (!cms) { BIO_printf(bio_err, "Error creating CMS structure\n"); goto end; } ret = 4; if (operation == SMIME_DECRYPT) { if (flags & CMS_DEBUG_DECRYPT) CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags); if (secret_key) { if (!CMS_decrypt_set1_key(cms, secret_key, secret_keylen, secret_keyid, secret_keyidlen)) { BIO_puts(bio_err, "Error decrypting CMS using secret key\n"); goto end; } } if (key) { if (!CMS_decrypt_set1_pkey(cms, key, recip)) { BIO_puts(bio_err, "Error decrypting CMS using private key\n"); goto end; } } if (pwri_pass) { if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) { BIO_puts(bio_err, "Error decrypting CMS using password\n"); goto end; } } if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) { BIO_printf(bio_err, "Error decrypting CMS structure\n"); goto end; } } else if (operation == SMIME_DATAOUT) { if (!CMS_data(cms, out, flags)) goto end; } else if (operation == SMIME_UNCOMPRESS) { if (!CMS_uncompress(cms, indata, out, flags)) goto end; } else if (operation == SMIME_DIGEST_VERIFY) { if (CMS_digest_verify(cms, indata, out, flags) > 0) BIO_printf(bio_err, "Verification successful\n"); else { BIO_printf(bio_err, "Verification failure\n"); goto end; } } else if (operation == SMIME_ENCRYPTED_DECRYPT) { if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen, indata, out, flags)) goto end; } else if (operation == SMIME_VERIFY) { if (CMS_verify(cms, other, store, indata, out, flags) > 0) BIO_printf(bio_err, "Verification successful\n"); else { BIO_printf(bio_err, "Verification failure\n"); if (verify_retcode) ret = verify_err + 32; goto end; } if (signerfile) { STACK_OF(X509) *signers; signers = CMS_get0_signers(cms); if (!save_certs(signerfile, signers)) { BIO_printf(bio_err, "Error writing signers to %s\n", signerfile); ret = 5; goto end; } sk_X509_free(signers); } if (rr_print) receipt_request_print(cms); } else if (operation == SMIME_VERIFY_RECEIPT) { if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) BIO_printf(bio_err, "Verification successful\n"); else { BIO_printf(bio_err, "Verification failure\n"); goto end; } } else { if (noout) { if (print) CMS_ContentInfo_print_ctx(out, cms, 0, NULL); } else if (outformat == FORMAT_SMIME) { if (to) BIO_printf(out, "To: %s\n", to); if (from) BIO_printf(out, "From: %s\n", from); if (subject) BIO_printf(out, "Subject: %s\n", subject); if (operation == SMIME_RESIGN) ret = SMIME_write_CMS(out, cms, indata, flags); else ret = SMIME_write_CMS(out, cms, in, flags); } else if (outformat == FORMAT_PEM) ret = PEM_write_bio_CMS_stream(out, cms, in, flags); else if (outformat == FORMAT_ASN1) ret = i2d_CMS_bio_stream(out, cms, in, flags); else { BIO_printf(bio_err, "Bad output format for CMS file\n"); goto end; } if (ret <= 0) { ret = 6; goto end; } } ret = 0; end: if (ret) ERR_print_errors(bio_err); if (need_rand) app_RAND_write_file(NULL); sk_X509_pop_free(encerts, X509_free); sk_X509_pop_free(other, X509_free); X509_VERIFY_PARAM_free(vpm); sk_OPENSSL_STRING_free(sksigners); sk_OPENSSL_STRING_free(skkeys); OPENSSL_free(secret_key); OPENSSL_free(secret_keyid); OPENSSL_free(pwri_tmp); ASN1_OBJECT_free(econtent_type); CMS_ReceiptRequest_free(rr); sk_OPENSSL_STRING_free(rr_to); sk_OPENSSL_STRING_free(rr_from); for (key_param = key_first; key_param;) { cms_key_param *tparam; sk_OPENSSL_STRING_free(key_param->param); tparam = key_param->next; OPENSSL_free(key_param); key_param = tparam; } X509_STORE_free(store); X509_free(cert); X509_free(recip); X509_free(signer); EVP_PKEY_free(key); CMS_ContentInfo_free(cms); CMS_ContentInfo_free(rcms); BIO_free(rctin); BIO_free(in); BIO_free(indata); BIO_free_all(out); OPENSSL_free(passin); return (ret); }
static int nullf_puts(BIO *bp, const char *str) { if (bp->next_bio == NULL) return(0); return(BIO_puts(bp->next_bio,str)); }
int MAIN(int argc, char **argv) { PKCS7 *p7 = NULL; int i, badops = 0; BIO *in = NULL, *out = NULL; int informat, outformat; char *infile, *outfile, *prog; int print_certs = 0, text = 0, noout = 0, p7_print = 0; int ret = 1; #ifndef OPENSSL_NO_ENGINE char *engine = NULL; #endif apps_startup(); if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; infile = NULL; outfile = NULL; informat = FORMAT_PEM; outformat = FORMAT_PEM; prog = argv[0]; argc--; argv++; while (argc >= 1) { if (strcmp(*argv, "-inform") == 0) { if (--argc < 1) goto bad; informat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-outform") == 0) { if (--argc < 1) goto bad; outformat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-in") == 0) { if (--argc < 1) goto bad; infile = *(++argv); } else if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outfile = *(++argv); } else if (strcmp(*argv, "-noout") == 0) noout = 1; else if (strcmp(*argv, "-text") == 0) text = 1; else if (strcmp(*argv, "-print") == 0) p7_print = 1; else if (strcmp(*argv, "-print_certs") == 0) print_certs = 1; #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } #endif else { BIO_printf(bio_err, "unknown option %s\n", *argv); badops = 1; break; } argc--; argv++; } if (badops) { bad: BIO_printf(bio_err, "%s [options] <infile >outfile\n", prog); BIO_printf(bio_err, "where options are\n"); BIO_printf(bio_err, " -inform arg input format - DER or PEM\n"); BIO_printf(bio_err, " -outform arg output format - DER or PEM\n"); BIO_printf(bio_err, " -in arg input file\n"); BIO_printf(bio_err, " -out arg output file\n"); BIO_printf(bio_err, " -print_certs print any certs or crl in the input\n"); BIO_printf(bio_err, " -text print full details of certificates\n"); BIO_printf(bio_err, " -noout don't output encoded data\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n"); #endif ret = 1; goto end; } ERR_load_crypto_strings(); #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, engine, 0); #endif in = BIO_new(BIO_s_file()); out = BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL)) { ERR_print_errors(bio_err); goto end; } if (infile == NULL) BIO_set_fp(in, stdin, BIO_NOCLOSE); else { if (BIO_read_filename(in, infile) <= 0) { BIO_printf(bio_err, "unable to load input file\n"); ERR_print_errors(bio_err); goto end; } } if (informat == FORMAT_ASN1) p7 = d2i_PKCS7_bio(in, NULL); else if (informat == FORMAT_PEM) p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL); else { BIO_printf(bio_err, "bad input format specified for pkcs7 object\n"); goto end; } if (p7 == NULL) { BIO_printf(bio_err, "unable to load PKCS7 object\n"); ERR_print_errors(bio_err); goto end; } if (outfile == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } else { if (BIO_write_filename(out, outfile) <= 0) { perror(outfile); goto end; } } if (p7_print) PKCS7_print_ctx(out, p7, 0, NULL); if (print_certs) { STACK_OF(X509) *certs = NULL; STACK_OF(X509_CRL) *crls = NULL; i = OBJ_obj2nid(p7->type); switch (i) { case NID_pkcs7_signed: certs = p7->d.sign->cert; crls = p7->d.sign->crl; break; case NID_pkcs7_signedAndEnveloped: certs = p7->d.signed_and_enveloped->cert; crls = p7->d.signed_and_enveloped->crl; break; default: break; } if (certs != NULL) { X509 *x; for (i = 0; i < sk_X509_num(certs); i++) { x = sk_X509_value(certs, i); if (text) X509_print(out, x); else dump_cert_text(out, x); if (!noout) PEM_write_bio_X509(out, x); BIO_puts(out, "\n"); } } if (crls != NULL) { X509_CRL *crl; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); X509_CRL_print(out, crl); if (!noout) PEM_write_bio_X509_CRL(out, crl); BIO_puts(out, "\n"); } } ret = 0; goto end; } if (!noout) { if (outformat == FORMAT_ASN1) i = i2d_PKCS7_bio(out, p7); else if (outformat == FORMAT_PEM) i = PEM_write_bio_PKCS7(out, p7); else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write pkcs7 object\n"); ERR_print_errors(bio_err); goto end; } } ret = 0; end: PKCS7_free(p7); BIO_free(in); BIO_free_all(out); apps_shutdown(); OPENSSL_EXIT(ret); }
int crl_main(int argc, char **argv) { unsigned long nmflag = 0; X509_CRL *x = NULL; int ret = 1, i; BIO *out = NULL; X509_STORE *store = NULL; X509_STORE_CTX ctx; X509_LOOKUP *lookup = NULL; X509_OBJECT xobj; EVP_PKEY *pkey; const EVP_MD *digest; char *digest_name = NULL; if (single_execution) { if (pledge("stdio cpath wpath rpath", NULL) == -1) { perror("pledge"); exit(1); } } if (bio_out == NULL) { if ((bio_out = BIO_new(BIO_s_file())) != NULL) { BIO_set_fp(bio_out, stdout, BIO_NOCLOSE); } } digest = EVP_sha1(); memset(&crl_config, 0, sizeof(crl_config)); crl_config.informat = FORMAT_PEM; crl_config.outformat = FORMAT_PEM; if (options_parse(argc, argv, crl_options, &digest_name, NULL) != 0) { crl_usage(); goto end; } if (crl_config.cafile != NULL || crl_config.capath != NULL) crl_config.verify = 1; if (crl_config.nameopt != NULL) { if (set_name_ex(&nmflag, crl_config.nameopt) != 1) { fprintf(stderr, "Invalid -nameopt argument '%s'\n", crl_config.nameopt); goto end; } } if (digest_name != NULL) { if ((digest = EVP_get_digestbyname(digest_name)) == NULL) { fprintf(stderr, "Unknown message digest algorithm '%s'\n", digest_name); goto end; } } x = load_crl(crl_config.infile, crl_config.informat); if (x == NULL) goto end; if (crl_config.verify) { store = X509_STORE_new(); lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (lookup == NULL) goto end; if (!X509_LOOKUP_load_file(lookup, crl_config.cafile, X509_FILETYPE_PEM)) X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT); lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (lookup == NULL) goto end; if (!X509_LOOKUP_add_dir(lookup, crl_config.capath, X509_FILETYPE_PEM)) X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT); ERR_clear_error(); if (!X509_STORE_CTX_init(&ctx, store, NULL, NULL)) { BIO_printf(bio_err, "Error initialising X509 store\n"); goto end; } i = X509_STORE_get_by_subject(&ctx, X509_LU_X509, X509_CRL_get_issuer(x), &xobj); if (i <= 0) { BIO_printf(bio_err, "Error getting CRL issuer certificate\n"); goto end; } pkey = X509_get_pubkey(xobj.data.x509); X509_OBJECT_free_contents(&xobj); if (!pkey) { BIO_printf(bio_err, "Error getting CRL issuer public key\n"); goto end; } i = X509_CRL_verify(x, pkey); EVP_PKEY_free(pkey); if (i < 0) goto end; if (i == 0) BIO_printf(bio_err, "verify failure\n"); else BIO_printf(bio_err, "verify OK\n"); } /* Print requested information the order that the flags were given. */ for (i = 1; i <= argc; i++) { if (crl_config.issuer == i) { print_name(bio_out, "issuer=", X509_CRL_get_issuer(x), nmflag); } if (crl_config.crlnumber == i) { ASN1_INTEGER *crlnum; crlnum = X509_CRL_get_ext_d2i(x, NID_crl_number, NULL, NULL); BIO_printf(bio_out, "crlNumber="); if (crlnum) { i2a_ASN1_INTEGER(bio_out, crlnum); ASN1_INTEGER_free(crlnum); } else BIO_puts(bio_out, "<NONE>"); BIO_printf(bio_out, "\n"); } if (crl_config.hash == i) { BIO_printf(bio_out, "%08lx\n", X509_NAME_hash(X509_CRL_get_issuer(x))); } #ifndef OPENSSL_NO_MD5 if (crl_config.hash_old == i) { BIO_printf(bio_out, "%08lx\n", X509_NAME_hash_old(X509_CRL_get_issuer(x))); } #endif if (crl_config.lastupdate == i) { BIO_printf(bio_out, "lastUpdate="); ASN1_TIME_print(bio_out, X509_CRL_get_lastUpdate(x)); BIO_printf(bio_out, "\n"); } if (crl_config.nextupdate == i) { BIO_printf(bio_out, "nextUpdate="); if (X509_CRL_get_nextUpdate(x)) ASN1_TIME_print(bio_out, X509_CRL_get_nextUpdate(x)); else BIO_printf(bio_out, "NONE"); BIO_printf(bio_out, "\n"); } if (crl_config.fingerprint == i) { int j; unsigned int n; unsigned char md[EVP_MAX_MD_SIZE]; if (!X509_CRL_digest(x, digest, md, &n)) { BIO_printf(bio_err, "out of memory\n"); goto end; } BIO_printf(bio_out, "%s Fingerprint=", OBJ_nid2sn(EVP_MD_type(digest))); for (j = 0; j < (int) n; j++) { BIO_printf(bio_out, "%02X%c", md[j], (j + 1 == (int)n) ? '\n' : ':'); } } } out = BIO_new(BIO_s_file()); if (out == NULL) { ERR_print_errors(bio_err); goto end; } if (crl_config.outfile == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); } else { if (BIO_write_filename(out, crl_config.outfile) <= 0) { perror(crl_config.outfile); goto end; } } if (crl_config.text) X509_CRL_print(out, x); if (crl_config.noout) { ret = 0; goto end; } if (crl_config.outformat == FORMAT_ASN1) i = (int) i2d_X509_CRL_bio(out, x); else if (crl_config.outformat == FORMAT_PEM) i = PEM_write_bio_X509_CRL(out, x); else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write CRL\n"); goto end; } ret = 0; end: BIO_free_all(out); BIO_free_all(bio_out); bio_out = NULL; X509_CRL_free(x); if (store) { X509_STORE_CTX_cleanup(&ctx); X509_STORE_free(store); } return (ret); }
int MS_CALLBACK verify_callback(int ok, X509_STORE_CTX *ctx) { X509 *err_cert; int err, depth; err_cert = X509_STORE_CTX_get_current_cert(ctx); err = X509_STORE_CTX_get_error(ctx); depth = X509_STORE_CTX_get_error_depth(ctx); if (!verify_quiet || !ok) { BIO_printf(bio_err, "depth=%d ", depth); if (err_cert) { X509_NAME_print_ex(bio_err, X509_get_subject_name(err_cert), 0, XN_FLAG_ONELINE); BIO_puts(bio_err, "\n"); } else BIO_puts(bio_err, "<no cert>\n"); } if (!ok) { BIO_printf(bio_err, "verify error:num=%d:%s\n", err, X509_verify_cert_error_string(err)); if (verify_depth >= depth) { if (!verify_return_error) ok = 1; verify_error = X509_V_OK; } else { ok = 0; verify_error = X509_V_ERR_CERT_CHAIN_TOO_LONG; } } switch (err) { case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: BIO_puts(bio_err, "issuer= "); X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert), 0, XN_FLAG_ONELINE); BIO_puts(bio_err, "\n"); break; case X509_V_ERR_CERT_NOT_YET_VALID: case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: BIO_printf(bio_err, "notBefore="); ASN1_TIME_print(bio_err, X509_get_notBefore(err_cert)); BIO_printf(bio_err, "\n"); break; case X509_V_ERR_CERT_HAS_EXPIRED: case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: BIO_printf(bio_err, "notAfter="); ASN1_TIME_print(bio_err, X509_get_notAfter(err_cert)); BIO_printf(bio_err, "\n"); break; case X509_V_ERR_NO_EXPLICIT_POLICY: if (!verify_quiet) policies_print(bio_err, ctx); break; } if (err == X509_V_OK && ok == 2 && !verify_quiet) policies_print(bio_err, ctx); if (ok && !verify_quiet) BIO_printf(bio_err, "verify return:%d\n", ok); return (ok); }
int x509_main(int argc, char **argv) { int ret = 1; X509_REQ *req = NULL; X509 *x = NULL, *xca = NULL; ASN1_OBJECT *objtmp; STACK_OF(OPENSSL_STRING) *sigopts = NULL; EVP_PKEY *Upkey = NULL, *CApkey = NULL; ASN1_INTEGER *sno = NULL; int i, num, badops = 0; BIO *out = NULL; BIO *STDout = NULL; STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL; int informat, outformat, keyformat, CAformat, CAkeyformat; char *infile = NULL, *outfile = NULL, *keyfile = NULL, *CAfile = NULL; char *CAkeyfile = NULL, *CAserial = NULL; char *alias = NULL; int text = 0, serial = 0, subject = 0, issuer = 0, startdate = 0, enddate = 0; int next_serial = 0; int subject_hash = 0, issuer_hash = 0, ocspid = 0; #ifndef OPENSSL_NO_MD5 int subject_hash_old = 0, issuer_hash_old = 0; #endif int noout = 0, sign_flag = 0, CA_flag = 0, CA_createserial = 0, email = 0; int ocsp_uri = 0; int trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0, clrext = 0; int C = 0; int x509req = 0, days = DEF_DAYS, modulus = 0, pubkey = 0; int pprint = 0; const char **pp; X509_STORE *ctx = NULL; X509_REQ *rq = NULL; int fingerprint = 0; char buf[256]; const EVP_MD *md_alg, *digest = NULL; CONF *extconf = NULL; char *extsect = NULL, *extfile = NULL, *passin = NULL, *passargin = NULL; int checkend = 0, checkoffset = 0; unsigned long nmflag = 0, certflag = 0; const char *errstr = NULL; if (single_execution) { if (pledge("stdio rpath wpath cpath tty", NULL) == -1) { perror("pledge"); exit(1); } } reqfile = 0; STDout = BIO_new_fp(stdout, BIO_NOCLOSE); informat = FORMAT_PEM; outformat = FORMAT_PEM; keyformat = FORMAT_PEM; CAformat = FORMAT_PEM; CAkeyformat = FORMAT_PEM; ctx = X509_STORE_new(); if (ctx == NULL) goto end; X509_STORE_set_verify_cb(ctx, callb); argc--; argv++; num = 0; while (argc >= 1) { if (strcmp(*argv, "-inform") == 0) { if (--argc < 1) goto bad; informat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-outform") == 0) { if (--argc < 1) goto bad; outformat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-keyform") == 0) { if (--argc < 1) goto bad; keyformat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-req") == 0) { reqfile = 1; } else if (strcmp(*argv, "-CAform") == 0) { if (--argc < 1) goto bad; CAformat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-CAkeyform") == 0) { if (--argc < 1) goto bad; CAkeyformat = str2fmt(*(++argv)); } else if (strcmp(*argv, "-sigopt") == 0) { if (--argc < 1) goto bad; if (!sigopts) sigopts = sk_OPENSSL_STRING_new_null(); if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, *(++argv))) goto bad; } else if (strcmp(*argv, "-days") == 0) { if (--argc < 1) goto bad; days = strtonum(*(++argv), 1, INT_MAX, &errstr); if (errstr) { BIO_printf(bio_err, "bad number of days: %s\n", errstr); goto bad; } } else if (strcmp(*argv, "-passin") == 0) { if (--argc < 1) goto bad; passargin = *(++argv); } else if (strcmp(*argv, "-extfile") == 0) { if (--argc < 1) goto bad; extfile = *(++argv); } else if (strcmp(*argv, "-extensions") == 0) { if (--argc < 1) goto bad; extsect = *(++argv); } else if (strcmp(*argv, "-in") == 0) { if (--argc < 1) goto bad; infile = *(++argv); } else if (strcmp(*argv, "-out") == 0) { if (--argc < 1) goto bad; outfile = *(++argv); } else if (strcmp(*argv, "-signkey") == 0) { if (--argc < 1) goto bad; keyfile = *(++argv); sign_flag = ++num; } else if (strcmp(*argv, "-CA") == 0) { if (--argc < 1) goto bad; CAfile = *(++argv); CA_flag = ++num; } else if (strcmp(*argv, "-CAkey") == 0) { if (--argc < 1) goto bad; CAkeyfile = *(++argv); } else if (strcmp(*argv, "-CAserial") == 0) { if (--argc < 1) goto bad; CAserial = *(++argv); } else if (strcmp(*argv, "-set_serial") == 0) { if (--argc < 1) goto bad; ASN1_INTEGER_free(sno); if (!(sno = s2i_ASN1_INTEGER(NULL, *(++argv)))) goto bad; } else if (strcmp(*argv, "-addtrust") == 0) { if (--argc < 1) goto bad; if (!(objtmp = OBJ_txt2obj(*(++argv), 0))) { BIO_printf(bio_err, "Invalid trust object value %s\n", *argv); goto bad; } if (!trust) trust = sk_ASN1_OBJECT_new_null(); sk_ASN1_OBJECT_push(trust, objtmp); trustout = 1; } else if (strcmp(*argv, "-addreject") == 0) { if (--argc < 1) goto bad; if (!(objtmp = OBJ_txt2obj(*(++argv), 0))) { BIO_printf(bio_err, "Invalid reject object value %s\n", *argv); goto bad; } if (!reject) reject = sk_ASN1_OBJECT_new_null(); sk_ASN1_OBJECT_push(reject, objtmp); trustout = 1; } else if (strcmp(*argv, "-setalias") == 0) { if (--argc < 1) goto bad; alias = *(++argv); trustout = 1; } else if (strcmp(*argv, "-certopt") == 0) { if (--argc < 1) goto bad; if (!set_cert_ex(&certflag, *(++argv))) goto bad; } else if (strcmp(*argv, "-nameopt") == 0) { if (--argc < 1) goto bad; if (!set_name_ex(&nmflag, *(++argv))) goto bad; } else if (strcmp(*argv, "-C") == 0) C = ++num; else if (strcmp(*argv, "-email") == 0) email = ++num; else if (strcmp(*argv, "-ocsp_uri") == 0) ocsp_uri = ++num; else if (strcmp(*argv, "-serial") == 0) serial = ++num; else if (strcmp(*argv, "-next_serial") == 0) next_serial = ++num; else if (strcmp(*argv, "-modulus") == 0) modulus = ++num; else if (strcmp(*argv, "-pubkey") == 0) pubkey = ++num; else if (strcmp(*argv, "-x509toreq") == 0) x509req = ++num; else if (strcmp(*argv, "-text") == 0) text = ++num; else if (strcmp(*argv, "-hash") == 0 || strcmp(*argv, "-subject_hash") == 0) subject_hash = ++num; #ifndef OPENSSL_NO_MD5 else if (strcmp(*argv, "-subject_hash_old") == 0) subject_hash_old = ++num; #endif else if (strcmp(*argv, "-issuer_hash") == 0) issuer_hash = ++num; #ifndef OPENSSL_NO_MD5 else if (strcmp(*argv, "-issuer_hash_old") == 0) issuer_hash_old = ++num; #endif else if (strcmp(*argv, "-subject") == 0) subject = ++num; else if (strcmp(*argv, "-issuer") == 0) issuer = ++num; else if (strcmp(*argv, "-fingerprint") == 0) fingerprint = ++num; else if (strcmp(*argv, "-dates") == 0) { startdate = ++num; enddate = ++num; } else if (strcmp(*argv, "-purpose") == 0) pprint = ++num; else if (strcmp(*argv, "-startdate") == 0) startdate = ++num; else if (strcmp(*argv, "-enddate") == 0) enddate = ++num; else if (strcmp(*argv, "-checkend") == 0) { if (--argc < 1) goto bad; checkoffset = strtonum(*(++argv), 0, INT_MAX, &errstr); if (errstr) { BIO_printf(bio_err, "checkend unusable: %s\n", errstr); goto bad; } checkend = 1; } else if (strcmp(*argv, "-noout") == 0) noout = ++num; else if (strcmp(*argv, "-trustout") == 0) trustout = 1; else if (strcmp(*argv, "-clrtrust") == 0) clrtrust = ++num; else if (strcmp(*argv, "-clrreject") == 0) clrreject = ++num; else if (strcmp(*argv, "-alias") == 0) aliasout = ++num; else if (strcmp(*argv, "-CAcreateserial") == 0) CA_createserial = ++num; else if (strcmp(*argv, "-clrext") == 0) clrext = 1; else if (strcmp(*argv, "-ocspid") == 0) ocspid = ++num; else if ((md_alg = EVP_get_digestbyname(*argv + 1))) { /* ok */ digest = md_alg; } else { BIO_printf(bio_err, "unknown option %s\n", *argv); badops = 1; break; } argc--; argv++; } if (badops) { bad: for (pp = x509_usage; (*pp != NULL); pp++) BIO_printf(bio_err, "%s", *pp); goto end; } if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (!X509_STORE_set_default_paths(ctx)) { ERR_print_errors(bio_err); goto end; } if ((CAkeyfile == NULL) && (CA_flag) && (CAformat == FORMAT_PEM)) { CAkeyfile = CAfile; } else if ((CA_flag) && (CAkeyfile == NULL)) { BIO_printf(bio_err, "need to specify a CAkey if using the CA command\n"); goto end; } if (extfile) { long errorline = -1; X509V3_CTX ctx2; extconf = NCONF_new(NULL); if (!NCONF_load(extconf, extfile, &errorline)) { if (errorline <= 0) BIO_printf(bio_err, "error loading the config file '%s'\n", extfile); else BIO_printf(bio_err, "error on line %ld of config file '%s'\n", errorline, extfile); goto end; } if (!extsect) { extsect = NCONF_get_string(extconf, "default", "extensions"); if (!extsect) { ERR_clear_error(); extsect = "default"; } } X509V3_set_ctx_test(&ctx2); X509V3_set_nconf(&ctx2, extconf); if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL)) { BIO_printf(bio_err, "Error Loading extension section %s\n", extsect); ERR_print_errors(bio_err); goto end; } } if (reqfile) { EVP_PKEY *pkey; BIO *in; if (!sign_flag && !CA_flag) { BIO_printf(bio_err, "We need a private key to sign with\n"); goto end; } in = BIO_new(BIO_s_file()); if (in == NULL) { ERR_print_errors(bio_err); goto end; } if (infile == NULL) BIO_set_fp(in, stdin, BIO_NOCLOSE | BIO_FP_TEXT); else { if (BIO_read_filename(in, infile) <= 0) { perror(infile); BIO_free(in); goto end; } } req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL); BIO_free(in); if (req == NULL) { ERR_print_errors(bio_err); goto end; } if ((req->req_info == NULL) || (req->req_info->pubkey == NULL) || (req->req_info->pubkey->public_key == NULL) || (req->req_info->pubkey->public_key->data == NULL)) { BIO_printf(bio_err, "The certificate request appears to corrupted\n"); BIO_printf(bio_err, "It does not contain a public key\n"); goto end; } if ((pkey = X509_REQ_get_pubkey(req)) == NULL) { BIO_printf(bio_err, "error unpacking public key\n"); goto end; } i = X509_REQ_verify(req, pkey); EVP_PKEY_free(pkey); if (i < 0) { BIO_printf(bio_err, "Signature verification error\n"); ERR_print_errors(bio_err); goto end; } if (i == 0) { BIO_printf(bio_err, "Signature did not match the certificate request\n"); goto end; } else BIO_printf(bio_err, "Signature ok\n"); print_name(bio_err, "subject=", X509_REQ_get_subject_name(req), nmflag); if ((x = X509_new()) == NULL) goto end; if (sno == NULL) { sno = ASN1_INTEGER_new(); if (!sno || !rand_serial(NULL, sno)) goto end; if (!X509_set_serialNumber(x, sno)) goto end; ASN1_INTEGER_free(sno); sno = NULL; } else if (!X509_set_serialNumber(x, sno)) goto end; if (!X509_set_issuer_name(x, req->req_info->subject)) goto end; if (!X509_set_subject_name(x, req->req_info->subject)) goto end; X509_gmtime_adj(X509_get_notBefore(x), 0); X509_time_adj_ex(X509_get_notAfter(x), days, 0, NULL); pkey = X509_REQ_get_pubkey(req); X509_set_pubkey(x, pkey); EVP_PKEY_free(pkey); } else x = load_cert(bio_err, infile, informat, NULL, "Certificate"); if (x == NULL) goto end; if (CA_flag) { xca = load_cert(bio_err, CAfile, CAformat, NULL, "CA Certificate"); if (xca == NULL) goto end; } if (!noout || text || next_serial) { OBJ_create("2.99999.3", "SET.ex3", "SET x509v3 extension 3"); out = BIO_new(BIO_s_file()); if (out == NULL) { ERR_print_errors(bio_err); goto end; } if (outfile == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); } else { if (BIO_write_filename(out, outfile) <= 0) { perror(outfile); goto end; } } } if (alias) X509_alias_set1(x, (unsigned char *) alias, -1); if (clrtrust) X509_trust_clear(x); if (clrreject) X509_reject_clear(x); if (trust) { for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) { objtmp = sk_ASN1_OBJECT_value(trust, i); X509_add1_trust_object(x, objtmp); } } if (reject) { for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) { objtmp = sk_ASN1_OBJECT_value(reject, i); X509_add1_reject_object(x, objtmp); } } if (num) { for (i = 1; i <= num; i++) { if (issuer == i) { print_name(STDout, "issuer= ", X509_get_issuer_name(x), nmflag); } else if (subject == i) { print_name(STDout, "subject= ", X509_get_subject_name(x), nmflag); } else if (serial == i) { BIO_printf(STDout, "serial="); i2a_ASN1_INTEGER(STDout, X509_get_serialNumber(x)); BIO_printf(STDout, "\n"); } else if (next_serial == i) { BIGNUM *bnser; ASN1_INTEGER *ser; ser = X509_get_serialNumber(x); bnser = ASN1_INTEGER_to_BN(ser, NULL); if (!bnser) goto end; if (!BN_add_word(bnser, 1)) goto end; ser = BN_to_ASN1_INTEGER(bnser, NULL); if (!ser) goto end; BN_free(bnser); i2a_ASN1_INTEGER(out, ser); ASN1_INTEGER_free(ser); BIO_puts(out, "\n"); } else if ((email == i) || (ocsp_uri == i)) { int j; STACK_OF(OPENSSL_STRING) *emlst; if (email == i) emlst = X509_get1_email(x); else emlst = X509_get1_ocsp(x); for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++) BIO_printf(STDout, "%s\n", sk_OPENSSL_STRING_value(emlst, j)); X509_email_free(emlst); } else if (aliasout == i) { unsigned char *alstr; alstr = X509_alias_get0(x, NULL); if (alstr) BIO_printf(STDout, "%s\n", alstr); else BIO_puts(STDout, "<No Alias>\n"); } else if (subject_hash == i) { BIO_printf(STDout, "%08lx\n", X509_subject_name_hash(x)); } #ifndef OPENSSL_NO_MD5 else if (subject_hash_old == i) { BIO_printf(STDout, "%08lx\n", X509_subject_name_hash_old(x)); } #endif else if (issuer_hash == i) { BIO_printf(STDout, "%08lx\n", X509_issuer_name_hash(x)); } #ifndef OPENSSL_NO_MD5 else if (issuer_hash_old == i) { BIO_printf(STDout, "%08lx\n", X509_issuer_name_hash_old(x)); } #endif else if (pprint == i) { X509_PURPOSE *ptmp; int j; BIO_printf(STDout, "Certificate purposes:\n"); for (j = 0; j < X509_PURPOSE_get_count(); j++) { ptmp = X509_PURPOSE_get0(j); purpose_print(STDout, x, ptmp); } } else if (modulus == i) { EVP_PKEY *pkey; pkey = X509_get_pubkey(x); if (pkey == NULL) { BIO_printf(bio_err, "Modulus=unavailable\n"); ERR_print_errors(bio_err); goto end; } BIO_printf(STDout, "Modulus="); if (pkey->type == EVP_PKEY_RSA) BN_print(STDout, pkey->pkey.rsa->n); else if (pkey->type == EVP_PKEY_DSA) BN_print(STDout, pkey->pkey.dsa->pub_key); else BIO_printf(STDout, "Wrong Algorithm type"); BIO_printf(STDout, "\n"); EVP_PKEY_free(pkey); } else if (pubkey == i) { EVP_PKEY *pkey; pkey = X509_get_pubkey(x); if (pkey == NULL) { BIO_printf(bio_err, "Error getting public key\n"); ERR_print_errors(bio_err); goto end; } PEM_write_bio_PUBKEY(STDout, pkey); EVP_PKEY_free(pkey); } else if (C == i) { unsigned char *d; char *m; int y, z; X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof buf); BIO_printf(STDout, "/* subject:%s */\n", buf); m = X509_NAME_oneline( X509_get_issuer_name(x), buf, sizeof buf); BIO_printf(STDout, "/* issuer :%s */\n", buf); z = i2d_X509(x, NULL); m = malloc(z); if (m == NULL) { BIO_printf(bio_err, "out of mem\n"); goto end; } d = (unsigned char *) m; z = i2d_X509_NAME(X509_get_subject_name(x), &d); BIO_printf(STDout, "unsigned char XXX_subject_name[%d]={\n", z); d = (unsigned char *) m; for (y = 0; y < z; y++) { BIO_printf(STDout, "0x%02X,", d[y]); if ((y & 0x0f) == 0x0f) BIO_printf(STDout, "\n"); } if (y % 16 != 0) BIO_printf(STDout, "\n"); BIO_printf(STDout, "};\n"); z = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &d); BIO_printf(STDout, "unsigned char XXX_public_key[%d]={\n", z); d = (unsigned char *) m; for (y = 0; y < z; y++) { BIO_printf(STDout, "0x%02X,", d[y]); if ((y & 0x0f) == 0x0f) BIO_printf(STDout, "\n"); } if (y % 16 != 0) BIO_printf(STDout, "\n"); BIO_printf(STDout, "};\n"); z = i2d_X509(x, &d); BIO_printf(STDout, "unsigned char XXX_certificate[%d]={\n", z); d = (unsigned char *) m; for (y = 0; y < z; y++) { BIO_printf(STDout, "0x%02X,", d[y]); if ((y & 0x0f) == 0x0f) BIO_printf(STDout, "\n"); } if (y % 16 != 0) BIO_printf(STDout, "\n"); BIO_printf(STDout, "};\n"); free(m); } else if (text == i) { X509_print_ex(STDout, x, nmflag, certflag); } else if (startdate == i) { BIO_puts(STDout, "notBefore="); ASN1_TIME_print(STDout, X509_get_notBefore(x)); BIO_puts(STDout, "\n"); } else if (enddate == i) { BIO_puts(STDout, "notAfter="); ASN1_TIME_print(STDout, X509_get_notAfter(x)); BIO_puts(STDout, "\n"); } else if (fingerprint == i) { int j; unsigned int n; unsigned char md[EVP_MAX_MD_SIZE]; const EVP_MD *fdig = digest; if (!fdig) fdig = EVP_sha1(); if (!X509_digest(x, fdig, md, &n)) { BIO_printf(bio_err, "out of memory\n"); goto end; } BIO_printf(STDout, "%s Fingerprint=", OBJ_nid2sn(EVP_MD_type(fdig))); for (j = 0; j < (int) n; j++) { BIO_printf(STDout, "%02X%c", md[j], (j + 1 == (int)n) ? '\n' : ':'); } } /* should be in the library */ else if ((sign_flag == i) && (x509req == 0)) { BIO_printf(bio_err, "Getting Private key\n"); if (Upkey == NULL) { Upkey = load_key(bio_err, keyfile, keyformat, 0, passin, "Private key"); if (Upkey == NULL) goto end; } if (!sign(x, Upkey, days, clrext, digest, extconf, extsect)) goto end; } else if (CA_flag == i) { BIO_printf(bio_err, "Getting CA Private Key\n"); if (CAkeyfile != NULL) { CApkey = load_key(bio_err, CAkeyfile, CAkeyformat, 0, passin, "CA Private Key"); if (CApkey == NULL) goto end; } if (!x509_certify(ctx, CAfile, digest, x, xca, CApkey, sigopts, CAserial, CA_createserial, days, clrext, extconf, extsect, sno)) goto end; } else if (x509req == i) { EVP_PKEY *pk; BIO_printf(bio_err, "Getting request Private Key\n"); if (keyfile == NULL) { BIO_printf(bio_err, "no request key file specified\n"); goto end; } else { pk = load_key(bio_err, keyfile, keyformat, 0, passin, "request key"); if (pk == NULL) goto end; } BIO_printf(bio_err, "Generating certificate request\n"); rq = X509_to_X509_REQ(x, pk, digest); EVP_PKEY_free(pk); if (rq == NULL) { ERR_print_errors(bio_err); goto end; } if (!noout) { X509_REQ_print(out, rq); PEM_write_bio_X509_REQ(out, rq); } noout = 1; } else if (ocspid == i) { X509_ocspid_print(out, x); } } } if (checkend) { time_t tcheck = time(NULL) + checkoffset; if (X509_cmp_time(X509_get_notAfter(x), &tcheck) < 0) { BIO_printf(out, "Certificate will expire\n"); ret = 1; } else { BIO_printf(out, "Certificate will not expire\n"); ret = 0; } goto end; } if (noout) { ret = 0; goto end; } if (outformat == FORMAT_ASN1) i = i2d_X509_bio(out, x); else if (outformat == FORMAT_PEM) { if (trustout) i = PEM_write_bio_X509_AUX(out, x); else i = PEM_write_bio_X509(out, x); } else if (outformat == FORMAT_NETSCAPE) { NETSCAPE_X509 nx; ASN1_OCTET_STRING hdr; hdr.data = (unsigned char *) NETSCAPE_CERT_HDR; hdr.length = strlen(NETSCAPE_CERT_HDR); nx.header = &hdr; nx.cert = x; i = ASN1_item_i2d_bio(ASN1_ITEM_rptr(NETSCAPE_X509), out, &nx); } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write certificate\n"); ERR_print_errors(bio_err); goto end; } ret = 0; end: OBJ_cleanup(); NCONF_free(extconf); BIO_free_all(out); BIO_free_all(STDout); X509_STORE_free(ctx); X509_REQ_free(req); X509_free(x); X509_free(xca); EVP_PKEY_free(Upkey); EVP_PKEY_free(CApkey); if (sigopts) sk_OPENSSL_STRING_free(sigopts); X509_REQ_free(rq); ASN1_INTEGER_free(sno); sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free); sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free); free(passin); return (ret); }
static int util_verbose(ENGINE * e, int verbose, BIO * bio_out, const char *indent) { static const int line_wrap = 78; int num; int ret = 0; char *name = NULL; char *desc = NULL; int flags; int xpos = 0; STACK_OF(OPENSSL_STRING) * cmds = NULL; if (!ENGINE_ctrl(e, ENGINE_CTRL_HAS_CTRL_FUNCTION, 0, NULL, NULL) || ((num = ENGINE_ctrl(e, ENGINE_CTRL_GET_FIRST_CMD_TYPE, 0, NULL, NULL)) <= 0)) { #if 0 BIO_printf(bio_out, "%s<no control commands>\n", indent); #endif return 1; } cmds = sk_OPENSSL_STRING_new_null(); if (!cmds) goto err; do { int len; /* Get the command input flags */ if ((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, num, NULL, NULL)) < 0) goto err; if (!(flags & ENGINE_CMD_FLAG_INTERNAL) || verbose >= 4) { /* Get the command name */ if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_LEN_FROM_CMD, num, NULL, NULL)) <= 0) goto err; if ((name = malloc(len + 1)) == NULL) goto err; if (ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_FROM_CMD, num, name, NULL) <= 0) goto err; /* Get the command description */ if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_LEN_FROM_CMD, num, NULL, NULL)) < 0) goto err; if (len > 0) { if ((desc = malloc(len + 1)) == NULL) goto err; if (ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_FROM_CMD, num, desc, NULL) <= 0) goto err; } /* Now decide on the output */ if (xpos == 0) /* Do an indent */ xpos = BIO_puts(bio_out, indent); else /* Otherwise prepend a ", " */ xpos += BIO_printf(bio_out, ", "); if (verbose == 1) { /* We're just listing names, comma-delimited */ if ((xpos > (int) strlen(indent)) && (xpos + (int) strlen(name) > line_wrap)) { BIO_printf(bio_out, "\n"); xpos = BIO_puts(bio_out, indent); } xpos += BIO_printf(bio_out, "%s", name); } else { /* We're listing names plus descriptions */ BIO_printf(bio_out, "%s: %s\n", name, (desc == NULL) ? "<no description>" : desc); /* ... and sometimes input flags */ if ((verbose >= 3) && !util_flags(bio_out, flags, indent)) goto err; xpos = 0; } } free(name); name = NULL; if (desc) { free(desc); desc = NULL; } /* Move to the next command */ num = ENGINE_ctrl(e, ENGINE_CTRL_GET_NEXT_CMD_TYPE, num, NULL, NULL); } while (num > 0); if (xpos > 0) BIO_printf(bio_out, "\n"); ret = 1; err: if (cmds) sk_OPENSSL_STRING_pop_free(cmds, identity); if (name) free(name); if (desc) free(desc); return ret; }
int MAIN(int argc, char **argv) { ENGINE *e = NULL; char **args, *outfile = NULL; char *passarg = NULL; BIO *in = NULL, *out = NULL; const EVP_CIPHER *cipher = NULL; int outformat; int text = 0; EVP_PKEY *pkey=NULL; EVP_PKEY_CTX *ctx = NULL; char *pass = NULL; int badarg = 0; int ret = 1, rv; int do_param = 0; if (bio_err == NULL) bio_err = BIO_new_fp (OPENSSL_TYPE__FILE_STDERR, BIO_NOCLOSE); if (!load_config(bio_err, NULL)) goto end; outformat=FORMAT_PEM; ERR_load_crypto_strings(); OpenSSL_add_all_algorithms(); args = argv + 1; while (!badarg && *args && *args[0] == '-') { if (!TINYCLR_SSL_STRCMP(*args,"-outform")) { if (args[1]) { args++; outformat=str2fmt(*args); } else badarg = 1; } else if (!TINYCLR_SSL_STRCMP(*args,"-pass")) { if (!args[1]) goto bad; passarg= *(++args); } #ifndef OPENSSL_NO_ENGINE else if (TINYCLR_SSL_STRCMP(*args,"-engine") == 0) { if (!args[1]) goto bad; e = setup_engine(bio_err, *(++args), 0); } #endif else if (!TINYCLR_SSL_STRCMP (*args, "-paramfile")) { if (!args[1]) goto bad; args++; if (do_param == 1) goto bad; if (!init_keygen_file(bio_err, &ctx, *args, e)) goto end; } else if (!TINYCLR_SSL_STRCMP (*args, "-out")) { if (args[1]) { args++; outfile = *args; } else badarg = 1; } else if (TINYCLR_SSL_STRCMP(*args,"-algorithm") == 0) { if (!args[1]) goto bad; if (!init_gen_str(bio_err, &ctx, *(++args),e, do_param)) goto end; } else if (TINYCLR_SSL_STRCMP(*args,"-pkeyopt") == 0) { if (!args[1]) goto bad; if (!ctx) { BIO_puts(bio_err, "No keytype specified\n"); goto bad; } else if (pkey_ctrl_string(ctx, *(++args)) <= 0) { BIO_puts(bio_err, "parameter setting error\n"); ERR_print_errors(bio_err); goto end; } } else if (TINYCLR_SSL_STRCMP(*args,"-genparam") == 0) { if (ctx) goto bad; do_param = 1; } else if (TINYCLR_SSL_STRCMP(*args,"-text") == 0) text=1; else { cipher = EVP_get_cipherbyname(*args + 1); if (!cipher) { BIO_printf(bio_err, "Unknown cipher %s\n", *args + 1); badarg = 1; } if (do_param == 1) badarg = 1; } args++; } if (!ctx) badarg = 1; if (badarg) { bad: BIO_printf(bio_err, "Usage: genpkey [options]\n"); BIO_printf(bio_err, "where options may be\n"); BIO_printf(bio_err, "-out file output file\n"); BIO_printf(bio_err, "-outform X output format (DER or PEM)\n"); BIO_printf(bio_err, "-pass arg output file pass phrase source\n"); BIO_printf(bio_err, "-<cipher> use cipher <cipher> to encrypt the key\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, "-engine e use engine e, possibly a hardware device.\n"); #endif BIO_printf(bio_err, "-paramfile file parameters file\n"); BIO_printf(bio_err, "-algorithm alg the public key algorithm\n"); BIO_printf(bio_err, "-pkeyopt opt:value set the public key algorithm option <opt>\n" " to value <value>\n"); BIO_printf(bio_err, "-genparam generate parameters, not key\n"); BIO_printf(bio_err, "-text print the in text\n"); BIO_printf(bio_err, "NB: options order may be important! See the manual page.\n"); goto end; } if (!app_passwd(bio_err, passarg, NULL, &pass, NULL)) { BIO_puts(bio_err, "Error getting password\n"); goto end; } if (outfile) { if (!(out = BIO_new_file (outfile, "wb"))) { BIO_printf(bio_err, "Can't open output file %s\n", outfile); goto end; } } else { out = BIO_new_fp (OPENSSL_TYPE__FILE_STDOUT, BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } EVP_PKEY_CTX_set_cb(ctx, genpkey_cb); EVP_PKEY_CTX_set_app_data(ctx, bio_err); if (do_param) { if (EVP_PKEY_paramgen(ctx, &pkey) <= 0) { BIO_puts(bio_err, "Error generating parameters\n"); ERR_print_errors(bio_err); goto end; } } else { if (EVP_PKEY_keygen(ctx, &pkey) <= 0) { BIO_puts(bio_err, "Error generating key\n"); ERR_print_errors(bio_err); goto end; } } if (do_param) rv = PEM_write_bio_Parameters(out, pkey); else if (outformat == FORMAT_PEM) rv = PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0, NULL, pass); else if (outformat == FORMAT_ASN1) rv = i2d_PrivateKey_bio(out, pkey); else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } if (rv <= 0) { BIO_puts(bio_err, "Error writing key\n"); ERR_print_errors(bio_err); } if (text) { if (do_param) rv = EVP_PKEY_print_params(out, pkey, 0, NULL); else rv = EVP_PKEY_print_private(out, pkey, 0, NULL); if (rv <= 0) { BIO_puts(bio_err, "Error printing key\n"); ERR_print_errors(bio_err); } } ret = 0; end: if (pkey) EVP_PKEY_free(pkey); if (ctx) EVP_PKEY_CTX_free(ctx); if (out) BIO_free_all(out); BIO_free(in); if (pass) OPENSSL_free(pass); return ret; }
int OCSP_RESPONSE_print(BIO *bp, OCSP_RESPONSE *o, unsigned long flags) { int i, ret = 0; long l; OCSP_CERTID *cid = NULL; OCSP_BASICRESP *br = NULL; OCSP_RESPID *rid = NULL; OCSP_RESPDATA *rd = NULL; OCSP_CERTSTATUS *cst = NULL; OCSP_REVOKEDINFO *rev = NULL; OCSP_SINGLERESP *single = NULL; OCSP_RESPBYTES *rb = o->responseBytes; if (BIO_puts(bp, "OCSP Response Data:\n") <= 0) goto err; l = ASN1_ENUMERATED_get(o->responseStatus); if (BIO_printf(bp, " OCSP Response Status: %s (0x%lx)\n", OCSP_response_status_str(l), l) <= 0) goto err; if (rb == NULL) return 1; if (BIO_puts(bp, " Response Type: ") <= 0) goto err; if (i2a_ASN1_OBJECT(bp, rb->responseType) <= 0) goto err; if (OBJ_obj2nid(rb->responseType) != NID_id_pkix_OCSP_basic) { BIO_puts(bp, " (unknown response type)\n"); return 1; } i = ASN1_STRING_length(rb->response); if (!(br = OCSP_response_get1_basic(o))) goto err; rd = br->tbsResponseData; l = ASN1_INTEGER_get(rd->version); if (BIO_printf(bp, "\n Version: %lu (0x%lx)\n", l + 1, l) <= 0) goto err; if (BIO_puts(bp, " Responder Id: ") <= 0) goto err; rid = rd->responderId; switch (rid->type) { case V_OCSP_RESPID_NAME: X509_NAME_print_ex(bp, rid->value.byName, 0, XN_FLAG_ONELINE); break; case V_OCSP_RESPID_KEY: i2a_ASN1_STRING(bp, rid->value.byKey, V_ASN1_OCTET_STRING); break; } if (BIO_printf(bp, "\n Produced At: ") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, rd->producedAt)) goto err; if (BIO_printf(bp, "\n Responses:\n") <= 0) goto err; for (i = 0; i < sk_OCSP_SINGLERESP_num(rd->responses); i++) { if (!sk_OCSP_SINGLERESP_value(rd->responses, i)) continue; single = sk_OCSP_SINGLERESP_value(rd->responses, i); cid = single->certId; if (ocsp_certid_print(bp, cid, 4) <= 0) goto err; cst = single->certStatus; if (BIO_printf(bp, " Cert Status: %s", OCSP_cert_status_str(cst->type)) <= 0) goto err; if (cst->type == V_OCSP_CERTSTATUS_REVOKED) { rev = cst->value.revoked; if (BIO_printf(bp, "\n Revocation Time: ") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, rev->revocationTime)) goto err; if (rev->revocationReason) { l = ASN1_ENUMERATED_get(rev->revocationReason); if (BIO_printf(bp, "\n Revocation Reason: %s (0x%lx)", OCSP_crl_reason_str(l), l) <= 0) goto err; } } if (BIO_printf(bp, "\n This Update: ") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, single->thisUpdate)) goto err; if (single->nextUpdate) { if (BIO_printf(bp, "\n Next Update: ") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, single->nextUpdate)) goto err; } if (BIO_write(bp, "\n", 1) <= 0) goto err; if (!X509V3_extensions_print(bp, "Response Single Extensions", single->singleExtensions, flags, 8)) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (!X509V3_extensions_print(bp, "Response Extensions", rd->responseExtensions, flags, 4)) goto err; if (X509_signature_print(bp, br->signatureAlgorithm, br->signature) <= 0) goto err; for (i = 0; i < sk_X509_num(br->certs); i++) { X509_print(bp, sk_X509_value(br->certs, i)); PEM_write_bio_X509(bp, sk_X509_value(br->certs, i)); } ret = 1; err: OCSP_BASICRESP_free(br); return ret; }
return NULL; #endif } int main(void) { unsigned char *abuf = NULL; //const EC_POINT *public_key; int i, alen, aout, jj = 0; int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct sockaddr_in my_addr; // my address information struct sockaddr_in their_addr; // connector's address information socklen_t sin_size; int yes = 1, numbytes; char buf[MAXDATASIZE]; /*//////////////////////////////////////////////////////////////Generating Keys/////////////////////////////////////*/ BN_CTX *ctx = NULL; int nid; BIO *out; CRYPTO_malloc_debug_init(); CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); const char *text = "NIST Prime-Curve P-192"; #ifdef OPENSSL_SYS_WIN32 CRYPTO_malloc_init(); #endif RAND_seed(rnd_seed, sizeof rnd_seed); out = BIO_new(BIO_s_file()); if (out == NULL) EXIT(1); BIO_set_fp(out, stdout, BIO_NOCLOSE); if ((ctx = BN_CTX_new()) == NULL) goto err; nid = NID_X9_62_prime192v1; EC_KEY *a = NULL; //EC_KEY is a structure BIGNUM *x_a = NULL, *y_a = NULL; const BIGNUM *BIG = NULL; char *buff; //unsigned char *abuf=NULL,*bbuf=NULL; const EC_GROUP *group; a = EC_KEY_new_by_curve_name(nid); if (a == NULL) goto err; group = EC_KEY_get0_group(a); // aa=EC_POINT_new(group); if ((x_a = BN_new()) == NULL) goto err; //BN_new returns a pointer to the bignum if ((y_a = BN_new()) == NULL) goto err; // if ((BIG=BN_new()) == NULL) goto err; BIO_puts(out, "Testing key generation with "); BIO_puts(out, text); if (!EC_KEY_generate_key(a)) goto err; printf("\n1 ) generating keys\n"); if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field) { if (!EC_POINT_get_affine_coordinates_GFp(group, EC_KEY_get0_public_key(a), x_a, y_a, ctx)) goto err; } //returns the public key else { if (!EC_POINT_get_affine_coordinates_GF2m(group, EC_KEY_get0_public_key(a), x_a, y_a, ctx)) goto err; } BIO_puts(out, " pri 1="); BN_print(out, EC_KEY_get0_private_key(a)); BIO_puts(out, "\n pub 1="); BN_print(out, x_a); BIO_puts(out, ","); BN_print(out, y_a); BIO_puts(out, "\n"); /* printf("importnt work\n"); //BN_print(out,x_a); buff=BN_bn2dec(x_a); printf("%s\n",buff); BN_dec2bn(&(x_a),buff); printf("%s\n",buff); BN_print(out,x_a); */ /*//////////////////////////////////////////////////////////////////////////////////////////////////////////////////*/ if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); exit(1); } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } my_addr.sin_family = AF_INET; // host byte order my_addr.sin_port = htons(MYPORT); // short, network byte order my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP memset(my_addr.sin_zero, '\0', sizeof my_addr.sin_zero); if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof my_addr) == -1) { perror("bind"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } while (1) { // main accept() loop sin_size = sizeof their_addr; if ((new_fd = accept(sockfd, (struct sockaddr *) &their_addr, &sin_size)) == -1) { perror("accept"); continue; } printf("server: got connection from %s\n", inet_ntoa(their_addr.sin_addr)); if (send(new_fd, "Hello, world!\n", 14, 0) == -1) perror("send"); // BN_print(out,x_a); // if ((jj=send(new_fd, &aa, sizeof(BIGNUM), 0)) == -1) // perror("send"); ////////////////////////////////////////////////////////////////////////////// //printf("side %d\n",sizeof(EC_POINT*)); //aa= EC_KEY_get0_public_key(a); //printf("side %d\n",sizeof(aa)); // if ((jj=send(new_fd, &aa, sizeof(EC_POINT*), 0)) == -1) //perror("send"); //printf("\nbytes send %d\n",jj); //////////////////////////////////////////////////////////////////////////////// //x_a=(BIGNUM*)&buff; //BN_print(out,x_a); //printf("%d",sizeof(EC_POINT)); //buff=(char*)&x_a; //if (send(new_fd, &x_a, sizeof(x_a), 0) == -1) //perror("send"); //buff[10]='\0'; //BIG =EC_KEY_get0_private_key(a); //BN_print(out,BIG); /* buff=BN_bn2dec(x_a); // BN_print(out,BIG); buff=(char*)&x_a; //buff[10]='\0'; printf("%s\n",buff); x_a=(BIGNUM*)&buff; BN_dec2bn(&(y_a),buff); printf("%s",buff); */ //sprintf(buff,"%u",EC_KEY_get0_private_key(a)); //printf("send: %d\n",BIG); //printf("%s",buff); //printf("%d",strlen(buff)); // float data1; //char data2[64]; //BIG=(BIGNUM*)(buff); //BIO_puts(out,BIG); //memcpy((void*)buff, (void*)EC_KEY_get0_private_key(a), 20); //printf("%s",buff); //for (i=0; i<10; i++) //{ //printf("%c",buff[i]); //BIO_puts(out,buff); //} //if (send(new_fd,buff,strlen(buff), 0) == -1) // { // perror("send"); // } //printf("\npublic key send\n"); /* //EC_POINT *bb; if ((numbytes=recv(new_fd,(char*)&bb,500, 0)) == -1) { perror("recv"); exit(1); } printf("\npublic key received\n"); */ /* if ((numbytes=recv(new_fd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv"); exit(1); } */ // buf[numbytes] = '\0'; /* printf("Received: %d",numbytes); printf("working\n"); alen=KDF1_SHA1_len; ///it is a static constant integer. printf("working\n"); abuf=(unsigned char *)OPENSSL_malloc(alen); printf("working\n"); if(abuf==NULL || bb==NULL || a==NULL) printf("i hate you error\n"); aout=ECDH_compute_key(abuf,alen,bb,a,KDF1_SHA1); //generating session key printf("working\n"); // BN_print(out, abuf); //BIO_puts(out,"\n"); BIO_puts(out," key1 ="); for (i=0; i<aout; i++) { sprintf(buf,"%02X",abuf[i]); BIO_puts(out,buf); } BIO_puts(out,"\n"); */ close(new_fd); exit(0); close(new_fd); // parent doesn't need this } err: ERR_print_errors_fp(stderr); if (x_a) BN_free(x_a); if (y_a) BN_free(y_a); if (a) EC_KEY_free(a); if (ctx) BN_CTX_free(ctx); BIO_free(out); CRYPTO_cleanup_all_ex_data(); ERR_remove_state(0);
int proxy_puts (BIO *b, const char *str) { return BIO_puts (b->next_bio, str); }
static int http_serve(SSL *ssl, int s) { char buf[BUFSIZZ]; int r,len; BIO *io,*ssl_bio; io=BIO_new(BIO_f_buffer()); ssl_bio=BIO_new(BIO_f_ssl()); BIO_set_ssl(ssl_bio,ssl,BIO_CLOSE); BIO_push(io,ssl_bio); while(1){ r=BIO_gets(io,buf,BUFSIZZ-1); switch(SSL_get_error(ssl,r)){ case SSL_ERROR_NONE: len=r; break; case SSL_ERROR_ZERO_RETURN: goto shutdown; break; default: berr_exit("SSL read problem"); } /* Look for the blank line that signals the end of the HTTP headers */ if(!strcmp(buf,"\r\n") || !strcmp(buf,"\n")) break; } /* Now perform renegotiation if requested */ if(client_auth==CLIENT_AUTH_REHANDSHAKE){ SSL_set_verify(ssl,SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,0); /* Stop the client from just resuming the un-authenticated session */ SSL_set_session_id_context(ssl, (void *)&s_server_auth_session_id_context, sizeof(s_server_auth_session_id_context)); if(SSL_renegotiate(ssl)<=0) berr_exit("SSL renegotiation error"); if(SSL_do_handshake(ssl)<=0) berr_exit("SSL renegotiation error"); ssl->state=SSL_ST_ACCEPT; if(SSL_do_handshake(ssl)<=0) berr_exit("SSL renegotiation error"); } if((r=BIO_puts (io,"HTTP/1.0 200 OK\r\n"))<=0) err_exit("Write error"); if((r=BIO_puts (io,"Server: EKRServer\r\n\r\n"))<=0) err_exit("Write error"); if((r=BIO_puts (io,"Server test page\r\n"))<=0) err_exit("Write error"); if((r=BIO_flush(io))<0) err_exit("Error flushing BIO"); shutdown: r=SSL_shutdown(ssl); if(!r){ /* If we called SSL_shutdown() first then we always get return value of '0'. In this case, try again, but first send a TCP FIN to trigger the other side's close_notify*/ shutdown(s,1); r=SSL_shutdown(ssl); } switch(r){ case 1: break; /* Success */ case 0: case -1: default: berr_exit("Shutdown failed"); } SSL_free(ssl); close(s); return(0); }
int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflags, unsigned long cflag) { long l; int i; EVP_PKEY *pkey; STACK_OF(X509_EXTENSION) *exts; char mlch = ' '; int nmindent = 0; if ((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) { mlch = '\n'; nmindent = 12; } if (nmflags == X509_FLAG_COMPAT) nmindent = 16; if (!(cflag & X509_FLAG_NO_HEADER)) { if (BIO_write(bp, "Certificate Request:\n", 21) <= 0) goto err; if (BIO_write(bp, " Data:\n", 10) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_VERSION)) { l = X509_REQ_get_version(x); if (BIO_printf(bp, "%8sVersion: %ld (0x%lx)\n", "", l + 1, l) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_SUBJECT)) { if (BIO_printf(bp, " Subject:%c", mlch) <= 0) goto err; if (X509_NAME_print_ex(bp, X509_REQ_get_subject_name(x), nmindent, nmflags) < 0) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_PUBKEY)) { X509_PUBKEY *xpkey; ASN1_OBJECT *koid; if (BIO_write(bp, " Subject Public Key Info:\n", 33) <= 0) goto err; if (BIO_printf(bp, "%12sPublic Key Algorithm: ", "") <= 0) goto err; xpkey = X509_REQ_get_X509_PUBKEY(x); X509_PUBKEY_get0_param(&koid, NULL, NULL, NULL, xpkey); if (i2a_ASN1_OBJECT(bp, koid) <= 0) goto err; if (BIO_puts(bp, "\n") <= 0) goto err; pkey = X509_REQ_get_pubkey(x); if (pkey == NULL) { BIO_printf(bp, "%12sUnable to load Public Key\n", ""); ERR_print_errors(bp); } else { EVP_PKEY_print_public(bp, pkey, 16, NULL); EVP_PKEY_free(pkey); } } if (!(cflag & X509_FLAG_NO_ATTRIBUTES)) { /* may not be */ if (BIO_printf(bp, "%8sAttributes:\n", "") <= 0) goto err; if (X509_REQ_get_attr_count(x) == 0) { if (BIO_printf(bp, "%12sa0:00\n", "") <= 0) goto err; } else { for (i = 0; i < X509_REQ_get_attr_count(x); i++) { ASN1_TYPE *at; X509_ATTRIBUTE *a; ASN1_BIT_STRING *bs = NULL; ASN1_OBJECT *aobj; int j, type = 0, count = 1, ii = 0; a = X509_REQ_get_attr(x, i); aobj = X509_ATTRIBUTE_get0_object(a); if (X509_REQ_extension_nid(OBJ_obj2nid(aobj))) continue; if (BIO_printf(bp, "%12s", "") <= 0) goto err; if ((j = i2a_ASN1_OBJECT(bp, aobj)) > 0) { ii = 0; count = X509_ATTRIBUTE_count(a); get_next: at = X509_ATTRIBUTE_get0_type(a, ii); type = at->type; bs = at->value.asn1_string; } for (j = 25 - j; j > 0; j--) if (BIO_write(bp, " ", 1) != 1) goto err; if (BIO_puts(bp, ":") <= 0) goto err; if ((type == V_ASN1_PRINTABLESTRING) || (type == V_ASN1_T61STRING) || (type == V_ASN1_IA5STRING)) { if (BIO_write(bp, (char *)bs->data, bs->length) != bs->length) goto err; BIO_puts(bp, "\n"); } else { BIO_puts(bp, "unable to print attribute\n"); } if (++ii < count) goto get_next; } } } if (!(cflag & X509_FLAG_NO_EXTENSIONS)) { exts = X509_REQ_get_extensions(x); if (exts) { BIO_printf(bp, "%8sRequested Extensions:\n", ""); for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) { ASN1_OBJECT *obj; X509_EXTENSION *ex; int j; ex = sk_X509_EXTENSION_value(exts, i); if (BIO_printf(bp, "%12s", "") <= 0) goto err; obj = X509_EXTENSION_get_object(ex); i2a_ASN1_OBJECT(bp, obj); j = X509_EXTENSION_get_critical(ex); if (BIO_printf(bp, ": %s\n", j ? "critical" : "") <= 0) goto err; if (!X509V3_EXT_print(bp, ex, cflag, 16)) { BIO_printf(bp, "%16s", ""); ASN1_STRING_print(bp, X509_EXTENSION_get_data(ex)); } if (BIO_write(bp, "\n", 1) <= 0) goto err; } sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); } } if (!(cflag & X509_FLAG_NO_SIGDUMP)) { X509_ALGOR *sig_alg; ASN1_BIT_STRING *sig; X509_REQ_get0_signature(&sig, &sig_alg, x); if (!X509_signature_print(bp, sig_alg, sig)) goto err; } return (1); err: X509err(X509_F_X509_REQ_PRINT_EX, ERR_R_BUF_LIB); return (0); }
static int ssl_print_extension(BIO *bio, int indent, int server, int extype, const unsigned char *ext, size_t extlen) { size_t xlen; BIO_indent(bio, indent, 80); BIO_printf(bio, "extension_type=%s(%d), length=%d\n", ssl_trace_str(extype, ssl_exts_tbl), extype, (int)extlen); switch (extype) { case TLSEXT_TYPE_ec_point_formats: if (extlen < 1) return 0; xlen = ext[0]; if (extlen != xlen + 1) return 0; return ssl_trace_list(bio, indent + 2, ext + 1, xlen, 1, ssl_point_tbl); case TLSEXT_TYPE_elliptic_curves: if (extlen < 2) return 0; xlen = (ext[0] << 8) | ext[1]; if (extlen != xlen + 2) return 0; return ssl_trace_list(bio, indent + 2, ext + 2, xlen, 2, ssl_curve_tbl); case TLSEXT_TYPE_signature_algorithms: if (extlen < 2) return 0; xlen = (ext[0] << 8) | ext[1]; if (extlen != xlen + 2) return 0; if (xlen & 1) return 0; ext += 2; while (xlen > 0) { BIO_indent(bio, indent + 2, 80); BIO_printf(bio, "%s+%s (%d+%d)\n", ssl_trace_str(ext[0], ssl_md_tbl), ssl_trace_str(ext[1], ssl_sig_tbl), ext[0], ext[1]); xlen -= 2; ext += 2; } break; case TLSEXT_TYPE_renegotiate: if (extlen < 1) return 0; xlen = ext[0]; if (xlen + 1 != extlen) return 0; ext++; if (xlen) { if (server) { if (xlen & 1) return 0; xlen >>= 1; } ssl_print_hex(bio, indent + 4, "client_verify_data", ext, xlen); if (server) { ext += xlen; ssl_print_hex(bio, indent + 4, "server_verify_data", ext, xlen); } } else { BIO_indent(bio, indent + 4, 80); BIO_puts(bio, "<EMPTY>\n"); } break; case TLSEXT_TYPE_heartbeat: if (extlen != 1) return 0; BIO_indent(bio, indent + 2, 80); BIO_printf(bio, "HeartbeatMode: %s\n", ssl_trace_str(ext[0], ssl_hb_tbl)); break; case TLSEXT_TYPE_session_ticket: if (extlen != 0) ssl_print_hex(bio, indent + 4, "ticket", ext, extlen); break; default: BIO_dump_indent(bio, (char *)ext, extlen, indent + 2); }
int main(int argc, char **argv) { BIO *sbio = NULL, *out = NULL; int i, len, rv; char tmpbuf[1024]; SSL_CTX *ctx = NULL; SSL_CONF_CTX *cctx = NULL; SSL *ssl = NULL; CONF *conf = NULL; STACK_OF(CONF_VALUE) *sect = NULL; CONF_VALUE *cnf; const char *connect_str = "localhost:4433"; long errline = -1; ERR_load_crypto_strings(); ERR_load_SSL_strings(); SSL_library_init(); conf = NCONF_new(NULL); if (NCONF_load(conf, "connect.cnf", &errline) <= 0) { if (errline <= 0) fprintf(stderr, "Error processing config file\n"); else fprintf(stderr, "Error on line %ld\n", errline); goto end; } sect = NCONF_get_section(conf, "default"); if (sect == NULL) { fprintf(stderr, "Error retrieving default section\n"); goto end; } ctx = SSL_CTX_new(SSLv23_client_method()); cctx = SSL_CONF_CTX_new(); SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT); SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE); SSL_CONF_CTX_set_ssl_ctx(cctx, ctx); for (i = 0; i < sk_CONF_VALUE_num(sect); i++) { cnf = sk_CONF_VALUE_value(sect, i); rv = SSL_CONF_cmd(cctx, cnf->name, cnf->value); if (rv > 0) continue; if (rv != -2) { fprintf(stderr, "Error processing %s = %s\n", cnf->name, cnf->value); ERR_print_errors_fp(stderr); goto end; } if (!strcmp(cnf->name, "Connect")) { connect_str = cnf->value; } else { fprintf(stderr, "Unknown configuration option %s\n", cnf->name); goto end; } } if (!SSL_CONF_CTX_finish(cctx)) { fprintf(stderr, "Finish error\n"); ERR_print_errors_fp(stderr); goto err; } /* * We'd normally set some stuff like the verify paths and * mode here * because as things stand this will connect to * any server whose * certificate is signed by any CA. */ sbio = BIO_new_ssl_connect(ctx); BIO_get_ssl(sbio, &ssl); if (!ssl) { fprintf(stderr, "Can't locate SSL pointer\n"); goto end; } /* Don't want any retries */ SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY); /* We might want to do other things with ssl here */ BIO_set_conn_hostname(sbio, connect_str); out = BIO_new_fp(stdout, BIO_NOCLOSE); if (BIO_do_connect(sbio) <= 0) { fprintf(stderr, "Error connecting to server\n"); ERR_print_errors_fp(stderr); goto end; } if (BIO_do_handshake(sbio) <= 0) { fprintf(stderr, "Error establishing SSL connection\n"); ERR_print_errors_fp(stderr); goto end; } /* Could examine ssl here to get connection info */ BIO_puts(sbio, "GET / HTTP/1.0\n\n"); for (;;) { len = BIO_read(sbio, tmpbuf, 1024); if (len <= 0) break; BIO_write(out, tmpbuf, len); } end: SSL_CONF_CTX_free(cctx); BIO_free_all(sbio); BIO_free(out); NCONF_free(conf); return 0; }
int main(int argc, char *argv[]) { BN_GENCB _cb; DH *a; DH *b=NULL; char buf[12]; unsigned char *abuf=NULL,*bbuf=NULL; int i,alen,blen,aout,bout,ret=1; BIO *out; CRYPTO_malloc_debug_init(); CRYPTO_dbg_set_options(V_CRYPTO_MDEBUG_ALL); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); #ifdef OPENSSL_SYS_WIN32 CRYPTO_malloc_init(); #endif RAND_seed(rnd_seed, sizeof rnd_seed); out=BIO_new(BIO_s_file()); if (out == NULL) EXIT(1); BIO_set_fp(out,stdout,BIO_NOCLOSE); BN_GENCB_set(&_cb, &cb, out); if(((a = DH_new()) == NULL) || !DH_generate_parameters_ex(a, 64, DH_GENERATOR_5, &_cb)) goto err; if (!DH_check(a, &i)) goto err; if (i & DH_CHECK_P_NOT_PRIME) BIO_puts(out, "p value is not prime\n"); if (i & DH_CHECK_P_NOT_SAFE_PRIME) BIO_puts(out, "p value is not a safe prime\n"); if (i & DH_UNABLE_TO_CHECK_GENERATOR) BIO_puts(out, "unable to check the generator value\n"); if (i & DH_NOT_SUITABLE_GENERATOR) BIO_puts(out, "the g value is not a generator\n"); BIO_puts(out,"\np ="); BN_print(out,a->p); BIO_puts(out,"\ng ="); BN_print(out,a->g); BIO_puts(out,"\n"); b=DH_new(); if (b == NULL) goto err; b->p=BN_dup(a->p); b->g=BN_dup(a->g); if ((b->p == NULL) || (b->g == NULL)) goto err; /* Set a to run with normal modexp and b to use constant time */ a->flags &= ~DH_FLAG_NO_EXP_CONSTTIME; b->flags |= DH_FLAG_NO_EXP_CONSTTIME; if (!DH_generate_key(a)) goto err; BIO_puts(out,"pri 1="); BN_print(out,a->priv_key); BIO_puts(out,"\npub 1="); BN_print(out,a->pub_key); BIO_puts(out,"\n"); if (!DH_generate_key(b)) goto err; BIO_puts(out,"pri 2="); BN_print(out,b->priv_key); BIO_puts(out,"\npub 2="); BN_print(out,b->pub_key); BIO_puts(out,"\n"); alen=DH_size(a); abuf=(unsigned char *)OPENSSL_malloc(alen); aout=DH_compute_key(abuf,b->pub_key,a); BIO_puts(out,"key1 ="); for (i=0; i<aout; i++) { op_sprintf(buf,"%02X",abuf[i]); BIO_puts(out,buf); } BIO_puts(out,"\n"); blen=DH_size(b); bbuf=(unsigned char *)OPENSSL_malloc(blen); bout=DH_compute_key(bbuf,a->pub_key,b); BIO_puts(out,"key2 ="); for (i=0; i<bout; i++) { op_sprintf(buf,"%02X",bbuf[i]); BIO_puts(out,buf); } BIO_puts(out,"\n"); if ((aout < 4) || (bout != aout) || (op_memcmp(abuf,bbuf,aout) != 0)) { fprintf(stderr,"Error in DH routines\n"); ret=1; } else ret=0; err: ERR_print_errors_fp(stderr); if (abuf != NULL) OPENSSL_free(abuf); if (bbuf != NULL) OPENSSL_free(bbuf); if(b != NULL) DH_free(b); if(a != NULL) DH_free(a); BIO_free(out); #ifdef OPENSSL_SYS_NETWARE if (ret) printf("ERROR: %d\n", ret); #endif EXIT(ret); return(ret); }
int MAIN(int argc, char **argv) { int ret=1,i; int verbose=0; const char **pp; const char *p; int badops=0; SSL_CTX *ctx=NULL; SSL *ssl=NULL; char *ciphers=NULL; SSL_METHOD *meth=NULL; STACK_OF(SSL_CIPHER) *sk; char buf[512]; BIO *STDout=NULL; #if !defined(OPENSSL_NO_SSL2) && !defined(OPENSSL_NO_SSL3) meth=SSLv23_server_method(); #elif !defined(OPENSSL_NO_SSL3) meth=SSLv3_server_method(); #elif !defined(OPENSSL_NO_SSL2) meth=SSLv2_server_method(); #endif apps_startup(); if (bio_err == NULL) bio_err=BIO_new_fp(stderr,BIO_NOCLOSE); STDout=BIO_new_fp(stdout,BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); STDout = BIO_push(tmpbio, STDout); } #endif argc--; argv++; while (argc >= 1) { if (strcmp(*argv,"-v") == 0) verbose=1; #ifndef OPENSSL_NO_SSL2 else if (strcmp(*argv,"-ssl2") == 0) meth=SSLv2_client_method(); #endif #ifndef OPENSSL_NO_SSL3 else if (strcmp(*argv,"-ssl3") == 0) meth=SSLv3_client_method(); #endif #ifndef OPENSSL_NO_TLS1 else if (strcmp(*argv,"-tls1") == 0) meth=TLSv1_client_method(); #endif else if ((strncmp(*argv,"-h",2) == 0) || (strcmp(*argv,"-?") == 0)) { badops=1; break; } else { ciphers= *argv; } argc--; argv++; } if (badops) { for (pp=ciphers_usage; (*pp != NULL); pp++) BIO_printf(bio_err,"%s",*pp); goto end; } OpenSSL_add_ssl_algorithms(); ctx=SSL_CTX_new(meth); if (ctx == NULL) goto err; if (ciphers != NULL) { if(!SSL_CTX_set_cipher_list(ctx,ciphers)) { BIO_printf(bio_err, "Error in cipher list\n"); goto err; } } ssl=SSL_new(ctx); if (ssl == NULL) goto err; if (!verbose) { for (i=0; ; i++) { p=SSL_get_cipher_list(ssl,i); if (p == NULL) break; if (i != 0) BIO_printf(STDout,":"); BIO_printf(STDout,"%s",p); } BIO_printf(STDout,"\n"); } else { sk=SSL_get_ciphers(ssl); for (i=0; i<sk_SSL_CIPHER_num(sk); i++) { BIO_puts(STDout,SSL_CIPHER_description( sk_SSL_CIPHER_value(sk,i), buf,sizeof buf)); } } ret=0; if (0) { err: SSL_load_error_strings(); ERR_print_errors(bio_err); } end: if (ctx != NULL) SSL_CTX_free(ctx); if (ssl != NULL) SSL_free(ssl); if (STDout != NULL) BIO_free_all(STDout); apps_shutdown(); OPENSSL_EXIT(ret); }
int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, unsigned long cflag) { long l; int ret = 0, i; char *m = NULL, mlch = ' '; int nmindent = 0; ASN1_INTEGER *bs; EVP_PKEY *pkey = NULL; const char *neg; if ((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) { mlch = '\n'; nmindent = 12; } if (nmflags == X509_FLAG_COMPAT) nmindent = 16; if (!(cflag & X509_FLAG_NO_HEADER)) { if (BIO_write(bp, "Certificate:\n", 13) <= 0) goto err; if (BIO_write(bp, " Data:\n", 10) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_VERSION)) { l = X509_get_version(x); if (l >= 0 && l <= 2) { if (BIO_printf(bp, "%8sVersion: %ld (0x%lx)\n", "", l + 1, (unsigned long)l) <= 0) goto err; } else { if (BIO_printf(bp, "%8sVersion: Unknown (%ld)\n", "", l) <= 0) goto err; } } if (!(cflag & X509_FLAG_NO_SERIAL)) { if (BIO_write(bp, " Serial Number:", 22) <= 0) goto err; bs = X509_get_serialNumber(x); if (bs->length <= (int)sizeof(long)) { ERR_set_mark(); l = ASN1_INTEGER_get(bs); ERR_pop_to_mark(); } else { l = -1; } if (l != -1) { unsigned long ul; if (bs->type == V_ASN1_NEG_INTEGER) { ul = 0 - (unsigned long)l; neg = "-"; } else { ul = l; neg = ""; } if (BIO_printf(bp, " %s%lu (%s0x%lx)\n", neg, ul, neg, ul) <= 0) goto err; } else { neg = (bs->type == V_ASN1_NEG_INTEGER) ? " (Negative)" : ""; if (BIO_printf(bp, "\n%12s%s", "", neg) <= 0) goto err; for (i = 0; i < bs->length; i++) { if (BIO_printf(bp, "%02x%c", bs->data[i], ((i + 1 == bs->length) ? '\n' : ':')) <= 0) goto err; } } } if (!(cflag & X509_FLAG_NO_SIGNAME)) { const X509_ALGOR *tsig_alg = X509_get0_tbs_sigalg(x); if (X509_signature_print(bp, tsig_alg, NULL) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_ISSUER)) { if (BIO_printf(bp, " Issuer:%c", mlch) <= 0) goto err; if (X509_NAME_print_ex(bp, X509_get_issuer_name(x), nmindent, nmflags) < 0) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_VALIDITY)) { if (BIO_write(bp, " Validity\n", 17) <= 0) goto err; if (BIO_write(bp, " Not Before: ", 24) <= 0) goto err; if (!ASN1_TIME_print(bp, X509_get0_notBefore(x))) goto err; if (BIO_write(bp, "\n Not After : ", 25) <= 0) goto err; if (!ASN1_TIME_print(bp, X509_get0_notAfter(x))) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_SUBJECT)) { if (BIO_printf(bp, " Subject:%c", mlch) <= 0) goto err; if (X509_NAME_print_ex (bp, X509_get_subject_name(x), nmindent, nmflags) < 0) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_PUBKEY)) { X509_PUBKEY *xpkey = X509_get_X509_PUBKEY(x); ASN1_OBJECT *xpoid; X509_PUBKEY_get0_param(&xpoid, NULL, NULL, NULL, xpkey); if (BIO_write(bp, " Subject Public Key Info:\n", 33) <= 0) goto err; if (BIO_printf(bp, "%12sPublic Key Algorithm: ", "") <= 0) goto err; if (i2a_ASN1_OBJECT(bp, xpoid) <= 0) goto err; if (BIO_puts(bp, "\n") <= 0) goto err; pkey = X509_get0_pubkey(x); if (pkey == NULL) { BIO_printf(bp, "%12sUnable to load Public Key\n", ""); ERR_print_errors(bp); } else { EVP_PKEY_print_public(bp, pkey, 16, NULL); } } if (!(cflag & X509_FLAG_NO_IDS)) { const ASN1_BIT_STRING *iuid, *suid; X509_get0_uids(x, &iuid, &suid); if (iuid != NULL) { if (BIO_printf(bp, "%8sIssuer Unique ID: ", "") <= 0) goto err; if (!X509_signature_dump(bp, iuid, 12)) goto err; } if (suid != NULL) { if (BIO_printf(bp, "%8sSubject Unique ID: ", "") <= 0) goto err; if (!X509_signature_dump(bp, suid, 12)) goto err; } } if (!(cflag & X509_FLAG_NO_EXTENSIONS)) X509V3_extensions_print(bp, "X509v3 extensions", X509_get0_extensions(x), cflag, 8); if (!(cflag & X509_FLAG_NO_SIGDUMP)) { const X509_ALGOR *sig_alg; const ASN1_BIT_STRING *sig; X509_get0_signature(&sig, &sig_alg, x); if (X509_signature_print(bp, sig_alg, sig) <= 0) goto err; } if (!(cflag & X509_FLAG_NO_AUX)) { if (!X509_aux_print(bp, x, 0)) goto err; } ret = 1; err: OPENSSL_free(m); return ret; }
int rand_main(int argc, char **argv) { ENGINE *e = NULL; BIO *out = NULL; char *outfile = NULL, *prog; OPTION_CHOICE o; int format = FORMAT_BINARY, i, num = -1, r, ret = 1; prog = opt_init(argc, argv, rand_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(rand_options); ret = 0; goto end; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_BASE64: format = FORMAT_BASE64; break; case OPT_HEX: format = FORMAT_TEXT; break; } } argc = opt_num_rest(); argv = opt_rest(); if (argc != 1 || !opt_int(argv[0], &num) || num < 0) goto opthelp; out = bio_open_default(outfile, 'w', format); if (out == NULL) goto end; if (format == FORMAT_BASE64) { BIO *b64 = BIO_new(BIO_f_base64()); if (b64 == NULL) goto end; out = BIO_push(b64, out); } while (num > 0) { unsigned char buf[4096]; int chunk; chunk = num; if (chunk > (int)sizeof(buf)) chunk = sizeof buf; r = RAND_bytes(buf, chunk); if (r <= 0) goto end; if (format != FORMAT_TEXT) { if (BIO_write(out, buf, chunk) != chunk) goto end; } else { for (i = 0; i < chunk; i++) if (BIO_printf(out, "%02x", buf[i]) != 2) goto end; } num -= chunk; } if (format == FORMAT_TEXT) BIO_puts(out, "\n"); if (BIO_flush(out) <= 0) goto end; ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); release_engine(e); BIO_free_all(out); return (ret); }
int MAIN(int argc, char **argv) { unsigned long nmflag = 0; X509_CRL *x=NULL; char *CAfile = NULL, *CApath = NULL; int ret=1,i,num,badops=0; BIO *out=NULL; int informat,outformat; char *infile=NULL,*outfile=NULL; int hash=0,issuer=0,lastupdate=0,nextupdate=0,noout=0,text=0; int fingerprint = 0, crlnumber = 0; const char **pp; X509_STORE *store = NULL; X509_STORE_CTX ctx; X509_LOOKUP *lookup = NULL; X509_OBJECT xobj; EVP_PKEY *pkey; int do_ver = 0; const EVP_MD *md_alg,*digest=EVP_sha1(); apps_startup(); if (bio_err == NULL) if ((bio_err=BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; if (bio_out == NULL) if ((bio_out=BIO_new(BIO_s_file())) != NULL) { BIO_set_fp(bio_out,stdout,BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); bio_out = BIO_push(tmpbio, bio_out); } #endif } informat=FORMAT_PEM; outformat=FORMAT_PEM; argc--; argv++; num=0; while (argc >= 1) { #ifdef undef if (strcmp(*argv,"-p") == 0) { if (--argc < 1) goto bad; if (!args_from_file(++argv,Nargc,Nargv)) { goto end; }*/ } #endif if (strcmp(*argv,"-inform") == 0) { if (--argc < 1) goto bad; informat=str2fmt(*(++argv)); } else if (strcmp(*argv,"-outform") == 0) { if (--argc < 1) goto bad; outformat=str2fmt(*(++argv)); } else if (strcmp(*argv,"-in") == 0) { if (--argc < 1) goto bad; infile= *(++argv); } else if (strcmp(*argv,"-out") == 0) { if (--argc < 1) goto bad; outfile= *(++argv); } else if (strcmp(*argv,"-CApath") == 0) { if (--argc < 1) goto bad; CApath = *(++argv); do_ver = 1; } else if (strcmp(*argv,"-CAfile") == 0) { if (--argc < 1) goto bad; CAfile = *(++argv); do_ver = 1; } else if (strcmp(*argv,"-verify") == 0) do_ver = 1; else if (strcmp(*argv,"-text") == 0) text = 1; else if (strcmp(*argv,"-hash") == 0) hash= ++num; else if (strcmp(*argv,"-nameopt") == 0) { if (--argc < 1) goto bad; if (!set_name_ex(&nmflag, *(++argv))) goto bad; } else if (strcmp(*argv,"-issuer") == 0) issuer= ++num; else if (strcmp(*argv,"-lastupdate") == 0) lastupdate= ++num; else if (strcmp(*argv,"-nextupdate") == 0) nextupdate= ++num; else if (strcmp(*argv,"-noout") == 0) noout= ++num; else if (strcmp(*argv,"-fingerprint") == 0) fingerprint= ++num; else if (strcmp(*argv,"-crlnumber") == 0) crlnumber= ++num; else if ((md_alg=EVP_get_digestbyname(*argv + 1))) { /* ok */ digest=md_alg; } else { BIO_printf(bio_err,"unknown option %s\n",*argv); badops=1; break; } argc--; argv++; } if (badops) { bad: for (pp=crl_usage; (*pp != NULL); pp++) BIO_printf(bio_err,"%s",*pp); goto end; } ERR_load_crypto_strings(); x=load_crl(infile,informat); if (x == NULL) { goto end; } if(do_ver) { store = X509_STORE_new(); lookup=X509_STORE_add_lookup(store,X509_LOOKUP_file()); if (lookup == NULL) goto end; if (!X509_LOOKUP_load_file(lookup,CAfile,X509_FILETYPE_PEM)) X509_LOOKUP_load_file(lookup,NULL,X509_FILETYPE_DEFAULT); lookup=X509_STORE_add_lookup(store,X509_LOOKUP_hash_dir()); if (lookup == NULL) goto end; if (!X509_LOOKUP_add_dir(lookup,CApath,X509_FILETYPE_PEM)) X509_LOOKUP_add_dir(lookup,NULL,X509_FILETYPE_DEFAULT); ERR_clear_error(); if(!X509_STORE_CTX_init(&ctx, store, NULL, NULL)) { BIO_printf(bio_err, "Error initialising X509 store\n"); goto end; } i = X509_STORE_get_by_subject(&ctx, X509_LU_X509, X509_CRL_get_issuer(x), &xobj); if(i <= 0) { BIO_printf(bio_err, "Error getting CRL issuer certificate\n"); goto end; } pkey = X509_get_pubkey(xobj.data.x509); X509_OBJECT_free_contents(&xobj); if(!pkey) { BIO_printf(bio_err, "Error getting CRL issuer public key\n"); goto end; } i = X509_CRL_verify(x, pkey); EVP_PKEY_free(pkey); if(i < 0) goto end; if(i == 0) BIO_printf(bio_err, "verify failure\n"); else BIO_printf(bio_err, "verify OK\n"); } if (num) { for (i=1; i<=num; i++) { if (issuer == i) { print_name(bio_out, "issuer=", X509_CRL_get_issuer(x), nmflag); } if (crlnumber == i) { ASN1_INTEGER *crlnum; crlnum = X509_CRL_get_ext_d2i(x, NID_crl_number, NULL, NULL); BIO_printf(bio_out,"crlNumber="); if (crlnum) { i2a_ASN1_INTEGER(bio_out, crlnum); ASN1_INTEGER_free(crlnum); } else BIO_puts(bio_out, "<NONE>"); BIO_printf(bio_out,"\n"); } if (hash == i) { BIO_printf(bio_out,"%08lx\n", X509_NAME_hash(X509_CRL_get_issuer(x))); } if (lastupdate == i) { BIO_printf(bio_out,"lastUpdate="); ASN1_TIME_print(bio_out, X509_CRL_get_lastUpdate(x)); BIO_printf(bio_out,"\n"); } if (nextupdate == i) { BIO_printf(bio_out,"nextUpdate="); if (X509_CRL_get_nextUpdate(x)) ASN1_TIME_print(bio_out, X509_CRL_get_nextUpdate(x)); else BIO_printf(bio_out,"NONE"); BIO_printf(bio_out,"\n"); } if (fingerprint == i) { int j; unsigned int n; unsigned char md[EVP_MAX_MD_SIZE]; if (!X509_CRL_digest(x,digest,md,&n)) { BIO_printf(bio_err,"out of memory\n"); goto end; } BIO_printf(bio_out,"%s Fingerprint=", OBJ_nid2sn(EVP_MD_type(digest))); for (j=0; j<(int)n; j++) { BIO_printf(bio_out,"%02X%c",md[j], (j+1 == (int)n) ?'\n':':'); } } } } out=BIO_new(BIO_s_file()); if (out == NULL) { ERR_print_errors(bio_err); goto end; } if (outfile == NULL) { BIO_set_fp(out,stdout,BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } else { if (BIO_write_filename(out,outfile) <= 0) { perror(outfile); goto end; } } if (text) X509_CRL_print(out, x); if (noout) { ret = 0; goto end; } if (outformat == FORMAT_ASN1) i=(int)i2d_X509_CRL_bio(out,x); else if (outformat == FORMAT_PEM) i=PEM_write_bio_X509_CRL(out,x); else { BIO_printf(bio_err,"bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err,"unable to write CRL\n"); goto end; } ret=0; end: BIO_free_all(out); BIO_free_all(bio_out); bio_out=NULL; X509_CRL_free(x); if(store) { X509_STORE_CTX_cleanup(&ctx); X509_STORE_free(store); } apps_shutdown(); OPENSSL_EXIT(ret); }
int sess_id_main(int argc, char **argv) { SSL_SESSION *x = NULL; X509 *peer = NULL; int ret = 1, i; BIO *out = NULL; memset(&sess_id_config, 0, sizeof(sess_id_config)); sess_id_config.informat = FORMAT_PEM; sess_id_config.outformat = FORMAT_PEM; if (options_parse(argc, argv, sess_id_options, NULL, NULL) != 0) { sess_id_usage(); return (1); } x = load_sess_id(sess_id_config.infile, sess_id_config.informat); if (x == NULL) { goto end; } peer = SSL_SESSION_get0_peer(x); if (sess_id_config.context) { size_t ctx_len = strlen(sess_id_config.context); if (ctx_len > SSL_MAX_SID_CTX_LENGTH) { BIO_printf(bio_err, "Context too long\n"); goto end; } SSL_SESSION_set1_id_context(x, (unsigned char *)sess_id_config.context, ctx_len); } if (!sess_id_config.noout || sess_id_config.text) { out = BIO_new(BIO_s_file()); if (out == NULL) { ERR_print_errors(bio_err); goto end; } if (sess_id_config.outfile == NULL) { BIO_set_fp(out, stdout, BIO_NOCLOSE); } else { if (BIO_write_filename(out, sess_id_config.outfile) <= 0) { perror(sess_id_config.outfile); goto end; } } } if (sess_id_config.text) { SSL_SESSION_print(out, x); if (sess_id_config.cert) { if (peer == NULL) BIO_puts(out, "No certificate present\n"); else X509_print(out, peer); } } if (!sess_id_config.noout && !sess_id_config.cert) { if (sess_id_config.outformat == FORMAT_ASN1) i = i2d_SSL_SESSION_bio(out, x); else if (sess_id_config.outformat == FORMAT_PEM) i = PEM_write_bio_SSL_SESSION(out, x); else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write SSL_SESSION\n"); goto end; } } else if (!sess_id_config.noout && (peer != NULL)) { /* just print the certificate */ if (sess_id_config.outformat == FORMAT_ASN1) i = (int) i2d_X509_bio(out, peer); else if (sess_id_config.outformat == FORMAT_PEM) i = PEM_write_bio_X509(out, peer); else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write X509\n"); goto end; } } ret = 0; end: BIO_free_all(out); SSL_SESSION_free(x); return (ret); }
int x509_main(int argc, char **argv) { ASN1_INTEGER *sno = NULL; ASN1_OBJECT *objtmp = NULL; BIO *out = NULL; CONF *extconf = NULL; EVP_PKEY *Upkey = NULL, *CApkey = NULL, *fkey = NULL; STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL; STACK_OF(OPENSSL_STRING) *sigopts = NULL; X509 *x = NULL, *xca = NULL; X509_REQ *req = NULL, *rq = NULL; X509_STORE *ctx = NULL; const EVP_MD *digest = NULL; char *CAkeyfile = NULL, *CAserial = NULL, *fkeyfile = NULL, *alias = NULL; char *checkhost = NULL, *checkemail = NULL, *checkip = NULL; char *extsect = NULL, *extfile = NULL, *passin = NULL, *passinarg = NULL; char *infile = NULL, *outfile = NULL, *keyfile = NULL, *CAfile = NULL; char buf[256], *prog; int x509req = 0, days = DEF_DAYS, modulus = 0, pubkey = 0, pprint = 0; int C = 0, CAformat = FORMAT_PEM, CAkeyformat = FORMAT_PEM; int fingerprint = 0, reqfile = 0, need_rand = 0, checkend = 0; int informat = FORMAT_PEM, outformat = FORMAT_PEM, keyformat = FORMAT_PEM; int next_serial = 0, subject_hash = 0, issuer_hash = 0, ocspid = 0; int noout = 0, sign_flag = 0, CA_flag = 0, CA_createserial = 0, email = 0; int ocsp_uri = 0, trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0; int ret = 1, i, num = 0, badsig = 0, clrext = 0, nocert = 0; int text = 0, serial = 0, subject = 0, issuer = 0, startdate = 0; int enddate = 0; time_t checkoffset = 0; unsigned long nmflag = 0, certflag = 0; char nmflag_set = 0; OPTION_CHOICE o; ENGINE *e = NULL; #ifndef OPENSSL_NO_MD5 int subject_hash_old = 0, issuer_hash_old = 0; #endif ctx = X509_STORE_new(); if (ctx == NULL) goto end; X509_STORE_set_verify_cb(ctx, callb); prog = opt_init(argc, argv, x509_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(x509_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &outformat)) goto opthelp; break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &keyformat)) goto opthelp; break; case OPT_CAFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &CAformat)) goto opthelp; break; case OPT_CAKEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &CAkeyformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_REQ: reqfile = need_rand = 1; break; case OPT_SIGOPT: if (!sigopts) sigopts = sk_OPENSSL_STRING_new_null(); if (!sigopts || !sk_OPENSSL_STRING_push(sigopts, opt_arg())) goto opthelp; break; case OPT_DAYS: days = atoi(opt_arg()); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_EXTFILE: extfile = opt_arg(); break; case OPT_EXTENSIONS: extsect = opt_arg(); break; case OPT_SIGNKEY: keyfile = opt_arg(); sign_flag = ++num; need_rand = 1; break; case OPT_CA: CAfile = opt_arg(); CA_flag = ++num; need_rand = 1; break; case OPT_CAKEY: CAkeyfile = opt_arg(); break; case OPT_CASERIAL: CAserial = opt_arg(); break; case OPT_SET_SERIAL: if (sno != NULL) { BIO_printf(bio_err, "Serial number supplied twice\n"); goto opthelp; } if ((sno = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL) goto opthelp; break; case OPT_FORCE_PUBKEY: fkeyfile = opt_arg(); break; case OPT_ADDTRUST: if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) { BIO_printf(bio_err, "%s: Invalid trust object value %s\n", prog, opt_arg()); goto opthelp; } if (trust == NULL && (trust = sk_ASN1_OBJECT_new_null()) == NULL) goto end; sk_ASN1_OBJECT_push(trust, objtmp); objtmp = NULL; trustout = 1; break; case OPT_ADDREJECT: if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) { BIO_printf(bio_err, "%s: Invalid reject object value %s\n", prog, opt_arg()); goto opthelp; } if (reject == NULL && (reject = sk_ASN1_OBJECT_new_null()) == NULL) goto end; sk_ASN1_OBJECT_push(reject, objtmp); objtmp = NULL; trustout = 1; break; case OPT_SETALIAS: alias = opt_arg(); trustout = 1; break; case OPT_CERTOPT: if (!set_cert_ex(&certflag, opt_arg())) goto opthelp; break; case OPT_NAMEOPT: nmflag_set = 1; if (!set_name_ex(&nmflag, opt_arg())) goto opthelp; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_C: C = ++num; break; case OPT_EMAIL: email = ++num; break; case OPT_OCSP_URI: ocsp_uri = ++num; break; case OPT_SERIAL: serial = ++num; break; case OPT_NEXT_SERIAL: next_serial = ++num; break; case OPT_MODULUS: modulus = ++num; break; case OPT_PUBKEY: pubkey = ++num; break; case OPT_X509TOREQ: x509req = ++num; break; case OPT_TEXT: text = ++num; break; case OPT_SUBJECT: subject = ++num; break; case OPT_ISSUER: issuer = ++num; break; case OPT_FINGERPRINT: fingerprint = ++num; break; case OPT_HASH: subject_hash = ++num; break; case OPT_ISSUER_HASH: issuer_hash = ++num; break; case OPT_PURPOSE: pprint = ++num; break; case OPT_STARTDATE: startdate = ++num; break; case OPT_ENDDATE: enddate = ++num; break; case OPT_NOOUT: noout = ++num; break; case OPT_NOCERT: nocert = 1; break; case OPT_TRUSTOUT: trustout = 1; break; case OPT_CLRTRUST: clrtrust = ++num; break; case OPT_CLRREJECT: clrreject = ++num; break; case OPT_ALIAS: aliasout = ++num; break; case OPT_CACREATESERIAL: CA_createserial = ++num; break; case OPT_CLREXT: clrext = 1; break; case OPT_OCSPID: ocspid = ++num; break; case OPT_BADSIG: badsig = 1; break; #ifndef OPENSSL_NO_MD5 case OPT_SUBJECT_HASH_OLD: subject_hash_old = ++num; break; case OPT_ISSUER_HASH_OLD: issuer_hash_old = ++num; break; #else case OPT_SUBJECT_HASH_OLD: case OPT_ISSUER_HASH_OLD: break; #endif case OPT_DATES: startdate = ++num; enddate = ++num; break; case OPT_CHECKEND: checkend = 1; { intmax_t temp = 0; if (!opt_imax(opt_arg(), &temp)) goto opthelp; checkoffset = (time_t)temp; if ((intmax_t)checkoffset != temp) { BIO_printf(bio_err, "%s: checkend time out of range %s\n", prog, opt_arg()); goto opthelp; } } break; case OPT_CHECKHOST: checkhost = opt_arg(); break; case OPT_CHECKEMAIL: checkemail = opt_arg(); break; case OPT_CHECKIP: checkip = opt_arg(); break; case OPT_MD: if (!opt_md(opt_unknown(), &digest)) goto opthelp; } } argc = opt_num_rest(); argv = opt_rest(); if (argc != 0) { BIO_printf(bio_err, "%s: Unknown parameter %s\n", prog, argv[0]); goto opthelp; } if (!nmflag_set) nmflag = XN_FLAG_ONELINE; out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (need_rand) app_RAND_load_file(NULL, 0); if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (!X509_STORE_set_default_paths(ctx)) { ERR_print_errors(bio_err); goto end; } if (fkeyfile) { fkey = load_pubkey(fkeyfile, keyformat, 0, NULL, e, "Forced key"); if (fkey == NULL) goto end; } if ((CAkeyfile == NULL) && (CA_flag) && (CAformat == FORMAT_PEM)) { CAkeyfile = CAfile; } else if ((CA_flag) && (CAkeyfile == NULL)) { BIO_printf(bio_err, "need to specify a CAkey if using the CA command\n"); goto end; } if (extfile) { X509V3_CTX ctx2; if ((extconf = app_load_config(extfile)) == NULL) goto end; if (!extsect) { extsect = NCONF_get_string(extconf, "default", "extensions"); if (!extsect) { ERR_clear_error(); extsect = "default"; } } X509V3_set_ctx_test(&ctx2); X509V3_set_nconf(&ctx2, extconf); if (!X509V3_EXT_add_nconf(extconf, &ctx2, extsect, NULL)) { BIO_printf(bio_err, "Error Loading extension section %s\n", extsect); ERR_print_errors(bio_err); goto end; } } if (reqfile) { EVP_PKEY *pkey; BIO *in; if (!sign_flag && !CA_flag) { BIO_printf(bio_err, "We need a private key to sign with\n"); goto end; } in = bio_open_default(infile, 'r', informat); if (in == NULL) goto end; req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL); BIO_free(in); if (req == NULL) { ERR_print_errors(bio_err); goto end; } if ((pkey = X509_REQ_get0_pubkey(req)) == NULL) { BIO_printf(bio_err, "error unpacking public key\n"); goto end; } i = X509_REQ_verify(req, pkey); if (i < 0) { BIO_printf(bio_err, "Signature verification error\n"); ERR_print_errors(bio_err); goto end; } if (i == 0) { BIO_printf(bio_err, "Signature did not match the certificate request\n"); goto end; } else BIO_printf(bio_err, "Signature ok\n"); print_name(bio_err, "subject=", X509_REQ_get_subject_name(req), nmflag); if ((x = X509_new()) == NULL) goto end; if (sno == NULL) { sno = ASN1_INTEGER_new(); if (sno == NULL || !rand_serial(NULL, sno)) goto end; if (!X509_set_serialNumber(x, sno)) goto end; ASN1_INTEGER_free(sno); sno = NULL; } else if (!X509_set_serialNumber(x, sno)) goto end; if (!X509_set_issuer_name(x, X509_REQ_get_subject_name(req))) goto end; if (!X509_set_subject_name(x, X509_REQ_get_subject_name(req))) goto end; if (!set_cert_times(x, NULL, NULL, days)) goto end; if (fkey) X509_set_pubkey(x, fkey); else { pkey = X509_REQ_get0_pubkey(req); X509_set_pubkey(x, pkey); } } else x = load_cert(infile, informat, "Certificate"); if (x == NULL) goto end; if (CA_flag) { xca = load_cert(CAfile, CAformat, "CA Certificate"); if (xca == NULL) goto end; } if (!noout || text || next_serial) { OBJ_create("2.99999.3", "SET.ex3", "SET x509v3 extension 3"); } if (alias) X509_alias_set1(x, (unsigned char *)alias, -1); if (clrtrust) X509_trust_clear(x); if (clrreject) X509_reject_clear(x); if (trust) { for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) { objtmp = sk_ASN1_OBJECT_value(trust, i); X509_add1_trust_object(x, objtmp); } objtmp = NULL; } if (reject) { for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) { objtmp = sk_ASN1_OBJECT_value(reject, i); X509_add1_reject_object(x, objtmp); } objtmp = NULL; } if (badsig) { const ASN1_BIT_STRING *signature; X509_get0_signature(&signature, NULL, x); corrupt_signature(signature); } if (num) { for (i = 1; i <= num; i++) { if (issuer == i) { print_name(out, "issuer=", X509_get_issuer_name(x), nmflag); } else if (subject == i) { print_name(out, "subject=", X509_get_subject_name(x), nmflag); } else if (serial == i) { BIO_printf(out, "serial="); i2a_ASN1_INTEGER(out, X509_get_serialNumber(x)); BIO_printf(out, "\n"); } else if (next_serial == i) { ASN1_INTEGER *ser = X509_get_serialNumber(x); BIGNUM *bnser = ASN1_INTEGER_to_BN(ser, NULL); if (!bnser) goto end; if (!BN_add_word(bnser, 1)) goto end; ser = BN_to_ASN1_INTEGER(bnser, NULL); if (!ser) goto end; BN_free(bnser); i2a_ASN1_INTEGER(out, ser); ASN1_INTEGER_free(ser); BIO_puts(out, "\n"); } else if ((email == i) || (ocsp_uri == i)) { int j; STACK_OF(OPENSSL_STRING) *emlst; if (email == i) emlst = X509_get1_email(x); else emlst = X509_get1_ocsp(x); for (j = 0; j < sk_OPENSSL_STRING_num(emlst); j++) BIO_printf(out, "%s\n", sk_OPENSSL_STRING_value(emlst, j)); X509_email_free(emlst); } else if (aliasout == i) { unsigned char *alstr; alstr = X509_alias_get0(x, NULL); if (alstr) BIO_printf(out, "%s\n", alstr); else BIO_puts(out, "<No Alias>\n"); } else if (subject_hash == i) { BIO_printf(out, "%08lx\n", X509_subject_name_hash(x)); } #ifndef OPENSSL_NO_MD5 else if (subject_hash_old == i) { BIO_printf(out, "%08lx\n", X509_subject_name_hash_old(x)); } #endif else if (issuer_hash == i) { BIO_printf(out, "%08lx\n", X509_issuer_name_hash(x)); } #ifndef OPENSSL_NO_MD5 else if (issuer_hash_old == i) { BIO_printf(out, "%08lx\n", X509_issuer_name_hash_old(x)); } #endif else if (pprint == i) { X509_PURPOSE *ptmp; int j; BIO_printf(out, "Certificate purposes:\n"); for (j = 0; j < X509_PURPOSE_get_count(); j++) { ptmp = X509_PURPOSE_get0(j); purpose_print(out, x, ptmp); } } else if (modulus == i) { EVP_PKEY *pkey; pkey = X509_get0_pubkey(x); if (pkey == NULL) { BIO_printf(bio_err, "Modulus=unavailable\n"); ERR_print_errors(bio_err); goto end; } BIO_printf(out, "Modulus="); #ifndef OPENSSL_NO_RSA if (EVP_PKEY_id(pkey) == EVP_PKEY_RSA) { const BIGNUM *n; RSA_get0_key(EVP_PKEY_get0_RSA(pkey), &n, NULL, NULL); BN_print(out, n); } else #endif #ifndef OPENSSL_NO_DSA if (EVP_PKEY_id(pkey) == EVP_PKEY_DSA) { const BIGNUM *dsapub = NULL; DSA_get0_key(EVP_PKEY_get0_DSA(pkey), &dsapub, NULL); BN_print(out, dsapub); } else #endif { BIO_printf(out, "Wrong Algorithm type"); } BIO_printf(out, "\n"); } else if (pubkey == i) { EVP_PKEY *pkey; pkey = X509_get0_pubkey(x); if (pkey == NULL) { BIO_printf(bio_err, "Error getting public key\n"); ERR_print_errors(bio_err); goto end; } PEM_write_bio_PUBKEY(out, pkey); } else if (C == i) { unsigned char *d; char *m; int len; X509_NAME_oneline(X509_get_subject_name(x), buf, sizeof buf); BIO_printf(out, "/*\n" " * Subject: %s\n", buf); X509_NAME_oneline(X509_get_issuer_name(x), buf, sizeof buf); BIO_printf(out, " * Issuer: %s\n" " */\n", buf); len = i2d_X509(x, NULL); m = app_malloc(len, "x509 name buffer"); d = (unsigned char *)m; len = i2d_X509_NAME(X509_get_subject_name(x), &d); print_array(out, "the_subject_name", len, (unsigned char *)m); d = (unsigned char *)m; len = i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &d); print_array(out, "the_public_key", len, (unsigned char *)m); d = (unsigned char *)m; len = i2d_X509(x, &d); print_array(out, "the_certificate", len, (unsigned char *)m); OPENSSL_free(m); } else if (text == i) { X509_print_ex(out, x, nmflag, certflag); } else if (startdate == i) { BIO_puts(out, "notBefore="); ASN1_TIME_print(out, X509_get0_notBefore(x)); BIO_puts(out, "\n"); } else if (enddate == i) { BIO_puts(out, "notAfter="); ASN1_TIME_print(out, X509_get0_notAfter(x)); BIO_puts(out, "\n"); } else if (fingerprint == i) { int j; unsigned int n; unsigned char md[EVP_MAX_MD_SIZE]; const EVP_MD *fdig = digest; if (!fdig) fdig = EVP_sha1(); if (!X509_digest(x, fdig, md, &n)) { BIO_printf(bio_err, "out of memory\n"); goto end; } BIO_printf(out, "%s Fingerprint=", OBJ_nid2sn(EVP_MD_type(fdig))); for (j = 0; j < (int)n; j++) { BIO_printf(out, "%02X%c", md[j], (j + 1 == (int)n) ? '\n' : ':'); } } /* should be in the library */ else if ((sign_flag == i) && (x509req == 0)) { BIO_printf(bio_err, "Getting Private key\n"); if (Upkey == NULL) { Upkey = load_key(keyfile, keyformat, 0, passin, e, "Private key"); if (Upkey == NULL) goto end; } assert(need_rand); if (!sign(x, Upkey, days, clrext, digest, extconf, extsect)) goto end; } else if (CA_flag == i) { BIO_printf(bio_err, "Getting CA Private Key\n"); if (CAkeyfile != NULL) { CApkey = load_key(CAkeyfile, CAkeyformat, 0, passin, e, "CA Private Key"); if (CApkey == NULL) goto end; } assert(need_rand); if (!x509_certify(ctx, CAfile, digest, x, xca, CApkey, sigopts, CAserial, CA_createserial, days, clrext, extconf, extsect, sno, reqfile)) goto end; } else if (x509req == i) { EVP_PKEY *pk; BIO_printf(bio_err, "Getting request Private Key\n"); if (keyfile == NULL) { BIO_printf(bio_err, "no request key file specified\n"); goto end; } else { pk = load_key(keyfile, keyformat, 0, passin, e, "request key"); if (pk == NULL) goto end; } BIO_printf(bio_err, "Generating certificate request\n"); rq = X509_to_X509_REQ(x, pk, digest); EVP_PKEY_free(pk); if (rq == NULL) { ERR_print_errors(bio_err); goto end; } if (!noout) { X509_REQ_print(out, rq); PEM_write_bio_X509_REQ(out, rq); } noout = 1; } else if (ocspid == i) { X509_ocspid_print(out, x); } } } if (checkend) { time_t tcheck = time(NULL) + checkoffset; if (X509_cmp_time(X509_get0_notAfter(x), &tcheck) < 0) { BIO_printf(out, "Certificate will expire\n"); ret = 1; } else { BIO_printf(out, "Certificate will not expire\n"); ret = 0; } goto end; } print_cert_checks(out, x, checkhost, checkemail, checkip); if (noout || nocert) { ret = 0; goto end; } if (outformat == FORMAT_ASN1) i = i2d_X509_bio(out, x); else if (outformat == FORMAT_PEM) { if (trustout) i = PEM_write_bio_X509_AUX(out, x); else i = PEM_write_bio_X509(out, x); } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write certificate\n"); ERR_print_errors(bio_err); goto end; } ret = 0; end: if (need_rand) app_RAND_write_file(NULL); NCONF_free(extconf); BIO_free_all(out); X509_STORE_free(ctx); X509_REQ_free(req); X509_free(x); X509_free(xca); EVP_PKEY_free(Upkey); EVP_PKEY_free(CApkey); EVP_PKEY_free(fkey); sk_OPENSSL_STRING_free(sigopts); X509_REQ_free(rq); ASN1_INTEGER_free(sno); sk_ASN1_OBJECT_pop_free(trust, ASN1_OBJECT_free); sk_ASN1_OBJECT_pop_free(reject, ASN1_OBJECT_free); ASN1_OBJECT_free(objtmp); release_engine(e); OPENSSL_free(passin); return (ret); }
int MAIN(int argc, char **argv) { int ret = 1, i; int verbose = 0, Verbose = 0; #ifndef OPENSSL_NO_SSL_TRACE int stdname = 0; #endif const char **pp; const char *p; int badops = 0; SSL_CTX *ctx = NULL; SSL *ssl = NULL; char *ciphers = NULL; const SSL_METHOD *meth = NULL; STACK_OF(SSL_CIPHER) *sk; char buf[512]; BIO *STDout = NULL; meth = SSLv23_server_method(); apps_startup(); if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); STDout = BIO_new_fp(stdout, BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); STDout = BIO_push(tmpbio, STDout); } #endif if (!load_config(bio_err, NULL)) goto end; argc--; argv++; while (argc >= 1) { if (strcmp(*argv, "-v") == 0) verbose = 1; else if (strcmp(*argv, "-V") == 0) verbose = Verbose = 1; #ifndef OPENSSL_NO_SSL_TRACE else if (strcmp(*argv, "-stdname") == 0) stdname = verbose = 1; #endif #ifndef OPENSSL_NO_SSL2 else if (strcmp(*argv, "-ssl2") == 0) meth = SSLv2_client_method(); #endif #ifndef OPENSSL_NO_SSL3 else if (strcmp(*argv, "-ssl3") == 0) meth = SSLv3_client_method(); #endif #ifndef OPENSSL_NO_TLS1 else if (strcmp(*argv, "-tls1") == 0) meth = TLSv1_client_method(); #endif else if ((strncmp(*argv, "-h", 2) == 0) || (strcmp(*argv, "-?") == 0)) { badops = 1; break; } else { ciphers = *argv; } argc--; argv++; } if (badops) { for (pp = ciphers_usage; (*pp != NULL); pp++) BIO_printf(bio_err, "%s", *pp); goto end; } OpenSSL_add_ssl_algorithms(); ctx = SSL_CTX_new(meth); if (ctx == NULL) goto err; if (ciphers != NULL) { if (!SSL_CTX_set_cipher_list(ctx, ciphers)) { BIO_printf(bio_err, "Error in cipher list\n"); goto err; } } ssl = SSL_new(ctx); if (ssl == NULL) goto err; if (!verbose) { for (i = 0;; i++) { p = SSL_get_cipher_list(ssl, i); if (p == NULL) break; if (i != 0) BIO_printf(STDout, ":"); BIO_printf(STDout, "%s", p); } BIO_printf(STDout, "\n"); } else { /* verbose */ sk = SSL_get_ciphers(ssl); for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) { SSL_CIPHER *c; c = sk_SSL_CIPHER_value(sk, i); if (Verbose) { unsigned long id = SSL_CIPHER_get_id(c); int id0 = (int)(id >> 24); int id1 = (int)((id >> 16) & 0xffL); int id2 = (int)((id >> 8) & 0xffL); int id3 = (int)(id & 0xffL); if ((id & 0xff000000L) == 0x02000000L) { /* SSL2 cipher */ BIO_printf(STDout, " 0x%02X,0x%02X,0x%02X - ", id1, id2, id3); } else if ((id & 0xff000000L) == 0x03000000L) { /* SSL3 cipher */ BIO_printf(STDout, " 0x%02X,0x%02X - ", id2, id3); } else { /* whatever */ BIO_printf(STDout, "0x%02X,0x%02X,0x%02X,0x%02X - ", id0, id1, id2, id3); } } #ifndef OPENSSL_NO_SSL_TRACE if (stdname) { const char *nm = SSL_CIPHER_standard_name(c); if (nm == NULL) nm = "UNKNOWN"; BIO_printf(STDout, "%s - ", nm); } #endif BIO_puts(STDout, SSL_CIPHER_description(c, buf, sizeof buf)); } } ret = 0; if (0) { err: SSL_load_error_strings(); ERR_print_errors(bio_err); } end: if (ctx != NULL) SSL_CTX_free(ctx); if (ssl != NULL) SSL_free(ssl); if (STDout != NULL) BIO_free_all(STDout); apps_shutdown(); OPENSSL_EXIT(ret); }
int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags, unsigned long cflag) { long l; int ret=0,i; char *m=NULL,mlch = ' '; int nmindent = 0; X509_CINF *ci; ASN1_INTEGER *bs; EVP_PKEY *pkey=NULL; const char *neg; if((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) { mlch = '\n'; nmindent = 12; } if(nmflags == X509_FLAG_COMPAT) nmindent = 16; ci=x->cert_info; if(!(cflag & X509_FLAG_NO_HEADER)) { if (BIO_write(bp,"Certificate:\n",13) <= 0) goto err; if (BIO_write(bp," Data:\n",10) <= 0) goto err; } if(!(cflag & X509_FLAG_NO_VERSION)) { l=X509_get_version(x); if (BIO_printf(bp,"%8sVersion: %lu (0x%lx)\n","",l+1,l) <= 0) goto err; } if(!(cflag & X509_FLAG_NO_SERIAL)) { if (BIO_write(bp," Serial Number:",22) <= 0) goto err; bs=X509_get_serialNumber(x); if (bs->length <= (int)sizeof(long)) { l=ASN1_INTEGER_get(bs); if (bs->type == V_ASN1_NEG_INTEGER) { l= -l; neg="-"; } else neg=""; if (BIO_printf(bp," %s%lu (%s0x%lx)\n",neg,l,neg,l) <= 0) goto err; } else { neg=(bs->type == V_ASN1_NEG_INTEGER)?" (Negative)":""; if (BIO_printf(bp,"\n%12s%s","",neg) <= 0) goto err; for (i=0; i<bs->length; i++) { if (BIO_printf(bp,"%02x%c",bs->data[i], ((i+1 == bs->length)?'\n':':')) <= 0) goto err; } } } if(!(cflag & X509_FLAG_NO_SIGNAME)) { if (X509_signature_print(bp, ci->signature, NULL) <= 0) goto err; } if(!(cflag & X509_FLAG_NO_ISSUER)) { if (BIO_printf(bp," Issuer:%c",mlch) <= 0) goto err; if (X509_NAME_print_ex(bp,X509_get_issuer_name(x),nmindent, nmflags) < 0) goto err; if (BIO_write(bp,"\n",1) <= 0) goto err; } if(!(cflag & X509_FLAG_NO_VALIDITY)) { if (BIO_write(bp," Validity\n",17) <= 0) goto err; if (BIO_write(bp," Not Before: ",24) <= 0) goto err; if (!ASN1_TIME_print(bp,X509_get_notBefore(x))) goto err; if (BIO_write(bp,"\n Not After : ",25) <= 0) goto err; if (!ASN1_TIME_print(bp,X509_get_notAfter(x))) goto err; if (BIO_write(bp,"\n",1) <= 0) goto err; } if(!(cflag & X509_FLAG_NO_SUBJECT)) { if (BIO_printf(bp," Subject:%c",mlch) <= 0) goto err; if (X509_NAME_print_ex(bp,X509_get_subject_name(x),nmindent, nmflags) < 0) goto err; if (BIO_write(bp,"\n",1) <= 0) goto err; } if(!(cflag & X509_FLAG_NO_PUBKEY)) { if (BIO_write(bp," Subject Public Key Info:\n",33) <= 0) goto err; if (BIO_printf(bp,"%12sPublic Key Algorithm: ","") <= 0) goto err; if (i2a_ASN1_OBJECT(bp, ci->key->algor->algorithm) <= 0) goto err; if (BIO_puts(bp, "\n") <= 0) goto err; pkey=X509_get_pubkey(x); if (pkey == NULL) { BIO_printf(bp,"%12sUnable to load Public Key\n",""); BIO_print_errors(bp); } else { EVP_PKEY_print_public(bp, pkey, 16, NULL); EVP_PKEY_free(pkey); } } if(!(cflag & X509_FLAG_NO_IDS)) { if (ci->issuerUID) { if (BIO_printf(bp,"%8sIssuer Unique ID: ","") <= 0) goto err; if (!X509_signature_dump(bp, ci->issuerUID, 12)) goto err; } if (ci->subjectUID) { if (BIO_printf(bp,"%8sSubject Unique ID: ","") <= 0) goto err; if (!X509_signature_dump(bp, ci->subjectUID, 12)) goto err; } } if (!(cflag & X509_FLAG_NO_EXTENSIONS)) X509V3_extensions_print(bp, "X509v3 extensions", ci->extensions, cflag, 8); if(!(cflag & X509_FLAG_NO_SIGDUMP)) { if(X509_signature_print(bp, x->sig_alg, x->signature) <= 0) goto err; } if(!(cflag & X509_FLAG_NO_AUX)) { if (!X509_CERT_AUX_print(bp, x->aux, 0)) goto err; } ret=1; err: if (m != NULL) OPENSSL_free(m); return(ret); }
static int test_ecdh_curve(int nid, BN_CTX *ctx, BIO *out) { EC_KEY *a = NULL; EC_KEY *b = NULL; BIGNUM *x_a = NULL, *y_a = NULL, *x_b = NULL, *y_b = NULL; char buf[12]; unsigned char *abuf = NULL, *bbuf = NULL; int i, alen, blen, aout, bout, ret = 0; const EC_GROUP *group; a = EC_KEY_new_by_curve_name(nid); b = EC_KEY_new_by_curve_name(nid); if (a == NULL || b == NULL) goto err; group = EC_KEY_get0_group(a); if ((x_a = BN_new()) == NULL) goto err; if ((y_a = BN_new()) == NULL) goto err; if ((x_b = BN_new()) == NULL) goto err; if ((y_b = BN_new()) == NULL) goto err; BIO_puts(out, "Testing key generation with "); BIO_puts(out, OBJ_nid2sn(nid)); # ifdef NOISY BIO_puts(out, "\n"); # else (void)BIO_flush(out); # endif if (!EC_KEY_generate_key(a)) goto err; if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field) { if (!EC_POINT_get_affine_coordinates_GFp (group, EC_KEY_get0_public_key(a), x_a, y_a, ctx)) goto err; } # ifndef OPENSSL_NO_EC2M else { if (!EC_POINT_get_affine_coordinates_GF2m(group, EC_KEY_get0_public_key(a), x_a, y_a, ctx)) goto err; } # endif # ifdef NOISY BIO_puts(out, " pri 1="); BN_print(out, a->priv_key); BIO_puts(out, "\n pub 1="); BN_print(out, x_a); BIO_puts(out, ","); BN_print(out, y_a); BIO_puts(out, "\n"); # else BIO_printf(out, " ."); (void)BIO_flush(out); # endif if (!EC_KEY_generate_key(b)) goto err; if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_prime_field) { if (!EC_POINT_get_affine_coordinates_GFp (group, EC_KEY_get0_public_key(b), x_b, y_b, ctx)) goto err; } # ifndef OPENSSL_NO_EC2M else { if (!EC_POINT_get_affine_coordinates_GF2m(group, EC_KEY_get0_public_key(b), x_b, y_b, ctx)) goto err; } # endif # ifdef NOISY BIO_puts(out, " pri 2="); BN_print(out, b->priv_key); BIO_puts(out, "\n pub 2="); BN_print(out, x_b); BIO_puts(out, ","); BN_print(out, y_b); BIO_puts(out, "\n"); # else BIO_printf(out, "."); (void)BIO_flush(out); # endif alen = KDF1_SHA1_len; abuf = OPENSSL_malloc(alen); aout = ECDH_compute_key(abuf, alen, EC_KEY_get0_public_key(b), a, KDF1_SHA1); # ifdef NOISY BIO_puts(out, " key1 ="); for (i = 0; i < aout; i++) { sprintf(buf, "%02X", abuf[i]); BIO_puts(out, buf); } BIO_puts(out, "\n"); # else BIO_printf(out, "."); (void)BIO_flush(out); # endif blen = KDF1_SHA1_len; bbuf = OPENSSL_malloc(blen); bout = ECDH_compute_key(bbuf, blen, EC_KEY_get0_public_key(a), b, KDF1_SHA1); # ifdef NOISY BIO_puts(out, " key2 ="); for (i = 0; i < bout; i++) { sprintf(buf, "%02X", bbuf[i]); BIO_puts(out, buf); } BIO_puts(out, "\n"); # else BIO_printf(out, "."); (void)BIO_flush(out); # endif if ((aout < 4) || (bout != aout) || (memcmp(abuf, bbuf, aout) != 0)) { # ifndef NOISY BIO_printf(out, " failed\n\n"); BIO_printf(out, "key a:\n"); BIO_printf(out, "private key: "); BN_print(out, EC_KEY_get0_private_key(a)); BIO_printf(out, "\n"); BIO_printf(out, "public key (x,y): "); BN_print(out, x_a); BIO_printf(out, ","); BN_print(out, y_a); BIO_printf(out, "\nkey b:\n"); BIO_printf(out, "private key: "); BN_print(out, EC_KEY_get0_private_key(b)); BIO_printf(out, "\n"); BIO_printf(out, "public key (x,y): "); BN_print(out, x_b); BIO_printf(out, ","); BN_print(out, y_b); BIO_printf(out, "\n"); BIO_printf(out, "generated key a: "); for (i = 0; i < bout; i++) { sprintf(buf, "%02X", bbuf[i]); BIO_puts(out, buf); } BIO_printf(out, "\n"); BIO_printf(out, "generated key b: "); for (i = 0; i < aout; i++) { sprintf(buf, "%02X", abuf[i]); BIO_puts(out, buf); } BIO_printf(out, "\n"); # endif fprintf(stderr, "Error in ECDH routines\n"); ret = 0; } else { # ifndef NOISY BIO_printf(out, " ok\n"); # endif ret = 1; } err: ERR_print_errors_fp(stderr); OPENSSL_free(abuf); OPENSSL_free(bbuf); BN_free(x_a); BN_free(y_a); BN_free(x_b); BN_free(y_b); EC_KEY_free(b); EC_KEY_free(a); return (ret); }
int MAIN(int argc, char **argv) { int i, r, ret = 1; int badopt; char *outfile = NULL; char *inrand = NULL; int base64 = 0; int hex = 0; BIO *out = NULL; int num = -1; #ifndef OPENSSL_NO_ENGINE char *engine = NULL; #endif apps_startup(); if (bio_err == NULL) if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE | BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto err; badopt = 0; i = 0; while (!badopt && argv[++i] != NULL) { if (strcmp(argv[i], "-out") == 0) { if ((argv[i + 1] != NULL) && (outfile == NULL)) outfile = argv[++i]; else badopt = 1; } #ifndef OPENSSL_NO_ENGINE else if (strcmp(argv[i], "-engine") == 0) { if ((argv[i + 1] != NULL) && (engine == NULL)) engine = argv[++i]; else badopt = 1; } #endif else if (strcmp(argv[i], "-rand") == 0) { if ((argv[i + 1] != NULL) && (inrand == NULL)) inrand = argv[++i]; else badopt = 1; } else if (strcmp(argv[i], "-base64") == 0) { if (!base64) base64 = 1; else badopt = 1; } else if (strcmp(argv[i], "-hex") == 0) { if (!hex) hex = 1; else badopt = 1; } else if (isdigit((unsigned char)argv[i][0])) { if (num < 0) { r = sscanf(argv[i], "%d", &num); if (r == 0 || num < 0) badopt = 1; } else badopt = 1; } else badopt = 1; } if (hex && base64) badopt = 1; if (num < 0) badopt = 1; if (badopt) { BIO_printf(bio_err, "Usage: rand [options] num\n"); BIO_printf(bio_err, "where options are\n"); BIO_printf(bio_err, "-out file - write to file\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, "-engine e - use engine e, possibly a hardware device.\n"); #endif BIO_printf(bio_err, "-rand file%cfile%c... - seed PRNG from files\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); BIO_printf(bio_err, "-base64 - base64 encode output\n"); BIO_printf(bio_err, "-hex - hex encode output\n"); goto err; } #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, engine, 0); #endif app_RAND_load_file(NULL, bio_err, (inrand != NULL)); if (inrand != NULL) BIO_printf(bio_err, "%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); out = BIO_new(BIO_s_file()); if (out == NULL) goto err; if (outfile != NULL) r = BIO_write_filename(out, outfile); else { r = BIO_set_fp(out, stdout, BIO_NOCLOSE | BIO_FP_TEXT); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } if (r <= 0) goto err; if (base64) { BIO *b64 = BIO_new(BIO_f_base64()); if (b64 == NULL) goto err; out = BIO_push(b64, out); } while (num > 0) { unsigned char buf[4096]; int chunk; chunk = num; if (chunk > (int)sizeof(buf)) chunk = sizeof buf; r = RAND_bytes(buf, chunk); if (r <= 0) goto err; if (!hex) BIO_write(out, buf, chunk); else { for (i = 0; i < chunk; i++) BIO_printf(out, "%02x", buf[i]); } num -= chunk; } if (hex) BIO_puts(out, "\n"); (void)BIO_flush(out); app_RAND_write_file(NULL, bio_err); ret = 0; err: ERR_print_errors(bio_err); if (out) BIO_free_all(out); apps_shutdown(); OPENSSL_EXIT(ret); }
/* * NIST SP800-56A co-factor ECDH tests. * KATs taken from NIST documents with parameters: * * - (QCAVSx,QCAVSy) is the public key for CAVS. * - dIUT is the private key for IUT. * - (QIUTx,QIUTy) is the public key for IUT. * - ZIUT is the shared secret KAT. * * CAVS: Cryptographic Algorithm Validation System * IUT: Implementation Under Test * * This function tests two things: * * 1. dIUT * G = (QIUTx,QIUTy) * i.e. public key for IUT computes correctly. * 2. x-coord of cofactor * dIUT * (QCAVSx,QCAVSy) = ZIUT * i.e. co-factor ECDH key computes correctly. * * returns zero on failure or unsupported curve. One otherwise. */ static int ecdh_cavs_kat(BIO *out, const ecdh_cavs_kat_t *kat) { int rv = 0, is_char_two = 0; EC_KEY *key1 = NULL; EC_POINT *pub = NULL; const EC_GROUP *group = NULL; BIGNUM *bnz = NULL, *x = NULL, *y = NULL; unsigned char *Ztmp = NULL, *Z = NULL; size_t Ztmplen, Zlen; BIO_puts(out, "Testing ECC CDH Primitive SP800-56A with "); BIO_puts(out, OBJ_nid2sn(kat->nid)); /* dIUT is IUT's private key */ if ((key1 = mk_eckey(kat->nid, kat->dIUT)) == NULL) goto err; /* these are cofactor ECDH KATs */ EC_KEY_set_flags(key1, EC_FLAG_COFACTOR_ECDH); if ((group = EC_KEY_get0_group(key1)) == NULL) goto err; if ((pub = EC_POINT_new(group)) == NULL) goto err; if (EC_METHOD_get_field_type(EC_GROUP_method_of(group)) == NID_X9_62_characteristic_two_field) is_char_two = 1; /* (QIUTx, QIUTy) is IUT's public key */ if(!BN_hex2bn(&x, kat->QIUTx)) goto err; if(!BN_hex2bn(&y, kat->QIUTy)) goto err; if (is_char_two) { #ifdef OPENSSL_NO_EC2M goto err; #else if (!EC_POINT_set_affine_coordinates_GF2m(group, pub, x, y, NULL)) goto err; #endif } else { if (!EC_POINT_set_affine_coordinates_GFp(group, pub, x, y, NULL)) goto err; } /* dIUT * G = (QIUTx, QIUTy) should hold */ if (EC_POINT_cmp(group, EC_KEY_get0_public_key(key1), pub, NULL)) goto err; /* (QCAVSx, QCAVSy) is CAVS's public key */ if(!BN_hex2bn(&x, kat->QCAVSx)) goto err; if(!BN_hex2bn(&y, kat->QCAVSy)) goto err; if (is_char_two) { #ifdef OPENSSL_NO_EC2M goto err; #else if (!EC_POINT_set_affine_coordinates_GF2m(group, pub, x, y, NULL)) goto err; #endif } else { if (!EC_POINT_set_affine_coordinates_GFp(group, pub, x, y, NULL)) goto err; } /* ZIUT is the shared secret */ if(!BN_hex2bn(&bnz, kat->ZIUT)) goto err; Ztmplen = (EC_GROUP_get_degree(EC_KEY_get0_group(key1)) + 7) / 8; Zlen = BN_num_bytes(bnz); if (Zlen > Ztmplen) goto err; if((Ztmp = OPENSSL_zalloc(Ztmplen)) == NULL) goto err; if((Z = OPENSSL_zalloc(Ztmplen)) == NULL) goto err; if(!BN_bn2binpad(bnz, Z, Ztmplen)) goto err; if (!ECDH_compute_key(Ztmp, Ztmplen, pub, key1, 0)) goto err; /* shared secrets should be identical */ if (memcmp(Ztmp, Z, Ztmplen)) goto err; rv = 1; err: EC_KEY_free(key1); EC_POINT_free(pub); BN_free(bnz); BN_free(x); BN_free(y); OPENSSL_free(Ztmp); OPENSSL_free(Z); if (rv) { BIO_puts(out, " ok\n"); } else { fprintf(stderr, "Error in ECC CDH routines\n"); ERR_print_errors_fp(stderr); } return rv; }
int t_puts(BIO *bp, const char *str){ printf("t_read\n"); return BIO_puts(bp->next_bio,str); }
static int asn1_parse2(BIO *bp, const unsigned char **pp, long length, int offset, int depth, int indent, int dump) { const unsigned char *p,*ep,*tot,*op,*opp; long len; int tag,xclass,ret=0; int nl,hl,j,r; ASN1_OBJECT *o=NULL; ASN1_OCTET_STRING *os=NULL; /* ASN1_BMPSTRING *bmp=NULL;*/ int dump_indent; #if 0 dump_indent = indent; #else dump_indent = 6; /* Because we know BIO_dump_indent() */ #endif p= *pp; tot=p+length; op=p-1; while ((p < tot) && (op < p)) { op=p; j=ASN1_get_object(&p,&len,&tag,&xclass,length); #ifdef LINT j=j; #endif if (j & 0x80) { if (BIO_puts(bp, "Error in encoding\n") <= 0) goto end; ret=0; goto end; } hl=(p-op); length-=hl; /* if j == 0x21 it is a constructed indefinite length object */ if (BIO_printf(bp,"%5ld:",(long)offset+(long)(op- *pp)) <= 0) goto end; if (j != (V_ASN1_CONSTRUCTED | 1)) { if (BIO_printf(bp,"d=%-2d hl=%ld l=%4ld ", depth,(long)hl,len) <= 0) goto end; } else { if (BIO_printf(bp,"d=%-2d hl=%ld l=inf ", depth,(long)hl) <= 0) goto end; } if (!asn1_print_info(bp,tag,xclass,j,(indent)?depth:0)) goto end; if (j & V_ASN1_CONSTRUCTED) { ep=p+len; if (BIO_puts(bp, "\n") <= 0) goto end; if (len > length) { BIO_printf(bp, "length is greater than %ld\n",length); ret=0; goto end; } if ((j == 0x21) && (len == 0)) { for (;;) { r=asn1_parse2(bp,&p,(long)(tot-p), offset+(p - *pp),depth+1, indent,dump); if (r == 0) { ret=0; goto end; } if ((r == 2) || (p >= tot)) break; } } else while (p < ep) { r=asn1_parse2(bp,&p,(long)len, offset+(p - *pp),depth+1, indent,dump); if (r == 0) { ret=0; goto end; } } } else if (xclass != 0) { p+=len; if (BIO_puts(bp, "\n") <= 0) goto end; } else { nl=0; if ( (tag == V_ASN1_PRINTABLESTRING) || (tag == V_ASN1_T61STRING) || (tag == V_ASN1_IA5STRING) || (tag == V_ASN1_VISIBLESTRING) || (tag == V_ASN1_NUMERICSTRING) || (tag == V_ASN1_UTF8STRING) || (tag == V_ASN1_UTCTIME) || (tag == V_ASN1_GENERALIZEDTIME)) { if (BIO_puts(bp, ":") <= 0) goto end; if ((len > 0) && BIO_write(bp,(const char *)p,(int)len) != (int)len) goto end; } else if (tag == V_ASN1_OBJECT) { opp=op; if (d2i_ASN1_OBJECT(&o,&opp,len+hl) != NULL) { if (BIO_puts(bp, ":") <= 0) goto end; i2a_ASN1_OBJECT(bp,o); } else { if (BIO_puts(bp, ":BAD OBJECT") <= 0) goto end; } } else if (tag == V_ASN1_BOOLEAN) { int ii; opp=op; ii=d2i_ASN1_BOOLEAN(NULL,&opp,len+hl); if (ii < 0) { if (BIO_puts(bp, "Bad boolean\n") <= 0) goto end; } BIO_printf(bp,":%d",ii); } else if (tag == V_ASN1_BMPSTRING) { /* do the BMP thang */ } else if (tag == V_ASN1_OCTET_STRING) { int i,printable=1; opp=op; os=d2i_ASN1_OCTET_STRING(NULL,&opp,len+hl); if (os != NULL && os->length > 0) { opp = os->data; /* testing whether the octet string is * printable */ for (i=0; i<os->length; i++) { if (( (opp[i] < ' ') && (opp[i] != '\n') && (opp[i] != '\r') && (opp[i] != '\t')) || (opp[i] > '~')) { printable=0; break; } } if (printable) /* printable string */ { if (BIO_puts(bp, ":") <= 0) goto end; if (BIO_write(bp,(const char *)opp, os->length) <= 0) goto end; } else if (!dump) /* not printable => print octet string * as hex dump */ { if (BIO_puts(bp, "[HEX DUMP]:") <= 0) goto end; for (i=0; i<os->length; i++) { if (BIO_printf(bp,"%02X" , opp[i]) <= 0) goto end; } } else /* print the normal dump */ { if (!nl) { if (BIO_puts(bp, "\n") <= 0) goto end; } if (!BIO_hexdump(bp, opp, ((dump == -1 || dump > os->length)?os->length:dump), dump_indent)) goto end; nl=1; } } if (os != NULL) { M_ASN1_OCTET_STRING_free(os); os=NULL; } } else if (tag == V_ASN1_INTEGER) { ASN1_INTEGER *bs; int i; opp=op; bs=d2i_ASN1_INTEGER(NULL,&opp,len+hl); if (bs != NULL) { if (BIO_puts(bp, ":") <= 0) goto end; if (bs->type == V_ASN1_NEG_INTEGER) if (BIO_puts(bp, "-") <= 0) goto end; for (i=0; i<bs->length; i++) { if (BIO_printf(bp,"%02X", bs->data[i]) <= 0) goto end; } if (bs->length == 0) { if (BIO_puts(bp, "00") <= 0) goto end; } } else { if (BIO_puts(bp, "BAD INTEGER") <= 0) goto end; } M_ASN1_INTEGER_free(bs); } else if (tag == V_ASN1_ENUMERATED) { ASN1_ENUMERATED *bs; int i; opp=op; bs=d2i_ASN1_ENUMERATED(NULL,&opp,len+hl); if (bs != NULL) { if (BIO_puts(bp, ":") <= 0) goto end; if (bs->type == V_ASN1_NEG_ENUMERATED) if (BIO_puts(bp, "-") <= 0) goto end; for (i=0; i<bs->length; i++) { if (BIO_printf(bp,"%02X", bs->data[i]) <= 0) goto end; } if (bs->length == 0) { if (BIO_puts(bp, "00") <= 0) goto end; } } else { if (BIO_puts(bp, "BAD ENUMERATED") <= 0) goto end; } M_ASN1_ENUMERATED_free(bs); } else if (len > 0 && dump) { if (!nl) { if (BIO_puts(bp, "\n") <= 0) goto end; } if (!BIO_hexdump(bp,p, ((dump == -1 || dump > len)?len:dump), dump_indent)) goto end; nl=1; } if (!nl) { if (BIO_puts(bp, "\n") <= 0) goto end; } p+=len; if ((tag == V_ASN1_EOC) && (xclass == 0)) { ret=2; /* End of sequence */ goto end; } } length-=len; } ret=1; end: if (o != NULL) ASN1_OBJECT_free(o); if (os != NULL) M_ASN1_OCTET_STRING_free(os); *pp=p; return(ret); }