int MAIN(int argc, char **argv) { #ifndef OPENSSL_NO_ENGINE ENGINE *e = NULL; #endif int i, r, ret = 1; int badopt; char *outfile = NULL; char *inrand = NULL; int base64 = 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 (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 (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 - encode output\n"); goto err; } #ifndef OPENSSL_NO_ENGINE e = 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; BIO_write(out, buf, chunk); num -= chunk; } (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); }
int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, EVP_PKEY *key, unsigned char *sigin, int siglen, const char *sig_name, const char *md_name, const char *file, BIO *bmd) { size_t len; int i; for (;;) { i = BIO_read(bp, (char *)buf, BUFSIZE); if (i < 0) { BIO_printf(bio_err, "Read Error in %s\n", file); ERR_print_errors(bio_err); return 1; } if (i == 0) break; } if (sigin) { EVP_MD_CTX *ctx; BIO_get_md_ctx(bp, &ctx); i = EVP_DigestVerifyFinal(ctx, sigin, (unsigned int)siglen); if (i > 0) BIO_printf(out, "Verified OK\n"); else if (i == 0) { BIO_printf(out, "Verification Failure\n"); return 1; } else { BIO_printf(bio_err, "Error Verifying Data\n"); ERR_print_errors(bio_err); return 1; } return 0; } if (key) { EVP_MD_CTX *ctx; BIO_get_md_ctx(bp, &ctx); len = BUFSIZE; if (!EVP_DigestSignFinal(ctx, buf, &len)) { BIO_printf(bio_err, "Error Signing Data\n"); ERR_print_errors(bio_err); return 1; } } else { len = BIO_gets(bp, (char *)buf, BUFSIZE); if ((int)len < 0) { ERR_print_errors(bio_err); return 1; } } if (binout) BIO_write(out, buf, len); else if (sep == 2) { for (i = 0; i < (int)len; i++) BIO_printf(out, "%02x", buf[i]); BIO_printf(out, " *%s\n", file); } else { if (sig_name) { BIO_puts(out, sig_name); if (md_name) BIO_printf(out, "-%s", md_name); BIO_printf(out, "(%s)= ", file); } else if (md_name) BIO_printf(out, "%s(%s)= ", md_name, file); else BIO_printf(out, "(%s)= ", file); for (i = 0; i < (int)len; i++) { if (sep && (i != 0)) BIO_printf(out, ":"); BIO_printf(out, "%02x", buf[i]); } BIO_printf(out, "\n"); } return 0; }
int smime_main(int argc, char **argv) { BIO *in = NULL, *out = NULL, *indata = NULL; EVP_PKEY *key = NULL; PKCS7 *p7 = 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; const EVP_CIPHER *cipher = NULL; const EVP_MD *sign_md = NULL; const char *CAfile = NULL, *CApath = NULL, *prog = NULL; char *certfile = NULL, *keyfile = NULL, *contfile = NULL, *inrand = NULL; char *infile = NULL, *outfile = NULL, *signerfile = NULL, *recipfile = NULL; char *passinarg = NULL, *passin = NULL, *to = NULL, *from = NULL, *subject = NULL; OPTION_CHOICE o; int noCApath = 0, noCAfile = 0; int flags = PKCS7_DETACHED, operation = 0, ret = 0, need_rand = 0, indef = 0; int informat = FORMAT_SMIME, outformat = FORMAT_SMIME, keyform = FORMAT_PEM; int vpmtouched = 0, rv = 0; ENGINE *e = NULL; const char *mime_eol = "\n"; if ((vpm = X509_VERIFY_PARAM_new()) == NULL) return 1; prog = opt_init(argc, argv, smime_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(smime_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PDS, &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_RESIGN: operation = SMIME_RESIGN; break; case OPT_VERIFY: operation = SMIME_VERIFY; break; case OPT_PK7OUT: operation = SMIME_PK7OUT; break; case OPT_TEXT: flags |= PKCS7_TEXT; break; case OPT_NOINTERN: flags |= PKCS7_NOINTERN; break; case OPT_NOVERIFY: flags |= PKCS7_NOVERIFY; break; case OPT_NOCHAIN: flags |= PKCS7_NOCHAIN; break; case OPT_NOCERTS: flags |= PKCS7_NOCERTS; break; case OPT_NOATTR: flags |= PKCS7_NOATTR; break; case OPT_NODETACH: flags &= ~PKCS7_DETACHED; break; case OPT_NOSMIMECAP: flags |= PKCS7_NOSMIMECAP; break; case OPT_BINARY: flags |= PKCS7_BINARY; break; case OPT_NOSIGS: flags |= PKCS7_NOSIGS; break; case OPT_STREAM: case OPT_INDEF: indef = 1; break; case OPT_NOINDEF: indef = 0; break; case OPT_CRLFEOL: flags |= PKCS7_CRLFEOL; mime_eol = "\r\n"; 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_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_RECIP: recipfile = opt_arg(); break; case OPT_MD: if (!opt_md(opt_arg(), &sign_md)) goto opthelp; break; case OPT_CIPHER: if (!opt_cipher(opt_unknown(), &cipher)) goto opthelp; break; case OPT_INKEY: /* If previous -inkey argument add signer to list */ if (keyfile) { if (signerfile == NULL) { BIO_printf(bio_err, "%s: Must have -signer before -inkey\n", prog); goto opthelp; } 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_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_CONTENT: contfile = opt_arg(); break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto opthelp; vpmtouched++; break; } } argc = opt_num_rest(); argv = opt_rest(); if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) { BIO_puts(bio_err, "Multiple signers or keys not allowed\n"); goto opthelp; } if (operation & SMIME_SIGNERS) { /* Check to see if any final signer needs to be appended */ if (keyfile && !signerfile) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto opthelp; } 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) { BIO_printf(bio_err, "No recipient certificate or key specified\n"); goto opthelp; } } else if (operation == SMIME_ENCRYPT) { if (argc == 0) { 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 &= ~PKCS7_DETACHED; if (!(operation & SMIME_OP)) { if (flags & PKCS7_BINARY) outformat = FORMAT_BINARY; } if (!(operation & SMIME_IP)) { if (flags & PKCS7_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 } encerts = sk_X509_new_null(); if (!encerts) goto end; while (*argv) { cert = load_cert(*argv, FORMAT_PEM, "recipient certificate file"); if (cert == NULL) goto end; sk_X509_push(encerts, cert); cert = NULL; argv++; } } if (certfile) { if (!load_certs(certfile, &other, FORMAT_PEM, NULL, "certificate file")) { ERR_print_errors(bio_err); goto end; } } if (recipfile && (operation == SMIME_DECRYPT)) { if ((recip = load_cert(recipfile, FORMAT_PEM, "recipient certificate file")) == NULL) { ERR_print_errors(bio_err); goto end; } } if (operation == SMIME_DECRYPT) { if (!keyfile) keyfile = recipfile; } else if (operation == SMIME_SIGN) { 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) p7 = SMIME_read_PKCS7(in, &indata); else if (informat == FORMAT_PEM) p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL); else if (informat == FORMAT_ASN1) p7 = d2i_PKCS7_bio(in, NULL); else { BIO_printf(bio_err, "Bad input format for PKCS#7 file\n"); goto end; } if (!p7) { 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; } } } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (operation == SMIME_VERIFY) { if ((store = setup_verify(CAfile, CApath, noCAfile, noCApath)) == NULL) goto end; X509_STORE_set_verify_cb(store, smime_cb); if (vpmtouched) X509_STORE_set1_param(store, vpm); } ret = 3; if (operation == SMIME_ENCRYPT) { if (indef) flags |= PKCS7_STREAM; p7 = PKCS7_encrypt(encerts, in, cipher, flags); } else if (operation & SMIME_SIGNERS) { int i; /* * If detached data content we only enable streaming if S/MIME output * format. */ if (operation == SMIME_SIGN) { if (flags & PKCS7_DETACHED) { if (outformat == FORMAT_SMIME) flags |= PKCS7_STREAM; } else if (indef) flags |= PKCS7_STREAM; flags |= PKCS7_PARTIAL; p7 = PKCS7_sign(NULL, NULL, other, in, flags); if (!p7) goto end; if (flags & PKCS7_NOCERTS) { for (i = 0; i < sk_X509_num(other); i++) { X509 *x = sk_X509_value(other, i); PKCS7_add_certificate(p7, x); } } } else flags |= PKCS7_REUSE_DIGEST; for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) { signerfile = sk_OPENSSL_STRING_value(sksigners, i); keyfile = sk_OPENSSL_STRING_value(skkeys, i); signer = load_cert(signerfile, FORMAT_PEM, "signer certificate"); if (!signer) goto end; key = load_key(keyfile, keyform, 0, passin, e, "signing key file"); if (!key) goto end; if (!PKCS7_sign_add_signer(p7, signer, key, sign_md, flags)) 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 & PKCS7_STREAM)) { if (!PKCS7_final(p7, in, flags)) goto end; } } if (!p7) { BIO_printf(bio_err, "Error creating PKCS#7 structure\n"); goto end; } ret = 4; if (operation == SMIME_DECRYPT) { if (!PKCS7_decrypt(p7, key, recip, out, flags)) { BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n"); goto end; } } else if (operation == SMIME_VERIFY) { STACK_OF(X509) *signers; if (PKCS7_verify(p7, other, store, indata, out, flags)) BIO_printf(bio_err, "Verification successful\n"); else { BIO_printf(bio_err, "Verification failure\n"); goto end; } signers = PKCS7_get0_signers(p7, other, flags); if (!save_certs(signerfile, signers)) { BIO_printf(bio_err, "Error writing signers to %s\n", signerfile); ret = 5; goto end; } sk_X509_free(signers); } else if (operation == SMIME_PK7OUT) PEM_write_bio_PKCS7(out, p7); else { if (to) BIO_printf(out, "To: %s%s", to, mime_eol); if (from) BIO_printf(out, "From: %s%s", from, mime_eol); if (subject) BIO_printf(out, "Subject: %s%s", subject, mime_eol); if (outformat == FORMAT_SMIME) { if (operation == SMIME_RESIGN) rv = SMIME_write_PKCS7(out, p7, indata, flags); else rv = SMIME_write_PKCS7(out, p7, in, flags); } else if (outformat == FORMAT_PEM) rv = PEM_write_bio_PKCS7_stream(out, p7, in, flags); else if (outformat == FORMAT_ASN1) rv = i2d_PKCS7_bio_stream(out, p7, in, flags); else { BIO_printf(bio_err, "Bad output format for PKCS#7 file\n"); goto end; } if (rv == 0) { BIO_printf(bio_err, "Error writing output\n"); ret = 3; goto end; } } ret = 0; end: if (need_rand) app_RAND_write_file(NULL); if (ret) ERR_print_errors(bio_err); 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); X509_STORE_free(store); X509_free(cert); X509_free(recip); X509_free(signer); EVP_PKEY_free(key); PKCS7_free(p7); BIO_free(in); BIO_free(indata); BIO_free_all(out); OPENSSL_free(passin); return (ret); }
int dh_main(int argc, char **argv) { DH *dh = NULL; int i, badops = 0, text = 0; BIO *in = NULL, *out = NULL; int informat, outformat, check = 0, noout = 0, C = 0, ret = 1; char *infile, *outfile, *prog; #ifndef OPENSSL_NO_ENGINE char *engine; #endif #ifndef OPENSSL_NO_ENGINE engine = NULL; #endif 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); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } #endif else if (strcmp(*argv, "-check") == 0) check = 1; else if (strcmp(*argv, "-text") == 0) text = 1; else if (strcmp(*argv, "-C") == 0) C = 1; else if (strcmp(*argv, "-noout") == 0) noout = 1; 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 - one of DER PEM\n"); BIO_printf(bio_err, " -outform arg output format - one of DER PEM\n"); BIO_printf(bio_err, " -in arg input file\n"); BIO_printf(bio_err, " -out arg output file\n"); BIO_printf(bio_err, " -check check the DH parameters\n"); BIO_printf(bio_err, " -text print a text form of the DH parameters\n"); BIO_printf(bio_err, " -C Output C code\n"); BIO_printf(bio_err, " -noout no output\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " -engine e use engine e, possibly a hardware device.\n"); #endif goto end; } #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) { perror(infile); 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 (informat == FORMAT_ASN1) dh = d2i_DHparams_bio(in, NULL); else if (informat == FORMAT_PEM) dh = PEM_read_bio_DHparams(in, NULL, NULL, NULL); else { BIO_printf(bio_err, "bad input format specified\n"); goto end; } if (dh == NULL) { BIO_printf(bio_err, "unable to load DH parameters\n"); ERR_print_errors(bio_err); goto end; } if (text) { DHparams_print(out, dh); } if (check) { if (!DH_check(dh, &i)) { ERR_print_errors(bio_err); goto end; } if (i & DH_CHECK_P_NOT_PRIME) printf("p value is not prime\n"); if (i & DH_CHECK_P_NOT_SAFE_PRIME) printf("p value is not a safe prime\n"); if (i & DH_UNABLE_TO_CHECK_GENERATOR) printf("unable to check the generator value\n"); if (i & DH_NOT_SUITABLE_GENERATOR) printf("the g value is not a generator\n"); if (i == 0) printf("DH parameters appear to be ok.\n"); } if (C) { unsigned char *data; int len, l, bits; len = BN_num_bytes(dh->p); bits = BN_num_bits(dh->p); data = malloc(len); if (data == NULL) { perror("malloc"); goto end; } l = BN_bn2bin(dh->p, data); printf("static unsigned char dh%d_p[] = {", bits); for (i = 0; i < l; i++) { if ((i % 12) == 0) printf("\n\t"); printf("0x%02X, ", data[i]); } printf("\n\t};\n"); l = BN_bn2bin(dh->g, data); printf("static unsigned char dh%d_g[] = {", bits); for (i = 0; i < l; i++) { if ((i % 12) == 0) printf("\n\t"); printf("0x%02X, ", data[i]); } printf("\n\t};\n\n"); printf("DH *get_dh%d()\n\t{\n", bits); printf("\tDH *dh;\n\n"); printf("\tif ((dh = DH_new()) == NULL) return(NULL);\n"); printf("\tdh->p = BN_bin2bn(dh%d_p, sizeof(dh%d_p), NULL);\n", bits, bits); printf("\tdh->g = BN_bin2bn(dh%d_g, sizeof(dh%d_g), NULL);\n", bits, bits); printf("\tif ((dh->p == NULL) || (dh->g == NULL))\n"); printf("\t\treturn(NULL);\n"); printf("\treturn(dh);\n\t}\n"); free(data); } if (!noout) { if (outformat == FORMAT_ASN1) i = i2d_DHparams_bio(out, dh); else if (outformat == FORMAT_PEM) i = PEM_write_bio_DHparams(out, dh); else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write DH parameters\n"); ERR_print_errors(bio_err); goto end; } } ret = 0; end: BIO_free(in); if (out != NULL) BIO_free_all(out); if (dh != NULL) DH_free(dh); 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 = 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; X509_gmtime_adj(X509_get_notBefore(x), 0); X509_time_adj_ex(X509_get_notAfter(x), days, 0, NULL); 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 (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) { 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(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) { 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) { 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_get_notBefore(x)); BIO_puts(out, "\n"); } else if (enddate == i) { BIO_puts(out, "notAfter="); ASN1_TIME_print(out, X509_get_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_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; } print_cert_checks(out, x, checkhost, checkemail, checkip); if (noout || nocert) { ret = 0; goto end; } if (badsig) { ASN1_BIT_STRING *signature; unsigned char *s; X509_get0_signature(&signature, NULL, x); s = ASN1_STRING_data(signature); s[ASN1_STRING_length(signature) - 1] ^= 0x1; } 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); OPENSSL_free(passin); return (ret); }
static int reply_command(CONF * conf, char *section, char *queryfile, char *passin, char *inkey, char *signer, char *chain, const char *policy, char *in, int token_in, char *out, int token_out, int text) { int ret = 0; TS_RESP *response = NULL; BIO *in_bio = NULL; BIO *query_bio = NULL; BIO *inkey_bio = NULL; BIO *signer_bio = NULL; BIO *out_bio = NULL; /* Build response object either from response or query. */ if (in != NULL) { if ((in_bio = BIO_new_file(in, "rb")) == NULL) goto end; if (token_in) { /* * We have a ContentInfo (PKCS7) object, add * 'granted' status info around it. */ response = read_PKCS7(in_bio); } else { /* We have a ready-made TS_RESP object. */ response = d2i_TS_RESP_bio(in_bio, NULL); } } else { response = create_response(conf, section, queryfile, passin, inkey, signer, chain, policy); if (response) BIO_printf(bio_err, "Response has been generated.\n"); else BIO_printf(bio_err, "Response is not generated.\n"); } if (response == NULL) goto end; /* Write response either in ASN.1 or text format. */ if ((out_bio = BIO_open_with_default(out, "wb", stdout)) == NULL) goto end; if (text) { /* Text output. */ if (token_out) { TS_TST_INFO *tst_info = TS_RESP_get_tst_info(response); if (!TS_TST_INFO_print_bio(out_bio, tst_info)) goto end; } else { if (!TS_RESP_print_bio(out_bio, response)) goto end; } } else { /* ASN.1 DER output. */ if (token_out) { PKCS7 *token = TS_RESP_get_token(response); if (!i2d_PKCS7_bio(out_bio, token)) goto end; } else { if (!i2d_TS_RESP_bio(out_bio, response)) goto end; } } ret = 1; end: ERR_print_errors(bio_err); /* Clean up. */ BIO_free_all(in_bio); BIO_free_all(query_bio); BIO_free_all(inkey_bio); BIO_free_all(signer_bio); BIO_free_all(out_bio); TS_RESP_free(response); return ret; }
int MAIN(int argc, char **argv) { int i,badops=0,offset=0,ret=1,j; unsigned int length=0; long num,tmplen; BIO *in=NULL,*out=NULL,*b64=NULL, *derout = NULL; int informat,indent=0, noout = 0, dump = 0; char *infile=NULL,*str=NULL,*prog,*oidfile=NULL, *derfile=NULL; char *genstr=NULL, *genconf=NULL; unsigned char *tmpbuf; const unsigned char *ctmpbuf; BUF_MEM *buf=NULL; STACK *osk=NULL; ASN1_TYPE *at=NULL; informat=FORMAT_PEM; 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; prog=argv[0]; argc--; argv++; if ((osk=sk_new_null()) == NULL) { BIO_printf(bio_err,"Memory allocation failure\n"); goto end; } while (argc >= 1) { if (strcmp(*argv,"-inform") == 0) { if (--argc < 1) goto bad; informat=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; derfile= *(++argv); } else if (strcmp(*argv,"-i") == 0) { indent=1; } else if (strcmp(*argv,"-noout") == 0) noout = 1; else if (strcmp(*argv,"-oid") == 0) { if (--argc < 1) goto bad; oidfile= *(++argv); } else if (strcmp(*argv,"-offset") == 0) { if (--argc < 1) goto bad; offset= atoi(*(++argv)); } else if (strcmp(*argv,"-length") == 0) { if (--argc < 1) goto bad; length= atoi(*(++argv)); if (length == 0) goto bad; } else if (strcmp(*argv,"-dump") == 0) { dump= -1; } else if (strcmp(*argv,"-dlimit") == 0) { if (--argc < 1) goto bad; dump= atoi(*(++argv)); if (dump <= 0) goto bad; } else if (strcmp(*argv,"-strparse") == 0) { if (--argc < 1) goto bad; sk_push(osk,*(++argv)); } else if (strcmp(*argv,"-genstr") == 0) { if (--argc < 1) goto bad; genstr= *(++argv); } else if (strcmp(*argv,"-genconf") == 0) { if (--argc < 1) goto bad; genconf= *(++argv); } 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\n",prog); BIO_printf(bio_err,"where options are\n"); BIO_printf(bio_err," -inform arg input format - one of DER PEM\n"); BIO_printf(bio_err," -in arg input file\n"); BIO_printf(bio_err," -out arg output file (output format is always DER\n"); BIO_printf(bio_err," -noout arg don't produce any output\n"); BIO_printf(bio_err," -offset arg offset into file\n"); BIO_printf(bio_err," -length arg length of section in file\n"); BIO_printf(bio_err," -i indent entries\n"); BIO_printf(bio_err," -dump dump unknown data in hex form\n"); BIO_printf(bio_err," -dlimit arg dump the first arg bytes of unknown data in hex form\n"); BIO_printf(bio_err," -oid file file of extra oid definitions\n"); BIO_printf(bio_err," -strparse offset\n"); BIO_printf(bio_err," a series of these can be used to 'dig' into multiple\n"); BIO_printf(bio_err," ASN1 blob wrappings\n"); BIO_printf(bio_err," -genstr str string to generate ASN1 structure from\n"); BIO_printf(bio_err," -genconf file file to generate ASN1 structure from\n"); goto end; } ERR_load_crypto_strings(); in=BIO_new(BIO_s_file()); out=BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL)) { ERR_print_errors(bio_err); goto end; } 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 (oidfile != NULL) { if (BIO_read_filename(in,oidfile) <= 0) { BIO_printf(bio_err,"problems opening %s\n",oidfile); ERR_print_errors(bio_err); goto end; } OBJ_create_objects(in); } if (infile == NULL) BIO_set_fp(in,stdin,BIO_NOCLOSE); else { if (BIO_read_filename(in,infile) <= 0) { perror(infile); goto end; } } if (derfile) { if(!(derout = BIO_new_file(derfile, "wb"))) { BIO_printf(bio_err,"problems opening %s\n",derfile); ERR_print_errors(bio_err); goto end; } } if ((buf=BUF_MEM_new()) == NULL) goto end; if (!BUF_MEM_grow(buf,BUFSIZ*8)) goto end; /* Pre-allocate :-) */ if (genstr || genconf) { num = do_generate(bio_err, genstr, genconf, buf); if (num < 0) { ERR_print_errors(bio_err); goto end; } } else { if (informat == FORMAT_PEM) { BIO *tmp; if ((b64=BIO_new(BIO_f_base64())) == NULL) goto end; BIO_push(b64,in); tmp=in; in=b64; b64=tmp; } num=0; for (;;) { if (!BUF_MEM_grow(buf,(int)num+BUFSIZ)) goto end; i=BIO_read(in,&(buf->data[num]),BUFSIZ); if (i <= 0) break; num+=i; } } str=buf->data; /* If any structs to parse go through in sequence */ if (sk_num(osk)) { tmpbuf=(unsigned char *)str; tmplen=num; for (i=0; i<sk_num(osk); i++) { ASN1_TYPE *atmp; int typ; j=atoi(sk_value(osk,i)); if (j == 0) { BIO_printf(bio_err,"'%s' is an invalid number\n",sk_value(osk,i)); continue; } tmpbuf+=j; tmplen-=j; atmp = at; ctmpbuf = tmpbuf; at = d2i_ASN1_TYPE(NULL,&ctmpbuf,tmplen); ASN1_TYPE_free(atmp); if(!at) { BIO_printf(bio_err,"Error parsing structure\n"); ERR_print_errors(bio_err); goto end; } typ = ASN1_TYPE_get(at); if ((typ == V_ASN1_OBJECT) || (typ == V_ASN1_NULL)) { BIO_printf(bio_err, "Can't parse %s type\n", typ == V_ASN1_NULL ? "NULL" : "OBJECT"); ERR_print_errors(bio_err); goto end; } /* hmm... this is a little evil but it works */ tmpbuf=at->value.asn1_string->data; tmplen=at->value.asn1_string->length; } str=(char *)tmpbuf; num=tmplen; } if (offset >= num) { BIO_printf(bio_err, "Error: offset too large\n"); goto end; } num -= offset; if ((length == 0) || ((long)length > num)) length=(unsigned int)num; if(derout) { if(BIO_write(derout, str + offset, length) != (int)length) { BIO_printf(bio_err, "Error writing output\n"); ERR_print_errors(bio_err); goto end; } } if (!noout && !ASN1_parse_dump(out,(unsigned char *)&(str[offset]),length, indent,dump)) { ERR_print_errors(bio_err); goto end; } ret=0; end: BIO_free(derout); if (in != NULL) BIO_free(in); if (out != NULL) BIO_free_all(out); if (b64 != NULL) BIO_free(b64); if (ret != 0) ERR_print_errors(bio_err); if (buf != NULL) BUF_MEM_free(buf); if (at != NULL) ASN1_TYPE_free(at); if (osk != NULL) sk_free(osk); OBJ_cleanup(); apps_shutdown(); OPENSSL_EXIT(ret); }
int ocsp_main(int argc, char **argv) { BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL; const EVP_MD *cert_id_md = NULL, *rsign_md = NULL; CA_DB *rdb = NULL; EVP_PKEY *key = NULL, *rkey = NULL; OCSP_BASICRESP *bs = NULL; OCSP_REQUEST *req = NULL; OCSP_RESPONSE *resp = NULL; STACK_OF(CONF_VALUE) *headers = NULL; STACK_OF(OCSP_CERTID) *ids = NULL; STACK_OF(OPENSSL_STRING) *reqnames = NULL; STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL; STACK_OF(X509) *issuers = NULL; X509 *issuer = NULL, *cert = NULL, *rca_cert = NULL; X509 *signer = NULL, *rsigner = NULL; X509_STORE *store = NULL; X509_VERIFY_PARAM *vpm = NULL; char *CAfile = NULL, *CApath = NULL, *header, *value; char *host = NULL, *port = NULL, *path = "/", *outfile = NULL; char *rca_filename = NULL, *reqin = NULL, *respin = NULL; char *reqout = NULL, *respout = NULL, *ridx_filename = NULL; char *rsignfile = NULL, *rkeyfile = NULL; char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL; char *signfile = NULL, *keyfile = NULL; char *thost = NULL, *tport = NULL, *tpath = NULL; int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1; int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1; int req_text = 0, resp_text = 0, req_timeout = -1, ret = 1; long nsec = MAX_VALIDITY_PERIOD, maxage = -1; unsigned long sign_flags = 0, verify_flags = 0, rflags = 0; OPTION_CHOICE o; char *prog; reqnames = sk_OPENSSL_STRING_new_null(); if (!reqnames) goto end; ids = sk_OCSP_CERTID_new_null(); if (!ids) goto end; if ((vpm = X509_VERIFY_PARAM_new()) == NULL) return 1; prog = opt_init(argc, argv, ocsp_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: ret = 0; opt_help(ocsp_options); goto end; case OPT_OUTFILE: outfile = opt_arg(); break; case OPT_TIMEOUT: req_timeout = atoi(opt_arg()); break; case OPT_URL: OPENSSL_free(thost); OPENSSL_free(tport); OPENSSL_free(tpath); if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) { BIO_printf(bio_err, "%s Error parsing URL\n", prog); goto end; } thost = host; tport = port; tpath = path; break; case OPT_HOST: host = opt_arg(); break; case OPT_PORT: port = opt_arg(); break; case OPT_IGNORE_ERR: ignore_err = 1; break; case OPT_NOVERIFY: noverify = 1; break; case OPT_NONCE: add_nonce = 2; break; case OPT_NO_NONCE: add_nonce = 0; break; case OPT_RESP_NO_CERTS: rflags |= OCSP_NOCERTS; break; case OPT_RESP_KEY_ID: rflags |= OCSP_RESPID_KEY; break; case OPT_NO_CERTS: sign_flags |= OCSP_NOCERTS; break; case OPT_NO_SIGNATURE_VERIFY: verify_flags |= OCSP_NOSIGS; break; case OPT_NO_CERT_VERIFY: verify_flags |= OCSP_NOVERIFY; break; case OPT_NO_CHAIN: verify_flags |= OCSP_NOCHAIN; break; case OPT_NO_CERT_CHECKS: verify_flags |= OCSP_NOCHECKS; break; case OPT_NO_EXPLICIT: verify_flags |= OCSP_NOEXPLICIT; break; case OPT_TRUST_OTHER: verify_flags |= OCSP_TRUSTOTHER; break; case OPT_NO_INTERN: verify_flags |= OCSP_NOINTERN; break; case OPT_BADSIG: badsig = 1; break; case OPT_TEXT: req_text = resp_text = 1; break; case OPT_REQ_TEXT: req_text = 1; break; case OPT_RESP_TEXT: resp_text = 1; break; case OPT_REQIN: reqin = opt_arg(); break; case OPT_RESPIN: respin = opt_arg(); break; case OPT_SIGNER: signfile = opt_arg(); break; case OPT_VAFILE: verify_certfile = opt_arg(); verify_flags |= OCSP_TRUSTOTHER; break; case OPT_SIGN_OTHER: sign_certfile = opt_arg(); break; case OPT_VERIFY_OTHER: verify_certfile = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_VALIDITY_PERIOD: opt_long(opt_arg(), &nsec); break; case OPT_STATUS_AGE: opt_long(opt_arg(), &maxage); break; case OPT_SIGNKEY: keyfile = opt_arg(); break; case OPT_REQOUT: reqout = opt_arg(); break; case OPT_RESPOUT: respout = opt_arg(); break; case OPT_PATH: path = opt_arg(); break; case OPT_ISSUER: X509_free(issuer); issuer = load_cert(opt_arg(), FORMAT_PEM, NULL, NULL, "issuer certificate"); if (issuer == NULL) goto end; if ((issuers = sk_X509_new_null()) == NULL) goto end; sk_X509_push(issuers, issuer); break; case OPT_CERT: X509_free(cert); cert = load_cert(opt_arg(), FORMAT_PEM, NULL, NULL, "certificate"); if (cert == NULL) goto end; if (cert_id_md == NULL) cert_id_md = EVP_sha1(); if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids)) goto end; if (!sk_OPENSSL_STRING_push(reqnames, opt_arg())) goto end; break; case OPT_SERIAL: if (cert_id_md == NULL) cert_id_md = EVP_sha1(); if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids)) goto end; if (!sk_OPENSSL_STRING_push(reqnames, opt_arg())) goto end; break; case OPT_INDEX: ridx_filename = opt_arg(); break; case OPT_CA: rca_filename = opt_arg(); break; case OPT_NMIN: opt_int(opt_arg(), &nmin); if (ndays == -1) ndays = 0; break; case OPT_REQUEST: opt_int(opt_arg(), &accept_count); break; case OPT_NDAYS: ndays = atoi(opt_arg()); break; case OPT_RSIGNER: rsignfile = opt_arg(); break; case OPT_RKEY: rkeyfile = opt_arg(); break; case OPT_ROTHER: rcertfile = opt_arg(); break; case OPT_RMD: if (!opt_md(opt_arg(), &rsign_md)) goto end; break; case OPT_HEADER: header = opt_arg(); value = strchr(header, '='); if (value == NULL) { BIO_printf(bio_err, "Missing = in header key=value\n"); goto opthelp; } *value++ = '\0'; if (!X509V3_add_value(header, value, &headers)) goto end; break; case OPT_MD: if (cert_id_md != NULL) { BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n", prog); goto opthelp; } if (!opt_md(opt_unknown(), &cert_id_md)) goto opthelp; break; } } argc = opt_num_rest(); argv = opt_rest(); /* Have we anything to do? */ if (!req && !reqin && !respin && !(port && ridx_filename)) goto opthelp; if (!app_load_modules(NULL)) goto end; out = bio_open_default(outfile, "w"); if (out == NULL) goto end; if (!req && (add_nonce != 2)) add_nonce = 0; if (!req && reqin) { derbio = bio_open_default(reqin, "rb"); if (derbio == NULL) goto end; req = d2i_OCSP_REQUEST_bio(derbio, NULL); BIO_free(derbio); if (!req) { BIO_printf(bio_err, "Error reading OCSP request\n"); goto end; } } if (!req && port) { acbio = init_responder(port); if (!acbio) goto end; } if (rsignfile && !rdb) { if (!rkeyfile) rkeyfile = rsignfile; rsigner = load_cert(rsignfile, FORMAT_PEM, NULL, NULL, "responder certificate"); if (!rsigner) { BIO_printf(bio_err, "Error loading responder certificate\n"); goto end; } rca_cert = load_cert(rca_filename, FORMAT_PEM, NULL, NULL, "CA certificate"); if (rcertfile) { rother = load_certs(rcertfile, FORMAT_PEM, NULL, NULL, "responder other certificates"); if (!rother) goto end; } rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL, "responder private key"); if (!rkey) goto end; } if (acbio) BIO_printf(bio_err, "Waiting for OCSP client connections...\n"); redo_accept: if (acbio) { if (!do_responder(&req, &cbio, acbio, port)) goto end; if (!req) { resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL); send_ocsp_response(cbio, resp); goto done_resp; } } if (!req && (signfile || reqout || host || add_nonce || ridx_filename)) { BIO_printf(bio_err, "Need an OCSP request for this operation!\n"); goto end; } if (req && add_nonce) OCSP_request_add1_nonce(req, NULL, -1); if (signfile) { if (!keyfile) keyfile = signfile; signer = load_cert(signfile, FORMAT_PEM, NULL, NULL, "signer certificate"); if (!signer) { BIO_printf(bio_err, "Error loading signer certificate\n"); goto end; } if (sign_certfile) { sign_other = load_certs(sign_certfile, FORMAT_PEM, NULL, NULL, "signer certificates"); if (!sign_other) goto end; } key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL, "signer private key"); if (!key) goto end; if (!OCSP_request_sign (req, signer, key, NULL, sign_other, sign_flags)) { BIO_printf(bio_err, "Error signing OCSP request\n"); goto end; } } if (req_text && req) OCSP_REQUEST_print(out, req, 0); if (reqout) { derbio = bio_open_default(reqout, "wb"); if (derbio == NULL) goto end; i2d_OCSP_REQUEST_bio(derbio, req); BIO_free(derbio); } if (ridx_filename && (!rkey || !rsigner || !rca_cert)) { BIO_printf(bio_err, "Need a responder certificate, key and CA for this operation!\n"); goto end; } if (ridx_filename && !rdb) { rdb = load_index(ridx_filename, NULL); if (!rdb) goto end; if (!index_index(rdb)) goto end; } if (rdb) { make_ocsp_response(&resp, req, rdb, rca_cert, rsigner, rkey, rsign_md, rother, rflags, nmin, ndays, badsig); if (cbio) send_ocsp_response(cbio, resp); } else if (host) { # ifndef OPENSSL_NO_SOCK resp = process_responder(req, host, path, port, use_ssl, headers, req_timeout); if (!resp) goto end; # else BIO_printf(bio_err, "Error creating connect BIO - sockets not supported.\n"); goto end; # endif } else if (respin) { derbio = bio_open_default(respin, "rb"); if (derbio == NULL) goto end; resp = d2i_OCSP_RESPONSE_bio(derbio, NULL); BIO_free(derbio); if (!resp) { BIO_printf(bio_err, "Error reading OCSP response\n"); goto end; } } else { ret = 0; goto end; } done_resp: if (respout) { derbio = bio_open_default(respout, "wb"); if (derbio == NULL) goto end; i2d_OCSP_RESPONSE_bio(derbio, resp); BIO_free(derbio); } i = OCSP_response_status(resp); if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) { BIO_printf(out, "Responder Error: %s (%d)\n", OCSP_response_status_str(i), i); if (ignore_err) goto redo_accept; ret = 0; goto end; } if (resp_text) OCSP_RESPONSE_print(out, resp, 0); /* If running as responder don't verify our own response */ if (cbio) { if (--accept_count <= 0) { ret = 0; goto end; } BIO_free_all(cbio); cbio = NULL; OCSP_REQUEST_free(req); req = NULL; OCSP_RESPONSE_free(resp); resp = NULL; goto redo_accept; } if (ridx_filename) { ret = 0; goto end; } if (!store) { store = setup_verify(CAfile, CApath); if (!store) goto end; } if (vpmtouched) X509_STORE_set1_param(store, vpm); if (verify_certfile) { verify_other = load_certs(verify_certfile, FORMAT_PEM, NULL, NULL, "validator certificate"); if (!verify_other) goto end; } bs = OCSP_response_get1_basic(resp); if (!bs) { BIO_printf(bio_err, "Error parsing response\n"); goto end; } ret = 0; if (!noverify) { if (req && ((i = OCSP_check_nonce(req, bs)) <= 0)) { if (i == -1) BIO_printf(bio_err, "WARNING: no nonce in response\n"); else { BIO_printf(bio_err, "Nonce Verify error\n"); ret = 1; goto end; } } i = OCSP_basic_verify(bs, verify_other, store, verify_flags); if (i <= 0 && issuers) { i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER); if (i > 0) ERR_clear_error(); } if (i <= 0) { BIO_printf(bio_err, "Response Verify Failure\n"); ERR_print_errors(bio_err); ret = 1; } else BIO_printf(bio_err, "Response verify OK\n"); } print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage); end: ERR_print_errors(bio_err); X509_free(signer); X509_STORE_free(store); X509_VERIFY_PARAM_free(vpm); EVP_PKEY_free(key); EVP_PKEY_free(rkey); X509_free(cert); X509_free(rsigner); X509_free(rca_cert); free_index(rdb); BIO_free_all(cbio); BIO_free_all(acbio); BIO_free(out); OCSP_REQUEST_free(req); OCSP_RESPONSE_free(resp); OCSP_BASICRESP_free(bs); sk_OPENSSL_STRING_free(reqnames); sk_OCSP_CERTID_free(ids); sk_X509_pop_free(sign_other, X509_free); sk_X509_pop_free(verify_other, X509_free); sk_CONF_VALUE_pop_free(headers, X509V3_conf_free); OPENSSL_free(thost); OPENSSL_free(tport); OPENSSL_free(tpath); return (ret); }
int MAIN(int argc, char **argv) { int add_user = 0; int list_user= 0; int delete_user= 0; int modify_user= 0; char * user = NULL; char *passargin = NULL, *passargout = NULL; char *passin = NULL, *passout = NULL; char * gN = NULL; int gNindex = -1; char ** gNrow = NULL; int maxgN = -1; char * userinfo = NULL; int badops=0; int ret=1; int errors=0; int verbose=0; int doupdatedb=0; char *configfile=NULL; char *dbfile=NULL; CA_DB *db=NULL; char **pp ; int i; long errorline = -1; char *randfile=NULL; #ifndef OPENSSL_NO_ENGINE char *engine = NULL; #endif char *tofree=NULL; DB_ATTR db_attr; #ifdef EFENCE EF_PROTECT_FREE=1; EF_PROTECT_BELOW=1; EF_ALIGNMENT=0; #endif apps_startup(); conf = NULL; section = NULL; if (bio_err == NULL) if ((bio_err=BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT); argc--; argv++; while (argc >= 1 && badops == 0) { if (strcmp(*argv,"-verbose") == 0) verbose++; else if (strcmp(*argv,"-config") == 0) { if (--argc < 1) goto bad; configfile= *(++argv); } else if (strcmp(*argv,"-name") == 0) { if (--argc < 1) goto bad; section= *(++argv); } else if (strcmp(*argv,"-srpvfile") == 0) { if (--argc < 1) goto bad; dbfile= *(++argv); } else if (strcmp(*argv,"-add") == 0) add_user=1; else if (strcmp(*argv,"-delete") == 0) delete_user=1; else if (strcmp(*argv,"-modify") == 0) modify_user=1; else if (strcmp(*argv,"-list") == 0) list_user=1; else if (strcmp(*argv,"-gn") == 0) { if (--argc < 1) goto bad; gN= *(++argv); } else if (strcmp(*argv,"-userinfo") == 0) { if (--argc < 1) goto bad; userinfo= *(++argv); } else if (strcmp(*argv,"-passin") == 0) { if (--argc < 1) goto bad; passargin= *(++argv); } else if (strcmp(*argv,"-passout") == 0) { if (--argc < 1) goto bad; passargout= *(++argv); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv,"-engine") == 0) { if (--argc < 1) goto bad; engine= *(++argv); } #endif else if (**argv == '-') { bad: BIO_printf(bio_err,"unknown option %s\n",*argv); badops=1; break; } else break; argc--; argv++; } if (dbfile && configfile) { BIO_printf(bio_err,"-dbfile and -configfile cannot be specified together.\n"); badops = 1; } if (add_user+delete_user+modify_user+list_user != 1) { BIO_printf(bio_err,"Exactly one of the options -add, -delete, -modify -list must be specified.\n"); badops = 1; } if (delete_user+modify_user+delete_user== 1 && argc <= 0) { BIO_printf(bio_err,"Need at least one user for options -add, -delete, -modify. \n"); badops = 1; } if ((passin || passout) && argc != 1 ) { BIO_printf(bio_err,"-passin, -passout arguments only valid with one user.\n"); badops = 1; } if (badops) { for (pp=srp_usage; (*pp != NULL); pp++) BIO_printf(bio_err,"%s",*pp); BIO_printf(bio_err," -rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); BIO_printf(bio_err," load the file (or the files in the directory) into\n"); BIO_printf(bio_err," the random number generator\n"); goto err; } ERR_load_crypto_strings(); #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, engine, 0); #endif if(!app_passwd(bio_err, passargin, passargout, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto err; } if (!dbfile) { /*****************************************************************/ tofree=NULL; if (configfile == NULL) configfile = getenv("OPENSSL_CONF"); if (configfile == NULL) configfile = getenv("SSLEAY_CONF"); if (configfile == NULL) { const char *s=X509_get_default_cert_area(); size_t len; #ifdef OPENSSL_SYS_VMS len = strlen(s)+sizeof(CONFIG_FILE); tofree=OPENSSL_malloc(len); strcpy(tofree,s); #else len = strlen(s)+sizeof(CONFIG_FILE)+1; tofree=OPENSSL_malloc(len); BUF_strlcpy(tofree,s,len); BUF_strlcat(tofree,"/",len); #endif BUF_strlcat(tofree,CONFIG_FILE,len); configfile=tofree; } VERBOSE BIO_printf(bio_err,"Using configuration from %s\n",configfile); conf = NCONF_new(NULL); if (NCONF_load(conf,configfile,&errorline) <= 0) { if (errorline <= 0) BIO_printf(bio_err,"error loading the config file '%s'\n", configfile); else BIO_printf(bio_err,"error on line %ld of config file '%s'\n" ,errorline,configfile); goto err; } if(tofree) { OPENSSL_free(tofree); tofree = NULL; } if (!load_config(bio_err, conf)) goto err; /* Lets get the config section we are using */ if (section == NULL) { VERBOSE BIO_printf(bio_err,"trying to read " ENV_DEFAULT_SRP " in \" BASE_SECTION \"\n"); section=NCONF_get_string(conf,BASE_SECTION,ENV_DEFAULT_SRP); if (section == NULL) { lookup_fail(BASE_SECTION,ENV_DEFAULT_SRP); goto err; } } if (randfile == NULL && conf) randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE"); VERBOSE BIO_printf(bio_err,"trying to read " ENV_DATABASE " in section \"%s\"\n",section); if ((dbfile=NCONF_get_string(conf,section,ENV_DATABASE)) == NULL) { lookup_fail(section,ENV_DATABASE); goto err; } } if (randfile == NULL) ERR_clear_error(); else app_RAND_load_file(randfile, bio_err, 0); VERBOSE BIO_printf(bio_err,"Trying to read SRP verifier file \"%s\"\n",dbfile); db = load_index(dbfile, &db_attr); if (db == NULL) goto err; /* Lets check some fields */ for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = (char **)sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_srptype][0] == DB_SRP_INDEX) { maxgN = i; if (gNindex < 0 && gN != NULL && !strcmp(gN, pp[DB_srpid])) gNindex = i; print_index(db, bio_err, i, verbose > 1); } } VERBOSE BIO_printf(bio_err, "Database initialised\n"); if (gNindex >= 0) { gNrow = (char **)sk_OPENSSL_PSTRING_value(db->db->data, gNindex); print_entry(db, bio_err, gNindex, verbose > 1, "Default g and N") ; } else if (maxgN > 0 && !SRP_get_default_gN(gN)) { BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN); goto err; } else { VERBOSE BIO_printf(bio_err, "Database has no g N information.\n"); gNrow = NULL; } VVERBOSE BIO_printf(bio_err,"Starting user processing\n"); if (argc > 0) user = *(argv++) ; while (list_user || user) { int userindex = -1; if (user) VVERBOSE BIO_printf(bio_err, "Processing user \"%s\"\n", user); if ((userindex = get_index(db, user, 'U')) >= 0) { print_user(db, bio_err, userindex, (verbose > 0) || list_user); } if (list_user) { if (user == NULL) { BIO_printf(bio_err,"List all users\n"); for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { print_user(db,bio_err, i, 1); } list_user = 0; } else if (userindex < 0) { BIO_printf(bio_err, "user \"%s\" does not exist, ignored. t\n", user); errors++; } } else if (add_user) { if (userindex >= 0) { /* reactivation of a new user */ char **row = (char **)sk_OPENSSL_PSTRING_value(db->db->data, userindex); BIO_printf(bio_err, "user \"%s\" reactivated.\n", user); row[DB_srptype][0] = 'V'; doupdatedb = 1; } else { char *row[DB_NUMBER] ; char *gNid; row[DB_srpverifier] = NULL; row[DB_srpsalt] = NULL; row[DB_srpinfo] = NULL; if (!(gNid = srp_create_user(user,&(row[DB_srpverifier]), &(row[DB_srpsalt]),gNrow?gNrow[DB_srpsalt]:gN,gNrow?gNrow[DB_srpverifier]:NULL, passout, bio_err,verbose))) { BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned .\n", user); errors++; goto err; } row[DB_srpid] = BUF_strdup(user); row[DB_srptype] = BUF_strdup("v"); row[DB_srpgN] = BUF_strdup(gNid); if (!row[DB_srpid] || !row[DB_srpgN] || !row[DB_srptype] || !row[DB_srpverifier] || !row[DB_srpsalt] || (userinfo && (!(row[DB_srpinfo] = BUF_strdup(userinfo)))) || !update_index(db, bio_err, row)) { if (row[DB_srpid]) OPENSSL_free(row[DB_srpid]); if (row[DB_srpgN]) OPENSSL_free(row[DB_srpgN]); if (row[DB_srpinfo]) OPENSSL_free(row[DB_srpinfo]); if (row[DB_srptype]) OPENSSL_free(row[DB_srptype]); if (row[DB_srpverifier]) OPENSSL_free(row[DB_srpverifier]); if (row[DB_srpsalt]) OPENSSL_free(row[DB_srpsalt]); goto err; } doupdatedb = 1; } } else if (modify_user) { if (userindex < 0) { BIO_printf(bio_err,"user \"%s\" does not exist, operation ignored.\n",user); errors++; } else { char **row = (char **)sk_OPENSSL_PSTRING_value(db->db->data, userindex); char type = row[DB_srptype][0]; if (type == 'v') { BIO_printf(bio_err,"user \"%s\" already updated, operation ignored.\n",user); errors++; } else { char *gNid; if (row[DB_srptype][0] == 'V') { int user_gN; char **irow = NULL; VERBOSE BIO_printf(bio_err,"Verifying password for user \"%s\"\n",user); if ( (user_gN = get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0) irow = (char **)sk_OPENSSL_PSTRING_value(db->db->data, userindex); if (!srp_verify_user(user, row[DB_srpverifier], row[DB_srpsalt], irow ? irow[DB_srpsalt] : row[DB_srpgN], irow ? irow[DB_srpverifier] : NULL, passin, bio_err, verbose)) { BIO_printf(bio_err, "Invalid password for user \"%s\", operation abandoned.\n", user); errors++; goto err; } } VERBOSE BIO_printf(bio_err,"Password for user \"%s\" ok.\n",user); if (!(gNid=srp_create_user(user,&(row[DB_srpverifier]), &(row[DB_srpsalt]),gNrow?gNrow[DB_srpsalt]:NULL, gNrow?gNrow[DB_srpverifier]:NULL, passout, bio_err,verbose))) { BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned.\n", user); errors++; goto err; } row[DB_srptype][0] = 'v'; row[DB_srpgN] = BUF_strdup(gNid); if (!row[DB_srpid] || !row[DB_srpgN] || !row[DB_srptype] || !row[DB_srpverifier] || !row[DB_srpsalt] || (userinfo && (!(row[DB_srpinfo] = BUF_strdup(userinfo))))) goto err; doupdatedb = 1; } } } else if (delete_user) { if (userindex < 0) { BIO_printf(bio_err, "user \"%s\" does not exist, operation ignored. t\n", user); errors++; } else { char **xpp = (char **)sk_OPENSSL_PSTRING_value(db->db->data, userindex); BIO_printf(bio_err, "user \"%s\" revoked. t\n", user); xpp[DB_srptype][0] = 'R'; doupdatedb = 1; } } if (--argc > 0) user = *(argv++) ; else { user = NULL; list_user = 0; } } VERBOSE BIO_printf(bio_err,"User procession done.\n"); if (doupdatedb) { /* Lets check some fields */ for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = (char **)sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_srptype][0] == 'v') { pp[DB_srptype][0] = 'V'; print_user(db, bio_err, i, verbose); } } VERBOSE BIO_printf(bio_err, "Trying to update srpvfile.\n"); if (!save_index(dbfile, "new", db)) goto err; VERBOSE BIO_printf(bio_err, "Temporary srpvfile created.\n"); if (!rotate_index(dbfile, "new", "old")) goto err; VERBOSE BIO_printf(bio_err, "srpvfile updated.\n"); } ret = (errors != 0); err: if (errors != 0) VERBOSE BIO_printf(bio_err,"User errors %d.\n",errors); VERBOSE BIO_printf(bio_err,"SRP terminating with code %d.\n",ret); if(tofree) OPENSSL_free(tofree); if (ret) ERR_print_errors(bio_err); if (randfile) app_RAND_write_file(randfile, bio_err); if (conf) NCONF_free(conf); if (db) free_index(db); OBJ_cleanup(); apps_shutdown(); OPENSSL_EXIT(ret); }
int enc_main(int argc, char **argv) { static char buf[128]; static const char magic[] = "Salted__"; BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio = NULL, *wbio = NULL; EVP_CIPHER_CTX *ctx = NULL; const EVP_CIPHER *cipher = NULL, *c; const EVP_MD *dgst = NULL; char *hkey = NULL, *hiv = NULL, *hsalt = NULL, *p; char *infile = NULL, *outfile = NULL, *prog; char *str = NULL, *passarg = NULL, *pass = NULL, *strbuf = NULL; char mbuf[sizeof magic - 1]; OPTION_CHOICE o; int bsize = BSIZE, verbose = 0, debug = 0, olb64 = 0, nosalt = 0; int enc = 1, printkey = 0, i, k, base64 = 0; int ret = 1, inl, nopad = 0, non_fips_allow = 0; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char *buff = NULL, salt[PKCS5_SALT_LEN]; unsigned long n; #ifdef ZLIB int do_zlib = 0; BIO *bzl = NULL; #endif /* first check the program name */ prog = opt_progname(argv[0]); if (strcmp(prog, "base64") == 0) base64 = 1; #ifdef ZLIB else if (strcmp(prog, "zlib") == 0) do_zlib = 1; #endif else { cipher = EVP_get_cipherbyname(prog); if (cipher == NULL && strcmp(prog, "enc") != 0) { BIO_printf(bio_err, "%s is not a known cipher\n", prog); goto end; } } prog = opt_init(argc, argv, enc_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(enc_options); ret = 0; BIO_printf(bio_err, "Cipher Types\n"); OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, show_ciphers, bio_err); BIO_printf(bio_err, "\n"); goto end; case OPT_E: enc = 1; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_PASS: passarg = opt_arg(); break; case OPT_ENGINE: (void)setup_engine(opt_arg(), 0); break; case OPT_D: enc = 0; break; case OPT_P: printkey = 1; break; case OPT_V: verbose = 1; break; case OPT_NOPAD: nopad = 1; break; case OPT_SALT: nosalt = 0; break; case OPT_NOSALT: nosalt = 1; break; case OPT_DEBUG: debug = 1; break; case OPT_UPPER_P: printkey = 2; break; case OPT_UPPER_A: olb64 = 1; break; case OPT_A: base64 = 1; break; case OPT_Z: #ifdef ZLIB do_zlib = 1; #endif break; case OPT_BUFSIZE: p = opt_arg(); i = (int)strlen(p) - 1; k = i >= 1 && p[i] == 'k'; if (k) p[i] = '\0'; if (!opt_ulong(opt_arg(), &n)) goto opthelp; if (k) n *= 1024; bsize = (int)n; break; case OPT_K: str = opt_arg(); break; case OPT_KFILE: in = bio_open_default(opt_arg(), "r"); if (in == NULL) goto opthelp; i = BIO_gets(in, buf, sizeof buf); BIO_free(in); in = NULL; if (i <= 0) { BIO_printf(bio_err, "%s Can't read key from %s\n", prog, opt_arg()); goto opthelp; } while (--i > 0 && (buf[i] == '\r' || buf[i] == '\n')) buf[i] = '\0'; if (i <= 0) { BIO_printf(bio_err, "%s: zero length password\n", prog); goto opthelp; } str = buf; break; case OPT_UPPER_K: hkey = opt_arg(); break; case OPT_UPPER_S: hsalt = opt_arg(); break; case OPT_IV: hiv = opt_arg(); break; case OPT_MD: if (!opt_md(opt_arg(), &dgst)) goto opthelp; break; case OPT_NON_FIPS_ALLOW: non_fips_allow = 1; break; case OPT_CIPHER: if (!opt_cipher(opt_unknown(), &c)) goto opthelp; cipher = c; break; case OPT_NONE: cipher = NULL; break; } } argc = opt_num_rest(); argv = opt_rest(); if (cipher && EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) { BIO_printf(bio_err, "%s: AEAD ciphers not supported\n", prog); goto end; } if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_XTS_MODE)) { BIO_printf(bio_err, "%s XTS ciphers not supported\n", prog); goto end; } if (dgst == NULL) dgst = EVP_md5(); /* It must be large enough for a base64 encoded line */ if (base64 && bsize < 80) bsize = 80; if (verbose) BIO_printf(bio_err, "bufsize=%d\n", bsize); strbuf = app_malloc(SIZE, "strbuf"); buff = app_malloc(EVP_ENCODE_LENGTH(bsize), "evp buffer"); if (debug) { BIO_set_callback(in, BIO_debug_callback); BIO_set_callback(out, BIO_debug_callback); BIO_set_callback_arg(in, (char *)bio_err); BIO_set_callback_arg(out, (char *)bio_err); } if (infile == NULL) { unbuffer(stdin); in = dup_bio_in(); } else in = bio_open_default(infile, "r"); if (in == NULL) goto end; if (!str && passarg) { if (!app_passwd(passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } str = pass; } if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) { for (;;) { char prompt[200]; BIO_snprintf(prompt, sizeof prompt, "enter %s %s password:"******"encryption" : "decryption"); strbuf[0] = '\0'; i = EVP_read_pw_string((char *)strbuf, SIZE, prompt, enc); if (i == 0) { if (strbuf[0] == '\0') { ret = 1; goto end; } str = strbuf; break; } if (i < 0) { BIO_printf(bio_err, "bad password read\n"); goto end; } } } out = bio_open_default(outfile, "w"); if (out == NULL) goto end; rbio = in; wbio = out; #ifdef ZLIB if (do_zlib) { if ((bzl = BIO_new(BIO_f_zlib())) == NULL) goto end; if (enc) wbio = BIO_push(bzl, wbio); else rbio = BIO_push(bzl, rbio); } #endif if (base64) { if ((b64 = BIO_new(BIO_f_base64())) == NULL) goto end; if (debug) { BIO_set_callback(b64, BIO_debug_callback); BIO_set_callback_arg(b64, (char *)bio_err); } if (olb64) BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); if (enc) wbio = BIO_push(b64, wbio); else rbio = BIO_push(b64, rbio); } if (cipher != NULL) { /* * Note that str is NULL if a key was passed on the command line, so * we get no salt in that case. Is this a bug? */ if (str != NULL) { /* * Salt handling: if encrypting generate a salt and write to * output BIO. If decrypting read salt from input BIO. */ unsigned char *sptr; if (nosalt) sptr = NULL; else { if (enc) { if (hsalt) { if (!set_hex(hsalt, salt, sizeof salt)) { BIO_printf(bio_err, "invalid hex salt value\n"); goto end; } } else if (RAND_bytes(salt, sizeof salt) <= 0) goto end; /* * If -P option then don't bother writing */ if ((printkey != 2) && (BIO_write(wbio, magic, sizeof magic - 1) != sizeof magic - 1 || BIO_write(wbio, (char *)salt, sizeof salt) != sizeof salt)) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf || BIO_read(rbio, (unsigned char *)salt, sizeof salt) != sizeof salt) { BIO_printf(bio_err, "error reading input file\n"); goto end; } else if (memcmp(mbuf, magic, sizeof magic - 1)) { BIO_printf(bio_err, "bad magic number\n"); goto end; } sptr = salt; } if (!EVP_BytesToKey(cipher, dgst, sptr, (unsigned char *)str, strlen(str), 1, key, iv)) { BIO_printf(bio_err, "EVP_BytesToKey failed\n"); goto end; } /* * zero the complete buffer or the string passed from the command * line bug picked up by Larry J. Hughes Jr. <*****@*****.**> */ if (str == strbuf) OPENSSL_cleanse(str, SIZE); else OPENSSL_cleanse(str, strlen(str)); } if (hiv != NULL) { int siz = EVP_CIPHER_iv_length(cipher); if (siz == 0) { BIO_printf(bio_err, "warning: iv not use by this cipher\n"); } else if (!set_hex(hiv, iv, sizeof iv)) { BIO_printf(bio_err, "invalid hex iv value\n"); goto end; } } if ((hiv == NULL) && (str == NULL) && EVP_CIPHER_iv_length(cipher) != 0) { /* * No IV was explicitly set and no IV was generated during * EVP_BytesToKey. Hence the IV is undefined, making correct * decryption impossible. */ BIO_printf(bio_err, "iv undefined\n"); goto end; } if ((hkey != NULL) && !set_hex(hkey, key, EVP_CIPHER_key_length(cipher))) { BIO_printf(bio_err, "invalid hex key value\n"); goto end; } if ((benc = BIO_new(BIO_f_cipher())) == NULL) goto end; /* * Since we may be changing parameters work on the encryption context * rather than calling BIO_set_cipher(). */ BIO_get_cipher_ctx(benc, &ctx); if (non_fips_allow) EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPH_FLAG_NON_FIPS_ALLOW); if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto end; } if (nopad) EVP_CIPHER_CTX_set_padding(ctx, 0); if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_name(cipher)); ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback(benc, BIO_debug_callback); BIO_set_callback_arg(benc, (char *)bio_err); } if (printkey) { if (!nosalt) { printf("salt="); for (i = 0; i < (int)sizeof(salt); i++) printf("%02X", salt[i]); printf("\n"); } if (cipher->key_len > 0) { printf("key="); for (i = 0; i < cipher->key_len; i++) printf("%02X", key[i]); printf("\n"); } if (cipher->iv_len > 0) { printf("iv ="); for (i = 0; i < cipher->iv_len; i++) printf("%02X", iv[i]); printf("\n"); } if (printkey == 2) { ret = 0; goto end; } } } /* Only encrypt/decrypt as we write the file */ if (benc != NULL) wbio = BIO_push(benc, wbio); for (;;) { inl = BIO_read(rbio, (char *)buff, bsize); if (inl <= 0) break; if (BIO_write(wbio, (char *)buff, inl) != inl) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } if (!BIO_flush(wbio)) { BIO_printf(bio_err, "bad decrypt\n"); goto end; } ret = 0; if (verbose) { BIO_printf(bio_err, "bytes read :%8ld\n", BIO_number_read(in)); BIO_printf(bio_err, "bytes written:%8ld\n", BIO_number_written(out)); } end: ERR_print_errors(bio_err); OPENSSL_free(strbuf); OPENSSL_free(buff); BIO_free(in); BIO_free_all(out); BIO_free(benc); BIO_free(b64); #ifdef ZLIB BIO_free(bzl); #endif OPENSSL_free(pass); return (ret); }
int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflags, unsigned long cflag) { unsigned long l; int i; const char *neg; X509_REQ_INFO *ri; EVP_PKEY *pkey; STACK_OF(X509_ATTRIBUTE) *sk; 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; ri = x->req_info; 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)) { neg = (ri->version->type == V_ASN1_NEG_INTEGER) ? "-" : ""; l = 0; for (i = 0; i < ri->version->length; i++) { l <<= 8; l += ri->version->data[i]; } if (BIO_printf(bp, "%8sVersion: %s%lu (%s0x%lx)\n", "", neg, l, neg, 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, ri->subject, 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, ri->pubkey->algor->algorithm) <= 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; sk = x->req_info->attributes; if (sk_X509_ATTRIBUTE_num(sk) == 0) { if (BIO_printf(bp, "%12sa0:00\n", "") <= 0) goto err; } else { for (i = 0; i < sk_X509_ATTRIBUTE_num(sk); i++) { ASN1_TYPE *at; X509_ATTRIBUTE *a; ASN1_BIT_STRING *bs = NULL; ASN1_TYPE *t; int j, type = 0, count = 1, ii = 0; a = sk_X509_ATTRIBUTE_value(sk, i); if (X509_REQ_extension_nid( OBJ_obj2nid(a->object))) continue; if (BIO_printf(bp, "%12s", "") <= 0) goto err; if ((j = i2a_ASN1_OBJECT(bp, a->object)) > 0) { if (a->single) { t = a->value.single; type = t->type; bs = t->value.bit_string; } else { ii = 0; count = sk_ASN1_TYPE_num( a->value.set); get_next: at = sk_ASN1_TYPE_value( a->value.set, 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, ex->value); } if (BIO_write(bp, "\n", 1) <= 0) goto err; } sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); } } if (!(cflag & X509_FLAG_NO_SIGDUMP)) { if (!X509_signature_print(bp, x->sig_alg, x->signature)) goto err; } return (1); err: X509error(ERR_R_BUF_LIB); return (0); }
int MAIN(int argc, char **argv) { ENGINE *e = NULL; int ret=1; RSA *rsa=NULL; int i,badops=0, sgckey=0; const EVP_CIPHER *enc=NULL; BIO *out=NULL; int informat,outformat,text=0,check=0,noout=0; int pubin = 0, pubout = 0; char *infile,*outfile,*prog; char *passargin = NULL, *passargout = NULL; char *passin = NULL, *passout = NULL; #ifndef OPENSSL_NO_ENGINE char *engine=NULL; #endif int modulus=0; int pvk_encr = 2; apps_startup(); if (bio_err == NULL) if ((bio_err=BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err,OPENSSL_TYPE__FILE_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 (TINYCLR_SSL_STRCMP(*argv,"-inform") == 0) { if (--argc < 1) goto bad; informat=str2fmt(*(++argv)); } else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0) { if (--argc < 1) goto bad; outformat=str2fmt(*(++argv)); } else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0) { if (--argc < 1) goto bad; infile= *(++argv); } else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0) { if (--argc < 1) goto bad; outfile= *(++argv); } else if (TINYCLR_SSL_STRCMP(*argv,"-passin") == 0) { if (--argc < 1) goto bad; passargin= *(++argv); } else if (TINYCLR_SSL_STRCMP(*argv,"-passout") == 0) { if (--argc < 1) goto bad; passargout= *(++argv); } #ifndef OPENSSL_NO_ENGINE else if (TINYCLR_SSL_STRCMP(*argv,"-engine") == 0) { if (--argc < 1) goto bad; engine= *(++argv); } #endif else if (TINYCLR_SSL_STRCMP(*argv,"-sgckey") == 0) sgckey=1; else if (TINYCLR_SSL_STRCMP(*argv,"-pubin") == 0) pubin=1; else if (TINYCLR_SSL_STRCMP(*argv,"-pubout") == 0) pubout=1; else if (TINYCLR_SSL_STRCMP(*argv,"-RSAPublicKey_in") == 0) pubin = 2; else if (TINYCLR_SSL_STRCMP(*argv,"-RSAPublicKey_out") == 0) pubout = 2; else if (TINYCLR_SSL_STRCMP(*argv,"-pvk-strong") == 0) pvk_encr=2; else if (TINYCLR_SSL_STRCMP(*argv,"-pvk-weak") == 0) pvk_encr=1; else if (TINYCLR_SSL_STRCMP(*argv,"-pvk-none") == 0) pvk_encr=0; else if (TINYCLR_SSL_STRCMP(*argv,"-noout") == 0) noout=1; else if (TINYCLR_SSL_STRCMP(*argv,"-text") == 0) text=1; else if (TINYCLR_SSL_STRCMP(*argv,"-modulus") == 0) modulus=1; else if (TINYCLR_SSL_STRCMP(*argv,"-check") == 0) check=1; else if ((enc=EVP_get_cipherbyname(&(argv[0][1]))) == NULL) { 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 - one of DER NET PEM\n"); BIO_printf(bio_err," -outform arg output format - one of DER NET PEM\n"); BIO_printf(bio_err," -in arg input file\n"); BIO_printf(bio_err," -sgckey Use IIS SGC key format\n"); BIO_printf(bio_err," -passin arg input file pass phrase source\n"); BIO_printf(bio_err," -out arg output file\n"); BIO_printf(bio_err," -passout arg output file pass phrase source\n"); BIO_printf(bio_err," -des encrypt PEM output with cbc des\n"); BIO_printf(bio_err," -des3 encrypt PEM output with ede cbc des using 168 bit key\n"); #ifndef OPENSSL_NO_IDEA BIO_printf(bio_err," -idea encrypt PEM output with cbc idea\n"); #endif #ifndef OPENSSL_NO_SEED BIO_printf(bio_err," -seed encrypt PEM output with cbc seed\n"); #endif #ifndef OPENSSL_NO_AES BIO_printf(bio_err," -aes128, -aes192, -aes256\n"); BIO_printf(bio_err," encrypt PEM output with cbc aes\n"); #endif #ifndef OPENSSL_NO_CAMELLIA BIO_printf(bio_err," -camellia128, -camellia192, -camellia256\n"); BIO_printf(bio_err," encrypt PEM output with cbc camellia\n"); #endif BIO_printf(bio_err," -text print the key in text\n"); BIO_printf(bio_err," -noout don't print key out\n"); BIO_printf(bio_err," -modulus print the RSA key modulus\n"); BIO_printf(bio_err," -check verify key consistency\n"); BIO_printf(bio_err," -pubin expect a public key in input file\n"); BIO_printf(bio_err," -pubout output a public key\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err," -engine e use engine e, possibly a hardware device.\n"); #endif goto end; } ERR_load_crypto_strings(); #ifndef OPENSSL_NO_ENGINE e = setup_engine(bio_err, engine, 0); #endif if(!app_passwd(bio_err, passargin, passargout, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if(check && pubin) { BIO_printf(bio_err, "Only private keys can be checked\n"); goto end; } out=BIO_new(BIO_s_file()); { EVP_PKEY *pkey; if (pubin) { int tmpformat=-1; if (pubin == 2) { if (informat == FORMAT_PEM) tmpformat = FORMAT_PEMRSA; else if (informat == FORMAT_ASN1) tmpformat = FORMAT_ASN1RSA; } else if (informat == FORMAT_NETSCAPE && sgckey) tmpformat = FORMAT_IISSGC; else tmpformat = informat; pkey = load_pubkey(bio_err, infile, tmpformat, 1, passin, e, "Public Key"); } else pkey = load_key(bio_err, infile, (informat == FORMAT_NETSCAPE && sgckey ? FORMAT_IISSGC : informat), 1, passin, e, "Private Key"); if (pkey != NULL) rsa = EVP_PKEY_get1_RSA(pkey); EVP_PKEY_free(pkey); } if (rsa == NULL) { ERR_print_errors(bio_err); goto end; } if (outfile == NULL) { BIO_set_fp(out,OPENSSL_TYPE__FILE_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) { TINYCLR_SSL_PERROR(outfile); goto end; } } if (text) if (!RSA_print(out,rsa,0)) { TINYCLR_SSL_PERROR(outfile); ERR_print_errors(bio_err); goto end; } if (modulus) { BIO_printf(out,"Modulus="); BN_print(out,rsa->n); BIO_printf(out,"\n"); } if (check) { int r = RSA_check_key(rsa); if (r == 1) BIO_printf(out,"RSA key ok\n"); else if (r == 0) { unsigned long err; while ((err = ERR_peek_error()) != 0 && ERR_GET_LIB(err) == ERR_LIB_RSA && ERR_GET_FUNC(err) == RSA_F_RSA_CHECK_KEY && ERR_GET_REASON(err) != ERR_R_MALLOC_FAILURE) { BIO_printf(out, "RSA key error: %s\n", ERR_reason_error_string(err)); ERR_get_error(); /* remove e from error stack */ } } if (r == -1 || ERR_peek_error() != 0) /* should happen only if r == -1 */ { ERR_print_errors(bio_err); goto end; } } if (noout) { ret = 0; goto end; } BIO_printf(bio_err,"writing RSA key\n"); if (outformat == FORMAT_ASN1) { if(pubout || pubin) { if (pubout == 2) i=i2d_RSAPublicKey_bio(out,rsa); else i=i2d_RSA_PUBKEY_bio(out,rsa); } else i=i2d_RSAPrivateKey_bio(out,rsa); } #ifndef OPENSSL_NO_RC4 else if (outformat == FORMAT_NETSCAPE) { unsigned char *p,*pp; int size; i=1; size=i2d_RSA_NET(rsa,NULL,NULL, sgckey); if ((p=(unsigned char *)OPENSSL_malloc(size)) == NULL) { BIO_printf(bio_err,"Memory allocation failure\n"); goto end; } pp=p; i2d_RSA_NET(rsa,&p,NULL, sgckey); BIO_write(out,(char *)pp,size); OPENSSL_free(pp); } #endif else if (outformat == FORMAT_PEM) { if(pubout || pubin) { if (pubout == 2) i=PEM_write_bio_RSAPublicKey(out,rsa); else i=PEM_write_bio_RSA_PUBKEY(out,rsa); } else i=PEM_write_bio_RSAPrivateKey(out,rsa, enc,NULL,0,NULL,passout); #if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_RC4) } else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) { EVP_PKEY *pk; pk = EVP_PKEY_new(); EVP_PKEY_set1_RSA(pk, rsa); if (outformat == FORMAT_PVK) i = i2b_PVK_bio(out, pk, pvk_encr, 0, passout); else if (pubin || pubout) i = i2b_PublicKey_bio(out, pk); else i = i2b_PrivateKey_bio(out, pk); EVP_PKEY_free(pk); #endif } else { BIO_printf(bio_err,"bad output format specified for outfile\n"); goto end; } if (i <= 0) { BIO_printf(bio_err,"unable to write key\n"); ERR_print_errors(bio_err); } else ret=0; end: if(out != NULL) BIO_free_all(out); if(rsa != NULL) RSA_free(rsa); if(passin) OPENSSL_free(passin); if(passout) OPENSSL_free(passout); apps_shutdown(); OPENSSL_EXIT(ret); }
int MAIN(int argc, char **argv) { BN_GENCB cb; DH *dh=NULL; int ret=1,num=DEFBITS; int g=2; char *outfile=NULL; char *inrand=NULL; #ifndef OPENSSL_NO_ENGINE char *engine=NULL; #endif BIO *out=NULL; apps_startup(); BN_GENCB_set(&cb, dh_cb, bio_err); 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; argv++; argc--; for (;;) { if (argc <= 0) break; if (strcmp(*argv,"-out") == 0) { if (--argc < 1) goto bad; outfile= *(++argv); } else if (strcmp(*argv,"-2") == 0) g=2; /* else if (strcmp(*argv,"-3") == 0) g=3; */ else if (strcmp(*argv,"-5") == 0) g=5; #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv,"-engine") == 0) { if (--argc < 1) goto bad; engine= *(++argv); } #endif else if (strcmp(*argv,"-rand") == 0) { if (--argc < 1) goto bad; inrand= *(++argv); } else break; argv++; argc--; } if ((argc >= 1) && ((sscanf(*argv,"%d",&num) == 0) || (num < 0))) { bad: BIO_printf(bio_err,"usage: gendh [args] [numbits]\n"); BIO_printf(bio_err," -out file - output the key to 'file\n"); BIO_printf(bio_err," -2 - use 2 as the generator value\n"); /* BIO_printf(bio_err," -3 - use 3 as the generator value\n"); */ BIO_printf(bio_err," -5 - use 5 as the generator value\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...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); BIO_printf(bio_err," - load the file (or the files in the directory) into\n"); BIO_printf(bio_err," the random number generator\n"); goto end; } #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, engine, 0); #endif 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 (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL) { BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n"); } if (inrand != NULL) BIO_printf(bio_err,"%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); BIO_printf(bio_err,"Generating DH parameters, %d bit long safe prime, generator %d\n",num,g); BIO_printf(bio_err,"This is going to take a long time\n"); if(((dh = DH_new()) == NULL) || !DH_generate_parameters_ex(dh, num, g, &cb)) goto end; app_RAND_write_file(NULL, bio_err); if (!PEM_write_bio_DHparams(out,dh)) goto end; ret=0; end: if (ret != 0) ERR_print_errors(bio_err); if (out != NULL) BIO_free_all(out); if (dh != NULL) DH_free(dh); apps_shutdown(); OPENSSL_EXIT(ret); }
int MAIN(int argc, char **argv) { ENGINE *e = NULL; int i,badops=0, ret = 1; BIO *in = NULL,*out = NULL; int verify=0,noout=0,pubkey=0; char *infile = NULL,*outfile = NULL,*prog; char *passargin = NULL, *passin = NULL; char *spkac = "SPKAC", *spksect = "default", *spkstr = NULL; char *challenge = NULL, *keyfile = NULL; CONF *conf = NULL; NETSCAPE_SPKI *spki = NULL; EVP_PKEY *pkey = NULL; char *engine=NULL; apps_startup(); if (!bio_err) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE); if (!load_config(bio_err, NULL)) goto end; prog=argv[0]; argc--; argv++; while (argc >= 1) { 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,"-passin") == 0) { if (--argc < 1) goto bad; passargin= *(++argv); } else if (strcmp(*argv,"-key") == 0) { if (--argc < 1) goto bad; keyfile= *(++argv); } else if (strcmp(*argv,"-challenge") == 0) { if (--argc < 1) goto bad; challenge= *(++argv); } else if (strcmp(*argv,"-spkac") == 0) { if (--argc < 1) goto bad; spkac= *(++argv); } else if (strcmp(*argv,"-spksect") == 0) { if (--argc < 1) goto bad; spksect= *(++argv); } else if (strcmp(*argv,"-engine") == 0) { if (--argc < 1) goto bad; engine= *(++argv); } else if (strcmp(*argv,"-noout") == 0) noout=1; else if (strcmp(*argv,"-pubkey") == 0) pubkey=1; else if (strcmp(*argv,"-verify") == 0) verify=1; else badops = 1; argc--; argv++; } if (badops) { bad: BIO_printf(bio_err,"%s [options]\n",prog); BIO_printf(bio_err,"where options are\n"); BIO_printf(bio_err," -in arg input file\n"); BIO_printf(bio_err," -out arg output file\n"); BIO_printf(bio_err," -key arg create SPKAC using private key\n"); BIO_printf(bio_err," -passin arg input file pass phrase source\n"); BIO_printf(bio_err," -challenge arg challenge string\n"); BIO_printf(bio_err," -spkac arg alternative SPKAC name\n"); BIO_printf(bio_err," -noout don't print SPKAC\n"); BIO_printf(bio_err," -pubkey output public key\n"); BIO_printf(bio_err," -verify verify SPKAC signature\n"); BIO_printf(bio_err," -engine e use engine e, possibly a hardware device.\n"); goto end; } ERR_load_crypto_strings(); if(!app_passwd(bio_err, passargin, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } e = setup_engine(bio_err, engine, 0); if(keyfile) { pkey = load_key(bio_err, strcmp(keyfile, "-") ? keyfile : NULL, FORMAT_PEM, 1, passin, e, "private key"); if(!pkey) { goto end; } spki = NETSCAPE_SPKI_new(); if(challenge) ASN1_STRING_set(spki->spkac->challenge, challenge, strlen(challenge)); NETSCAPE_SPKI_set_pubkey(spki, pkey); NETSCAPE_SPKI_sign(spki, pkey, EVP_md5()); spkstr = NETSCAPE_SPKI_b64_encode(spki); if (outfile) 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\n"); ERR_print_errors(bio_err); goto end; } BIO_printf(out, "SPKAC=%s\n", spkstr); OPENSSL_free(spkstr); ret = 0; goto end; } if (infile) in = BIO_new_file(infile, "r"); else in = BIO_new_fp(stdin, BIO_NOCLOSE); if(!in) { BIO_printf(bio_err, "Error opening input file\n"); ERR_print_errors(bio_err); goto end; } conf = NCONF_new(NULL); i = NCONF_load_bio(conf, in, NULL); if(!i) { BIO_printf(bio_err, "Error parsing config file\n"); ERR_print_errors(bio_err); goto end; } spkstr = NCONF_get_string(conf, spksect, spkac); if(!spkstr) { BIO_printf(bio_err, "Can't find SPKAC called \"%s\"\n", spkac); ERR_print_errors(bio_err); goto end; } spki = NETSCAPE_SPKI_b64_decode(spkstr, -1); if(!spki) { BIO_printf(bio_err, "Error loading SPKAC\n"); ERR_print_errors(bio_err); goto end; } if (outfile) 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\n"); ERR_print_errors(bio_err); goto end; } if(!noout) NETSCAPE_SPKI_print(out, spki); pkey = NETSCAPE_SPKI_get_pubkey(spki); if(verify) { i = NETSCAPE_SPKI_verify(spki, pkey); if(i) BIO_printf(bio_err, "Signature OK\n"); else { BIO_printf(bio_err, "Signature Failure\n"); ERR_print_errors(bio_err); goto end; } } if(pubkey) PEM_write_bio_PUBKEY(out, pkey); ret = 0; end: NCONF_free(conf); NETSCAPE_SPKI_free(spki); BIO_free(in); BIO_free_all(out); EVP_PKEY_free(pkey); if(passin) OPENSSL_free(passin); apps_shutdown(); OPENSSL_EXIT(ret); }
int nseq_main(int argc, char **argv) { char **args, *infile = NULL, *outfile = NULL; BIO *in = NULL, *out = NULL; int toseq = 0; X509 *x509 = NULL; NETSCAPE_CERT_SEQUENCE *seq = NULL; int i, ret = 1; int badarg = 0; ERR_load_crypto_strings(); args = argv + 1; while (!badarg && *args && *args[0] == '-') { if (!strcmp(*args, "-toseq")) toseq = 1; else if (!strcmp(*args, "-in")) { if (args[1]) { args++; infile = *args; } else badarg = 1; } else if (!strcmp(*args, "-out")) { if (args[1]) { args++; outfile = *args; } else badarg = 1; } else badarg = 1; args++; } if (badarg) { BIO_printf(bio_err, "Netscape certificate sequence utility\n"); BIO_printf(bio_err, "Usage nseq [options]\n"); BIO_printf(bio_err, "where options are\n"); BIO_printf(bio_err, "-in file input file\n"); BIO_printf(bio_err, "-out file output file\n"); BIO_printf(bio_err, "-toseq output NS Sequence file\n"); return (1); } if (infile) { if (!(in = BIO_new_file(infile, "r"))) { BIO_printf(bio_err, "Can't open input file %s\n", infile); goto end; } } else in = BIO_new_fp(stdin, BIO_NOCLOSE); if (outfile) { if (!(out = BIO_new_file(outfile, "w"))) { BIO_printf(bio_err, "Can't open output file %s\n", outfile); goto end; } } else { out = BIO_new_fp(stdout, BIO_NOCLOSE); } if (toseq) { seq = NETSCAPE_CERT_SEQUENCE_new(); seq->certs = sk_X509_new_null(); while ((x509 = PEM_read_bio_X509(in, NULL, NULL, NULL))) sk_X509_push(seq->certs, x509); if (!sk_X509_num(seq->certs)) { BIO_printf(bio_err, "Error reading certs file %s\n", infile); ERR_print_errors(bio_err); goto end; } PEM_write_bio_NETSCAPE_CERT_SEQUENCE(out, seq); ret = 0; goto end; } if (!(seq = PEM_read_bio_NETSCAPE_CERT_SEQUENCE(in, NULL, NULL, NULL))) { BIO_printf(bio_err, "Error reading sequence file %s\n", infile); ERR_print_errors(bio_err); goto end; } for (i = 0; i < sk_X509_num(seq->certs); i++) { x509 = sk_X509_value(seq->certs, i); dump_cert_text(out, x509); PEM_write_bio_X509(out, x509); } ret = 0; end: BIO_free(in); BIO_free_all(out); NETSCAPE_CERT_SEQUENCE_free(seq); return (ret); }
/* * open a connection to the HTTP server and send the client message to * the server, wait for the reply */ BIO *getrequest(scep_t *scep) { int s, bytes, used, rc, l; struct sockaddr_in sa; struct hostent *hep; char headers[20480]; char *buffer; char *p; BIO *bio; /* connect to the server */ if ((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) { BIO_printf(bio_err, "%s:%d: cannot allocate socket for HTTP\n", __FILE__, __LINE__); goto err; } if (NULL == (hep = gethostbyname(scep->h.httphost))) { BIO_printf(bio_err, "%s:%d: cannot resolve name '%s': " "%s (%d)\n", __FILE__, __LINE__, scep->h.httphost, strerror(errno), errno); goto err; } memcpy(&sa.sin_addr, hep->h_addr, hep->h_length); sa.sin_port = htons(scep->h.httpport); sa.sin_family = AF_INET; if (debug) BIO_printf(bio_err, "%s:%d: connecting to %s:%hd -> %s\n", __FILE__, __LINE__, scep->h.httphost, ntohs(sa.sin_port), inet_ntoa(sa.sin_addr)); if (connect(s, (struct sockaddr *)&sa, sizeof(sa)) < 0) { BIO_printf(bio_err, "%s:%d: cannot connect to remote host: " "%s (%d)\n", __FILE__, __LINE__, strerror(errno), errno); goto err; } /* correctly encode the base 64 representation of the request */ p = urlencode(scep->request.data); if (debug) BIO_printf(bio_err, "%s:%d: request data is '%24.24s...%24.24s'\n", __FILE__, __LINE__, p, p + strlen(p) - 24); if (debug > 1) { char filename[64]; FILE *scepfile; snprintf(filename, sizeof(filename), "%s/%d-scep.b64", tmppath, getpid()); if (NULL != (scepfile = fopen(filename, "w"))) { fputs(scep->request.data, scepfile); fclose(scepfile); } } /* formulate the HTTP request */ snprintf(headers, sizeof(headers), "GET %s/pkiclient.exe?operation=PKIOperation&message=%s " "HTTP/1.0\r\n\r\n", scep->h.httppath, p); if (debug) BIO_printf(bio_err, "%s:%d: request is '%68.68s...%21.21s'\n", __FILE__, __LINE__, headers, headers + strlen(headers) - 21); write(s, headers, strlen(headers)); /* read reply from the server until it closes the connection */ buffer = (char *)malloc(1024); used = 0; while ((bytes = read(s, &buffer[used], 1024)) > 0) { used += bytes; buffer = (char *)realloc(buffer, used + 1024); } buffer[used] = '\0'; /* get the first line from the reply */ sscanf(buffer, "%s %d ", headers, &rc); if (debug) BIO_printf(bio_err, "%s:%d: HTTP return code: %d\n", __FILE__, __LINE__, rc); if (rc >= 300) { BIO_printf(bio_err, "%s:%d: HTTP return code %d >= 300\n", __FILE__, __LINE__, rc); goto err; } /* check the MIME type of the reply */ if (strstr(buffer, "application/x-pki-message") == NULL) { BIO_printf(bio_err, "%s:%d: reply seems to have wrong content " "type\n", __FILE__, __LINE__); goto err; } if (debug) BIO_printf(bio_err, "%s:%d: reply type correct\n", __FILE__, __LINE__); /* extract the data portion of the reply */ if ((p = strstr(buffer, "\n\n"))) p += 2; if (p == NULL) if ((p = strstr(buffer, "\n\r\n\r"))) p += 4; if (p == NULL) if ((p = strstr(buffer, "\r\n\r\n"))) p += 4; if (p == NULL) { BIO_printf(bio_err, "%s:%d: reply content marker (two " "consecutive newlines) not found\n", __FILE__, __LINE__); goto err; } if (debug) BIO_printf(bio_err, "%s:%d: reply from server: %*.*s\n", __FILE__, __LINE__, p - buffer, p - buffer, buffer); if (debug) BIO_printf(bio_err, "%s:%d: header length: %d\n", __FILE__, __LINE__, p - buffer); l = used - (p - buffer); if (debug) BIO_printf(bio_err, "%s:%d: reply content has length %d\n", __FILE__, __LINE__, l); /* pack this data into a bio */ bio = BIO_new_mem_buf(p, l); return bio; /* error reply */ err: ERR_print_errors(bio_err); return NULL; }
int s_time_main(int argc, char **argv) { char buf[1024 * 8]; SSL *scon = NULL; SSL_CTX *ctx = NULL; const SSL_METHOD *meth = NULL; char *CApath = NULL, *CAfile = NULL, *cipher = NULL, *www_path = NULL; char *host = SSL_CONNECT_NAME, *certfile = NULL, *keyfile = NULL, *prog; double totalTime = 0.0; int noCApath = 0, noCAfile = 0; int maxtime = SECONDS, nConn = 0, perform = 3, ret = 1, i, st_bugs = 0, ver; long bytes_read = 0, finishtime = 0; OPTION_CHOICE o; int max_version = 0; meth = TLS_client_method(); verify_depth = 0; verify_error = X509_V_OK; prog = opt_init(argc, argv, s_time_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(s_time_options); ret = 0; goto end; case OPT_CONNECT: host = opt_arg(); break; case OPT_REUSE: perform = 2; break; case OPT_NEW: perform = 1; break; case OPT_VERIFY: if (!opt_int(opt_arg(), &verify_depth)) goto opthelp; BIO_printf(bio_err, "%s: verify depth is %d\n", prog, verify_depth); break; case OPT_CERT: certfile = opt_arg(); break; case OPT_KEY: keyfile = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_CIPHER: cipher = opt_arg(); break; case OPT_BUGS: st_bugs = 1; break; case OPT_TIME: if (!opt_int(opt_arg(), &maxtime)) goto opthelp; break; case OPT_WWW: www_path = opt_arg(); if (strlen(www_path) > MYBUFSIZ - 100) { BIO_printf(bio_err, "%s: -www option too long\n", prog); goto end; } break; case OPT_SSL3: max_version = SSL3_VERSION; break; } } argc = opt_num_rest(); if (argc != 0) goto opthelp; if (cipher == NULL) cipher = getenv("SSL_CIPHER"); if (cipher == NULL) { BIO_printf(bio_err, "No CIPHER specified\n"); goto end; } if ((ctx = SSL_CTX_new(meth)) == NULL) goto end; SSL_CTX_set_quiet_shutdown(ctx, 1); if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0) goto end; if (st_bugs) SSL_CTX_set_options(ctx, SSL_OP_ALL); if (!SSL_CTX_set_cipher_list(ctx, cipher)) goto end; if (!set_cert_stuff(ctx, certfile, keyfile)) goto end; if (!ctx_set_verify_locations(ctx, CAfile, CApath, noCAfile, noCApath)) { ERR_print_errors(bio_err); goto end; } if (!(perform & 1)) goto next; printf("Collecting connection statistics for %d seconds\n", maxtime); /* Loop and time how long it takes to make connections */ bytes_read = 0; finishtime = (long)time(NULL) + maxtime; tm_Time_F(START); for (;;) { if (finishtime < (long)time(NULL)) break; if ((scon = doConnection(NULL, host, ctx)) == NULL) goto end; if (www_path != NULL) { BIO_snprintf(buf, sizeof buf, "GET %s HTTP/1.0\r\n\r\n", www_path); if (SSL_write(scon, buf, strlen(buf)) <= 0) goto end; while ((i = SSL_read(scon, buf, sizeof(buf))) > 0) bytes_read += i; } #ifdef NO_SHUTDOWN SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); #else SSL_shutdown(scon); #endif BIO_closesocket(SSL_get_fd(scon)); nConn += 1; if (SSL_session_reused(scon)) ver = 'r'; else { ver = SSL_version(scon); if (ver == TLS1_VERSION) ver = 't'; else if (ver == SSL3_VERSION) ver = '3'; else ver = '*'; } fputc(ver, stdout); fflush(stdout); SSL_free(scon); scon = NULL; } totalTime += tm_Time_F(STOP); /* Add the time for this iteration */ i = (int)((long)time(NULL) - finishtime + maxtime); printf ("\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n", nConn, totalTime, ((double)nConn / totalTime), bytes_read); printf ("%d connections in %ld real seconds, %ld bytes read per connection\n", nConn, (long)time(NULL) - finishtime + maxtime, bytes_read / nConn); /* * Now loop and time connections using the same session id over and over */ next: if (!(perform & 2)) goto end; printf("\n\nNow timing with session id reuse.\n"); /* Get an SSL object so we can reuse the session id */ if ((scon = doConnection(NULL, host, ctx)) == NULL) { BIO_printf(bio_err, "Unable to get connection\n"); goto end; } if (www_path != NULL) { BIO_snprintf(buf, sizeof buf, "GET %s HTTP/1.0\r\n\r\n", www_path); if (SSL_write(scon, buf, strlen(buf)) <= 0) goto end; while (SSL_read(scon, buf, sizeof(buf)) > 0) continue; } #ifdef NO_SHUTDOWN SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); #else SSL_shutdown(scon); #endif BIO_closesocket(SSL_get_fd(scon)); nConn = 0; totalTime = 0.0; finishtime = (long)time(NULL) + maxtime; printf("starting\n"); bytes_read = 0; tm_Time_F(START); for (;;) { if (finishtime < (long)time(NULL)) break; if ((doConnection(scon, host, ctx)) == NULL) goto end; if (www_path) { BIO_snprintf(buf, sizeof buf, "GET %s HTTP/1.0\r\n\r\n", www_path); if (SSL_write(scon, buf, strlen(buf)) <= 0) goto end; while ((i = SSL_read(scon, buf, sizeof(buf))) > 0) bytes_read += i; } #ifdef NO_SHUTDOWN SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); #else SSL_shutdown(scon); #endif BIO_closesocket(SSL_get_fd(scon)); nConn += 1; if (SSL_session_reused(scon)) ver = 'r'; else { ver = SSL_version(scon); if (ver == TLS1_VERSION) ver = 't'; else if (ver == SSL3_VERSION) ver = '3'; else ver = '*'; } fputc(ver, stdout); fflush(stdout); } totalTime += tm_Time_F(STOP); /* Add the time for this iteration */ printf ("\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n", nConn, totalTime, ((double)nConn / totalTime), bytes_read); printf ("%d connections in %ld real seconds, %ld bytes read per connection\n", nConn, (long)time(NULL) - finishtime + maxtime, bytes_read / nConn); ret = 0; end: SSL_free(scon); SSL_CTX_free(ctx); return (ret); }
int main(int argc, char **argv) { BN_GENCB *cb; DSA *dsa = NULL; int counter, ret = 0, i, j; unsigned char buf[256]; unsigned long h; unsigned char sig[256]; unsigned int siglen; if (bio_err == NULL) bio_err = BIO_new_fp(stderr, BIO_NOCLOSE | BIO_FP_TEXT); CRYPTO_set_mem_debug(1); CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON); ERR_load_crypto_strings(); RAND_seed(rnd_seed, sizeof rnd_seed); BIO_printf(bio_err, "test generation of DSA parameters\n"); cb = BN_GENCB_new(); if (!cb) goto end; BN_GENCB_set(cb, dsa_cb, bio_err); if (((dsa = DSA_new()) == NULL) || !DSA_generate_parameters_ex(dsa, 512, seed, 20, &counter, &h, cb)) goto end; BIO_printf(bio_err, "seed\n"); for (i = 0; i < 20; i += 4) { BIO_printf(bio_err, "%02X%02X%02X%02X ", seed[i], seed[i + 1], seed[i + 2], seed[i + 3]); } BIO_printf(bio_err, "\ncounter=%d h=%ld\n", counter, h); DSA_print(bio_err, dsa, 0); if (counter != 105) { BIO_printf(bio_err, "counter should be 105\n"); goto end; } if (h != 2) { BIO_printf(bio_err, "h should be 2\n"); goto end; } i = BN_bn2bin(dsa->q, buf); j = sizeof(out_q); if ((i != j) || (memcmp(buf, out_q, i) != 0)) { BIO_printf(bio_err, "q value is wrong\n"); goto end; } i = BN_bn2bin(dsa->p, buf); j = sizeof(out_p); if ((i != j) || (memcmp(buf, out_p, i) != 0)) { BIO_printf(bio_err, "p value is wrong\n"); goto end; } i = BN_bn2bin(dsa->g, buf); j = sizeof(out_g); if ((i != j) || (memcmp(buf, out_g, i) != 0)) { BIO_printf(bio_err, "g value is wrong\n"); goto end; } dsa->flags |= DSA_FLAG_NO_EXP_CONSTTIME; DSA_generate_key(dsa); DSA_sign(0, str1, 20, sig, &siglen, dsa); if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1) ret = 1; dsa->flags &= ~DSA_FLAG_NO_EXP_CONSTTIME; DSA_generate_key(dsa); DSA_sign(0, str1, 20, sig, &siglen, dsa); if (DSA_verify(0, str1, 20, sig, siglen, dsa) == 1) ret = 1; end: if (!ret) ERR_print_errors(bio_err); DSA_free(dsa); BN_GENCB_free(cb); CRYPTO_cleanup_all_ex_data(); ERR_remove_thread_state(NULL); ERR_free_strings(); #ifndef OPENSSL_NO_CRYPTO_MDEBUG CRYPTO_mem_leaks(bio_err); #endif BIO_free(bio_err); bio_err = NULL; # ifdef OPENSSL_SYS_NETWARE if (!ret) printf("ERROR\n"); # endif EXIT(!ret); }
int MAIN(int argc, char **argv) { ENGINE *e = NULL; int i, ret = 1, badarg = 0; char *CApath = NULL, *CAfile = NULL; char *untfile = NULL, *trustfile = NULL, *crlfile = NULL; STACK_OF(X509) *untrusted = NULL, *trusted = NULL; STACK_OF(X509_CRL) *crls = NULL; X509_STORE *cert_ctx = NULL; X509_LOOKUP *lookup = NULL; X509_VERIFY_PARAM *vpm = NULL; int crl_download = 0; char *engine = NULL; cert_ctx = X509_STORE_new(); if (cert_ctx == NULL) goto end; X509_STORE_set_verify_cb(cert_ctx, cb); ERR_load_crypto_strings(); 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; argc--; argv++; for (;;) { if (argc >= 1) { if (strcmp(*argv, "-CApath") == 0) { if (argc-- < 1) goto usage; CApath = *(++argv); } else if (strcmp(*argv, "-CAfile") == 0) { if (argc-- < 1) goto usage; CAfile = *(++argv); } else if (args_verify(&argv, &argc, &badarg, bio_err, &vpm)) { if (badarg) goto usage; continue; } else if (strcmp(*argv, "-untrusted") == 0) { if (argc-- < 1) goto usage; untfile = *(++argv); } else if (strcmp(*argv, "-trusted") == 0) { if (argc-- < 1) goto usage; trustfile = *(++argv); } else if (strcmp(*argv, "-CRLfile") == 0) { if (argc-- < 1) goto usage; crlfile = *(++argv); } else if (strcmp(*argv, "-crl_download") == 0) crl_download = 1; #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv, "-engine") == 0) { if (--argc < 1) goto usage; engine = *(++argv); } #endif else if (strcmp(*argv, "-help") == 0) goto usage; else if (strcmp(*argv, "-verbose") == 0) v_verbose = 1; else if (argv[0][0] == '-') goto usage; else break; argc--; argv++; } else break; } e = setup_engine(bio_err, engine, 0); if (vpm) X509_STORE_set1_param(cert_ctx, vpm); lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file()); if (lookup == NULL) abort(); if (CAfile) { i = X509_LOOKUP_load_file(lookup, CAfile, X509_FILETYPE_PEM); if (!i) { BIO_printf(bio_err, "Error loading file %s\n", CAfile); ERR_print_errors(bio_err); goto end; } } else X509_LOOKUP_load_file(lookup, NULL, X509_FILETYPE_DEFAULT); lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir()); if (lookup == NULL) abort(); if (CApath) { i = X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM); if (!i) { BIO_printf(bio_err, "Error loading directory %s\n", CApath); ERR_print_errors(bio_err); goto end; } } else X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT); ERR_clear_error(); if (untfile) { untrusted = load_certs(bio_err, untfile, FORMAT_PEM, NULL, e, "untrusted certificates"); if (!untrusted) goto end; } if (trustfile) { trusted = load_certs(bio_err, trustfile, FORMAT_PEM, NULL, e, "trusted certificates"); if (!trusted) goto end; } if (crlfile) { crls = load_crls(bio_err, crlfile, FORMAT_PEM, NULL, e, "other CRLs"); if (!crls) goto end; } ret = 0; if (crl_download) store_setup_crl_download(cert_ctx); if (argc < 1) { if (1 != check(cert_ctx, NULL, untrusted, trusted, crls, e)) ret = -1; } else { for (i = 0; i < argc; i++) if (1 != check(cert_ctx, argv[i], untrusted, trusted, crls, e)) ret = -1; } usage: if (ret == 1) { BIO_printf(bio_err, "usage: verify [-verbose] [-CApath path] [-CAfile file] [-purpose purpose] [-crl_check]"); BIO_printf(bio_err, " [-no_alt_chains] [-attime timestamp]"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err, " [-engine e]"); #endif BIO_printf(bio_err, " cert1 cert2 ...\n"); BIO_printf(bio_err, "recognized usages:\n"); for (i = 0; i < X509_PURPOSE_get_count(); i++) { X509_PURPOSE *ptmp; ptmp = X509_PURPOSE_get0(i); BIO_printf(bio_err, "\t%-10s\t%s\n", X509_PURPOSE_get0_sname(ptmp), X509_PURPOSE_get0_name(ptmp)); } } end: if (vpm) X509_VERIFY_PARAM_free(vpm); if (cert_ctx != NULL) X509_STORE_free(cert_ctx); sk_X509_pop_free(untrusted, X509_free); sk_X509_pop_free(trusted, X509_free); sk_X509_CRL_pop_free(crls, X509_CRL_free); release_engine(e); apps_shutdown(); OPENSSL_EXIT(ret < 0 ? 2 : ret); }
int MAIN(int argc, char **argv) { DH *dh=NULL; int i,badops=0,text=0; BIO *in=NULL,*out=NULL; int informat,outformat,check=0,noout=0,C=0,ret=1; char *infile,*outfile,*prog; #ifndef OPENSSL_NO_ENGINE char *engine; #endif apps_startup(); if (bio_err == NULL) if ((bio_err=BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err,OPENSSL_TYPE__FILE_STDERR,BIO_NOCLOSE|BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; #ifndef OPENSSL_NO_ENGINE engine=NULL; #endif infile=NULL; outfile=NULL; informat=FORMAT_PEM; outformat=FORMAT_PEM; prog=argv[0]; argc--; argv++; while (argc >= 1) { if (TINYCLR_SSL_STRCMP(*argv,"-inform") == 0) { if (--argc < 1) goto bad; informat=str2fmt(*(++argv)); } else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0) { if (--argc < 1) goto bad; outformat=str2fmt(*(++argv)); } else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0) { if (--argc < 1) goto bad; infile= *(++argv); } else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0) { if (--argc < 1) goto bad; outfile= *(++argv); } #ifndef OPENSSL_NO_ENGINE else if (TINYCLR_SSL_STRCMP(*argv,"-engine") == 0) { if (--argc < 1) goto bad; engine= *(++argv); } #endif else if (TINYCLR_SSL_STRCMP(*argv,"-check") == 0) check=1; else if (TINYCLR_SSL_STRCMP(*argv,"-text") == 0) text=1; else if (TINYCLR_SSL_STRCMP(*argv,"-C") == 0) C=1; else if (TINYCLR_SSL_STRCMP(*argv,"-noout") == 0) noout=1; 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 - one of DER PEM\n"); BIO_printf(bio_err," -outform arg output format - one of DER PEM\n"); BIO_printf(bio_err," -in arg input file\n"); BIO_printf(bio_err," -out arg output file\n"); BIO_printf(bio_err," -check check the DH parameters\n"); BIO_printf(bio_err," -text print a text form of the DH parameters\n"); BIO_printf(bio_err," -C Output C code\n"); BIO_printf(bio_err," -noout no output\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf(bio_err," -engine e use engine e, possibly a hardware device.\n"); #endif 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,OPENSSL_TYPE__FILE_STDIN,BIO_NOCLOSE); else { if (BIO_read_filename(in,infile) <= 0) { TINYCLR_SSL_PERROR(infile); goto end; } } if (outfile == NULL) { BIO_set_fp(out,OPENSSL_TYPE__FILE_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) { TINYCLR_SSL_PERROR(outfile); goto end; } } if (informat == FORMAT_ASN1) dh=d2i_DHparams_bio(in,NULL); else if (informat == FORMAT_PEM) dh=PEM_read_bio_DHparams(in,NULL,NULL,NULL); else { BIO_printf(bio_err,"bad input format specified\n"); goto end; } if (dh == NULL) { BIO_printf(bio_err,"unable to load DH parameters\n"); ERR_print_errors(bio_err); goto end; } if (text) { DHparams_print(out,dh); #ifdef undef TINYCLR_SSL_PRINTF("p="); BN_print(OPENSSL_TYPE__FILE_STDOUT,dh->p); TINYCLR_SSL_PRINTF("\ng="); BN_print(OPENSSL_TYPE__FILE_STDOUT,dh->g); TINYCLR_SSL_PRINTF("\n"); if (dh->length != 0) TINYCLR_SSL_PRINTF("recommended private length=%ld\n",dh->length); #endif } if (check) { if (!DH_check(dh,&i)) { ERR_print_errors(bio_err); goto end; } if (i & DH_CHECK_P_NOT_PRIME) TINYCLR_SSL_PRINTF("p value is not prime\n"); if (i & DH_CHECK_P_NOT_SAFE_PRIME) TINYCLR_SSL_PRINTF("p value is not a safe prime\n"); if (i & DH_UNABLE_TO_CHECK_GENERATOR) TINYCLR_SSL_PRINTF("unable to check the generator value\n"); if (i & DH_NOT_SUITABLE_GENERATOR) TINYCLR_SSL_PRINTF("the g value is not a generator\n"); if (i == 0) TINYCLR_SSL_PRINTF("DH parameters appear to be ok.\n"); } if (C) { unsigned char *data; int len,l,bits; len=BN_num_bytes(dh->p); bits=BN_num_bits(dh->p); data=(unsigned char *)OPENSSL_malloc(len); if (data == NULL) { TINYCLR_SSL_PERROR("OPENSSL_malloc"); goto end; } l=BN_bn2bin(dh->p,data); TINYCLR_SSL_PRINTF("static unsigned char dh%d_p[]={",bits); for (i=0; i<l; i++) { if ((i%12) == 0) TINYCLR_SSL_PRINTF("\n\t"); TINYCLR_SSL_PRINTF("0x%02X,",data[i]); } TINYCLR_SSL_PRINTF("\n\t};\n"); l=BN_bn2bin(dh->g,data); TINYCLR_SSL_PRINTF("static unsigned char dh%d_g[]={",bits); for (i=0; i<l; i++) { if ((i%12) == 0) TINYCLR_SSL_PRINTF("\n\t"); TINYCLR_SSL_PRINTF("0x%02X,",data[i]); } TINYCLR_SSL_PRINTF("\n\t};\n\n"); TINYCLR_SSL_PRINTF("DH *get_dh%d()\n\t{\n",bits); TINYCLR_SSL_PRINTF("\tDH *dh;\n\n"); TINYCLR_SSL_PRINTF("\tif ((dh=DH_new()) == NULL) return(NULL);\n"); TINYCLR_SSL_PRINTF("\tdh->p=BN_bin2bn(dh%d_p,sizeof(dh%d_p),NULL);\n", bits,bits); TINYCLR_SSL_PRINTF("\tdh->g=BN_bin2bn(dh%d_g,sizeof(dh%d_g),NULL);\n", bits,bits); TINYCLR_SSL_PRINTF("\tif ((dh->p == NULL) || (dh->g == NULL))\n"); TINYCLR_SSL_PRINTF("\t\treturn(NULL);\n"); TINYCLR_SSL_PRINTF("\treturn(dh);\n\t}\n"); OPENSSL_free(data); } if (!noout) { if (outformat == FORMAT_ASN1) i=i2d_DHparams_bio(out,dh); else if (outformat == FORMAT_PEM) i=PEM_write_bio_DHparams(out,dh); else { BIO_printf(bio_err,"bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err,"unable to write DH parameters\n"); ERR_print_errors(bio_err); goto end; } } ret=0; end: if (in != NULL) BIO_free(in); if (out != NULL) BIO_free_all(out); if (dh != NULL) DH_free(dh); apps_shutdown(); OPENSSL_EXIT(ret); }
int MAIN(int argc, char **argv) { DH *dh=NULL; int i,badops=0,text=0; #ifndef OPENSSL_NO_DSA int dsaparam=0; #endif BIO *in=NULL,*out=NULL; int informat,outformat,check=0,noout=0,C=0,ret=1; char *infile,*outfile,*prog; char *inrand=NULL; #ifndef OPENSSL_NO_ENGINE char *engine=NULL; #endif int num = 0, g = 0; 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); } #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv,"-engine") == 0) { if (--argc < 1) goto bad; engine= *(++argv); } #endif else if (strcmp(*argv,"-check") == 0) check=1; else if (strcmp(*argv,"-text") == 0) text=1; #ifndef OPENSSL_NO_DSA else if (strcmp(*argv,"-dsaparam") == 0) dsaparam=1; #endif else if (strcmp(*argv,"-C") == 0) C=1; else if (strcmp(*argv,"-noout") == 0) noout=1; else if (strcmp(*argv,"-2") == 0) g=2; else if (strcmp(*argv,"-5") == 0) g=5; else if (strcmp(*argv,"-rand") == 0) { if (--argc < 1) goto bad; inrand= *(++argv); } else if (((sscanf(*argv,"%d",&num) == 0) || (num <= 0))) goto bad; argv++; argc--; } if (badops) { bad: BIO_printf(bio_err,"%s [options] [numbits]\n",prog); BIO_printf(bio_err,"where options are\n"); BIO_printf(bio_err," -inform arg input format - one of DER PEM\n"); BIO_printf(bio_err," -outform arg output format - one of DER PEM\n"); BIO_printf(bio_err," -in arg input file\n"); BIO_printf(bio_err," -out arg output file\n"); #ifndef OPENSSL_NO_DSA BIO_printf(bio_err," -dsaparam read or generate DSA parameters, convert to DH\n"); #endif BIO_printf(bio_err," -check check the DH parameters\n"); BIO_printf(bio_err," -text print a text form of the DH parameters\n"); BIO_printf(bio_err," -C Output C code\n"); BIO_printf(bio_err," -2 generate parameters using 2 as the generator value\n"); BIO_printf(bio_err," -5 generate parameters using 5 as the generator value\n"); BIO_printf(bio_err," numbits number of bits in to generate (default 512)\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...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); BIO_printf(bio_err," - load the file (or the files in the directory) into\n"); BIO_printf(bio_err," the random number generator\n"); BIO_printf(bio_err," -noout no output\n"); goto end; } ERR_load_crypto_strings(); #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, engine, 0); #endif if (g && !num) num = DEFBITS; #ifndef OPENSSL_NO_DSA if (dsaparam) { if (g) { BIO_printf(bio_err, "generator may not be chosen for DSA parameters\n"); goto end; } } else #endif { /* DH parameters */ if (num && !g) g = 2; } if(num) { BN_GENCB cb; BN_GENCB_set(&cb, dh_cb, bio_err); if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL) { BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n"); } if (inrand != NULL) BIO_printf(bio_err,"%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); #ifndef OPENSSL_NO_DSA if (dsaparam) { DSA *dsa = DSA_new(); BIO_printf(bio_err,"Generating DSA parameters, %d bit long prime\n",num); if(!dsa || !DSA_generate_parameters_ex(dsa, num, NULL, 0, NULL, NULL, &cb)) { if(dsa) DSA_free(dsa); ERR_print_errors(bio_err); goto end; } dh = DSA_dup_DH(dsa); DSA_free(dsa); if (dh == NULL) { ERR_print_errors(bio_err); goto end; } } else #endif { dh = DH_new(); BIO_printf(bio_err,"Generating DH parameters, %d bit long safe prime, generator %d\n",num,g); BIO_printf(bio_err,"This is going to take a long time\n"); if(!dh || !DH_generate_parameters_ex(dh, num, g, &cb)) { if(dh) DH_free(dh); ERR_print_errors(bio_err); goto end; } } app_RAND_write_file(NULL, bio_err); } else { 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); else { if (BIO_read_filename(in,infile) <= 0) { perror(infile); goto end; } } if (informat != FORMAT_ASN1 && informat != FORMAT_PEM) { BIO_printf(bio_err,"bad input format specified\n"); goto end; } #ifndef OPENSSL_NO_DSA if (dsaparam) { DSA *dsa; if (informat == FORMAT_ASN1) dsa=d2i_DSAparams_bio(in,NULL); else /* informat == FORMAT_PEM */ dsa=PEM_read_bio_DSAparams(in,NULL,NULL,NULL); if (dsa == NULL) { BIO_printf(bio_err,"unable to load DSA parameters\n"); ERR_print_errors(bio_err); goto end; } dh = DSA_dup_DH(dsa); DSA_free(dsa); if (dh == NULL) { ERR_print_errors(bio_err); goto end; } } else #endif { if (informat == FORMAT_ASN1) dh=d2i_DHparams_bio(in,NULL); else /* informat == FORMAT_PEM */ dh=PEM_read_bio_DHparams(in,NULL,NULL,NULL); if (dh == NULL) { BIO_printf(bio_err,"unable to load DH parameters\n"); ERR_print_errors(bio_err); goto end; } } /* dh != NULL */ } 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) { DHparams_print(out,dh); } if (check) { if (!DH_check(dh,&i)) { ERR_print_errors(bio_err); goto end; } if (i & DH_CHECK_P_NOT_PRIME) printf("p value is not prime\n"); if (i & DH_CHECK_P_NOT_SAFE_PRIME) printf("p value is not a safe prime\n"); if (i & DH_UNABLE_TO_CHECK_GENERATOR) printf("unable to check the generator value\n"); if (i & DH_NOT_SUITABLE_GENERATOR) printf("the g value is not a generator\n"); if (i == 0) printf("DH parameters appear to be ok.\n"); } if (C) { unsigned char *data; int len,l,bits; len=BN_num_bytes(dh->p); bits=BN_num_bits(dh->p); data=(unsigned char *)OPENSSL_malloc(len); if (data == NULL) { perror("OPENSSL_malloc"); goto end; } printf("#ifndef HEADER_DH_H\n" "#include <openssl/dh.h>\n" "#endif\n"); printf("DH *get_dh%d()\n\t{\n",bits); l=BN_bn2bin(dh->p,data); printf("\tstatic unsigned char dh%d_p[]={",bits); for (i=0; i<l; i++) { if ((i%12) == 0) printf("\n\t\t"); printf("0x%02X,",data[i]); } printf("\n\t\t};\n"); l=BN_bn2bin(dh->g,data); printf("\tstatic unsigned char dh%d_g[]={",bits); for (i=0; i<l; i++) { if ((i%12) == 0) printf("\n\t\t"); printf("0x%02X,",data[i]); } printf("\n\t\t};\n"); printf("\tDH *dh;\n\n"); printf("\tif ((dh=DH_new()) == NULL) return(NULL);\n"); printf("\tdh->p=BN_bin2bn(dh%d_p,sizeof(dh%d_p),NULL);\n", bits,bits); printf("\tdh->g=BN_bin2bn(dh%d_g,sizeof(dh%d_g),NULL);\n", bits,bits); printf("\tif ((dh->p == NULL) || (dh->g == NULL))\n"); printf("\t\t{ DH_free(dh); return(NULL); }\n"); if (dh->length) printf("\tdh->length = %ld;\n", dh->length); printf("\treturn(dh);\n\t}\n"); OPENSSL_free(data); } if (!noout) { if (outformat == FORMAT_ASN1) i=i2d_DHparams_bio(out,dh); else if (outformat == FORMAT_PEM) i=PEM_write_bio_DHparams(out,dh); else { BIO_printf(bio_err,"bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err,"unable to write DH parameters\n"); ERR_print_errors(bio_err); goto end; } } ret=0; end: if (in != NULL) BIO_free(in); if (out != NULL) BIO_free_all(out); if (dh != NULL) DH_free(dh); apps_shutdown(); OPENSSL_EXIT(ret); }
int pkeyutl_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; char *infile = NULL, *outfile = NULL, *sigfile = NULL; int pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY; int keyform = FORMAT_PEM, peerform = FORMAT_PEM; char badarg = 0, rev = 0; char hexdump = 0, asn1parse = 0; EVP_PKEY_CTX *ctx = NULL; char *passargin = NULL; int keysize = -1; unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL; size_t buf_outlen; int buf_inlen = 0, siglen = -1; int ret = 1, rv = -1; if (single_execution) { if (pledge("stdio cpath wpath rpath tty", NULL) == -1) { perror("pledge"); exit(1); } } argc--; argv++; while (argc >= 1) { if (!strcmp(*argv, "-in")) { if (--argc < 1) badarg = 1; else infile = *(++argv); } else if (!strcmp(*argv, "-out")) { if (--argc < 1) badarg = 1; else outfile = *(++argv); } else if (!strcmp(*argv, "-sigfile")) { if (--argc < 1) badarg = 1; else sigfile = *(++argv); } else if (!strcmp(*argv, "-inkey")) { if (--argc < 1) badarg = 1; else { ctx = init_ctx(&keysize, *(++argv), keyform, key_type, passargin, pkey_op); if (!ctx) { BIO_puts(bio_err, "Error initializing context\n"); ERR_print_errors(bio_err); badarg = 1; } } } else if (!strcmp(*argv, "-peerkey")) { if (--argc < 1) badarg = 1; else if (!setup_peer(bio_err, ctx, peerform, *(++argv))) badarg = 1; } else if (!strcmp(*argv, "-passin")) { if (--argc < 1) badarg = 1; else passargin = *(++argv); } else if (strcmp(*argv, "-peerform") == 0) { if (--argc < 1) badarg = 1; else peerform = str2fmt(*(++argv)); } else if (strcmp(*argv, "-keyform") == 0) { if (--argc < 1) badarg = 1; else keyform = str2fmt(*(++argv)); } else if (!strcmp(*argv, "-pubin")) key_type = KEY_PUBKEY; else if (!strcmp(*argv, "-certin")) key_type = KEY_CERT; else if (!strcmp(*argv, "-asn1parse")) asn1parse = 1; else if (!strcmp(*argv, "-hexdump")) hexdump = 1; else if (!strcmp(*argv, "-sign")) pkey_op = EVP_PKEY_OP_SIGN; else if (!strcmp(*argv, "-verify")) pkey_op = EVP_PKEY_OP_VERIFY; else if (!strcmp(*argv, "-verifyrecover")) pkey_op = EVP_PKEY_OP_VERIFYRECOVER; else if (!strcmp(*argv, "-rev")) rev = 1; else if (!strcmp(*argv, "-encrypt")) pkey_op = EVP_PKEY_OP_ENCRYPT; else if (!strcmp(*argv, "-decrypt")) pkey_op = EVP_PKEY_OP_DECRYPT; else if (!strcmp(*argv, "-derive")) pkey_op = EVP_PKEY_OP_DERIVE; else if (strcmp(*argv, "-pkeyopt") == 0) { if (--argc < 1) badarg = 1; else if (!ctx) { BIO_puts(bio_err, "-pkeyopt command before -inkey\n"); badarg = 1; } else if (pkey_ctrl_string(ctx, *(++argv)) <= 0) { BIO_puts(bio_err, "parameter setting error\n"); ERR_print_errors(bio_err); goto end; } } else badarg = 1; if (badarg) { usage(); goto end; } argc--; argv++; } if (!ctx) { usage(); goto end; } if (sigfile && (pkey_op != EVP_PKEY_OP_VERIFY)) { BIO_puts(bio_err, "Signature file specified for non verify\n"); goto end; } if (!sigfile && (pkey_op == EVP_PKEY_OP_VERIFY)) { BIO_puts(bio_err, "No signature file specified for verify\n"); goto end; } if (pkey_op != EVP_PKEY_OP_DERIVE) { if (infile) { if (!(in = BIO_new_file(infile, "rb"))) { BIO_puts(bio_err, "Error Opening Input File\n"); ERR_print_errors(bio_err); goto end; } } else in = BIO_new_fp(stdin, BIO_NOCLOSE); } if (outfile) { if (!(out = BIO_new_file(outfile, "wb"))) { BIO_printf(bio_err, "Error Creating Output File\n"); ERR_print_errors(bio_err); goto end; } } else { out = BIO_new_fp(stdout, BIO_NOCLOSE); } if (sigfile) { BIO *sigbio = BIO_new_file(sigfile, "rb"); if (!sigbio) { BIO_printf(bio_err, "Can't open signature file %s\n", sigfile); goto end; } siglen = bio_to_mem(&sig, keysize * 10, sigbio); BIO_free(sigbio); if (siglen <= 0) { BIO_printf(bio_err, "Error reading signature data\n"); goto end; } } if (in) { /* Read the input data */ buf_inlen = bio_to_mem(&buf_in, keysize * 10, in); if (buf_inlen <= 0) { BIO_printf(bio_err, "Error reading input Data\n"); exit(1); } if (rev) { size_t i; unsigned char ctmp; size_t l = (size_t) buf_inlen; for (i = 0; i < l / 2; i++) { ctmp = buf_in[i]; buf_in[i] = buf_in[l - 1 - i]; buf_in[l - 1 - i] = ctmp; } } } if (pkey_op == EVP_PKEY_OP_VERIFY) { rv = EVP_PKEY_verify(ctx, sig, (size_t) siglen, buf_in, (size_t) buf_inlen); if (rv == 1) { BIO_puts(out, "Signature Verified Successfully\n"); ret = 0; } else BIO_puts(out, "Signature Verification Failure\n"); if (rv >= 0) goto end; } else { rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen, buf_in, (size_t) buf_inlen); if (rv > 0) { buf_out = malloc(buf_outlen); if (!buf_out) rv = -1; else rv = do_keyop(ctx, pkey_op, buf_out, (size_t *) & buf_outlen, buf_in, (size_t) buf_inlen); } } if (rv <= 0) { BIO_printf(bio_err, "Public Key operation error\n"); ERR_print_errors(bio_err); goto end; } ret = 0; if (asn1parse) { if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1)) ERR_print_errors(bio_err); } else if (hexdump) BIO_dump(out, (char *) buf_out, buf_outlen); else BIO_write(out, buf_out, buf_outlen); end: if (ctx) EVP_PKEY_CTX_free(ctx); BIO_free(in); BIO_free_all(out); free(buf_in); free(buf_out); free(sig); return ret; }
int MAIN(int argc, char **argv) { ENGINE *e = NULL; int operation = 0; int ret = 0; char **args; const char *inmode = "r", *outmode = "w"; char *infile = NULL, *outfile = NULL; char *signerfile = NULL, *recipfile = NULL; STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL; char *certfile = NULL, *keyfile = NULL, *contfile=NULL; const EVP_CIPHER *cipher = NULL; PKCS7 *p7 = NULL; X509_STORE *store = NULL; X509 *cert = NULL, *recip = NULL, *signer = NULL; EVP_PKEY *key = NULL; STACK_OF(X509) *encerts = NULL, *other = NULL; BIO *in = NULL, *out = NULL, *indata = NULL; int badarg = 0; int flags = PKCS7_DETACHED; char *to = NULL, *from = NULL, *subject = NULL; char *CAfile = NULL, *CApath = NULL; char *passargin = NULL, *passin = NULL; char *inrand = NULL; int need_rand = 0; int indef = 0; const EVP_MD *sign_md = NULL; int informat = FORMAT_SMIME, outformat = FORMAT_SMIME; int keyform = FORMAT_PEM; #ifndef OPENSSL_NO_ENGINE char *engine=NULL; #endif X509_VERIFY_PARAM *vpm = NULL; args = argv + 1; ret = 1; 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; while (!badarg && *args && *args[0] == '-') { if (!strcmp (*args, "-encrypt")) operation = SMIME_ENCRYPT; else if (!strcmp (*args, "-decrypt")) operation = SMIME_DECRYPT; else if (!strcmp (*args, "-sign")) operation = SMIME_SIGN; else if (!strcmp (*args, "-resign")) operation = SMIME_RESIGN; else if (!strcmp (*args, "-verify")) operation = SMIME_VERIFY; else if (!strcmp (*args, "-pk7out")) operation = SMIME_PK7OUT; #ifndef OPENSSL_NO_DES else if (!strcmp (*args, "-des3")) cipher = EVP_des_ede3_cbc(); else if (!strcmp (*args, "-des")) cipher = EVP_des_cbc(); #endif #ifndef OPENSSL_NO_SEED else if (!strcmp (*args, "-seed")) cipher = EVP_seed_cbc(); #endif #ifndef OPENSSL_NO_RC2 else if (!strcmp (*args, "-rc2-40")) cipher = EVP_rc2_40_cbc(); else if (!strcmp (*args, "-rc2-128")) cipher = EVP_rc2_cbc(); else if (!strcmp (*args, "-rc2-64")) cipher = EVP_rc2_64_cbc(); #endif #ifndef OPENSSL_NO_AES else if (!strcmp(*args,"-aes128")) cipher = EVP_aes_128_cbc(); else if (!strcmp(*args,"-aes192")) cipher = EVP_aes_192_cbc(); else if (!strcmp(*args,"-aes256")) cipher = EVP_aes_256_cbc(); #endif #ifndef OPENSSL_NO_CAMELLIA else if (!strcmp(*args,"-camellia128")) cipher = EVP_camellia_128_cbc(); else if (!strcmp(*args,"-camellia192")) cipher = EVP_camellia_192_cbc(); else if (!strcmp(*args,"-camellia256")) cipher = EVP_camellia_256_cbc(); #endif else if (!strcmp (*args, "-text")) flags |= PKCS7_TEXT; else if (!strcmp (*args, "-nointern")) flags |= PKCS7_NOINTERN; else if (!strcmp (*args, "-noverify")) flags |= PKCS7_NOVERIFY; else if (!strcmp (*args, "-nochain")) flags |= PKCS7_NOCHAIN; else if (!strcmp (*args, "-nocerts")) flags |= PKCS7_NOCERTS; else if (!strcmp (*args, "-noattr")) flags |= PKCS7_NOATTR; else if (!strcmp (*args, "-nodetach")) flags &= ~PKCS7_DETACHED; else if (!strcmp (*args, "-nosmimecap")) flags |= PKCS7_NOSMIMECAP; else if (!strcmp (*args, "-binary")) flags |= PKCS7_BINARY; else if (!strcmp (*args, "-nosigs")) flags |= PKCS7_NOSIGS; else if (!strcmp (*args, "-stream")) indef = 1; else if (!strcmp (*args, "-indef")) indef = 1; else if (!strcmp (*args, "-noindef")) indef = 0; else if (!strcmp (*args, "-nooldmime")) flags |= PKCS7_NOOLDMIMETYPE; else if (!strcmp (*args, "-crlfeol")) flags |= PKCS7_CRLFEOL; else if (!strcmp(*args,"-rand")) { if (!args[1]) goto argerr; args++; inrand = *args; need_rand = 1; } #ifndef OPENSSL_NO_ENGINE else if (!strcmp(*args,"-engine")) { if (!args[1]) goto argerr; engine = *++args; } #endif else if (!strcmp(*args,"-passin")) { if (!args[1]) goto argerr; passargin = *++args; } else if (!strcmp (*args, "-to")) { if (!args[1]) goto argerr; to = *++args; } else if (!strcmp (*args, "-from")) { if (!args[1]) goto argerr; from = *++args; } else if (!strcmp (*args, "-subject")) { if (!args[1]) goto argerr; subject = *++args; } else if (!strcmp (*args, "-signer")) { if (!args[1]) goto argerr; /* If previous -signer argument add signer to list */ if (signerfile) { if (!sksigners) sksigners = sk_OPENSSL_STRING_new_null(); sk_OPENSSL_STRING_push(sksigners, signerfile); if (!keyfile) keyfile = signerfile; if (!skkeys) skkeys = sk_OPENSSL_STRING_new_null(); sk_OPENSSL_STRING_push(skkeys, keyfile); keyfile = NULL; } signerfile = *++args; } else if (!strcmp (*args, "-recip")) { if (!args[1]) goto argerr; recipfile = *++args; } else if (!strcmp (*args, "-md")) { if (!args[1]) goto argerr; sign_md = EVP_get_digestbyname(*++args); if (sign_md == NULL) { BIO_printf(bio_err, "Unknown digest %s\n", *args); goto argerr; } } else if (!strcmp (*args, "-inkey")) { if (!args[1]) goto argerr; /* If previous -inkey arument add signer to list */ if (keyfile) { if (!signerfile) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto argerr; } if (!sksigners) sksigners = sk_OPENSSL_STRING_new_null(); sk_OPENSSL_STRING_push(sksigners, signerfile); signerfile = NULL; if (!skkeys) skkeys = sk_OPENSSL_STRING_new_null(); sk_OPENSSL_STRING_push(skkeys, keyfile); } keyfile = *++args; } else if (!strcmp (*args, "-keyform")) { if (!args[1]) goto argerr; keyform = str2fmt(*++args); } else if (!strcmp (*args, "-certfile")) { if (!args[1]) goto argerr; certfile = *++args; } else if (!strcmp (*args, "-CAfile")) { if (!args[1]) goto argerr; CAfile = *++args; } else if (!strcmp (*args, "-CApath")) { if (!args[1]) goto argerr; CApath = *++args; } else if (!strcmp (*args, "-in")) { if (!args[1]) goto argerr; infile = *++args; } else if (!strcmp (*args, "-inform")) { if (!args[1]) goto argerr; informat = str2fmt(*++args); } else if (!strcmp (*args, "-outform")) { if (!args[1]) goto argerr; outformat = str2fmt(*++args); } else if (!strcmp (*args, "-out")) { if (!args[1]) goto argerr; outfile = *++args; } else if (!strcmp (*args, "-content")) { if (!args[1]) goto argerr; contfile = *++args; } else if (args_verify(&args, NULL, &badarg, bio_err, &vpm)) continue; else if ((cipher = EVP_get_cipherbyname(*args + 1)) == NULL) badarg = 1; args++; } if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) { BIO_puts(bio_err, "Multiple signers or keys not allowed\n"); goto argerr; } if (operation & SMIME_SIGNERS) { /* Check to see if any final signer needs to be appended */ if (keyfile && !signerfile) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto argerr; } if (signerfile) { if (!sksigners) sksigners = sk_OPENSSL_STRING_new_null(); sk_OPENSSL_STRING_push(sksigners, signerfile); if (!skkeys) skkeys = sk_OPENSSL_STRING_new_null(); if (!keyfile) keyfile = signerfile; sk_OPENSSL_STRING_push(skkeys, keyfile); } if (!sksigners) { BIO_printf(bio_err, "No signer certificate specified\n"); badarg = 1; } signerfile = NULL; keyfile = NULL; need_rand = 1; } else if (operation == SMIME_DECRYPT) { if (!recipfile && !keyfile) { BIO_printf(bio_err, "No recipient certificate or key specified\n"); badarg = 1; } } else if (operation == SMIME_ENCRYPT) { if (!*args) { BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n"); badarg = 1; } need_rand = 1; } else if (!operation) badarg = 1; if (badarg) { argerr: BIO_printf (bio_err, "Usage smime [options] cert.pem ...\n"); BIO_printf (bio_err, "where options are\n"); BIO_printf (bio_err, "-encrypt encrypt message\n"); BIO_printf (bio_err, "-decrypt decrypt encrypted message\n"); BIO_printf (bio_err, "-sign sign message\n"); BIO_printf (bio_err, "-verify verify signed message\n"); BIO_printf (bio_err, "-pk7out output PKCS#7 structure\n"); #ifndef OPENSSL_NO_DES BIO_printf (bio_err, "-des3 encrypt with triple DES\n"); BIO_printf (bio_err, "-des encrypt with DES\n"); #endif #ifndef OPENSSL_NO_SEED BIO_printf (bio_err, "-seed encrypt with SEED\n"); #endif #ifndef OPENSSL_NO_RC2 BIO_printf (bio_err, "-rc2-40 encrypt with RC2-40 (default)\n"); BIO_printf (bio_err, "-rc2-64 encrypt with RC2-64\n"); BIO_printf (bio_err, "-rc2-128 encrypt with RC2-128\n"); #endif #ifndef OPENSSL_NO_AES BIO_printf (bio_err, "-aes128, -aes192, -aes256\n"); BIO_printf (bio_err, " encrypt PEM output with cbc aes\n"); #endif #ifndef OPENSSL_NO_CAMELLIA BIO_printf (bio_err, "-camellia128, -camellia192, -camellia256\n"); BIO_printf (bio_err, " encrypt PEM output with cbc camellia\n"); #endif BIO_printf (bio_err, "-nointern don't search certificates in message for signer\n"); BIO_printf (bio_err, "-nosigs don't verify message signature\n"); BIO_printf (bio_err, "-noverify don't verify signers certificate\n"); BIO_printf (bio_err, "-nocerts don't include signers certificate when signing\n"); BIO_printf (bio_err, "-nodetach use opaque signing\n"); BIO_printf (bio_err, "-noattr don't include any signed attributes\n"); BIO_printf (bio_err, "-binary don't translate message to text\n"); BIO_printf (bio_err, "-certfile file other certificates file\n"); BIO_printf (bio_err, "-signer file signer certificate file\n"); BIO_printf (bio_err, "-recip file recipient certificate file for decryption\n"); BIO_printf (bio_err, "-in file input file\n"); BIO_printf (bio_err, "-inform arg input format SMIME (default), PEM or DER\n"); BIO_printf (bio_err, "-inkey file input private key (if not signer or recipient)\n"); BIO_printf (bio_err, "-keyform arg input private key format (PEM or ENGINE)\n"); BIO_printf (bio_err, "-out file output file\n"); BIO_printf (bio_err, "-outform arg output format SMIME (default), PEM or DER\n"); BIO_printf (bio_err, "-content file supply or override content for detached signature\n"); BIO_printf (bio_err, "-to addr to address\n"); BIO_printf (bio_err, "-from ad from address\n"); BIO_printf (bio_err, "-subject s subject\n"); BIO_printf (bio_err, "-text include or delete text MIME headers\n"); BIO_printf (bio_err, "-CApath dir trusted certificates directory\n"); BIO_printf (bio_err, "-CAfile file trusted certificates file\n"); BIO_printf (bio_err, "-crl_check check revocation status of signer's certificate using CRLs\n"); BIO_printf (bio_err, "-crl_check_all check revocation status of signer's certificate chain using CRLs\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf (bio_err, "-engine e use engine e, possibly a hardware device.\n"); #endif BIO_printf (bio_err, "-passin arg input file pass phrase source\n"); BIO_printf(bio_err, "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); BIO_printf(bio_err, " load the file (or the files in the directory) into\n"); BIO_printf(bio_err, " the random number generator\n"); BIO_printf (bio_err, "cert.pem recipient certificate(s) for encryption\n"); goto end; } #ifndef OPENSSL_NO_ENGINE e = setup_engine(bio_err, engine, 0); #endif if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (need_rand) { 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)); } ret = 2; if (!(operation & SMIME_SIGNERS)) flags &= ~PKCS7_DETACHED; if (operation & SMIME_OP) { if (outformat == FORMAT_ASN1) outmode = "wb"; } else { if (flags & PKCS7_BINARY) outmode = "wb"; } if (operation & SMIME_IP) { if (informat == FORMAT_ASN1) inmode = "rb"; } else { if (flags & PKCS7_BINARY) inmode = "rb"; } if (operation == SMIME_ENCRYPT) { if (!cipher) { #ifndef OPENSSL_NO_RC2 cipher = EVP_rc2_40_cbc(); #else BIO_printf(bio_err, "No cipher selected\n"); goto end; #endif } encerts = sk_X509_new_null(); while (*args) { if (!(cert = load_cert(bio_err,*args,FORMAT_PEM, NULL, e, "recipient certificate file"))) { #if 0 /* An appropriate message is already printed */ BIO_printf(bio_err, "Can't read recipient certificate file %s\n", *args); #endif goto end; } sk_X509_push(encerts, cert); cert = NULL; args++; } } if (certfile) { if (!(other = load_certs(bio_err,certfile,FORMAT_PEM, NULL, e, "certificate file"))) { ERR_print_errors(bio_err); goto end; } } if (recipfile && (operation == SMIME_DECRYPT)) { if (!(recip = load_cert(bio_err,recipfile,FORMAT_PEM,NULL, e, "recipient certificate file"))) { ERR_print_errors(bio_err); goto end; } } if (operation == SMIME_DECRYPT) { if (!keyfile) keyfile = recipfile; } else if (operation == SMIME_SIGN) { if (!keyfile) keyfile = signerfile; } else keyfile = NULL; if (keyfile) { key = load_key(bio_err, keyfile, keyform, 0, passin, e, "signing key file"); if (!key) goto end; } if (infile) { if (!(in = BIO_new_file(infile, inmode))) { BIO_printf (bio_err, "Can't open input file %s\n", infile); goto end; } } else in = BIO_new_fp(stdin, BIO_NOCLOSE); if (operation & SMIME_IP) { if (informat == FORMAT_SMIME) p7 = SMIME_read_PKCS7(in, &indata); else if (informat == FORMAT_PEM) p7 = PEM_read_bio_PKCS7(in, NULL, NULL, NULL); else if (informat == FORMAT_ASN1) p7 = d2i_PKCS7_bio(in, NULL); else { BIO_printf(bio_err, "Bad input format for PKCS#7 file\n"); goto end; } if (!p7) { BIO_printf(bio_err, "Error reading S/MIME message\n"); goto end; } if (contfile) { BIO_free(indata); if (!(indata = BIO_new_file(contfile, "rb"))) { BIO_printf(bio_err, "Can't read content file %s\n", contfile); goto end; } } } if (outfile) { if (!(out = BIO_new_file(outfile, outmode))) { BIO_printf (bio_err, "Can't open output file %s\n", outfile); goto end; } } 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 (operation == SMIME_VERIFY) { if (!(store = setup_verify(bio_err, CAfile, CApath))) goto end; X509_STORE_set_verify_cb(store, smime_cb); if (vpm) X509_STORE_set1_param(store, vpm); } ret = 3; if (operation == SMIME_ENCRYPT) { if (indef) flags |= PKCS7_STREAM; p7 = PKCS7_encrypt(encerts, in, cipher, flags); } else if (operation & SMIME_SIGNERS) { int i; /* If detached data content we only enable streaming if * S/MIME output format. */ if (operation == SMIME_SIGN) { if (flags & PKCS7_DETACHED) { if (outformat == FORMAT_SMIME) flags |= PKCS7_STREAM; } else if (indef) flags |= PKCS7_STREAM; flags |= PKCS7_PARTIAL; p7 = PKCS7_sign(NULL, NULL, other, in, flags); if (!p7) goto end; } else flags |= PKCS7_REUSE_DIGEST; for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) { signerfile = sk_OPENSSL_STRING_value(sksigners, i); keyfile = sk_OPENSSL_STRING_value(skkeys, i); signer = load_cert(bio_err, signerfile,FORMAT_PEM, NULL, e, "signer certificate"); if (!signer) goto end; key = load_key(bio_err, keyfile, keyform, 0, passin, e, "signing key file"); if (!key) goto end; if (!PKCS7_sign_add_signer(p7, signer, key, sign_md, flags)) 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 & PKCS7_STREAM)) { if (!PKCS7_final(p7, in, flags)) goto end; } } if (!p7) { BIO_printf(bio_err, "Error creating PKCS#7 structure\n"); goto end; } ret = 4; if (operation == SMIME_DECRYPT) { if (!PKCS7_decrypt(p7, key, recip, out, flags)) { BIO_printf(bio_err, "Error decrypting PKCS#7 structure\n"); goto end; } } else if (operation == SMIME_VERIFY) { STACK_OF(X509) *signers; if (PKCS7_verify(p7, other, store, indata, out, flags)) BIO_printf(bio_err, "Verification successful\n"); else { BIO_printf(bio_err, "Verification failure\n"); goto end; } signers = PKCS7_get0_signers(p7, other, flags); if (!save_certs(signerfile, signers)) { BIO_printf(bio_err, "Error writing signers to %s\n", signerfile); ret = 5; goto end; } sk_X509_free(signers); } else if (operation == SMIME_PK7OUT) PEM_write_bio_PKCS7(out, p7); else { 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 (outformat == FORMAT_SMIME) { if (operation == SMIME_RESIGN) SMIME_write_PKCS7(out, p7, indata, flags); else SMIME_write_PKCS7(out, p7, in, flags); } else if (outformat == FORMAT_PEM) PEM_write_bio_PKCS7_stream(out, p7, in, flags); else if (outformat == FORMAT_ASN1) i2d_PKCS7_bio_stream(out,p7, in, flags); else { BIO_printf(bio_err, "Bad output format for PKCS#7 file\n"); goto end; } } ret = 0; end: if (need_rand) app_RAND_write_file(NULL, bio_err); if (ret) ERR_print_errors(bio_err); sk_X509_pop_free(encerts, X509_free); sk_X509_pop_free(other, X509_free); if (vpm) X509_VERIFY_PARAM_free(vpm); if (sksigners) sk_OPENSSL_STRING_free(sksigners); if (skkeys) sk_OPENSSL_STRING_free(skkeys); X509_STORE_free(store); X509_free(cert); X509_free(recip); X509_free(signer); EVP_PKEY_free(key); PKCS7_free(p7); BIO_free(in); BIO_free(indata); BIO_free_all(out); if (passin) OPENSSL_free(passin); return (ret); }
int srp_main(int argc, char **argv) { ENGINE *e = NULL; CA_DB *db = NULL; CONF *conf = NULL; int gNindex = -1, maxgN = -1, ret = 1, errors = 0, verbose = 0, i; int doupdatedb = 0, mode = OPT_ERR; char *user = NULL, *passinarg = NULL, *passoutarg = NULL; char *passin = NULL, *passout = NULL, *gN = NULL, *userinfo = NULL; char *randfile = NULL, *section = NULL; char **gNrow = NULL, *configfile = NULL; char *srpvfile = NULL, **pp, *prog; OPTION_CHOICE o; prog = opt_init(argc, argv, srp_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(srp_options); ret = 0; goto end; case OPT_VERBOSE: verbose++; break; case OPT_CONFIG: configfile = opt_arg(); break; case OPT_NAME: section = opt_arg(); break; case OPT_SRPVFILE: srpvfile = opt_arg(); break; case OPT_ADD: case OPT_DELETE: case OPT_MODIFY: case OPT_LIST: if (mode != OPT_ERR) { BIO_printf(bio_err, "%s: Only one of -add/delete-modify/-list\n", prog); goto opthelp; } mode = o; break; case OPT_GN: gN = opt_arg(); break; case OPT_USERINFO: userinfo = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; } } argc = opt_num_rest(); argv = opt_rest(); if (srpvfile && configfile) { BIO_printf(bio_err, "-srpvfile and -configfile cannot be specified together.\n"); goto end; } if (mode == OPT_ERR) { BIO_printf(bio_err, "Exactly one of the options -add, -delete, -modify -list must be specified.\n"); goto opthelp; } if ((mode == OPT_DELETE || mode == OPT_MODIFY || mode == OPT_ADD) && argc < 1) { BIO_printf(bio_err, "Need at least one user for options -add, -delete, -modify. \n"); goto opthelp; } if ((passin || passout) && argc != 1) { BIO_printf(bio_err, "-passin, -passout arguments only valid with one user.\n"); goto opthelp; } if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if (!srpvfile) { if (!configfile) configfile = default_config_file; if (verbose) BIO_printf(bio_err, "Using configuration from %s\n", configfile); conf = app_load_config(configfile); if (conf == NULL) goto end; if (configfile != default_config_file && !app_load_modules(conf)) goto end; /* Lets get the config section we are using */ if (section == NULL) { if (verbose) BIO_printf(bio_err, "trying to read " ENV_DEFAULT_SRP " in " BASE_SECTION "\n"); section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_SRP); if (section == NULL) goto end; } if (randfile == NULL) randfile = NCONF_get_string(conf, BASE_SECTION, "RANDFILE"); if (verbose) BIO_printf(bio_err, "trying to read " ENV_DATABASE " in section \"%s\"\n", section); srpvfile = lookup_conf(conf, section, ENV_DATABASE); if (srpvfile == NULL) goto end; } if (randfile == NULL) ERR_clear_error(); else app_RAND_load_file(randfile, 0); if (verbose) BIO_printf(bio_err, "Trying to read SRP verifier file \"%s\"\n", srpvfile); db = load_index(srpvfile, NULL); if (db == NULL) goto end; /* Lets check some fields */ for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_srptype][0] == DB_SRP_INDEX) { maxgN = i; if ((gNindex < 0) && (gN != NULL) && strcmp(gN, pp[DB_srpid]) == 0) gNindex = i; print_index(db, i, verbose > 1); } } if (verbose) BIO_printf(bio_err, "Database initialised\n"); if (gNindex >= 0) { gNrow = sk_OPENSSL_PSTRING_value(db->db->data, gNindex); print_entry(db, gNindex, verbose > 1, "Default g and N"); } else if (maxgN > 0 && !SRP_get_default_gN(gN)) { BIO_printf(bio_err, "No g and N value for index \"%s\"\n", gN); goto end; } else { if (verbose) BIO_printf(bio_err, "Database has no g N information.\n"); gNrow = NULL; } if (verbose > 1) BIO_printf(bio_err, "Starting user processing\n"); if (argc > 0) user = *(argv++); while (mode == OPT_LIST || user) { int userindex = -1; if (user != NULL && verbose > 1) BIO_printf(bio_err, "Processing user \"%s\"\n", user); if ((userindex = get_index(db, user, 'U')) >= 0) { print_user(db, userindex, (verbose > 0) || mode == OPT_LIST); } if (mode == OPT_LIST) { if (user == NULL) { BIO_printf(bio_err, "List all users\n"); for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { print_user(db, i, 1); } } else if (userindex < 0) { BIO_printf(bio_err, "user \"%s\" does not exist, ignored. t\n", user); errors++; } } else if (mode == OPT_ADD) { if (userindex >= 0) { /* reactivation of a new user */ char **row = sk_OPENSSL_PSTRING_value(db->db->data, userindex); BIO_printf(bio_err, "user \"%s\" reactivated.\n", user); row[DB_srptype][0] = 'V'; doupdatedb = 1; } else { char *row[DB_NUMBER]; char *gNid; row[DB_srpverifier] = NULL; row[DB_srpsalt] = NULL; row[DB_srpinfo] = NULL; if (! (gNid = srp_create_user(user, &(row[DB_srpverifier]), &(row[DB_srpsalt]), gNrow ? gNrow[DB_srpsalt] : gN, gNrow ? gNrow[DB_srpverifier] : NULL, passout, verbose))) { BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned .\n", user); errors++; goto end; } row[DB_srpid] = OPENSSL_strdup(user); row[DB_srptype] = OPENSSL_strdup("v"); row[DB_srpgN] = OPENSSL_strdup(gNid); if ((row[DB_srpid] == NULL) || (row[DB_srpgN] == NULL) || (row[DB_srptype] == NULL) || (row[DB_srpverifier] == NULL) || (row[DB_srpsalt] == NULL) || (userinfo && ((row[DB_srpinfo] = OPENSSL_strdup(userinfo)) == NULL)) || !update_index(db, row)) { OPENSSL_free(row[DB_srpid]); OPENSSL_free(row[DB_srpgN]); OPENSSL_free(row[DB_srpinfo]); OPENSSL_free(row[DB_srptype]); OPENSSL_free(row[DB_srpverifier]); OPENSSL_free(row[DB_srpsalt]); goto end; } doupdatedb = 1; } } else if (mode == OPT_MODIFY) { if (userindex < 0) { BIO_printf(bio_err, "user \"%s\" does not exist, operation ignored.\n", user); errors++; } else { char **row = sk_OPENSSL_PSTRING_value(db->db->data, userindex); char type = row[DB_srptype][0]; if (type == 'v') { BIO_printf(bio_err, "user \"%s\" already updated, operation ignored.\n", user); errors++; } else { char *gNid; if (row[DB_srptype][0] == 'V') { int user_gN; char **irow = NULL; if (verbose) BIO_printf(bio_err, "Verifying password for user \"%s\"\n", user); if ((user_gN = get_index(db, row[DB_srpgN], DB_SRP_INDEX)) >= 0) irow = sk_OPENSSL_PSTRING_value(db->db->data, userindex); if (!srp_verify_user (user, row[DB_srpverifier], row[DB_srpsalt], irow ? irow[DB_srpsalt] : row[DB_srpgN], irow ? irow[DB_srpverifier] : NULL, passin, verbose)) { BIO_printf(bio_err, "Invalid password for user \"%s\", operation abandoned.\n", user); errors++; goto end; } } if (verbose) BIO_printf(bio_err, "Password for user \"%s\" ok.\n", user); if (! (gNid = srp_create_user(user, &(row[DB_srpverifier]), &(row[DB_srpsalt]), gNrow ? gNrow[DB_srpsalt] : NULL, gNrow ? gNrow[DB_srpverifier] : NULL, passout, verbose))) { BIO_printf(bio_err, "Cannot create srp verifier for user \"%s\", operation abandoned.\n", user); errors++; goto end; } row[DB_srptype][0] = 'v'; row[DB_srpgN] = OPENSSL_strdup(gNid); if (row[DB_srpid] == NULL || row[DB_srpgN] == NULL || row[DB_srptype] == NULL || row[DB_srpverifier] == NULL || row[DB_srpsalt] == NULL || (userinfo && ((row[DB_srpinfo] = OPENSSL_strdup(userinfo)) == NULL))) goto end; doupdatedb = 1; } } } else if (mode == OPT_DELETE) { if (userindex < 0) { BIO_printf(bio_err, "user \"%s\" does not exist, operation ignored. t\n", user); errors++; } else { char **xpp = sk_OPENSSL_PSTRING_value(db->db->data, userindex); BIO_printf(bio_err, "user \"%s\" revoked. t\n", user); xpp[DB_srptype][0] = 'R'; doupdatedb = 1; } } if (--argc > 0) user = *(argv++); else { user = NULL; } } if (verbose) BIO_printf(bio_err, "User procession done.\n"); if (doupdatedb) { /* Lets check some fields */ for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_srptype][0] == 'v') { pp[DB_srptype][0] = 'V'; print_user(db, i, verbose); } } if (verbose) BIO_printf(bio_err, "Trying to update srpvfile.\n"); if (!save_index(srpvfile, "new", db)) goto end; if (verbose) BIO_printf(bio_err, "Temporary srpvfile created.\n"); if (!rotate_index(srpvfile, "new", "old")) goto end; if (verbose) BIO_printf(bio_err, "srpvfile updated.\n"); } ret = (errors != 0); end: if (errors != 0) if (verbose) BIO_printf(bio_err, "User errors %d.\n", errors); if (verbose) BIO_printf(bio_err, "SRP terminating with code %d.\n", ret); OPENSSL_free(passin); OPENSSL_free(passout); if (ret) ERR_print_errors(bio_err); if (randfile) app_RAND_write_file(randfile); NCONF_free(conf); free_index(db); release_engine(e); return (ret); }
int dgst_main(int argc, char **argv) { BIO *in = NULL, *inp, *bmd = NULL, *out = NULL; ENGINE *e = NULL, *impl = NULL; EVP_PKEY *sigkey = NULL; STACK_OF(OPENSSL_STRING) *sigopts = NULL, *macopts = NULL; char *hmac_key = NULL; char *mac_name = NULL; char *passinarg = NULL, *passin = NULL; const EVP_MD *md = NULL, *m; const char *outfile = NULL, *keyfile = NULL, *prog = NULL; const char *sigfile = NULL, *randfile = NULL; OPTION_CHOICE o; int separator = 0, debug = 0, keyform = FORMAT_PEM, siglen = 0; int i, ret = 1, out_bin = -1, want_pub = 0, do_verify = 0, non_fips_allow = 0; unsigned char *buf = NULL, *sigbuf = NULL; int engine_impl = 0; prog = opt_progname(argv[0]); buf = app_malloc(BUFSIZE, "I/O buffer"); md = EVP_get_digestbyname(prog); prog = opt_init(argc, argv, dgst_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(dgst_options); ret = 0; goto end; case OPT_C: separator = 1; break; case OPT_R: separator = 2; break; case OPT_RAND: randfile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_SIGN: keyfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_VERIFY: keyfile = opt_arg(); want_pub = do_verify = 1; break; case OPT_PRVERIFY: keyfile = opt_arg(); do_verify = 1; break; case OPT_SIGNATURE: sigfile = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform)) goto opthelp; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_ENGINE_IMPL: engine_impl = 1; break; case OPT_HEX: out_bin = 0; break; case OPT_BINARY: out_bin = 1; break; case OPT_DEBUG: debug = 1; break; case OPT_FIPS_FINGERPRINT: hmac_key = "etaonrishdlcupfm"; break; case OPT_NON_FIPS_ALLOW: non_fips_allow = 1; break; case OPT_HMAC: hmac_key = opt_arg(); break; case OPT_MAC: mac_name = opt_arg(); 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_MACOPT: if (!macopts) macopts = sk_OPENSSL_STRING_new_null(); if (!macopts || !sk_OPENSSL_STRING_push(macopts, opt_arg())) goto opthelp; break; case OPT_DIGEST: if (!opt_md(opt_unknown(), &m)) goto opthelp; md = m; break; } } argc = opt_num_rest(); argv = opt_rest(); if (do_verify && !sigfile) { BIO_printf(bio_err, "No signature to verify: use the -signature option\n"); goto end; } if (engine_impl) impl = e; in = BIO_new(BIO_s_file()); bmd = BIO_new(BIO_f_md()); if ((in == NULL) || (bmd == NULL)) { ERR_print_errors(bio_err); goto end; } 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(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (out_bin == -1) { if (keyfile) out_bin = 1; else out_bin = 0; } if (randfile) app_RAND_load_file(randfile, 0); out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT); if (out == NULL) 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(keyfile, keyform, 0, NULL, e, "key file"); else sigkey = load_key(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(&mac_ctx, mac_name, impl, 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: 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, impl, (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, impl, sigkey); else r = EVP_DigestSignInit(mctx, &pctx, md, impl, 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 { EVP_MD_CTX *mctx = NULL; if (!BIO_get_md_ctx(bmd, &mctx)) { BIO_printf(bio_err, "Error getting context\n"); ERR_print_errors(bio_err); goto end; } if (md == NULL) md = EVP_sha256(); if (!EVP_DigestInit_ex(mctx, md, impl)) { BIO_printf(bio_err, "Error setting digest\n"); ERR_print_errors(bio_err); goto end; } } if (sigfile && sigkey) { BIO *sigbio = BIO_new_file(sigfile, "rb"); if (!sigbio) { BIO_printf(bio_err, "Error opening signature file %s\n", sigfile); ERR_print_errors(bio_err); goto end; } siglen = EVP_PKEY_size(sigkey); sigbuf = app_malloc(siglen, "signature buffer"); 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); ret = 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); } if (md) md_name = EVP_MD_name(md); } ret = 0; for (i = 0; i < argc; i++) { int r; if (BIO_read_filename(in, argv[i]) <= 0) { perror(argv[i]); ret++; continue; } else r = do_fp(out, buf, inp, separator, out_bin, sigkey, sigbuf, siglen, sig_name, md_name, argv[i], bmd); if (r) ret = r; (void)BIO_reset(bmd); } } end: OPENSSL_clear_free(buf, BUFSIZE); BIO_free(in); OPENSSL_free(passin); BIO_free_all(out); EVP_PKEY_free(sigkey); sk_OPENSSL_STRING_free(sigopts); sk_OPENSSL_STRING_free(macopts); OPENSSL_free(sigbuf); BIO_free(bmd); return (ret); }
int nseq_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; X509 *x509 = NULL; NETSCAPE_CERT_SEQUENCE *seq = NULL; int i, ret = 1; if (single_execution) { if (pledge("stdio cpath wpath rpath", NULL) == -1) { perror("pledge"); exit(1); } } memset(&nseq_config, 0, sizeof(nseq_config)); if (options_parse(argc, argv, nseq_options, NULL, NULL) != 0) { nseq_usage(); return (1); } if (nseq_config.infile) { if (!(in = BIO_new_file(nseq_config.infile, "r"))) { BIO_printf(bio_err, "Can't open input file %s\n", nseq_config.infile); goto end; } } else in = BIO_new_fp(stdin, BIO_NOCLOSE); if (nseq_config.outfile) { if (!(out = BIO_new_file(nseq_config.outfile, "w"))) { BIO_printf(bio_err, "Can't open output file %s\n", nseq_config.outfile); goto end; } } else { out = BIO_new_fp(stdout, BIO_NOCLOSE); } if (nseq_config.toseq) { seq = NETSCAPE_CERT_SEQUENCE_new(); seq->certs = sk_X509_new_null(); while ((x509 = PEM_read_bio_X509(in, NULL, NULL, NULL))) sk_X509_push(seq->certs, x509); if (!sk_X509_num(seq->certs)) { BIO_printf(bio_err, "Error reading certs file %s\n", nseq_config.infile); ERR_print_errors(bio_err); goto end; } PEM_write_bio_NETSCAPE_CERT_SEQUENCE(out, seq); ret = 0; goto end; } if (!(seq = PEM_read_bio_NETSCAPE_CERT_SEQUENCE(in, NULL, NULL, NULL))) { BIO_printf(bio_err, "Error reading sequence file %s\n", nseq_config.infile); ERR_print_errors(bio_err); goto end; } for (i = 0; i < sk_X509_num(seq->certs); i++) { x509 = sk_X509_value(seq->certs, i); dump_cert_text(out, x509); PEM_write_bio_X509(out, x509); } ret = 0; end: BIO_free(in); BIO_free_all(out); NETSCAPE_CERT_SEQUENCE_free(seq); return (ret); }
int MAIN(int argc, char **argv) { BN_GENCB cb; #ifndef OPENSSL_NO_ENGINE ENGINE *e = NULL; #endif int ret=1; int i,num=DEFBITS; long l; const EVP_CIPHER *enc=NULL; unsigned long f4=RSA_F4; char *outfile=NULL; char *passargout = NULL, *passout = NULL; #ifndef OPENSSL_NO_ENGINE char *engine=NULL; #endif char *inrand=NULL; BIO *out=NULL; BIGNUM *bn = BN_new(); RSA *rsa = NULL; if(!bn) goto err; apps_startup(); BN_GENCB_set(&cb, genrsa_cb, bio_err); 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; if ((out=BIO_new(BIO_s_file())) == NULL) { BIO_printf(bio_err,"unable to create BIO for output\n"); goto err; } argv++; argc--; for (;;) { if (argc <= 0) break; if (strcmp(*argv,"-out") == 0) { if (--argc < 1) goto bad; outfile= *(++argv); } else if (strcmp(*argv,"-3") == 0) f4=3; else if (strcmp(*argv,"-F4") == 0 || strcmp(*argv,"-f4") == 0) f4=RSA_F4; #ifndef OPENSSL_NO_ENGINE else if (strcmp(*argv,"-engine") == 0) { if (--argc < 1) goto bad; engine= *(++argv); } #endif else if (strcmp(*argv,"-rand") == 0) { if (--argc < 1) goto bad; inrand= *(++argv); } #ifndef OPENSSL_NO_DES else if (strcmp(*argv,"-des") == 0) enc=EVP_des_cbc(); else if (strcmp(*argv,"-des3") == 0) enc=EVP_des_ede3_cbc(); #endif #ifndef OPENSSL_NO_IDEA else if (strcmp(*argv,"-idea") == 0) enc=EVP_idea_cbc(); #endif #ifndef OPENSSL_NO_SEED else if (strcmp(*argv,"-seed") == 0) enc=EVP_seed_cbc(); #endif #ifndef OPENSSL_NO_AES else if (strcmp(*argv,"-aes128") == 0) enc=EVP_aes_128_cbc(); else if (strcmp(*argv,"-aes192") == 0) enc=EVP_aes_192_cbc(); else if (strcmp(*argv,"-aes256") == 0) enc=EVP_aes_256_cbc(); #endif #ifndef OPENSSL_NO_CAMELLIA else if (strcmp(*argv,"-camellia128") == 0) enc=EVP_camellia_128_cbc(); else if (strcmp(*argv,"-camellia192") == 0) enc=EVP_camellia_192_cbc(); else if (strcmp(*argv,"-camellia256") == 0) enc=EVP_camellia_256_cbc(); #endif else if (strcmp(*argv,"-passout") == 0) { if (--argc < 1) goto bad; passargout= *(++argv); } else break; argv++; argc--; } if ((argc >= 1) && ((sscanf(*argv,"%d",&num) == 0) || (num < 0))) { bad: BIO_printf(bio_err,"usage: genrsa [args] [numbits]\n"); BIO_printf(bio_err," -des encrypt the generated key with DES in cbc mode\n"); BIO_printf(bio_err," -des3 encrypt the generated key with DES in ede cbc mode (168 bit key)\n"); #ifndef OPENSSL_NO_IDEA BIO_printf(bio_err," -idea encrypt the generated key with IDEA in cbc mode\n"); #endif #ifndef OPENSSL_NO_SEED BIO_printf(bio_err," -seed\n"); BIO_printf(bio_err," encrypt PEM output with cbc seed\n"); #endif #ifndef OPENSSL_NO_AES BIO_printf(bio_err," -aes128, -aes192, -aes256\n"); BIO_printf(bio_err," encrypt PEM output with cbc aes\n"); #endif #ifndef OPENSSL_NO_CAMELLIA BIO_printf(bio_err," -camellia128, -camellia192, -camellia256\n"); BIO_printf(bio_err," encrypt PEM output with cbc camellia\n"); #endif BIO_printf(bio_err," -out file output the key to 'file\n"); BIO_printf(bio_err," -passout arg output file pass phrase source\n"); BIO_printf(bio_err," -f4 use F4 (0x10001) for the E value\n"); BIO_printf(bio_err," -3 use 3 for the E value\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...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); BIO_printf(bio_err," load the file (or the files in the directory) into\n"); BIO_printf(bio_err," the random number generator\n"); goto err; } ERR_load_crypto_strings(); if(!app_passwd(bio_err, NULL, passargout, NULL, &passout)) { BIO_printf(bio_err, "Error getting password\n"); goto err; } #ifndef OPENSSL_NO_ENGINE e = setup_engine(bio_err, engine, 0); #endif 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 err; } } if (!app_RAND_load_file(NULL, bio_err, 1) && inrand == NULL && !RAND_status()) { BIO_printf(bio_err,"warning, not much extra random data, consider using the -rand option\n"); } if (inrand != NULL) BIO_printf(bio_err,"%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); BIO_printf(bio_err,"Generating RSA private key, %d bit long modulus\n", num); #ifdef OPENSSL_NO_ENGINE rsa = RSA_new(); #else rsa = RSA_new_method(e); #endif if (!rsa) goto err; if(!BN_set_word(bn, f4) || !RSA_generate_key_ex(rsa, num, bn, &cb)) goto err; app_RAND_write_file(NULL, bio_err); /* We need to do the following for when the base number size is < * long, esp windows 3.1 :-(. */ l=0L; for (i=0; i<rsa->e->top; i++) { #ifndef SIXTY_FOUR_BIT l<<=BN_BITS4; l<<=BN_BITS4; #endif l+=rsa->e->d[i]; } BIO_printf(bio_err,"e is %ld (0x%lX)\n",l,l); { PW_CB_DATA cb_data; cb_data.password = passout; cb_data.prompt_info = outfile; if (!PEM_write_bio_RSAPrivateKey(out,rsa,enc,NULL,0, (pem_password_cb *)password_callback,&cb_data)) goto err; } ret=0; err: if (bn) BN_free(bn); if (rsa) RSA_free(rsa); if (out) BIO_free_all(out); if(passout) OPENSSL_free(passout); if (ret != 0) ERR_print_errors(bio_err); apps_shutdown(); OPENSSL_EXIT(ret); }
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,"-non-fips-allow") == 0) non_fips_allow=1; else if (!strcmp(*argv,"-fips-fingerprint")) hmac_key = "etaonrishdlcupfm"; 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, e, sigkey); else r = EVP_DigestSignInit(mctx, &pctx, md, e, 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 rsa_main(int argc, char **argv) { ENGINE *e = NULL; BIO *out = NULL; RSA *rsa = NULL; const EVP_CIPHER *enc = NULL; char *infile = NULL, *outfile = NULL, *prog; char *passin = NULL, *passout = NULL, *passinarg = NULL, *passoutarg = NULL; int i; int informat = FORMAT_PEM, outformat = FORMAT_PEM, text = 0, check = 0; int noout = 0, modulus = 0, pubin = 0, pubout = 0, pvk_encr = 2, ret = 1; OPTION_CHOICE o; prog = opt_init(argc, argv, rsa_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: #ifdef OPENSSL_NO_RC4 case OPT_PVK_STRONG: case OPT_PVK_WEAK: case OPT_PVK_NONE: #endif opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(rsa_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_OUT: outfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PUBIN: pubin = 1; break; case OPT_PUBOUT: pubout = 1; break; case OPT_RSAPUBKEY_IN: pubin = 2; break; case OPT_RSAPUBKEY_OUT: pubout = 2; break; #ifndef OPENSSL_NO_RC4 case OPT_PVK_STRONG: pvk_encr = 2; break; case OPT_PVK_WEAK: pvk_encr = 1; break; case OPT_PVK_NONE: pvk_encr = 0; break; #endif case OPT_NOOUT: noout = 1; break; case OPT_TEXT: text = 1; break; case OPT_MODULUS: modulus = 1; break; case OPT_CHECK: check = 1; break; case OPT_CIPHER: if (!opt_cipher(opt_unknown(), &enc)) goto opthelp; break; } } argc = opt_num_rest(); argv = opt_rest(); if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if (check && pubin) { BIO_printf(bio_err, "Only private keys can be checked\n"); goto end; } { EVP_PKEY *pkey; if (pubin) { int tmpformat = -1; if (pubin == 2) { if (informat == FORMAT_PEM) tmpformat = FORMAT_PEMRSA; else if (informat == FORMAT_ASN1) tmpformat = FORMAT_ASN1RSA; } else tmpformat = informat; pkey = load_pubkey(infile, tmpformat, 1, passin, e, "Public Key"); } else pkey = load_key(infile, informat, 1, passin, e, "Private Key"); if (pkey != NULL) rsa = EVP_PKEY_get1_RSA(pkey); EVP_PKEY_free(pkey); } if (rsa == NULL) { ERR_print_errors(bio_err); goto end; } out = bio_open_default(outfile, "w"); if (out == NULL) goto end; if (text) if (!RSA_print(out, rsa, 0)) { perror(outfile); ERR_print_errors(bio_err); goto end; } if (modulus) { BIO_printf(out, "Modulus="); BN_print(out, rsa->n); BIO_printf(out, "\n"); } if (check) { int r = RSA_check_key(rsa); if (r == 1) BIO_printf(out, "RSA key ok\n"); else if (r == 0) { unsigned long err; while ((err = ERR_peek_error()) != 0 && ERR_GET_LIB(err) == ERR_LIB_RSA && ERR_GET_FUNC(err) == RSA_F_RSA_CHECK_KEY && ERR_GET_REASON(err) != ERR_R_MALLOC_FAILURE) { BIO_printf(out, "RSA key error: %s\n", ERR_reason_error_string(err)); ERR_get_error(); /* remove e from error stack */ } } /* should happen only if r == -1 */ if (r == -1 || ERR_peek_error() != 0) { ERR_print_errors(bio_err); goto end; } } if (noout) { ret = 0; goto end; } BIO_printf(bio_err, "writing RSA key\n"); if (outformat == FORMAT_ASN1) { if (pubout || pubin) { if (pubout == 2) i = i2d_RSAPublicKey_bio(out, rsa); else i = i2d_RSA_PUBKEY_bio(out, rsa); } else i = i2d_RSAPrivateKey_bio(out, rsa); } # ifndef OPENSSL_NO_RC4 else if (outformat == FORMAT_NETSCAPE) { unsigned char *p, *save; int size = i2d_RSA_NET(rsa, NULL, NULL, 0); save = p = app_malloc(size, "RSA i2d buffer"); i2d_RSA_NET(rsa, &p, NULL, 0); BIO_write(out, (char *)save, size); OPENSSL_free(save); i = 1; } # endif else if (outformat == FORMAT_PEM) { if (pubout || pubin) { if (pubout == 2) i = PEM_write_bio_RSAPublicKey(out, rsa); else i = PEM_write_bio_RSA_PUBKEY(out, rsa); } else i = PEM_write_bio_RSAPrivateKey(out, rsa, enc, NULL, 0, NULL, passout); # if !defined(OPENSSL_NO_DSA) && !defined(OPENSSL_NO_RC4) } else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) { EVP_PKEY *pk; pk = EVP_PKEY_new(); EVP_PKEY_set1_RSA(pk, rsa); if (outformat == FORMAT_PVK) i = i2b_PVK_bio(out, pk, pvk_encr, 0, passout); else if (pubin || pubout) i = i2b_PublicKey_bio(out, pk); else i = i2b_PrivateKey_bio(out, pk); EVP_PKEY_free(pk); # endif } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (i <= 0) { BIO_printf(bio_err, "unable to write key\n"); ERR_print_errors(bio_err); } else ret = 0; end: BIO_free_all(out); RSA_free(rsa); OPENSSL_free(passin); OPENSSL_free(passout); return (ret); }
/* * This starts a minimal TLS server that only does a * handshake and then closes the connection. This is * strictly used to test TLS session negotiation * behavior with EST. */ static void us1060c_start_tls_server (char *cipherstring) { BIO *conn; BIO *listener; BIO *berr; char h_p[25]; SSL *ssl; SSL_CTX *ssl_ctx = NULL; int nid, rv; EC_KEY *ecdh = NULL; berr = BIO_new_fp(stderr, BIO_NOCLOSE); ssl_ctx = SSL_CTX_new(SSLv23_server_method()); if (!ssl_ctx) { printf("Failed to create SSL context\n"); ERR_print_errors(berr); return; } SSL_CTX_set_mode(ssl_ctx, SSL_MODE_AUTO_RETRY); if (SSL_CTX_use_certificate_chain_file(ssl_ctx, US1060C_RSA_CERT) != 1) { printf("Failed to load server certificate\n"); ERR_print_errors(berr); return; } if (SSL_CTX_use_PrivateKey_file(ssl_ctx, US1060C_RSA_KEY, SSL_FILETYPE_PEM) != 1) { printf("Failed to load server private key\n"); ERR_print_errors(berr); return; } SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_SINGLE_ECDH_USE | SSL_OP_SINGLE_DH_USE | SSL_OP_NO_TICKET); nid = OBJ_sn2nid("prime256v1"); ecdh = EC_KEY_new_by_curve_name(nid); if (ecdh == NULL) { printf("Failed to retreive ECDH curve\n"); ERR_print_errors(berr); return; } SSL_CTX_set_tmp_ecdh(ssl_ctx, ecdh); EC_KEY_free(ecdh); if (SSL_CTX_set_cipher_list(ssl_ctx, cipherstring) != 1) { printf("Failed to set server cipher list\n"); ERR_print_errors(berr); return; } SSL_CTX_set_srp_username_callback(ssl_ctx, us1060_srp_cb); sprintf(h_p, "%s:%d", US1060C_SERVER_IP, US1060C_TLS_PORT); listener = BIO_new_accept(h_p); if (listener == NULL) { printf("IP connection failed\n"); return; } BIO_set_bind_mode(listener, BIO_BIND_REUSEADDR); /* * The first call to do_accept binds the socket */ if (BIO_do_accept(listener) <= 0) { printf("TCP bind failed\n"); BIO_free_all(listener); return; } /* * The second call to do_accept waits for a new * connection request on the listener. * Note that we are in blocking mode for this socket */ if (BIO_do_accept(listener) <= 0) { printf("TCP accept failed\n"); BIO_free_all(listener); return; } conn = BIO_pop(listener); ssl = SSL_new(ssl_ctx); SSL_set_bio(ssl, conn, conn); /* * Now that we have everything ready, let's start waiting for * a client to contact us. Normally we might using a pthread * or some other construct to avoid blocking on the main * thread while waiting for an incoming connection. This * code is simply a contrived example, we will wait on the * main thread for an incoming connection. */ rv = SSL_accept(ssl); if (rv <= 0) { printf("\nFailed to complete TLS handshake %d\n", rv); ERR_print_errors(berr); } #ifdef WIN32 SLEEP(2); #endif SSL_shutdown(ssl); SSL_free(ssl); SSL_CTX_free(ssl_ctx); BIO_free(berr); (void)BIO_reset(listener); BIO_free_all(listener); #ifndef WIN32 pthread_exit(0); #else ExitThread(0); #endif }