code
stringlengths
49
1.37M
repo_name
stringclasses
117 values
path
stringlengths
17
73
from
stringclasses
1 value
#include <openssl/opensslconf.h> #include "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/store.h> #include <openssl/x509v3.h> static int process(const char *uri, const UI_METHOD *uimeth, PW_CB_DATA *uidata, int expected, int criterion, OSSL_STORE_SEARCH *search, int text, int noout, int recursive, int indent, BIO *out, const char *prog, OSSL_LIB_CTX *libctx); typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_OUT, OPT_PASSIN, OPT_NOOUT, OPT_TEXT, OPT_RECURSIVE, OPT_SEARCHFOR_CERTS, OPT_SEARCHFOR_KEYS, OPT_SEARCHFOR_CRLS, OPT_CRITERION_SUBJECT, OPT_CRITERION_ISSUER, OPT_CRITERION_SERIAL, OPT_CRITERION_FINGERPRINT, OPT_CRITERION_ALIAS, OPT_MD, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS storeutl_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] uri\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"", OPT_MD, '-', "Any supported digest"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Search"), {"certs", OPT_SEARCHFOR_CERTS, '-', "Search for certificates only"}, {"keys", OPT_SEARCHFOR_KEYS, '-', "Search for keys only"}, {"crls", OPT_SEARCHFOR_CRLS, '-', "Search for CRLs only"}, {"subject", OPT_CRITERION_SUBJECT, 's', "Search by subject"}, {"issuer", OPT_CRITERION_ISSUER, 's', "Search by issuer and serial, issuer name"}, {"serial", OPT_CRITERION_SERIAL, 's', "Search by issuer and serial, serial number"}, {"fingerprint", OPT_CRITERION_FINGERPRINT, 's', "Search by public key fingerprint, given in hex"}, {"alias", OPT_CRITERION_ALIAS, 's', "Search by alias"}, {"r", OPT_RECURSIVE, '-', "Recurse through names"}, OPT_SECTION("Input"), {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file - default stdout"}, {"text", OPT_TEXT, '-', "Print a text form of the objects"}, {"noout", OPT_NOOUT, '-', "No PEM output, just status"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"uri", 0, 0, "URI of the store object"}, {NULL} }; int storeutl_main(int argc, char *argv[]) { int ret = 1, noout = 0, text = 0, recursive = 0; char *outfile = NULL, *passin = NULL, *passinarg = NULL; BIO *out = NULL; ENGINE *e = NULL; OPTION_CHOICE o; char *prog; PW_CB_DATA pw_cb_data; int expected = 0; int criterion = 0; X509_NAME *subject = NULL, *issuer = NULL; ASN1_INTEGER *serial = NULL; unsigned char *fingerprint = NULL; size_t fingerprintlen = 0; char *alias = NULL, *digestname = NULL; OSSL_STORE_SEARCH *search = NULL; EVP_MD *digest = NULL; OSSL_LIB_CTX *libctx = app_get0_libctx(); opt_set_unknown_name("digest"); prog = opt_init(argc, argv, storeutl_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(storeutl_options); ret = 0; goto end; case OPT_OUT: outfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_NOOUT: noout = 1; break; case OPT_TEXT: text = 1; break; case OPT_RECURSIVE: recursive = 1; break; case OPT_SEARCHFOR_CERTS: case OPT_SEARCHFOR_KEYS: case OPT_SEARCHFOR_CRLS: if (expected != 0) { BIO_printf(bio_err, "%s: only one search type can be given.\n", prog); goto end; } { static const struct { enum OPTION_choice choice; int type; } map[] = { {OPT_SEARCHFOR_CERTS, OSSL_STORE_INFO_CERT}, {OPT_SEARCHFOR_KEYS, OSSL_STORE_INFO_PKEY}, {OPT_SEARCHFOR_CRLS, OSSL_STORE_INFO_CRL}, }; size_t i; for (i = 0; i < OSSL_NELEM(map); i++) { if (o == map[i].choice) { expected = map[i].type; break; } } OPENSSL_assert(expected != 0); } break; case OPT_CRITERION_SUBJECT: if (criterion != 0) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_NAME; if (subject != NULL) { BIO_printf(bio_err, "%s: subject already given.\n", prog); goto end; } subject = parse_name(opt_arg(), MBSTRING_UTF8, 1, "subject"); if (subject == NULL) goto end; break; case OPT_CRITERION_ISSUER: if (criterion != 0 && criterion != OSSL_STORE_SEARCH_BY_ISSUER_SERIAL) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL; if (issuer != NULL) { BIO_printf(bio_err, "%s: issuer already given.\n", prog); goto end; } issuer = parse_name(opt_arg(), MBSTRING_UTF8, 1, "issuer"); if (issuer == NULL) goto end; break; case OPT_CRITERION_SERIAL: if (criterion != 0 && criterion != OSSL_STORE_SEARCH_BY_ISSUER_SERIAL) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_ISSUER_SERIAL; if (serial != NULL) { BIO_printf(bio_err, "%s: serial number already given.\n", prog); goto end; } if ((serial = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL) { BIO_printf(bio_err, "%s: can't parse serial number argument.\n", prog); goto end; } break; case OPT_CRITERION_FINGERPRINT: if (criterion != 0 || (criterion == OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT && fingerprint != NULL)) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT; if (fingerprint != NULL) { BIO_printf(bio_err, "%s: fingerprint already given.\n", prog); goto end; } { long tmplen = 0; if ((fingerprint = OPENSSL_hexstr2buf(opt_arg(), &tmplen)) == NULL) { BIO_printf(bio_err, "%s: can't parse fingerprint argument.\n", prog); goto end; } fingerprintlen = (size_t)tmplen; } break; case OPT_CRITERION_ALIAS: if (criterion != 0) { BIO_printf(bio_err, "%s: criterion already given.\n", prog); goto end; } criterion = OSSL_STORE_SEARCH_BY_ALIAS; if (alias != NULL) { BIO_printf(bio_err, "%s: alias already given.\n", prog); goto end; } if ((alias = OPENSSL_strdup(opt_arg())) == NULL) { BIO_printf(bio_err, "%s: can't parse alias argument.\n", prog); goto end; } break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_MD: digestname = opt_unknown(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg("URI")) goto opthelp; argv = opt_rest(); if (!opt_md(digestname, &digest)) goto opthelp; if (criterion != 0) { switch (criterion) { case OSSL_STORE_SEARCH_BY_NAME: if ((search = OSSL_STORE_SEARCH_by_name(subject)) == NULL) { ERR_print_errors(bio_err); goto end; } break; case OSSL_STORE_SEARCH_BY_ISSUER_SERIAL: if (issuer == NULL || serial == NULL) { BIO_printf(bio_err, "%s: both -issuer and -serial must be given.\n", prog); goto end; } if ((search = OSSL_STORE_SEARCH_by_issuer_serial(issuer, serial)) == NULL) { ERR_print_errors(bio_err); goto end; } break; case OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT: if ((search = OSSL_STORE_SEARCH_by_key_fingerprint(digest, fingerprint, fingerprintlen)) == NULL) { ERR_print_errors(bio_err); goto end; } break; case OSSL_STORE_SEARCH_BY_ALIAS: if ((search = OSSL_STORE_SEARCH_by_alias(alias)) == NULL) { ERR_print_errors(bio_err); goto end; } break; } } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } pw_cb_data.password = passin; pw_cb_data.prompt_info = argv[0]; out = bio_open_default(outfile, 'w', FORMAT_TEXT); if (out == NULL) goto end; ret = process(argv[0], get_ui_method(), &pw_cb_data, expected, criterion, search, text, noout, recursive, 0, out, prog, libctx); end: EVP_MD_free(digest); OPENSSL_free(fingerprint); OPENSSL_free(alias); ASN1_INTEGER_free(serial); X509_NAME_free(subject); X509_NAME_free(issuer); OSSL_STORE_SEARCH_free(search); BIO_free_all(out); OPENSSL_free(passin); release_engine(e); return ret; } static int indent_printf(int indent, BIO *bio, const char *format, ...) { va_list args; int ret; va_start(args, format); ret = BIO_printf(bio, "%*s", indent, "") + BIO_vprintf(bio, format, args); va_end(args); return ret; } static int process(const char *uri, const UI_METHOD *uimeth, PW_CB_DATA *uidata, int expected, int criterion, OSSL_STORE_SEARCH *search, int text, int noout, int recursive, int indent, BIO *out, const char *prog, OSSL_LIB_CTX *libctx) { OSSL_STORE_CTX *store_ctx = NULL; int ret = 1, items = 0; if ((store_ctx = OSSL_STORE_open_ex(uri, libctx, app_get0_propq(), uimeth, uidata, NULL, NULL, NULL)) == NULL) { BIO_printf(bio_err, "Couldn't open file or uri %s\n", uri); ERR_print_errors(bio_err); return ret; } if (expected != 0) { if (!OSSL_STORE_expect(store_ctx, expected)) { ERR_print_errors(bio_err); goto end2; } } if (criterion != 0) { if (!OSSL_STORE_supports_search(store_ctx, criterion)) { BIO_printf(bio_err, "%s: the store scheme doesn't support the given search criteria.\n", prog); goto end2; } if (!OSSL_STORE_find(store_ctx, search)) { ERR_print_errors(bio_err); goto end2; } } ret = 0; for (;;) { OSSL_STORE_INFO *info = OSSL_STORE_load(store_ctx); int type = info == NULL ? 0 : OSSL_STORE_INFO_get_type(info); const char *infostr = info == NULL ? NULL : OSSL_STORE_INFO_type_string(type); if (info == NULL) { if (OSSL_STORE_error(store_ctx)) { if (recursive) ERR_clear_error(); else ERR_print_errors(bio_err); if (OSSL_STORE_eof(store_ctx)) break; ret++; continue; } if (OSSL_STORE_eof(store_ctx)) break; BIO_printf(bio_err, "ERROR: OSSL_STORE_load() returned NULL without " "eof or error indications\n"); BIO_printf(bio_err, " This is an error in the loader\n"); ERR_print_errors(bio_err); ret++; break; } if (type == OSSL_STORE_INFO_NAME) { const char *name = OSSL_STORE_INFO_get0_NAME(info); const char *desc = OSSL_STORE_INFO_get0_NAME_description(info); indent_printf(indent, bio_out, "%d: %s: %s\n", items, infostr, name); if (desc != NULL) indent_printf(indent, bio_out, "%s\n", desc); } else { indent_printf(indent, bio_out, "%d: %s\n", items, infostr); } switch (type) { case OSSL_STORE_INFO_NAME: if (recursive) { const char *suburi = OSSL_STORE_INFO_get0_NAME(info); ret += process(suburi, uimeth, uidata, expected, criterion, search, text, noout, recursive, indent + 2, out, prog, libctx); } break; case OSSL_STORE_INFO_PARAMS: if (text) EVP_PKEY_print_params(out, OSSL_STORE_INFO_get0_PARAMS(info), 0, NULL); if (!noout) PEM_write_bio_Parameters(out, OSSL_STORE_INFO_get0_PARAMS(info)); break; case OSSL_STORE_INFO_PUBKEY: if (text) EVP_PKEY_print_public(out, OSSL_STORE_INFO_get0_PUBKEY(info), 0, NULL); if (!noout) PEM_write_bio_PUBKEY(out, OSSL_STORE_INFO_get0_PUBKEY(info)); break; case OSSL_STORE_INFO_PKEY: if (text) EVP_PKEY_print_private(out, OSSL_STORE_INFO_get0_PKEY(info), 0, NULL); if (!noout) PEM_write_bio_PrivateKey(out, OSSL_STORE_INFO_get0_PKEY(info), NULL, NULL, 0, NULL, NULL); break; case OSSL_STORE_INFO_CERT: if (text) X509_print(out, OSSL_STORE_INFO_get0_CERT(info)); if (!noout) PEM_write_bio_X509(out, OSSL_STORE_INFO_get0_CERT(info)); break; case OSSL_STORE_INFO_CRL: if (text) X509_CRL_print(out, OSSL_STORE_INFO_get0_CRL(info)); if (!noout) PEM_write_bio_X509_CRL(out, OSSL_STORE_INFO_get0_CRL(info)); break; default: BIO_printf(bio_err, "!!! Unknown code\n"); ret++; break; } items++; OSSL_STORE_INFO_free(info); } indent_printf(indent, out, "Total found: %d\n", items); end2: if (!OSSL_STORE_close(store_ctx)) { ERR_print_errors(bio_err); ret++; } return ret; }
apps
openssl/apps/storeutl.c
openssl
#include "apps.h" #include "progs.h" #if defined(OPENSSL_SYS_UNIX) || defined(__APPLE__) || \ (defined(__VMS) && defined(__DECC) && __CRTL_VER >= 80300000) # include <unistd.h> # include <stdio.h> # include <limits.h> # include <errno.h> # include <string.h> # include <ctype.h> # include <sys/stat.h> # ifdef __VMS # pragma names save # pragma names as_is,shortened # endif # include "internal/o_dir.h" # ifdef __VMS # pragma names restore # endif # include <openssl/evp.h> # include <openssl/pem.h> # include <openssl/x509.h> # ifndef PATH_MAX # define PATH_MAX 4096 # endif # define MAX_COLLISIONS 256 # if defined(OPENSSL_SYS_VXWORKS) # define lstat(path, buf) stat(path, buf) int symlink(const char *target, const char *linkpath) { errno = ENOSYS; return -1; } ssize_t readlink(const char *pathname, char *buf, size_t bufsiz) { errno = ENOSYS; return -1; } # endif typedef struct hentry_st { struct hentry_st *next; char *filename; unsigned short old_id; unsigned char need_symlink; unsigned char digest[EVP_MAX_MD_SIZE]; } HENTRY; typedef struct bucket_st { struct bucket_st *next; HENTRY *first_entry, *last_entry; unsigned int hash; unsigned short type; unsigned short num_needed; } BUCKET; enum Type { TYPE_CERT=0, TYPE_CRL=1 }; enum Hash { HASH_OLD, HASH_NEW, HASH_BOTH }; static int evpmdsize; static const EVP_MD *evpmd; static int remove_links = 1; static int verbose = 0; static BUCKET *hash_table[257]; static const char *suffixes[] = { "", "r" }; static const char *extensions[] = { "pem", "crt", "cer", "crl" }; static void bit_set(unsigned char *set, unsigned int bit) { set[bit >> 3] |= 1 << (bit & 0x7); } static int bit_isset(unsigned char *set, unsigned int bit) { return set[bit >> 3] & (1 << (bit & 0x7)); } static int add_entry(enum Type type, unsigned int hash, const char *filename, const unsigned char *digest, int need_symlink, unsigned short old_id) { static BUCKET nilbucket; static HENTRY nilhentry; BUCKET *bp; HENTRY *ep, *found = NULL; unsigned int ndx = (type + hash) % OSSL_NELEM(hash_table); for (bp = hash_table[ndx]; bp; bp = bp->next) if (bp->type == type && bp->hash == hash) break; if (bp == NULL) { bp = app_malloc(sizeof(*bp), "hash bucket"); *bp = nilbucket; bp->next = hash_table[ndx]; bp->type = type; bp->hash = hash; hash_table[ndx] = bp; } for (ep = bp->first_entry; ep; ep = ep->next) { if (digest && memcmp(digest, ep->digest, evpmdsize) == 0) { BIO_printf(bio_err, "%s: warning: skipping duplicate %s in %s\n", opt_getprog(), type == TYPE_CERT ? "certificate" : "CRL", filename); return 0; } if (strcmp(filename, ep->filename) == 0) { found = ep; if (digest == NULL) break; } } ep = found; if (ep == NULL) { if (bp->num_needed >= MAX_COLLISIONS) { BIO_printf(bio_err, "%s: error: hash table overflow for %s\n", opt_getprog(), filename); return 1; } ep = app_malloc(sizeof(*ep), "collision bucket"); *ep = nilhentry; ep->old_id = ~0; ep->filename = OPENSSL_strdup(filename); if (ep->filename == NULL) { OPENSSL_free(ep); ep = NULL; BIO_printf(bio_err, "out of memory\n"); return 1; } if (bp->last_entry) bp->last_entry->next = ep; if (bp->first_entry == NULL) bp->first_entry = ep; bp->last_entry = ep; } if (old_id < ep->old_id) ep->old_id = old_id; if (need_symlink && !ep->need_symlink) { ep->need_symlink = 1; bp->num_needed++; memcpy(ep->digest, digest, evpmdsize); } return 0; } static int handle_symlink(const char *filename, const char *fullpath) { unsigned int hash = 0; int i, type, id; unsigned char ch; char linktarget[PATH_MAX], *endptr; ossl_ssize_t n; for (i = 0; i < 8; i++) { ch = filename[i]; if (!isxdigit(ch)) return -1; hash <<= 4; hash += OPENSSL_hexchar2int(ch); } if (filename[i++] != '.') return -1; for (type = OSSL_NELEM(suffixes) - 1; type > 0; type--) if (OPENSSL_strncasecmp(&filename[i], suffixes[type], strlen(suffixes[type])) == 0) break; i += strlen(suffixes[type]); id = strtoul(&filename[i], &endptr, 10); if (*endptr != '\0') return -1; n = readlink(fullpath, linktarget, sizeof(linktarget)); if (n < 0 || n >= (int)sizeof(linktarget)) return -1; linktarget[n] = 0; return add_entry(type, hash, linktarget, NULL, 0, id); } static int do_file(const char *filename, const char *fullpath, enum Hash h) { STACK_OF (X509_INFO) *inf = NULL; X509_INFO *x; const X509_NAME *name = NULL; BIO *b; const char *ext; unsigned char digest[EVP_MAX_MD_SIZE]; int type, errs = 0; size_t i; if ((ext = strrchr(filename, '.')) == NULL) goto end; for (i = 0; i < OSSL_NELEM(extensions); i++) { if (OPENSSL_strcasecmp(extensions[i], ext + 1) == 0) break; } if (i >= OSSL_NELEM(extensions)) goto end; if ((b = BIO_new_file(fullpath, "r")) == NULL) { BIO_printf(bio_err, "%s: error: skipping %s, cannot open file\n", opt_getprog(), filename); errs++; goto end; } inf = PEM_X509_INFO_read_bio(b, NULL, NULL, NULL); BIO_free(b); if (inf == NULL) goto end; if (sk_X509_INFO_num(inf) != 1) { BIO_printf(bio_err, "%s: warning: skipping %s, " "it does not contain exactly one certificate or CRL\n", opt_getprog(), filename); goto end; } x = sk_X509_INFO_value(inf, 0); if (x->x509 != NULL) { type = TYPE_CERT; name = X509_get_subject_name(x->x509); if (!X509_digest(x->x509, evpmd, digest, NULL)) { BIO_printf(bio_err, "out of memory\n"); ++errs; goto end; } } else if (x->crl != NULL) { type = TYPE_CRL; name = X509_CRL_get_issuer(x->crl); if (!X509_CRL_digest(x->crl, evpmd, digest, NULL)) { BIO_printf(bio_err, "out of memory\n"); ++errs; goto end; } } else { ++errs; goto end; } if (name != NULL) { if (h == HASH_NEW || h == HASH_BOTH) { int ok; unsigned long hash_value = X509_NAME_hash_ex(name, app_get0_libctx(), app_get0_propq(), &ok); if (ok) { errs += add_entry(type, hash_value, filename, digest, 1, ~0); } else { BIO_printf(bio_err, "%s: error calculating SHA1 hash value\n", opt_getprog()); errs++; } } if ((h == HASH_OLD) || (h == HASH_BOTH)) errs += add_entry(type, X509_NAME_hash_old(name), filename, digest, 1, ~0); } end: sk_X509_INFO_pop_free(inf, X509_INFO_free); return errs; } static void str_free(char *s) { OPENSSL_free(s); } static int ends_with_dirsep(const char *path) { if (*path != '\0') path += strlen(path) - 1; # if defined __VMS if (*path == ']' || *path == '>' || *path == ':') return 1; # elif defined _WIN32 if (*path == '\\') return 1; # endif return *path == '/'; } static int sk_strcmp(const char * const *a, const char * const *b) { return strcmp(*a, *b); } static int do_dir(const char *dirname, enum Hash h) { BUCKET *bp, *nextbp; HENTRY *ep, *nextep; OPENSSL_DIR_CTX *d = NULL; struct stat st; unsigned char idmask[MAX_COLLISIONS / 8]; int n, numfiles, nextid, dirlen, buflen, errs = 0; size_t i, fname_max_len = 20; const char *pathsep = ""; const char *filename; char *buf = NULL, *copy = NULL; STACK_OF(OPENSSL_STRING) *files = NULL; if (app_access(dirname, W_OK) < 0) { BIO_printf(bio_err, "Skipping %s, can't write\n", dirname); return 1; } dirlen = strlen(dirname); if (dirlen != 0 && !ends_with_dirsep(dirname)) { pathsep = "/"; dirlen++; } if (verbose) BIO_printf(bio_out, "Doing %s\n", dirname); if ((files = sk_OPENSSL_STRING_new(sk_strcmp)) == NULL) { BIO_printf(bio_err, "Skipping %s, out of memory\n", dirname); errs = 1; goto err; } while ((filename = OPENSSL_DIR_read(&d, dirname)) != NULL) { size_t fname_len = strlen(filename); if ((copy = OPENSSL_strdup(filename)) == NULL || sk_OPENSSL_STRING_push(files, copy) == 0) { OPENSSL_free(copy); OPENSSL_DIR_end(&d); BIO_puts(bio_err, "out of memory\n"); errs = 1; goto err; } if (fname_len > fname_max_len) fname_max_len = fname_len; } OPENSSL_DIR_end(&d); sk_OPENSSL_STRING_sort(files); buflen = dirlen + fname_max_len + 1; buf = app_malloc(buflen, "filename buffer"); numfiles = sk_OPENSSL_STRING_num(files); for (n = 0; n < numfiles; ++n) { filename = sk_OPENSSL_STRING_value(files, n); if (BIO_snprintf(buf, buflen, "%s%s%s", dirname, pathsep, filename) >= buflen) continue; if (lstat(buf, &st) < 0) continue; if (S_ISLNK(st.st_mode) && handle_symlink(filename, buf) == 0) continue; errs += do_file(filename, buf, h); } for (i = 0; i < OSSL_NELEM(hash_table); i++) { for (bp = hash_table[i]; bp; bp = nextbp) { nextbp = bp->next; nextid = 0; memset(idmask, 0, (bp->num_needed + 7) / 8); for (ep = bp->first_entry; ep; ep = ep->next) if (ep->old_id < bp->num_needed) bit_set(idmask, ep->old_id); for (ep = bp->first_entry; ep; ep = nextep) { nextep = ep->next; if (ep->old_id < bp->num_needed) { BIO_snprintf(buf, buflen, "%08x.%s%d", bp->hash, suffixes[bp->type], ep->old_id); if (verbose) BIO_printf(bio_out, "link %s -> %s\n", ep->filename, buf); } else if (ep->need_symlink) { while (bit_isset(idmask, nextid)) nextid++; BIO_snprintf(buf, buflen, "%s%s%08x.%s%d", dirname, pathsep, bp->hash, suffixes[bp->type], nextid); if (verbose) BIO_printf(bio_out, "link %s -> %s\n", ep->filename, &buf[dirlen]); if (unlink(buf) < 0 && errno != ENOENT) { BIO_printf(bio_err, "%s: Can't unlink %s, %s\n", opt_getprog(), buf, strerror(errno)); errs++; } if (symlink(ep->filename, buf) < 0) { BIO_printf(bio_err, "%s: Can't symlink %s, %s\n", opt_getprog(), ep->filename, strerror(errno)); errs++; } bit_set(idmask, nextid); } else if (remove_links) { BIO_snprintf(buf, buflen, "%s%s%08x.%s%d", dirname, pathsep, bp->hash, suffixes[bp->type], ep->old_id); if (verbose) BIO_printf(bio_out, "unlink %s\n", &buf[dirlen]); if (unlink(buf) < 0 && errno != ENOENT) { BIO_printf(bio_err, "%s: Can't unlink %s, %s\n", opt_getprog(), buf, strerror(errno)); errs++; } } OPENSSL_free(ep->filename); OPENSSL_free(ep); } OPENSSL_free(bp); } hash_table[i] = NULL; } err: sk_OPENSSL_STRING_pop_free(files, str_free); OPENSSL_free(buf); return errs; } typedef enum OPTION_choice { OPT_COMMON, OPT_COMPAT, OPT_OLD, OPT_N, OPT_VERBOSE, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS rehash_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [directory...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"h", OPT_HELP, '-', "Display this summary"}, {"compat", OPT_COMPAT, '-', "Create both new- and old-style hash links"}, {"old", OPT_OLD, '-', "Use old-style hash to generate links"}, {"n", OPT_N, '-', "Do not remove existing links"}, OPT_SECTION("Output"), {"v", OPT_VERBOSE, '-', "Verbose output"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"directory", 0, 0, "One or more directories to process (optional)"}, {NULL} }; int rehash_main(int argc, char **argv) { const char *env, *prog; char *e, *m; int errs = 0; OPTION_CHOICE o; enum Hash h = HASH_NEW; prog = opt_init(argc, argv, rehash_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(rehash_options); goto end; case OPT_COMPAT: h = HASH_BOTH; break; case OPT_OLD: h = HASH_OLD; break; case OPT_N: remove_links = 0; break; case OPT_VERBOSE: verbose = 1; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } argc = opt_num_rest(); argv = opt_rest(); evpmd = EVP_sha1(); evpmdsize = EVP_MD_get_size(evpmd); if (*argv != NULL) { while (*argv != NULL) errs += do_dir(*argv++, h); } else if ((env = getenv(X509_get_default_cert_dir_env())) != NULL) { char lsc[2] = { LIST_SEPARATOR_CHAR, '\0' }; m = OPENSSL_strdup(env); for (e = strtok(m, lsc); e != NULL; e = strtok(NULL, lsc)) errs += do_dir(e, h); OPENSSL_free(m); } else { errs += do_dir(X509_get_default_cert_dir(), h); } end: return errs; } #else const OPTIONS rehash_options[] = { {NULL} }; int rehash_main(int argc, char **argv) { BIO_printf(bio_err, "Not available; use c_rehash script\n"); return 1; } #endif
apps
openssl/apps/rehash.c
openssl
#include <stdio.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/evp.h> static int verbose = 1; static int init_keygen_file(EVP_PKEY_CTX **pctx, const char *file, ENGINE *e, OSSL_LIB_CTX *libctx, const char *propq); typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_OUTFORM, OPT_OUT, OPT_PASS, OPT_PARAMFILE, OPT_ALGORITHM, OPT_PKEYOPT, OPT_GENPARAM, OPT_TEXT, OPT_CIPHER, OPT_VERBOSE, OPT_QUIET, OPT_CONFIG, OPT_OUTPUBKEY, OPT_PROV_ENUM, OPT_R_ENUM } OPTION_CHOICE; const OPTIONS genpkey_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"paramfile", OPT_PARAMFILE, '<', "Parameters file"}, {"algorithm", OPT_ALGORITHM, 's', "The public key algorithm"}, {"verbose", OPT_VERBOSE, '-', "Output status while generating keys"}, {"quiet", OPT_QUIET, '-', "Do not output status while generating keys"}, {"pkeyopt", OPT_PKEYOPT, 's', "Set the public key algorithm option as opt:value"}, OPT_CONFIG_OPTION, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output (private key) file"}, {"outpubkey", OPT_OUTPUBKEY, '>', "Output public key file"}, {"outform", OPT_OUTFORM, 'F', "output format (DER or PEM)"}, {"pass", OPT_PASS, 's', "Output file pass phrase source"}, {"genparam", OPT_GENPARAM, '-', "Generate parameters, not key"}, {"text", OPT_TEXT, '-', "Print the private key in text"}, {"", OPT_CIPHER, '-', "Cipher to use to encrypt the key"}, OPT_PROV_OPTIONS, OPT_R_OPTIONS, {OPT_HELP_STR, 1, 1, "Order of options may be important! See the documentation.\n"}, {NULL} }; static const char *param_datatype_2name(unsigned int type, int *ishex) { *ishex = 0; switch (type) { case OSSL_PARAM_INTEGER: return "int"; case OSSL_PARAM_UNSIGNED_INTEGER: return "uint"; case OSSL_PARAM_REAL: return "float"; case OSSL_PARAM_OCTET_STRING: *ishex = 1; return "string"; case OSSL_PARAM_UTF8_STRING: return "string"; default: return NULL; } } static void show_gen_pkeyopt(const char *algname, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY_CTX *ctx = NULL; const OSSL_PARAM *params; int i, ishex = 0; if (algname == NULL) return; ctx = EVP_PKEY_CTX_new_from_name(libctx, algname, propq); if (ctx == NULL) return; if (EVP_PKEY_keygen_init(ctx) <= 0) goto cleanup; params = EVP_PKEY_CTX_settable_params(ctx); if (params == NULL) goto cleanup; BIO_printf(bio_err, "\nThe possible -pkeyopt arguments are:\n"); for (i = 0; params[i].key != NULL; ++i) { const char *name = param_datatype_2name(params[i].data_type, &ishex); if (name != NULL) BIO_printf(bio_err, " %s%s:%s\n", ishex ? "hex" : "", params[i].key, name); } cleanup: EVP_PKEY_CTX_free(ctx); } int genpkey_main(int argc, char **argv) { CONF *conf = NULL; BIO *in = NULL, *out = NULL, *outpubkey = NULL; ENGINE *e = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; char *outfile = NULL, *passarg = NULL, *pass = NULL, *prog, *p; char *outpubkeyfile = NULL; const char *ciphername = NULL, *paramfile = NULL, *algname = NULL; EVP_CIPHER *cipher = NULL; OPTION_CHOICE o; int outformat = FORMAT_PEM, text = 0, ret = 1, rv, do_param = 0; int private = 0, i; OSSL_LIB_CTX *libctx = app_get0_libctx(); STACK_OF(OPENSSL_STRING) *keyopt = NULL; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, genpkey_options); keyopt = sk_OPENSSL_STRING_new_null(); if (keyopt == NULL) goto end; 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(genpkey_options); show_gen_pkeyopt(algname, libctx, app_get0_propq()); goto end; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_OUTPUBKEY: outpubkeyfile = opt_arg(); break; case OPT_PASS: passarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PARAMFILE: if (do_param == 1) goto opthelp; paramfile = opt_arg(); break; case OPT_ALGORITHM: algname = opt_arg(); break; case OPT_PKEYOPT: if (!sk_OPENSSL_STRING_push(keyopt, opt_arg())) goto end; break; case OPT_QUIET: verbose = 0; break; case OPT_VERBOSE: verbose = 1; break; case OPT_GENPARAM: do_param = 1; break; case OPT_TEXT: text = 1; break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_CONFIG: conf = app_load_config_modules(opt_arg()); if (conf == NULL) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (paramfile != NULL) { if (!init_keygen_file(&ctx, paramfile, e, libctx, app_get0_propq())) goto end; } if (algname != NULL) { if (!init_gen_str(&ctx, algname, e, do_param, libctx, app_get0_propq())) goto end; } if (ctx == NULL) goto opthelp; for (i = 0; i < sk_OPENSSL_STRING_num(keyopt); i++) { p = sk_OPENSSL_STRING_value(keyopt, i); if (pkey_ctrl_string(ctx, p) <= 0) { BIO_printf(bio_err, "%s: Error setting %s parameter:\n", prog, p); ERR_print_errors(bio_err); goto end; } } if (!opt_cipher(ciphername, &cipher)) goto opthelp; if (ciphername != NULL && do_param == 1) { BIO_printf(bio_err, "Cannot use cipher with -genparam option\n"); goto opthelp; } private = do_param ? 0 : 1; if (!app_passwd(passarg, NULL, &pass, NULL)) { BIO_puts(bio_err, "Error getting password\n"); goto end; } out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (outpubkeyfile != NULL) { outpubkey = bio_open_owner(outpubkeyfile, outformat, private); if (outpubkey == NULL) goto end; } if (verbose) EVP_PKEY_CTX_set_cb(ctx, progress_cb); EVP_PKEY_CTX_set_app_data(ctx, bio_err); pkey = do_param ? app_paramgen(ctx, algname) : app_keygen(ctx, algname, 0, 0 ); if (pkey == NULL) goto end; if (do_param) { rv = PEM_write_bio_Parameters(out, pkey); } else if (outformat == FORMAT_PEM) { assert(private); rv = PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0, NULL, pass); if (rv > 0 && outpubkey != NULL) rv = PEM_write_bio_PUBKEY(outpubkey, pkey); } else if (outformat == FORMAT_ASN1) { assert(private); rv = i2d_PrivateKey_bio(out, pkey); if (rv > 0 && outpubkey != NULL) rv = i2d_PUBKEY_bio(outpubkey, pkey); } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } ret = 0; if (rv <= 0) { BIO_puts(bio_err, "Error writing key(s)\n"); ret = 1; } if (text) { if (do_param) rv = EVP_PKEY_print_params(out, pkey, 0, NULL); else rv = EVP_PKEY_print_private(out, pkey, 0, NULL); if (rv <= 0) { BIO_puts(bio_err, "Error printing key\n"); ret = 1; } } end: sk_OPENSSL_STRING_free(keyopt); if (ret != 0) ERR_print_errors(bio_err); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(ctx); EVP_CIPHER_free(cipher); BIO_free_all(out); BIO_free_all(outpubkey); BIO_free(in); release_engine(e); OPENSSL_free(pass); NCONF_free(conf); return ret; } static int init_keygen_file(EVP_PKEY_CTX **pctx, const char *file, ENGINE *e, OSSL_LIB_CTX *libctx, const char *propq) { BIO *pbio; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; if (*pctx) { BIO_puts(bio_err, "Parameters already set!\n"); return 0; } pbio = BIO_new_file(file, "r"); if (pbio == NULL) { BIO_printf(bio_err, "Can't open parameter file %s\n", file); return 0; } pkey = PEM_read_bio_Parameters_ex(pbio, NULL, libctx, propq); BIO_free(pbio); if (pkey == NULL) { BIO_printf(bio_err, "Error reading parameter file %s\n", file); return 0; } if (e != NULL) ctx = EVP_PKEY_CTX_new(pkey, e); else ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (ctx == NULL) goto err; if (EVP_PKEY_keygen_init(ctx) <= 0) goto err; EVP_PKEY_free(pkey); *pctx = ctx; return 1; err: BIO_puts(bio_err, "Error initializing context\n"); ERR_print_errors(bio_err); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); return 0; } int init_gen_str(EVP_PKEY_CTX **pctx, const char *algname, ENGINE *e, int do_param, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY_CTX *ctx = NULL; int pkey_id; if (*pctx) { BIO_puts(bio_err, "Algorithm already set!\n"); return 0; } pkey_id = get_legacy_pkey_id(libctx, algname, e); if (pkey_id != NID_undef) ctx = EVP_PKEY_CTX_new_id(pkey_id, e); else ctx = EVP_PKEY_CTX_new_from_name(libctx, algname, propq); if (ctx == NULL) goto err; if (do_param) { if (EVP_PKEY_paramgen_init(ctx) <= 0) goto err; } else { if (EVP_PKEY_keygen_init(ctx) <= 0) goto err; } *pctx = ctx; return 1; err: BIO_printf(bio_err, "Error initializing %s context\n", algname); ERR_print_errors(bio_err); EVP_PKEY_CTX_free(ctx); return 0; }
apps
openssl/apps/genpkey.c
openssl
#include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/kdf.h> #include <openssl/params.h> typedef enum OPTION_choice { OPT_COMMON, OPT_KDFOPT, OPT_BIN, OPT_KEYLEN, OPT_OUT, OPT_CIPHER, OPT_DIGEST, OPT_MAC, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS kdf_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] kdf_name\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"kdfopt", OPT_KDFOPT, 's', "KDF algorithm control parameters in n:v form"}, {"cipher", OPT_CIPHER, 's', "Cipher"}, {"digest", OPT_DIGEST, 's', "Digest"}, {"mac", OPT_MAC, 's', "MAC"}, {OPT_MORE_STR, 1, '-', "See 'Supported Controls' in the EVP_KDF_ docs\n"}, {"keylen", OPT_KEYLEN, 's', "The size of the output derived key"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output to filename rather than stdout"}, {"binary", OPT_BIN, '-', "Output in binary format (default is hexadecimal)"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"kdf_name", 0, 0, "Name of the KDF algorithm"}, {NULL} }; static char *alloc_kdf_algorithm_name(STACK_OF(OPENSSL_STRING) **optp, const char *name, const char *arg) { size_t len = strlen(name) + strlen(arg) + 2; char *res; if (*optp == NULL) *optp = sk_OPENSSL_STRING_new_null(); if (*optp == NULL) return NULL; res = app_malloc(len, "algorithm name"); BIO_snprintf(res, len, "%s:%s", name, arg); if (sk_OPENSSL_STRING_push(*optp, res)) return res; OPENSSL_free(res); return NULL; } int kdf_main(int argc, char **argv) { int ret = 1, out_bin = 0; OPTION_CHOICE o; STACK_OF(OPENSSL_STRING) *opts = NULL; char *prog, *hexout = NULL; const char *outfile = NULL; unsigned char *dkm_bytes = NULL; size_t dkm_len = 0; BIO *out = NULL; EVP_KDF *kdf = NULL; EVP_KDF_CTX *ctx = NULL; char *digest = NULL, *cipher = NULL, *mac = NULL; prog = opt_init(argc, argv, kdf_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { default: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto err; case OPT_HELP: opt_help(kdf_options); ret = 0; goto err; case OPT_BIN: out_bin = 1; break; case OPT_KEYLEN: dkm_len = (size_t)atoi(opt_arg()); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_KDFOPT: if (opts == NULL) opts = sk_OPENSSL_STRING_new_null(); if (opts == NULL || !sk_OPENSSL_STRING_push(opts, opt_arg())) goto opthelp; break; case OPT_CIPHER: OPENSSL_free(cipher); cipher = alloc_kdf_algorithm_name(&opts, "cipher", opt_arg()); if (cipher == NULL) goto opthelp; break; case OPT_DIGEST: OPENSSL_free(digest); digest = alloc_kdf_algorithm_name(&opts, "digest", opt_arg()); if (digest == NULL) goto opthelp; break; case OPT_MAC: OPENSSL_free(mac); mac = alloc_kdf_algorithm_name(&opts, "mac", opt_arg()); if (mac == NULL) goto opthelp; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto err; break; } } argc = opt_num_rest(); argv = opt_rest(); if (argc != 1) goto opthelp; if ((kdf = EVP_KDF_fetch(app_get0_libctx(), argv[0], app_get0_propq())) == NULL) { BIO_printf(bio_err, "Invalid KDF name %s\n", argv[0]); goto opthelp; } ctx = EVP_KDF_CTX_new(kdf); if (ctx == NULL) goto err; if (opts != NULL) { int ok = 1; OSSL_PARAM *params = app_params_new_from_opts(opts, EVP_KDF_settable_ctx_params(kdf)); if (params == NULL) goto err; if (!EVP_KDF_CTX_set_params(ctx, params)) { BIO_printf(bio_err, "KDF parameter error\n"); ERR_print_errors(bio_err); ok = 0; } app_params_free(params); if (!ok) goto err; } out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT); if (out == NULL) goto err; if (dkm_len <= 0) { BIO_printf(bio_err, "Invalid derived key length.\n"); goto err; } dkm_bytes = app_malloc(dkm_len, "out buffer"); if (dkm_bytes == NULL) goto err; if (!EVP_KDF_derive(ctx, dkm_bytes, dkm_len, NULL)) { BIO_printf(bio_err, "EVP_KDF_derive failed\n"); goto err; } if (out_bin) { BIO_write(out, dkm_bytes, dkm_len); } else { hexout = OPENSSL_buf2hexstr(dkm_bytes, dkm_len); if (hexout == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto err; } BIO_printf(out, "%s\n\n", hexout); } ret = 0; err: if (ret != 0) ERR_print_errors(bio_err); OPENSSL_clear_free(dkm_bytes, dkm_len); sk_OPENSSL_STRING_free(opts); EVP_KDF_free(kdf); EVP_KDF_CTX_free(ctx); BIO_free(out); OPENSSL_free(hexout); OPENSSL_free(cipher); OPENSSL_free(digest); OPENSSL_free(mac); return ret; }
apps
openssl/apps/kdf.c
openssl
#define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/conf.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/txt_db.h> #include <openssl/buffer.h> #include <openssl/srp.h> #include "apps.h" #include "progs.h" #define BASE_SECTION "srp" #define CONFIG_FILE "openssl.cnf" #define ENV_DATABASE "srpvfile" #define ENV_DEFAULT_SRP "default_srp" static int get_index(CA_DB *db, char *id, char type) { char **pp; int i; if (id == NULL) return -1; if (type == DB_SRP_INDEX) { 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 && strcmp(id, pp[DB_srpid]) == 0) return i; } } else { 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 && strcmp(id, pp[DB_srpid]) == 0) return i; } } return -1; } static void print_entry(CA_DB *db, int indx, int verbose, char *s) { if (indx >= 0 && verbose) { int j; char **pp = sk_OPENSSL_PSTRING_value(db->db->data, indx); BIO_printf(bio_err, "%s \"%s\"\n", s, pp[DB_srpid]); for (j = 0; j < DB_NUMBER; j++) { BIO_printf(bio_err, " %d = \"%s\"\n", j, pp[j]); } } } static void print_index(CA_DB *db, int indexindex, int verbose) { print_entry(db, indexindex, verbose, "g N entry"); } static void print_user(CA_DB *db, int userindex, int verbose) { if (verbose > 0) { char **pp = sk_OPENSSL_PSTRING_value(db->db->data, userindex); if (pp[DB_srptype][0] != 'I') { print_entry(db, userindex, verbose, "User entry"); print_entry(db, get_index(db, pp[DB_srpgN], 'I'), verbose, "g N entry"); } } } static int update_index(CA_DB *db, char **row) { char **irow; int i; irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row pointers"); for (i = 0; i < DB_NUMBER; i++) irow[i] = row[i]; irow[DB_NUMBER] = NULL; if (!TXT_DB_insert(db->db, irow)) { BIO_printf(bio_err, "failed to update srpvfile\n"); BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error); OPENSSL_free(irow); return 0; } return 1; } static char *lookup_conf(const CONF *conf, const char *section, const char *tag) { char *entry = NCONF_get_string(conf, section, tag); if (entry == NULL) BIO_printf(bio_err, "variable lookup failed for %s::%s\n", section, tag); return entry; } static char *srp_verify_user(const char *user, const char *srp_verifier, char *srp_usersalt, const char *g, const char *N, const char *passin, int verbose) { char password[1025]; PW_CB_DATA cb_tmp; char *verifier = NULL; char *gNid = NULL; int len; cb_tmp.prompt_info = user; cb_tmp.password = passin; len = password_callback(password, sizeof(password)-1, 0, &cb_tmp); if (len > 0) { password[len] = 0; if (verbose) BIO_printf(bio_err, "Validating\n user=\"%s\"\n srp_verifier=\"%s\"\n srp_usersalt=\"%s\"\n g=\"%s\"\n N=\"%s\"\n", user, srp_verifier, srp_usersalt, g, N); if (verbose > 1) BIO_printf(bio_err, "Pass %s\n", password); OPENSSL_assert(srp_usersalt != NULL); if ((gNid = SRP_create_verifier(user, password, &srp_usersalt, &verifier, N, g)) == NULL) { BIO_printf(bio_err, "Internal error validating SRP verifier\n"); } else { if (strcmp(verifier, srp_verifier)) gNid = NULL; OPENSSL_free(verifier); } OPENSSL_cleanse(password, len); } return gNid; } static char *srp_create_user(char *user, char **srp_verifier, char **srp_usersalt, char *g, char *N, char *passout, int verbose) { char password[1025]; PW_CB_DATA cb_tmp; char *gNid = NULL; char *salt = NULL; int len; cb_tmp.prompt_info = user; cb_tmp.password = passout; len = password_callback(password, sizeof(password)-1, 1, &cb_tmp); if (len > 0) { password[len] = 0; if (verbose) BIO_printf(bio_err, "Creating\n user=\"%s\"\n g=\"%s\"\n N=\"%s\"\n", user, g, N); if ((gNid = SRP_create_verifier(user, password, &salt, srp_verifier, N, g)) == NULL) { BIO_printf(bio_err, "Internal error creating SRP verifier\n"); } else { *srp_usersalt = salt; } OPENSSL_cleanse(password, len); if (verbose > 1) BIO_printf(bio_err, "gNid=%s salt =\"%s\"\n verifier =\"%s\"\n", gNid, salt, *srp_verifier); } return gNid; } typedef enum OPTION_choice { OPT_COMMON, OPT_VERBOSE, OPT_CONFIG, OPT_NAME, OPT_SRPVFILE, OPT_ADD, OPT_DELETE, OPT_MODIFY, OPT_LIST, OPT_GN, OPT_USERINFO, OPT_PASSIN, OPT_PASSOUT, OPT_ENGINE, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS srp_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [user...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"verbose", OPT_VERBOSE, '-', "Talk a lot while doing things"}, {"config", OPT_CONFIG, '<', "A config file"}, {"name", OPT_NAME, 's', "The particular srp definition to use"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Action"), {"add", OPT_ADD, '-', "Add a user and SRP verifier"}, {"modify", OPT_MODIFY, '-', "Modify the SRP verifier of an existing user"}, {"delete", OPT_DELETE, '-', "Delete user from verifier file"}, {"list", OPT_LIST, '-', "List users"}, OPT_SECTION("Configuration"), {"srpvfile", OPT_SRPVFILE, '<', "The srp verifier file name"}, {"gn", OPT_GN, 's', "Set g and N values to be used for new verifier"}, {"userinfo", OPT_USERINFO, 's', "Additional info to be set for user"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"user", 0, 0, "Username(s) to process (optional)"}, {NULL} }; 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 *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; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } argc = opt_num_rest(); argv = opt_rest(); if (!app_RAND_load()) goto end; if (srpvfile != NULL && configfile != NULL) { 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) { if (argc == 0) { BIO_printf(bio_err, "Need at least one user.\n"); goto opthelp; } user = *argv++; } if ((passinarg != NULL || passoutarg != NULL) && 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 == NULL) { if (configfile == NULL) configfile = default_config_file; conf = app_load_config_verbose(configfile, verbose); if (conf == NULL) goto end; if (configfile != default_config_file && !app_load_modules(conf)) goto end; 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; } app_RAND_load_conf(conf, BASE_SECTION); 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 (verbose) BIO_printf(bio_err, "Trying to read SRP verifier file \"%s\"\n", srpvfile); db = load_index(srpvfile, NULL); if (db == NULL) { BIO_printf(bio_err, "Problem with index file: %s (could not load/parse file)\n", srpvfile); goto end; } 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"); while (mode == OPT_LIST || user != NULL) { 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) { 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; } } user = *argv++; if (user == NULL) { break; } } if (verbose) BIO_printf(bio_err, "User procession done.\n"); if (doupdatedb) { 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); NCONF_free(conf); free_index(db); release_engine(e); return ret; }
apps
openssl/apps/srp.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/asn1t.h> typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_IN, OPT_OUT, OPT_INDENT, OPT_NOOUT, OPT_OID, OPT_OFFSET, OPT_LENGTH, OPT_DUMP, OPT_DLIMIT, OPT_STRPARSE, OPT_GENSTR, OPT_GENCONF, OPT_STRICTPEM, OPT_ITEM } OPTION_CHOICE; const OPTIONS asn1parse_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"oid", OPT_OID, '<', "file of extra oid definitions"}, OPT_SECTION("I/O"), {"inform", OPT_INFORM, 'A', "input format - one of DER PEM B64"}, {"in", OPT_IN, '<', "input file"}, {"out", OPT_OUT, '>', "output file (output format is always DER)"}, {"noout", OPT_NOOUT, 0, "do not produce any output"}, {"offset", OPT_OFFSET, 'p', "offset into file"}, {"length", OPT_LENGTH, 'p', "length of section in file"}, {"strparse", OPT_STRPARSE, 'p', "offset; a series of these can be used to 'dig'"}, {"genstr", OPT_GENSTR, 's', "string to generate ASN1 structure from"}, {OPT_MORE_STR, 0, 0, "into multiple ASN1 blob wrappings"}, {"genconf", OPT_GENCONF, 's', "file to generate ASN1 structure from"}, {"strictpem", OPT_STRICTPEM, 0, "equivalent to '-inform pem' (obsolete)"}, {"item", OPT_ITEM, 's', "item to parse and print"}, {OPT_MORE_STR, 0, 0, "(-inform will be ignored)"}, OPT_SECTION("Formatting"), {"i", OPT_INDENT, 0, "indents the output"}, {"dump", OPT_DUMP, 0, "unknown data in hex form"}, {"dlimit", OPT_DLIMIT, 'p', "dump the first arg bytes of unknown data in hex form"}, {NULL} }; static int do_generate(char *genstr, const char *genconf, BUF_MEM *buf); int asn1parse_main(int argc, char **argv) { ASN1_TYPE *at = NULL; BIO *in = NULL, *b64 = NULL, *derout = NULL; BUF_MEM *buf = NULL; STACK_OF(OPENSSL_STRING) *osk = NULL; char *genstr = NULL, *genconf = NULL; char *infile = NULL, *oidfile = NULL, *derfile = NULL; unsigned char *str = NULL; char *name = NULL, *header = NULL, *prog; const unsigned char *ctmpbuf; int indent = 0, noout = 0, dump = 0, informat = FORMAT_PEM; int offset = 0, ret = 1, i, j; long num, tmplen; unsigned char *tmpbuf; unsigned int length = 0; OPTION_CHOICE o; const ASN1_ITEM *it = NULL; prog = opt_init(argc, argv, asn1parse_options); if ((osk = sk_OPENSSL_STRING_new_null()) == NULL) { BIO_printf(bio_err, "%s: Memory allocation failure\n", prog); goto end; } 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(asn1parse_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_ASN1, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: derfile = opt_arg(); break; case OPT_INDENT: indent = 1; break; case OPT_NOOUT: noout = 1; break; case OPT_OID: oidfile = opt_arg(); break; case OPT_OFFSET: offset = strtol(opt_arg(), NULL, 0); break; case OPT_LENGTH: length = strtol(opt_arg(), NULL, 0); break; case OPT_DUMP: dump = -1; break; case OPT_DLIMIT: dump = strtol(opt_arg(), NULL, 0); break; case OPT_STRPARSE: sk_OPENSSL_STRING_push(osk, opt_arg()); break; case OPT_GENSTR: genstr = opt_arg(); break; case OPT_GENCONF: genconf = opt_arg(); break; case OPT_STRICTPEM: informat = FORMAT_PEM; break; case OPT_ITEM: it = ASN1_ITEM_lookup(opt_arg()); if (it == NULL) { size_t tmp; BIO_printf(bio_err, "Unknown item name %s\n", opt_arg()); BIO_puts(bio_err, "Supported types:\n"); for (tmp = 0;; tmp++) { it = ASN1_ITEM_get(tmp); if (it == NULL) break; BIO_printf(bio_err, " %s\n", it->sname); } goto end; } break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (oidfile != NULL) { in = bio_open_default(oidfile, 'r', FORMAT_TEXT); if (in == NULL) goto end; OBJ_create_objects(in); BIO_free(in); } if ((in = bio_open_default(infile, 'r', informat)) == NULL) goto end; if (derfile && (derout = bio_open_default(derfile, 'w', FORMAT_ASN1)) == NULL) goto end; if ((buf = BUF_MEM_new()) == NULL) goto end; if (genconf == NULL && genstr == NULL && informat == FORMAT_PEM) { if (PEM_read_bio(in, &name, &header, &str, &num) != 1) { BIO_printf(bio_err, "Error reading PEM file\n"); ERR_print_errors(bio_err); goto end; } buf->data = (char *)str; buf->length = buf->max = num; } else { if (!BUF_MEM_grow(buf, BUFSIZ * 8)) goto end; if (genstr || genconf) { num = do_generate(genstr, genconf, buf); if (num < 0) { ERR_print_errors(bio_err); goto end; } } else { if (informat == FORMAT_BASE64) { 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, num + BUFSIZ)) goto end; i = BIO_read(in, &(buf->data[num]), BUFSIZ); if (i <= 0) break; num += i; } } str = (unsigned char *)buf->data; } if (sk_OPENSSL_STRING_num(osk)) { tmpbuf = str; tmplen = num; for (i = 0; i < sk_OPENSSL_STRING_num(osk); i++) { ASN1_TYPE *atmp; int typ; j = strtol(sk_OPENSSL_STRING_value(osk, i), NULL, 0); if (j <= 0 || j >= tmplen) { BIO_printf(bio_err, "'%s' is out of range\n", sk_OPENSSL_STRING_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_BOOLEAN) || (typ == V_ASN1_NULL)) { BIO_printf(bio_err, "Can't parse %s type\n", ASN1_tag2str(typ)); ERR_print_errors(bio_err); goto end; } tmpbuf = at->value.asn1_string->data; tmplen = at->value.asn1_string->length; } str = tmpbuf; num = tmplen; } if (offset < 0 || offset >= num) { BIO_printf(bio_err, "Error: offset out of range\n"); goto end; } num -= offset; if (length == 0 || length > (unsigned int)num) length = (unsigned int)num; if (derout != NULL) { 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) { const unsigned char *p = str + offset; if (it != NULL) { ASN1_VALUE *value = ASN1_item_d2i(NULL, &p, length, it); if (value == NULL) { BIO_printf(bio_err, "Error parsing item %s\n", it->sname); ERR_print_errors(bio_err); goto end; } ASN1_item_print(bio_out, value, 0, it, NULL); ASN1_item_free(value, it); } else { if (!ASN1_parse_dump(bio_out, p, length, indent, dump)) { ERR_print_errors(bio_err); goto end; } } } ret = 0; end: BIO_free(derout); BIO_free(in); BIO_free(b64); if (ret != 0) ERR_print_errors(bio_err); BUF_MEM_free(buf); OPENSSL_free(name); OPENSSL_free(header); ASN1_TYPE_free(at); sk_OPENSSL_STRING_free(osk); return ret; } static int do_generate(char *genstr, const char *genconf, BUF_MEM *buf) { CONF *cnf = NULL; int len; unsigned char *p; ASN1_TYPE *atyp = NULL; if (genconf != NULL) { if ((cnf = app_load_config(genconf)) == NULL) goto err; if (genstr == NULL) genstr = NCONF_get_string(cnf, "default", "asn1"); if (genstr == NULL) { BIO_printf(bio_err, "Can't find 'asn1' in '%s'\n", genconf); goto err; } } atyp = ASN1_generate_nconf(genstr, cnf); NCONF_free(cnf); cnf = NULL; if (atyp == NULL) return -1; len = i2d_ASN1_TYPE(atyp, NULL); if (len <= 0) goto err; if (!BUF_MEM_grow(buf, len)) goto err; p = (unsigned char *)buf->data; i2d_ASN1_TYPE(atyp, &p); ASN1_TYPE_free(atyp); return len; err: NCONF_free(cnf); ASN1_TYPE_free(atyp); return -1; }
apps
openssl/apps/asn1parse.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/ssl.h> #include "s_apps.h" typedef enum OPTION_choice { OPT_COMMON, OPT_STDNAME, OPT_CONVERT, OPT_SSL3, OPT_TLS1, OPT_TLS1_1, OPT_TLS1_2, OPT_TLS1_3, OPT_PSK, OPT_SRP, OPT_CIPHERSUITES, OPT_V, OPT_UPPER_V, OPT_S, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS ciphers_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cipher]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Output"), {"v", OPT_V, '-', "Verbose listing of the SSL/TLS ciphers"}, {"V", OPT_UPPER_V, '-', "Even more verbose"}, {"stdname", OPT_STDNAME, '-', "Show standard cipher names"}, {"convert", OPT_CONVERT, 's', "Convert standard name into OpenSSL name"}, OPT_SECTION("Cipher specification"), {"s", OPT_S, '-', "Only supported ciphers"}, #ifndef OPENSSL_NO_SSL3 {"ssl3", OPT_SSL3, '-', "Ciphers compatible with SSL3"}, #endif #ifndef OPENSSL_NO_TLS1 {"tls1", OPT_TLS1, '-', "Ciphers compatible with TLS1"}, #endif #ifndef OPENSSL_NO_TLS1_1 {"tls1_1", OPT_TLS1_1, '-', "Ciphers compatible with TLS1.1"}, #endif #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "Ciphers compatible with TLS1.2"}, #endif #ifndef OPENSSL_NO_TLS1_3 {"tls1_3", OPT_TLS1_3, '-', "Ciphers compatible with TLS1.3"}, #endif #ifndef OPENSSL_NO_PSK {"psk", OPT_PSK, '-', "Include ciphersuites requiring PSK"}, #endif #ifndef OPENSSL_NO_SRP {"srp", OPT_SRP, '-', "(deprecated) Include ciphersuites requiring SRP"}, #endif {"ciphersuites", OPT_CIPHERSUITES, 's', "Configure the TLSv1.3 ciphersuites to use"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"cipher", 0, 0, "Cipher string to decode (optional)"}, {NULL} }; #ifndef OPENSSL_NO_PSK static unsigned int dummy_psk(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len) { return 0; } #endif int ciphers_main(int argc, char **argv) { SSL_CTX *ctx = NULL; SSL *ssl = NULL; STACK_OF(SSL_CIPHER) *sk = NULL; const SSL_METHOD *meth = TLS_server_method(); int ret = 1, i, verbose = 0, Verbose = 0, use_supported = 0; int stdname = 0; #ifndef OPENSSL_NO_PSK int psk = 0; #endif #ifndef OPENSSL_NO_SRP int srp = 0; #endif const char *p; char *ciphers = NULL, *prog, *convert = NULL, *ciphersuites = NULL; char buf[512]; OPTION_CHOICE o; int min_version = 0, max_version = 0; prog = opt_init(argc, argv, ciphers_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(ciphers_options); ret = 0; goto end; case OPT_V: verbose = 1; break; case OPT_UPPER_V: verbose = Verbose = 1; break; case OPT_S: use_supported = 1; break; case OPT_STDNAME: stdname = verbose = 1; break; case OPT_CONVERT: convert = opt_arg(); break; case OPT_SSL3: min_version = SSL3_VERSION; max_version = SSL3_VERSION; break; case OPT_TLS1: min_version = TLS1_VERSION; max_version = TLS1_VERSION; break; case OPT_TLS1_1: min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; break; case OPT_TLS1_2: min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; break; case OPT_TLS1_3: min_version = TLS1_3_VERSION; max_version = TLS1_3_VERSION; break; case OPT_PSK: #ifndef OPENSSL_NO_PSK psk = 1; #endif break; case OPT_SRP: #ifndef OPENSSL_NO_SRP srp = 1; #endif break; case OPT_CIPHERSUITES: ciphersuites = opt_arg(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } argv = opt_rest(); if (opt_num_rest() == 1) ciphers = argv[0]; else if (!opt_check_rest_arg(NULL)) goto opthelp; if (convert != NULL) { BIO_printf(bio_out, "OpenSSL cipher name: %s\n", OPENSSL_cipher_name(convert)); ret = 0; goto end; } ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth); if (ctx == NULL) goto err; if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0) goto err; if (SSL_CTX_set_max_proto_version(ctx, max_version) == 0) goto err; #ifndef OPENSSL_NO_PSK if (psk) SSL_CTX_set_psk_client_callback(ctx, dummy_psk); #endif #ifndef OPENSSL_NO_SRP if (srp) set_up_dummy_srp(ctx); #endif if (ciphersuites != NULL && !SSL_CTX_set_ciphersuites(ctx, ciphersuites)) { BIO_printf(bio_err, "Error setting TLSv1.3 ciphersuites\n"); goto err; } if (ciphers != NULL) { if (!SSL_CTX_set_cipher_list(ctx, ciphers)) { BIO_printf(bio_err, "Error in cipher list\n"); goto err; } } ssl = SSL_new(ctx); if (ssl == NULL) goto err; if (use_supported) sk = SSL_get1_supported_ciphers(ssl); else sk = SSL_get_ciphers(ssl); if (!verbose) { for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) { const SSL_CIPHER *c = sk_SSL_CIPHER_value(sk, i); if (!ossl_assert(c != NULL)) continue; p = SSL_CIPHER_get_name(c); if (p == NULL) break; if (i != 0) BIO_printf(bio_out, ":"); BIO_printf(bio_out, "%s", p); } BIO_printf(bio_out, "\n"); } else { for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) { const SSL_CIPHER *c; c = sk_SSL_CIPHER_value(sk, i); if (!ossl_assert(c != NULL)) continue; if (Verbose) { unsigned long id = SSL_CIPHER_get_id(c); int id0 = (int)(id >> 24); int id1 = (int)((id >> 16) & 0xffL); int id2 = (int)((id >> 8) & 0xffL); int id3 = (int)(id & 0xffL); if ((id & 0xff000000L) == 0x03000000L) BIO_printf(bio_out, " 0x%02X,0x%02X - ", id2, id3); else BIO_printf(bio_out, "0x%02X,0x%02X,0x%02X,0x%02X - ", id0, id1, id2, id3); } if (stdname) { const char *nm = SSL_CIPHER_standard_name(c); if (nm == NULL) nm = "UNKNOWN"; BIO_printf(bio_out, "%-45s - ", nm); } BIO_puts(bio_out, SSL_CIPHER_description(c, buf, sizeof(buf))); } } ret = 0; goto end; err: ERR_print_errors(bio_err); end: if (use_supported) sk_SSL_CIPHER_free(sk); SSL_CTX_free(ctx); SSL_free(ssl); return ret; }
apps
openssl/apps/ciphers.c
openssl
#include <string.h> #include <openssl/opensslconf.h> #include <openssl/evp.h> #include <openssl/encoder.h> #include <openssl/decoder.h> #include <openssl/core_names.h> #include <openssl/core_dispatch.h> #include <openssl/params.h> #include <openssl/err.h> #include "apps.h" #include "progs.h" #include "ec_common.h" typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT, OPT_CHECK, OPT_LIST_CURVES, OPT_NO_SEED, OPT_NOOUT, OPT_NAME, OPT_CONV_FORM, OPT_PARAM_ENC, OPT_GENKEY, OPT_ENGINE, OPT_CHECK_NAMED, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS ecparam_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"list_curves", OPT_LIST_CURVES, '-', "Prints a list of all curve 'short names'"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"genkey", OPT_GENKEY, '-', "Generate ec key"}, {"in", OPT_IN, '<', "Input file - default stdin"}, {"inform", OPT_INFORM, 'F', "Input format - default PEM (DER or PEM)"}, {"out", OPT_OUT, '>', "Output file - default stdout"}, {"outform", OPT_OUTFORM, 'F', "Output format - default PEM"}, OPT_SECTION("Output"), {"text", OPT_TEXT, '-', "Print the ec parameters in text form"}, {"noout", OPT_NOOUT, '-', "Do not print the ec parameter"}, {"param_enc", OPT_PARAM_ENC, 's', "Specifies the way the ec parameters are encoded"}, OPT_SECTION("Parameter"), {"check", OPT_CHECK, '-', "Validate the ec parameters"}, {"check_named", OPT_CHECK_NAMED, '-', "Check that named EC curve parameters have not been modified"}, {"no_seed", OPT_NO_SEED, '-', "If 'explicit' parameters are chosen do not use the seed"}, {"name", OPT_NAME, 's', "Use the ec parameters with specified 'short name'"}, {"conv_form", OPT_CONV_FORM, 's', "Specifies the point conversion form "}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; static int list_builtin_curves(BIO *out) { int ret = 0; EC_builtin_curve *curves = NULL; size_t n, crv_len = EC_get_builtin_curves(NULL, 0); curves = app_malloc((int)sizeof(*curves) * crv_len, "list curves"); if (!EC_get_builtin_curves(curves, crv_len)) goto end; for (n = 0; n < crv_len; n++) { const char *comment = curves[n].comment; const char *sname = OBJ_nid2sn(curves[n].nid); if (comment == NULL) comment = "CURVE DESCRIPTION NOT AVAILABLE"; if (sname == NULL) sname = ""; BIO_printf(out, " %-10s: ", sname); BIO_printf(out, "%s\n", comment); } ret = 1; end: OPENSSL_free(curves); return ret; } int ecparam_main(int argc, char **argv) { EVP_PKEY_CTX *gctx_params = NULL, *gctx_key = NULL, *pctx = NULL; EVP_PKEY *params_key = NULL, *key = NULL; OSSL_ENCODER_CTX *ectx_key = NULL, *ectx_params = NULL; OSSL_DECODER_CTX *dctx_params = NULL; ENGINE *e = NULL; BIO *out = NULL; char *curve_name = NULL; char *asn1_encoding = NULL; char *point_format = NULL; char *infile = NULL, *outfile = NULL, *prog; OPTION_CHOICE o; int informat = FORMAT_PEM, outformat = FORMAT_PEM, noout = 0; int ret = 1, private = 0; int no_seed = 0, check = 0, check_named = 0, text = 0, genkey = 0; int list_curves = 0; prog = opt_init(argc, argv, ecparam_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(ecparam_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_TEXT: text = 1; break; case OPT_CHECK: check = 1; break; case OPT_CHECK_NAMED: check_named = 1; break; case OPT_LIST_CURVES: list_curves = 1; break; case OPT_NO_SEED: no_seed = 1; break; case OPT_NOOUT: noout = 1; break; case OPT_NAME: curve_name = opt_arg(); break; case OPT_CONV_FORM: point_format = opt_arg(); if (!opt_string(point_format, point_format_options)) goto opthelp; break; case OPT_PARAM_ENC: asn1_encoding = opt_arg(); if (!opt_string(asn1_encoding, asn1_encoding_options)) goto opthelp; break; case OPT_GENKEY: genkey = 1; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; private = genkey ? 1 : 0; out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (list_curves) { if (list_builtin_curves(out)) ret = 0; goto end; } if (curve_name != NULL) { OSSL_PARAM params[4]; OSSL_PARAM *p = params; if (strcmp(curve_name, "secp192r1") == 0) { BIO_printf(bio_err, "using curve name prime192v1 instead of secp192r1\n"); curve_name = SN_X9_62_prime192v1; } else if (strcmp(curve_name, "secp256r1") == 0) { BIO_printf(bio_err, "using curve name prime256v1 instead of secp256r1\n"); curve_name = SN_X9_62_prime256v1; } *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, curve_name, 0); if (asn1_encoding != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_EC_ENCODING, asn1_encoding, 0); if (point_format != NULL) *p++ = OSSL_PARAM_construct_utf8_string( OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, point_format, 0); *p = OSSL_PARAM_construct_end(); if (OPENSSL_strcasecmp(curve_name, "SM2") == 0) gctx_params = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), "sm2", app_get0_propq()); else gctx_params = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), "ec", app_get0_propq()); if (gctx_params == NULL || EVP_PKEY_keygen_init(gctx_params) <= 0 || EVP_PKEY_CTX_set_params(gctx_params, params) <= 0 || EVP_PKEY_keygen(gctx_params, &params_key) <= 0) { BIO_printf(bio_err, "unable to generate key\n"); goto end; } } else { params_key = load_keyparams_suppress(infile, informat, 1, "EC", "EC parameters", 1); if (params_key == NULL) params_key = load_keyparams_suppress(infile, informat, 1, "SM2", "SM2 parameters", 1); if (params_key == NULL) { BIO_printf(bio_err, "Unable to load parameters from %s\n", infile); goto end; } if (point_format && !EVP_PKEY_set_utf8_string_param( params_key, OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, point_format)) { BIO_printf(bio_err, "unable to set point conversion format\n"); goto end; } if (asn1_encoding != NULL && !EVP_PKEY_set_utf8_string_param( params_key, OSSL_PKEY_PARAM_EC_ENCODING, asn1_encoding)) { BIO_printf(bio_err, "unable to set asn1 encoding format\n"); goto end; } } if (no_seed && !EVP_PKEY_set_octet_string_param(params_key, OSSL_PKEY_PARAM_EC_SEED, NULL, 0)) { BIO_printf(bio_err, "unable to clear seed\n"); goto end; } if (text && !EVP_PKEY_print_params(out, params_key, 0, NULL)) { BIO_printf(bio_err, "unable to print params\n"); goto end; } if (check || check_named) { BIO_printf(bio_err, "checking elliptic curve parameters: "); if (check_named && !EVP_PKEY_set_utf8_string_param(params_key, OSSL_PKEY_PARAM_EC_GROUP_CHECK_TYPE, OSSL_PKEY_EC_GROUP_CHECK_NAMED)) { BIO_printf(bio_err, "unable to set check_type\n"); goto end; } pctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), params_key, app_get0_propq()); if (pctx == NULL || EVP_PKEY_param_check(pctx) <= 0) { BIO_printf(bio_err, "failed\n"); goto end; } BIO_printf(bio_err, "ok\n"); } if (outformat == FORMAT_ASN1 && genkey) noout = 1; if (!noout) { ectx_params = OSSL_ENCODER_CTX_new_for_pkey( params_key, OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS, outformat == FORMAT_ASN1 ? "DER" : "PEM", NULL, NULL); if (!OSSL_ENCODER_to_bio(ectx_params, out)) { BIO_printf(bio_err, "unable to write elliptic curve parameters\n"); goto end; } } if (genkey) { gctx_key = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), params_key, app_get0_propq()); if (EVP_PKEY_keygen_init(gctx_key) <= 0 || EVP_PKEY_keygen(gctx_key, &key) <= 0) { BIO_printf(bio_err, "unable to generate key\n"); goto end; } assert(private); ectx_key = OSSL_ENCODER_CTX_new_for_pkey( key, OSSL_KEYMGMT_SELECT_ALL, outformat == FORMAT_ASN1 ? "DER" : "PEM", NULL, NULL); if (!OSSL_ENCODER_to_bio(ectx_key, out)) { BIO_printf(bio_err, "unable to write elliptic " "curve parameters\n"); goto end; } } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); release_engine(e); EVP_PKEY_free(params_key); EVP_PKEY_free(key); EVP_PKEY_CTX_free(pctx); EVP_PKEY_CTX_free(gctx_params); EVP_PKEY_CTX_free(gctx_key); OSSL_DECODER_CTX_free(dctx_params); OSSL_ENCODER_CTX_free(ectx_params); OSSL_ENCODER_CTX_free(ectx_key); BIO_free_all(out); return ret; }
apps
openssl/apps/ecparam.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/pkcs12.h> #define STR(a) XSTR(a) #define XSTR(a) #a typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_IN, OPT_OUT, OPT_TOPK8, OPT_NOITER, OPT_NOCRYPT, #ifndef OPENSSL_NO_SCRYPT OPT_SCRYPT, OPT_SCRYPT_N, OPT_SCRYPT_R, OPT_SCRYPT_P, #endif OPT_V2, OPT_V1, OPT_V2PRF, OPT_ITER, OPT_PASSIN, OPT_PASSOUT, OPT_TRADITIONAL, OPT_SALTLEN, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS pkcs8_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"v1", OPT_V1, 's', "Use PKCS#5 v1.5 and cipher"}, {"v2", OPT_V2, 's', "Use PKCS#5 v2.0 and cipher"}, {"v2prf", OPT_V2PRF, 's', "Set the PRF algorithm to use with PKCS#5 v2.0"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"inform", OPT_INFORM, 'F', "Input format (DER or PEM)"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"nocrypt", OPT_NOCRYPT, '-', "Use or expect unencrypted private key"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format (DER or PEM)"}, {"topk8", OPT_TOPK8, '-', "Output PKCS8 file"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"traditional", OPT_TRADITIONAL, '-', "use traditional format private key"}, {"iter", OPT_ITER, 'p', "Specify the iteration count"}, {"noiter", OPT_NOITER, '-', "Use 1 as iteration count"}, {"saltlen", OPT_SALTLEN, 'p', "Specify the salt length (in bytes)"}, {OPT_MORE_STR, 0, 0, "Default: 8 (For PBE1) or 16 (for PBE2)"}, #ifndef OPENSSL_NO_SCRYPT OPT_SECTION("Scrypt"), {"scrypt", OPT_SCRYPT, '-', "Use scrypt algorithm"}, {"scrypt_N", OPT_SCRYPT_N, 's', "Set scrypt N parameter"}, {"scrypt_r", OPT_SCRYPT_R, 's', "Set scrypt r parameter"}, {"scrypt_p", OPT_SCRYPT_P, 's', "Set scrypt p parameter"}, #endif OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; int pkcs8_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; ENGINE *e = NULL; EVP_PKEY *pkey = NULL; PKCS8_PRIV_KEY_INFO *p8inf = NULL; X509_SIG *p8 = NULL; EVP_CIPHER *cipher = NULL; char *infile = NULL, *outfile = NULL, *ciphername = NULL; char *passinarg = NULL, *passoutarg = NULL, *prog; #ifndef OPENSSL_NO_UI_CONSOLE char pass[APP_PASS_LEN]; #endif char *passin = NULL, *passout = NULL, *p8pass = NULL; OPTION_CHOICE o; int nocrypt = 0, ret = 1, iter = PKCS12_DEFAULT_ITER; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, topk8 = 0, pbe_nid = -1; int private = 0, traditional = 0; #ifndef OPENSSL_NO_SCRYPT long scrypt_N = 0, scrypt_r = 0, scrypt_p = 0; #endif int saltlen = 0; prog = opt_init(argc, argv, pkcs8_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(pkcs8_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_TOPK8: topk8 = 1; break; case OPT_NOITER: iter = 1; break; case OPT_NOCRYPT: nocrypt = 1; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_TRADITIONAL: traditional = 1; break; case OPT_V2: ciphername = opt_arg(); break; case OPT_V1: pbe_nid = OBJ_txt2nid(opt_arg()); if (pbe_nid == NID_undef) { BIO_printf(bio_err, "%s: Unknown PBE algorithm %s\n", prog, opt_arg()); goto opthelp; } break; case OPT_V2PRF: pbe_nid = OBJ_txt2nid(opt_arg()); if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, pbe_nid, NULL, NULL, 0)) { BIO_printf(bio_err, "%s: Unknown PRF algorithm %s\n", prog, opt_arg()); goto opthelp; } if (cipher == NULL) cipher = (EVP_CIPHER *)EVP_aes_256_cbc(); break; case OPT_ITER: iter = opt_int_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; #ifndef OPENSSL_NO_SCRYPT case OPT_SCRYPT: scrypt_N = 16384; scrypt_r = 8; scrypt_p = 1; if (cipher == NULL) cipher = (EVP_CIPHER *)EVP_aes_256_cbc(); break; case OPT_SCRYPT_N: if (!opt_long(opt_arg(), &scrypt_N) || scrypt_N <= 0) goto opthelp; break; case OPT_SCRYPT_R: if (!opt_long(opt_arg(), &scrypt_r) || scrypt_r <= 0) goto opthelp; break; case OPT_SCRYPT_P: if (!opt_long(opt_arg(), &scrypt_p) || scrypt_p <= 0) goto opthelp; break; #endif case OPT_SALTLEN: if (!opt_int(opt_arg(), &saltlen)) goto opthelp; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; private = 1; if (!app_RAND_load()) goto end; if (ciphername != NULL) { if (!opt_cipher(ciphername, &cipher)) goto opthelp; } if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if ((pbe_nid == -1) && cipher == NULL) cipher = (EVP_CIPHER *)EVP_aes_256_cbc(); in = bio_open_default(infile, 'r', informat == FORMAT_UNDEF ? FORMAT_PEM : informat); if (in == NULL) goto end; out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (topk8) { pkey = load_key(infile, informat, 1, passin, e, "key"); if (pkey == NULL) goto end; if ((p8inf = EVP_PKEY2PKCS8(pkey)) == NULL) { BIO_printf(bio_err, "Error converting key\n"); ERR_print_errors(bio_err); goto end; } if (nocrypt) { assert(private); if (outformat == FORMAT_PEM) { PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf); } else if (outformat == FORMAT_ASN1) { i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf); } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } } else { X509_ALGOR *pbe; if (cipher) { #ifndef OPENSSL_NO_SCRYPT if (scrypt_N && scrypt_r && scrypt_p) pbe = PKCS5_pbe2_set_scrypt(cipher, NULL, saltlen, NULL, scrypt_N, scrypt_r, scrypt_p); else #endif pbe = PKCS5_pbe2_set_iv(cipher, iter, NULL, saltlen, NULL, pbe_nid); } else { pbe = PKCS5_pbe_set(pbe_nid, iter, NULL, saltlen); } if (pbe == NULL) { BIO_printf(bio_err, "Error setting PBE algorithm\n"); ERR_print_errors(bio_err); goto end; } if (passout != NULL) { p8pass = passout; } else if (1) { #ifndef OPENSSL_NO_UI_CONSOLE p8pass = pass; if (EVP_read_pw_string (pass, sizeof(pass), "Enter Encryption Password:", 1)) { X509_ALGOR_free(pbe); goto end; } } else { #endif BIO_printf(bio_err, "Password required\n"); goto end; } p8 = PKCS8_set0_pbe(p8pass, strlen(p8pass), p8inf, pbe); if (p8 == NULL) { X509_ALGOR_free(pbe); BIO_printf(bio_err, "Error encrypting key\n"); ERR_print_errors(bio_err); goto end; } assert(private); if (outformat == FORMAT_PEM) PEM_write_bio_PKCS8(out, p8); else if (outformat == FORMAT_ASN1) i2d_PKCS8_bio(out, p8); else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } } ret = 0; goto end; } if (nocrypt) { if (informat == FORMAT_PEM || informat == FORMAT_UNDEF) { p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL); } else if (informat == FORMAT_ASN1) { p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL); } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } } else { if (informat == FORMAT_PEM || informat == FORMAT_UNDEF) { p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL); } else if (informat == FORMAT_ASN1) { p8 = d2i_PKCS8_bio(in, NULL); } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } if (p8 == NULL) { BIO_printf(bio_err, "Error reading key\n"); ERR_print_errors(bio_err); goto end; } if (passin != NULL) { p8pass = passin; } else if (1) { #ifndef OPENSSL_NO_UI_CONSOLE p8pass = pass; if (EVP_read_pw_string(pass, sizeof(pass), "Enter Password:", 0)) { BIO_printf(bio_err, "Can't read Password\n"); goto end; } } else { #endif BIO_printf(bio_err, "Password required\n"); goto end; } p8inf = PKCS8_decrypt(p8, p8pass, strlen(p8pass)); } if (p8inf == NULL) { BIO_printf(bio_err, "Error decrypting key\n"); ERR_print_errors(bio_err); goto end; } if ((pkey = EVP_PKCS82PKEY(p8inf)) == NULL) { BIO_printf(bio_err, "Error converting key\n"); ERR_print_errors(bio_err); goto end; } assert(private); if (outformat == FORMAT_PEM) { if (traditional) PEM_write_bio_PrivateKey_traditional(out, pkey, NULL, NULL, 0, NULL, passout); else PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, passout); } else if (outformat == FORMAT_ASN1) { i2d_PrivateKey_bio(out, pkey); } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } ret = 0; end: X509_SIG_free(p8); PKCS8_PRIV_KEY_INFO_free(p8inf); EVP_PKEY_free(pkey); EVP_CIPHER_free(cipher); release_engine(e); BIO_free_all(out); BIO_free(in); OPENSSL_free(passin); OPENSSL_free(passout); return ret; }
apps
openssl/apps/pkcs8.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <openssl/conf.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/txt_db.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/objects.h> #include <openssl/ocsp.h> #include <openssl/pem.h> #ifndef W_OK # ifdef OPENSSL_SYS_VMS # include <unistd.h> # elif !defined(OPENSSL_SYS_VXWORKS) && !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_TANDEM) # include <sys/file.h> # endif #endif #include "apps.h" #include "progs.h" #ifndef W_OK # define F_OK 0 # define W_OK 2 # define R_OK 4 #endif #ifndef PATH_MAX # define PATH_MAX 4096 #endif #define BASE_SECTION "ca" #define ENV_DEFAULT_CA "default_ca" #define STRING_MASK "string_mask" #define UTF8_IN "utf8" #define ENV_NEW_CERTS_DIR "new_certs_dir" #define ENV_CERTIFICATE "certificate" #define ENV_SERIAL "serial" #define ENV_RAND_SERIAL "rand_serial" #define ENV_CRLNUMBER "crlnumber" #define ENV_PRIVATE_KEY "private_key" #define ENV_DEFAULT_DAYS "default_days" #define ENV_DEFAULT_STARTDATE "default_startdate" #define ENV_DEFAULT_ENDDATE "default_enddate" #define ENV_DEFAULT_CRL_DAYS "default_crl_days" #define ENV_DEFAULT_CRL_HOURS "default_crl_hours" #define ENV_DEFAULT_MD "default_md" #define ENV_DEFAULT_EMAIL_DN "email_in_dn" #define ENV_PRESERVE "preserve" #define ENV_POLICY "policy" #define ENV_EXTENSIONS "x509_extensions" #define ENV_CRLEXT "crl_extensions" #define ENV_MSIE_HACK "msie_hack" #define ENV_NAMEOPT "name_opt" #define ENV_CERTOPT "cert_opt" #define ENV_EXTCOPY "copy_extensions" #define ENV_UNIQUE_SUBJECT "unique_subject" #define ENV_DATABASE "database" typedef enum { REV_VALID = -1, REV_NONE = 0, REV_CRL_REASON = 1, REV_HOLD = 2, REV_KEY_COMPROMISE = 3, REV_CA_COMPROMISE = 4 } REVINFO_TYPE; static char *lookup_conf(const CONF *conf, const char *group, const char *tag); static int certify(X509 **xret, const char *infile, int informat, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(OPENSSL_STRING) *vfyopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, int batch, const char *ext_sect, CONF *conf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign, unsigned long dateopt); static int certify_cert(X509 **xret, const char *infile, int certformat, const char *passin, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(OPENSSL_STRING) *vfyopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, int batch, const char *ext_sect, CONF *conf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, unsigned long dateopt); static int certify_spkac(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, const char *ext_sect, CONF *conf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, unsigned long dateopt); static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, int batch, int verbose, X509_REQ *req, const char *ext_sect, CONF *conf, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign, unsigned long dateopt); static int get_certificate_status(const char *ser_status, CA_DB *db); static int check_time_format(const char *str); static int do_revoke(X509 *x509, CA_DB *db, REVINFO_TYPE rev_type, const char *extval); static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg); static int make_revoked(X509_REVOKED *rev, const char *str); static int old_entry_print(const ASN1_OBJECT *obj, const ASN1_STRING *str); static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext); static CONF *extfile_conf = NULL; static int preserve = 0; static int msie_hack = 0; typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_VERBOSE, OPT_CONFIG, OPT_NAME, OPT_SUBJ, OPT_UTF8, OPT_CREATE_SERIAL, OPT_MULTIVALUE_RDN, OPT_STARTDATE, OPT_ENDDATE, OPT_DAYS, OPT_MD, OPT_POLICY, OPT_KEYFILE, OPT_KEYFORM, OPT_PASSIN, OPT_KEY, OPT_CERT, OPT_CERTFORM, OPT_SELFSIGN, OPT_IN, OPT_INFORM, OPT_OUT, OPT_DATEOPT, OPT_OUTDIR, OPT_VFYOPT, OPT_SIGOPT, OPT_NOTEXT, OPT_BATCH, OPT_PRESERVEDN, OPT_NOEMAILDN, OPT_GENCRL, OPT_MSIE_HACK, OPT_CRL_LASTUPDATE, OPT_CRL_NEXTUPDATE, OPT_CRLDAYS, OPT_CRLHOURS, OPT_CRLSEC, OPT_INFILES, OPT_SS_CERT, OPT_SPKAC, OPT_REVOKE, OPT_VALID, OPT_EXTENSIONS, OPT_EXTFILE, OPT_STATUS, OPT_UPDATEDB, OPT_CRLEXTS, OPT_RAND_SERIAL, OPT_QUIET, OPT_R_ENUM, OPT_PROV_ENUM, OPT_CRL_REASON, OPT_CRL_HOLD, OPT_CRL_COMPROMISE, OPT_CRL_CA_COMPROMISE } OPTION_CHOICE; const OPTIONS ca_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [certreq...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"verbose", OPT_VERBOSE, '-', "Verbose output during processing"}, {"quiet", OPT_QUIET, '-', "Terse output during processing"}, {"outdir", OPT_OUTDIR, '/', "Where to put output cert"}, {"in", OPT_IN, '<', "The input cert request(s)"}, {"inform", OPT_INFORM, 'F', "CSR input format to use (PEM or DER; by default try PEM first)"}, {"infiles", OPT_INFILES, '-', "The last argument, requests to process"}, {"out", OPT_OUT, '>', "Where to put the output file(s)"}, {"dateopt", OPT_DATEOPT, 's', "Datetime format used for printing. (rfc_822/iso_8601). Default is rfc_822."}, {"notext", OPT_NOTEXT, '-', "Do not print the generated certificate"}, {"batch", OPT_BATCH, '-', "Don't ask questions"}, {"msie_hack", OPT_MSIE_HACK, '-', "msie modifications to handle all Universal Strings"}, {"ss_cert", OPT_SS_CERT, '<', "File contains a self signed cert to sign"}, {"spkac", OPT_SPKAC, '<', "File contains DN and signed public key and challenge"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Configuration"), {"config", OPT_CONFIG, 's', "A config file"}, {"name", OPT_NAME, 's', "The particular CA definition to use"}, {"section", OPT_NAME, 's', "An alias for -name"}, {"policy", OPT_POLICY, 's', "The CA 'policy' to support"}, OPT_SECTION("Certificate"), {"subj", OPT_SUBJ, 's', "Use arg instead of request's subject"}, {"utf8", OPT_UTF8, '-', "Input characters are UTF8; default ASCII"}, {"create_serial", OPT_CREATE_SERIAL, '-', "If reading serial fails, create a new random serial"}, {"rand_serial", OPT_RAND_SERIAL, '-', "Always create a random serial; do not store it"}, {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-', "Deprecated; multi-valued RDNs support is always on."}, {"startdate", OPT_STARTDATE, 's', "Cert notBefore, YYMMDDHHMMSSZ"}, {"enddate", OPT_ENDDATE, 's', "YYMMDDHHMMSSZ cert notAfter (overrides -days)"}, {"days", OPT_DAYS, 'p', "Number of days to certify the cert for"}, {"extensions", OPT_EXTENSIONS, 's', "Extension section (override value in config file)"}, {"extfile", OPT_EXTFILE, '<', "Configuration file with X509v3 extensions to add"}, {"preserveDN", OPT_PRESERVEDN, '-', "Don't re-order the DN"}, {"noemailDN", OPT_NOEMAILDN, '-', "Don't add the EMAIL field to the DN"}, OPT_SECTION("Signing"), {"md", OPT_MD, 's', "Digest to use, such as sha256"}, {"keyfile", OPT_KEYFILE, 's', "The CA private key"}, {"keyform", OPT_KEYFORM, 'f', "Private key file format (ENGINE, other values ignored)"}, {"passin", OPT_PASSIN, 's', "Key and cert input file pass phrase source"}, {"key", OPT_KEY, 's', "Key to decrypt the private key or cert files if encrypted. Better use -passin"}, {"cert", OPT_CERT, '<', "The CA cert"}, {"certform", OPT_CERTFORM, 'F', "Certificate input format (DER/PEM/P12); has no effect"}, {"selfsign", OPT_SELFSIGN, '-', "Sign a cert with the key associated with it"}, {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"}, {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"}, OPT_SECTION("Revocation"), {"gencrl", OPT_GENCRL, '-', "Generate a new CRL"}, {"valid", OPT_VALID, 's', "Add a Valid(not-revoked) DB entry about a cert (given in file)"}, {"status", OPT_STATUS, 's', "Shows cert status given the serial number"}, {"updatedb", OPT_UPDATEDB, '-', "Updates db for expired cert"}, {"crlexts", OPT_CRLEXTS, 's', "CRL extension section (override value in config file)"}, {"crl_reason", OPT_CRL_REASON, 's', "revocation reason"}, {"crl_hold", OPT_CRL_HOLD, 's', "the hold instruction, an OID. Sets revocation reason to certificateHold"}, {"crl_compromise", OPT_CRL_COMPROMISE, 's', "sets compromise time to val and the revocation reason to keyCompromise"}, {"crl_CA_compromise", OPT_CRL_CA_COMPROMISE, 's', "sets compromise time to val and the revocation reason to CACompromise"}, {"crl_lastupdate", OPT_CRL_LASTUPDATE, 's', "Sets the CRL lastUpdate time to val (YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ)"}, {"crl_nextupdate", OPT_CRL_NEXTUPDATE, 's', "Sets the CRL nextUpdate time to val (YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ)"}, {"crldays", OPT_CRLDAYS, 'p', "Days until the next CRL is due"}, {"crlhours", OPT_CRLHOURS, 'p', "Hours until the next CRL is due"}, {"crlsec", OPT_CRLSEC, 'p', "Seconds until the next CRL is due"}, {"revoke", OPT_REVOKE, '<', "Revoke a cert (given in file)"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"certreq", 0, 0, "Certificate requests to be signed (optional)"}, {NULL} }; int ca_main(int argc, char **argv) { CONF *conf = NULL; ENGINE *e = NULL; BIGNUM *crlnumber = NULL, *serial = NULL; EVP_PKEY *pkey = NULL; BIO *in = NULL, *out = NULL, *Sout = NULL; ASN1_INTEGER *tmpser; CA_DB *db = NULL; DB_ATTR db_attr; STACK_OF(CONF_VALUE) *attribs = NULL; STACK_OF(OPENSSL_STRING) *sigopts = NULL, *vfyopts = NULL; STACK_OF(X509) *cert_sk = NULL; X509_CRL *crl = NULL; char *configfile = default_config_file, *section = NULL; char def_dgst[80] = ""; char *dgst = NULL, *policy = NULL, *keyfile = NULL; char *certfile = NULL, *crl_ext = NULL, *crlnumberfile = NULL; int certformat = FORMAT_UNDEF, informat = FORMAT_UNDEF; unsigned long dateopt = ASN1_DTFLGS_RFC822; const char *infile = NULL, *spkac_file = NULL, *ss_cert_file = NULL; const char *extensions = NULL, *extfile = NULL, *passinarg = NULL; char *passin = NULL; char *outdir = NULL, *outfile = NULL, *rev_arg = NULL, *ser_status = NULL; const char *serialfile = NULL, *subj = NULL; char *prog, *startdate = NULL, *enddate = NULL; char *dbfile = NULL, *f; char new_cert[PATH_MAX]; char tmp[10 + 1] = "\0"; char *const *pp; const char *p; size_t outdirlen = 0; int create_ser = 0, free_passin = 0, total = 0, total_done = 0; int batch = 0, default_op = 1, doupdatedb = 0, ext_copy = EXT_COPY_NONE; int keyformat = FORMAT_UNDEF, multirdn = 1, notext = 0, output_der = 0; int ret = 1, email_dn = 1, req = 0, verbose = 0, gencrl = 0, dorevoke = 0; int rand_ser = 0, i, j, selfsign = 0, def_ret; char *crl_lastupdate = NULL, *crl_nextupdate = NULL; long crldays = 0, crlhours = 0, crlsec = 0, days = 0; unsigned long chtype = MBSTRING_ASC, certopt = 0; X509 *x509 = NULL, *x509p = NULL, *x = NULL; REVINFO_TYPE rev_type = REV_NONE; X509_REVOKED *r = NULL; OPTION_CHOICE o; prog = opt_init(argc, argv, ca_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(ca_options); ret = 0; goto end; case OPT_IN: req = 1; infile = opt_arg(); break; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_DATEOPT: if (!set_dateopt(&dateopt, opt_arg())) goto opthelp; break; case OPT_VERBOSE: verbose = 1; break; case OPT_QUIET: verbose = 0; break; case OPT_CONFIG: configfile = opt_arg(); break; case OPT_NAME: section = opt_arg(); break; case OPT_SUBJ: subj = opt_arg(); break; case OPT_UTF8: chtype = MBSTRING_UTF8; break; case OPT_RAND_SERIAL: rand_ser = 1; break; case OPT_CREATE_SERIAL: create_ser = 1; break; case OPT_MULTIVALUE_RDN: break; case OPT_STARTDATE: startdate = opt_arg(); break; case OPT_ENDDATE: enddate = opt_arg(); break; case OPT_DAYS: days = atoi(opt_arg()); break; case OPT_MD: dgst = opt_arg(); break; case OPT_POLICY: policy = opt_arg(); break; case OPT_KEYFILE: keyfile = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat)) goto opthelp; break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_KEY: passin = opt_arg(); break; case OPT_CERT: certfile = opt_arg(); break; case OPT_CERTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &certformat)) goto opthelp; break; case OPT_SELFSIGN: selfsign = 1; break; case OPT_OUTDIR: outdir = opt_arg(); break; case OPT_SIGOPT: if (sigopts == NULL) sigopts = sk_OPENSSL_STRING_new_null(); if (sigopts == NULL || !sk_OPENSSL_STRING_push(sigopts, opt_arg())) goto end; break; case OPT_VFYOPT: if (vfyopts == NULL) vfyopts = sk_OPENSSL_STRING_new_null(); if (vfyopts == NULL || !sk_OPENSSL_STRING_push(vfyopts, opt_arg())) goto end; break; case OPT_NOTEXT: notext = 1; break; case OPT_BATCH: batch = 1; break; case OPT_PRESERVEDN: preserve = 1; break; case OPT_NOEMAILDN: email_dn = 0; break; case OPT_GENCRL: gencrl = 1; break; case OPT_MSIE_HACK: msie_hack = 1; break; case OPT_CRL_LASTUPDATE: crl_lastupdate = opt_arg(); break; case OPT_CRL_NEXTUPDATE: crl_nextupdate = opt_arg(); break; case OPT_CRLDAYS: crldays = atol(opt_arg()); break; case OPT_CRLHOURS: crlhours = atol(opt_arg()); break; case OPT_CRLSEC: crlsec = atol(opt_arg()); break; case OPT_INFILES: req = 1; goto end_of_options; case OPT_SS_CERT: ss_cert_file = opt_arg(); req = 1; break; case OPT_SPKAC: spkac_file = opt_arg(); req = 1; break; case OPT_REVOKE: infile = opt_arg(); dorevoke = 1; break; case OPT_VALID: infile = opt_arg(); dorevoke = 2; break; case OPT_EXTENSIONS: extensions = opt_arg(); break; case OPT_EXTFILE: extfile = opt_arg(); break; case OPT_STATUS: ser_status = opt_arg(); break; case OPT_UPDATEDB: doupdatedb = 1; break; case OPT_CRLEXTS: crl_ext = opt_arg(); break; case OPT_CRL_REASON: case OPT_CRL_HOLD: case OPT_CRL_COMPROMISE: case OPT_CRL_CA_COMPROMISE: rev_arg = opt_arg(); rev_type = (o - OPT_CRL_REASON) + REV_CRL_REASON; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; } } end_of_options: argc = opt_num_rest(); argv = opt_rest(); if ((conf = app_load_config_verbose(configfile, 1)) == NULL) goto end; if (configfile != default_config_file && !app_load_modules(conf)) goto end; if (section == NULL && (section = lookup_conf(conf, BASE_SECTION, ENV_DEFAULT_CA)) == NULL) goto end; p = app_conf_try_string(conf, NULL, "oid_file"); if (p != NULL) { BIO *oid_bio = BIO_new_file(p, "r"); if (oid_bio == NULL) { ERR_clear_error(); } else { OBJ_create_objects(oid_bio); BIO_free(oid_bio); } } if (!add_oid_section(conf)) goto end; app_RAND_load_conf(conf, BASE_SECTION); if (!app_RAND_load()) goto end; f = app_conf_try_string(conf, section, STRING_MASK); if (f != NULL && !ASN1_STRING_set_default_mask_asc(f)) { BIO_printf(bio_err, "Invalid global string mask setting %s\n", f); goto end; } if (chtype != MBSTRING_UTF8) { f = app_conf_try_string(conf, section, UTF8_IN); if (f != NULL && strcmp(f, "yes") == 0) chtype = MBSTRING_UTF8; } db_attr.unique_subject = 1; p = app_conf_try_string(conf, section, ENV_UNIQUE_SUBJECT); if (p != NULL) db_attr.unique_subject = parse_yesno(p, 1); if (ser_status) { dbfile = lookup_conf(conf, section, ENV_DATABASE); if (dbfile == NULL) goto end; db = load_index(dbfile, &db_attr); if (db == NULL) { BIO_printf(bio_err, "Problem with index file: %s (could not load/parse file)\n", dbfile); goto end; } if (index_index(db) <= 0) goto end; if (get_certificate_status(ser_status, db) != 1) BIO_printf(bio_err, "Error verifying serial %s!\n", ser_status); goto end; } if (keyfile == NULL && (keyfile = lookup_conf(conf, section, ENV_PRIVATE_KEY)) == NULL) goto end; if (passin == NULL) { free_passin = 1; if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } } pkey = load_key(keyfile, keyformat, 0, passin, e, "CA private key"); cleanse(passin); if (pkey == NULL) goto end; if (!selfsign || spkac_file || ss_cert_file || gencrl) { if (certfile == NULL && (certfile = lookup_conf(conf, section, ENV_CERTIFICATE)) == NULL) goto end; x509 = load_cert_pass(certfile, certformat, 1, passin, "CA certificate"); if (x509 == NULL) goto end; if (!X509_check_private_key(x509, pkey)) { BIO_printf(bio_err, "CA certificate and CA private key do not match\n"); goto end; } } if (!selfsign) x509p = x509; f = app_conf_try_string(conf, BASE_SECTION, ENV_PRESERVE); if (f != NULL && (*f == 'y' || *f == 'Y')) preserve = 1; f = app_conf_try_string(conf, BASE_SECTION, ENV_MSIE_HACK); if (f != NULL && (*f == 'y' || *f == 'Y')) msie_hack = 1; f = app_conf_try_string(conf, section, ENV_NAMEOPT); if (f != NULL) { if (!set_nameopt(f)) { BIO_printf(bio_err, "Invalid name options: \"%s\"\n", f); goto end; } default_op = 0; } f = app_conf_try_string(conf, section, ENV_CERTOPT); if (f != NULL) { if (!set_cert_ex(&certopt, f)) { BIO_printf(bio_err, "Invalid certificate options: \"%s\"\n", f); goto end; } default_op = 0; } f = app_conf_try_string(conf, section, ENV_EXTCOPY); if (f != NULL) { if (!set_ext_copy(&ext_copy, f)) { BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n", f); goto end; } } if ((outdir == NULL) && (req)) { outdir = NCONF_get_string(conf, section, ENV_NEW_CERTS_DIR); if (outdir == NULL) { BIO_printf(bio_err, "there needs to be defined a directory for new certificate to be placed in\n"); goto end; } #ifndef OPENSSL_SYS_VMS if (app_isdir(outdir) <= 0) { BIO_printf(bio_err, "%s: %s is not a directory\n", prog, outdir); perror(outdir); goto end; } #endif } dbfile = lookup_conf(conf, section, ENV_DATABASE); if (dbfile == NULL) goto end; db = load_index(dbfile, &db_attr); if (db == NULL) { BIO_printf(bio_err, "Problem with index file: %s (could not load/parse file)\n", dbfile); goto end; } for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if ((pp[DB_type][0] != DB_TYPE_REV) && (pp[DB_rev_date][0] != '\0')) { BIO_printf(bio_err, "entry %d: not revoked yet, but has a revocation date\n", i + 1); goto end; } if ((pp[DB_type][0] == DB_TYPE_REV) && !make_revoked(NULL, pp[DB_rev_date])) { BIO_printf(bio_err, " in entry %d\n", i + 1); goto end; } if (!check_time_format((char *)pp[DB_exp_date])) { BIO_printf(bio_err, "entry %d: invalid expiry date\n", i + 1); goto end; } p = pp[DB_serial]; j = strlen(p); if (*p == '-') { p++; j--; } if ((j & 1) || (j < 2)) { BIO_printf(bio_err, "entry %d: bad serial number length (%d)\n", i + 1, j); goto end; } for ( ; *p; p++) { if (!isxdigit(_UC(*p))) { BIO_printf(bio_err, "entry %d: bad char 0%o '%c' in serial number\n", i + 1, *p, *p); goto end; } } } if (verbose) { TXT_DB_write(bio_out, db->db); BIO_printf(bio_err, "%d entries loaded from the database\n", sk_OPENSSL_PSTRING_num(db->db->data)); BIO_printf(bio_err, "generating index\n"); } if (index_index(db) <= 0) goto end; if (doupdatedb) { if (verbose) BIO_printf(bio_err, "Updating %s ...\n", dbfile); i = do_updatedb(db, NULL); if (i == -1) { BIO_printf(bio_err, "Malloc failure\n"); goto end; } else if (i == 0) { if (verbose) BIO_printf(bio_err, "No entries found to mark expired\n"); } else { if (!save_index(dbfile, "new", db)) goto end; if (!rotate_index(dbfile, "new", "old")) goto end; if (verbose) BIO_printf(bio_err, "Done. %d entries marked as expired\n", i); } } if (extfile) { if ((extfile_conf = app_load_config(extfile)) == NULL) { ret = 1; goto end; } if (verbose) BIO_printf(bio_err, "Successfully loaded extensions file %s\n", extfile); if (extensions == NULL) { extensions = app_conf_try_string(extfile_conf, "default", "extensions"); if (extensions == NULL) extensions = "default"; } } if (req || gencrl) { if (spkac_file != NULL && outfile != NULL) { output_der = 1; batch = 1; } } def_ret = EVP_PKEY_get_default_digest_name(pkey, def_dgst, sizeof(def_dgst)); if (def_ret == 2 && strcmp(def_dgst, "UNDEF") == 0) { dgst = NULL; } else if (dgst == NULL && (dgst = lookup_conf(conf, section, ENV_DEFAULT_MD)) == NULL && strcmp(def_dgst, "UNDEF") != 0) { goto end; } else { if (strcmp(dgst, "default") == 0 || strcmp(def_dgst, "UNDEF") == 0) { if (def_ret <= 0) { BIO_puts(bio_err, "no default digest\n"); goto end; } dgst = def_dgst; } } if (req) { if (email_dn == 1) { char *tmp_email_dn = NULL; tmp_email_dn = app_conf_try_string(conf, section, ENV_DEFAULT_EMAIL_DN); if (tmp_email_dn != NULL && strcmp(tmp_email_dn, "no") == 0) email_dn = 0; } if (verbose) BIO_printf(bio_err, "message digest is %s\n", dgst); if (policy == NULL && (policy = lookup_conf(conf, section, ENV_POLICY)) == NULL) goto end; if (verbose) BIO_printf(bio_err, "policy is %s\n", policy); if (app_conf_try_string(conf, section, ENV_RAND_SERIAL) != NULL) { rand_ser = 1; } else { serialfile = lookup_conf(conf, section, ENV_SERIAL); if (serialfile == NULL) goto end; } if (extfile_conf != NULL) { X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, extfile_conf); if (!X509V3_EXT_add_nconf(extfile_conf, &ctx, extensions, NULL)) { BIO_printf(bio_err, "Error checking certificate extensions from extfile section %s\n", extensions); ret = 1; goto end; } } else { if (extensions == NULL) extensions = app_conf_try_string(conf, section, ENV_EXTENSIONS); if (extensions != NULL) { X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, conf); if (!X509V3_EXT_add_nconf(conf, &ctx, extensions, NULL)) { BIO_printf(bio_err, "Error checking certificate extension config section %s\n", extensions); ret = 1; goto end; } } } if (startdate == NULL) startdate = app_conf_try_string(conf, section, ENV_DEFAULT_STARTDATE); if (startdate != NULL && !ASN1_TIME_set_string_X509(NULL, startdate)) { BIO_printf(bio_err, "start date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n"); goto end; } if (startdate == NULL) startdate = "today"; if (enddate == NULL) enddate = app_conf_try_string(conf, section, ENV_DEFAULT_ENDDATE); if (enddate != NULL && !ASN1_TIME_set_string_X509(NULL, enddate)) { BIO_printf(bio_err, "end date is invalid, it should be YYMMDDHHMMSSZ or YYYYMMDDHHMMSSZ\n"); goto end; } if (days == 0) { if (!app_conf_try_number(conf, section, ENV_DEFAULT_DAYS, &days)) days = 0; } if (enddate == NULL && days == 0) { BIO_printf(bio_err, "cannot lookup how many days to certify for\n"); goto end; } if (rand_ser) { if ((serial = BN_new()) == NULL || !rand_serial(serial, NULL)) { BIO_printf(bio_err, "error generating serial number\n"); goto end; } } else { serial = load_serial(serialfile, NULL, create_ser, NULL); if (serial == NULL) { BIO_printf(bio_err, "error while loading serial number\n"); goto end; } if (verbose) { if (BN_is_zero(serial)) { BIO_printf(bio_err, "next serial number is 00\n"); } else { if ((f = BN_bn2hex(serial)) == NULL) goto end; BIO_printf(bio_err, "next serial number is %s\n", f); OPENSSL_free(f); } } } if ((attribs = NCONF_get_section(conf, policy)) == NULL) { BIO_printf(bio_err, "unable to find 'section' for %s\n", policy); goto end; } if ((cert_sk = sk_X509_new_null()) == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } if (spkac_file != NULL) { total++; j = certify_spkac(&x, spkac_file, pkey, x509, dgst, sigopts, attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, extensions, conf, verbose, certopt, get_nameopt(), default_op, ext_copy, dateopt); if (j < 0) goto end; if (j > 0) { total_done++; BIO_printf(bio_err, "\n"); if (!BN_add_word(serial, 1)) goto end; if (!sk_X509_push(cert_sk, x)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } } } if (ss_cert_file != NULL) { total++; j = certify_cert(&x, ss_cert_file, certformat, passin, pkey, x509, dgst, sigopts, vfyopts, attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, extensions, conf, verbose, certopt, get_nameopt(), default_op, ext_copy, dateopt); if (j < 0) goto end; if (j > 0) { total_done++; BIO_printf(bio_err, "\n"); if (!BN_add_word(serial, 1)) goto end; if (!sk_X509_push(cert_sk, x)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } } } if (infile != NULL) { total++; j = certify(&x, infile, informat, pkey, x509p, dgst, sigopts, vfyopts, attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, extensions, conf, verbose, certopt, get_nameopt(), default_op, ext_copy, selfsign, dateopt); if (j < 0) goto end; if (j > 0) { total_done++; BIO_printf(bio_err, "\n"); if (!BN_add_word(serial, 1)) goto end; if (!sk_X509_push(cert_sk, x)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } } } for (i = 0; i < argc; i++) { total++; j = certify(&x, argv[i], informat, pkey, x509p, dgst, sigopts, vfyopts, attribs, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, extensions, conf, verbose, certopt, get_nameopt(), default_op, ext_copy, selfsign, dateopt); if (j < 0) goto end; if (j > 0) { total_done++; BIO_printf(bio_err, "\n"); if (!BN_add_word(serial, 1)) { X509_free(x); goto end; } if (!sk_X509_push(cert_sk, x)) { BIO_printf(bio_err, "Memory allocation failure\n"); X509_free(x); goto end; } } } if (sk_X509_num(cert_sk) > 0) { if (!batch) { BIO_printf(bio_err, "\n%d out of %d certificate requests certified, commit? [y/n]", total_done, total); (void)BIO_flush(bio_err); tmp[0] = '\0'; if (fgets(tmp, sizeof(tmp), stdin) == NULL) { BIO_printf(bio_err, "CERTIFICATION CANCELED: I/O error\n"); ret = 0; goto end; } if (tmp[0] != 'y' && tmp[0] != 'Y') { BIO_printf(bio_err, "CERTIFICATION CANCELED\n"); ret = 0; goto end; } } BIO_printf(bio_err, "Write out database with %d new entries\n", sk_X509_num(cert_sk)); if (serialfile != NULL && !save_serial(serialfile, "new", serial, NULL)) goto end; if (!save_index(dbfile, "new", db)) goto end; } outdirlen = OPENSSL_strlcpy(new_cert, outdir, sizeof(new_cert)); #ifndef OPENSSL_SYS_VMS outdirlen = OPENSSL_strlcat(new_cert, "/", sizeof(new_cert)); #endif if (verbose) BIO_printf(bio_err, "writing new certificates\n"); for (i = 0; i < sk_X509_num(cert_sk); i++) { BIO *Cout = NULL; X509 *xi = sk_X509_value(cert_sk, i); const ASN1_INTEGER *serialNumber = X509_get0_serialNumber(xi); const unsigned char *psn = ASN1_STRING_get0_data(serialNumber); const int snl = ASN1_STRING_length(serialNumber); const int filen_len = 2 * (snl > 0 ? snl : 1) + sizeof(".pem"); char *n = new_cert + outdirlen; if (outdirlen + filen_len > PATH_MAX) { BIO_printf(bio_err, "certificate file name too long\n"); goto end; } if (snl > 0) { static const char HEX_DIGITS[] = "0123456789ABCDEF"; for (j = 0; j < snl; j++, psn++) { *n++ = HEX_DIGITS[*psn >> 4]; *n++ = HEX_DIGITS[*psn & 0x0F]; } } else { *(n++) = '0'; *(n++) = '0'; } *(n++) = '.'; *(n++) = 'p'; *(n++) = 'e'; *(n++) = 'm'; *n = '\0'; if (verbose) BIO_printf(bio_err, "writing %s\n", new_cert); Sout = bio_open_default(outfile, 'w', output_der ? FORMAT_ASN1 : FORMAT_TEXT); if (Sout == NULL) goto end; Cout = BIO_new_file(new_cert, "w"); if (Cout == NULL) { perror(new_cert); goto end; } write_new_certificate(Cout, xi, 0, notext); write_new_certificate(Sout, xi, output_der, notext); BIO_free_all(Cout); BIO_free_all(Sout); Sout = NULL; } if (sk_X509_num(cert_sk)) { if (serialfile != NULL && !rotate_serial(serialfile, "new", "old")) goto end; if (!rotate_index(dbfile, "new", "old")) goto end; BIO_printf(bio_err, "Database updated\n"); } } if (gencrl) { int crl_v2 = 0; if (crl_ext == NULL) crl_ext = app_conf_try_string(conf, section, ENV_CRLEXT); if (crl_ext != NULL) { X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, conf); if (!X509V3_EXT_add_nconf(conf, &ctx, crl_ext, NULL)) { BIO_printf(bio_err, "Error checking CRL extension section %s\n", crl_ext); ret = 1; goto end; } } crlnumberfile = app_conf_try_string(conf, section, ENV_CRLNUMBER); if (crlnumberfile != NULL) { if ((crlnumber = load_serial(crlnumberfile, NULL, 0, NULL)) == NULL) { BIO_printf(bio_err, "error while loading CRL number\n"); goto end; } } if (!crldays && !crlhours && !crlsec) { if (!app_conf_try_number(conf, section, ENV_DEFAULT_CRL_DAYS, &crldays)) crldays = 0; if (!app_conf_try_number(conf, section, ENV_DEFAULT_CRL_HOURS, &crlhours)) crlhours = 0; } if ((crl_nextupdate == NULL) && (crldays == 0) && (crlhours == 0) && (crlsec == 0)) { BIO_printf(bio_err, "cannot lookup how long until the next CRL is issued\n"); goto end; } if (verbose) BIO_printf(bio_err, "making CRL\n"); if ((crl = X509_CRL_new_ex(app_get0_libctx(), app_get0_propq())) == NULL) goto end; if (!X509_CRL_set_issuer_name(crl, X509_get_subject_name(x509))) goto end; if (!set_crl_lastupdate(crl, crl_lastupdate)) { BIO_puts(bio_err, "error setting CRL lastUpdate\n"); ret = 1; goto end; } if (!set_crl_nextupdate(crl, crl_nextupdate, crldays, crlhours, crlsec)) { BIO_puts(bio_err, "error setting CRL nextUpdate\n"); ret = 1; goto end; } for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { pp = sk_OPENSSL_PSTRING_value(db->db->data, i); if (pp[DB_type][0] == DB_TYPE_REV) { if ((r = X509_REVOKED_new()) == NULL) goto end; j = make_revoked(r, pp[DB_rev_date]); if (!j) goto end; if (j == 2) crl_v2 = 1; if (!BN_hex2bn(&serial, pp[DB_serial])) goto end; tmpser = BN_to_ASN1_INTEGER(serial, NULL); BN_free(serial); serial = NULL; if (!tmpser) goto end; X509_REVOKED_set_serialNumber(r, tmpser); ASN1_INTEGER_free(tmpser); X509_CRL_add0_revoked(crl, r); } } X509_CRL_sort(crl); if (verbose) BIO_printf(bio_err, "signing CRL\n"); if (crl_ext != NULL || crlnumberfile != NULL) { X509V3_CTX crlctx; X509V3_set_ctx(&crlctx, x509, NULL, NULL, crl, 0); X509V3_set_nconf(&crlctx, conf); if (crl_ext != NULL) if (!X509V3_EXT_CRL_add_nconf(conf, &crlctx, crl_ext, crl)) { BIO_printf(bio_err, "Error adding CRL extensions from section %s\n", crl_ext); goto end; } if (crlnumberfile != NULL) { tmpser = BN_to_ASN1_INTEGER(crlnumber, NULL); if (!tmpser) goto end; X509_CRL_add1_ext_i2d(crl, NID_crl_number, tmpser, 0, 0); ASN1_INTEGER_free(tmpser); crl_v2 = 1; if (!BN_add_word(crlnumber, 1)) goto end; } } if (crl_ext != NULL || crl_v2) { if (!X509_CRL_set_version(crl, X509_CRL_VERSION_2)) goto end; } if (crlnumberfile != NULL && !save_serial(crlnumberfile, "new", crlnumber, NULL)) goto end; BN_free(crlnumber); crlnumber = NULL; if (!do_X509_CRL_sign(crl, pkey, dgst, sigopts)) goto end; Sout = bio_open_default(outfile, 'w', output_der ? FORMAT_ASN1 : FORMAT_TEXT); if (Sout == NULL) goto end; PEM_write_bio_X509_CRL(Sout, crl); if (crlnumberfile != NULL && !rotate_serial(crlnumberfile, "new", "old")) goto end; } if (dorevoke) { if (infile == NULL) { BIO_printf(bio_err, "no input files\n"); goto end; } else { X509 *revcert; revcert = load_cert_pass(infile, informat, 1, passin, "certificate to be revoked"); if (revcert == NULL) goto end; if (dorevoke == 2) rev_type = REV_VALID; j = do_revoke(revcert, db, rev_type, rev_arg); if (j <= 0) goto end; X509_free(revcert); if (!save_index(dbfile, "new", db)) goto end; if (!rotate_index(dbfile, "new", "old")) goto end; BIO_printf(bio_err, "Database updated\n"); } } ret = 0; end: if (ret) ERR_print_errors(bio_err); BIO_free_all(Sout); BIO_free_all(out); BIO_free_all(in); OSSL_STACK_OF_X509_free(cert_sk); cleanse(passin); if (free_passin) OPENSSL_free(passin); BN_free(serial); BN_free(crlnumber); free_index(db); sk_OPENSSL_STRING_free(sigopts); sk_OPENSSL_STRING_free(vfyopts); EVP_PKEY_free(pkey); X509_free(x509); X509_CRL_free(crl); NCONF_free(conf); NCONF_free(extfile_conf); release_engine(e); return ret; } static char *lookup_conf(const CONF *conf, const char *section, const char *tag) { char *entry = NCONF_get_string(conf, section, tag); if (entry == NULL) BIO_printf(bio_err, "variable lookup failed for %s::%s\n", section, tag); return entry; } static int certify(X509 **xret, const char *infile, int informat, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(OPENSSL_STRING) *vfyopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, int batch, const char *ext_sect, CONF *lconf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign, unsigned long dateopt) { X509_REQ *req = NULL; EVP_PKEY *pktmp = NULL; int ok = -1, i; req = load_csr_autofmt(infile, informat, vfyopts, "certificate request"); if (req == NULL) goto end; if ((pktmp = X509_REQ_get0_pubkey(req)) == NULL) { BIO_printf(bio_err, "Error unpacking public key\n"); goto end; } if (verbose) X509_REQ_print_ex(bio_err, req, nameopt, X509_FLAG_COMPAT); BIO_printf(bio_err, "Check that the request matches the signature\n"); ok = 0; if (selfsign && !X509_REQ_check_private_key(req, pkey)) { BIO_printf(bio_err, "Certificate request and CA private key do not match\n"); goto end; } i = do_X509_REQ_verify(req, pktmp, vfyopts); if (i < 0) { BIO_printf(bio_err, "Signature verification problems...\n"); goto end; } if (i == 0) { BIO_printf(bio_err, "Signature did not match the certificate request\n"); goto end; } BIO_printf(bio_err, "Signature ok\n"); ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, verbose, req, ext_sect, lconf, certopt, nameopt, default_op, ext_copy, selfsign, dateopt); end: ERR_print_errors(bio_err); X509_REQ_free(req); return ok; } static int certify_cert(X509 **xret, const char *infile, int certformat, const char *passin, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(OPENSSL_STRING) *vfyopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, int batch, const char *ext_sect, CONF *lconf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, unsigned long dateopt) { X509 *template_cert = NULL; X509_REQ *rreq = NULL; EVP_PKEY *pktmp = NULL; int ok = -1, i; if ((template_cert = load_cert_pass(infile, certformat, 1, passin, "template certificate")) == NULL) goto end; if (verbose) X509_print(bio_err, template_cert); BIO_printf(bio_err, "Check that the request matches the signature\n"); if ((pktmp = X509_get0_pubkey(template_cert)) == NULL) { BIO_printf(bio_err, "error unpacking public key\n"); goto end; } i = do_X509_verify(template_cert, pktmp, vfyopts); if (i < 0) { ok = 0; BIO_printf(bio_err, "Signature verification problems....\n"); goto end; } if (i == 0) { ok = 0; BIO_printf(bio_err, "Signature did not match the certificate\n"); goto end; } else { BIO_printf(bio_err, "Signature ok\n"); } if ((rreq = X509_to_X509_REQ(template_cert, NULL, NULL)) == NULL) goto end; ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, batch, verbose, rreq, ext_sect, lconf, certopt, nameopt, default_op, ext_copy, 0, dateopt); end: X509_REQ_free(rreq); X509_free(template_cert); return ok; } static int do_body(X509 **xret, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, int batch, int verbose, X509_REQ *req, const char *ext_sect, CONF *lconf, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, int selfsign, unsigned long dateopt) { const X509_NAME *name = NULL; X509_NAME *CAname = NULL, *subject = NULL; const ASN1_TIME *tm; ASN1_STRING *str, *str2; ASN1_OBJECT *obj; X509 *ret = NULL; X509_NAME_ENTRY *ne, *tne; EVP_PKEY *pktmp; int ok = -1, i, j, last, nid; const char *p; CONF_VALUE *cv; OPENSSL_STRING row[DB_NUMBER]; OPENSSL_STRING *irow = NULL; OPENSSL_STRING *rrow = NULL; char buf[25]; X509V3_CTX ext_ctx; for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; if (subj) { X509_NAME *n = parse_name(subj, chtype, multirdn, "subject"); if (!n) goto end; X509_REQ_set_subject_name(req, n); X509_NAME_free(n); } if (default_op) BIO_printf(bio_err, "The Subject's Distinguished Name is as follows\n"); name = X509_REQ_get_subject_name(req); for (i = 0; i < X509_NAME_entry_count(name); i++) { ne = X509_NAME_get_entry(name, i); str = X509_NAME_ENTRY_get_data(ne); obj = X509_NAME_ENTRY_get_object(ne); nid = OBJ_obj2nid(obj); if (msie_hack) { if (str->type == V_ASN1_UNIVERSALSTRING) ASN1_UNIVERSALSTRING_to_string(str); if (str->type == V_ASN1_IA5STRING && nid != NID_pkcs9_emailAddress) str->type = V_ASN1_T61STRING; if (nid == NID_pkcs9_emailAddress && str->type == V_ASN1_PRINTABLESTRING) str->type = V_ASN1_IA5STRING; } if (nid == NID_pkcs9_emailAddress && !email_dn) continue; if (nid == NID_pkcs9_emailAddress && str->type != V_ASN1_IA5STRING) { BIO_printf(bio_err, "\nemailAddress type needs to be of type IA5STRING\n"); goto end; } if (str->type != V_ASN1_BMPSTRING && str->type != V_ASN1_UTF8STRING) { j = ASN1_PRINTABLE_type(str->data, str->length); if ((j == V_ASN1_T61STRING && str->type != V_ASN1_T61STRING) || (j == V_ASN1_IA5STRING && str->type == V_ASN1_PRINTABLESTRING)) { BIO_printf(bio_err, "\nThe string contains characters that are illegal for the ASN.1 type\n"); goto end; } } if (default_op) old_entry_print(obj, str); } if ((subject = X509_NAME_new()) == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } if (selfsign) CAname = X509_NAME_dup(name); else CAname = X509_NAME_dup(X509_get_subject_name(x509)); if (CAname == NULL) goto end; str = str2 = NULL; for (i = 0; i < sk_CONF_VALUE_num(policy); i++) { cv = sk_CONF_VALUE_value(policy, i); if ((j = OBJ_txt2nid(cv->name)) == NID_undef) { BIO_printf(bio_err, "%s:unknown object type in 'policy' configuration\n", cv->name); goto end; } obj = OBJ_nid2obj(j); last = -1; for (;;) { X509_NAME_ENTRY *push = NULL; j = X509_NAME_get_index_by_OBJ(name, obj, last); if (j < 0) { if (last != -1) break; tne = NULL; } else { tne = X509_NAME_get_entry(name, j); } last = j; if (strcmp(cv->value, "optional") == 0) { if (tne != NULL) push = tne; } else if (strcmp(cv->value, "supplied") == 0) { if (tne == NULL) { BIO_printf(bio_err, "The %s field needed to be supplied and was missing\n", cv->name); goto end; } else { push = tne; } } else if (strcmp(cv->value, "match") == 0) { int last2; if (tne == NULL) { BIO_printf(bio_err, "The mandatory %s field was missing\n", cv->name); goto end; } last2 = -1; again2: j = X509_NAME_get_index_by_OBJ(CAname, obj, last2); if ((j < 0) && (last2 == -1)) { BIO_printf(bio_err, "The %s field does not exist in the CA certificate,\n" "the 'policy' is misconfigured\n", cv->name); goto end; } if (j >= 0) { push = X509_NAME_get_entry(CAname, j); str = X509_NAME_ENTRY_get_data(tne); str2 = X509_NAME_ENTRY_get_data(push); last2 = j; if (ASN1_STRING_cmp(str, str2) != 0) goto again2; } if (j < 0) { BIO_printf(bio_err, "The %s field is different between\n" "CA certificate (%s) and the request (%s)\n", cv->name, ((str2 == NULL) ? "NULL" : (char *)str2->data), ((str == NULL) ? "NULL" : (char *)str->data)); goto end; } } else { BIO_printf(bio_err, "%s:invalid type in 'policy' configuration\n", cv->value); goto end; } if (push != NULL) { if (!X509_NAME_add_entry(subject, push, -1, 0)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } } if (j < 0) break; } } if (preserve) { X509_NAME_free(subject); subject = X509_NAME_dup(name); if (subject == NULL) goto end; } if (verbose) BIO_printf(bio_err, "Everything appears to be ok, creating and signing the certificate\n"); if ((ret = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL) goto end; if (BN_to_ASN1_INTEGER(serial, X509_get_serialNumber(ret)) == NULL) goto end; if (selfsign) { if (!X509_set_issuer_name(ret, subject)) goto end; } else { if (!X509_set_issuer_name(ret, X509_get_subject_name(x509))) goto end; } if (!set_cert_times(ret, startdate, enddate, days)) goto end; if (enddate != NULL) { int tdays; if (!ASN1_TIME_diff(&tdays, NULL, NULL, X509_get0_notAfter(ret))) goto end; days = tdays; } if (!X509_set_subject_name(ret, subject)) goto end; pktmp = X509_REQ_get0_pubkey(req); i = X509_set_pubkey(ret, pktmp); if (!i) goto end; X509V3_set_ctx(&ext_ctx, selfsign ? ret : x509, ret, NULL , NULL, X509V3_CTX_REPLACE); if (selfsign) { if (!X509V3_set_issuer_pkey(&ext_ctx, pkey)) goto end; if (!cert_matches_key(ret, pkey)) BIO_printf(bio_err, "Warning: Signature key and public key of cert do not match\n"); } if (ext_sect) { if (extfile_conf != NULL) { if (verbose) BIO_printf(bio_err, "Extra configuration file found\n"); X509V3_set_nconf(&ext_ctx, extfile_conf); if (!X509V3_EXT_add_nconf(extfile_conf, &ext_ctx, ext_sect, ret)) { BIO_printf(bio_err, "Error adding certificate extensions from extfile section %s\n", ext_sect); goto end; } if (verbose) BIO_printf(bio_err, "Successfully added extensions from file.\n"); } else if (ext_sect) { X509V3_set_nconf(&ext_ctx, lconf); if (!X509V3_EXT_add_nconf(lconf, &ext_ctx, ext_sect, ret)) { BIO_printf(bio_err, "Error adding certificate extensions from config section %s\n", ext_sect); goto end; } if (verbose) BIO_printf(bio_err, "Successfully added extensions from config\n"); } } if (!copy_extensions(ret, req, ext_copy)) { BIO_printf(bio_err, "ERROR: adding extensions from request\n"); goto end; } if (verbose) BIO_printf(bio_err, "The subject name appears to be ok, checking database for clashes\n"); if (!email_dn) { X509_NAME_ENTRY *tmpne; X509_NAME *dn_subject; if ((dn_subject = X509_NAME_dup(subject)) == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } i = -1; while ((i = X509_NAME_get_index_by_NID(dn_subject, NID_pkcs9_emailAddress, i)) >= 0) { tmpne = X509_NAME_delete_entry(dn_subject, i--); X509_NAME_ENTRY_free(tmpne); } if (!X509_set_subject_name(ret, dn_subject)) { X509_NAME_free(dn_subject); goto end; } X509_NAME_free(dn_subject); } row[DB_name] = X509_NAME_oneline(X509_get_subject_name(ret), NULL, 0); if (row[DB_name] == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } if (BN_is_zero(serial)) row[DB_serial] = OPENSSL_strdup("00"); else row[DB_serial] = BN_bn2hex(serial); if (row[DB_serial] == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } if (row[DB_name][0] == '\0') { OPENSSL_free(row[DB_name]); row[DB_name] = OPENSSL_strdup(row[DB_serial]); if (row[DB_name] == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } } if (db->attributes.unique_subject) { OPENSSL_STRING *crow = row; rrow = TXT_DB_get_by_index(db->db, DB_name, crow); if (rrow != NULL) { BIO_printf(bio_err, "ERROR:There is already a certificate for %s\n", row[DB_name]); } } if (rrow == NULL) { rrow = TXT_DB_get_by_index(db->db, DB_serial, row); if (rrow != NULL) { BIO_printf(bio_err, "ERROR:Serial number %s has already been issued,\n", row[DB_serial]); BIO_printf(bio_err, " check the database/serial_file for corruption\n"); } } if (rrow != NULL) { BIO_printf(bio_err, "The matching entry has the following details\n"); if (rrow[DB_type][0] == DB_TYPE_EXP) p = "Expired"; else if (rrow[DB_type][0] == DB_TYPE_REV) p = "Revoked"; else if (rrow[DB_type][0] == DB_TYPE_VAL) p = "Valid"; else p = "\ninvalid type, Database error\n"; BIO_printf(bio_err, "Type :%s\n", p); if (rrow[DB_type][0] == DB_TYPE_REV) { p = rrow[DB_exp_date]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "Was revoked on:%s\n", p); } p = rrow[DB_exp_date]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "Expires on :%s\n", p); p = rrow[DB_serial]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "Serial Number :%s\n", p); p = rrow[DB_file]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "File name :%s\n", p); p = rrow[DB_name]; if (p == NULL) p = "undef"; BIO_printf(bio_err, "Subject Name :%s\n", p); ok = -1; goto end; } if (!default_op) { BIO_printf(bio_err, "Certificate Details:\n"); certopt |= X509_FLAG_NO_SIGDUMP | X509_FLAG_NO_SIGNAME; X509_print_ex(bio_err, ret, nameopt, certopt); } BIO_printf(bio_err, "Certificate is to be certified until "); ASN1_TIME_print_ex(bio_err, X509_get0_notAfter(ret), dateopt); if (days) BIO_printf(bio_err, " (%ld days)", days); BIO_printf(bio_err, "\n"); if (!batch) { BIO_printf(bio_err, "Sign the certificate? [y/n]:"); (void)BIO_flush(bio_err); buf[0] = '\0'; if (fgets(buf, sizeof(buf), stdin) == NULL) { BIO_printf(bio_err, "CERTIFICATE WILL NOT BE CERTIFIED: I/O error\n"); ok = 0; goto end; } if (!(buf[0] == 'y' || buf[0] == 'Y')) { BIO_printf(bio_err, "CERTIFICATE WILL NOT BE CERTIFIED\n"); ok = 0; goto end; } } pktmp = X509_get0_pubkey(ret); if (EVP_PKEY_missing_parameters(pktmp) && !EVP_PKEY_missing_parameters(pkey)) EVP_PKEY_copy_parameters(pktmp, pkey); if (!do_X509_sign(ret, 0, pkey, dgst, sigopts, &ext_ctx)) goto end; row[DB_type] = OPENSSL_strdup("V"); tm = X509_get0_notAfter(ret); row[DB_exp_date] = app_malloc(tm->length + 1, "row expdate"); memcpy(row[DB_exp_date], tm->data, tm->length); row[DB_exp_date][tm->length] = '\0'; row[DB_rev_date] = NULL; row[DB_file] = OPENSSL_strdup("unknown"); if ((row[DB_type] == NULL) || (row[DB_file] == NULL) || (row[DB_name] == NULL)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row space"); for (i = 0; i < DB_NUMBER; i++) irow[i] = row[i]; irow[DB_NUMBER] = NULL; if (!TXT_DB_insert(db->db, irow)) { BIO_printf(bio_err, "failed to update database\n"); BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error); goto end; } irow = NULL; ok = 1; end: if (ok != 1) { for (i = 0; i < DB_NUMBER; i++) OPENSSL_free(row[i]); } OPENSSL_free(irow); X509_NAME_free(CAname); X509_NAME_free(subject); if (ok <= 0) X509_free(ret); else *xret = ret; return ok; } static void write_new_certificate(BIO *bp, X509 *x, int output_der, int notext) { if (output_der) { (void)i2d_X509_bio(bp, x); return; } if (!notext) X509_print(bp, x); PEM_write_bio_X509(bp, x); } static int certify_spkac(X509 **xret, const char *infile, EVP_PKEY *pkey, X509 *x509, const char *dgst, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(CONF_VALUE) *policy, CA_DB *db, BIGNUM *serial, const char *subj, unsigned long chtype, int multirdn, int email_dn, const char *startdate, const char *enddate, long days, const char *ext_sect, CONF *lconf, int verbose, unsigned long certopt, unsigned long nameopt, int default_op, int ext_copy, unsigned long dateopt) { STACK_OF(CONF_VALUE) *sk = NULL; LHASH_OF(CONF_VALUE) *parms = NULL; X509_REQ *req = NULL; CONF_VALUE *cv = NULL; NETSCAPE_SPKI *spki = NULL; char *type, *buf; EVP_PKEY *pktmp = NULL; X509_NAME *n = NULL; X509_NAME_ENTRY *ne = NULL; int ok = -1, i, j; long errline; int nid; parms = CONF_load(NULL, infile, &errline); if (parms == NULL) { BIO_printf(bio_err, "error on line %ld of %s\n", errline, infile); goto end; } sk = CONF_get_section(parms, "default"); if (sk_CONF_VALUE_num(sk) == 0) { BIO_printf(bio_err, "no name/value pairs found in %s\n", infile); goto end; } req = X509_REQ_new(); if (req == NULL) goto end; n = X509_REQ_get_subject_name(req); for (i = 0;; i++) { if (sk_CONF_VALUE_num(sk) <= i) break; cv = sk_CONF_VALUE_value(sk, i); type = cv->name; for (buf = cv->name; *buf; buf++) if ((*buf == ':') || (*buf == ',') || (*buf == '.')) { buf++; if (*buf) type = buf; break; } buf = cv->value; if ((nid = OBJ_txt2nid(type)) == NID_undef) { if (strcmp(type, "SPKAC") == 0) { spki = NETSCAPE_SPKI_b64_decode(cv->value, -1); if (spki == NULL) { BIO_printf(bio_err, "unable to load Netscape SPKAC structure\n"); goto end; } } continue; } if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char *)buf, -1, -1, 0)) goto end; } if (spki == NULL) { BIO_printf(bio_err, "Netscape SPKAC structure not found in %s\n", infile); goto end; } BIO_printf(bio_err, "Check that the SPKAC request matches the signature\n"); if ((pktmp = NETSCAPE_SPKI_get_pubkey(spki)) == NULL) { BIO_printf(bio_err, "error unpacking SPKAC public key\n"); goto end; } j = NETSCAPE_SPKI_verify(spki, pktmp); if (j <= 0) { EVP_PKEY_free(pktmp); BIO_printf(bio_err, "signature verification failed on SPKAC public key\n"); goto end; } BIO_printf(bio_err, "Signature ok\n"); X509_REQ_set_pubkey(req, pktmp); EVP_PKEY_free(pktmp); ok = do_body(xret, pkey, x509, dgst, sigopts, policy, db, serial, subj, chtype, multirdn, email_dn, startdate, enddate, days, 1, verbose, req, ext_sect, lconf, certopt, nameopt, default_op, ext_copy, 0, dateopt); end: X509_REQ_free(req); CONF_free(parms); NETSCAPE_SPKI_free(spki); X509_NAME_ENTRY_free(ne); return ok; } static int check_time_format(const char *str) { return ASN1_TIME_set_string(NULL, str); } static int do_revoke(X509 *x509, CA_DB *db, REVINFO_TYPE rev_type, const char *value) { const ASN1_TIME *tm = NULL; char *row[DB_NUMBER], **rrow, **irow; char *rev_str = NULL; BIGNUM *bn = NULL; int ok = -1, i; for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; row[DB_name] = X509_NAME_oneline(X509_get_subject_name(x509), NULL, 0); bn = ASN1_INTEGER_to_BN(X509_get0_serialNumber(x509), NULL); if (!bn) goto end; if (BN_is_zero(bn)) row[DB_serial] = OPENSSL_strdup("00"); else row[DB_serial] = BN_bn2hex(bn); BN_free(bn); if (row[DB_name] != NULL && row[DB_name][0] == '\0') { OPENSSL_free(row[DB_name]); row[DB_name] = OPENSSL_strdup(row[DB_serial]); } if ((row[DB_name] == NULL) || (row[DB_serial] == NULL)) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } rrow = TXT_DB_get_by_index(db->db, DB_serial, row); if (rrow == NULL) { BIO_printf(bio_err, "Adding Entry with serial number %s to DB for %s\n", row[DB_serial], row[DB_name]); row[DB_type] = OPENSSL_strdup("V"); tm = X509_get0_notAfter(x509); row[DB_exp_date] = app_malloc(tm->length + 1, "row exp_data"); memcpy(row[DB_exp_date], tm->data, tm->length); row[DB_exp_date][tm->length] = '\0'; row[DB_rev_date] = NULL; row[DB_file] = OPENSSL_strdup("unknown"); if (row[DB_type] == NULL || row[DB_file] == NULL) { BIO_printf(bio_err, "Memory allocation failure\n"); goto end; } irow = app_malloc(sizeof(*irow) * (DB_NUMBER + 1), "row ptr"); for (i = 0; i < DB_NUMBER; i++) irow[i] = row[i]; irow[DB_NUMBER] = NULL; if (!TXT_DB_insert(db->db, irow)) { BIO_printf(bio_err, "failed to update database\n"); BIO_printf(bio_err, "TXT_DB error number %ld\n", db->db->error); OPENSSL_free(irow); goto end; } for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; if (rev_type == REV_VALID) ok = 1; else ok = do_revoke(x509, db, rev_type, value); goto end; } else if (index_name_cmp_noconst(row, rrow)) { BIO_printf(bio_err, "ERROR:name does not match %s\n", row[DB_name]); goto end; } else if (rev_type == REV_VALID) { BIO_printf(bio_err, "ERROR:Already present, serial number %s\n", row[DB_serial]); goto end; } else if (rrow[DB_type][0] == DB_TYPE_REV) { BIO_printf(bio_err, "ERROR:Already revoked, serial number %s\n", row[DB_serial]); goto end; } else { BIO_printf(bio_err, "Revoking Certificate %s.\n", rrow[DB_serial]); rev_str = make_revocation_str(rev_type, value); if (!rev_str) { BIO_printf(bio_err, "Error in revocation arguments\n"); goto end; } rrow[DB_type][0] = DB_TYPE_REV; rrow[DB_type][1] = '\0'; rrow[DB_rev_date] = rev_str; } ok = 1; end: for (i = 0; i < DB_NUMBER; i++) OPENSSL_free(row[i]); return ok; } static int get_certificate_status(const char *serial, CA_DB *db) { char *row[DB_NUMBER], **rrow; int ok = -1, i; size_t serial_len = strlen(serial); for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; row[DB_serial] = app_malloc(serial_len + 2, "row serial#"); if (serial_len % 2) { row[DB_serial][0] = '0'; memcpy(row[DB_serial] + 1, serial, serial_len); row[DB_serial][serial_len + 1] = '\0'; } else { memcpy(row[DB_serial], serial, serial_len); row[DB_serial][serial_len] = '\0'; } make_uppercase(row[DB_serial]); ok = 1; rrow = TXT_DB_get_by_index(db->db, DB_serial, row); if (rrow == NULL) { BIO_printf(bio_err, "Serial %s not present in db.\n", row[DB_serial]); ok = -1; goto end; } else if (rrow[DB_type][0] == DB_TYPE_VAL) { BIO_printf(bio_err, "%s=Valid (%c)\n", row[DB_serial], rrow[DB_type][0]); goto end; } else if (rrow[DB_type][0] == DB_TYPE_REV) { BIO_printf(bio_err, "%s=Revoked (%c)\n", row[DB_serial], rrow[DB_type][0]); goto end; } else if (rrow[DB_type][0] == DB_TYPE_EXP) { BIO_printf(bio_err, "%s=Expired (%c)\n", row[DB_serial], rrow[DB_type][0]); goto end; } else if (rrow[DB_type][0] == DB_TYPE_SUSP) { BIO_printf(bio_err, "%s=Suspended (%c)\n", row[DB_serial], rrow[DB_type][0]); goto end; } else { BIO_printf(bio_err, "%s=Unknown (%c).\n", row[DB_serial], rrow[DB_type][0]); ok = -1; } end: for (i = 0; i < DB_NUMBER; i++) { OPENSSL_free(row[i]); } return ok; } int do_updatedb(CA_DB *db, time_t *now) { ASN1_TIME *a_tm = NULL; int i, cnt = 0; char **rrow; a_tm = ASN1_TIME_new(); if (a_tm == NULL) return -1; if (X509_time_adj(a_tm, 0, now) == NULL) { ASN1_TIME_free(a_tm); return -1; } for (i = 0; i < sk_OPENSSL_PSTRING_num(db->db->data); i++) { rrow = sk_OPENSSL_PSTRING_value(db->db->data, i); if (rrow[DB_type][0] == DB_TYPE_VAL) { ASN1_TIME *exp_date = NULL; exp_date = ASN1_TIME_new(); if (exp_date == NULL) { ASN1_TIME_free(a_tm); return -1; } if (!ASN1_TIME_set_string(exp_date, rrow[DB_exp_date])) { ASN1_TIME_free(a_tm); ASN1_TIME_free(exp_date); return -1; } if (ASN1_TIME_compare(exp_date, a_tm) <= 0) { rrow[DB_type][0] = DB_TYPE_EXP; rrow[DB_type][1] = '\0'; cnt++; BIO_printf(bio_err, "%s=Expired\n", rrow[DB_serial]); } ASN1_TIME_free(exp_date); } } ASN1_TIME_free(a_tm); return cnt; } static const char *crl_reasons[] = { "unspecified", "keyCompromise", "CACompromise", "affiliationChanged", "superseded", "cessationOfOperation", "certificateHold", "removeFromCRL", "holdInstruction", "keyTime", "CAkeyTime" }; #define NUM_REASONS OSSL_NELEM(crl_reasons) static char *make_revocation_str(REVINFO_TYPE rev_type, const char *rev_arg) { char *str; const char *reason = NULL, *other = NULL; ASN1_OBJECT *otmp; ASN1_UTCTIME *revtm = NULL; int i; switch (rev_type) { case REV_NONE: case REV_VALID: break; case REV_CRL_REASON: for (i = 0; i < 8; i++) { if (OPENSSL_strcasecmp(rev_arg, crl_reasons[i]) == 0) { reason = crl_reasons[i]; break; } } if (reason == NULL) { BIO_printf(bio_err, "Unknown CRL reason %s\n", rev_arg); return NULL; } break; case REV_HOLD: otmp = OBJ_txt2obj(rev_arg, 0); ASN1_OBJECT_free(otmp); if (otmp == NULL) { BIO_printf(bio_err, "Invalid object identifier %s\n", rev_arg); return NULL; } reason = "holdInstruction"; other = rev_arg; break; case REV_KEY_COMPROMISE: case REV_CA_COMPROMISE: if (!ASN1_GENERALIZEDTIME_set_string(NULL, rev_arg)) { BIO_printf(bio_err, "Invalid time format %s. Need YYYYMMDDHHMMSSZ\n", rev_arg); return NULL; } other = rev_arg; if (rev_type == REV_KEY_COMPROMISE) reason = "keyTime"; else reason = "CAkeyTime"; break; } revtm = X509_gmtime_adj(NULL, 0); if (!revtm) return NULL; i = revtm->length + 1; if (reason) i += strlen(reason) + 1; if (other) i += strlen(other) + 1; str = app_malloc(i, "revocation reason"); OPENSSL_strlcpy(str, (char *)revtm->data, i); if (reason) { OPENSSL_strlcat(str, ",", i); OPENSSL_strlcat(str, reason, i); } if (other) { OPENSSL_strlcat(str, ",", i); OPENSSL_strlcat(str, other, i); } ASN1_UTCTIME_free(revtm); return str; } static int make_revoked(X509_REVOKED *rev, const char *str) { char *tmp = NULL; int reason_code = -1; int i, ret = 0; ASN1_OBJECT *hold = NULL; ASN1_GENERALIZEDTIME *comp_time = NULL; ASN1_ENUMERATED *rtmp = NULL; ASN1_TIME *revDate = NULL; i = unpack_revinfo(&revDate, &reason_code, &hold, &comp_time, str); if (i == 0) goto end; if (rev && !X509_REVOKED_set_revocationDate(rev, revDate)) goto end; if (rev && (reason_code != OCSP_REVOKED_STATUS_NOSTATUS)) { rtmp = ASN1_ENUMERATED_new(); if (rtmp == NULL || !ASN1_ENUMERATED_set(rtmp, reason_code)) goto end; if (X509_REVOKED_add1_ext_i2d(rev, NID_crl_reason, rtmp, 0, 0) <= 0) goto end; } if (rev && comp_time) { if (X509_REVOKED_add1_ext_i2d (rev, NID_invalidity_date, comp_time, 0, 0) <= 0) goto end; } if (rev && hold) { if (X509_REVOKED_add1_ext_i2d (rev, NID_hold_instruction_code, hold, 0, 0) <= 0) goto end; } if (reason_code != OCSP_REVOKED_STATUS_NOSTATUS) ret = 2; else ret = 1; end: OPENSSL_free(tmp); ASN1_OBJECT_free(hold); ASN1_GENERALIZEDTIME_free(comp_time); ASN1_ENUMERATED_free(rtmp); ASN1_TIME_free(revDate); return ret; } static int old_entry_print(const ASN1_OBJECT *obj, const ASN1_STRING *str) { char buf[25], *pbuf; const char *p; int j; j = i2a_ASN1_OBJECT(bio_err, obj); pbuf = buf; for (j = 22 - j; j > 0; j--) *(pbuf++) = ' '; *(pbuf++) = ':'; *(pbuf++) = '\0'; BIO_puts(bio_err, buf); if (str->type == V_ASN1_PRINTABLESTRING) BIO_printf(bio_err, "PRINTABLE:'"); else if (str->type == V_ASN1_T61STRING) BIO_printf(bio_err, "T61STRING:'"); else if (str->type == V_ASN1_IA5STRING) BIO_printf(bio_err, "IA5STRING:'"); else if (str->type == V_ASN1_UNIVERSALSTRING) BIO_printf(bio_err, "UNIVERSALSTRING:'"); else BIO_printf(bio_err, "ASN.1 %2d:'", str->type); p = (const char *)str->data; for (j = str->length; j > 0; j--) { if ((*p >= ' ') && (*p <= '~')) BIO_printf(bio_err, "%c", *p); else if (*p & 0x80) BIO_printf(bio_err, "\\0x%02X", *p); else if ((unsigned char)*p == 0xf7) BIO_printf(bio_err, "^?"); else BIO_printf(bio_err, "^%c", *p + '@'); p++; } BIO_printf(bio_err, "'\n"); return 1; } int unpack_revinfo(ASN1_TIME **prevtm, int *preason, ASN1_OBJECT **phold, ASN1_GENERALIZEDTIME **pinvtm, const char *str) { char *tmp; char *rtime_str, *reason_str = NULL, *arg_str = NULL, *p; int reason_code = -1; int ret = 0; unsigned int i; ASN1_OBJECT *hold = NULL; ASN1_GENERALIZEDTIME *comp_time = NULL; tmp = OPENSSL_strdup(str); if (!tmp) { BIO_printf(bio_err, "memory allocation failure\n"); goto end; } p = strchr(tmp, ','); rtime_str = tmp; if (p) { *p = '\0'; p++; reason_str = p; p = strchr(p, ','); if (p) { *p = '\0'; arg_str = p + 1; } } if (prevtm) { *prevtm = ASN1_UTCTIME_new(); if (*prevtm == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); goto end; } if (!ASN1_UTCTIME_set_string(*prevtm, rtime_str)) { BIO_printf(bio_err, "invalid revocation date %s\n", rtime_str); goto end; } } if (reason_str) { for (i = 0; i < NUM_REASONS; i++) { if (OPENSSL_strcasecmp(reason_str, crl_reasons[i]) == 0) { reason_code = i; break; } } if (reason_code == OCSP_REVOKED_STATUS_NOSTATUS) { BIO_printf(bio_err, "invalid reason code %s\n", reason_str); goto end; } if (reason_code == 7) { reason_code = OCSP_REVOKED_STATUS_REMOVEFROMCRL; } else if (reason_code == 8) { if (!arg_str) { BIO_printf(bio_err, "missing hold instruction\n"); goto end; } reason_code = OCSP_REVOKED_STATUS_CERTIFICATEHOLD; hold = OBJ_txt2obj(arg_str, 0); if (!hold) { BIO_printf(bio_err, "invalid object identifier %s\n", arg_str); goto end; } if (phold) *phold = hold; else ASN1_OBJECT_free(hold); } else if ((reason_code == 9) || (reason_code == 10)) { if (!arg_str) { BIO_printf(bio_err, "missing compromised time\n"); goto end; } comp_time = ASN1_GENERALIZEDTIME_new(); if (comp_time == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); goto end; } if (!ASN1_GENERALIZEDTIME_set_string(comp_time, arg_str)) { BIO_printf(bio_err, "invalid compromised time %s\n", arg_str); goto end; } if (reason_code == 9) reason_code = OCSP_REVOKED_STATUS_KEYCOMPROMISE; else reason_code = OCSP_REVOKED_STATUS_CACOMPROMISE; } } if (preason) *preason = reason_code; if (pinvtm) { *pinvtm = comp_time; comp_time = NULL; } ret = 1; end: OPENSSL_free(tmp); ASN1_GENERALIZEDTIME_free(comp_time); return ret; }
apps
openssl/apps/ca.c
openssl
#include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/dsa.h> #include <openssl/dh.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/core_names.h> #include <openssl/core_dispatch.h> #include <openssl/param_build.h> #include <openssl/encoder.h> #include <openssl/decoder.h> #define DEFBITS 2048 static EVP_PKEY *dsa_to_dh(EVP_PKEY *dh); static int verbose = 1; typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENGINE, OPT_CHECK, OPT_TEXT, OPT_NOOUT, OPT_DSAPARAM, OPT_2, OPT_3, OPT_5, OPT_VERBOSE, OPT_QUIET, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS dhparam_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [numbits]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"check", OPT_CHECK, '-', "Check the DH parameters"}, #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_DEPRECATED_3_0) {"dsaparam", OPT_DSAPARAM, '-', "Read or generate DSA parameters, convert to DH"}, #endif #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"inform", OPT_INFORM, 'F', "Input format, DER or PEM"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format, DER or PEM"}, {"text", OPT_TEXT, '-', "Print a text form of the DH parameters"}, {"noout", OPT_NOOUT, '-', "Don't output any DH parameters"}, {"2", OPT_2, '-', "Generate parameters using 2 as the generator value"}, {"3", OPT_3, '-', "Generate parameters using 3 as the generator value"}, {"5", OPT_5, '-', "Generate parameters using 5 as the generator value"}, {"verbose", OPT_VERBOSE, '-', "Verbose output"}, {"quiet", OPT_QUIET, '-', "Terse output"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"numbits", 0, 0, "Number of bits if generating parameters (optional)"}, {NULL} }; int dhparam_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; EVP_PKEY *pkey = NULL, *tmppkey = NULL; EVP_PKEY_CTX *ctx = NULL; char *infile = NULL, *outfile = NULL, *prog; ENGINE *e = NULL; int dsaparam = 0; int text = 0, ret = 1, num = 0, g = 0; int informat = FORMAT_PEM, outformat = FORMAT_PEM, check = 0, noout = 0; OPTION_CHOICE o; prog = opt_init(argc, argv, dhparam_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(dhparam_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_CHECK: check = 1; break; case OPT_TEXT: text = 1; break; case OPT_DSAPARAM: dsaparam = 1; break; case OPT_2: g = 2; break; case OPT_3: g = 3; break; case OPT_5: g = 5; break; case OPT_NOOUT: noout = 1; break; case OPT_VERBOSE: verbose = 1; break; case OPT_QUIET: verbose = 0; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } argc = opt_num_rest(); argv = opt_rest(); if (argc == 1) { if (!opt_int(argv[0], &num) || num <= 0) goto opthelp; } else if (!opt_check_rest_arg(NULL)) { goto opthelp; } if (!app_RAND_load()) goto end; if (g && !num) num = DEFBITS; if (dsaparam && g) { BIO_printf(bio_err, "Error, generator may not be chosen for DSA parameters\n"); goto end; } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (num && !g) g = 2; if (num) { const char *alg = dsaparam ? "DSA" : "DH"; if (infile != NULL) { BIO_printf(bio_err, "Warning, input file %s ignored\n", infile); } ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), alg, app_get0_propq()); if (ctx == NULL) { BIO_printf(bio_err, "Error, %s param generation context allocation failed\n", alg); goto end; } EVP_PKEY_CTX_set_app_data(ctx, bio_err); if (verbose) { EVP_PKEY_CTX_set_cb(ctx, progress_cb); BIO_printf(bio_err, "Generating %s parameters, %d bit long %sprime\n", alg, num, dsaparam ? "" : "safe "); } if (EVP_PKEY_paramgen_init(ctx) <= 0) { BIO_printf(bio_err, "Error, unable to initialise %s parameters\n", alg); goto end; } if (dsaparam) { if (EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, num) <= 0) { BIO_printf(bio_err, "Error, unable to set DSA prime length\n"); goto end; } } else { if (EVP_PKEY_CTX_set_dh_paramgen_prime_len(ctx, num) <= 0) { BIO_printf(bio_err, "Error, unable to set DH prime length\n"); goto end; } if (EVP_PKEY_CTX_set_dh_paramgen_generator(ctx, g) <= 0) { BIO_printf(bio_err, "Error, unable to set generator\n"); goto end; } } tmppkey = app_paramgen(ctx, alg); if (tmppkey == NULL) goto end; EVP_PKEY_CTX_free(ctx); ctx = NULL; if (dsaparam) { pkey = dsa_to_dh(tmppkey); if (pkey == NULL) goto end; EVP_PKEY_free(tmppkey); } else { pkey = tmppkey; } tmppkey = NULL; } else { OSSL_DECODER_CTX *decoderctx = NULL; const char *keytype = "DH"; int done; in = bio_open_default(infile, 'r', informat); if (in == NULL) goto end; do { done = 1; decoderctx = OSSL_DECODER_CTX_new_for_pkey(&tmppkey, (informat == FORMAT_ASN1) ? "DER" : "PEM", NULL, (informat == FORMAT_ASN1) ? keytype : NULL, OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS, NULL, NULL); if (decoderctx != NULL && !OSSL_DECODER_from_bio(decoderctx, in) && informat == FORMAT_ASN1 && strcmp(keytype, "DH") == 0) { keytype = "DHX"; if (BIO_reset(in) == 0) done = 0; } OSSL_DECODER_CTX_free(decoderctx); } while (!done); if (tmppkey == NULL) { BIO_printf(bio_err, "Error, unable to load parameters\n"); goto end; } if (dsaparam) { if (!EVP_PKEY_is_a(tmppkey, "DSA")) { BIO_printf(bio_err, "Error, unable to load DSA parameters\n"); goto end; } pkey = dsa_to_dh(tmppkey); if (pkey == NULL) goto end; } else { if (!EVP_PKEY_is_a(tmppkey, "DH") && !EVP_PKEY_is_a(tmppkey, "DHX")) { BIO_printf(bio_err, "Error, unable to load DH parameters\n"); goto end; } pkey = tmppkey; tmppkey = NULL; } } if (text) EVP_PKEY_print_params(out, pkey, 4, NULL); if (check) { ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); if (ctx == NULL) { BIO_printf(bio_err, "Error, failed to check DH parameters\n"); goto end; } if (EVP_PKEY_param_check(ctx) <= 0) { BIO_printf(bio_err, "Error, invalid parameters generated\n"); goto end; } BIO_printf(bio_err, "DH parameters appear to be ok.\n"); } if (!noout) { OSSL_ENCODER_CTX *ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS, outformat == FORMAT_ASN1 ? "DER" : "PEM", NULL, NULL); if (ectx == NULL || !OSSL_ENCODER_to_bio(ectx, out)) { OSSL_ENCODER_CTX_free(ectx); BIO_printf(bio_err, "Error, unable to write DH parameters\n"); goto end; } OSSL_ENCODER_CTX_free(ectx); } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); BIO_free(in); BIO_free_all(out); EVP_PKEY_free(pkey); EVP_PKEY_free(tmppkey); EVP_PKEY_CTX_free(ctx); release_engine(e); return ret; } static EVP_PKEY *dsa_to_dh(EVP_PKEY *dh) { OSSL_PARAM_BLD *tmpl = NULL; OSSL_PARAM *params = NULL; BIGNUM *bn_p = NULL, *bn_q = NULL, *bn_g = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; if (!EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_P, &bn_p) || !EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_Q, &bn_q) || !EVP_PKEY_get_bn_param(dh, OSSL_PKEY_PARAM_FFC_G, &bn_g)) { BIO_printf(bio_err, "Error, failed to set DH parameters\n"); goto err; } if ((tmpl = OSSL_PARAM_BLD_new()) == NULL || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, bn_p) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_Q, bn_q) || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, bn_g) || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) { BIO_printf(bio_err, "Error, failed to set DH parameters\n"); goto err; } ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), "DHX", app_get0_propq()); if (ctx == NULL || EVP_PKEY_fromdata_init(ctx) <= 0 || EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, params) <= 0) { BIO_printf(bio_err, "Error, failed to set DH parameters\n"); goto err; } err: EVP_PKEY_CTX_free(ctx); OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(tmpl); BN_free(bn_p); BN_free(bn_q); BN_free(bn_g); return pkey; }
apps
openssl/apps/dhparam.c
openssl
#include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/asn1.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/pkcs12.h> #include <openssl/provider.h> #include <openssl/kdf.h> #include <openssl/rand.h> #define NOKEYS 0x1 #define NOCERTS 0x2 #define INFO 0x4 #define CLCERTS 0x8 #define CACERTS 0x10 #define PASSWD_BUF_SIZE 2048 #define WARN_EXPORT(opt) \ BIO_printf(bio_err, "Warning: -%s option ignored with -export\n", opt); #define WARN_NO_EXPORT(opt) \ BIO_printf(bio_err, "Warning: -%s option ignored without -export\n", opt); static int get_cert_chain(X509 *cert, X509_STORE *store, STACK_OF(X509) *untrusted_certs, STACK_OF(X509) **chain); int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc); int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc); int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bags, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc); void print_attribute(BIO *out, const ASN1_TYPE *av); int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst, const char *name); void hex_prin(BIO *out, unsigned char *buf, int len); static int alg_print(const X509_ALGOR *alg); int cert_load(BIO *in, STACK_OF(X509) *sk); static int set_pbe(int *ppbe, const char *str); static int jdk_trust(PKCS12_SAFEBAG *bag, void *cbarg); typedef enum OPTION_choice { OPT_COMMON, OPT_CIPHER, OPT_NOKEYS, OPT_KEYEX, OPT_KEYSIG, OPT_NOCERTS, OPT_CLCERTS, OPT_CACERTS, OPT_NOOUT, OPT_INFO, OPT_CHAIN, OPT_TWOPASS, OPT_NOMACVER, #ifndef OPENSSL_NO_DES OPT_DESCERT, #endif OPT_EXPORT, OPT_ITER, OPT_NOITER, OPT_MACITER, OPT_NOMACITER, OPT_MACSALTLEN, OPT_NOMAC, OPT_LMK, OPT_NODES, OPT_NOENC, OPT_MACALG, OPT_CERTPBE, OPT_KEYPBE, OPT_INKEY, OPT_CERTFILE, OPT_UNTRUSTED, OPT_PASSCERTS, OPT_NAME, OPT_CSP, OPT_CANAME, OPT_IN, OPT_OUT, OPT_PASSIN, OPT_PASSOUT, OPT_PASSWORD, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_ENGINE, OPT_R_ENUM, OPT_PROV_ENUM, OPT_JDKTRUST, #ifndef OPENSSL_NO_DES OPT_LEGACY_ALG #endif } OPTION_CHOICE; const OPTIONS pkcs12_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"in", OPT_IN, '<', "Input file"}, {"out", OPT_OUT, '>', "Output file"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"password", OPT_PASSWORD, 's', "Set PKCS#12 import/export password source"}, {"twopass", OPT_TWOPASS, '-', "Separate MAC, encryption passwords"}, {"nokeys", OPT_NOKEYS, '-', "Don't output private keys"}, {"nocerts", OPT_NOCERTS, '-', "Don't output certificates"}, {"noout", OPT_NOOUT, '-', "Don't output anything, just verify PKCS#12 input"}, #ifndef OPENSSL_NO_DES {"legacy", OPT_LEGACY_ALG, '-', # ifdef OPENSSL_NO_RC2 "Use legacy encryption algorithm 3DES_CBC for keys and certs" # else "Use legacy encryption: 3DES_CBC for keys, RC2_CBC for certs" # endif }, #endif #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_PROV_OPTIONS, OPT_R_OPTIONS, OPT_SECTION("PKCS#12 import (parsing PKCS#12)"), {"info", OPT_INFO, '-', "Print info about PKCS#12 structure"}, {"nomacver", OPT_NOMACVER, '-', "Don't verify integrity MAC"}, {"clcerts", OPT_CLCERTS, '-', "Only output client certificates"}, {"cacerts", OPT_CACERTS, '-', "Only output CA certificates"}, {"", OPT_CIPHER, '-', "Any supported cipher for output encryption"}, {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"}, {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"}, OPT_SECTION("PKCS#12 output (export)"), {"export", OPT_EXPORT, '-', "Create PKCS12 file"}, {"inkey", OPT_INKEY, 's', "Private key, else read from -in input file"}, {"certfile", OPT_CERTFILE, '<', "Extra certificates for PKCS12 output"}, {"passcerts", OPT_PASSCERTS, 's', "Certificate file pass phrase source"}, {"chain", OPT_CHAIN, '-', "Build and add certificate chain for EE cert,"}, {OPT_MORE_STR, 0, 0, "which is the 1st cert from -in matching the private key (if given)"}, {"untrusted", OPT_UNTRUSTED, '<', "Untrusted certificates for chain building"}, {"CAfile", OPT_CAFILE, '<', "PEM-format file of CA's"}, {"CApath", OPT_CAPATH, '/', "PEM-format directory of CA's"}, {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, {"name", OPT_NAME, 's', "Use name as friendly name"}, {"caname", OPT_CANAME, 's', "Use name as CA friendly name (can be repeated)"}, {"CSP", OPT_CSP, 's', "Microsoft CSP name"}, {"LMK", OPT_LMK, '-', "Add local machine keyset attribute to private key"}, {"keyex", OPT_KEYEX, '-', "Set key type to MS key exchange"}, {"keysig", OPT_KEYSIG, '-', "Set key type to MS key signature"}, {"keypbe", OPT_KEYPBE, 's', "Private key PBE algorithm (default AES-256 CBC)"}, {"certpbe", OPT_CERTPBE, 's', "Certificate PBE algorithm (default PBES2 with PBKDF2 and AES-256 CBC)"}, #ifndef OPENSSL_NO_DES {"descert", OPT_DESCERT, '-', "Encrypt output with 3DES (default PBES2 with PBKDF2 and AES-256 CBC)"}, #endif {"macalg", OPT_MACALG, 's', "Digest algorithm to use in MAC (default SHA256)"}, {"iter", OPT_ITER, 'p', "Specify the iteration count for encryption and MAC"}, {"noiter", OPT_NOITER, '-', "Don't use encryption iteration"}, {"nomaciter", OPT_NOMACITER, '-', "Don't use MAC iteration)"}, {"maciter", OPT_MACITER, '-', "Unused, kept for backwards compatibility"}, {"macsaltlen", OPT_MACSALTLEN, 'p', "Specify the salt len for MAC"}, {"nomac", OPT_NOMAC, '-', "Don't generate MAC"}, {"jdktrust", OPT_JDKTRUST, 's', "Mark certificate in PKCS#12 store as trusted for JDK compatibility"}, {NULL} }; int pkcs12_main(int argc, char **argv) { char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL; char *untrusted = NULL, *ciphername = NULL, *enc_name = NULL; char *passcertsarg = NULL, *passcerts = NULL; char *name = NULL, *csp_name = NULL; char pass[PASSWD_BUF_SIZE] = "", macpass[PASSWD_BUF_SIZE] = ""; int export_pkcs12 = 0, options = 0, chain = 0, twopass = 0, keytype = 0; char *jdktrust = NULL; #ifndef OPENSSL_NO_DES int use_legacy = 0; #endif int iter = 0, maciter = 0; int macsaltlen = PKCS12_SALT_LEN; int cert_pbe = NID_undef; int key_pbe = NID_undef; int ret = 1, macver = 1, add_lmk = 0, private = 0; int noprompt = 0; char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL; char *passin = NULL, *passout = NULL, *macalg = NULL; char *cpass = NULL, *mpass = NULL, *badpass = NULL; const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL, *prog; int noCApath = 0, noCAfile = 0, noCAstore = 0; ENGINE *e = NULL; BIO *in = NULL, *out = NULL; PKCS12 *p12 = NULL; STACK_OF(OPENSSL_STRING) *canames = NULL; EVP_CIPHER *default_enc = (EVP_CIPHER *)EVP_aes_256_cbc(); EVP_CIPHER *enc = (EVP_CIPHER *)default_enc; OPTION_CHOICE o; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, pkcs12_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(pkcs12_options); ret = 0; goto end; case OPT_NOKEYS: options |= NOKEYS; break; case OPT_KEYEX: keytype = KEY_EX; break; case OPT_KEYSIG: keytype = KEY_SIG; break; case OPT_NOCERTS: options |= NOCERTS; break; case OPT_CLCERTS: options |= CLCERTS; break; case OPT_CACERTS: options |= CACERTS; break; case OPT_NOOUT: options |= (NOKEYS | NOCERTS); break; case OPT_JDKTRUST: jdktrust = opt_arg(); options |= NOKEYS; break; case OPT_INFO: options |= INFO; break; case OPT_CHAIN: chain = 1; break; case OPT_TWOPASS: twopass = 1; break; case OPT_NOMACVER: macver = 0; break; #ifndef OPENSSL_NO_DES case OPT_DESCERT: cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; break; #endif case OPT_EXPORT: export_pkcs12 = 1; break; case OPT_NODES: case OPT_NOENC: enc_name = opt_flag() + 1; enc = NULL; ciphername = NULL; break; case OPT_CIPHER: enc_name = ciphername = opt_unknown(); break; case OPT_ITER: maciter = iter = opt_int_arg(); break; case OPT_NOITER: iter = 1; break; case OPT_MACITER: break; case OPT_NOMACITER: maciter = 1; break; case OPT_MACSALTLEN: macsaltlen = opt_int_arg(); break; case OPT_NOMAC: cert_pbe = -1; maciter = -1; break; case OPT_MACALG: macalg = opt_arg(); break; case OPT_CERTPBE: if (!set_pbe(&cert_pbe, opt_arg())) goto opthelp; break; case OPT_KEYPBE: if (!set_pbe(&key_pbe, opt_arg())) goto opthelp; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_INKEY: keyname = opt_arg(); break; case OPT_CERTFILE: certfile = opt_arg(); break; case OPT_UNTRUSTED: untrusted = opt_arg(); break; case OPT_PASSCERTS: passcertsarg = opt_arg(); break; case OPT_NAME: name = opt_arg(); break; case OPT_LMK: add_lmk = 1; break; case OPT_CSP: csp_name = opt_arg(); break; case OPT_CANAME: if (canames == NULL && (canames = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(canames, opt_arg()); break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_PASSWORD: passarg = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; #ifndef OPENSSL_NO_DES case OPT_LEGACY_ALG: use_legacy = 1; break; #endif case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (!opt_cipher_any(ciphername, &enc)) goto opthelp; if (export_pkcs12) { if ((options & INFO) != 0) WARN_EXPORT("info"); if (macver == 0) WARN_EXPORT("nomacver"); if ((options & CLCERTS) != 0) WARN_EXPORT("clcerts"); if ((options & CACERTS) != 0) WARN_EXPORT("cacerts"); if (enc != default_enc) BIO_printf(bio_err, "Warning: output encryption option -%s ignored with -export\n", enc_name); } else { if (keyname != NULL) WARN_NO_EXPORT("inkey"); if (certfile != NULL) WARN_NO_EXPORT("certfile"); if (passcertsarg != NULL) WARN_NO_EXPORT("passcerts"); if (chain) WARN_NO_EXPORT("chain"); if (untrusted != NULL) WARN_NO_EXPORT("untrusted"); if (CAfile != NULL) WARN_NO_EXPORT("CAfile"); if (CApath != NULL) WARN_NO_EXPORT("CApath"); if (CAstore != NULL) WARN_NO_EXPORT("CAstore"); if (noCAfile) WARN_NO_EXPORT("no-CAfile"); if (noCApath) WARN_NO_EXPORT("no-CApath"); if (noCAstore) WARN_NO_EXPORT("no-CAstore"); if (name != NULL) WARN_NO_EXPORT("name"); if (canames != NULL) WARN_NO_EXPORT("caname"); if (csp_name != NULL) WARN_NO_EXPORT("CSP"); if (add_lmk) WARN_NO_EXPORT("LMK"); if (keytype == KEY_EX) WARN_NO_EXPORT("keyex"); if (keytype == KEY_SIG) WARN_NO_EXPORT("keysig"); if (key_pbe != NID_undef) WARN_NO_EXPORT("keypbe"); if (cert_pbe != NID_undef && cert_pbe != -1) WARN_NO_EXPORT("certpbe and -descert"); if (macalg != NULL) WARN_NO_EXPORT("macalg"); if (iter != 0) WARN_NO_EXPORT("iter and -noiter"); if (maciter == 1) WARN_NO_EXPORT("nomaciter"); if (cert_pbe == -1 && maciter == -1) WARN_NO_EXPORT("nomac"); if (macsaltlen != PKCS12_SALT_LEN) WARN_NO_EXPORT("macsaltlen"); } #ifndef OPENSSL_NO_DES if (use_legacy) { if (!OSSL_PROVIDER_available(app_get0_libctx(), "legacy")) { if (!app_provider_load(app_get0_libctx(), "legacy")) goto end; if (!app_provider_load(app_get0_libctx(), "default")) goto end; } if (cert_pbe == NID_undef) { # ifndef OPENSSL_NO_RC2 cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC; # else cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; # endif } if (key_pbe == NID_undef) key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; if (enc == default_enc) enc = (EVP_CIPHER *)EVP_des_ede3_cbc(); if (macalg == NULL) macalg = "sha1"; } #endif private = 1; if (!app_passwd(passcertsarg, NULL, &passcerts, NULL)) { BIO_printf(bio_err, "Error getting certificate file password\n"); goto end; } if (passarg != NULL) { if (export_pkcs12) passoutarg = passarg; else passinarg = passarg; } if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if (cpass == NULL) { if (export_pkcs12) cpass = passout; else cpass = passin; } if (cpass != NULL) { mpass = cpass; noprompt = 1; if (twopass) { if (export_pkcs12) BIO_printf(bio_err, "Option -twopass cannot be used with -passout or -password\n"); else BIO_printf(bio_err, "Option -twopass cannot be used with -passin or -password\n"); goto end; } } else { cpass = pass; mpass = macpass; } if (twopass) { if (1) { #ifndef OPENSSL_NO_UI_CONSOLE if (EVP_read_pw_string( macpass, sizeof(macpass), "Enter MAC Password:", export_pkcs12)) { BIO_printf(bio_err, "Can't read Password\n"); goto end; } } else { #endif BIO_printf(bio_err, "Unsupported option -twopass\n"); goto end; } } if (export_pkcs12) { EVP_PKEY *key = NULL; X509 *ee_cert = NULL, *x = NULL; STACK_OF(X509) *certs = NULL; STACK_OF(X509) *untrusted_certs = NULL; EVP_MD *macmd = NULL; unsigned char *catmp = NULL; int i; ASN1_OBJECT *obj = NULL; if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) { BIO_printf(bio_err, "Nothing to export due to -noout or -nocerts and -nokeys\n"); goto export_end; } if ((options & NOCERTS) != 0) { chain = 0; BIO_printf(bio_err, "Warning: -chain option ignored with -nocerts\n"); } if (!(options & NOKEYS)) { key = load_key(keyname ? keyname : infile, FORMAT_PEM, 1, passin, e, keyname ? "private key from -inkey file" : "private key from -in file"); if (key == NULL) goto export_end; } if (!(options & NOCERTS)) { if (!load_certs(infile, 1, &certs, passin, "certificates from -in file")) goto export_end; if (sk_X509_num(certs) < 1) { BIO_printf(bio_err, "No certificate in -in file %s\n", infile); goto export_end; } if (key != NULL) { for (i = 0; i < sk_X509_num(certs); i++) { x = sk_X509_value(certs, i); if (cert_matches_key(x, key)) { ee_cert = x; X509_keyid_set1(ee_cert, NULL, 0); X509_alias_set1(ee_cert, NULL, 0); (void)sk_X509_delete(certs, i); break; } } if (ee_cert == NULL) { BIO_printf(bio_err, "No cert in -in file '%s' matches private key\n", infile); goto export_end; } } } if (untrusted != NULL) { if (!load_certs(untrusted, 0, &untrusted_certs, passcerts, "untrusted certificates")) goto export_end; } if (chain) { int vret; STACK_OF(X509) *chain2; X509_STORE *store; X509 *ee_cert_tmp = ee_cert; if (ee_cert_tmp == NULL && certs != NULL) ee_cert_tmp = sk_X509_value(certs, 0); if (ee_cert_tmp == NULL) { BIO_printf(bio_err, "No end entity certificate to check with -chain\n"); goto export_end; } if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) == NULL) goto export_end; vret = get_cert_chain(ee_cert_tmp, store, untrusted_certs, &chain2); X509_STORE_free(store); if (vret == X509_V_OK) { int add_certs; X509_free(sk_X509_shift(chain2)); add_certs = X509_add_certs(certs, chain2, X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP); OSSL_STACK_OF_X509_free(chain2); if (!add_certs) goto export_end; } else { if (vret != X509_V_ERR_UNSPECIFIED) BIO_printf(bio_err, "Error getting chain: %s\n", X509_verify_cert_error_string(vret)); goto export_end; } } if (certfile != NULL) { if (!load_certs(certfile, 0, &certs, passcerts, "extra certificates from -certfile")) goto export_end; } for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) { catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i); X509_alias_set1(sk_X509_value(certs, i), catmp, -1); } if (csp_name != NULL && key != NULL) EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name, MBSTRING_ASC, (unsigned char *)csp_name, -1); if (add_lmk && key != NULL) EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1); if (!noprompt && !(enc == NULL && maciter == -1)) { if (1) { #ifndef OPENSSL_NO_UI_CONSOLE if (EVP_read_pw_string(pass, sizeof(pass), "Enter Export Password:", 1)) { BIO_printf(bio_err, "Can't read Password\n"); goto export_end; } } else { #endif BIO_printf(bio_err, "Password required\n"); goto export_end; } } if (!twopass) OPENSSL_strlcpy(macpass, pass, sizeof(macpass)); if (jdktrust != NULL) { obj = OBJ_txt2obj(jdktrust, 0); } p12 = PKCS12_create_ex2(cpass, name, key, ee_cert, certs, key_pbe, cert_pbe, iter, -1, keytype, app_get0_libctx(), app_get0_propq(), jdk_trust, (void*)obj); if (p12 == NULL) { BIO_printf(bio_err, "Error creating PKCS12 structure for %s\n", outfile); goto export_end; } if (macalg != NULL) { if (!opt_md(macalg, &macmd)) goto opthelp; } if (maciter != -1) { if (!PKCS12_set_mac(p12, mpass, -1, NULL, macsaltlen, maciter, macmd)) { BIO_printf(bio_err, "Error creating PKCS12 MAC; no PKCS12KDF support?\n"); BIO_printf(bio_err, "Use -nomac if MAC not required and PKCS12KDF support not available.\n"); goto export_end; } } assert(private); out = bio_open_owner(outfile, FORMAT_PKCS12, private); if (out == NULL) goto end; i2d_PKCS12_bio(out, p12); ret = 0; export_end: EVP_PKEY_free(key); EVP_MD_free(macmd); OSSL_STACK_OF_X509_free(certs); OSSL_STACK_OF_X509_free(untrusted_certs); X509_free(ee_cert); ASN1_OBJECT_free(obj); ERR_print_errors(bio_err); goto end; } in = bio_open_default(infile, 'r', FORMAT_PKCS12); if (in == NULL) goto end; out = bio_open_owner(outfile, FORMAT_PEM, private); if (out == NULL) goto end; p12 = PKCS12_init_ex(NID_pkcs7_data, app_get0_libctx(), app_get0_propq()); if (p12 == NULL) { ERR_print_errors(bio_err); goto end; } if ((p12 = d2i_PKCS12_bio(in, &p12)) == NULL) { ERR_print_errors(bio_err); goto end; } if (!noprompt) { if (1) { #ifndef OPENSSL_NO_UI_CONSOLE if (EVP_read_pw_string(pass, sizeof(pass), "Enter Import Password:", 0)) { BIO_printf(bio_err, "Can't read Password\n"); goto end; } } else { #endif BIO_printf(bio_err, "Password required\n"); goto end; } } if (!twopass) OPENSSL_strlcpy(macpass, pass, sizeof(macpass)); if ((options & INFO) && PKCS12_mac_present(p12)) { const ASN1_INTEGER *tmaciter; const X509_ALGOR *macalgid; const ASN1_OBJECT *macobj; const ASN1_OCTET_STRING *tmac; const ASN1_OCTET_STRING *tsalt; PKCS12_get0_mac(&tmac, &macalgid, &tsalt, &tmaciter, p12); X509_ALGOR_get0(&macobj, NULL, NULL, macalgid); BIO_puts(bio_err, "MAC: "); i2a_ASN1_OBJECT(bio_err, macobj); BIO_printf(bio_err, ", Iteration %ld\n", tmaciter != NULL ? ASN1_INTEGER_get(tmaciter) : 1L); BIO_printf(bio_err, "MAC length: %ld, salt length: %ld\n", tmac != NULL ? ASN1_STRING_length(tmac) : 0L, tsalt != NULL ? ASN1_STRING_length(tsalt) : 0L); } if (macver) { EVP_KDF *pkcs12kdf; pkcs12kdf = EVP_KDF_fetch(app_get0_libctx(), "PKCS12KDF", app_get0_propq()); if (pkcs12kdf == NULL) { BIO_printf(bio_err, "Error verifying PKCS12 MAC; no PKCS12KDF support.\n"); BIO_printf(bio_err, "Use -nomacver if MAC verification is not required.\n"); goto end; } EVP_KDF_free(pkcs12kdf); if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) { if (!twopass) cpass = NULL; } else if (!PKCS12_verify_mac(p12, mpass, -1)) { unsigned char *utmp; int utmplen; unsigned long err = ERR_peek_error(); if (ERR_GET_LIB(err) == ERR_LIB_PKCS12 && ERR_GET_REASON(err) == PKCS12_R_MAC_ABSENT) { BIO_printf(bio_err, "Warning: MAC is absent!\n"); goto dump; } utmp = OPENSSL_asc2uni(mpass, -1, NULL, &utmplen); if (utmp == NULL) goto end; badpass = OPENSSL_uni2utf8(utmp, utmplen); OPENSSL_free(utmp); if (!PKCS12_verify_mac(p12, badpass, -1)) { BIO_printf(bio_err, "Mac verify error: invalid password?\n"); ERR_print_errors(bio_err); goto end; } else { BIO_printf(bio_err, "Warning: using broken algorithm\n"); if (!twopass) cpass = badpass; } } } dump: assert(private); if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) { BIO_printf(bio_err, "Error outputting keys and certificates\n"); ERR_print_errors(bio_err); goto end; } ret = 0; end: PKCS12_free(p12); release_engine(e); BIO_free(in); BIO_free_all(out); sk_OPENSSL_STRING_free(canames); OPENSSL_free(badpass); OPENSSL_free(passcerts); OPENSSL_free(passin); OPENSSL_free(passout); return ret; } static int jdk_trust(PKCS12_SAFEBAG *bag, void *cbarg) { STACK_OF(X509_ATTRIBUTE) *attrs = NULL; X509_ATTRIBUTE *attr = NULL; if (cbarg == NULL) return 1; attrs = (STACK_OF(X509_ATTRIBUTE)*)PKCS12_SAFEBAG_get0_attrs(bag); attr = X509_ATTRIBUTE_create(NID_oracle_jdk_trustedkeyusage, V_ASN1_OBJECT, (ASN1_OBJECT*)cbarg); X509at_add1_attr(&attrs, attr); PKCS12_SAFEBAG_set0_attrs(bag, attrs); X509_ATTRIBUTE_free(attr); return 1; } int dump_certs_keys_p12(BIO *out, const PKCS12 *p12, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc) { STACK_OF(PKCS7) *asafes = NULL; int i, bagnid; int ret = 0; PKCS7 *p7; if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL) return 0; for (i = 0; i < sk_PKCS7_num(asafes); i++) { STACK_OF(PKCS12_SAFEBAG) *bags; p7 = sk_PKCS7_value(asafes, i); bagnid = OBJ_obj2nid(p7->type); if (bagnid == NID_pkcs7_data) { bags = PKCS12_unpack_p7data(p7); if (options & INFO) BIO_printf(bio_err, "PKCS7 Data\n"); } else if (bagnid == NID_pkcs7_encrypted) { if (options & INFO) { BIO_printf(bio_err, "PKCS7 Encrypted data: "); if (p7->d.encrypted == NULL) { BIO_printf(bio_err, "<no data>\n"); } else { alg_print(p7->d.encrypted->enc_data->algorithm); } } bags = PKCS12_unpack_p7encdata(p7, pass, passlen); } else { continue; } if (bags == NULL) goto err; if (!dump_certs_pkeys_bags(out, bags, pass, passlen, options, pempass, enc)) { sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); goto err; } sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); } ret = 1; err: sk_PKCS7_pop_free(asafes, PKCS7_free); return ret; } int dump_certs_pkeys_bags(BIO *out, const STACK_OF(PKCS12_SAFEBAG) *bags, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc) { int i; for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) { if (!dump_certs_pkeys_bag(out, sk_PKCS12_SAFEBAG_value(bags, i), pass, passlen, options, pempass, enc)) return 0; } return 1; } int dump_certs_pkeys_bag(BIO *out, const PKCS12_SAFEBAG *bag, const char *pass, int passlen, int options, char *pempass, const EVP_CIPHER *enc) { EVP_PKEY *pkey; PKCS8_PRIV_KEY_INFO *p8; const PKCS8_PRIV_KEY_INFO *p8c; X509 *x509; const STACK_OF(X509_ATTRIBUTE) *attrs; int ret = 0; attrs = PKCS12_SAFEBAG_get0_attrs(bag); switch (PKCS12_SAFEBAG_get_nid(bag)) { case NID_keyBag: if (options & INFO) BIO_printf(bio_err, "Key bag\n"); if (options & NOKEYS) return 1; print_attribs(out, attrs, "Bag Attributes"); p8c = PKCS12_SAFEBAG_get0_p8inf(bag); if ((pkey = EVP_PKCS82PKEY(p8c)) == NULL) return 0; print_attribs(out, PKCS8_pkey_get0_attrs(p8c), "Key Attributes"); ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass); EVP_PKEY_free(pkey); break; case NID_pkcs8ShroudedKeyBag: if (options & INFO) { const X509_SIG *tp8; const X509_ALGOR *tp8alg; BIO_printf(bio_err, "Shrouded Keybag: "); tp8 = PKCS12_SAFEBAG_get0_pkcs8(bag); X509_SIG_get0(tp8, &tp8alg, NULL); alg_print(tp8alg); } if (options & NOKEYS) return 1; print_attribs(out, attrs, "Bag Attributes"); if ((p8 = PKCS12_decrypt_skey(bag, pass, passlen)) == NULL) return 0; if ((pkey = EVP_PKCS82PKEY(p8)) == NULL) { PKCS8_PRIV_KEY_INFO_free(p8); return 0; } print_attribs(out, PKCS8_pkey_get0_attrs(p8), "Key Attributes"); PKCS8_PRIV_KEY_INFO_free(p8); ret = PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, pempass); EVP_PKEY_free(pkey); break; case NID_certBag: if (options & INFO) BIO_printf(bio_err, "Certificate bag\n"); if (options & NOCERTS) return 1; if (PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID)) { if (options & CACERTS) return 1; } else if (options & CLCERTS) return 1; print_attribs(out, attrs, "Bag Attributes"); if (PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate) return 1; if ((x509 = PKCS12_SAFEBAG_get1_cert(bag)) == NULL) return 0; dump_cert_text(out, x509); ret = PEM_write_bio_X509(out, x509); X509_free(x509); break; case NID_secretBag: if (options & INFO) BIO_printf(bio_err, "Secret bag\n"); print_attribs(out, attrs, "Bag Attributes"); BIO_printf(bio_err, "Bag Type: "); i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_bag_type(bag)); BIO_printf(bio_err, "\nBag Value: "); print_attribute(out, PKCS12_SAFEBAG_get0_bag_obj(bag)); return 1; case NID_safeContentsBag: if (options & INFO) BIO_printf(bio_err, "Safe Contents bag\n"); print_attribs(out, attrs, "Bag Attributes"); return dump_certs_pkeys_bags(out, PKCS12_SAFEBAG_get0_safes(bag), pass, passlen, options, pempass, enc); default: BIO_printf(bio_err, "Warning unsupported bag type: "); i2a_ASN1_OBJECT(bio_err, PKCS12_SAFEBAG_get0_type(bag)); BIO_printf(bio_err, "\n"); return 1; } return ret; } static int get_cert_chain(X509 *cert, X509_STORE *store, STACK_OF(X509) *untrusted_certs, STACK_OF(X509) **chain) { X509_STORE_CTX *store_ctx = NULL; STACK_OF(X509) *chn = NULL; int i = 0; store_ctx = X509_STORE_CTX_new_ex(app_get0_libctx(), app_get0_propq()); if (store_ctx == NULL) { i = X509_V_ERR_UNSPECIFIED; goto end; } if (!X509_STORE_CTX_init(store_ctx, store, cert, untrusted_certs)) { i = X509_V_ERR_UNSPECIFIED; goto end; } if (X509_verify_cert(store_ctx) > 0) chn = X509_STORE_CTX_get1_chain(store_ctx); else if ((i = X509_STORE_CTX_get_error(store_ctx)) == 0) i = X509_V_ERR_UNSPECIFIED; end: X509_STORE_CTX_free(store_ctx); *chain = chn; return i; } static int alg_print(const X509_ALGOR *alg) { int pbenid, aparamtype; const ASN1_OBJECT *aoid; const void *aparam; PBEPARAM *pbe = NULL; X509_ALGOR_get0(&aoid, &aparamtype, &aparam, alg); pbenid = OBJ_obj2nid(aoid); BIO_printf(bio_err, "%s", OBJ_nid2ln(pbenid)); if (pbenid == NID_pbes2) { PBE2PARAM *pbe2 = NULL; int encnid; if (aparamtype == V_ASN1_SEQUENCE) pbe2 = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBE2PARAM)); if (pbe2 == NULL) { BIO_puts(bio_err, ", <unsupported parameters>"); goto done; } X509_ALGOR_get0(&aoid, &aparamtype, &aparam, pbe2->keyfunc); pbenid = OBJ_obj2nid(aoid); X509_ALGOR_get0(&aoid, NULL, NULL, pbe2->encryption); encnid = OBJ_obj2nid(aoid); BIO_printf(bio_err, ", %s, %s", OBJ_nid2ln(pbenid), OBJ_nid2sn(encnid)); if (pbenid == NID_id_pbkdf2) { PBKDF2PARAM *kdf = NULL; int prfnid; if (aparamtype == V_ASN1_SEQUENCE) kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBKDF2PARAM)); if (kdf == NULL) { BIO_puts(bio_err, ", <unsupported parameters>"); goto done; } if (kdf->prf == NULL) { prfnid = NID_hmacWithSHA1; } else { X509_ALGOR_get0(&aoid, NULL, NULL, kdf->prf); prfnid = OBJ_obj2nid(aoid); } BIO_printf(bio_err, ", Iteration %ld, PRF %s", ASN1_INTEGER_get(kdf->iter), OBJ_nid2sn(prfnid)); PBKDF2PARAM_free(kdf); #ifndef OPENSSL_NO_SCRYPT } else if (pbenid == NID_id_scrypt) { SCRYPT_PARAMS *kdf = NULL; if (aparamtype == V_ASN1_SEQUENCE) kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(SCRYPT_PARAMS)); if (kdf == NULL) { BIO_puts(bio_err, ", <unsupported parameters>"); goto done; } BIO_printf(bio_err, ", Salt length: %d, Cost(N): %ld, " "Block size(r): %ld, Parallelism(p): %ld", ASN1_STRING_length(kdf->salt), ASN1_INTEGER_get(kdf->costParameter), ASN1_INTEGER_get(kdf->blockSize), ASN1_INTEGER_get(kdf->parallelizationParameter)); SCRYPT_PARAMS_free(kdf); #endif } PBE2PARAM_free(pbe2); } else { if (aparamtype == V_ASN1_SEQUENCE) pbe = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBEPARAM)); if (pbe == NULL) { BIO_puts(bio_err, ", <unsupported parameters>"); goto done; } BIO_printf(bio_err, ", Iteration %ld", ASN1_INTEGER_get(pbe->iter)); PBEPARAM_free(pbe); } done: BIO_puts(bio_err, "\n"); return 1; } int cert_load(BIO *in, STACK_OF(X509) *sk) { int ret = 0; X509 *cert; while ((cert = PEM_read_bio_X509(in, NULL, NULL, NULL))) { ret = 1; if (!sk_X509_push(sk, cert)) return 0; } if (ret) ERR_clear_error(); return ret; } void print_attribute(BIO *out, const ASN1_TYPE *av) { char *value; const char *ln; char objbuf[80]; switch (av->type) { case V_ASN1_BMPSTRING: value = OPENSSL_uni2asc(av->value.bmpstring->data, av->value.bmpstring->length); BIO_printf(out, "%s\n", value); OPENSSL_free(value); break; case V_ASN1_UTF8STRING: BIO_printf(out, "%.*s\n", av->value.utf8string->length, av->value.utf8string->data); break; case V_ASN1_OCTET_STRING: hex_prin(out, av->value.octet_string->data, av->value.octet_string->length); BIO_printf(out, "\n"); break; case V_ASN1_BIT_STRING: hex_prin(out, av->value.bit_string->data, av->value.bit_string->length); BIO_printf(out, "\n"); break; case V_ASN1_OBJECT: ln = OBJ_nid2ln(OBJ_obj2nid(av->value.object)); if (!ln) ln = ""; OBJ_obj2txt(objbuf, sizeof(objbuf), av->value.object, 1); BIO_printf(out, "%s (%s)", ln, objbuf); BIO_printf(out, "\n"); break; default: BIO_printf(out, "<Unsupported tag %d>\n", av->type); break; } } int print_attribs(BIO *out, const STACK_OF(X509_ATTRIBUTE) *attrlst, const char *name) { X509_ATTRIBUTE *attr; ASN1_TYPE *av; int i, j, attr_nid; if (!attrlst) { BIO_printf(out, "%s: <No Attributes>\n", name); return 1; } if (!sk_X509_ATTRIBUTE_num(attrlst)) { BIO_printf(out, "%s: <Empty Attributes>\n", name); return 1; } BIO_printf(out, "%s\n", name); for (i = 0; i < sk_X509_ATTRIBUTE_num(attrlst); i++) { ASN1_OBJECT *attr_obj; attr = sk_X509_ATTRIBUTE_value(attrlst, i); attr_obj = X509_ATTRIBUTE_get0_object(attr); attr_nid = OBJ_obj2nid(attr_obj); BIO_printf(out, " "); if (attr_nid == NID_undef) { i2a_ASN1_OBJECT(out, attr_obj); BIO_printf(out, ": "); } else { BIO_printf(out, "%s: ", OBJ_nid2ln(attr_nid)); } if (X509_ATTRIBUTE_count(attr)) { for (j = 0; j < X509_ATTRIBUTE_count(attr); j++) { av = X509_ATTRIBUTE_get0_type(attr, j); print_attribute(out, av); } } else { BIO_printf(out, "<No Values>\n"); } } return 1; } void hex_prin(BIO *out, unsigned char *buf, int len) { int i; for (i = 0; i < len; i++) BIO_printf(out, "%02X ", buf[i]); } static int set_pbe(int *ppbe, const char *str) { if (!str) return 0; if (strcmp(str, "NONE") == 0) { *ppbe = -1; return 1; } *ppbe = OBJ_txt2nid(str); if (*ppbe == NID_undef) { BIO_printf(bio_err, "Unknown PBE algorithm %s\n", str); return 0; } return 1; }
apps
openssl/apps/pkcs12.c
openssl
#include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/params.h> #include <openssl/core_names.h> #undef BUFSIZE #define BUFSIZE 1024*8 typedef enum OPTION_choice { OPT_COMMON, OPT_MACOPT, OPT_BIN, OPT_IN, OPT_OUT, OPT_CIPHER, OPT_DIGEST, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS mac_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] mac_name\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"macopt", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form"}, {"cipher", OPT_CIPHER, 's', "Cipher"}, {"digest", OPT_DIGEST, 's', "Digest"}, {OPT_MORE_STR, 1, '-', "See 'PARAMETER NAMES' in the EVP_MAC_ docs"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file to MAC (default is stdin)"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output to filename rather than stdout"}, {"binary", OPT_BIN, '-', "Output in binary format (default is hexadecimal)"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"mac_name", 0, 0, "MAC algorithm"}, {NULL} }; static char *alloc_mac_algorithm_name(STACK_OF(OPENSSL_STRING) **optp, const char *name, const char *arg) { size_t len = strlen(name) + strlen(arg) + 2; char *res; if (*optp == NULL) *optp = sk_OPENSSL_STRING_new_null(); if (*optp == NULL) return NULL; res = app_malloc(len, "algorithm name"); BIO_snprintf(res, len, "%s:%s", name, arg); if (sk_OPENSSL_STRING_push(*optp, res)) return res; OPENSSL_free(res); return NULL; } int mac_main(int argc, char **argv) { int ret = 1; char *prog; EVP_MAC *mac = NULL; OPTION_CHOICE o; EVP_MAC_CTX *ctx = NULL; STACK_OF(OPENSSL_STRING) *opts = NULL; unsigned char *buf = NULL; size_t len; int i; BIO *in = NULL, *out = NULL; const char *outfile = NULL; const char *infile = NULL; int out_bin = 0; int inform = FORMAT_BINARY; char *digest = NULL, *cipher = NULL; OSSL_PARAM *params = NULL; prog = opt_init(argc, argv, mac_options); buf = app_malloc(BUFSIZE, "I/O buffer"); while ((o = opt_next()) != OPT_EOF) { switch (o) { default: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto err; case OPT_HELP: opt_help(mac_options); ret = 0; goto err; case OPT_BIN: out_bin = 1; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_MACOPT: if (opts == NULL) opts = sk_OPENSSL_STRING_new_null(); if (opts == NULL || !sk_OPENSSL_STRING_push(opts, opt_arg())) goto opthelp; break; case OPT_CIPHER: OPENSSL_free(cipher); cipher = alloc_mac_algorithm_name(&opts, "cipher", opt_arg()); if (cipher == NULL) goto opthelp; break; case OPT_DIGEST: OPENSSL_free(digest); digest = alloc_mac_algorithm_name(&opts, "digest", opt_arg()); if (digest == NULL) goto opthelp; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto err; break; } } if (!opt_check_rest_arg("MAC name")) goto opthelp; argv = opt_rest(); mac = EVP_MAC_fetch(app_get0_libctx(), argv[0], app_get0_propq()); if (mac == NULL) { BIO_printf(bio_err, "Invalid MAC name %s\n", argv[0]); goto opthelp; } ctx = EVP_MAC_CTX_new(mac); if (ctx == NULL) goto err; if (opts != NULL) { int ok = 1; params = app_params_new_from_opts(opts, EVP_MAC_settable_ctx_params(mac)); if (params == NULL) goto err; if (!EVP_MAC_CTX_set_params(ctx, params)) { BIO_printf(bio_err, "MAC parameter error\n"); ERR_print_errors(bio_err); ok = 0; } app_params_free(params); if (!ok) goto err; } in = bio_open_default(infile, 'r', inform); if (in == NULL) goto err; out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT); if (out == NULL) goto err; if (!EVP_MAC_init(ctx, NULL, 0, NULL)) { BIO_printf(bio_err, "EVP_MAC_Init failed\n"); goto err; } while (BIO_pending(in) || !BIO_eof(in)) { i = BIO_read(in, (char *)buf, BUFSIZE); if (i < 0) { BIO_printf(bio_err, "Read Error in '%s'\n", infile); ERR_print_errors(bio_err); goto err; } if (i == 0) break; if (!EVP_MAC_update(ctx, buf, i)) { BIO_printf(bio_err, "EVP_MAC_update failed\n"); goto err; } } if (!EVP_MAC_final(ctx, NULL, &len, 0)) { BIO_printf(bio_err, "EVP_MAC_final failed\n"); goto err; } if (len > BUFSIZE) { BIO_printf(bio_err, "output len is too large\n"); goto err; } if (!EVP_MAC_final(ctx, buf, &len, BUFSIZE)) { BIO_printf(bio_err, "EVP_MAC_final failed\n"); goto err; } if (out_bin) { BIO_write(out, buf, len); } else { for (i = 0; i < (int)len; ++i) BIO_printf(out, "%02X", buf[i]); if (outfile == NULL) BIO_printf(out, "\n"); } ret = 0; err: if (ret != 0) ERR_print_errors(bio_err); OPENSSL_clear_free(buf, BUFSIZE); OPENSSL_free(cipher); OPENSSL_free(digest); sk_OPENSSL_STRING_free(opts); BIO_free(in); BIO_free(out); EVP_MAC_CTX_free(ctx); EVP_MAC_free(mac); return ret; }
apps
openssl/apps/mac.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/asn1.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/objects.h> #include <openssl/pem.h> #include <openssl/rsa.h> #ifndef OPENSSL_NO_DSA # include <openssl/dsa.h> #endif #include "internal/e_os.h" #undef POSTFIX #define POSTFIX ".srl" #define DEFAULT_DAYS 30 #define UNSET_DAYS -2 #define EXT_COPY_UNSET -1 static int callb(int ok, X509_STORE_CTX *ctx); static ASN1_INTEGER *x509_load_serial(const char *CAfile, const char *serialfile, int create); static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt); static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names); typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_KEYFORM, OPT_REQ, OPT_CAFORM, OPT_CAKEYFORM, OPT_VFYOPT, OPT_SIGOPT, OPT_DAYS, OPT_PASSIN, OPT_EXTFILE, OPT_EXTENSIONS, OPT_IN, OPT_OUT, OPT_KEY, OPT_SIGNKEY, OPT_CA, OPT_CAKEY, OPT_CASERIAL, OPT_SET_SERIAL, OPT_NEW, OPT_FORCE_PUBKEY, OPT_ISSU, OPT_SUBJ, OPT_ADDTRUST, OPT_ADDREJECT, OPT_SETALIAS, OPT_CERTOPT, OPT_DATEOPT, OPT_NAMEOPT, OPT_EMAIL, OPT_OCSP_URI, OPT_SERIAL, OPT_NEXT_SERIAL, OPT_MODULUS, OPT_PUBKEY, OPT_X509TOREQ, OPT_TEXT, OPT_HASH, OPT_ISSUER_HASH, OPT_SUBJECT, OPT_ISSUER, OPT_FINGERPRINT, OPT_DATES, OPT_PURPOSE, OPT_STARTDATE, OPT_ENDDATE, OPT_CHECKEND, OPT_CHECKHOST, OPT_CHECKEMAIL, OPT_CHECKIP, OPT_NOOUT, OPT_TRUSTOUT, OPT_CLRTRUST, OPT_CLRREJECT, OPT_ALIAS, OPT_CACREATESERIAL, OPT_CLREXT, OPT_OCSPID, OPT_SUBJECT_HASH_OLD, OPT_ISSUER_HASH_OLD, OPT_COPY_EXTENSIONS, OPT_BADSIG, OPT_MD, OPT_ENGINE, OPT_NOCERT, OPT_PRESERVE_DATES, OPT_R_ENUM, OPT_PROV_ENUM, OPT_EXT } OPTION_CHOICE; const OPTIONS x509_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"in", OPT_IN, '<', "Certificate input, or CSR input file with -req (default stdin)"}, {"passin", OPT_PASSIN, 's', "Private key and cert file pass-phrase source"}, {"new", OPT_NEW, '-', "Generate a certificate from scratch"}, {"x509toreq", OPT_X509TOREQ, '-', "Output a certification request (rather than a certificate)"}, {"req", OPT_REQ, '-', "Input is a CSR file (rather than a certificate)"}, {"copy_extensions", OPT_COPY_EXTENSIONS, 's', "copy extensions when converting from CSR to x509 or vice versa"}, {"inform", OPT_INFORM, 'f', "CSR input format to use (PEM or DER; by default try PEM first)"}, {"vfyopt", OPT_VFYOPT, 's', "CSR verification parameter in n:v form"}, {"key", OPT_KEY, 's', "Key for signing, and to include unless using -force_pubkey"}, {"signkey", OPT_SIGNKEY, 's', "Same as -key"}, {"keyform", OPT_KEYFORM, 'E', "Key input format (ENGINE, other values ignored)"}, {"out", OPT_OUT, '>', "Output file - default stdout"}, {"outform", OPT_OUTFORM, 'f', "Output format (DER or PEM) - default PEM"}, {"nocert", OPT_NOCERT, '-', "No cert output (except for requested printing)"}, {"noout", OPT_NOOUT, '-', "No output (except for requested printing)"}, OPT_SECTION("Certificate printing"), {"text", OPT_TEXT, '-', "Print the certificate in text form"}, {"dateopt", OPT_DATEOPT, 's', "Datetime format used for printing. (rfc_822/iso_8601). Default is rfc_822."}, {"certopt", OPT_CERTOPT, 's', "Various certificate text printing options"}, {"fingerprint", OPT_FINGERPRINT, '-', "Print the certificate fingerprint"}, {"alias", OPT_ALIAS, '-', "Print certificate alias"}, {"serial", OPT_SERIAL, '-', "Print serial number value"}, {"startdate", OPT_STARTDATE, '-', "Print the notBefore field"}, {"enddate", OPT_ENDDATE, '-', "Print the notAfter field"}, {"dates", OPT_DATES, '-', "Print both notBefore and notAfter fields"}, {"subject", OPT_SUBJECT, '-', "Print subject DN"}, {"issuer", OPT_ISSUER, '-', "Print issuer DN"}, {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"email", OPT_EMAIL, '-', "Print email address(es)"}, {"hash", OPT_HASH, '-', "Synonym for -subject_hash (for backward compat)"}, {"subject_hash", OPT_HASH, '-', "Print subject hash value"}, #ifndef OPENSSL_NO_MD5 {"subject_hash_old", OPT_SUBJECT_HASH_OLD, '-', "Print old-style (MD5) subject hash value"}, #endif {"issuer_hash", OPT_ISSUER_HASH, '-', "Print issuer hash value"}, #ifndef OPENSSL_NO_MD5 {"issuer_hash_old", OPT_ISSUER_HASH_OLD, '-', "Print old-style (MD5) issuer hash value"}, #endif {"ext", OPT_EXT, 's', "Restrict which X.509 extensions to print and/or copy"}, {"ocspid", OPT_OCSPID, '-', "Print OCSP hash values for the subject name and public key"}, {"ocsp_uri", OPT_OCSP_URI, '-', "Print OCSP Responder URL(s)"}, {"purpose", OPT_PURPOSE, '-', "Print out certificate purposes"}, {"pubkey", OPT_PUBKEY, '-', "Print the public key in PEM format"}, {"modulus", OPT_MODULUS, '-', "Print the RSA key modulus"}, OPT_SECTION("Certificate checking"), {"checkend", OPT_CHECKEND, 'M', "Check whether cert expires in the next arg seconds"}, {OPT_MORE_STR, 1, 1, "Exit 1 (failure) if so, 0 if not"}, {"checkhost", OPT_CHECKHOST, 's', "Check certificate matches host"}, {"checkemail", OPT_CHECKEMAIL, 's', "Check certificate matches email"}, {"checkip", OPT_CHECKIP, 's', "Check certificate matches ipaddr"}, OPT_SECTION("Certificate output"), {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use, overrides -CAserial"}, {"next_serial", OPT_NEXT_SERIAL, '-', "Increment current certificate serial number"}, {"days", OPT_DAYS, 'n', "Number of days until newly generated certificate expires - default 30"}, {"preserve_dates", OPT_PRESERVE_DATES, '-', "Preserve existing validity dates"}, {"set_issuer", OPT_ISSU, 's', "Set or override certificate issuer"}, {"set_subject", OPT_SUBJ, 's', "Set or override certificate subject (and issuer)"}, {"subj", OPT_SUBJ, 's', "Alias for -set_subject"}, {"force_pubkey", OPT_FORCE_PUBKEY, '<', "Key to be placed in new certificate or certificate request"}, {"clrext", OPT_CLREXT, '-', "Do not take over any extensions from the source certificate or request"}, {"extfile", OPT_EXTFILE, '<', "Config file with X509V3 extensions to add"}, {"extensions", OPT_EXTENSIONS, 's', "Section of extfile to use - default: unnamed section"}, {"sigopt", OPT_SIGOPT, 's', "Signature parameter, in n:v form"}, {"badsig", OPT_BADSIG, '-', "Corrupt last byte of certificate signature (for test)"}, {"", OPT_MD, '-', "Any supported digest, used for signing and printing"}, OPT_SECTION("Micro-CA"), {"CA", OPT_CA, '<', "Use the given CA certificate, conflicts with -key"}, {"CAform", OPT_CAFORM, 'F', "CA cert format (PEM/DER/P12); has no effect"}, {"CAkey", OPT_CAKEY, 's', "The corresponding CA key; default is -CA arg"}, {"CAkeyform", OPT_CAKEYFORM, 'E', "CA key format (ENGINE, other values ignored)"}, {"CAserial", OPT_CASERIAL, 's', "File that keeps track of CA-generated serial number"}, {"CAcreateserial", OPT_CACREATESERIAL, '-', "Create CA serial number file if it does not exist"}, OPT_SECTION("Certificate trust output"), {"trustout", OPT_TRUSTOUT, '-', "Mark certificate PEM output as trusted"}, {"setalias", OPT_SETALIAS, 's', "Set certificate alias (nickname)"}, {"clrtrust", OPT_CLRTRUST, '-', "Clear all trusted purposes"}, {"addtrust", OPT_ADDTRUST, 's', "Trust certificate for a given purpose"}, {"clrreject", OPT_CLRREJECT, '-', "Clears all the prohibited or rejected uses of the certificate"}, {"addreject", OPT_ADDREJECT, 's', "Reject certificate for a given purpose"}, OPT_R_OPTIONS, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_PROV_OPTIONS, {NULL} }; static void warn_copying(ASN1_OBJECT *excluded, const char *names) { const char *sn = OBJ_nid2sn(OBJ_obj2nid(excluded)); if (names != NULL && strstr(names, sn) != NULL) BIO_printf(bio_err, "Warning: -ext should not specify copying %s extension to CSR; ignoring this\n", sn); } static X509_REQ *x509_to_req(X509 *cert, int ext_copy, const char *names) { const STACK_OF(X509_EXTENSION) *cert_exts = X509_get0_extensions(cert); int i, n = sk_X509_EXTENSION_num(cert_exts ); ASN1_OBJECT *skid = OBJ_nid2obj(NID_subject_key_identifier); ASN1_OBJECT *akid = OBJ_nid2obj(NID_authority_key_identifier); STACK_OF(X509_EXTENSION) *exts; X509_REQ *req = X509_to_X509_REQ(cert, NULL, NULL); if (req == NULL) return NULL; warn_copying(skid, names); warn_copying(akid, names); if ((exts = sk_X509_EXTENSION_new_reserve(NULL, n)) == NULL) goto err; for (i = 0; i < n; i++) { X509_EXTENSION *ex = sk_X509_EXTENSION_value(cert_exts, i); ASN1_OBJECT *obj = X509_EXTENSION_get_object(ex); if (OBJ_cmp(obj, skid) != 0 && OBJ_cmp(obj, akid) != 0 && !sk_X509_EXTENSION_push(exts, ex)) goto err; } if (sk_X509_EXTENSION_num(exts) > 0) { if (ext_copy != EXT_COPY_UNSET && ext_copy != EXT_COPY_NONE && !X509_REQ_add_extensions(req, exts)) { BIO_printf(bio_err, "Error copying extensions from certificate\n"); goto err; } } sk_X509_EXTENSION_free(exts); return req; err: sk_X509_EXTENSION_free(exts); X509_REQ_free(req); return NULL; } static int self_signed(X509_STORE *ctx, X509 *cert) { X509_STORE_CTX *xsc = X509_STORE_CTX_new(); int ret = 0; if (xsc == NULL || !X509_STORE_CTX_init(xsc, ctx, cert, NULL)) { BIO_printf(bio_err, "Error initialising X509 store\n"); } else { X509_STORE_CTX_set_flags(xsc, X509_V_FLAG_CHECK_SS_SIGNATURE); ret = X509_verify_cert(xsc) > 0; } X509_STORE_CTX_free(xsc); return ret; } int x509_main(int argc, char **argv) { ASN1_INTEGER *sno = NULL; ASN1_OBJECT *objtmp = NULL; BIO *out = NULL; CONF *extconf = NULL; int ext_copy = EXT_COPY_UNSET; X509V3_CTX ext_ctx; EVP_PKEY *privkey = NULL, *CAkey = NULL, *pubkey = NULL; EVP_PKEY *pkey; int newcert = 0; char *issu = NULL, *subj = NULL, *digest = NULL; X509_NAME *fissu = NULL, *fsubj = NULL; const unsigned long chtype = MBSTRING_ASC; const int multirdn = 1; STACK_OF(ASN1_OBJECT) *trust = NULL, *reject = NULL; STACK_OF(OPENSSL_STRING) *sigopts = NULL, *vfyopts = NULL; X509 *x = NULL, *xca = NULL, *issuer_cert; X509_REQ *req = NULL, *rq = NULL; X509_STORE *ctx = NULL; char *CAkeyfile = NULL, *CAserial = NULL, *pubkeyfile = NULL, *alias = NULL; char *checkhost = NULL, *checkemail = NULL, *checkip = NULL; char *ext_names = NULL; char *extsect = NULL, *extfile = NULL, *passin = NULL, *passinarg = NULL; char *infile = NULL, *outfile = NULL, *privkeyfile = NULL, *CAfile = NULL; char *prog; int days = UNSET_DAYS; int x509toreq = 0, modulus = 0, print_pubkey = 0, pprint = 0; int CAformat = FORMAT_UNDEF, CAkeyformat = FORMAT_UNDEF; unsigned long dateopt = ASN1_DTFLGS_RFC822; int fingerprint = 0, reqfile = 0, checkend = 0; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyformat = FORMAT_UNDEF; int next_serial = 0, subject_hash = 0, issuer_hash = 0, ocspid = 0; int noout = 0, CA_createserial = 0, email = 0; int ocsp_uri = 0, trustout = 0, clrtrust = 0, clrreject = 0, aliasout = 0; int ret = 1, i, j, num = 0, badsig = 0, clrext = 0, nocert = 0; int text = 0, serial = 0, subject = 0, issuer = 0, startdate = 0, ext = 0; int enddate = 0; time_t checkoffset = 0; unsigned long certflag = 0; int preserve_dates = 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 err; X509_STORE_set_verify_cb(ctx, callb); opt_set_unknown_name("digest"); 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 err; case OPT_HELP: opt_help(x509_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &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_ANY, &keyformat)) goto opthelp; break; case OPT_CAFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &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 = 1; break; case OPT_DATEOPT: if (!set_dateopt(&dateopt, opt_arg())) { BIO_printf(bio_err, "Invalid date format: %s\n", opt_arg()); goto err; } break; case OPT_COPY_EXTENSIONS: if (!set_ext_copy(&ext_copy, opt_arg())) { BIO_printf(bio_err, "Invalid extension copy option: %s\n", opt_arg()); goto err; } 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_VFYOPT: if (!vfyopts) vfyopts = sk_OPENSSL_STRING_new_null(); if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg())) goto opthelp; break; case OPT_DAYS: days = atoi(opt_arg()); if (days < -1) { BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n", prog); goto err; } break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_EXTFILE: extfile = opt_arg(); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_EXTENSIONS: extsect = opt_arg(); break; case OPT_KEY: case OPT_SIGNKEY: privkeyfile = opt_arg(); break; case OPT_CA: CAfile = opt_arg(); break; case OPT_CAKEY: CAkeyfile = opt_arg(); break; case OPT_CASERIAL: CAserial = opt_arg(); break; case OPT_SET_SERIAL: if (sno != NULL) { BIO_printf(bio_err, "Serial number supplied twice\n"); goto opthelp; } if ((sno = s2i_ASN1_INTEGER(NULL, opt_arg())) == NULL) goto opthelp; break; case OPT_NEW: newcert = 1; break; case OPT_FORCE_PUBKEY: pubkeyfile = opt_arg(); break; case OPT_ISSU: issu = opt_arg(); break; case OPT_SUBJ: subj = opt_arg(); break; case OPT_ADDTRUST: if (trust == NULL && (trust = sk_ASN1_OBJECT_new_null()) == NULL) goto end; if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) { BIO_printf(bio_err, "%s: Invalid trust object value %s\n", prog, opt_arg()); goto opthelp; } sk_ASN1_OBJECT_push(trust, objtmp); trustout = 1; break; case OPT_ADDREJECT: if (reject == NULL && (reject = sk_ASN1_OBJECT_new_null()) == NULL) goto end; if ((objtmp = OBJ_txt2obj(opt_arg(), 0)) == NULL) { BIO_printf(bio_err, "%s: Invalid reject object value %s\n", prog, opt_arg()); goto opthelp; } sk_ASN1_OBJECT_push(reject, objtmp); 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: if (!set_nameopt(opt_arg())) goto opthelp; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); 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: print_pubkey = ++num; break; case OPT_X509TOREQ: x509toreq = 1; 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_EXT: ext = ++num; ext_names = opt_arg(); 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 = 1; 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; { ossl_intmax_t temp = 0; if (!opt_intmax(opt_arg(), &temp)) goto opthelp; checkoffset = (time_t)temp; if ((ossl_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_PRESERVE_DATES: preserve_dates = 1; break; case OPT_MD: digest = opt_unknown(); break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (!opt_check_md(digest)) goto opthelp; if (preserve_dates && days != UNSET_DAYS) { BIO_printf(bio_err, "Cannot use -preserve_dates with -days option\n"); goto err; } if (days == UNSET_DAYS) days = DEFAULT_DAYS; if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto err; } if (!X509_STORE_set_default_paths_ex(ctx, app_get0_libctx(), app_get0_propq())) goto end; if (newcert && infile != NULL) { BIO_printf(bio_err, "The -in option cannot be used with -new\n"); goto err; } if (newcert && reqfile) { BIO_printf(bio_err, "The -req option cannot be used with -new\n"); goto err; } if (privkeyfile != NULL) { privkey = load_key(privkeyfile, keyformat, 0, passin, e, "private key"); if (privkey == NULL) goto end; } if (pubkeyfile != NULL) { if ((pubkey = load_pubkey(pubkeyfile, keyformat, 0, NULL, e, "explicitly set public key")) == NULL) goto end; } if (newcert) { if (subj == NULL) { BIO_printf(bio_err, "The -new option requires a subject to be set using -subj\n"); goto err; } if (privkeyfile == NULL && pubkeyfile == NULL) { BIO_printf(bio_err, "The -new option requires using the -key or -force_pubkey option\n"); goto err; } } if (issu != NULL && (fissu = parse_name(issu, chtype, multirdn, "issuer")) == NULL) goto end; if (subj != NULL && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL) goto end; if (CAkeyfile == NULL) CAkeyfile = CAfile; if (CAfile != NULL) { if (privkeyfile != NULL) { BIO_printf(bio_err, "Cannot use both -key/-signkey and -CA option\n"); goto err; } } else { #define WARN_NO_CA(opt) BIO_printf(bio_err, \ "Warning: ignoring " opt " option since -CA option is not given\n"); if (CAkeyfile != NULL) WARN_NO_CA("-CAkey"); if (CAkeyformat != FORMAT_UNDEF) WARN_NO_CA("-CAkeyform"); if (CAformat != FORMAT_UNDEF) WARN_NO_CA("-CAform"); if (CAserial != NULL) WARN_NO_CA("-CAserial"); if (CA_createserial) WARN_NO_CA("-CAcreateserial"); } if (extfile == NULL) { if (extsect != NULL) BIO_printf(bio_err, "Warning: ignoring -extensions option without -extfile\n"); } else { X509V3_CTX ctx2; if ((extconf = app_load_config(extfile)) == NULL) goto end; if (extsect == NULL) { extsect = app_conf_try_string(extconf, "default", "extensions"); if (extsect == NULL) 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 checking extension section %s\n", extsect); goto err; } } if (reqfile) { if (infile == NULL && isatty(fileno_stdin())) BIO_printf(bio_err, "Warning: Reading cert request from stdin since no -in option is given\n"); req = load_csr_autofmt(infile, informat, vfyopts, "certificate request input"); if (req == NULL) goto end; if ((pkey = X509_REQ_get0_pubkey(req)) == NULL) { BIO_printf(bio_err, "Error unpacking public key from CSR\n"); goto err; } i = do_X509_REQ_verify(req, pkey, vfyopts); if (i <= 0) { BIO_printf(bio_err, i < 0 ? "Error while verifying certificate request self-signature\n" : "Certificate request self-signature did not match the contents\n"); goto err; } BIO_printf(bio_err, "Certificate request self-signature ok\n"); print_name(bio_err, "subject=", X509_REQ_get_subject_name(req)); } else if (!x509toreq && ext_copy != EXT_COPY_UNSET) { BIO_printf(bio_err, "Warning: ignoring -copy_extensions since neither -x509toreq nor -req is given\n"); } if (reqfile || newcert) { if (preserve_dates) BIO_printf(bio_err, "Warning: ignoring -preserve_dates option with -req or -new\n"); preserve_dates = 0; if (privkeyfile == NULL && CAkeyfile == NULL) { BIO_printf(bio_err, "We need a private key to sign with, use -key or -CAkey or -CA with private key\n"); goto err; } if ((x = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL) goto end; if (CAfile == NULL && sno == NULL) { sno = ASN1_INTEGER_new(); if (sno == NULL || !rand_serial(NULL, sno)) goto end; } if (req != NULL && ext_copy != EXT_COPY_UNSET) { if (clrext && ext_copy != EXT_COPY_NONE) { BIO_printf(bio_err, "Must not use -clrext together with -copy_extensions\n"); goto err; } else if (!copy_extensions(x, req, ext_copy)) { BIO_printf(bio_err, "Error copying extensions from request\n"); goto err; } } } else { if (infile == NULL && isatty(fileno_stdin())) BIO_printf(bio_err, "Warning: Reading certificate from stdin since no -in or -new option is given\n"); x = load_cert_pass(infile, informat, 1, passin, "certificate"); if (x == NULL) goto end; } if ((fsubj != NULL || req != NULL) && !X509_set_subject_name(x, fsubj != NULL ? fsubj : X509_REQ_get_subject_name(req))) goto end; if ((pubkey != NULL || privkey != NULL || req != NULL) && !X509_set_pubkey(x, pubkey != NULL ? pubkey : privkey != NULL ? privkey : X509_REQ_get0_pubkey(req))) goto end; if (CAfile != NULL) { xca = load_cert_pass(CAfile, CAformat, 1, passin, "CA certificate"); if (xca == NULL) goto end; } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (alias) X509_alias_set1(x, (unsigned char *)alias, -1); if (clrtrust) X509_trust_clear(x); if (clrreject) X509_reject_clear(x); if (trust != NULL) { for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) X509_add1_trust_object(x, sk_ASN1_OBJECT_value(trust, i)); } if (reject != NULL) { for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) X509_add1_reject_object(x, sk_ASN1_OBJECT_value(reject, i)); } if (clrext && ext_names != NULL) BIO_printf(bio_err, "Warning: Ignoring -ext since -clrext is given\n"); for (i = X509_get_ext_count(x) - 1; i >= 0; i--) { X509_EXTENSION *ex = X509_get_ext(x, i); const char *sn = OBJ_nid2sn(OBJ_obj2nid(X509_EXTENSION_get_object(ex))); if (clrext || (ext_names != NULL && strstr(ext_names, sn) == NULL)) X509_EXTENSION_free(X509_delete_ext(x, i)); } issuer_cert = x; if (CAfile != NULL) { issuer_cert = xca; if (sno == NULL) sno = x509_load_serial(CAfile, CAserial, CA_createserial); if (sno == NULL) goto end; if (!x509toreq && !reqfile && !newcert && !self_signed(ctx, x)) goto end; } else { if (privkey != NULL && !cert_matches_key(x, privkey)) BIO_printf(bio_err, "Warning: Signature key and public key of cert do not match\n"); } if (sno != NULL && !X509_set_serialNumber(x, sno)) goto end; if (reqfile || newcert || privkey != NULL || CAfile != NULL) { if (!preserve_dates && !set_cert_times(x, NULL, NULL, days)) goto end; if (fissu != NULL) { if (!X509_set_issuer_name(x, fissu)) goto end; } else { if (!X509_set_issuer_name(x, X509_get_subject_name(issuer_cert))) goto end; } } X509V3_set_ctx(&ext_ctx, issuer_cert, x, NULL, NULL, X509V3_CTX_REPLACE); if (CAfile == NULL) { if (!X509V3_set_issuer_pkey(&ext_ctx, privkey)) goto end; } if (extconf != NULL && !x509toreq) { X509V3_set_nconf(&ext_ctx, extconf); if (!X509V3_EXT_add_nconf(extconf, &ext_ctx, extsect, x)) { BIO_printf(bio_err, "Error adding extensions from section %s\n", extsect); goto err; } } pkey = X509_get0_pubkey(x); if ((print_pubkey != 0 || modulus != 0) && pkey == NULL) { BIO_printf(bio_err, "Error getting public key\n"); goto err; } if (x509toreq) { if (privkey == NULL) { BIO_printf(bio_err, "Must specify request signing key using -key\n"); goto err; } if (clrext && ext_copy != EXT_COPY_NONE) { BIO_printf(bio_err, "Must not use -clrext together with -copy_extensions\n"); goto err; } if ((rq = x509_to_req(x, ext_copy, ext_names)) == NULL) goto end; if (extconf != NULL) { X509V3_set_nconf(&ext_ctx, extconf); if (!X509V3_EXT_REQ_add_nconf(extconf, &ext_ctx, extsect, rq)) { BIO_printf(bio_err, "Error adding request extensions from section %s\n", extsect); goto err; } } if (!do_X509_REQ_sign(rq, privkey, digest, sigopts)) goto end; if (!noout) { if (outformat == FORMAT_ASN1) { X509_REQ_print_ex(out, rq, get_nameopt(), X509_FLAG_COMPAT); i = i2d_X509_bio(out, x); } else { i = PEM_write_bio_X509_REQ(out, rq); } if (!i) { BIO_printf(bio_err, "Unable to write certificate request\n"); goto err; } } noout = 1; } else if (CAfile != NULL) { if ((CAkey = load_key(CAkeyfile, CAkeyformat, 0, passin, e, "CA private key")) == NULL) goto end; if (!X509_check_private_key(xca, CAkey)) { BIO_printf(bio_err, "CA certificate and CA private key do not match\n"); goto err; } if (!do_X509_sign(x, 0, CAkey, digest, sigopts, &ext_ctx)) goto end; } else if (privkey != NULL) { if (!do_X509_sign(x, 0, privkey, digest, sigopts, &ext_ctx)) goto end; } if (badsig) { const ASN1_BIT_STRING *signature; X509_get0_signature(&signature, NULL, x); corrupt_signature(signature); } for (i = 1; i <= num; i++) { if (i == issuer) { print_name(out, "issuer=", X509_get_issuer_name(x)); } else if (i == subject) { print_name(out, "subject=", X509_get_subject_name(x)); } else if (i == serial) { BIO_printf(out, "serial="); i2a_ASN1_INTEGER(out, X509_get0_serialNumber(x)); BIO_printf(out, "\n"); } else if (i == next_serial) { ASN1_INTEGER *ser; BIGNUM *bnser = ASN1_INTEGER_to_BN(X509_get0_serialNumber(x), NULL); if (bnser == NULL) goto end; if (!BN_add_word(bnser, 1) || (ser = BN_to_ASN1_INTEGER(bnser, NULL)) == NULL) { BN_free(bnser); goto end; } BN_free(bnser); i2a_ASN1_INTEGER(out, ser); ASN1_INTEGER_free(ser); BIO_puts(out, "\n"); } else if (i == email || i == ocsp_uri) { STACK_OF(OPENSSL_STRING) *emlst = i == email ? X509_get1_email(x) : 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 (i == aliasout) { unsigned char *alstr = X509_alias_get0(x, NULL); if (alstr) BIO_printf(out, "%s\n", alstr); else BIO_puts(out, "<No Alias>\n"); } else if (i == subject_hash) { BIO_printf(out, "%08lx\n", X509_subject_name_hash(x)); #ifndef OPENSSL_NO_MD5 } else if (i == subject_hash_old) { BIO_printf(out, "%08lx\n", X509_subject_name_hash_old(x)); #endif } else if (i == issuer_hash) { BIO_printf(out, "%08lx\n", X509_issuer_name_hash(x)); #ifndef OPENSSL_NO_MD5 } else if (i == issuer_hash_old) { BIO_printf(out, "%08lx\n", X509_issuer_name_hash_old(x)); #endif } else if (i == pprint) { BIO_printf(out, "Certificate purposes:\n"); for (j = 0; j < X509_PURPOSE_get_count(); j++) purpose_print(out, x, X509_PURPOSE_get0(j)); } else if (i == modulus) { BIO_printf(out, "Modulus="); if (EVP_PKEY_is_a(pkey, "RSA") || EVP_PKEY_is_a(pkey, "RSA-PSS")) { BIGNUM *n = NULL; EVP_PKEY_get_bn_param(pkey, "n", &n); BN_print(out, n); BN_free(n); } else if (EVP_PKEY_is_a(pkey, "DSA")) { BIGNUM *dsapub = NULL; EVP_PKEY_get_bn_param(pkey, "pub", &dsapub); BN_print(out, dsapub); BN_free(dsapub); } else { BIO_printf(out, "No modulus for this public key type"); } BIO_printf(out, "\n"); } else if (i == print_pubkey) { PEM_write_bio_PUBKEY(out, pkey); } else if (i == text) { X509_print_ex(out, x, get_nameopt(), certflag); } else if (i == startdate) { BIO_puts(out, "notBefore="); ASN1_TIME_print_ex(out, X509_get0_notBefore(x), dateopt); BIO_puts(out, "\n"); } else if (i == enddate) { BIO_puts(out, "notAfter="); ASN1_TIME_print_ex(out, X509_get0_notAfter(x), dateopt); BIO_puts(out, "\n"); } else if (i == fingerprint) { unsigned int n; unsigned char md[EVP_MAX_MD_SIZE]; const char *fdigname = digest; EVP_MD *fdig; int digres; if (fdigname == NULL) fdigname = "SHA1"; if ((fdig = EVP_MD_fetch(app_get0_libctx(), fdigname, app_get0_propq())) == NULL) { BIO_printf(bio_err, "Unknown digest\n"); goto err; } digres = X509_digest(x, fdig, md, &n); EVP_MD_free(fdig); if (!digres) { BIO_printf(bio_err, "Out of memory\n"); goto err; } BIO_printf(out, "%s Fingerprint=", fdigname); for (j = 0; j < (int)n; j++) BIO_printf(out, "%02X%c", md[j], (j + 1 == (int)n) ? '\n' : ':'); } else if (i == ocspid) { X509_ocspid_print(out, x); } else if (i == ext) { print_x509v3_exts(out, x, ext_names); } } if (checkend) { time_t tcheck = time(NULL) + checkoffset; ret = X509_cmp_time(X509_get0_notAfter(x), &tcheck) < 0; if (ret) BIO_printf(out, "Certificate will expire\n"); else BIO_printf(out, "Certificate will not expire\n"); goto end; } if (!check_cert_attributes(out, x, checkhost, checkemail, checkip, 1)) goto err; if (noout || nocert) { ret = 0; goto end; } if (outformat == FORMAT_ASN1) { i = i2d_X509_bio(out, x); } else if (outformat == FORMAT_PEM) { if (trustout) i = PEM_write_bio_X509_AUX(out, x); else i = PEM_write_bio_X509(out, x); } else { BIO_printf(bio_err, "Bad output format specified for outfile\n"); goto err; } if (!i) { BIO_printf(bio_err, "Unable to write certificate\n"); goto err; } ret = 0; goto end; err: ERR_print_errors(bio_err); end: NCONF_free(extconf); BIO_free_all(out); X509_STORE_free(ctx); X509_NAME_free(fissu); X509_NAME_free(fsubj); X509_REQ_free(req); X509_free(x); X509_free(xca); EVP_PKEY_free(privkey); EVP_PKEY_free(CAkey); EVP_PKEY_free(pubkey); sk_OPENSSL_STRING_free(sigopts); sk_OPENSSL_STRING_free(vfyopts); 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); release_engine(e); clear_free(passin); return ret; } static ASN1_INTEGER *x509_load_serial(const char *CAfile, const char *serialfile, int create) { char *buf = NULL; ASN1_INTEGER *bs = NULL; BIGNUM *serial = NULL; int defaultfile = 0, file_exists; if (serialfile == NULL) { const char *p = strrchr(CAfile, '.'); size_t len = p != NULL ? (size_t)(p - CAfile) : strlen(CAfile); buf = app_malloc(len + sizeof(POSTFIX), "serial# buffer"); memcpy(buf, CAfile, len); memcpy(buf + len, POSTFIX, sizeof(POSTFIX)); serialfile = buf; defaultfile = 1; } serial = load_serial(serialfile, &file_exists, create || defaultfile, NULL); if (serial == NULL) goto end; if (!BN_add_word(serial, 1)) { BIO_printf(bio_err, "Serial number increment failure\n"); goto end; } if (file_exists || create) save_serial(serialfile, NULL, serial, &bs); else bs = BN_to_ASN1_INTEGER(serial, NULL); end: OPENSSL_free(buf); BN_free(serial); return bs; } static int callb(int ok, X509_STORE_CTX *ctx) { int err; X509 *err_cert; err = X509_STORE_CTX_get_error(ctx); if (err == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) return 1; if (!ok) { err_cert = X509_STORE_CTX_get_current_cert(ctx); print_name(bio_err, "subject=", X509_get_subject_name(err_cert)); BIO_printf(bio_err, "Error with certificate - error %d at depth %d\n%s\n", err, X509_STORE_CTX_get_error_depth(ctx), X509_verify_cert_error_string(err)); return 1; } return 1; } static int purpose_print(BIO *bio, X509 *cert, X509_PURPOSE *pt) { int id, i, idret; const char *pname; id = X509_PURPOSE_get_id(pt); pname = X509_PURPOSE_get0_name(pt); for (i = 0; i < 2; i++) { idret = X509_check_purpose(cert, id, i); BIO_printf(bio, "%s%s : ", pname, i ? " CA" : ""); if (idret == 1) BIO_printf(bio, "Yes\n"); else if (idret == 0) BIO_printf(bio, "No\n"); else BIO_printf(bio, "Yes (WARNING code=%d)\n", idret); } return 1; } static int parse_ext_names(char *names, const char **result) { char *p, *q; int cnt = 0, len = 0; p = q = names; len = strlen(names); while (q - names <= len) { if (*q != ',' && *q != '\0') { q++; continue; } if (p != q) { if (result != NULL) { result[cnt] = p; *q = '\0'; } cnt++; } p = ++q; } return cnt; } static int print_x509v3_exts(BIO *bio, X509 *x, const char *ext_names) { const STACK_OF(X509_EXTENSION) *exts = NULL; STACK_OF(X509_EXTENSION) *exts2 = NULL; X509_EXTENSION *ext = NULL; ASN1_OBJECT *obj; int i, j, ret = 0, num, nn = 0; const char *sn, **names = NULL; char *tmp_ext_names = NULL; exts = X509_get0_extensions(x); if ((num = sk_X509_EXTENSION_num(exts)) <= 0) { BIO_printf(bio_err, "No extensions in certificate\n"); ret = 1; goto end; } if ((tmp_ext_names = OPENSSL_strdup(ext_names)) == NULL) goto end; if ((nn = parse_ext_names(tmp_ext_names, NULL)) == 0) { BIO_printf(bio, "Invalid extension names: %s\n", ext_names); goto end; } if ((names = OPENSSL_malloc(sizeof(char *) * nn)) == NULL) goto end; parse_ext_names(tmp_ext_names, names); for (i = 0; i < num; i++) { ext = sk_X509_EXTENSION_value(exts, i); obj = X509_EXTENSION_get_object(ext); sn = OBJ_nid2sn(OBJ_obj2nid(obj)); if (sn == NULL || strcmp(sn, "UNDEF") == 0) continue; for (j = 0; j < nn; j++) { if (strcmp(sn, names[j]) == 0) { if (exts2 == NULL && (exts2 = sk_X509_EXTENSION_new_null()) == NULL) goto end; if (!sk_X509_EXTENSION_push(exts2, ext)) goto end; } } } if (!sk_X509_EXTENSION_num(exts2)) { BIO_printf(bio, "No extensions matched with %s\n", ext_names); ret = 1; goto end; } ret = X509V3_extensions_print(bio, NULL, exts2, 0, 0); end: sk_X509_EXTENSION_free(exts2); OPENSSL_free(names); OPENSSL_free(tmp_ext_names); return ret; }
apps
openssl/apps/x509.c
openssl
#include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/dsa.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/bn.h> #include <openssl/encoder.h> #include <openssl/core_names.h> #include <openssl/core_dispatch.h> #ifndef OPENSSL_NO_RC4 # define DEFAULT_PVK_ENCR_STRENGTH 2 #else # define DEFAULT_PVK_ENCR_STRENGTH 0 #endif typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENGINE, OPT_PVK_NONE, OPT_PVK_WEAK, OPT_PVK_STRONG, OPT_NOOUT, OPT_TEXT, OPT_MODULUS, OPT_PUBIN, OPT_PUBOUT, OPT_CIPHER, OPT_PASSIN, OPT_PASSOUT, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS dsa_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"", OPT_CIPHER, '-', "Any supported cipher"}, #ifndef OPENSSL_NO_RC4 {"pvk-strong", OPT_PVK_STRONG, '-', "Enable 'Strong' PVK encoding level (default)"}, {"pvk-weak", OPT_PVK_WEAK, '-', "Enable 'Weak' PVK encoding level"}, {"pvk-none", OPT_PVK_NONE, '-', "Don't enforce PVK encoding"}, #endif #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, 's', "Input key"}, {"inform", OPT_INFORM, 'f', "Input format (DER/PEM/PVK); has no effect"}, {"pubin", OPT_PUBIN, '-', "Expect a public key in input file"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'f', "Output format, DER PEM PVK"}, {"noout", OPT_NOOUT, '-', "Don't print key out"}, {"text", OPT_TEXT, '-', "Print the key in text"}, {"modulus", OPT_MODULUS, '-', "Print the DSA public value"}, {"pubout", OPT_PUBOUT, '-', "Output public key, not private"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, OPT_PROV_OPTIONS, {NULL} }; int dsa_main(int argc, char **argv) { BIO *out = NULL; ENGINE *e = NULL; EVP_PKEY *pkey = NULL; EVP_CIPHER *enc = NULL; char *infile = NULL, *outfile = NULL, *prog; char *passin = NULL, *passout = NULL, *passinarg = NULL, *passoutarg = NULL; OPTION_CHOICE o; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, text = 0, noout = 0; int modulus = 0, pubin = 0, pubout = 0, ret = 1; int pvk_encr = DEFAULT_PVK_ENCR_STRENGTH; int private = 0; const char *output_type = NULL, *ciphername = NULL; const char *output_structure = NULL; int selection = 0; OSSL_ENCODER_CTX *ectx = NULL; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, dsa_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: ret = 0; BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(dsa_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_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_PVK_STRONG: case OPT_PVK_WEAK: case OPT_PVK_NONE: #ifndef OPENSSL_NO_RC4 pvk_encr = (o - OPT_PVK_NONE); #endif break; case OPT_NOOUT: noout = 1; break; case OPT_TEXT: text = 1; break; case OPT_MODULUS: modulus = 1; break; case OPT_PUBIN: pubin = 1; break; case OPT_PUBOUT: pubout = 1; break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!opt_cipher(ciphername, &enc)) goto end; private = !pubin && (!pubout || text); if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } BIO_printf(bio_err, "read DSA key\n"); if (pubin) pkey = load_pubkey(infile, informat, 1, passin, e, "public key"); else pkey = load_key(infile, informat, 1, passin, e, "private key"); if (pkey == NULL) { BIO_printf(bio_err, "unable to load Key\n"); ERR_print_errors(bio_err); goto end; } if (!EVP_PKEY_is_a(pkey, "DSA")) { BIO_printf(bio_err, "Not a DSA key\n"); goto end; } out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (text) { assert(pubin || private); if ((pubin && EVP_PKEY_print_public(out, pkey, 0, NULL) <= 0) || (!pubin && EVP_PKEY_print_private(out, pkey, 0, NULL) <= 0)) { perror(outfile); ERR_print_errors(bio_err); goto end; } } if (modulus) { BIGNUM *pub_key = NULL; if (!EVP_PKEY_get_bn_param(pkey, "pub", &pub_key)) { ERR_print_errors(bio_err); goto end; } BIO_printf(out, "Public Key="); BN_print(out, pub_key); BIO_printf(out, "\n"); BN_free(pub_key); } if (noout) { ret = 0; goto end; } BIO_printf(bio_err, "writing DSA key\n"); if (outformat == FORMAT_ASN1) { output_type = "DER"; } else if (outformat == FORMAT_PEM) { output_type = "PEM"; } else if (outformat == FORMAT_MSBLOB) { output_type = "MSBLOB"; } else if (outformat == FORMAT_PVK) { if (pubin) { BIO_printf(bio_err, "PVK form impossible with public key input\n"); goto end; } output_type = "PVK"; } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (outformat == FORMAT_ASN1 || outformat == FORMAT_PEM) { if (pubout || pubin) output_structure = "SubjectPublicKeyInfo"; else output_structure = "type-specific"; } if (pubout || pubin) { selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY; } else { assert(private); selection = (OSSL_KEYMGMT_SELECT_KEYPAIR | OSSL_KEYMGMT_SELECT_ALL_PARAMETERS); } ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, output_type, output_structure, NULL); if (OSSL_ENCODER_CTX_get_num_encoders(ectx) == 0) { BIO_printf(bio_err, "%s format not supported\n", output_type); goto end; } if (enc != NULL) OSSL_ENCODER_CTX_set_cipher(ectx, EVP_CIPHER_get0_name(enc), NULL); if (enc != NULL || outformat == FORMAT_PVK) { OSSL_ENCODER_CTX_set_passphrase_ui(ectx, get_ui_method(), NULL); if (passout != NULL) OSSL_ENCODER_CTX_set_passphrase(ectx, (const unsigned char *)passout, strlen(passout)); } if (outformat == FORMAT_PVK) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_int("encrypt-level", &pvk_encr); if (!OSSL_ENCODER_CTX_set_params(ectx, params)) { BIO_printf(bio_err, "invalid PVK encryption level\n"); goto end; } } if (!OSSL_ENCODER_to_bio(ectx, out)) { BIO_printf(bio_err, "unable to write key\n"); goto end; } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); OSSL_ENCODER_CTX_free(ectx); BIO_free_all(out); EVP_PKEY_free(pkey); EVP_CIPHER_free(enc); release_engine(e); OPENSSL_free(passin); OPENSSL_free(passout); return ret; }
apps
openssl/apps/dsa.c
openssl
#include <stdio.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/crypto.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/x509_vfy.h> #include <openssl/x509v3.h> static int save_certs(char *signerfile, STACK_OF(X509) *signers); static int smime_cb(int ok, X509_STORE_CTX *ctx); #define SMIME_OP 0x10 #define SMIME_IP 0x20 #define SMIME_SIGNERS 0x40 #define SMIME_ENCRYPT (1 | SMIME_OP) #define SMIME_DECRYPT (2 | SMIME_IP) #define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS) #define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS) #define SMIME_VERIFY (4 | SMIME_IP) #define SMIME_PK7OUT (5 | SMIME_IP | SMIME_OP) typedef enum OPTION_choice { OPT_COMMON, OPT_ENCRYPT, OPT_DECRYPT, OPT_SIGN, OPT_RESIGN, OPT_VERIFY, OPT_PK7OUT, OPT_TEXT, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCHAIN, OPT_NOCERTS, OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_NOSIGS, OPT_STREAM, OPT_INDEF, OPT_NOINDEF, OPT_CRLFEOL, OPT_ENGINE, OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP, OPT_MD, OPT_CIPHER, OPT_INKEY, OPT_KEYFORM, OPT_CERTFILE, OPT_CAFILE, OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE, OPT_NOCAPATH, OPT_NOCASTORE, OPT_R_ENUM, OPT_PROV_ENUM, OPT_CONFIG, OPT_V_ENUM, OPT_IN, OPT_INFORM, OPT_OUT, OPT_OUTFORM, OPT_CONTENT } OPTION_CHOICE; const OPTIONS smime_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"in", OPT_IN, '<', "Input file"}, {"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"}, {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'c', "Output format SMIME (default), PEM or DER"}, {"inkey", OPT_INKEY, 's', "Input private key (if not signer or recipient)"}, {"keyform", OPT_KEYFORM, 'f', "Input private key format (ENGINE, other values ignored)"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"stream", OPT_STREAM, '-', "Enable CMS streaming" }, {"indef", OPT_INDEF, '-', "Same as -stream" }, {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"}, OPT_CONFIG_OPTION, OPT_SECTION("Action"), {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"}, {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"}, {"sign", OPT_SIGN, '-', "Sign message"}, {"resign", OPT_RESIGN, '-', "Resign a signed message"}, {"verify", OPT_VERIFY, '-', "Verify signed message"}, {"pk7out", OPT_PK7OUT, '-', "Output PKCS#7 structure"}, OPT_SECTION("Signing/Encryption"), {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"md", OPT_MD, 's', "Digest algorithm to use when signing or resigning"}, {"", OPT_CIPHER, '-', "Any supported cipher"}, {"nointern", OPT_NOINTERN, '-', "Don't search certificates in message for signer"}, {"nodetach", OPT_NODETACH, '-', "Use opaque signing"}, {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"}, {"binary", OPT_BINARY, '-', "Don't translate message to text"}, {"signer", OPT_SIGNER, 's', "Signer certificate file"}, {"content", OPT_CONTENT, '<', "Supply or override content for detached signature"}, {"nocerts", OPT_NOCERTS, '-', "Don't include signers certificate when signing"}, OPT_SECTION("Verification/Decryption"), {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"}, {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"}, {"certfile", OPT_CERTFILE, '<', "Other certificates file"}, {"recip", OPT_RECIP, '<', "Recipient certificate file for decryption"}, OPT_SECTION("Email"), {"to", OPT_TO, 's', "To address"}, {"from", OPT_FROM, 's', "From address"}, {"subject", OPT_SUBJECT, 's', "Subject"}, {"text", OPT_TEXT, '-', "Include or delete text MIME headers"}, {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"}, OPT_SECTION("Certificate chain"), {"CApath", OPT_CAPATH, '/', "Trusted certificates directory"}, {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"}, {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, {"nochain", OPT_NOCHAIN, '-', "set PKCS7_NOCHAIN so certificates contained in the message are not used as untrusted CAs" }, {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only"}, OPT_R_OPTIONS, OPT_V_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"cert", 0, 0, "Recipient certs, used when encrypting"}, {NULL} }; static const char *operation_name(int operation) { switch (operation) { case SMIME_ENCRYPT: return "encrypt"; case SMIME_DECRYPT: return "decrypt"; case SMIME_SIGN: return "sign"; case SMIME_RESIGN: return "resign"; case SMIME_VERIFY: return "verify"; case SMIME_PK7OUT: return "pk7out"; default: return "(invalid operation)"; } } #define SET_OPERATION(op) \ ((operation != 0 && (operation != (op))) \ ? 0 * BIO_printf(bio_err, "%s: Cannot use -%s together with -%s\n", \ prog, operation_name(op), operation_name(operation)) \ : (operation = (op))) int smime_main(int argc, char **argv) { CONF *conf = NULL; 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; EVP_CIPHER *cipher = NULL; EVP_MD *sign_md = NULL; const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL, *prog = NULL; char *certfile = NULL, *keyfile = NULL, *contfile = NULL; char *infile = NULL, *outfile = NULL, *signerfile = NULL, *recipfile = NULL; char *passinarg = NULL, *passin = NULL, *to = NULL, *from = NULL; char *subject = NULL, *digestname = NULL, *ciphername = NULL; OPTION_CHOICE o; int noCApath = 0, noCAfile = 0, noCAstore = 0; int flags = PKCS7_DETACHED, operation = 0, ret = 0, indef = 0; int informat = FORMAT_SMIME, outformat = FORMAT_SMIME, keyform = FORMAT_UNDEF; int vpmtouched = 0, rv = 0; ENGINE *e = NULL; const char *mime_eol = "\n"; OSSL_LIB_CTX *libctx = app_get0_libctx(); if ((vpm = X509_VERIFY_PARAM_new()) == NULL) return 1; opt_set_unknown_name("cipher"); 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: if (!SET_OPERATION(SMIME_ENCRYPT)) goto end; break; case OPT_DECRYPT: if (!SET_OPERATION(SMIME_DECRYPT)) goto end; break; case OPT_SIGN: if (!SET_OPERATION(SMIME_SIGN)) goto end; break; case OPT_RESIGN: if (!SET_OPERATION(SMIME_RESIGN)) goto end; break; case OPT_VERIFY: if (!SET_OPERATION(SMIME_VERIFY)) goto end; break; case OPT_PK7OUT: if (!SET_OPERATION(SMIME_PK7OUT)) goto end; 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_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_CONFIG: conf = app_load_config_modules(opt_arg()); if (conf == NULL) goto end; 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 (signerfile != NULL) { 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: digestname = opt_arg(); break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_INKEY: if (keyfile != NULL) { 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_CASTORE: CAstore = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCASTORE: noCAstore = 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 (!app_RAND_load()) goto end; if (digestname != NULL) { if (!opt_md(digestname, &sign_md)) goto opthelp; } if (!opt_cipher_any(ciphername, &cipher)) goto opthelp; if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) { BIO_puts(bio_err, "Multiple signers or keys not allowed\n"); goto opthelp; } if (!operation) { BIO_puts(bio_err, "No operation (-encrypt|-sign|...) specified\n"); goto opthelp; } if (operation & SMIME_SIGNERS) { if (keyfile && !signerfile) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto opthelp; } if (signerfile != NULL) { if (sksigners == NULL && (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 == NULL) { BIO_printf(bio_err, "No signer certificate specified\n"); goto opthelp; } signerfile = NULL; keyfile = NULL; } else if (operation == SMIME_DECRYPT) { if (recipfile == NULL && keyfile == NULL) { 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; } } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } 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 == NULL) { #ifndef OPENSSL_NO_DES cipher = (EVP_CIPHER *)EVP_des_ede3_cbc(); #else BIO_printf(bio_err, "No cipher selected\n"); goto end; #endif } encerts = sk_X509_new_null(); if (encerts == NULL) goto end; while (*argv != NULL) { cert = load_cert(*argv, FORMAT_UNDEF, "recipient certificate file"); if (cert == NULL) goto end; if (!sk_X509_push(encerts, cert)) goto end; cert = NULL; argv++; } } if (certfile != NULL) { if (!load_certs(certfile, 0, &other, NULL, "certificates")) { ERR_print_errors(bio_err); goto end; } } if (recipfile != NULL && (operation == SMIME_DECRYPT)) { if ((recip = load_cert(recipfile, FORMAT_UNDEF, "recipient certificate file")) == NULL) { ERR_print_errors(bio_err); goto end; } } if (operation == SMIME_DECRYPT) { if (keyfile == NULL) keyfile = recipfile; } else if (operation == SMIME_SIGN) { if (keyfile == NULL) keyfile = signerfile; } else { keyfile = NULL; } if (keyfile != NULL) { key = load_key(keyfile, keyform, 0, passin, e, "signing key"); if (key == NULL) goto end; } in = bio_open_default(infile, 'r', informat); if (in == NULL) goto end; if (operation & SMIME_IP) { PKCS7 *p7_in = NULL; p7 = PKCS7_new_ex(libctx, app_get0_propq()); if (p7 == NULL) { BIO_printf(bio_err, "Error allocating PKCS7 object\n"); goto end; } if (informat == FORMAT_SMIME) { p7_in = SMIME_read_PKCS7_ex(in, &indata, &p7); } else if (informat == FORMAT_PEM) { p7_in = PEM_read_bio_PKCS7(in, &p7, NULL, NULL); } else if (informat == FORMAT_ASN1) { p7_in = d2i_PKCS7_bio(in, &p7); } else { BIO_printf(bio_err, "Bad input format for PKCS#7 file\n"); goto end; } if (p7_in == NULL) { BIO_printf(bio_err, "Error reading S/MIME message\n"); goto end; } if (contfile != NULL) { 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, noCAfile, CApath, noCApath, CAstore, noCAstore)) == 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_ex(encerts, in, cipher, flags, libctx, app_get0_propq()); } else if (operation & SMIME_SIGNERS) { int i; 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_ex(NULL, NULL, other, in, flags, libctx, app_get0_propq()); if (p7 == NULL) 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_UNDEF, "signer certificate"); if (signer == NULL) goto end; key = load_key(keyfile, keyform, 0, passin, e, "signing key"); if (key == NULL) 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 ((operation == SMIME_SIGN) && !(flags & PKCS7_STREAM)) { if (!PKCS7_final(p7, in, flags)) goto end; } } if (p7 == NULL) { 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 (ret) ERR_print_errors(bio_err); OSSL_STACK_OF_X509_free(encerts); OSSL_STACK_OF_X509_free(other); 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); EVP_MD_free(sign_md); EVP_CIPHER_free(cipher); PKCS7_free(p7); release_engine(e); BIO_free(in); BIO_free(indata); BIO_free_all(out); OPENSSL_free(passin); NCONF_free(conf); return ret; } static int save_certs(char *signerfile, STACK_OF(X509) *signers) { int i; BIO *tmp; if (signerfile == NULL) return 1; tmp = BIO_new_file(signerfile, "w"); if (tmp == NULL) return 0; for (i = 0; i < sk_X509_num(signers); i++) PEM_write_bio_X509(tmp, sk_X509_value(signers, i)); BIO_free(tmp); return 1; } static int smime_cb(int ok, X509_STORE_CTX *ctx) { int error; error = X509_STORE_CTX_get_error(ctx); if ((error != X509_V_ERR_NO_EXPLICIT_POLICY) && ((error != X509_V_OK) || (ok != 2))) return ok; policies_print(ctx); return ok; }
apps
openssl/apps/smime.c
openssl
#include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/dsa.h> #include <openssl/x509.h> #include <openssl/pem.h> static int verbose = 0; typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT, OPT_NOOUT, OPT_GENKEY, OPT_ENGINE, OPT_VERBOSE, OPT_QUIET, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS dsaparam_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [numbits] [numqbits]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, {"text", OPT_TEXT, '-', "Print as text"}, {"noout", OPT_NOOUT, '-', "No output"}, {"verbose", OPT_VERBOSE, '-', "Verbose output"}, {"quiet", OPT_QUIET, '-', "Terse output"}, {"genkey", OPT_GENKEY, '-', "Generate a DSA key"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"numbits", 0, 0, "Number of bits if generating parameters or key (optional)"}, {"numqbits", 0, 0, "Number of bits in the subprime parameter q if generating parameters or key (optional)"}, {NULL} }; int dsaparam_main(int argc, char **argv) { ENGINE *e = NULL; BIO *out = NULL; EVP_PKEY *params = NULL, *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; int numbits = -1, numqbits = -1, num = 0, genkey = 0; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, noout = 0; int ret = 1, i, text = 0, private = 0; char *infile = NULL, *outfile = NULL, *prog; OPTION_CHOICE o; prog = opt_init(argc, argv, dsaparam_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(dsaparam_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_TEXT: text = 1; break; case OPT_GENKEY: genkey = 1; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_NOOUT: noout = 1; break; case OPT_VERBOSE: verbose = 1; break; case OPT_QUIET: verbose = 0; break; } } argc = opt_num_rest(); argv = opt_rest(); if (argc == 2) { if (!opt_int(argv[0], &num) || num < 0) goto opthelp; if (!opt_int(argv[1], &numqbits) || numqbits < 0) goto opthelp; } else if (argc == 1) { if (!opt_int(argv[0], &num) || num < 0) goto opthelp; } else if (!opt_check_rest_arg(NULL)) { goto opthelp; } if (!app_RAND_load()) goto end; numbits = num; private = genkey ? 1 : 0; out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), "DSA", app_get0_propq()); if (ctx == NULL) { BIO_printf(bio_err, "Error, DSA parameter generation context allocation failed\n"); goto end; } if (numbits > 0) { if (numbits > OPENSSL_DSA_MAX_MODULUS_BITS) BIO_printf(bio_err, "Warning: It is not recommended to use more than %d bit for DSA keys.\n" " Your key size is %d! Larger key size may behave not as expected.\n", OPENSSL_DSA_MAX_MODULUS_BITS, numbits); EVP_PKEY_CTX_set_app_data(ctx, bio_err); if (verbose) { EVP_PKEY_CTX_set_cb(ctx, progress_cb); BIO_printf(bio_err, "Generating DSA parameters, %d bit long prime\n", num); BIO_printf(bio_err, "This could take some time\n"); } if (EVP_PKEY_paramgen_init(ctx) <= 0) { BIO_printf(bio_err, "Error, DSA key generation paramgen init failed\n"); goto end; } if (EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx, num) <= 0) { BIO_printf(bio_err, "Error, DSA key generation setting bit length failed\n"); goto end; } if (numqbits > 0) { if (EVP_PKEY_CTX_set_dsa_paramgen_q_bits(ctx, numqbits) <= 0) { BIO_printf(bio_err, "Error, DSA key generation setting subprime bit length failed\n"); goto end; } } params = app_paramgen(ctx, "DSA"); } else { params = load_keyparams(infile, informat, 1, "DSA", "DSA parameters"); } if (params == NULL) { goto end; } if (text) { EVP_PKEY_print_params(out, params, 0, NULL); } if (outformat == FORMAT_ASN1 && genkey) noout = 1; if (!noout) { if (outformat == FORMAT_ASN1) i = i2d_KeyParams_bio(out, params); else i = PEM_write_bio_Parameters(out, params); if (!i) { BIO_printf(bio_err, "Error, unable to write DSA parameters\n"); goto end; } } if (genkey) { EVP_PKEY_CTX_free(ctx); ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), params, app_get0_propq()); if (ctx == NULL) { BIO_printf(bio_err, "Error, DSA key generation context allocation failed\n"); goto end; } if (EVP_PKEY_keygen_init(ctx) <= 0) { BIO_printf(bio_err, "Error, unable to initialise for key generation\n"); goto end; } pkey = app_keygen(ctx, "DSA", numbits, verbose); if (pkey == NULL) goto end; assert(private); if (outformat == FORMAT_ASN1) i = i2d_PrivateKey_bio(out, pkey); else i = PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, NULL); } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); BIO_free_all(out); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); EVP_PKEY_free(params); release_engine(e); return ret; }
apps
openssl/apps/dsaparam.c
openssl
#include <openssl/evp.h> #include <openssl/err.h> #include <openssl/provider.h> #include <openssl/params.h> #include <openssl/fips_names.h> #include <openssl/core_names.h> #include <openssl/self_test.h> #include <openssl/fipskey.h> #include "apps.h" #include "progs.h" #define BUFSIZE 4096 #define VERSION_KEY "version" #define VERSION_VAL "1" #define INSTALL_STATUS_VAL "INSTALL_SELF_TEST_KATS_RUN" static OSSL_CALLBACK self_test_events; static char *self_test_corrupt_desc = NULL; static char *self_test_corrupt_type = NULL; static int self_test_log = 1; static int quiet = 0; typedef enum OPTION_choice { OPT_COMMON, OPT_IN, OPT_OUT, OPT_MODULE, OPT_PEDANTIC, OPT_PROV_NAME, OPT_SECTION_NAME, OPT_MAC_NAME, OPT_MACOPT, OPT_VERIFY, OPT_NO_LOG, OPT_CORRUPT_DESC, OPT_CORRUPT_TYPE, OPT_QUIET, OPT_CONFIG, OPT_NO_CONDITIONAL_ERRORS, OPT_NO_SECURITY_CHECKS, OPT_TLS_PRF_EMS_CHECK, OPT_DISALLOW_DRGB_TRUNC_DIGEST, OPT_SELF_TEST_ONLOAD, OPT_SELF_TEST_ONINSTALL } OPTION_CHOICE; const OPTIONS fipsinstall_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"pedantic", OPT_PEDANTIC, '-', "Set options for strict FIPS compliance"}, {"verify", OPT_VERIFY, '-', "Verify a config file instead of generating one"}, {"module", OPT_MODULE, '<', "File name of the provider module"}, {"provider_name", OPT_PROV_NAME, 's', "FIPS provider name"}, {"section_name", OPT_SECTION_NAME, 's', "FIPS Provider config section name (optional)"}, {"no_conditional_errors", OPT_NO_CONDITIONAL_ERRORS, '-', "Disable the ability of the fips module to enter an error state if" " any conditional self tests fail"}, {"no_security_checks", OPT_NO_SECURITY_CHECKS, '-', "Disable the run-time FIPS security checks in the module"}, {"self_test_onload", OPT_SELF_TEST_ONLOAD, '-', "Forces self tests to always run on module load"}, {"self_test_oninstall", OPT_SELF_TEST_ONINSTALL, '-', "Forces self tests to run once on module installation"}, {"ems_check", OPT_TLS_PRF_EMS_CHECK, '-', "Enable the run-time FIPS check for EMS during TLS1_PRF"}, {"no_drbg_truncated_digests", OPT_DISALLOW_DRGB_TRUNC_DIGEST, '-', "Disallow truncated digests with Hash and HMAC DRBGs"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input config file, used when verifying"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output config file, used when generating"}, {"mac_name", OPT_MAC_NAME, 's', "MAC name"}, {"macopt", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form."}, {OPT_MORE_STR, 0, 0, "See 'PARAMETER NAMES' in the EVP_MAC_ docs"}, {"noout", OPT_NO_LOG, '-', "Disable logging of self test events"}, {"corrupt_desc", OPT_CORRUPT_DESC, 's', "Corrupt a self test by description"}, {"corrupt_type", OPT_CORRUPT_TYPE, 's', "Corrupt a self test by type"}, {"config", OPT_CONFIG, '<', "The parent config to verify"}, {"quiet", OPT_QUIET, '-', "No messages, just exit status"}, {NULL} }; typedef struct { unsigned int self_test_onload : 1; unsigned int conditional_errors : 1; unsigned int security_checks : 1; unsigned int tls_prf_ems_check : 1; unsigned int drgb_no_trunc_dgst : 1; } FIPS_OPTS; static const FIPS_OPTS pedantic_opts = { 1, 1, 1, 1, 1, }; static FIPS_OPTS fips_opts = { 1, 1, 1, 0, 0, }; static int check_non_pedantic_fips(int pedantic, const char *name) { if (pedantic) { BIO_printf(bio_err, "Cannot specify -%s after -pedantic\n", name); return 0; } return 1; } static int do_mac(EVP_MAC_CTX *ctx, unsigned char *tmp, BIO *in, unsigned char *out, size_t *out_len) { int ret = 0; int i; size_t outsz = *out_len; if (!EVP_MAC_init(ctx, NULL, 0, NULL)) goto err; if (EVP_MAC_CTX_get_mac_size(ctx) > outsz) goto end; while ((i = BIO_read(in, (char *)tmp, BUFSIZE)) != 0) { if (i < 0 || !EVP_MAC_update(ctx, tmp, i)) goto err; } end: if (!EVP_MAC_final(ctx, out, out_len, outsz)) goto err; ret = 1; err: return ret; } static int load_fips_prov_and_run_self_test(const char *prov_name) { int ret = 0; OSSL_PROVIDER *prov = NULL; OSSL_PARAM params[4], *p = params; char *name = "", *vers = "", *build = ""; prov = OSSL_PROVIDER_load(NULL, prov_name); if (prov == NULL) { BIO_printf(bio_err, "Failed to load FIPS module\n"); goto end; } if (!quiet) { *p++ = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_NAME, &name, sizeof(name)); *p++ = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_VERSION, &vers, sizeof(vers)); *p++ = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_BUILDINFO, &build, sizeof(build)); *p = OSSL_PARAM_construct_end(); if (!OSSL_PROVIDER_get_params(prov, params)) { BIO_printf(bio_err, "Failed to query FIPS module parameters\n"); goto end; } if (OSSL_PARAM_modified(params)) BIO_printf(bio_err, "\t%-10s\t%s\n", "name:", name); if (OSSL_PARAM_modified(params + 1)) BIO_printf(bio_err, "\t%-10s\t%s\n", "version:", vers); if (OSSL_PARAM_modified(params + 2)) BIO_printf(bio_err, "\t%-10s\t%s\n", "build:", build); } ret = 1; end: OSSL_PROVIDER_unload(prov); return ret; } static int print_mac(BIO *bio, const char *label, const unsigned char *mac, size_t len) { int ret; char *hexstr = NULL; hexstr = OPENSSL_buf2hexstr(mac, (long)len); if (hexstr == NULL) return 0; ret = BIO_printf(bio, "%s = %s\n", label, hexstr); OPENSSL_free(hexstr); return ret; } static int write_config_header(BIO *out, const char *prov_name, const char *section) { return BIO_printf(out, "openssl_conf = openssl_init\n\n") && BIO_printf(out, "[openssl_init]\n") && BIO_printf(out, "providers = provider_section\n\n") && BIO_printf(out, "[provider_section]\n") && BIO_printf(out, "%s = %s\n\n", prov_name, section); } static int write_config_fips_section(BIO *out, const char *section, unsigned char *module_mac, size_t module_mac_len, const FIPS_OPTS *opts, unsigned char *install_mac, size_t install_mac_len) { int ret = 0; if (BIO_printf(out, "[%s]\n", section) <= 0 || BIO_printf(out, "activate = 1\n") <= 0 || BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_INSTALL_VERSION, VERSION_VAL) <= 0 || BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_CONDITIONAL_ERRORS, opts->conditional_errors ? "1" : "0") <= 0 || BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_SECURITY_CHECKS, opts->security_checks ? "1" : "0") <= 0 || BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_TLS1_PRF_EMS_CHECK, opts->tls_prf_ems_check ? "1" : "0") <= 0 || BIO_printf(out, "%s = %s\n", OSSL_PROV_PARAM_DRBG_TRUNC_DIGEST, opts->drgb_no_trunc_dgst ? "1" : "0") <= 0 || !print_mac(out, OSSL_PROV_FIPS_PARAM_MODULE_MAC, module_mac, module_mac_len)) goto end; if (install_mac != NULL && install_mac_len > 0) { if (!print_mac(out, OSSL_PROV_FIPS_PARAM_INSTALL_MAC, install_mac, install_mac_len) || BIO_printf(out, "%s = %s\n", OSSL_PROV_FIPS_PARAM_INSTALL_STATUS, INSTALL_STATUS_VAL) <= 0) goto end; } ret = 1; end: return ret; } static CONF *generate_config_and_load(const char *prov_name, const char *section, unsigned char *module_mac, size_t module_mac_len, const FIPS_OPTS *opts) { BIO *mem_bio = NULL; CONF *conf = NULL; mem_bio = BIO_new(BIO_s_mem()); if (mem_bio == NULL) return 0; if (!write_config_header(mem_bio, prov_name, section) || !write_config_fips_section(mem_bio, section, module_mac, module_mac_len, opts, NULL, 0)) goto end; conf = app_load_config_bio(mem_bio, NULL); if (conf == NULL) goto end; if (CONF_modules_load(conf, NULL, 0) <= 0) goto end; BIO_free(mem_bio); return conf; end: NCONF_free(conf); BIO_free(mem_bio); return NULL; } static void free_config_and_unload(CONF *conf) { if (conf != NULL) { NCONF_free(conf); CONF_modules_unload(1); } } static int verify_module_load(const char *parent_config_file) { return OSSL_LIB_CTX_load_config(NULL, parent_config_file); } static int verify_config(const char *infile, const char *section, unsigned char *module_mac, size_t module_mac_len, unsigned char *install_mac, size_t install_mac_len) { int ret = 0; char *s = NULL; unsigned char *buf1 = NULL, *buf2 = NULL; long len; CONF *conf = NULL; conf = app_load_config(infile); if (conf == NULL) goto end; s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_INSTALL_VERSION); if (s == NULL || strcmp(s, VERSION_VAL) != 0) { BIO_printf(bio_err, "version not found\n"); goto end; } s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_MODULE_MAC); if (s == NULL) { BIO_printf(bio_err, "Module integrity MAC not found\n"); goto end; } buf1 = OPENSSL_hexstr2buf(s, &len); if (buf1 == NULL || (size_t)len != module_mac_len || memcmp(module_mac, buf1, module_mac_len) != 0) { BIO_printf(bio_err, "Module integrity mismatch\n"); goto end; } if (install_mac != NULL && install_mac_len > 0) { s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_INSTALL_STATUS); if (s == NULL || strcmp(s, INSTALL_STATUS_VAL) != 0) { BIO_printf(bio_err, "install status not found\n"); goto end; } s = NCONF_get_string(conf, section, OSSL_PROV_FIPS_PARAM_INSTALL_MAC); if (s == NULL) { BIO_printf(bio_err, "Install indicator MAC not found\n"); goto end; } buf2 = OPENSSL_hexstr2buf(s, &len); if (buf2 == NULL || (size_t)len != install_mac_len || memcmp(install_mac, buf2, install_mac_len) != 0) { BIO_printf(bio_err, "Install indicator status mismatch\n"); goto end; } } ret = 1; end: OPENSSL_free(buf1); OPENSSL_free(buf2); NCONF_free(conf); return ret; } int fipsinstall_main(int argc, char **argv) { int ret = 1, verify = 0, gotkey = 0, gotdigest = 0, pedantic = 0; const char *section_name = "fips_sect"; const char *mac_name = "HMAC"; const char *prov_name = "fips"; BIO *module_bio = NULL, *mem_bio = NULL, *fout = NULL; char *in_fname = NULL, *out_fname = NULL, *prog; char *module_fname = NULL, *parent_config = NULL, *module_path = NULL; const char *tail; EVP_MAC_CTX *ctx = NULL, *ctx2 = NULL; STACK_OF(OPENSSL_STRING) *opts = NULL; OPTION_CHOICE o; unsigned char *read_buffer = NULL; unsigned char module_mac[EVP_MAX_MD_SIZE]; size_t module_mac_len = EVP_MAX_MD_SIZE; unsigned char install_mac[EVP_MAX_MD_SIZE]; size_t install_mac_len = EVP_MAX_MD_SIZE; EVP_MAC *mac = NULL; CONF *conf = NULL; if ((opts = sk_OPENSSL_STRING_new_null()) == NULL) goto end; prog = opt_init(argc, argv, fipsinstall_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 cleanup; case OPT_HELP: opt_help(fipsinstall_options); ret = 0; goto end; case OPT_IN: in_fname = opt_arg(); break; case OPT_OUT: out_fname = opt_arg(); break; case OPT_PEDANTIC: fips_opts = pedantic_opts; pedantic = 1; break; case OPT_NO_CONDITIONAL_ERRORS: if (!check_non_pedantic_fips(pedantic, "no_conditional_errors")) goto end; fips_opts.conditional_errors = 0; break; case OPT_NO_SECURITY_CHECKS: if (!check_non_pedantic_fips(pedantic, "no_security_checks")) goto end; fips_opts.security_checks = 0; break; case OPT_TLS_PRF_EMS_CHECK: fips_opts.tls_prf_ems_check = 1; break; case OPT_DISALLOW_DRGB_TRUNC_DIGEST: fips_opts.drgb_no_trunc_dgst = 1; break; case OPT_QUIET: quiet = 1; case OPT_NO_LOG: self_test_log = 0; break; case OPT_CORRUPT_DESC: self_test_corrupt_desc = opt_arg(); break; case OPT_CORRUPT_TYPE: self_test_corrupt_type = opt_arg(); break; case OPT_PROV_NAME: prov_name = opt_arg(); break; case OPT_MODULE: module_fname = opt_arg(); break; case OPT_SECTION_NAME: section_name = opt_arg(); break; case OPT_MAC_NAME: mac_name = opt_arg(); break; case OPT_CONFIG: parent_config = opt_arg(); break; case OPT_MACOPT: if (!sk_OPENSSL_STRING_push(opts, opt_arg())) goto opthelp; if (HAS_PREFIX(opt_arg(), "hexkey:")) gotkey = 1; else if (HAS_PREFIX(opt_arg(), "digest:")) gotdigest = 1; break; case OPT_VERIFY: verify = 1; break; case OPT_SELF_TEST_ONLOAD: fips_opts.self_test_onload = 1; break; case OPT_SELF_TEST_ONINSTALL: if (!check_non_pedantic_fips(pedantic, "self_test_oninstall")) goto end; fips_opts.self_test_onload = 0; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (verify && in_fname == NULL) { BIO_printf(bio_err, "Missing -in option for -verify\n"); goto opthelp; } if (parent_config != NULL) { if (verify_module_load(parent_config)) { ret = OSSL_PROVIDER_available(NULL, prov_name) ? 0 : 1; if (!quiet) { BIO_printf(bio_err, "FIPS provider is %s\n", ret == 0 ? "available" : " not available"); } } goto end; } if (module_fname == NULL) goto opthelp; tail = opt_path_end(module_fname); if (tail != NULL) { module_path = OPENSSL_strdup(module_fname); if (module_path == NULL) goto end; module_path[tail - module_fname] = '\0'; if (!OSSL_PROVIDER_set_default_search_path(NULL, module_path)) goto end; } if (self_test_log || self_test_corrupt_desc != NULL || self_test_corrupt_type != NULL) OSSL_SELF_TEST_set_callback(NULL, self_test_events, NULL); if (!gotdigest && !sk_OPENSSL_STRING_push(opts, "digest:SHA256")) goto end; if (!gotkey && !sk_OPENSSL_STRING_push(opts, "hexkey:" FIPS_KEY_STRING)) goto end; module_bio = bio_open_default(module_fname, 'r', FORMAT_BINARY); if (module_bio == NULL) { BIO_printf(bio_err, "Failed to open module file\n"); goto end; } read_buffer = app_malloc(BUFSIZE, "I/O buffer"); if (read_buffer == NULL) goto end; mac = EVP_MAC_fetch(app_get0_libctx(), mac_name, app_get0_propq()); if (mac == NULL) { BIO_printf(bio_err, "Unable to get MAC of type %s\n", mac_name); goto end; } ctx = EVP_MAC_CTX_new(mac); if (ctx == NULL) { BIO_printf(bio_err, "Unable to create MAC CTX for module check\n"); goto end; } if (opts != NULL) { int ok = 1; OSSL_PARAM *params = app_params_new_from_opts(opts, EVP_MAC_settable_ctx_params(mac)); if (params == NULL) goto end; if (!EVP_MAC_CTX_set_params(ctx, params)) { BIO_printf(bio_err, "MAC parameter error\n"); ERR_print_errors(bio_err); ok = 0; } app_params_free(params); if (!ok) goto end; } ctx2 = EVP_MAC_CTX_dup(ctx); if (ctx2 == NULL) { BIO_printf(bio_err, "Unable to create MAC CTX for install indicator\n"); goto end; } if (!do_mac(ctx, read_buffer, module_bio, module_mac, &module_mac_len)) goto end; if (fips_opts.self_test_onload == 0) { mem_bio = BIO_new_mem_buf((const void *)INSTALL_STATUS_VAL, strlen(INSTALL_STATUS_VAL)); if (mem_bio == NULL) { BIO_printf(bio_err, "Unable to create memory BIO\n"); goto end; } if (!do_mac(ctx2, read_buffer, mem_bio, install_mac, &install_mac_len)) goto end; } else { install_mac_len = 0; } if (verify) { if (!verify_config(in_fname, section_name, module_mac, module_mac_len, install_mac, install_mac_len)) goto end; if (!quiet) BIO_printf(bio_err, "VERIFY PASSED\n"); } else { conf = generate_config_and_load(prov_name, section_name, module_mac, module_mac_len, &fips_opts); if (conf == NULL) goto end; if (!load_fips_prov_and_run_self_test(prov_name)) goto end; fout = out_fname == NULL ? dup_bio_out(FORMAT_TEXT) : bio_open_default(out_fname, 'w', FORMAT_TEXT); if (fout == NULL) { BIO_printf(bio_err, "Failed to open file\n"); goto end; } if (!write_config_fips_section(fout, section_name, module_mac, module_mac_len, &fips_opts, install_mac, install_mac_len)) goto end; if (!quiet) BIO_printf(bio_err, "INSTALL PASSED\n"); } ret = 0; end: if (ret == 1) { if (!quiet) BIO_printf(bio_err, "%s FAILED\n", verify ? "VERIFY" : "INSTALL"); ERR_print_errors(bio_err); } cleanup: OPENSSL_free(module_path); BIO_free(fout); BIO_free(mem_bio); BIO_free(module_bio); sk_OPENSSL_STRING_free(opts); EVP_MAC_free(mac); EVP_MAC_CTX_free(ctx2); EVP_MAC_CTX_free(ctx); OPENSSL_free(read_buffer); free_config_and_unload(conf); return ret; } static int self_test_events(const OSSL_PARAM params[], void *arg) { const OSSL_PARAM *p = NULL; const char *phase = NULL, *type = NULL, *desc = NULL; int ret = 0; p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_PHASE); if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) goto err; phase = (const char *)p->data; p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_DESC); if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) goto err; desc = (const char *)p->data; p = OSSL_PARAM_locate_const(params, OSSL_PROV_PARAM_SELF_TEST_TYPE); if (p == NULL || p->data_type != OSSL_PARAM_UTF8_STRING) goto err; type = (const char *)p->data; if (self_test_log) { if (strcmp(phase, OSSL_SELF_TEST_PHASE_START) == 0) BIO_printf(bio_err, "%s : (%s) : ", desc, type); else if (strcmp(phase, OSSL_SELF_TEST_PHASE_PASS) == 0 || strcmp(phase, OSSL_SELF_TEST_PHASE_FAIL) == 0) BIO_printf(bio_err, "%s\n", phase); } if (strcmp(phase, OSSL_SELF_TEST_PHASE_CORRUPT) == 0 && (self_test_corrupt_desc != NULL || self_test_corrupt_type != NULL)) { if (self_test_corrupt_desc != NULL && strcmp(self_test_corrupt_desc, desc) != 0) goto end; if (self_test_corrupt_type != NULL && strcmp(self_test_corrupt_type, type) != 0) goto end; BIO_printf(bio_err, "%s ", phase); goto err; } end: ret = 1; err: return ret; }
apps
openssl/apps/fipsinstall.c
openssl
#include "internal/e_os.h" #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <openssl/e_os2.h> #include "internal/nelem.h" #ifndef OPENSSL_NO_SOCK #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT) # define __U_INT typedef unsigned int u_int; #endif #include "apps.h" #include "progs.h" #include <openssl/x509.h> #include <openssl/ssl.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/ocsp.h> #include <openssl/bn.h> #include <openssl/trace.h> #include <openssl/async.h> #ifndef OPENSSL_NO_CT # include <openssl/ct.h> #endif #include "s_apps.h" #include "timeouts.h" #include "internal/sockets.h" #if defined(__has_feature) # if __has_feature(memory_sanitizer) # include <sanitizer/msan_interface.h> # endif #endif #undef BUFSIZZ #define BUFSIZZ 1024*8 #define S_CLIENT_IRC_READ_TIMEOUT 8 #define USER_DATA_MODE_NONE 0 #define USER_DATA_MODE_BASIC 1 #define USER_DATA_MODE_ADVANCED 2 #define USER_DATA_PROCESS_BAD_ARGUMENT 0 #define USER_DATA_PROCESS_SHUT 1 #define USER_DATA_PROCESS_RESTART 2 #define USER_DATA_PROCESS_NO_DATA 3 #define USER_DATA_PROCESS_CONTINUE 4 struct user_data_st { SSL *con; char *buf; size_t bufmax; size_t buflen; size_t bufoff; int mode; int isfin; }; static void user_data_init(struct user_data_st *user_data, SSL *con, char *buf, size_t bufmax, int mode); static int user_data_add(struct user_data_st *user_data, size_t i); static int user_data_process(struct user_data_st *user_data, size_t *len, size_t *off); static int user_data_has_data(struct user_data_st *user_data); static char *prog; static int c_debug = 0; static int c_showcerts = 0; static char *keymatexportlabel = NULL; static int keymatexportlen = 20; static BIO *bio_c_out = NULL; static int c_quiet = 0; static char *sess_out = NULL; static SSL_SESSION *psksess = NULL; static void print_stuff(BIO *berr, SSL *con, int full); #ifndef OPENSSL_NO_OCSP static int ocsp_resp_cb(SSL *s, void *arg); #endif static int ldap_ExtendedResponse_parse(const char *buf, long rem); static int is_dNS_name(const char *host); static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 }; static int enable_server_rpk = 0; static int saved_errno; static void save_errno(void) { saved_errno = errno; errno = 0; } static int restore_errno(void) { int ret = errno; errno = saved_errno; return ret; } static char *psk_identity = "Client_identity"; #ifndef OPENSSL_NO_PSK static unsigned int psk_client_cb(SSL *ssl, const char *hint, char *identity, unsigned int max_identity_len, unsigned char *psk, unsigned int max_psk_len) { int ret; long key_len; unsigned char *key; if (c_debug) BIO_printf(bio_c_out, "psk_client_cb\n"); if (!hint) { if (c_debug) BIO_printf(bio_c_out, "NULL received PSK identity hint, continuing anyway\n"); } else if (c_debug) { BIO_printf(bio_c_out, "Received PSK identity hint '%s'\n", hint); } ret = BIO_snprintf(identity, max_identity_len, "%s", psk_identity); if (ret < 0 || (unsigned int)ret > max_identity_len) goto out_err; if (c_debug) BIO_printf(bio_c_out, "created identity '%s' len=%d\n", identity, ret); key = OPENSSL_hexstr2buf(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } if (max_psk_len > INT_MAX || key_len > (long)max_psk_len) { BIO_printf(bio_err, "psk buffer of callback is too small (%d) for key (%ld)\n", max_psk_len, key_len); OPENSSL_free(key); return 0; } memcpy(psk, key, key_len); OPENSSL_free(key); if (c_debug) BIO_printf(bio_c_out, "created PSK len=%ld\n", key_len); return key_len; out_err: if (c_debug) BIO_printf(bio_err, "Error in PSK client callback\n"); return 0; } #endif const unsigned char tls13_aes128gcmsha256_id[] = { 0x13, 0x01 }; const unsigned char tls13_aes256gcmsha384_id[] = { 0x13, 0x02 }; static int psk_use_session_cb(SSL *s, const EVP_MD *md, const unsigned char **id, size_t *idlen, SSL_SESSION **sess) { SSL_SESSION *usesess = NULL; const SSL_CIPHER *cipher = NULL; if (psksess != NULL) { SSL_SESSION_up_ref(psksess); usesess = psksess; } else { long key_len; unsigned char *key = OPENSSL_hexstr2buf(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } cipher = SSL_CIPHER_find(s, tls13_aes128gcmsha256_id); if (cipher == NULL) { BIO_printf(bio_err, "Error finding suitable ciphersuite\n"); OPENSSL_free(key); return 0; } usesess = SSL_SESSION_new(); if (usesess == NULL || !SSL_SESSION_set1_master_key(usesess, key, key_len) || !SSL_SESSION_set_cipher(usesess, cipher) || !SSL_SESSION_set_protocol_version(usesess, TLS1_3_VERSION)) { OPENSSL_free(key); goto err; } OPENSSL_free(key); } cipher = SSL_SESSION_get0_cipher(usesess); if (cipher == NULL) goto err; if (md != NULL && SSL_CIPHER_get_handshake_digest(cipher) != md) { *id = NULL; *idlen = 0; *sess = NULL; SSL_SESSION_free(usesess); } else { *sess = usesess; *id = (unsigned char *)psk_identity; *idlen = strlen(psk_identity); } return 1; err: SSL_SESSION_free(usesess); return 0; } typedef struct tlsextctx_st { BIO *biodebug; int ack; } tlsextctx; static int ssl_servername_cb(SSL *s, int *ad, void *arg) { tlsextctx *p = (tlsextctx *) arg; const char *hn = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); if (SSL_get_servername_type(s) != -1) p->ack = !SSL_session_reused(s) && hn != NULL; else BIO_printf(bio_err, "Can't use SSL_get_servername\n"); return SSL_TLSEXT_ERR_OK; } #ifndef OPENSSL_NO_NEXTPROTONEG typedef struct tlsextnextprotoctx_st { unsigned char *data; size_t len; int status; } tlsextnextprotoctx; static tlsextnextprotoctx next_proto; static int next_proto_cb(SSL *s, unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { tlsextnextprotoctx *ctx = arg; if (!c_quiet) { unsigned i; BIO_printf(bio_c_out, "Protocols advertised by server: "); for (i = 0; i < inlen;) { if (i) BIO_write(bio_c_out, ", ", 2); BIO_write(bio_c_out, &in[i + 1], in[i]); i += in[i] + 1; } BIO_write(bio_c_out, "\n", 1); } ctx->status = SSL_select_next_proto(out, outlen, in, inlen, ctx->data, ctx->len); return SSL_TLSEXT_ERR_OK; } #endif static int serverinfo_cli_parse_cb(SSL *s, unsigned int ext_type, const unsigned char *in, size_t inlen, int *al, void *arg) { char pem_name[100]; unsigned char ext_buf[4 + 65536]; inlen &= 0xffff; ext_buf[0] = (unsigned char)(ext_type >> 8); ext_buf[1] = (unsigned char)(ext_type); ext_buf[2] = (unsigned char)(inlen >> 8); ext_buf[3] = (unsigned char)(inlen); memcpy(ext_buf + 4, in, inlen); BIO_snprintf(pem_name, sizeof(pem_name), "SERVERINFO FOR EXTENSION %d", ext_type); PEM_write_bio(bio_c_out, pem_name, "", ext_buf, 4 + inlen); return 1; } static ossl_ssize_t hexdecode(const char **inptr, void *result) { unsigned char **out = (unsigned char **)result; const char *in = *inptr; unsigned char *ret = app_malloc(strlen(in) / 2, "hexdecode"); unsigned char *cp = ret; uint8_t byte; int nibble = 0; if (ret == NULL) return -1; for (byte = 0; *in; ++in) { int x; if (isspace(_UC(*in))) continue; x = OPENSSL_hexchar2int(*in); if (x < 0) { OPENSSL_free(ret); return 0; } byte |= (char)x; if ((nibble ^= 1) == 0) { *cp++ = byte; byte = 0; } else { byte <<= 4; } } if (nibble != 0) { OPENSSL_free(ret); return 0; } *inptr = in; return cp - (*out = ret); } static ossl_ssize_t checked_uint8(const char **inptr, void *out) { uint8_t *result = (uint8_t *)out; const char *in = *inptr; char *endp; long v; int e; save_errno(); v = strtol(in, &endp, 10); e = restore_errno(); if (((v == LONG_MIN || v == LONG_MAX) && e == ERANGE) || endp == in || !isspace(_UC(*endp)) || v != (*result = (uint8_t) v)) { return -1; } for (in = endp; isspace(_UC(*in)); ++in) continue; *inptr = in; return 1; } struct tlsa_field { void *var; const char *name; ossl_ssize_t (*parser)(const char **, void *); }; static int tlsa_import_rr(SSL *con, const char *rrdata) { static uint8_t usage; static uint8_t selector; static uint8_t mtype; static unsigned char *data; static struct tlsa_field tlsa_fields[] = { { &usage, "usage", checked_uint8 }, { &selector, "selector", checked_uint8 }, { &mtype, "mtype", checked_uint8 }, { &data, "data", hexdecode }, { NULL, } }; struct tlsa_field *f; int ret; const char *cp = rrdata; ossl_ssize_t len = 0; for (f = tlsa_fields; f->var; ++f) { if ((len = f->parser(&cp, f->var)) <= 0) { BIO_printf(bio_err, "%s: warning: bad TLSA %s field in: %s\n", prog, f->name, rrdata); return 0; } } ret = SSL_dane_tlsa_add(con, usage, selector, mtype, data, len); OPENSSL_free(data); if (ret == 0) { ERR_print_errors(bio_err); BIO_printf(bio_err, "%s: warning: unusable TLSA rrdata: %s\n", prog, rrdata); return 0; } if (ret < 0) { ERR_print_errors(bio_err); BIO_printf(bio_err, "%s: warning: error loading TLSA rrdata: %s\n", prog, rrdata); return 0; } return ret; } static int tlsa_import_rrset(SSL *con, STACK_OF(OPENSSL_STRING) *rrset) { int num = sk_OPENSSL_STRING_num(rrset); int count = 0; int i; for (i = 0; i < num; ++i) { char *rrdata = sk_OPENSSL_STRING_value(rrset, i); if (tlsa_import_rr(con, rrdata) > 0) ++count; } return count > 0; } typedef enum OPTION_choice { OPT_COMMON, OPT_4, OPT_6, OPT_HOST, OPT_PORT, OPT_CONNECT, OPT_BIND, OPT_UNIX, OPT_XMPPHOST, OPT_VERIFY, OPT_NAMEOPT, OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SESS_OUT, OPT_SESS_IN, OPT_CERTFORM, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET, OPT_BRIEF, OPT_PREXIT, OPT_NO_INTERACTIVE, OPT_CRLF, OPT_QUIET, OPT_NBIO, OPT_SSL_CLIENT_ENGINE, OPT_IGN_EOF, OPT_NO_IGN_EOF, OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_WDEBUG, OPT_MSG, OPT_MSGFILE, OPT_ENGINE, OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_SHOWCERTS, OPT_NBIO_TEST, OPT_STATE, OPT_PSK_IDENTITY, OPT_PSK, OPT_PSK_SESS, #ifndef OPENSSL_NO_SRP OPT_SRPUSER, OPT_SRPPASS, OPT_SRP_STRENGTH, OPT_SRP_LATEUSER, OPT_SRP_MOREGROUPS, #endif OPT_SSL3, OPT_SSL_CONFIG, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1, OPT_DTLS1_2, OPT_QUIC, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_KEYFORM, OPT_PASS, OPT_CERT_CHAIN, OPT_KEY, OPT_RECONNECT, OPT_BUILD_CHAIN, OPT_NEXTPROTONEG, OPT_ALPN, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE, OPT_SERVERINFO, OPT_STARTTLS, OPT_SERVERNAME, OPT_NOSERVERNAME, OPT_ASYNC, OPT_USE_SRTP, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_PROTOHOST, OPT_MAXFRAGLEN, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF, OPT_KEYLOG_FILE, OPT_EARLY_DATA, OPT_REQCAFILE, OPT_TFO, OPT_V_ENUM, OPT_X_ENUM, OPT_S_ENUM, OPT_IGNORE_UNEXPECTED_EOF, OPT_FALLBACKSCSV, OPT_NOCMDS, OPT_ADV, OPT_PROXY, OPT_PROXY_USER, OPT_PROXY_PASS, OPT_DANE_TLSA_DOMAIN, #ifndef OPENSSL_NO_CT OPT_CT, OPT_NOCT, OPT_CTLOG_FILE, #endif OPT_DANE_TLSA_RRDATA, OPT_DANE_EE_NO_NAME, OPT_ENABLE_PHA, OPT_ENABLE_SERVER_RPK, OPT_ENABLE_CLIENT_RPK, OPT_SCTP_LABEL_BUG, OPT_KTLS, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS s_client_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [host:port]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, {"ssl_client_engine", OPT_SSL_CLIENT_ENGINE, 's', "Specify engine to be used for client certificate operations"}, #endif {"ssl_config", OPT_SSL_CONFIG, 's', "Use specified section for SSL_CTX configuration"}, #ifndef OPENSSL_NO_CT {"ct", OPT_CT, '-', "Request and parse SCTs (also enables OCSP stapling)"}, {"noct", OPT_NOCT, '-', "Do not request or parse SCTs (default)"}, {"ctlogfile", OPT_CTLOG_FILE, '<', "CT log list CONF file"}, #endif OPT_SECTION("Network"), {"host", OPT_HOST, 's', "Use -connect instead"}, {"port", OPT_PORT, 'p', "Use -connect instead"}, {"connect", OPT_CONNECT, 's', "TCP/IP where to connect; default: " PORT ")"}, {"bind", OPT_BIND, 's', "bind local address for connection"}, {"proxy", OPT_PROXY, 's', "Connect to via specified proxy to the real server"}, {"proxy_user", OPT_PROXY_USER, 's', "UserID for proxy authentication"}, {"proxy_pass", OPT_PROXY_PASS, 's', "Proxy authentication password source"}, #ifdef AF_UNIX {"unix", OPT_UNIX, 's', "Connect over the specified Unix-domain socket"}, #endif {"4", OPT_4, '-', "Use IPv4 only"}, #ifdef AF_INET6 {"6", OPT_6, '-', "Use IPv6 only"}, #endif {"maxfraglen", OPT_MAXFRAGLEN, 'p', "Enable Maximum Fragment Length Negotiation (len values: 512, 1024, 2048 and 4096)"}, {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "}, {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p', "Size used to split data for encrypt pipelines"}, {"max_pipelines", OPT_MAX_PIPELINES, 'p', "Maximum number of encrypt/decrypt pipelines to be used"}, {"read_buf", OPT_READ_BUF, 'p', "Default read buffer size to be used for connections"}, {"fallback_scsv", OPT_FALLBACKSCSV, '-', "Send the fallback SCSV"}, OPT_SECTION("Identity"), {"cert", OPT_CERT, '<', "Client certificate file to use"}, {"certform", OPT_CERTFORM, 'F', "Client certificate file format (PEM/DER/P12); has no effect"}, {"cert_chain", OPT_CERT_CHAIN, '<', "Client certificate chain file (in PEM format)"}, {"build_chain", OPT_BUILD_CHAIN, '-', "Build client certificate chain"}, {"key", OPT_KEY, 's', "Private key file to use; default: -cert file"}, {"keyform", OPT_KEYFORM, 'E', "Key format (ENGINE, other values ignored)"}, {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"}, {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification"}, {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"}, {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"}, {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, {"requestCAfile", OPT_REQCAFILE, '<', "PEM format file of CA names to send to the server"}, #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO) {"tfo", OPT_TFO, '-', "Connect using TCP Fast Open"}, #endif {"dane_tlsa_domain", OPT_DANE_TLSA_DOMAIN, 's', "DANE TLSA base domain"}, {"dane_tlsa_rrdata", OPT_DANE_TLSA_RRDATA, 's', "DANE TLSA rrdata presentation form"}, {"dane_ee_no_namechecks", OPT_DANE_EE_NO_NAME, '-', "Disable name checks when matching DANE-EE(3) TLSA records"}, {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity"}, {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"}, {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"}, {"name", OPT_PROTOHOST, 's', "Hostname to use for \"-starttls lmtp\", \"-starttls smtp\" or \"-starttls xmpp[-server]\""}, OPT_SECTION("Session"), {"reconnect", OPT_RECONNECT, '-', "Drop and re-make the connection with the same Session-ID"}, {"sess_out", OPT_SESS_OUT, '>', "File to write SSL session to"}, {"sess_in", OPT_SESS_IN, '<', "File to read SSL session from"}, OPT_SECTION("Input/Output"), {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"}, {"quiet", OPT_QUIET, '-', "No s_client output"}, {"ign_eof", OPT_IGN_EOF, '-', "Ignore input eof (default when -quiet)"}, {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Don't ignore input eof"}, {"starttls", OPT_STARTTLS, 's', "Use the appropriate STARTTLS command before starting TLS"}, {"xmpphost", OPT_XMPPHOST, 's', "Alias of -name option for \"-starttls xmpp[-server]\""}, {"brief", OPT_BRIEF, '-', "Restrict output to brief summary of connection parameters"}, {"prexit", OPT_PREXIT, '-', "Print session information when the program exits"}, {"no-interactive", OPT_NO_INTERACTIVE, '-', "Don't run the client in the interactive mode"}, OPT_SECTION("Debug"), {"showcerts", OPT_SHOWCERTS, '-', "Show all certificates sent by the server"}, {"debug", OPT_DEBUG, '-', "Extra output"}, {"msg", OPT_MSG, '-', "Show protocol messages"}, {"msgfile", OPT_MSGFILE, '>', "File to send output of -msg or -trace, instead of stdout"}, {"nbio_test", OPT_NBIO_TEST, '-', "More ssl protocol testing"}, {"state", OPT_STATE, '-', "Print the ssl states"}, {"keymatexport", OPT_KEYMATEXPORT, 's', "Export keying material using label"}, {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p', "Export len bytes of keying material; default 20"}, {"security_debug", OPT_SECURITY_DEBUG, '-', "Enable security debug messages"}, {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-', "Output more security debug output"}, #ifndef OPENSSL_NO_SSL_TRACE {"trace", OPT_TRACE, '-', "Show trace output of protocol messages"}, #endif #ifdef WATT32 {"wdebug", OPT_WDEBUG, '-', "WATT-32 tcp debugging"}, #endif {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"}, {"nocommands", OPT_NOCMDS, '-', "Do not use interactive command letters"}, {"adv", OPT_ADV, '-', "Advanced command mode"}, {"servername", OPT_SERVERNAME, 's', "Set TLS extension servername (SNI) in ClientHello (default)"}, {"noservername", OPT_NOSERVERNAME, '-', "Do not send the server name (SNI) extension in the ClientHello"}, {"tlsextdebug", OPT_TLSEXTDEBUG, '-', "Hex dump of all TLS extensions received"}, {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-', "Do not treat lack of close_notify from a peer as an error"}, #ifndef OPENSSL_NO_OCSP {"status", OPT_STATUS, '-', "Request certificate status from server"}, #endif {"serverinfo", OPT_SERVERINFO, 's', "types Send empty ClientHello extensions (comma-separated numbers)"}, {"alpn", OPT_ALPN, 's', "Enable ALPN extension, considering named protocols supported (comma-separated list)"}, {"async", OPT_ASYNC, '-', "Support asynchronous operation"}, {"nbio", OPT_NBIO, '-', "Use non-blocking IO"}, OPT_SECTION("Protocol and version"), #ifndef OPENSSL_NO_SSL3 {"ssl3", OPT_SSL3, '-', "Just use SSLv3"}, #endif #ifndef OPENSSL_NO_TLS1 {"tls1", OPT_TLS1, '-', "Just use TLSv1"}, #endif #ifndef OPENSSL_NO_TLS1_1 {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"}, #endif #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"}, #endif #ifndef OPENSSL_NO_TLS1_3 {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"}, #endif #ifndef OPENSSL_NO_DTLS {"dtls", OPT_DTLS, '-', "Use any version of DTLS"}, {"quic", OPT_QUIC, '-', "Use QUIC"}, {"timeout", OPT_TIMEOUT, '-', "Enable send/receive timeout on DTLS connections"}, {"mtu", OPT_MTU, 'p', "Set the link layer MTU"}, #endif #ifndef OPENSSL_NO_DTLS1 {"dtls1", OPT_DTLS1, '-', "Just use DTLSv1"}, #endif #ifndef OPENSSL_NO_DTLS1_2 {"dtls1_2", OPT_DTLS1_2, '-', "Just use DTLSv1.2"}, #endif #ifndef OPENSSL_NO_SCTP {"sctp", OPT_SCTP, '-', "Use SCTP"}, {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"}, #endif #ifndef OPENSSL_NO_NEXTPROTONEG {"nextprotoneg", OPT_NEXTPROTONEG, 's', "Enable NPN extension, considering named protocols supported (comma-separated list)"}, #endif {"early_data", OPT_EARLY_DATA, '<', "File to send as early data"}, {"enable_pha", OPT_ENABLE_PHA, '-', "Enable post-handshake-authentication"}, {"enable_server_rpk", OPT_ENABLE_SERVER_RPK, '-', "Enable raw public keys (RFC7250) from the server"}, {"enable_client_rpk", OPT_ENABLE_CLIENT_RPK, '-', "Enable raw public keys (RFC7250) from the client"}, #ifndef OPENSSL_NO_SRTP {"use_srtp", OPT_USE_SRTP, 's', "Offer SRTP key management with a colon-separated profile list"}, #endif #ifndef OPENSSL_NO_SRP {"srpuser", OPT_SRPUSER, 's', "(deprecated) SRP authentication for 'user'"}, {"srppass", OPT_SRPPASS, 's', "(deprecated) Password for 'user'"}, {"srp_lateuser", OPT_SRP_LATEUSER, '-', "(deprecated) SRP username into second ClientHello message"}, {"srp_moregroups", OPT_SRP_MOREGROUPS, '-', "(deprecated) Tolerate other than the known g N values."}, {"srp_strength", OPT_SRP_STRENGTH, 'p', "(deprecated) Minimal length in bits for N"}, #endif #ifndef OPENSSL_NO_KTLS {"ktls", OPT_KTLS, '-', "Enable Kernel TLS for sending and receiving"}, #endif OPT_R_OPTIONS, OPT_S_OPTIONS, OPT_V_OPTIONS, {"CRL", OPT_CRL, '<', "CRL file to use"}, {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRL from distribution points"}, {"CRLform", OPT_CRLFORM, 'F', "CRL format (PEM or DER); default PEM"}, {"verify_return_error", OPT_VERIFY_RET_ERROR, '-', "Close connection on verification error"}, {"verify_quiet", OPT_VERIFY_QUIET, '-', "Restrict verify output to errors"}, {"chainCAfile", OPT_CHAINCAFILE, '<', "CA file for certificate chain (PEM format)"}, {"chainCApath", OPT_CHAINCAPATH, '/', "Use dir as certificate store path to build CA certificate chain"}, {"chainCAstore", OPT_CHAINCASTORE, ':', "CA store URI for certificate chain"}, {"verifyCAfile", OPT_VERIFYCAFILE, '<', "CA file for certificate verification (PEM format)"}, {"verifyCApath", OPT_VERIFYCAPATH, '/', "Use dir as certificate store path to verify CA certificate"}, {"verifyCAstore", OPT_VERIFYCASTORE, ':', "CA store URI for certificate verification"}, OPT_X_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"host:port", 0, 0, "Where to connect; same as -connect option"}, {NULL} }; typedef enum PROTOCOL_choice { PROTO_OFF, PROTO_SMTP, PROTO_POP3, PROTO_IMAP, PROTO_FTP, PROTO_TELNET, PROTO_XMPP, PROTO_XMPP_SERVER, PROTO_IRC, PROTO_MYSQL, PROTO_POSTGRES, PROTO_LMTP, PROTO_NNTP, PROTO_SIEVE, PROTO_LDAP } PROTOCOL_CHOICE; static const OPT_PAIR services[] = { {"smtp", PROTO_SMTP}, {"pop3", PROTO_POP3}, {"imap", PROTO_IMAP}, {"ftp", PROTO_FTP}, {"xmpp", PROTO_XMPP}, {"xmpp-server", PROTO_XMPP_SERVER}, {"telnet", PROTO_TELNET}, {"irc", PROTO_IRC}, {"mysql", PROTO_MYSQL}, {"postgres", PROTO_POSTGRES}, {"lmtp", PROTO_LMTP}, {"nntp", PROTO_NNTP}, {"sieve", PROTO_SIEVE}, {"ldap", PROTO_LDAP}, {NULL, 0} }; #define IS_INET_FLAG(o) \ (o == OPT_4 || o == OPT_6 || o == OPT_HOST || o == OPT_PORT || o == OPT_CONNECT) #define IS_UNIX_FLAG(o) (o == OPT_UNIX) #define IS_PROT_FLAG(o) \ (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \ || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2 \ || o == OPT_QUIC) static void freeandcopy(char **dest, const char *source) { OPENSSL_free(*dest); *dest = NULL; if (source != NULL) *dest = OPENSSL_strdup(source); } static int new_session_cb(SSL *s, SSL_SESSION *sess) { if (sess_out != NULL) { BIO *stmp = BIO_new_file(sess_out, "w"); if (stmp == NULL) { BIO_printf(bio_err, "Error writing session file %s\n", sess_out); } else { PEM_write_bio_SSL_SESSION(stmp, sess); BIO_free(stmp); } } if (SSL_version(s) == TLS1_3_VERSION) { BIO_printf(bio_c_out, "---\nPost-Handshake New Session Ticket arrived:\n"); SSL_SESSION_print(bio_c_out, sess); BIO_printf(bio_c_out, "---\n"); } return 0; } int s_client_main(int argc, char **argv) { BIO *sbio; EVP_PKEY *key = NULL; SSL *con = NULL; SSL_CTX *ctx = NULL; STACK_OF(X509) *chain = NULL; X509 *cert = NULL; X509_VERIFY_PARAM *vpm = NULL; SSL_EXCERT *exc = NULL; SSL_CONF_CTX *cctx = NULL; STACK_OF(OPENSSL_STRING) *ssl_args = NULL; char *dane_tlsa_domain = NULL; STACK_OF(OPENSSL_STRING) *dane_tlsa_rrset = NULL; int dane_ee_no_name = 0; STACK_OF(X509_CRL) *crls = NULL; const SSL_METHOD *meth = TLS_client_method(); const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL; char *cbuf = NULL, *sbuf = NULL, *mbuf = NULL; char *proxystr = NULL, *proxyuser = NULL; char *proxypassarg = NULL, *proxypass = NULL; char *connectstr = NULL, *bindstr = NULL; char *cert_file = NULL, *key_file = NULL, *chain_file = NULL; char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL, *host = NULL; char *thost = NULL, *tport = NULL; char *port = NULL; char *bindhost = NULL, *bindport = NULL; char *passarg = NULL, *pass = NULL; char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL; char *ReqCAfile = NULL; char *sess_in = NULL, *crl_file = NULL, *p; const char *protohost = NULL; struct timeval timeout, *timeoutp; fd_set readfds, writefds; int noCApath = 0, noCAfile = 0, noCAstore = 0; int build_chain = 0, cert_format = FORMAT_UNDEF; size_t cbuf_len, cbuf_off; int key_format = FORMAT_UNDEF, crlf = 0, full_log = 1, mbuf_len = 0; int prexit = 0; int nointeractive = 0; int sdebug = 0; int reconnect = 0, verify = SSL_VERIFY_NONE, vpmtouched = 0; int ret = 1, in_init = 1, i, nbio_test = 0, sock = -1, k, width, state = 0; int sbuf_len, sbuf_off, cmdmode = USER_DATA_MODE_BASIC; int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0; int starttls_proto = PROTO_OFF, crl_format = FORMAT_UNDEF, crl_download = 0; int write_tty, read_tty, write_ssl, read_ssl, tty_on, ssl_pending; int first_loop; #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) int at_eof = 0; #endif int read_buf_len = 0; int fallback_scsv = 0; OPTION_CHOICE o; #ifndef OPENSSL_NO_DTLS int enable_timeouts = 0; long socket_mtu = 0; #endif #ifndef OPENSSL_NO_ENGINE ENGINE *ssl_client_engine = NULL; #endif ENGINE *e = NULL; #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) struct timeval tv; #endif const char *servername = NULL; char *sname_alloc = NULL; int noservername = 0; const char *alpn_in = NULL; tlsextctx tlsextcbp = { NULL, 0 }; const char *ssl_config = NULL; #define MAX_SI_TYPES 100 unsigned short serverinfo_types[MAX_SI_TYPES]; int serverinfo_count = 0, start = 0, len; #ifndef OPENSSL_NO_NEXTPROTONEG const char *next_proto_neg_in = NULL; #endif #ifndef OPENSSL_NO_SRP char *srppass = NULL; int srp_lateuser = 0; SRP_ARG srp_arg = { NULL, NULL, 0, 0, 0, 1024 }; #endif #ifndef OPENSSL_NO_SRTP char *srtp_profiles = NULL; #endif #ifndef OPENSSL_NO_CT char *ctlog_file = NULL; int ct_validation = 0; #endif int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0; int async = 0; unsigned int max_send_fragment = 0; unsigned int split_send_fragment = 0, max_pipelines = 0; enum { use_inet, use_unix, use_unknown } connect_type = use_unknown; int count4or6 = 0; uint8_t maxfraglen = 0; int c_nbio = 0, c_msg = 0, c_ign_eof = 0, c_brief = 0; int c_tlsextdebug = 0; #ifndef OPENSSL_NO_OCSP int c_status_req = 0; #endif BIO *bio_c_msg = NULL; const char *keylog_file = NULL, *early_data_file = NULL; int isdtls = 0, isquic = 0; char *psksessf = NULL; int enable_pha = 0; int enable_client_rpk = 0; #ifndef OPENSSL_NO_SCTP int sctp_label_bug = 0; #endif int ignore_unexpected_eof = 0; #ifndef OPENSSL_NO_KTLS int enable_ktls = 0; #endif int tfo = 0; int is_infinite; BIO_ADDR *peer_addr = NULL; struct user_data_st user_data; FD_ZERO(&readfds); FD_ZERO(&writefds); #if defined(__has_feature) # if __has_feature(memory_sanitizer) __msan_unpoison(&readfds, sizeof(readfds)); __msan_unpoison(&writefds, sizeof(writefds)); # endif #endif c_quiet = 0; c_debug = 0; c_showcerts = 0; c_nbio = 0; port = OPENSSL_strdup(PORT); vpm = X509_VERIFY_PARAM_new(); cctx = SSL_CONF_CTX_new(); if (port == NULL || vpm == NULL || cctx == NULL) { BIO_printf(bio_err, "%s: out of memory\n", opt_getprog()); goto end; } cbuf = app_malloc(BUFSIZZ, "cbuf"); sbuf = app_malloc(BUFSIZZ, "sbuf"); mbuf = app_malloc(BUFSIZZ, "mbuf"); SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT | SSL_CONF_FLAG_CMDLINE); prog = opt_init(argc, argv, s_client_options); while ((o = opt_next()) != OPT_EOF) { if (connect_type == use_unix && IS_INET_FLAG(o)) { BIO_printf(bio_err, "%s: Intermixed protocol flags (unix and internet domains)\n", prog); goto end; } if (connect_type == use_inet && IS_UNIX_FLAG(o)) { BIO_printf(bio_err, "%s: Intermixed protocol flags (internet and unix domains)\n", prog); goto end; } if (IS_PROT_FLAG(o) && ++prot_opt > 1) { BIO_printf(bio_err, "Cannot supply multiple protocol flags\n"); goto end; } if (IS_NO_PROT_FLAG(o)) no_prot_opt++; if (prot_opt == 1 && no_prot_opt) { BIO_printf(bio_err, "Cannot supply both a protocol flag and '-no_<prot>'\n"); goto end; } 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_client_options); ret = 0; goto end; case OPT_4: connect_type = use_inet; socket_family = AF_INET; count4or6++; break; #ifdef AF_INET6 case OPT_6: connect_type = use_inet; socket_family = AF_INET6; count4or6++; break; #endif case OPT_HOST: connect_type = use_inet; freeandcopy(&host, opt_arg()); break; case OPT_PORT: connect_type = use_inet; freeandcopy(&port, opt_arg()); break; case OPT_CONNECT: connect_type = use_inet; freeandcopy(&connectstr, opt_arg()); break; case OPT_BIND: freeandcopy(&bindstr, opt_arg()); break; case OPT_PROXY: proxystr = opt_arg(); break; case OPT_PROXY_USER: proxyuser = opt_arg(); break; case OPT_PROXY_PASS: proxypassarg = opt_arg(); break; #ifdef AF_UNIX case OPT_UNIX: connect_type = use_unix; socket_family = AF_UNIX; freeandcopy(&host, opt_arg()); break; #endif case OPT_XMPPHOST: case OPT_PROTOHOST: protohost = opt_arg(); break; case OPT_VERIFY: verify = SSL_VERIFY_PEER; verify_args.depth = atoi(opt_arg()); if (!c_quiet) BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth); break; case OPT_CERT: cert_file = opt_arg(); break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto end; break; case OPT_CRL: crl_file = opt_arg(); break; case OPT_CRL_DOWNLOAD: crl_download = 1; break; case OPT_SESS_OUT: sess_out = opt_arg(); break; case OPT_SESS_IN: sess_in = opt_arg(); break; case OPT_CERTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &cert_format)) goto opthelp; break; case OPT_CRLFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format)) goto opthelp; break; case OPT_VERIFY_RET_ERROR: verify = SSL_VERIFY_PEER; verify_args.return_error = 1; break; case OPT_VERIFY_QUIET: verify_args.quiet = 1; break; case OPT_BRIEF: c_brief = verify_args.quiet = c_quiet = 1; break; case OPT_S_CASES: if (ssl_args == NULL) ssl_args = sk_OPENSSL_STRING_new_null(); if (ssl_args == NULL || !sk_OPENSSL_STRING_push(ssl_args, opt_flag()) || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) { BIO_printf(bio_err, "%s: Memory allocation failure\n", prog); goto end; } break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_X_CASES: if (!args_excert(o, &exc)) goto end; break; case OPT_IGNORE_UNEXPECTED_EOF: ignore_unexpected_eof = 1; break; case OPT_PREXIT: prexit = 1; break; case OPT_NO_INTERACTIVE: nointeractive = 1; break; case OPT_CRLF: crlf = 1; break; case OPT_QUIET: c_quiet = c_ign_eof = 1; break; case OPT_NBIO: c_nbio = 1; break; case OPT_NOCMDS: cmdmode = USER_DATA_MODE_NONE; break; case OPT_ADV: cmdmode = USER_DATA_MODE_ADVANCED; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 1); break; case OPT_SSL_CLIENT_ENGINE: #ifndef OPENSSL_NO_ENGINE ssl_client_engine = setup_engine(opt_arg(), 0); if (ssl_client_engine == NULL) { BIO_printf(bio_err, "Error getting client auth engine\n"); goto opthelp; } #endif break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_IGN_EOF: c_ign_eof = 1; break; case OPT_NO_IGN_EOF: c_ign_eof = 0; break; case OPT_DEBUG: c_debug = 1; break; case OPT_TLSEXTDEBUG: c_tlsextdebug = 1; break; case OPT_STATUS: #ifndef OPENSSL_NO_OCSP c_status_req = 1; #endif break; case OPT_WDEBUG: #ifdef WATT32 dbug_init(); #endif break; case OPT_MSG: c_msg = 1; break; case OPT_MSGFILE: bio_c_msg = BIO_new_file(opt_arg(), "w"); if (bio_c_msg == NULL) { BIO_printf(bio_err, "Error writing file %s\n", opt_arg()); goto end; } break; case OPT_TRACE: #ifndef OPENSSL_NO_SSL_TRACE c_msg = 2; #endif break; case OPT_SECURITY_DEBUG: sdebug = 1; break; case OPT_SECURITY_DEBUG_VERBOSE: sdebug = 2; break; case OPT_SHOWCERTS: c_showcerts = 1; break; case OPT_NBIO_TEST: nbio_test = 1; break; case OPT_STATE: state = 1; break; case OPT_PSK_IDENTITY: psk_identity = opt_arg(); break; case OPT_PSK: for (p = psk_key = opt_arg(); *p; p++) { if (isxdigit(_UC(*p))) continue; BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key); goto end; } break; case OPT_PSK_SESS: psksessf = opt_arg(); break; #ifndef OPENSSL_NO_SRP case OPT_SRPUSER: srp_arg.srplogin = opt_arg(); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; break; case OPT_SRPPASS: srppass = opt_arg(); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; break; case OPT_SRP_STRENGTH: srp_arg.strength = atoi(opt_arg()); BIO_printf(bio_err, "SRP minimal length for N is %d\n", srp_arg.strength); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; break; case OPT_SRP_LATEUSER: srp_lateuser = 1; if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; break; case OPT_SRP_MOREGROUPS: srp_arg.amp = 1; if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; break; #endif case OPT_SSL_CONFIG: ssl_config = opt_arg(); break; case OPT_SSL3: min_version = SSL3_VERSION; max_version = SSL3_VERSION; socket_type = SOCK_STREAM; #ifndef OPENSSL_NO_DTLS isdtls = 0; #endif isquic = 0; break; case OPT_TLS1_3: min_version = TLS1_3_VERSION; max_version = TLS1_3_VERSION; socket_type = SOCK_STREAM; #ifndef OPENSSL_NO_DTLS isdtls = 0; #endif isquic = 0; break; case OPT_TLS1_2: min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; socket_type = SOCK_STREAM; #ifndef OPENSSL_NO_DTLS isdtls = 0; #endif isquic = 0; break; case OPT_TLS1_1: min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; socket_type = SOCK_STREAM; #ifndef OPENSSL_NO_DTLS isdtls = 0; #endif isquic = 0; break; case OPT_TLS1: min_version = TLS1_VERSION; max_version = TLS1_VERSION; socket_type = SOCK_STREAM; #ifndef OPENSSL_NO_DTLS isdtls = 0; #endif isquic = 0; break; case OPT_DTLS: #ifndef OPENSSL_NO_DTLS meth = DTLS_client_method(); socket_type = SOCK_DGRAM; isdtls = 1; isquic = 0; #endif break; case OPT_DTLS1: #ifndef OPENSSL_NO_DTLS1 meth = DTLS_client_method(); min_version = DTLS1_VERSION; max_version = DTLS1_VERSION; socket_type = SOCK_DGRAM; isdtls = 1; isquic = 0; #endif break; case OPT_DTLS1_2: #ifndef OPENSSL_NO_DTLS1_2 meth = DTLS_client_method(); min_version = DTLS1_2_VERSION; max_version = DTLS1_2_VERSION; socket_type = SOCK_DGRAM; isdtls = 1; isquic = 0; #endif break; case OPT_QUIC: #ifndef OPENSSL_NO_QUIC meth = OSSL_QUIC_client_method(); min_version = 0; max_version = 0; socket_type = SOCK_DGRAM; # ifndef OPENSSL_NO_DTLS isdtls = 0; # endif isquic = 1; #endif break; case OPT_SCTP: #ifndef OPENSSL_NO_SCTP protocol = IPPROTO_SCTP; #endif break; case OPT_SCTP_LABEL_BUG: #ifndef OPENSSL_NO_SCTP sctp_label_bug = 1; #endif break; case OPT_TIMEOUT: #ifndef OPENSSL_NO_DTLS enable_timeouts = 1; #endif break; case OPT_MTU: #ifndef OPENSSL_NO_DTLS socket_mtu = atol(opt_arg()); #endif break; case OPT_FALLBACKSCSV: fallback_scsv = 1; break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &key_format)) goto opthelp; break; case OPT_PASS: passarg = opt_arg(); break; case OPT_CERT_CHAIN: chain_file = opt_arg(); break; case OPT_KEY: key_file = opt_arg(); break; case OPT_RECONNECT: reconnect = 5; break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_CHAINCAPATH: chCApath = opt_arg(); break; case OPT_VERIFYCAPATH: vfyCApath = opt_arg(); break; case OPT_BUILD_CHAIN: build_chain = 1; break; case OPT_REQCAFILE: ReqCAfile = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; #ifndef OPENSSL_NO_CT case OPT_NOCT: ct_validation = 0; break; case OPT_CT: ct_validation = 1; break; case OPT_CTLOG_FILE: ctlog_file = opt_arg(); break; #endif case OPT_CHAINCAFILE: chCAfile = opt_arg(); break; case OPT_VERIFYCAFILE: vfyCAfile = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_CHAINCASTORE: chCAstore = opt_arg(); break; case OPT_VERIFYCASTORE: vfyCAstore = opt_arg(); break; case OPT_DANE_TLSA_DOMAIN: dane_tlsa_domain = opt_arg(); break; case OPT_DANE_TLSA_RRDATA: if (dane_tlsa_rrset == NULL) dane_tlsa_rrset = sk_OPENSSL_STRING_new_null(); if (dane_tlsa_rrset == NULL || !sk_OPENSSL_STRING_push(dane_tlsa_rrset, opt_arg())) { BIO_printf(bio_err, "%s: Memory allocation failure\n", prog); goto end; } break; case OPT_DANE_EE_NO_NAME: dane_ee_no_name = 1; break; case OPT_NEXTPROTONEG: #ifndef OPENSSL_NO_NEXTPROTONEG next_proto_neg_in = opt_arg(); #endif break; case OPT_ALPN: alpn_in = opt_arg(); break; case OPT_SERVERINFO: p = opt_arg(); len = strlen(p); for (start = 0, i = 0; i <= len; ++i) { if (i == len || p[i] == ',') { serverinfo_types[serverinfo_count] = atoi(p + start); if (++serverinfo_count == MAX_SI_TYPES) break; start = i + 1; } } break; case OPT_STARTTLS: if (!opt_pair(opt_arg(), services, &starttls_proto)) goto end; break; case OPT_TFO: tfo = 1; break; case OPT_SERVERNAME: servername = opt_arg(); break; case OPT_NOSERVERNAME: noservername = 1; break; case OPT_USE_SRTP: #ifndef OPENSSL_NO_SRTP srtp_profiles = opt_arg(); #endif break; case OPT_KEYMATEXPORT: keymatexportlabel = opt_arg(); break; case OPT_KEYMATEXPORTLEN: keymatexportlen = atoi(opt_arg()); break; case OPT_ASYNC: async = 1; break; case OPT_MAXFRAGLEN: len = atoi(opt_arg()); switch (len) { case 512: maxfraglen = TLSEXT_max_fragment_length_512; break; case 1024: maxfraglen = TLSEXT_max_fragment_length_1024; break; case 2048: maxfraglen = TLSEXT_max_fragment_length_2048; break; case 4096: maxfraglen = TLSEXT_max_fragment_length_4096; break; default: BIO_printf(bio_err, "%s: Max Fragment Len %u is out of permitted values", prog, len); goto opthelp; } break; case OPT_MAX_SEND_FRAG: max_send_fragment = atoi(opt_arg()); break; case OPT_SPLIT_SEND_FRAG: split_send_fragment = atoi(opt_arg()); break; case OPT_MAX_PIPELINES: max_pipelines = atoi(opt_arg()); break; case OPT_READ_BUF: read_buf_len = atoi(opt_arg()); break; case OPT_KEYLOG_FILE: keylog_file = opt_arg(); break; case OPT_EARLY_DATA: early_data_file = opt_arg(); break; case OPT_ENABLE_PHA: enable_pha = 1; break; case OPT_KTLS: #ifndef OPENSSL_NO_KTLS enable_ktls = 1; #endif break; case OPT_ENABLE_SERVER_RPK: enable_server_rpk = 1; break; case OPT_ENABLE_CLIENT_RPK: enable_client_rpk = 1; break; } } if (opt_num_rest() == 1) { if (connectstr != NULL) { BIO_printf(bio_err, "%s: cannot provide both -connect option and target parameter\n", prog); goto opthelp; } connect_type = use_inet; freeandcopy(&connectstr, *opt_rest()); } else if (!opt_check_rest_arg(NULL)) { goto opthelp; } if (!app_RAND_load()) goto end; if (c_ign_eof) cmdmode = USER_DATA_MODE_NONE; if (count4or6 >= 2) { BIO_printf(bio_err, "%s: Can't use both -4 and -6\n", prog); goto opthelp; } if (noservername) { if (servername != NULL) { BIO_printf(bio_err, "%s: Can't use -servername and -noservername together\n", prog); goto opthelp; } if (dane_tlsa_domain != NULL) { BIO_printf(bio_err, "%s: Can't use -dane_tlsa_domain and -noservername together\n", prog); goto opthelp; } } #ifndef OPENSSL_NO_NEXTPROTONEG if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) { BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n"); goto opthelp; } #endif if (connectstr != NULL) { int res; char *tmp_host = host, *tmp_port = port; res = BIO_parse_hostserv(connectstr, &host, &port, BIO_PARSE_PRIO_HOST); if (tmp_host != host) OPENSSL_free(tmp_host); if (tmp_port != port) OPENSSL_free(tmp_port); if (!res) { BIO_printf(bio_err, "%s: -connect argument or target parameter malformed or ambiguous\n", prog); goto end; } } if (proxystr != NULL) { #ifndef OPENSSL_NO_HTTP int res; char *tmp_host = host, *tmp_port = port; if (host == NULL || port == NULL) { BIO_printf(bio_err, "%s: -proxy requires use of -connect or target parameter\n", prog); goto opthelp; } if (servername == NULL && !noservername) { servername = sname_alloc = OPENSSL_strdup(host); if (sname_alloc == NULL) { BIO_printf(bio_err, "%s: out of memory\n", prog); goto end; } } thost = OPENSSL_strdup(host); tport = OPENSSL_strdup(port); if (thost == NULL || tport == NULL) { BIO_printf(bio_err, "%s: out of memory\n", prog); goto end; } res = BIO_parse_hostserv(proxystr, &host, &port, BIO_PARSE_PRIO_HOST); if (tmp_host != host) OPENSSL_free(tmp_host); if (tmp_port != port) OPENSSL_free(tmp_port); if (!res) { BIO_printf(bio_err, "%s: -proxy argument malformed or ambiguous\n", prog); goto end; } #else BIO_printf(bio_err, "%s: -proxy not supported in no-http build\n", prog); goto end; #endif } if (bindstr != NULL) { int res; res = BIO_parse_hostserv(bindstr, &bindhost, &bindport, BIO_PARSE_PRIO_HOST); if (!res) { BIO_printf(bio_err, "%s: -bind argument parameter malformed or ambiguous\n", prog); goto end; } } #ifdef AF_UNIX if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) { BIO_printf(bio_err, "Can't use unix sockets and datagrams together\n"); goto end; } #endif #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP) { if (socket_type != SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -sctp without DTLS\n"); goto end; } socket_type = SOCK_STREAM; } #endif #if !defined(OPENSSL_NO_NEXTPROTONEG) next_proto.status = -1; if (next_proto_neg_in) { next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in); if (next_proto.data == NULL) { BIO_printf(bio_err, "Error parsing -nextprotoneg argument\n"); goto end; } } else next_proto.data = NULL; #endif if (!app_passwd(passarg, NULL, &pass, NULL)) { BIO_printf(bio_err, "Error getting private key password\n"); goto end; } if (!app_passwd(proxypassarg, NULL, &proxypass, NULL)) { BIO_printf(bio_err, "Error getting proxy password\n"); goto end; } if (proxypass != NULL && proxyuser == NULL) { BIO_printf(bio_err, "Error: Must specify proxy_user with proxy_pass\n"); goto end; } if (key_file == NULL) key_file = cert_file; if (key_file != NULL) { key = load_key(key_file, key_format, 0, pass, e, "client certificate private key"); if (key == NULL) goto end; } if (cert_file != NULL) { cert = load_cert_pass(cert_file, cert_format, 1, pass, "client certificate"); if (cert == NULL) goto end; } if (chain_file != NULL) { if (!load_certs(chain_file, 0, &chain, pass, "client certificate chain")) goto end; } if (crl_file != NULL) { X509_CRL *crl; crl = load_crl(crl_file, crl_format, 0, "CRL"); if (crl == NULL) goto end; crls = sk_X509_CRL_new_null(); if (crls == NULL || !sk_X509_CRL_push(crls, crl)) { BIO_puts(bio_err, "Error adding CRL\n"); ERR_print_errors(bio_err); X509_CRL_free(crl); goto end; } } if (!load_excert(&exc)) goto end; if (bio_c_out == NULL) { if (c_quiet && !c_debug) { bio_c_out = BIO_new(BIO_s_null()); if (c_msg && bio_c_msg == NULL) { bio_c_msg = dup_bio_out(FORMAT_TEXT); if (bio_c_msg == NULL) { BIO_printf(bio_err, "Out of memory\n"); goto end; } } } else { bio_c_out = dup_bio_out(FORMAT_TEXT); } if (bio_c_out == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto end; } } #ifndef OPENSSL_NO_SRP if (!app_passwd(srppass, NULL, &srp_arg.srppassin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } #endif ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY); if (sdebug) ssl_ctx_security_debug(ctx, sdebug); if (!config_ctx(cctx, ssl_args, ctx)) goto end; if (ssl_config != NULL) { if (SSL_CTX_config(ctx, ssl_config) == 0) { BIO_printf(bio_err, "Error using configuration \"%s\"\n", ssl_config); ERR_print_errors(bio_err); goto end; } } #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP && sctp_label_bug == 1) SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG); #endif if (min_version != 0 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0) goto end; if (max_version != 0 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0) goto end; if (ignore_unexpected_eof) SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF); #ifndef OPENSSL_NO_KTLS if (enable_ktls) SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS); #endif if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) { BIO_printf(bio_err, "Error setting verify params\n"); ERR_print_errors(bio_err); goto end; } if (async) { SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC); } if (max_send_fragment > 0 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) { BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n", prog, max_send_fragment); goto end; } if (split_send_fragment > 0 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) { BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n", prog, split_send_fragment); goto end; } if (max_pipelines > 0 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) { BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n", prog, max_pipelines); goto end; } if (read_buf_len > 0) { SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len); } if (maxfraglen > 0 && !SSL_CTX_set_tlsext_max_fragment_length(ctx, maxfraglen)) { BIO_printf(bio_err, "%s: Max Fragment Length code %u is out of permitted values" "\n", prog, maxfraglen); goto end; } if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, vfyCAstore, chCApath, chCAfile, chCAstore, crls, crl_download)) { BIO_printf(bio_err, "Error loading store locations\n"); ERR_print_errors(bio_err); goto end; } if (ReqCAfile != NULL) { STACK_OF(X509_NAME) *nm = sk_X509_NAME_new_null(); if (nm == NULL || !SSL_add_file_cert_subjects_to_stack(nm, ReqCAfile)) { sk_X509_NAME_pop_free(nm, X509_NAME_free); BIO_printf(bio_err, "Error loading CA names\n"); ERR_print_errors(bio_err); goto end; } SSL_CTX_set0_CA_list(ctx, nm); } #ifndef OPENSSL_NO_ENGINE if (ssl_client_engine) { if (!SSL_CTX_set_client_cert_engine(ctx, ssl_client_engine)) { BIO_puts(bio_err, "Error setting client auth engine\n"); ERR_print_errors(bio_err); release_engine(ssl_client_engine); goto end; } release_engine(ssl_client_engine); } #endif #ifndef OPENSSL_NO_PSK if (psk_key != NULL) { if (c_debug) BIO_printf(bio_c_out, "PSK key given, setting client callback\n"); SSL_CTX_set_psk_client_callback(ctx, psk_client_cb); } #endif if (psksessf != NULL) { BIO *stmp = BIO_new_file(psksessf, "r"); if (stmp == NULL) { BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf); ERR_print_errors(bio_err); goto end; } psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL); BIO_free(stmp); if (psksess == NULL) { BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf); ERR_print_errors(bio_err); goto end; } } if (psk_key != NULL || psksess != NULL) SSL_CTX_set_psk_use_session_callback(ctx, psk_use_session_cb); #ifndef OPENSSL_NO_SRTP if (srtp_profiles != NULL) { if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) { BIO_printf(bio_err, "Error setting SRTP profile\n"); ERR_print_errors(bio_err); goto end; } } #endif if (exc != NULL) ssl_ctx_set_excert(ctx, exc); #if !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto.data != NULL) SSL_CTX_set_next_proto_select_cb(ctx, next_proto_cb, &next_proto); #endif if (alpn_in) { size_t alpn_len; unsigned char *alpn = next_protos_parse(&alpn_len, alpn_in); if (alpn == NULL) { BIO_printf(bio_err, "Error parsing -alpn argument\n"); goto end; } if (SSL_CTX_set_alpn_protos(ctx, alpn, alpn_len) != 0) { BIO_printf(bio_err, "Error setting ALPN\n"); goto end; } OPENSSL_free(alpn); } for (i = 0; i < serverinfo_count; i++) { if (!SSL_CTX_add_client_custom_ext(ctx, serverinfo_types[i], NULL, NULL, NULL, serverinfo_cli_parse_cb, NULL)) { BIO_printf(bio_err, "Warning: Unable to add custom extension %u, skipping\n", serverinfo_types[i]); } } if (state) SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback); #ifndef OPENSSL_NO_CT if (ct_validation && !SSL_CTX_enable_ct(ctx, SSL_CT_VALIDATION_PERMISSIVE)) { ERR_print_errors(bio_err); goto end; } if (!ctx_set_ctlog_list_file(ctx, ctlog_file)) { if (ct_validation) { ERR_print_errors(bio_err); goto end; } ERR_clear_error(); } #endif SSL_CTX_set_verify(ctx, verify, verify_callback); if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) { ERR_print_errors(bio_err); goto end; } ssl_ctx_add_crls(ctx, crls, crl_download); if (!set_cert_key_stuff(ctx, cert, key, chain, build_chain)) goto end; if (!noservername) { tlsextcbp.biodebug = bio_err; SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp); } #ifndef OPENSSL_NO_SRP if (srp_arg.srplogin != NULL && !set_up_srp_arg(ctx, &srp_arg, srp_lateuser, c_msg, c_debug)) goto end; # endif if (dane_tlsa_domain != NULL) { if (SSL_CTX_dane_enable(ctx) <= 0) { BIO_printf(bio_err, "%s: Error enabling DANE TLSA authentication.\n", prog); ERR_print_errors(bio_err); goto end; } } SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_CLIENT | SSL_SESS_CACHE_NO_INTERNAL_STORE); SSL_CTX_sess_set_new_cb(ctx, new_session_cb); if (set_keylog_file(ctx, keylog_file)) goto end; con = SSL_new(ctx); if (con == NULL) goto end; if (enable_pha) SSL_set_post_handshake_auth(con, 1); if (enable_client_rpk) if (!SSL_set1_client_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) { BIO_printf(bio_err, "Error setting client certificate types\n"); goto end; } if (enable_server_rpk) { if (!SSL_set1_server_cert_type(con, cert_type_rpk, sizeof(cert_type_rpk))) { BIO_printf(bio_err, "Error setting server certificate types\n"); goto end; } } if (sess_in != NULL) { SSL_SESSION *sess; BIO *stmp = BIO_new_file(sess_in, "r"); if (stmp == NULL) { BIO_printf(bio_err, "Can't open session file %s\n", sess_in); ERR_print_errors(bio_err); goto end; } sess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL); BIO_free(stmp); if (sess == NULL) { BIO_printf(bio_err, "Can't open session file %s\n", sess_in); ERR_print_errors(bio_err); goto end; } if (!SSL_set_session(con, sess)) { BIO_printf(bio_err, "Can't set session\n"); ERR_print_errors(bio_err); goto end; } SSL_SESSION_free(sess); } if (fallback_scsv) SSL_set_mode(con, SSL_MODE_SEND_FALLBACK_SCSV); if (!noservername && (servername != NULL || dane_tlsa_domain == NULL)) { if (servername == NULL) { if (host == NULL || is_dNS_name(host)) servername = (host == NULL) ? "localhost" : host; } if (servername != NULL && !SSL_set_tlsext_host_name(con, servername)) { BIO_printf(bio_err, "Unable to set TLS servername extension.\n"); ERR_print_errors(bio_err); goto end; } } if (dane_tlsa_domain != NULL) { if (SSL_dane_enable(con, dane_tlsa_domain) <= 0) { BIO_printf(bio_err, "%s: Error enabling DANE TLSA " "authentication.\n", prog); ERR_print_errors(bio_err); goto end; } if (dane_tlsa_rrset == NULL) { BIO_printf(bio_err, "%s: DANE TLSA authentication requires at " "least one -dane_tlsa_rrdata option.\n", prog); goto end; } if (tlsa_import_rrset(con, dane_tlsa_rrset) <= 0) { BIO_printf(bio_err, "%s: Failed to import any TLSA " "records.\n", prog); goto end; } if (dane_ee_no_name) SSL_dane_set_flags(con, DANE_FLAG_NO_DANE_EE_NAMECHECKS); } else if (dane_tlsa_rrset != NULL) { BIO_printf(bio_err, "%s: DANE TLSA authentication requires the " "-dane_tlsa_domain option.\n", prog); goto end; } #ifndef OPENSSL_NO_DTLS if (isdtls && tfo) { BIO_printf(bio_err, "%s: DTLS does not support the -tfo option\n", prog); goto end; } #endif #ifndef OPENSSL_NO_QUIC if (isquic && tfo) { BIO_printf(bio_err, "%s: QUIC does not support the -tfo option\n", prog); goto end; } if (isquic && alpn_in == NULL) { BIO_printf(bio_err, "%s: QUIC requires ALPN to be specified (e.g. \"h3\" for HTTP/3) via the -alpn option\n", prog); goto end; } #endif if (tfo) BIO_printf(bio_c_out, "Connecting via TFO\n"); re_start: if (init_client(&sock, host, port, bindhost, bindport, socket_family, socket_type, protocol, tfo, !isquic, &peer_addr) == 0) { BIO_printf(bio_err, "connect:errno=%d\n", get_last_socket_error()); BIO_closesocket(sock); goto end; } BIO_printf(bio_c_out, "CONNECTED(%08X)\n", sock); if (c_nbio || isquic) { if (!BIO_socket_nbio(sock, 1)) { ERR_print_errors(bio_err); goto end; } if (c_nbio) { if (isquic && !SSL_set_blocking_mode(con, 0)) goto end; BIO_printf(bio_c_out, "Turned on non blocking io\n"); } } #ifndef OPENSSL_NO_DTLS if (isdtls) { union BIO_sock_info_u peer_info; #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP) sbio = BIO_new_dgram_sctp(sock, BIO_NOCLOSE); else #endif sbio = BIO_new_dgram(sock, BIO_NOCLOSE); if (sbio == NULL || (peer_info.addr = BIO_ADDR_new()) == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); BIO_free(sbio); BIO_closesocket(sock); goto end; } if (!BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &peer_info)) { BIO_printf(bio_err, "getsockname:errno=%d\n", get_last_socket_error()); BIO_free(sbio); BIO_ADDR_free(peer_info.addr); BIO_closesocket(sock); goto end; } (void)BIO_ctrl_set_connected(sbio, peer_info.addr); BIO_ADDR_free(peer_info.addr); peer_info.addr = NULL; if (enable_timeouts) { timeout.tv_sec = 0; timeout.tv_usec = DGRAM_RCV_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout); timeout.tv_sec = 0; timeout.tv_usec = DGRAM_SND_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout); } if (socket_mtu) { if (socket_mtu < DTLS_get_link_min_mtu(con)) { BIO_printf(bio_err, "MTU too small. Must be at least %ld\n", DTLS_get_link_min_mtu(con)); BIO_free(sbio); goto shut; } SSL_set_options(con, SSL_OP_NO_QUERY_MTU); if (!DTLS_set_link_mtu(con, socket_mtu)) { BIO_printf(bio_err, "Failed to set MTU\n"); BIO_free(sbio); goto shut; } } else { BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL); } } else #endif #ifndef OPENSSL_NO_QUIC if (isquic) { sbio = BIO_new_dgram(sock, BIO_NOCLOSE); if (!SSL_set1_initial_peer_addr(con, peer_addr)) { BIO_printf(bio_err, "Failed to set the initial peer address\n"); goto shut; } } else #endif sbio = BIO_new_socket(sock, BIO_NOCLOSE); if (sbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); ERR_print_errors(bio_err); BIO_closesocket(sock); goto end; } if (tfo) { (void)BIO_set_conn_address(sbio, peer_addr); (void)BIO_set_tfo(sbio, 1); } if (nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); if (test == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); BIO_free(sbio); goto shut; } sbio = BIO_push(test, sbio); } if (c_debug) { BIO_set_callback_ex(sbio, bio_dump_callback); BIO_set_callback_arg(sbio, (char *)bio_c_out); } if (c_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (c_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_c_msg ? bio_c_msg : bio_c_out); } if (c_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_c_out); } #ifndef OPENSSL_NO_OCSP if (c_status_req) { SSL_set_tlsext_status_type(con, TLSEXT_STATUSTYPE_ocsp); SSL_CTX_set_tlsext_status_cb(ctx, ocsp_resp_cb); SSL_CTX_set_tlsext_status_arg(ctx, bio_c_out); } #endif SSL_set_bio(con, sbio, sbio); SSL_set_connect_state(con); if (fileno_stdin() > SSL_get_fd(con)) width = fileno_stdin() + 1; else width = SSL_get_fd(con) + 1; read_tty = 1; write_tty = 0; tty_on = 0; read_ssl = 1; write_ssl = 1; first_loop = 1; cbuf_len = 0; cbuf_off = 0; sbuf_len = 0; sbuf_off = 0; #ifndef OPENSSL_NO_HTTP if (proxystr != NULL) { if (!OSSL_HTTP_proxy_connect(sbio, thost, tport, proxyuser, proxypass, 0 , bio_err, prog)) goto shut; } #endif switch ((PROTOCOL_CHOICE) starttls_proto) { case PROTO_OFF: break; case PROTO_LMTP: case PROTO_SMTP: { int foundit = 0; BIO *fbio = BIO_new(BIO_f_buffer()); if (fbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto shut; } BIO_push(fbio, sbio); do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); } while (mbuf_len > 3 && mbuf[3] == '-'); if (protohost == NULL) protohost = "mail.example.com"; if (starttls_proto == (int)PROTO_LMTP) BIO_printf(fbio, "LHLO %s\r\n", protohost); else BIO_printf(fbio, "EHLO %s\r\n", protohost); (void)BIO_flush(fbio); do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); if (strstr(mbuf, "STARTTLS")) foundit = 1; } while (mbuf_len > 3 && mbuf[3] == '-'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, "Didn't find STARTTLS in server response," " trying anyway...\n"); BIO_printf(sbio, "STARTTLS\r\n"); BIO_read(sbio, sbuf, BUFSIZZ); } break; case PROTO_POP3: { BIO_read(sbio, mbuf, BUFSIZZ); BIO_printf(sbio, "STLS\r\n"); mbuf_len = BIO_read(sbio, sbuf, BUFSIZZ); if (mbuf_len < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto end; } } break; case PROTO_IMAP: { int foundit = 0; BIO *fbio = BIO_new(BIO_f_buffer()); if (fbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto shut; } BIO_push(fbio, sbio); BIO_gets(fbio, mbuf, BUFSIZZ); BIO_printf(fbio, ". CAPABILITY\r\n"); (void)BIO_flush(fbio); do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); if (strstr(mbuf, "STARTTLS")) foundit = 1; } while (mbuf_len > 3 && mbuf[0] != '.'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, "Didn't find STARTTLS in server response," " trying anyway...\n"); BIO_printf(sbio, ". STARTTLS\r\n"); BIO_read(sbio, sbuf, BUFSIZZ); } break; case PROTO_FTP: { BIO *fbio = BIO_new(BIO_f_buffer()); if (fbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto shut; } BIO_push(fbio, sbio); do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); } while (mbuf_len > 3 && (!isdigit((unsigned char)mbuf[0]) || !isdigit((unsigned char)mbuf[1]) || !isdigit((unsigned char)mbuf[2]) || mbuf[3] != ' ')); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); BIO_printf(sbio, "AUTH TLS\r\n"); BIO_read(sbio, sbuf, BUFSIZZ); } break; case PROTO_XMPP: case PROTO_XMPP_SERVER: { int seen = 0; BIO_printf(sbio, "<stream:stream " "xmlns:stream='http: "xmlns='jabber:%s' to='%s' version='1.0'>", starttls_proto == PROTO_XMPP ? "client" : "server", protohost ? protohost : host); seen = BIO_read(sbio, mbuf, BUFSIZZ); if (seen < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto end; } mbuf[seen] = '\0'; while (!strstr (mbuf, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'") && !strstr(mbuf, "<starttls xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"")) { seen = BIO_read(sbio, mbuf, BUFSIZZ); if (seen <= 0) goto shut; mbuf[seen] = '\0'; } BIO_printf(sbio, "<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>"); seen = BIO_read(sbio, sbuf, BUFSIZZ); if (seen < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto shut; } sbuf[seen] = '\0'; if (!strstr(sbuf, "<proceed")) goto shut; mbuf[0] = '\0'; } break; case PROTO_TELNET: { static const unsigned char tls_do[] = { 255, 253, 46 }; static const unsigned char tls_will[] = { 255, 251, 46 }; static const unsigned char tls_follows[] = { 255, 250, 46, 1, 255, 240 }; int bytes; bytes = BIO_read(sbio, mbuf, BUFSIZZ); if (bytes != 3 || memcmp(mbuf, tls_do, 3) != 0) goto shut; BIO_write(sbio, tls_will, 3); BIO_write(sbio, tls_follows, 6); (void)BIO_flush(sbio); bytes = BIO_read(sbio, mbuf, BUFSIZZ); if (bytes != 6 || memcmp(mbuf, tls_follows, 6) != 0) goto shut; } break; case PROTO_IRC: { int numeric; BIO *fbio = BIO_new(BIO_f_buffer()); if (fbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto end; } BIO_push(fbio, sbio); BIO_printf(fbio, "STARTTLS\r\n"); (void)BIO_flush(fbio); width = SSL_get_fd(con) + 1; do { numeric = 0; FD_ZERO(&readfds); openssl_fdset(SSL_get_fd(con), &readfds); timeout.tv_sec = S_CLIENT_IRC_READ_TIMEOUT; timeout.tv_usec = 0; if (!BIO_get_buffer_num_lines(fbio) && !BIO_pending(fbio) && !BIO_pending(sbio) && select(width, (void *)&readfds, NULL, NULL, &timeout) < 1) { BIO_printf(bio_err, "Timeout waiting for response (%d seconds).\n", S_CLIENT_IRC_READ_TIMEOUT); break; } mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); if (mbuf_len < 1 || sscanf(mbuf, "%*s %d", &numeric) != 1) break; if ((numeric == 451 || numeric == 421) && strstr(mbuf, "STARTTLS") != NULL) { BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf); break; } if (numeric == 691) { BIO_printf(bio_err, "STARTTLS negotiation failed: "); ERR_print_errors(bio_err); break; } } while (numeric != 670); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (numeric != 670) { BIO_printf(bio_err, "Server does not support STARTTLS.\n"); ret = 1; goto shut; } } break; case PROTO_MYSQL: { static const unsigned char ssl_req[] = { 0x20, 0x00, 0x00, 0x01, 0x85, 0xae, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x01, 0x21, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; int bytes = 0; int ssl_flg = 0x800; int pos; const unsigned char *packet = (const unsigned char *)sbuf; bytes = BIO_read(sbio, (void *)packet, BUFSIZZ); if (bytes < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto shut; } else if (bytes < 21) { BIO_printf(bio_err, "MySQL packet too short.\n"); goto shut; } else if (bytes != (4 + packet[0] + (packet[1] << 8) + (packet[2] << 16))) { BIO_printf(bio_err, "MySQL packet length does not match.\n"); goto shut; } else if (packet[4] != 0xA) { BIO_printf(bio_err, "Only MySQL protocol version 10 is supported.\n"); goto shut; } pos = 5; for (;;) { if (pos >= bytes) { BIO_printf(bio_err, "Cannot confirm server version. "); goto shut; } else if (packet[pos++] == '\0') { break; } } if (pos + 15 > bytes) { BIO_printf(bio_err, "MySQL server handshake packet is broken.\n"); goto shut; } pos += 12; if (packet[pos++] != '\0') { BIO_printf(bio_err, "MySQL packet is broken.\n"); goto shut; } if (!((packet[pos] + (packet[pos + 1] << 8)) & ssl_flg)) { BIO_printf(bio_err, "MySQL server does not support SSL.\n"); goto shut; } BIO_write(sbio, ssl_req, sizeof(ssl_req)); (void)BIO_flush(sbio); } break; case PROTO_POSTGRES: { static const unsigned char ssl_request[] = { 0, 0, 0, 8, 4, 210, 22, 47 }; int bytes; BIO_write(sbio, ssl_request, 8); (void)BIO_flush(sbio); bytes = BIO_read(sbio, sbuf, BUFSIZZ); if (bytes != 1 || sbuf[0] != 'S') goto shut; } break; case PROTO_NNTP: { int foundit = 0; BIO *fbio = BIO_new(BIO_f_buffer()); if (fbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto end; } BIO_push(fbio, sbio); BIO_gets(fbio, mbuf, BUFSIZZ); BIO_printf(fbio, "CAPABILITIES\r\n"); (void)BIO_flush(fbio); BIO_gets(fbio, mbuf, BUFSIZZ); if (strstr(mbuf, "101") != NULL) { do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); if (strstr(mbuf, "STARTTLS")) foundit = 1; } while (mbuf_len > 1 && mbuf[0] != '.'); } (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, "Didn't find STARTTLS in server response," " trying anyway...\n"); BIO_printf(sbio, "STARTTLS\r\n"); mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ); if (mbuf_len < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto end; } mbuf[mbuf_len] = '\0'; if (strstr(mbuf, "382") == NULL) { BIO_printf(bio_err, "STARTTLS failed: %s", mbuf); goto shut; } } break; case PROTO_SIEVE: { int foundit = 0; BIO *fbio = BIO_new(BIO_f_buffer()); if (fbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); goto end; } BIO_push(fbio, sbio); do { mbuf_len = BIO_gets(fbio, mbuf, BUFSIZZ); if (mbuf_len > 1 && mbuf[0] == '"') { make_uppercase(mbuf); if (HAS_PREFIX(mbuf, "\"STARTTLS\"")) foundit = 1; } } while (mbuf_len > 1 && mbuf[0] == '"'); (void)BIO_flush(fbio); BIO_pop(fbio); BIO_free(fbio); if (!foundit) BIO_printf(bio_err, "Didn't find STARTTLS in server response," " trying anyway...\n"); BIO_printf(sbio, "STARTTLS\r\n"); mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ); if (mbuf_len < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto end; } mbuf[mbuf_len] = '\0'; if (mbuf_len < 2) { BIO_printf(bio_err, "STARTTLS failed: %s", mbuf); goto shut; } strncpy(sbuf, mbuf, 2); make_uppercase(sbuf); if (!HAS_PREFIX(sbuf, "OK")) { BIO_printf(bio_err, "STARTTLS not supported: %s", mbuf); goto shut; } } break; case PROTO_LDAP: { static char ldap_tls_genconf[] = "asn1=SEQUENCE:LDAPMessage\n" "[LDAPMessage]\n" "messageID=INTEGER:1\n" "extendedReq=EXPLICIT:23A,IMPLICIT:0C," "FORMAT:ASCII,OCT:1.3.6.1.4.1.1466.20037\n"; long errline = -1; char *genstr = NULL; int result = -1; ASN1_TYPE *atyp = NULL; BIO *ldapbio = BIO_new(BIO_s_mem()); CONF *cnf = NCONF_new(NULL); if (ldapbio == NULL || cnf == NULL) { BIO_free(ldapbio); NCONF_free(cnf); goto end; } BIO_puts(ldapbio, ldap_tls_genconf); if (NCONF_load_bio(cnf, ldapbio, &errline) <= 0) { BIO_free(ldapbio); NCONF_free(cnf); if (errline <= 0) { BIO_printf(bio_err, "NCONF_load_bio failed\n"); goto end; } else { BIO_printf(bio_err, "Error on line %ld\n", errline); goto end; } } BIO_free(ldapbio); genstr = NCONF_get_string(cnf, "default", "asn1"); if (genstr == NULL) { NCONF_free(cnf); BIO_printf(bio_err, "NCONF_get_string failed\n"); goto end; } atyp = ASN1_generate_nconf(genstr, cnf); if (atyp == NULL) { NCONF_free(cnf); BIO_printf(bio_err, "ASN1_generate_nconf failed\n"); goto end; } NCONF_free(cnf); BIO_write(sbio, atyp->value.sequence->data, atyp->value.sequence->length); (void)BIO_flush(sbio); ASN1_TYPE_free(atyp); mbuf_len = BIO_read(sbio, mbuf, BUFSIZZ); if (mbuf_len < 0) { BIO_printf(bio_err, "BIO_read failed\n"); goto end; } result = ldap_ExtendedResponse_parse(mbuf, mbuf_len); if (result < 0) { BIO_printf(bio_err, "ldap_ExtendedResponse_parse failed\n"); goto shut; } else if (result > 0) { BIO_printf(bio_err, "STARTTLS failed, LDAP Result Code: %i\n", result); goto shut; } mbuf_len = 0; } break; } if (early_data_file != NULL && ((SSL_get0_session(con) != NULL && SSL_SESSION_get_max_early_data(SSL_get0_session(con)) > 0) || (psksess != NULL && SSL_SESSION_get_max_early_data(psksess) > 0))) { BIO *edfile = BIO_new_file(early_data_file, "r"); size_t readbytes, writtenbytes; int finish = 0; if (edfile == NULL) { BIO_printf(bio_err, "Cannot open early data file\n"); goto shut; } while (!finish) { if (!BIO_read_ex(edfile, cbuf, BUFSIZZ, &readbytes)) finish = 1; while (!SSL_write_early_data(con, cbuf, readbytes, &writtenbytes)) { switch (SSL_get_error(con, 0)) { case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_ASYNC: case SSL_ERROR_WANT_READ: continue; default: BIO_printf(bio_err, "Error writing early data\n"); BIO_free(edfile); ERR_print_errors(bio_err); goto shut; } } } BIO_free(edfile); } user_data_init(&user_data, con, cbuf, BUFSIZZ, cmdmode); for (;;) { FD_ZERO(&readfds); FD_ZERO(&writefds); if ((isdtls || isquic) && SSL_get_event_timeout(con, &timeout, &is_infinite) && !is_infinite) timeoutp = &timeout; else timeoutp = NULL; if (!SSL_is_init_finished(con) && SSL_total_renegotiations(con) == 0 && SSL_get_key_update_type(con) == SSL_KEY_UPDATE_NONE) { in_init = 1; tty_on = 0; } else { tty_on = 1; if (in_init) { in_init = 0; if (c_brief) { BIO_puts(bio_err, "CONNECTION ESTABLISHED\n"); print_ssl_summary(con); } print_stuff(bio_c_out, con, full_log); if (full_log > 0) full_log--; if (starttls_proto) { BIO_write(bio_err, mbuf, mbuf_len); if (!reconnect) starttls_proto = PROTO_OFF; } if (reconnect) { reconnect--; BIO_printf(bio_c_out, "drop connection and then reconnect\n"); do_ssl_shutdown(con); SSL_set_connect_state(con); BIO_closesocket(SSL_get_fd(con)); goto re_start; } } } if (!write_ssl) { do { switch (user_data_process(&user_data, &cbuf_len, &cbuf_off)) { default: BIO_printf(bio_err, "ERROR\n"); case USER_DATA_PROCESS_SHUT: ret = 0; goto shut; case USER_DATA_PROCESS_RESTART: goto re_start; case USER_DATA_PROCESS_NO_DATA: break; case USER_DATA_PROCESS_CONTINUE: write_ssl = 1; break; } } while (!write_ssl && cbuf_len == 0 && user_data_has_data(&user_data)); if (cbuf_len > 0) { read_tty = 0; timeout.tv_sec = 0; timeout.tv_usec = 0; } else { read_tty = 1; } } ssl_pending = read_ssl && SSL_has_pending(con); if (!ssl_pending) { #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) if (tty_on) { if (read_tty && !at_eof) openssl_fdset(fileno_stdin(), &readfds); #if !defined(OPENSSL_SYS_VMS) if (write_tty) openssl_fdset(fileno_stdout(), &writefds); #endif } if ((!isquic && read_ssl) || (isquic && SSL_net_read_desired(con))) openssl_fdset(SSL_get_fd(con), &readfds); if ((!isquic && write_ssl) || (isquic && (first_loop || SSL_net_write_desired(con)))) openssl_fdset(SSL_get_fd(con), &writefds); #else if (!tty_on || !write_tty) { if ((!isquic && read_ssl) || (isquic && SSL_net_read_desired(con))) openssl_fdset(SSL_get_fd(con), &readfds); if ((!isquic && write_ssl) || (isquic && (first_loop || SSL_net_write_desired(con)))) openssl_fdset(SSL_get_fd(con), &writefds); } #endif #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) i = 0; if (!write_tty) { if (read_tty) { tv.tv_sec = 1; tv.tv_usec = 0; i = select(width, (void *)&readfds, (void *)&writefds, NULL, &tv); if (!i && (!has_stdin_waiting() || !read_tty)) continue; } else i = select(width, (void *)&readfds, (void *)&writefds, NULL, timeoutp); } #else i = select(width, (void *)&readfds, (void *)&writefds, NULL, timeoutp); #endif if (i < 0) { BIO_printf(bio_err, "bad select %d\n", get_last_socket_error()); goto shut; } } if (timeoutp != NULL) { SSL_handle_events(con); if (isdtls && !FD_ISSET(SSL_get_fd(con), &readfds) && !FD_ISSET(SSL_get_fd(con), &writefds)) BIO_printf(bio_err, "TIMEOUT occurred\n"); } if (!ssl_pending && ((!isquic && FD_ISSET(SSL_get_fd(con), &writefds)) || (isquic && (cbuf_len > 0 || first_loop)))) { k = SSL_write(con, &(cbuf[cbuf_off]), (unsigned int)cbuf_len); switch (SSL_get_error(con, k)) { case SSL_ERROR_NONE: cbuf_off += k; cbuf_len -= k; if (k <= 0) goto end; if (cbuf_len == 0) { read_tty = 1; write_ssl = 0; } else { read_tty = 0; write_ssl = 1; } break; case SSL_ERROR_WANT_WRITE: BIO_printf(bio_c_out, "write W BLOCK\n"); write_ssl = 1; read_tty = 0; break; case SSL_ERROR_WANT_ASYNC: BIO_printf(bio_c_out, "write A BLOCK\n"); wait_for_async(con); write_ssl = 1; read_tty = 0; break; case SSL_ERROR_WANT_READ: BIO_printf(bio_c_out, "write R BLOCK\n"); write_tty = 0; read_ssl = 1; write_ssl = 0; break; case SSL_ERROR_WANT_X509_LOOKUP: BIO_printf(bio_c_out, "write X BLOCK\n"); break; case SSL_ERROR_ZERO_RETURN: if (cbuf_len != 0) { BIO_printf(bio_c_out, "shutdown\n"); ret = 0; goto shut; } else { read_tty = 1; write_ssl = 0; break; } case SSL_ERROR_SYSCALL: if ((k != 0) || (cbuf_len != 0)) { int sockerr = get_last_socket_error(); if (!tfo || sockerr != EISCONN) { BIO_printf(bio_err, "write:errno=%d\n", sockerr); goto shut; } } else { read_tty = 1; write_ssl = 0; } break; case SSL_ERROR_WANT_ASYNC_JOB: case SSL_ERROR_SSL: ERR_print_errors(bio_err); goto shut; } } #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) || defined(OPENSSL_SYS_VMS) else if (!ssl_pending && write_tty) #else else if (!ssl_pending && FD_ISSET(fileno_stdout(), &writefds)) #endif { #ifdef CHARSET_EBCDIC ascii2ebcdic(&(sbuf[sbuf_off]), &(sbuf[sbuf_off]), sbuf_len); #endif i = raw_write_stdout(&(sbuf[sbuf_off]), sbuf_len); if (i <= 0) { BIO_printf(bio_c_out, "DONE\n"); ret = 0; goto shut; } sbuf_len -= i; sbuf_off += i; if (sbuf_len <= 0) { read_ssl = 1; write_tty = 0; } } else if (ssl_pending || (!isquic && FD_ISSET(SSL_get_fd(con), &readfds))) { #ifdef RENEG { static int iiii; if (++iiii == 52) { SSL_renegotiate(con); iiii = 0; } } #endif k = SSL_read(con, sbuf, 1024 ); switch (SSL_get_error(con, k)) { case SSL_ERROR_NONE: if (k <= 0) goto end; sbuf_off = 0; sbuf_len = k; read_ssl = 0; write_tty = 1; break; case SSL_ERROR_WANT_ASYNC: BIO_printf(bio_c_out, "read A BLOCK\n"); wait_for_async(con); write_tty = 0; read_ssl = 1; if ((read_tty == 0) && (write_ssl == 0)) write_ssl = 1; break; case SSL_ERROR_WANT_WRITE: BIO_printf(bio_c_out, "read W BLOCK\n"); write_ssl = 1; read_tty = 0; break; case SSL_ERROR_WANT_READ: BIO_printf(bio_c_out, "read R BLOCK\n"); write_tty = 0; read_ssl = 1; if ((read_tty == 0) && (write_ssl == 0)) write_ssl = 1; break; case SSL_ERROR_WANT_X509_LOOKUP: BIO_printf(bio_c_out, "read X BLOCK\n"); break; case SSL_ERROR_SYSCALL: ret = get_last_socket_error(); if (c_brief) BIO_puts(bio_err, "CONNECTION CLOSED BY SERVER\n"); else BIO_printf(bio_err, "read:errno=%d\n", ret); goto shut; case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_c_out, "closed\n"); ret = 0; goto shut; case SSL_ERROR_WANT_ASYNC_JOB: case SSL_ERROR_SSL: ERR_print_errors(bio_err); goto shut; } } else if (nointeractive) { ret = 0; goto shut; } #if defined(OPENSSL_SYS_MSDOS) else if (has_stdin_waiting()) #else else if (FD_ISSET(fileno_stdin(), &readfds)) #endif { if (crlf) { int j, lf_num; i = raw_read_stdin(cbuf, BUFSIZZ / 2); lf_num = 0; for (j = 0; j < i; j++) if (cbuf[j] == '\n') lf_num++; for (j = i - 1; j >= 0; j--) { cbuf[j + lf_num] = cbuf[j]; if (cbuf[j] == '\n') { lf_num--; i++; cbuf[j + lf_num] = '\r'; } } assert(lf_num == 0); } else i = raw_read_stdin(cbuf, BUFSIZZ); #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) if (i == 0) at_eof = 1; #endif if (!c_ign_eof && i <= 0) { BIO_printf(bio_err, "DONE\n"); ret = 0; goto shut; } if (i > 0 && !user_data_add(&user_data, i)) { ret = 0; goto shut; } read_tty = 0; } first_loop = 0; } shut: if (in_init) print_stuff(bio_c_out, con, full_log); do_ssl_shutdown(con); shutdown(SSL_get_fd(con), 1); timeout.tv_sec = 0; timeout.tv_usec = 500000; do { FD_ZERO(&readfds); openssl_fdset(sock, &readfds); } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0 && BIO_read(sbio, sbuf, BUFSIZZ) > 0); BIO_closesocket(SSL_get_fd(con)); end: if (con != NULL) { if (prexit != 0) print_stuff(bio_c_out, con, 1); SSL_free(con); } SSL_SESSION_free(psksess); #if !defined(OPENSSL_NO_NEXTPROTONEG) OPENSSL_free(next_proto.data); #endif SSL_CTX_free(ctx); set_keylog_file(NULL, NULL); X509_free(cert); sk_X509_CRL_pop_free(crls, X509_CRL_free); EVP_PKEY_free(key); OSSL_STACK_OF_X509_free(chain); OPENSSL_free(pass); #ifndef OPENSSL_NO_SRP OPENSSL_free(srp_arg.srppassin); #endif OPENSSL_free(sname_alloc); BIO_ADDR_free(peer_addr); OPENSSL_free(connectstr); OPENSSL_free(bindstr); OPENSSL_free(bindhost); OPENSSL_free(bindport); OPENSSL_free(host); OPENSSL_free(port); OPENSSL_free(thost); OPENSSL_free(tport); X509_VERIFY_PARAM_free(vpm); ssl_excert_free(exc); sk_OPENSSL_STRING_free(ssl_args); sk_OPENSSL_STRING_free(dane_tlsa_rrset); SSL_CONF_CTX_free(cctx); OPENSSL_clear_free(cbuf, BUFSIZZ); OPENSSL_clear_free(sbuf, BUFSIZZ); OPENSSL_clear_free(mbuf, BUFSIZZ); clear_free(proxypass); release_engine(e); BIO_free(bio_c_out); bio_c_out = NULL; BIO_free(bio_c_msg); bio_c_msg = NULL; return ret; } static void print_stuff(BIO *bio, SSL *s, int full) { X509 *peer = NULL; STACK_OF(X509) *sk; const SSL_CIPHER *c; EVP_PKEY *public_key; int i, istls13 = (SSL_version(s) == TLS1_3_VERSION); long verify_result; #ifndef OPENSSL_NO_COMP const COMP_METHOD *comp, *expansion; #endif unsigned char *exportedkeymat; #ifndef OPENSSL_NO_CT const SSL_CTX *ctx = SSL_get_SSL_CTX(s); #endif if (full) { int got_a_chain = 0; sk = SSL_get_peer_cert_chain(s); if (sk != NULL) { got_a_chain = 1; BIO_printf(bio, "---\nCertificate chain\n"); for (i = 0; i < sk_X509_num(sk); i++) { BIO_printf(bio, "%2d s:", i); X509_NAME_print_ex(bio, X509_get_subject_name(sk_X509_value(sk, i)), 0, get_nameopt()); BIO_puts(bio, "\n"); BIO_printf(bio, " i:"); X509_NAME_print_ex(bio, X509_get_issuer_name(sk_X509_value(sk, i)), 0, get_nameopt()); BIO_puts(bio, "\n"); public_key = X509_get_pubkey(sk_X509_value(sk, i)); if (public_key != NULL) { BIO_printf(bio, " a:PKEY: %s, %d (bit); sigalg: %s\n", OBJ_nid2sn(EVP_PKEY_get_base_id(public_key)), EVP_PKEY_get_bits(public_key), OBJ_nid2sn(X509_get_signature_nid(sk_X509_value(sk, i)))); EVP_PKEY_free(public_key); } BIO_printf(bio, " v:NotBefore: "); ASN1_TIME_print(bio, X509_get0_notBefore(sk_X509_value(sk, i))); BIO_printf(bio, "; NotAfter: "); ASN1_TIME_print(bio, X509_get0_notAfter(sk_X509_value(sk, i))); BIO_puts(bio, "\n"); if (c_showcerts) PEM_write_bio_X509(bio, sk_X509_value(sk, i)); } } BIO_printf(bio, "---\n"); peer = SSL_get0_peer_certificate(s); if (peer != NULL) { BIO_printf(bio, "Server certificate\n"); if (!(c_showcerts && got_a_chain)) PEM_write_bio_X509(bio, peer); dump_cert_text(bio, peer); } else { BIO_printf(bio, "no peer certificate available\n"); } if (SSL_get_negotiated_client_cert_type(s) == TLSEXT_cert_type_rpk) BIO_printf(bio, "Client-to-server raw public key negotiated\n"); if (SSL_get_negotiated_server_cert_type(s) == TLSEXT_cert_type_rpk) BIO_printf(bio, "Server-to-client raw public key negotiated\n"); if (enable_server_rpk) { EVP_PKEY *peer_rpk = SSL_get0_peer_rpk(s); if (peer_rpk != NULL) { BIO_printf(bio, "Server raw public key\n"); EVP_PKEY_print_public(bio, peer_rpk, 2, NULL); } else { BIO_printf(bio, "no peer rpk available\n"); } } print_ca_names(bio, s); ssl_print_sigalgs(bio, s); ssl_print_tmp_key(bio, s); #ifndef OPENSSL_NO_CT if (peer != NULL && !SSL_session_reused(s) && SSL_ct_is_enabled(s)) { const STACK_OF(SCT) *scts = SSL_get0_peer_scts(s); int sct_count = scts != NULL ? sk_SCT_num(scts) : 0; BIO_printf(bio, "---\nSCTs present (%i)\n", sct_count); if (sct_count > 0) { const CTLOG_STORE *log_store = SSL_CTX_get0_ctlog_store(ctx); BIO_printf(bio, "---\n"); for (i = 0; i < sct_count; ++i) { SCT *sct = sk_SCT_value(scts, i); BIO_printf(bio, "SCT validation status: %s\n", SCT_validation_status_string(sct)); SCT_print(sct, bio, 0, log_store); if (i < sct_count - 1) BIO_printf(bio, "\n---\n"); } BIO_printf(bio, "\n"); } } #endif BIO_printf(bio, "---\nSSL handshake has read %ju bytes " "and written %ju bytes\n", BIO_number_read(SSL_get_rbio(s)), BIO_number_written(SSL_get_wbio(s))); } print_verify_detail(s, bio); BIO_printf(bio, (SSL_session_reused(s) ? "---\nReused, " : "---\nNew, ")); c = SSL_get_current_cipher(s); BIO_printf(bio, "%s, Cipher is %s\n", SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c)); if (peer != NULL) { EVP_PKEY *pktmp; pktmp = X509_get0_pubkey(peer); BIO_printf(bio, "Server public key is %d bit\n", EVP_PKEY_get_bits(pktmp)); } ssl_print_secure_renegotiation_notes(bio, s); #ifndef OPENSSL_NO_COMP comp = SSL_get_current_compression(s); expansion = SSL_get_current_expansion(s); BIO_printf(bio, "Compression: %s\n", comp ? SSL_COMP_get_name(comp) : "NONE"); BIO_printf(bio, "Expansion: %s\n", expansion ? SSL_COMP_get_name(expansion) : "NONE"); #endif #ifndef OPENSSL_NO_KTLS if (BIO_get_ktls_send(SSL_get_wbio(s))) BIO_printf(bio_err, "Using Kernel TLS for sending\n"); if (BIO_get_ktls_recv(SSL_get_rbio(s))) BIO_printf(bio_err, "Using Kernel TLS for receiving\n"); #endif if (OSSL_TRACE_ENABLED(TLS)) { int sock; union BIO_sock_info_u info; sock = SSL_get_fd(s); if ((info.addr = BIO_ADDR_new()) != NULL && BIO_sock_info(sock, BIO_SOCK_INFO_ADDRESS, &info)) { BIO_printf(bio_c_out, "LOCAL PORT is %u\n", ntohs(BIO_ADDR_rawport(info.addr))); } BIO_ADDR_free(info.addr); } #if !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto.status != -1) { const unsigned char *proto; unsigned int proto_len; SSL_get0_next_proto_negotiated(s, &proto, &proto_len); BIO_printf(bio, "Next protocol: (%d) ", next_proto.status); BIO_write(bio, proto, proto_len); BIO_write(bio, "\n", 1); } #endif { const unsigned char *proto; unsigned int proto_len; SSL_get0_alpn_selected(s, &proto, &proto_len); if (proto_len > 0) { BIO_printf(bio, "ALPN protocol: "); BIO_write(bio, proto, proto_len); BIO_write(bio, "\n", 1); } else BIO_printf(bio, "No ALPN negotiated\n"); } #ifndef OPENSSL_NO_SRTP { SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(s); if (srtp_profile) BIO_printf(bio, "SRTP Extension negotiated, profile=%s\n", srtp_profile->name); } #endif if (istls13) { switch (SSL_get_early_data_status(s)) { case SSL_EARLY_DATA_NOT_SENT: BIO_printf(bio, "Early data was not sent\n"); break; case SSL_EARLY_DATA_REJECTED: BIO_printf(bio, "Early data was rejected\n"); break; case SSL_EARLY_DATA_ACCEPTED: BIO_printf(bio, "Early data was accepted\n"); break; } verify_result = SSL_get_verify_result(s); BIO_printf(bio, "Verify return code: %ld (%s)\n", verify_result, X509_verify_cert_error_string(verify_result)); } else { SSL_SESSION_print(bio, SSL_get_session(s)); } if (SSL_get_session(s) != NULL && keymatexportlabel != NULL) { BIO_printf(bio, "Keying material exporter:\n"); BIO_printf(bio, " Label: '%s'\n", keymatexportlabel); BIO_printf(bio, " Length: %i bytes\n", keymatexportlen); exportedkeymat = app_malloc(keymatexportlen, "export key"); if (SSL_export_keying_material(s, exportedkeymat, keymatexportlen, keymatexportlabel, strlen(keymatexportlabel), NULL, 0, 0) <= 0) { BIO_printf(bio, " Error\n"); } else { BIO_printf(bio, " Keying material: "); for (i = 0; i < keymatexportlen; i++) BIO_printf(bio, "%02X", exportedkeymat[i]); BIO_printf(bio, "\n"); } OPENSSL_free(exportedkeymat); } BIO_printf(bio, "---\n"); (void)BIO_flush(bio); } # ifndef OPENSSL_NO_OCSP static int ocsp_resp_cb(SSL *s, void *arg) { const unsigned char *p; int len; OCSP_RESPONSE *rsp; len = SSL_get_tlsext_status_ocsp_resp(s, &p); BIO_puts(arg, "OCSP response: "); if (p == NULL) { BIO_puts(arg, "no response sent\n"); return 1; } rsp = d2i_OCSP_RESPONSE(NULL, &p, len); if (rsp == NULL) { BIO_puts(arg, "response parse error\n"); BIO_dump_indent(arg, (char *)p, len, 4); return 0; } BIO_puts(arg, "\n======================================\n"); OCSP_RESPONSE_print(arg, rsp, 0); BIO_puts(arg, "======================================\n"); OCSP_RESPONSE_free(rsp); return 1; } # endif static int ldap_ExtendedResponse_parse(const char *buf, long rem) { const unsigned char *cur, *end; long len; int tag, xclass, inf, ret = -1; cur = (const unsigned char *)buf; end = cur + rem; inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem); if (inf != V_ASN1_CONSTRUCTED || tag != V_ASN1_SEQUENCE || (rem = end - cur, len > rem)) { BIO_printf(bio_err, "Unexpected LDAP response\n"); goto end; } rem = len; inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem); if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_INTEGER || (rem = end - cur, len > rem)) { BIO_printf(bio_err, "No MessageID\n"); goto end; } cur += len; rem = end - cur; inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem); if (inf != V_ASN1_CONSTRUCTED || xclass != V_ASN1_APPLICATION || tag != 24) { BIO_printf(bio_err, "Not ExtendedResponse\n"); goto end; } rem = end - cur; inf = ASN1_get_object(&cur, &len, &tag, &xclass, rem); if (inf != V_ASN1_UNIVERSAL || tag != V_ASN1_ENUMERATED || len == 0 || (rem = end - cur, len > rem)) { BIO_printf(bio_err, "Not LDAPResult\n"); goto end; } for (ret = 0, inf = 0; inf < len; inf++) { ret <<= 8; ret |= cur[inf]; } end: return ret; } static int is_dNS_name(const char *host) { const size_t MAX_LABEL_LENGTH = 63; size_t i; int isdnsname = 0; size_t length = strlen(host); size_t label_length = 0; int all_numeric = 1; for (i = 0; i < length && label_length < MAX_LABEL_LENGTH; ++i) { char c = host[i]; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_') { label_length += 1; all_numeric = 0; continue; } if (c >= '0' && c <= '9') { label_length += 1; continue; } if (i > 0 && i < length - 1) { if (c == '-') { label_length += 1; continue; } if (c == '.' && host[i + 1] != '.' && host[i - 1] != '-' && host[i + 1] != '-') { label_length = 0; isdnsname = 1; continue; } } isdnsname = 0; break; } isdnsname &= !all_numeric && !(label_length == MAX_LABEL_LENGTH); return isdnsname; } static void user_data_init(struct user_data_st *user_data, SSL *con, char *buf, size_t bufmax, int mode) { user_data->con = con; user_data->buf = buf; user_data->bufmax = bufmax; user_data->buflen = 0; user_data->bufoff = 0; user_data->mode = mode; user_data->isfin = 0; } static int user_data_add(struct user_data_st *user_data, size_t i) { if (user_data->buflen != 0 || i > user_data->bufmax) return 0; user_data->buflen = i; user_data->bufoff = 0; return 1; } #define USER_COMMAND_HELP 0 #define USER_COMMAND_QUIT 1 #define USER_COMMAND_RECONNECT 2 #define USER_COMMAND_RENEGOTIATE 3 #define USER_COMMAND_KEY_UPDATE 4 #define USER_COMMAND_FIN 5 static int user_data_execute(struct user_data_st *user_data, int cmd, char *arg) { switch (cmd) { case USER_COMMAND_HELP: BIO_printf(bio_err, "Enter text to send to the peer followed by <enter>\n"); BIO_printf(bio_err, "To issue a command insert {cmd} or {cmd:arg} anywhere in the text\n"); BIO_printf(bio_err, "Entering {{ will send { to the peer\n"); BIO_printf(bio_err, "The following commands are available\n"); BIO_printf(bio_err, " {help}: Get this help text\n"); BIO_printf(bio_err, " {quit}: Close the connection to the peer\n"); BIO_printf(bio_err, " {reconnect}: Reconnect to the peer\n"); if (SSL_is_quic(user_data->con)) { BIO_printf(bio_err, " {fin}: Send FIN on the stream. No further writing is possible\n"); } else if(SSL_version(user_data->con) == TLS1_3_VERSION) { BIO_printf(bio_err, " {keyup:req|noreq}: Send a Key Update message\n"); BIO_printf(bio_err, " Arguments:\n"); BIO_printf(bio_err, " req = peer update requested (default)\n"); BIO_printf(bio_err, " noreq = peer update not requested\n"); } else { BIO_printf(bio_err, " {reneg}: Attempt to renegotiate\n"); } BIO_printf(bio_err, "\n"); return USER_DATA_PROCESS_NO_DATA; case USER_COMMAND_QUIT: BIO_printf(bio_err, "DONE\n"); return USER_DATA_PROCESS_SHUT; case USER_COMMAND_RECONNECT: BIO_printf(bio_err, "RECONNECTING\n"); do_ssl_shutdown(user_data->con); SSL_set_connect_state(user_data->con); BIO_closesocket(SSL_get_fd(user_data->con)); return USER_DATA_PROCESS_RESTART; case USER_COMMAND_RENEGOTIATE: BIO_printf(bio_err, "RENEGOTIATING\n"); if (!SSL_renegotiate(user_data->con)) break; return USER_DATA_PROCESS_CONTINUE; case USER_COMMAND_KEY_UPDATE: { int updatetype; if (OPENSSL_strcasecmp(arg, "req") == 0) updatetype = SSL_KEY_UPDATE_REQUESTED; else if (OPENSSL_strcasecmp(arg, "noreq") == 0) updatetype = SSL_KEY_UPDATE_NOT_REQUESTED; else return USER_DATA_PROCESS_BAD_ARGUMENT; BIO_printf(bio_err, "KEYUPDATE\n"); if (!SSL_key_update(user_data->con, updatetype)) break; return USER_DATA_PROCESS_CONTINUE; } case USER_COMMAND_FIN: if (!SSL_stream_conclude(user_data->con, 0)) break; user_data->isfin = 1; return USER_DATA_PROCESS_NO_DATA; default: break; } BIO_printf(bio_err, "ERROR\n"); ERR_print_errors(bio_err); return USER_DATA_PROCESS_SHUT; } static int user_data_process(struct user_data_st *user_data, size_t *len, size_t *off) { char *buf_start = user_data->buf + user_data->bufoff; size_t outlen = user_data->buflen; if (user_data->buflen == 0) { *len = 0; *off = 0; return USER_DATA_PROCESS_NO_DATA; } if (user_data->mode == USER_DATA_MODE_BASIC) { switch (buf_start[0]) { case 'Q': user_data->buflen = user_data->bufoff = *len = *off = 0; return user_data_execute(user_data, USER_COMMAND_QUIT, NULL); case 'C': user_data->buflen = user_data->bufoff = *len = *off = 0; return user_data_execute(user_data, USER_COMMAND_RECONNECT, NULL); case 'R': user_data->buflen = user_data->bufoff = *len = *off = 0; return user_data_execute(user_data, USER_COMMAND_RENEGOTIATE, NULL); case 'K': case 'k': user_data->buflen = user_data->bufoff = *len = *off = 0; return user_data_execute(user_data, USER_COMMAND_KEY_UPDATE, buf_start[0] == 'K' ? "req" : "noreq"); default: break; } } else if (user_data->mode == USER_DATA_MODE_ADVANCED) { char *cmd_start = buf_start; cmd_start[outlen] = '\0'; for (;;) { cmd_start = strchr(cmd_start, '{'); if (cmd_start == buf_start && *(cmd_start + 1) == '{') { cmd_start += 2; buf_start++; user_data->bufoff++; user_data->buflen--; outlen--; continue; } break; } if (cmd_start == buf_start) { char *cmd_end = strchr(cmd_start, '}'); char *arg_start; int cmd = -1, ret = USER_DATA_PROCESS_NO_DATA; size_t oldoff; if (cmd_end == NULL) { cmd_start[outlen - 1] = '\0'; BIO_printf(bio_err, "ERROR PROCESSING COMMAND. REST OF LINE IGNORED: %s\n", cmd_start); user_data->buflen = user_data->bufoff = *len = *off = 0; return USER_DATA_PROCESS_NO_DATA; } *cmd_end = '\0'; arg_start = strchr(cmd_start, ':'); if (arg_start != NULL) { *arg_start = '\0'; arg_start++; } cmd_start++; if (OPENSSL_strcasecmp(cmd_start, "help") == 0) { cmd = USER_COMMAND_HELP; } else if (OPENSSL_strcasecmp(cmd_start, "quit") == 0) { cmd = USER_COMMAND_QUIT; } else if (OPENSSL_strcasecmp(cmd_start, "reconnect") == 0) { cmd = USER_COMMAND_RECONNECT; } else if(SSL_is_quic(user_data->con)) { if (OPENSSL_strcasecmp(cmd_start, "fin") == 0) cmd = USER_COMMAND_FIN; } if (SSL_version(user_data->con) == TLS1_3_VERSION) { if (OPENSSL_strcasecmp(cmd_start, "keyup") == 0) { cmd = USER_COMMAND_KEY_UPDATE; if (arg_start == NULL) arg_start = "req"; } } else { if (OPENSSL_strcasecmp(cmd_start, "reneg") == 0) cmd = USER_COMMAND_RENEGOTIATE; } if (cmd == -1) { BIO_printf(bio_err, "UNRECOGNISED COMMAND (IGNORED): %s\n", cmd_start); } else { ret = user_data_execute(user_data, cmd, arg_start); if (ret == USER_DATA_PROCESS_BAD_ARGUMENT) { BIO_printf(bio_err, "BAD ARGUMENT (COMMAND IGNORED): %s\n", arg_start); ret = USER_DATA_PROCESS_NO_DATA; } } oldoff = user_data->bufoff; user_data->bufoff = (cmd_end - user_data->buf) + 1; user_data->buflen -= user_data->bufoff - oldoff; if (user_data->buf + 1 == cmd_start && user_data->buflen == 1 && user_data->buf[user_data->bufoff] == '\n') { user_data->bufoff = 0; user_data->buflen = 0; } *len = *off = 0; return ret; } else if (cmd_start != NULL) { outlen = cmd_start - buf_start; } } if (user_data->isfin) { user_data->buflen = user_data->bufoff = *len = *off = 0; return USER_DATA_PROCESS_NO_DATA; } #ifdef CHARSET_EBCDIC ebcdic2ascii(buf_start, buf_start, outlen); #endif *len = outlen; *off = user_data->bufoff; user_data->buflen -= outlen; if (user_data->buflen == 0) user_data->bufoff = 0; else user_data->bufoff += outlen; return USER_DATA_PROCESS_CONTINUE; } static int user_data_has_data(struct user_data_st *user_data) { return user_data->buflen > 0; } #endif
apps
openssl/apps/s_client.c
openssl
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/hmac.h> #include <ctype.h> #undef BUFSIZE #define BUFSIZE 1024*8 int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, int xoflen, EVP_PKEY *key, unsigned char *sigin, int siglen, const char *sig_name, const char *md_name, const char *file); static void show_digests(const OBJ_NAME *name, void *bio_); struct doall_dgst_digests { BIO *bio; int n; }; typedef enum OPTION_choice { OPT_COMMON, OPT_LIST, OPT_C, OPT_R, OPT_OUT, OPT_SIGN, OPT_PASSIN, OPT_VERIFY, OPT_PRVERIFY, OPT_SIGNATURE, OPT_KEYFORM, OPT_ENGINE, OPT_ENGINE_IMPL, OPT_HEX, OPT_BINARY, OPT_DEBUG, OPT_FIPS_FINGERPRINT, OPT_HMAC, OPT_MAC, OPT_SIGOPT, OPT_MACOPT, OPT_XOFLEN, OPT_DIGEST, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS dgst_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [file...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"list", OPT_LIST, '-', "List digests"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"}, {"engine_impl", OPT_ENGINE_IMPL, '-', "Also use engine given by -engine for digest operations"}, #endif {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, OPT_SECTION("Output"), {"c", OPT_C, '-', "Print the digest with separating colons"}, {"r", OPT_R, '-', "Print the digest in coreutils format"}, {"out", OPT_OUT, '>', "Output to filename rather than stdout"}, {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"}, {"hex", OPT_HEX, '-', "Print as hex dump"}, {"binary", OPT_BINARY, '-', "Print in binary form"}, {"xoflen", OPT_XOFLEN, 'p', "Output length for XOF algorithms. To obtain the maximum security strength set this to 32 (or greater) for SHAKE128, and 64 (or greater) for SHAKE256"}, {"d", OPT_DEBUG, '-', "Print debug info"}, {"debug", OPT_DEBUG, '-', "Print debug info"}, OPT_SECTION("Signing"), {"sign", OPT_SIGN, 's', "Sign digest using private key"}, {"verify", OPT_VERIFY, 's', "Verify a signature using public key"}, {"prverify", OPT_PRVERIFY, 's', "Verify a signature using private key"}, {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"}, {"signature", OPT_SIGNATURE, '<', "File with signature to verify"}, {"hmac", OPT_HMAC, 's', "Create hashed MAC with key"}, {"mac", OPT_MAC, 's', "Create MAC (not necessarily HMAC)"}, {"macopt", OPT_MACOPT, 's', "MAC algorithm parameters in n:v form or key"}, {"", OPT_DIGEST, '-', "Any supported digest"}, {"fips-fingerprint", OPT_FIPS_FINGERPRINT, '-', "Compute HMAC with the key used in OpenSSL-FIPS fingerprint"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"file", 0, 0, "Files to digest (optional; default is stdin)"}, {NULL} }; 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, *digestname = NULL; char *passinarg = NULL, *passin = NULL; EVP_MD *md = NULL; const char *outfile = NULL, *keyfile = NULL, *prog = NULL; const char *sigfile = NULL; const char *md_name = NULL; OPTION_CHOICE o; int separator = 0, debug = 0, keyform = FORMAT_UNDEF, siglen = 0; int i, ret = EXIT_FAILURE, out_bin = -1, want_pub = 0, do_verify = 0; int xoflen = 0; unsigned char *buf = NULL, *sigbuf = NULL; int engine_impl = 0; struct doall_dgst_digests dec; buf = app_malloc(BUFSIZE, "I/O buffer"); md = (EVP_MD *)EVP_get_digestbyname(argv[0]); if (md != NULL) digestname = argv[0]; opt_set_unknown_name("digest"); 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 = EXIT_SUCCESS; goto end; case OPT_LIST: BIO_printf(bio_out, "Supported digests:\n"); dec.bio = bio_out; dec.n = 0; OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_MD_METH, show_digests, &dec); BIO_printf(bio_out, "\n"); ret = EXIT_SUCCESS; goto end; case OPT_C: separator = 1; break; case OPT_R: separator = 2; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; 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_XOFLEN: xoflen = atoi(opt_arg()); break; case OPT_DEBUG: debug = 1; break; case OPT_FIPS_FINGERPRINT: hmac_key = "etaonrishdlcupfm"; 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: digestname = opt_unknown(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } argc = opt_num_rest(); argv = opt_rest(); if (keyfile != NULL && argc > 1) { BIO_printf(bio_err, "%s: Can only sign or verify one file.\n", prog); goto end; } if (!app_RAND_load()) goto end; if (digestname != NULL) { if (!opt_md(digestname, &md)) goto opthelp; } if (do_verify && sigfile == NULL) { 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) goto end; if (debug) { BIO_set_callback_ex(in, BIO_debug_callback_ex); 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 != NULL) out_bin = 1; else out_bin = 0; } out = bio_open_default(outfile, 'w', out_bin ? FORMAT_BINARY : FORMAT_TEXT); if (out == NULL) goto end; if ((!(mac_name == NULL) + !(keyfile == NULL) + !(hmac_key == NULL)) > 1) { BIO_printf(bio_err, "MAC and signing key cannot both be specified\n"); goto end; } if (keyfile != NULL) { int type; if (want_pub) sigkey = load_pubkey(keyfile, keyform, 0, NULL, e, "public key"); else sigkey = load_key(keyfile, keyform, 0, passin, e, "private key"); if (sigkey == NULL) { goto end; } type = EVP_PKEY_get_id(sigkey); if (type == EVP_PKEY_ED25519 || type == EVP_PKEY_ED448) { BIO_printf(bio_err, "Key type not supported for this operation\n"); goto end; } } if (mac_name != NULL) { EVP_PKEY_CTX *mac_ctx = NULL; if (!init_gen_str(&mac_ctx, mac_name, impl, 0, NULL, NULL)) goto end; if (macopts != NULL) { for (i = 0; i < sk_OPENSSL_STRING_num(macopts); i++) { char *macopt = sk_OPENSSL_STRING_value(macopts, i); if (pkey_ctrl_string(mac_ctx, macopt) <= 0) { EVP_PKEY_CTX_free(mac_ctx); BIO_printf(bio_err, "MAC parameter error \"%s\"\n", macopt); goto end; } } } sigkey = app_keygen(mac_ctx, mac_name, 0, 0 ); EVP_PKEY_CTX_free(mac_ctx); if (sigkey == NULL) goto end; } if (hmac_key != NULL) { if (md == NULL) { md = (EVP_MD *)EVP_sha256(); digestname = SN_sha256; } sigkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, impl, (unsigned char *)hmac_key, strlen(hmac_key)); if (sigkey == NULL) goto end; } if (sigkey != NULL) { EVP_MD_CTX *mctx = NULL; EVP_PKEY_CTX *pctx = NULL; int res; if (BIO_get_md_ctx(bmd, &mctx) <= 0) { BIO_printf(bio_err, "Error getting context\n"); goto end; } if (do_verify) if (impl == NULL) res = EVP_DigestVerifyInit_ex(mctx, &pctx, digestname, app_get0_libctx(), app_get0_propq(), sigkey, NULL); else res = EVP_DigestVerifyInit(mctx, &pctx, md, impl, sigkey); else if (impl == NULL) res = EVP_DigestSignInit_ex(mctx, &pctx, digestname, app_get0_libctx(), app_get0_propq(), sigkey, NULL); else res = EVP_DigestSignInit(mctx, &pctx, md, impl, sigkey); if (res == 0) { BIO_printf(bio_err, "Error setting context\n"); goto end; } if (sigopts != NULL) { for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) { char *sigopt = sk_OPENSSL_STRING_value(sigopts, i); if (pkey_ctrl_string(pctx, sigopt) <= 0) { BIO_printf(bio_err, "Signature parameter error \"%s\"\n", sigopt); goto end; } } } } else { EVP_MD_CTX *mctx = NULL; if (BIO_get_md_ctx(bmd, &mctx) <= 0) { BIO_printf(bio_err, "Error getting context\n"); goto end; } if (md == NULL) md = (EVP_MD *)EVP_sha256(); if (!EVP_DigestInit_ex(mctx, md, impl)) { BIO_printf(bio_err, "Error setting digest\n"); goto end; } } if (sigfile != NULL && sigkey != NULL) { BIO *sigbio = BIO_new_file(sigfile, "rb"); if (sigbio == NULL) { BIO_printf(bio_err, "Error opening signature file %s\n", sigfile); goto end; } siglen = EVP_PKEY_get_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); goto end; } } inp = BIO_push(bmd, in); if (md == NULL) { EVP_MD_CTX *tctx; BIO_get_md_ctx(bmd, &tctx); md = EVP_MD_CTX_get1_md(tctx); } if (md != NULL) md_name = EVP_MD_get0_name(md); if (xoflen > 0) { if (!(EVP_MD_get_flags(md) & EVP_MD_FLAG_XOF)) { BIO_printf(bio_err, "Length can only be specified for XOF\n"); goto end; } if (sigkey != NULL) { BIO_printf(bio_err, "Signing key cannot be specified for XOF\n"); goto end; } } if (argc == 0) { BIO_set_fp(in, stdin, BIO_NOCLOSE); ret = do_fp(out, buf, inp, separator, out_bin, xoflen, sigkey, sigbuf, siglen, NULL, md_name, "stdin"); } else { const char *sig_name = NULL; if (out_bin == 0) { if (sigkey != NULL) sig_name = EVP_PKEY_get0_type_name(sigkey); } ret = EXIT_SUCCESS; for (i = 0; i < argc; i++) { if (BIO_read_filename(in, argv[i]) <= 0) { perror(argv[i]); ret = EXIT_FAILURE; continue; } else { if (do_fp(out, buf, inp, separator, out_bin, xoflen, sigkey, sigbuf, siglen, sig_name, md_name, argv[i])) ret = EXIT_FAILURE; } (void)BIO_reset(bmd); } } end: if (ret != EXIT_SUCCESS) ERR_print_errors(bio_err); OPENSSL_clear_free(buf, BUFSIZE); BIO_free(in); OPENSSL_free(passin); BIO_free_all(out); EVP_MD_free(md); EVP_PKEY_free(sigkey); sk_OPENSSL_STRING_free(sigopts); sk_OPENSSL_STRING_free(macopts); OPENSSL_free(sigbuf); BIO_free(bmd); release_engine(e); return ret; } static void show_digests(const OBJ_NAME *name, void *arg) { struct doall_dgst_digests *dec = (struct doall_dgst_digests *)arg; const EVP_MD *md = NULL; if (strstr(name->name, "rsa") != NULL || strstr(name->name, "RSA") != NULL) return; if (!islower((unsigned char)*name->name)) return; md = EVP_MD_fetch(app_get0_libctx(), name->name, app_get0_propq()); if (md == NULL) { md = EVP_get_digestbyname(name->name); if (md == NULL) return; } BIO_printf(dec->bio, "-%-25s", name->name); if (++dec->n == 3) { BIO_printf(dec->bio, "\n"); dec->n = 0; } else { BIO_printf(dec->bio, " "); } } static const char *newline_escape_filename(const char *file, int *backslash) { size_t i, e = 0, length = strlen(file), newline_count = 0, mem_len = 0; char *file_cpy = NULL; for (i = 0; i < length; i++) if (file[i] == '\n') newline_count++; mem_len = length + newline_count + 1; file_cpy = app_malloc(mem_len, file); i = 0; while (e < length) { const char c = file[e]; if (c == '\n') { file_cpy[i++] = '\\'; file_cpy[i++] = 'n'; *backslash = 1; } else { file_cpy[i++] = c; } e++; } file_cpy[i] = '\0'; return (const char*)file_cpy; } int do_fp(BIO *out, unsigned char *buf, BIO *bp, int sep, int binout, int xoflen, EVP_PKEY *key, unsigned char *sigin, int siglen, const char *sig_name, const char *md_name, const char *file) { size_t len = BUFSIZE; int i, backslash = 0, ret = EXIT_FAILURE; unsigned char *allocated_buf = NULL; while (BIO_pending(bp) || !BIO_eof(bp)) { i = BIO_read(bp, (char *)buf, BUFSIZE); if (i < 0) { BIO_printf(bio_err, "Read error in %s\n", file); goto end; } if (i == 0) break; } if (sigin != NULL) { 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"); goto end; } else { BIO_printf(bio_err, "Error verifying data\n"); goto end; } ret = EXIT_SUCCESS; goto end; } if (key != NULL) { EVP_MD_CTX *ctx; size_t tmplen; BIO_get_md_ctx(bp, &ctx); if (!EVP_DigestSignFinal(ctx, NULL, &tmplen)) { BIO_printf(bio_err, "Error getting maximum length of signed data\n"); goto end; } if (tmplen > BUFSIZE) { len = tmplen; allocated_buf = app_malloc(len, "Signature buffer"); buf = allocated_buf; } if (!EVP_DigestSignFinal(ctx, buf, &len)) { BIO_printf(bio_err, "Error signing data\n"); goto end; } } else if (xoflen > 0) { EVP_MD_CTX *ctx; len = xoflen; if (len > BUFSIZE) { allocated_buf = app_malloc(len, "Digest buffer"); buf = allocated_buf; } BIO_get_md_ctx(bp, &ctx); if (!EVP_DigestFinalXOF(ctx, buf, len)) { BIO_printf(bio_err, "Error Digesting Data\n"); goto end; } } else { len = BIO_gets(bp, (char *)buf, BUFSIZE); if ((int)len < 0) goto end; } if (binout) { BIO_write(out, buf, len); } else if (sep == 2) { file = newline_escape_filename(file, &backslash); if (backslash == 1) BIO_puts(out, "\\"); for (i = 0; i < (int)len; i++) BIO_printf(out, "%02x", buf[i]); BIO_printf(out, " *%s\n", file); OPENSSL_free((char *)file); } else { if (sig_name != NULL) { BIO_puts(out, sig_name); if (md_name != NULL) BIO_printf(out, "-%s", md_name); BIO_printf(out, "(%s)= ", file); } else if (md_name != NULL) { 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"); } ret = EXIT_SUCCESS; end: if (allocated_buf != NULL) OPENSSL_clear_free(allocated_buf, len); return ret; }
apps
openssl/apps/dgst.c
openssl
#include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/ts.h> #include <openssl/bn.h> #define NONCE_LENGTH 64 #define ENV_OID_FILE "oid_file" #define EXACTLY_ONE(a, b, c) \ (( a && !b && !c) || \ ( b && !a && !c) || \ ( c && !a && !b)) static ASN1_OBJECT *txt2obj(const char *oid); static CONF *load_config_file(const char *configfile); static int query_command(const char *data, const char *digest, const EVP_MD *md, const char *policy, int no_nonce, int cert, const char *in, const char *out, int text); static TS_REQ *create_query(BIO *data_bio, const char *digest, const EVP_MD *md, const char *policy, int no_nonce, int cert); static int create_digest(BIO *input, const char *digest, const EVP_MD *md, unsigned char **md_value); static ASN1_INTEGER *create_nonce(int bits); static int reply_command(CONF *conf, const char *section, const char *engine, const char *queryfile, const char *passin, const char *inkey, const EVP_MD *md, const char *signer, const char *chain, const char *policy, const char *in, int token_in, const char *out, int token_out, int text); static TS_RESP *read_PKCS7(BIO *in_bio); static TS_RESP *create_response(CONF *conf, const char *section, const char *engine, const char *queryfile, const char *passin, const char *inkey, const EVP_MD *md, const char *signer, const char *chain, const char *policy); static ASN1_INTEGER *serial_cb(TS_RESP_CTX *ctx, void *data); static ASN1_INTEGER *next_serial(const char *serialfile); static int save_ts_serial(const char *serialfile, ASN1_INTEGER *serial); static int verify_command(const char *data, const char *digest, const char *queryfile, const char *in, int token_in, const char *CApath, const char *CAfile, const char *CAstore, char *untrusted, X509_VERIFY_PARAM *vpm); static TS_VERIFY_CTX *create_verify_ctx(const char *data, const char *digest, const char *queryfile, const char *CApath, const char *CAfile, const char *CAstore, char *untrusted, X509_VERIFY_PARAM *vpm); static X509_STORE *create_cert_store(const char *CApath, const char *CAfile, const char *CAstore, X509_VERIFY_PARAM *vpm); static int verify_cb(int ok, X509_STORE_CTX *ctx); typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_CONFIG, OPT_SECTION, OPT_QUERY, OPT_DATA, OPT_DIGEST, OPT_TSPOLICY, OPT_NO_NONCE, OPT_CERT, OPT_IN, OPT_TOKEN_IN, OPT_OUT, OPT_TOKEN_OUT, OPT_TEXT, OPT_REPLY, OPT_QUERYFILE, OPT_PASSIN, OPT_INKEY, OPT_SIGNER, OPT_CHAIN, OPT_VERIFY, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE, OPT_UNTRUSTED, OPT_MD, OPT_V_ENUM, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS ts_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"config", OPT_CONFIG, '<', "Configuration file"}, {"section", OPT_SECTION, 's', "Section to use within config file"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"inkey", OPT_INKEY, 's', "File with private key for reply"}, {"signer", OPT_SIGNER, 's', "Signer certificate file"}, {"chain", OPT_CHAIN, '<', "File with signer CA chain"}, {"CAfile", OPT_CAFILE, '<', "File with trusted CA certs"}, {"CApath", OPT_CAPATH, '/', "Path to trusted CA files"}, {"CAstore", OPT_CASTORE, ':', "URI to trusted CA store"}, {"untrusted", OPT_UNTRUSTED, '<', "Extra untrusted certs"}, {"token_in", OPT_TOKEN_IN, '-', "Input is a PKCS#7 file"}, {"token_out", OPT_TOKEN_OUT, '-', "Output is a PKCS#7 file"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"", OPT_MD, '-', "Any supported digest"}, OPT_SECTION("Query"), {"query", OPT_QUERY, '-', "Generate a TS query"}, {"data", OPT_DATA, '<', "File to hash"}, {"digest", OPT_DIGEST, 's', "Digest (as a hex string)"}, {"queryfile", OPT_QUERYFILE, '<', "File containing a TS query"}, {"cert", OPT_CERT, '-', "Put cert request into query"}, {"in", OPT_IN, '<', "Input file"}, OPT_SECTION("Verify"), {"verify", OPT_VERIFY, '-', "Verify a TS response"}, {"reply", OPT_REPLY, '-', "Generate a TS reply"}, {"tspolicy", OPT_TSPOLICY, 's', "Policy OID to use"}, {"no_nonce", OPT_NO_NONCE, '-', "Do not include a nonce"}, {"out", OPT_OUT, '>', "Output file"}, {"text", OPT_TEXT, '-', "Output text (not DER)"}, OPT_R_OPTIONS, OPT_V_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; static char* opt_helplist[] = { "", "Typical uses:", " openssl ts -query [-rand file...] [-config file] [-data file]", " [-digest hexstring] [-tspolicy oid] [-no_nonce] [-cert]", " [-in file] [-out file] [-text]", "", " openssl ts -reply [-config file] [-section tsa_section]", " [-queryfile file] [-passin password]", " [-signer tsa_cert.pem] [-inkey private_key.pem]", " [-chain certs_file.pem] [-tspolicy oid]", " [-in file] [-token_in] [-out file] [-token_out]", #ifndef OPENSSL_NO_ENGINE " [-text] [-engine id]", #else " [-text]", #endif "", " openssl ts -verify -CApath dir -CAfile root-cert.pem -CAstore uri", " -untrusted extra-certs.pem [-data file] [-digest hexstring]", " [-queryfile request.tsq] -in response.tsr [-token_in] ...", NULL, }; int ts_main(int argc, char **argv) { CONF *conf = NULL; const char *CAfile = NULL, *prog; char *untrusted = NULL; const char *configfile = default_config_file, *engine = NULL; const char *section = NULL, *digestname = NULL; char **helpp; char *password = NULL; char *data = NULL, *digest = NULL, *policy = NULL; char *in = NULL, *out = NULL, *queryfile = NULL, *passin = NULL; char *inkey = NULL, *signer = NULL, *chain = NULL, *CApath = NULL; char *CAstore = NULL; EVP_MD *md = NULL; OPTION_CHOICE o, mode = OPT_ERR; int ret = 1, no_nonce = 0, cert = 0, text = 0; int vpmtouched = 0; X509_VERIFY_PARAM *vpm = NULL; int token_in = 0; int token_out = 0; if ((vpm = X509_VERIFY_PARAM_new()) == NULL) goto end; opt_set_unknown_name("digest"); prog = opt_init(argc, argv, ts_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(ts_options); for (helpp = opt_helplist; *helpp; ++helpp) BIO_printf(bio_err, "%s\n", *helpp); ret = 0; goto end; case OPT_CONFIG: configfile = opt_arg(); break; case OPT_SECTION: section = opt_arg(); break; case OPT_QUERY: case OPT_REPLY: case OPT_VERIFY: if (mode != OPT_ERR) { BIO_printf(bio_err, "%s: Must give only one of -query, -reply, or -verify\n", prog); goto opthelp; } mode = o; break; case OPT_DATA: data = opt_arg(); break; case OPT_DIGEST: digest = opt_arg(); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_TSPOLICY: policy = opt_arg(); break; case OPT_NO_NONCE: no_nonce = 1; break; case OPT_CERT: cert = 1; break; case OPT_IN: in = opt_arg(); break; case OPT_TOKEN_IN: token_in = 1; break; case OPT_OUT: out = opt_arg(); break; case OPT_TOKEN_OUT: token_out = 1; break; case OPT_TEXT: text = 1; break; case OPT_QUERYFILE: queryfile = opt_arg(); break; case OPT_PASSIN: passin = opt_arg(); break; case OPT_INKEY: inkey = opt_arg(); break; case OPT_SIGNER: signer = opt_arg(); break; case OPT_CHAIN: chain = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_UNTRUSTED: untrusted = opt_arg(); break; case OPT_ENGINE: engine = opt_arg(); break; case OPT_MD: digestname = opt_unknown(); break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (mode == OPT_ERR) { BIO_printf(bio_err, "%s: Must give one of -query, -reply, or -verify\n", prog); goto opthelp; } if (!app_RAND_load()) goto end; if (!opt_md(digestname, &md)) goto opthelp; if (mode == OPT_REPLY && passin && !app_passwd(passin, NULL, &password, NULL)) { BIO_printf(bio_err, "Error getting password.\n"); goto end; } if ((conf = load_config_file(configfile)) == NULL) goto end; if (configfile != default_config_file && !app_load_modules(conf)) goto end; if (mode == OPT_QUERY) { if (vpmtouched) goto opthelp; if ((data != NULL) && (digest != NULL)) goto opthelp; ret = !query_command(data, digest, md, policy, no_nonce, cert, in, out, text); } else if (mode == OPT_REPLY) { if (vpmtouched) goto opthelp; if ((in != NULL) && (queryfile != NULL)) goto opthelp; if (in == NULL) { if ((conf == NULL) || (token_in != 0)) goto opthelp; } ret = !reply_command(conf, section, engine, queryfile, password, inkey, md, signer, chain, policy, in, token_in, out, token_out, text); } else if (mode == OPT_VERIFY) { if ((in == NULL) || !EXACTLY_ONE(queryfile, data, digest)) goto opthelp; ret = !verify_command(data, digest, queryfile, in, token_in, CApath, CAfile, CAstore, untrusted, vpmtouched ? vpm : NULL); } else { goto opthelp; } end: X509_VERIFY_PARAM_free(vpm); EVP_MD_free(md); NCONF_free(conf); OPENSSL_free(password); return ret; } static ASN1_OBJECT *txt2obj(const char *oid) { ASN1_OBJECT *oid_obj = NULL; if ((oid_obj = OBJ_txt2obj(oid, 0)) == NULL) BIO_printf(bio_err, "cannot convert %s to OID\n", oid); return oid_obj; } static CONF *load_config_file(const char *configfile) { CONF *conf = app_load_config(configfile); if (conf != NULL) { const char *p; BIO_printf(bio_err, "Using configuration from %s\n", configfile); p = app_conf_try_string(conf, NULL, ENV_OID_FILE); if (p != NULL) { BIO *oid_bio = BIO_new_file(p, "r"); if (!oid_bio) ERR_print_errors(bio_err); else { OBJ_create_objects(oid_bio); BIO_free_all(oid_bio); } } if (!add_oid_section(conf)) ERR_print_errors(bio_err); } return conf; } static int query_command(const char *data, const char *digest, const EVP_MD *md, const char *policy, int no_nonce, int cert, const char *in, const char *out, int text) { int ret = 0; TS_REQ *query = NULL; BIO *in_bio = NULL; BIO *data_bio = NULL; BIO *out_bio = NULL; if (in != NULL) { if ((in_bio = bio_open_default(in, 'r', FORMAT_ASN1)) == NULL) goto end; query = d2i_TS_REQ_bio(in_bio, NULL); } else { if (digest == NULL && (data_bio = bio_open_default(data, 'r', FORMAT_ASN1)) == NULL) goto end; query = create_query(data_bio, digest, md, policy, no_nonce, cert); } if (query == NULL) goto end; if (text) { if ((out_bio = bio_open_default(out, 'w', FORMAT_TEXT)) == NULL) goto end; if (!TS_REQ_print_bio(out_bio, query)) goto end; } else { if ((out_bio = bio_open_default(out, 'w', FORMAT_ASN1)) == NULL) goto end; if (!i2d_TS_REQ_bio(out_bio, query)) goto end; } ret = 1; end: ERR_print_errors(bio_err); BIO_free_all(in_bio); BIO_free_all(data_bio); BIO_free_all(out_bio); TS_REQ_free(query); return ret; } static TS_REQ *create_query(BIO *data_bio, const char *digest, const EVP_MD *md, const char *policy, int no_nonce, int cert) { int ret = 0; TS_REQ *ts_req = NULL; int len; TS_MSG_IMPRINT *msg_imprint = NULL; X509_ALGOR *algo = NULL; unsigned char *data = NULL; ASN1_OBJECT *policy_obj = NULL; ASN1_INTEGER *nonce_asn1 = NULL; if (md == NULL && (md = EVP_get_digestbyname("sha256")) == NULL) goto err; if ((ts_req = TS_REQ_new()) == NULL) goto err; if (!TS_REQ_set_version(ts_req, 1)) goto err; if ((msg_imprint = TS_MSG_IMPRINT_new()) == NULL) goto err; if ((algo = X509_ALGOR_new()) == NULL) goto err; if ((algo->algorithm = OBJ_nid2obj(EVP_MD_get_type(md))) == NULL) goto err; if ((algo->parameter = ASN1_TYPE_new()) == NULL) goto err; algo->parameter->type = V_ASN1_NULL; if (!TS_MSG_IMPRINT_set_algo(msg_imprint, algo)) goto err; if ((len = create_digest(data_bio, digest, md, &data)) == 0) goto err; if (!TS_MSG_IMPRINT_set_msg(msg_imprint, data, len)) goto err; if (!TS_REQ_set_msg_imprint(ts_req, msg_imprint)) goto err; if (policy && (policy_obj = txt2obj(policy)) == NULL) goto err; if (policy_obj && !TS_REQ_set_policy_id(ts_req, policy_obj)) goto err; if (!no_nonce && (nonce_asn1 = create_nonce(NONCE_LENGTH)) == NULL) goto err; if (nonce_asn1 && !TS_REQ_set_nonce(ts_req, nonce_asn1)) goto err; if (!TS_REQ_set_cert_req(ts_req, cert)) goto err; ret = 1; err: if (!ret) { TS_REQ_free(ts_req); ts_req = NULL; BIO_printf(bio_err, "could not create query\n"); ERR_print_errors(bio_err); } TS_MSG_IMPRINT_free(msg_imprint); X509_ALGOR_free(algo); OPENSSL_free(data); ASN1_OBJECT_free(policy_obj); ASN1_INTEGER_free(nonce_asn1); return ts_req; } static int create_digest(BIO *input, const char *digest, const EVP_MD *md, unsigned char **md_value) { int md_value_len; int rv = 0; EVP_MD_CTX *md_ctx = NULL; md_value_len = EVP_MD_get_size(md); if (md_value_len < 0) return 0; if (input != NULL) { unsigned char buffer[4096]; int length; md_ctx = EVP_MD_CTX_new(); if (md_ctx == NULL) return 0; *md_value = app_malloc(md_value_len, "digest buffer"); if (!EVP_DigestInit(md_ctx, md)) goto err; while ((length = BIO_read(input, buffer, sizeof(buffer))) > 0) { if (!EVP_DigestUpdate(md_ctx, buffer, length)) goto err; } if (!EVP_DigestFinal(md_ctx, *md_value, NULL)) goto err; md_value_len = EVP_MD_get_size(md); } else { long digest_len; *md_value = OPENSSL_hexstr2buf(digest, &digest_len); if (*md_value == NULL || md_value_len != digest_len) { OPENSSL_free(*md_value); *md_value = NULL; BIO_printf(bio_err, "bad digest, %d bytes " "must be specified\n", md_value_len); return 0; } } rv = md_value_len; err: EVP_MD_CTX_free(md_ctx); return rv; } static ASN1_INTEGER *create_nonce(int bits) { unsigned char buf[20]; ASN1_INTEGER *nonce = NULL; int len = (bits - 1) / 8 + 1; int i; if (len > (int)sizeof(buf)) goto err; if (RAND_bytes(buf, len) <= 0) goto err; for (i = 0; i < len && !buf[i]; ++i) continue; if ((nonce = ASN1_INTEGER_new()) == NULL) goto err; OPENSSL_free(nonce->data); nonce->length = len - i; nonce->data = app_malloc(nonce->length + 1, "nonce buffer"); memcpy(nonce->data, buf + i, nonce->length); return nonce; err: BIO_printf(bio_err, "could not create nonce\n"); ASN1_INTEGER_free(nonce); return NULL; } static int reply_command(CONF *conf, const char *section, const char *engine, const char *queryfile, const char *passin, const char *inkey, const EVP_MD *md, const char *signer, const char *chain, const char *policy, const char *in, int token_in, const 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; if (in != NULL) { if ((in_bio = BIO_new_file(in, "rb")) == NULL) goto end; if (token_in) { response = read_PKCS7(in_bio); } else { response = d2i_TS_RESP_bio(in_bio, NULL); } } else { response = create_response(conf, section, engine, queryfile, passin, inkey, md, signer, chain, policy); if (response != NULL) BIO_printf(bio_err, "Response has been generated.\n"); else BIO_printf(bio_err, "Response is not generated.\n"); } if (response == NULL) goto end; if (text) { if ((out_bio = bio_open_default(out, 'w', FORMAT_TEXT)) == NULL) goto end; 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 { if ((out_bio = bio_open_default(out, 'w', FORMAT_ASN1)) == NULL) goto end; 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); 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; } static TS_RESP *read_PKCS7(BIO *in_bio) { int ret = 0; PKCS7 *token = NULL; TS_TST_INFO *tst_info = NULL; TS_RESP *resp = NULL; TS_STATUS_INFO *si = NULL; if ((token = d2i_PKCS7_bio(in_bio, NULL)) == NULL) goto end; if ((tst_info = PKCS7_to_TS_TST_INFO(token)) == NULL) goto end; if ((resp = TS_RESP_new()) == NULL) goto end; if ((si = TS_STATUS_INFO_new()) == NULL) goto end; if (!TS_STATUS_INFO_set_status(si, TS_STATUS_GRANTED)) goto end; if (!TS_RESP_set_status_info(resp, si)) goto end; TS_RESP_set_tst_info(resp, token, tst_info); token = NULL; tst_info = NULL; ret = 1; end: PKCS7_free(token); TS_TST_INFO_free(tst_info); if (!ret) { TS_RESP_free(resp); resp = NULL; } TS_STATUS_INFO_free(si); return resp; } static TS_RESP *create_response(CONF *conf, const char *section, const char *engine, const char *queryfile, const char *passin, const char *inkey, const EVP_MD *md, const char *signer, const char *chain, const char *policy) { int ret = 0; TS_RESP *response = NULL; BIO *query_bio = NULL; TS_RESP_CTX *resp_ctx = NULL; if ((query_bio = BIO_new_file(queryfile, "rb")) == NULL) goto end; if ((section = TS_CONF_get_tsa_section(conf, section)) == NULL) goto end; if ((resp_ctx = TS_RESP_CTX_new()) == NULL) goto end; if (!TS_CONF_set_serial(conf, section, serial_cb, resp_ctx)) goto end; #ifndef OPENSSL_NO_ENGINE if (!TS_CONF_set_crypto_device(conf, section, engine)) goto end; #endif if (!TS_CONF_set_signer_cert(conf, section, signer, resp_ctx)) goto end; if (!TS_CONF_set_certs(conf, section, chain, resp_ctx)) goto end; if (!TS_CONF_set_signer_key(conf, section, inkey, passin, resp_ctx)) goto end; if (md) { if (!TS_RESP_CTX_set_signer_digest(resp_ctx, md)) goto end; } else if (!TS_CONF_set_signer_digest(conf, section, NULL, resp_ctx)) { goto end; } if (!TS_CONF_set_ess_cert_id_digest(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_def_policy(conf, section, policy, resp_ctx)) goto end; if (!TS_CONF_set_policies(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_digests(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_accuracy(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_clock_precision_digits(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_ordering(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_tsa_name(conf, section, resp_ctx)) goto end; if (!TS_CONF_set_ess_cert_id_chain(conf, section, resp_ctx)) goto end; if ((response = TS_RESP_create_response(resp_ctx, query_bio)) == NULL) goto end; ret = 1; end: if (!ret) { TS_RESP_free(response); response = NULL; } TS_RESP_CTX_free(resp_ctx); BIO_free_all(query_bio); return response; } static ASN1_INTEGER *serial_cb(TS_RESP_CTX *ctx, void *data) { const char *serial_file = (const char *)data; ASN1_INTEGER *serial = next_serial(serial_file); if (serial == NULL) { TS_RESP_CTX_set_status_info(ctx, TS_STATUS_REJECTION, "Error during serial number " "generation."); TS_RESP_CTX_add_failure_info(ctx, TS_INFO_ADD_INFO_NOT_AVAILABLE); } else { save_ts_serial(serial_file, serial); } return serial; } static ASN1_INTEGER *next_serial(const char *serialfile) { int ret = 0; BIO *in = NULL; ASN1_INTEGER *serial = NULL; BIGNUM *bn = NULL; if ((serial = ASN1_INTEGER_new()) == NULL) goto err; if ((in = BIO_new_file(serialfile, "r")) == NULL) { ERR_clear_error(); BIO_printf(bio_err, "Warning: could not open file %s for " "reading, using serial number: 1\n", serialfile); if (!ASN1_INTEGER_set(serial, 1)) goto err; } else { char buf[1024]; if (!a2i_ASN1_INTEGER(in, serial, buf, sizeof(buf))) { BIO_printf(bio_err, "unable to load number from %s\n", serialfile); goto err; } if ((bn = ASN1_INTEGER_to_BN(serial, NULL)) == NULL) goto err; ASN1_INTEGER_free(serial); serial = NULL; if (!BN_add_word(bn, 1)) goto err; if ((serial = BN_to_ASN1_INTEGER(bn, NULL)) == NULL) goto err; } ret = 1; err: if (!ret) { ASN1_INTEGER_free(serial); serial = NULL; } BIO_free_all(in); BN_free(bn); return serial; } static int save_ts_serial(const char *serialfile, ASN1_INTEGER *serial) { int ret = 0; BIO *out = NULL; if ((out = BIO_new_file(serialfile, "w")) == NULL) goto err; if (i2a_ASN1_INTEGER(out, serial) <= 0) goto err; if (BIO_puts(out, "\n") <= 0) goto err; ret = 1; err: if (!ret) BIO_printf(bio_err, "could not save serial number to %s\n", serialfile); BIO_free_all(out); return ret; } static int verify_command(const char *data, const char *digest, const char *queryfile, const char *in, int token_in, const char *CApath, const char *CAfile, const char *CAstore, char *untrusted, X509_VERIFY_PARAM *vpm) { BIO *in_bio = NULL; PKCS7 *token = NULL; TS_RESP *response = NULL; TS_VERIFY_CTX *verify_ctx = NULL; int ret = 0; if ((in_bio = BIO_new_file(in, "rb")) == NULL) goto end; if (token_in) { if ((token = d2i_PKCS7_bio(in_bio, NULL)) == NULL) goto end; } else { if ((response = d2i_TS_RESP_bio(in_bio, NULL)) == NULL) goto end; } if ((verify_ctx = create_verify_ctx(data, digest, queryfile, CApath, CAfile, CAstore, untrusted, vpm)) == NULL) goto end; ret = token_in ? TS_RESP_verify_token(verify_ctx, token) : TS_RESP_verify_response(verify_ctx, response); end: printf("Verification: "); if (ret) printf("OK\n"); else { printf("FAILED\n"); ERR_print_errors(bio_err); } BIO_free_all(in_bio); PKCS7_free(token); TS_RESP_free(response); TS_VERIFY_CTX_free(verify_ctx); return ret; } static TS_VERIFY_CTX *create_verify_ctx(const char *data, const char *digest, const char *queryfile, const char *CApath, const char *CAfile, const char *CAstore, char *untrusted, X509_VERIFY_PARAM *vpm) { TS_VERIFY_CTX *ctx = NULL; STACK_OF(X509) *certs; BIO *input = NULL; TS_REQ *request = NULL; int ret = 0; int f = 0; if (data != NULL || digest != NULL) { if ((ctx = TS_VERIFY_CTX_new()) == NULL) goto err; f = TS_VFY_VERSION | TS_VFY_SIGNER; if (data != NULL) { BIO *out = NULL; f |= TS_VFY_DATA; if ((out = BIO_new_file(data, "rb")) == NULL) goto err; if (TS_VERIFY_CTX_set_data(ctx, out) == NULL) { BIO_free_all(out); goto err; } } else if (digest != NULL) { long imprint_len; unsigned char *hexstr = OPENSSL_hexstr2buf(digest, &imprint_len); f |= TS_VFY_IMPRINT; if (TS_VERIFY_CTX_set_imprint(ctx, hexstr, imprint_len) == NULL) { BIO_printf(bio_err, "invalid digest string\n"); goto err; } } } else if (queryfile != NULL) { if ((input = BIO_new_file(queryfile, "rb")) == NULL) goto err; if ((request = d2i_TS_REQ_bio(input, NULL)) == NULL) goto err; if ((ctx = TS_REQ_to_TS_VERIFY_CTX(request, NULL)) == NULL) goto err; } else { return NULL; } TS_VERIFY_CTX_add_flags(ctx, f | TS_VFY_SIGNATURE); if (TS_VERIFY_CTX_set_store(ctx, create_cert_store(CApath, CAfile, CAstore, vpm)) == NULL) goto err; if (untrusted != NULL) { certs = load_certs_multifile(untrusted, NULL, "extra untrusted certs", vpm); if (certs == NULL || TS_VERIFY_CTX_set_certs(ctx, certs) == NULL) goto err; } ret = 1; err: if (!ret) { TS_VERIFY_CTX_free(ctx); ctx = NULL; } BIO_free_all(input); TS_REQ_free(request); return ctx; } static X509_STORE *create_cert_store(const char *CApath, const char *CAfile, const char *CAstore, X509_VERIFY_PARAM *vpm) { X509_STORE *cert_ctx = NULL; X509_LOOKUP *lookup = NULL; OSSL_LIB_CTX *libctx = app_get0_libctx(); const char *propq = app_get0_propq(); cert_ctx = X509_STORE_new(); if (cert_ctx == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); return NULL; } X509_STORE_set_verify_cb(cert_ctx, verify_cb); if (CApath != NULL) { lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_hash_dir()); if (lookup == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); goto err; } if (X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM) <= 0) { BIO_printf(bio_err, "Error loading directory %s\n", CApath); goto err; } } if (CAfile != NULL) { lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_file()); if (lookup == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); goto err; } if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM, libctx, propq) <= 0) { BIO_printf(bio_err, "Error loading file %s\n", CAfile); goto err; } } if (CAstore != NULL) { lookup = X509_STORE_add_lookup(cert_ctx, X509_LOOKUP_store()); if (lookup == NULL) { BIO_printf(bio_err, "memory allocation failure\n"); goto err; } if (X509_LOOKUP_load_store_ex(lookup, CAstore, libctx, propq) <= 0) { BIO_printf(bio_err, "Error loading store URI %s\n", CAstore); goto err; } } if (vpm != NULL) X509_STORE_set1_param(cert_ctx, vpm); return cert_ctx; err: X509_STORE_free(cert_ctx); return NULL; } static int verify_cb(int ok, X509_STORE_CTX *ctx) { return ok; }
apps
openssl/apps/ts.c
openssl
#define OPENSSL_SUPPRESS_DEPRECATED #include <string.h> #include <openssl/evp.h> #include <openssl/err.h> #include <openssl/provider.h> #include <openssl/safestack.h> #include <openssl/kdf.h> #include <openssl/encoder.h> #include <openssl/decoder.h> #include <openssl/store.h> #include <openssl/core_names.h> #include <openssl/rand.h> #include "apps.h" #include "app_params.h" #include "progs.h" #include "opt.h" #include "names.h" static int verbose = 0; static const char *select_name = NULL; #define IS_FETCHABLE(type, TYPE) \ static int is_ ## type ## _fetchable(const TYPE *alg) \ { \ TYPE *impl; \ const char *propq = app_get0_propq(); \ OSSL_LIB_CTX *libctx = app_get0_libctx(); \ const char *name = TYPE ## _get0_name(alg); \ \ ERR_set_mark(); \ impl = TYPE ## _fetch(libctx, name, propq); \ ERR_pop_to_mark(); \ if (impl == NULL) \ return 0; \ TYPE ## _free(impl); \ return 1; \ } IS_FETCHABLE(cipher, EVP_CIPHER) IS_FETCHABLE(digest, EVP_MD) IS_FETCHABLE(mac, EVP_MAC) IS_FETCHABLE(kdf, EVP_KDF) IS_FETCHABLE(rand, EVP_RAND) IS_FETCHABLE(keymgmt, EVP_KEYMGMT) IS_FETCHABLE(signature, EVP_SIGNATURE) IS_FETCHABLE(kem, EVP_KEM) IS_FETCHABLE(asym_cipher, EVP_ASYM_CIPHER) IS_FETCHABLE(keyexch, EVP_KEYEXCH) IS_FETCHABLE(decoder, OSSL_DECODER) IS_FETCHABLE(encoder, OSSL_ENCODER) #ifndef OPENSSL_NO_DEPRECATED_3_0 static int include_legacy(void) { return app_get0_propq() == NULL; } static void legacy_cipher_fn(const EVP_CIPHER *c, const char *from, const char *to, void *arg) { if (select_name != NULL && (c == NULL || OPENSSL_strcasecmp(select_name, EVP_CIPHER_get0_name(c)) != 0)) return; if (c != NULL) { BIO_printf(arg, " %s\n", EVP_CIPHER_get0_name(c)); } else { if (from == NULL) from = "<undefined>"; if (to == NULL) to = "<undefined>"; BIO_printf(arg, " %s => %s\n", from, to); } } #endif DEFINE_STACK_OF(EVP_CIPHER) static int cipher_cmp(const EVP_CIPHER * const *a, const EVP_CIPHER * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_CIPHER_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_CIPHER_get0_provider(*b))); } static void collect_ciphers(EVP_CIPHER *cipher, void *stack) { STACK_OF(EVP_CIPHER) *cipher_stack = stack; if (is_cipher_fetchable(cipher) && sk_EVP_CIPHER_push(cipher_stack, cipher) > 0) EVP_CIPHER_up_ref(cipher); } static void list_ciphers(const char *prefix) { STACK_OF(EVP_CIPHER) *ciphers = sk_EVP_CIPHER_new(cipher_cmp); int i; if (ciphers == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } #ifndef OPENSSL_NO_DEPRECATED_3_0 if (include_legacy()) { BIO_printf(bio_out, "%sLegacy:\n", prefix); EVP_CIPHER_do_all_sorted(legacy_cipher_fn, bio_out); } #endif BIO_printf(bio_out, "%sProvided:\n", prefix); EVP_CIPHER_do_all_provided(app_get0_libctx(), collect_ciphers, ciphers); sk_EVP_CIPHER_sort(ciphers); for (i = 0; i < sk_EVP_CIPHER_num(ciphers); i++) { const EVP_CIPHER *c = sk_EVP_CIPHER_value(ciphers, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_CIPHER_is_a(c, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_CIPHER_names_do_all(c, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_CIPHER_get0_provider(c))); if (verbose) { const char *desc = EVP_CIPHER_get0_description(c); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("retrievable algorithm parameters", EVP_CIPHER_gettable_params(c), 4); print_param_types("retrievable operation parameters", EVP_CIPHER_gettable_ctx_params(c), 4); print_param_types("settable operation parameters", EVP_CIPHER_settable_ctx_params(c), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_CIPHER_pop_free(ciphers, EVP_CIPHER_free); } #ifndef OPENSSL_NO_DEPRECATED_3_0 static void legacy_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg) { if (m != NULL) { BIO_printf(arg, " %s\n", EVP_MD_get0_name(m)); } else { if (from == NULL) from = "<undefined>"; if (to == NULL) to = "<undefined>"; BIO_printf((BIO *)arg, " %s => %s\n", from, to); } } #endif DEFINE_STACK_OF(EVP_MD) static int md_cmp(const EVP_MD * const *a, const EVP_MD * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_MD_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_MD_get0_provider(*b))); } static void collect_digests(EVP_MD *digest, void *stack) { STACK_OF(EVP_MD) *digest_stack = stack; if (is_digest_fetchable(digest) && sk_EVP_MD_push(digest_stack, digest) > 0) EVP_MD_up_ref(digest); } static void list_digests(const char *prefix) { STACK_OF(EVP_MD) *digests = sk_EVP_MD_new(md_cmp); int i; if (digests == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } #ifndef OPENSSL_NO_DEPRECATED_3_0 if (include_legacy()) { BIO_printf(bio_out, "%sLegacy:\n", prefix); EVP_MD_do_all_sorted(legacy_md_fn, bio_out); } #endif BIO_printf(bio_out, "%sProvided:\n", prefix); EVP_MD_do_all_provided(app_get0_libctx(), collect_digests, digests); sk_EVP_MD_sort(digests); for (i = 0; i < sk_EVP_MD_num(digests); i++) { const EVP_MD *m = sk_EVP_MD_value(digests, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_MD_is_a(m, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_MD_names_do_all(m, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_MD_get0_provider(m))); if (verbose) { const char *desc = EVP_MD_get0_description(m); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("retrievable algorithm parameters", EVP_MD_gettable_params(m), 4); print_param_types("retrievable operation parameters", EVP_MD_gettable_ctx_params(m), 4); print_param_types("settable operation parameters", EVP_MD_settable_ctx_params(m), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_MD_pop_free(digests, EVP_MD_free); } DEFINE_STACK_OF(EVP_MAC) static int mac_cmp(const EVP_MAC * const *a, const EVP_MAC * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_MAC_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_MAC_get0_provider(*b))); } static void collect_macs(EVP_MAC *mac, void *stack) { STACK_OF(EVP_MAC) *mac_stack = stack; if (is_mac_fetchable(mac) && sk_EVP_MAC_push(mac_stack, mac) > 0) EVP_MAC_up_ref(mac); } static void list_macs(void) { STACK_OF(EVP_MAC) *macs = sk_EVP_MAC_new(mac_cmp); int i; if (macs == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Provided MACs:\n"); EVP_MAC_do_all_provided(app_get0_libctx(), collect_macs, macs); sk_EVP_MAC_sort(macs); for (i = 0; i < sk_EVP_MAC_num(macs); i++) { const EVP_MAC *m = sk_EVP_MAC_value(macs, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_MAC_is_a(m, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_MAC_names_do_all(m, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_MAC_get0_provider(m))); if (verbose) { const char *desc = EVP_MAC_get0_description(m); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("retrievable algorithm parameters", EVP_MAC_gettable_params(m), 4); print_param_types("retrievable operation parameters", EVP_MAC_gettable_ctx_params(m), 4); print_param_types("settable operation parameters", EVP_MAC_settable_ctx_params(m), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_MAC_pop_free(macs, EVP_MAC_free); } DEFINE_STACK_OF(EVP_KDF) static int kdf_cmp(const EVP_KDF * const *a, const EVP_KDF * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_KDF_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_KDF_get0_provider(*b))); } static void collect_kdfs(EVP_KDF *kdf, void *stack) { STACK_OF(EVP_KDF) *kdf_stack = stack; if (is_kdf_fetchable(kdf) && sk_EVP_KDF_push(kdf_stack, kdf) > 0) EVP_KDF_up_ref(kdf); } static void list_kdfs(void) { STACK_OF(EVP_KDF) *kdfs = sk_EVP_KDF_new(kdf_cmp); int i; if (kdfs == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Provided KDFs and PDFs:\n"); EVP_KDF_do_all_provided(app_get0_libctx(), collect_kdfs, kdfs); sk_EVP_KDF_sort(kdfs); for (i = 0; i < sk_EVP_KDF_num(kdfs); i++) { const EVP_KDF *k = sk_EVP_KDF_value(kdfs, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_KDF_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_KDF_names_do_all(k, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_KDF_get0_provider(k))); if (verbose) { const char *desc = EVP_KDF_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("retrievable algorithm parameters", EVP_KDF_gettable_params(k), 4); print_param_types("retrievable operation parameters", EVP_KDF_gettable_ctx_params(k), 4); print_param_types("settable operation parameters", EVP_KDF_settable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_KDF_pop_free(kdfs, EVP_KDF_free); } DEFINE_STACK_OF(EVP_RAND) static int rand_cmp(const EVP_RAND * const *a, const EVP_RAND * const *b) { int ret = OPENSSL_strcasecmp(EVP_RAND_get0_name(*a), EVP_RAND_get0_name(*b)); if (ret == 0) ret = strcmp(OSSL_PROVIDER_get0_name(EVP_RAND_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_RAND_get0_provider(*b))); return ret; } static void collect_rands(EVP_RAND *rand, void *stack) { STACK_OF(EVP_RAND) *rand_stack = stack; if (is_rand_fetchable(rand) && sk_EVP_RAND_push(rand_stack, rand) > 0) EVP_RAND_up_ref(rand); } static void list_random_generators(void) { STACK_OF(EVP_RAND) *rands = sk_EVP_RAND_new(rand_cmp); int i; if (rands == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Provided RNGs and seed sources:\n"); EVP_RAND_do_all_provided(app_get0_libctx(), collect_rands, rands); sk_EVP_RAND_sort(rands); for (i = 0; i < sk_EVP_RAND_num(rands); i++) { const EVP_RAND *m = sk_EVP_RAND_value(rands, i); if (select_name != NULL && OPENSSL_strcasecmp(EVP_RAND_get0_name(m), select_name) != 0) continue; BIO_printf(bio_out, " %s", EVP_RAND_get0_name(m)); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_RAND_get0_provider(m))); if (verbose) { const char *desc = EVP_RAND_get0_description(m); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("retrievable algorithm parameters", EVP_RAND_gettable_params(m), 4); print_param_types("retrievable operation parameters", EVP_RAND_gettable_ctx_params(m), 4); print_param_types("settable operation parameters", EVP_RAND_settable_ctx_params(m), 4); } } sk_EVP_RAND_pop_free(rands, EVP_RAND_free); } static void display_random(const char *name, EVP_RAND_CTX *drbg) { EVP_RAND *rand; uint64_t u; const char *p; const OSSL_PARAM *gettables; OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; unsigned char buf[1000]; BIO_printf(bio_out, "%s:\n", name); if (drbg != NULL) { rand = EVP_RAND_CTX_get0_rand(drbg); BIO_printf(bio_out, " %s", EVP_RAND_get0_name(rand)); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_RAND_get0_provider(rand))); switch (EVP_RAND_get_state(drbg)) { case EVP_RAND_STATE_UNINITIALISED: p = "uninitialised"; break; case EVP_RAND_STATE_READY: p = "ready"; break; case EVP_RAND_STATE_ERROR: p = "error"; break; default: p = "unknown"; break; } BIO_printf(bio_out, " state = %s\n", p); gettables = EVP_RAND_gettable_ctx_params(rand); if (gettables != NULL) for (; gettables->key != NULL; gettables++) { if (OPENSSL_strcasecmp(gettables->key, OSSL_RAND_PARAM_STATE) == 0) continue; if (gettables->data_type != OSSL_PARAM_UTF8_STRING && gettables->data_type != OSSL_PARAM_UTF8_PTR && !verbose) continue; params->key = gettables->key; params->data_type = gettables->data_type; if (gettables->data_type == OSSL_PARAM_UNSIGNED_INTEGER || gettables->data_type == OSSL_PARAM_INTEGER) { params->data = &u; params->data_size = sizeof(u); } else { params->data = buf; params->data_size = sizeof(buf); } params->return_size = 0; if (EVP_RAND_CTX_get_params(drbg, params)) print_param_value(params, 2); } } } static void list_random_instances(void) { display_random("primary", RAND_get0_primary(NULL)); display_random("public", RAND_get0_public(NULL)); display_random("private", RAND_get0_private(NULL)); } DEFINE_STACK_OF(OSSL_ENCODER) static int encoder_cmp(const OSSL_ENCODER * const *a, const OSSL_ENCODER * const *b) { return strcmp(OSSL_PROVIDER_get0_name(OSSL_ENCODER_get0_provider(*a)), OSSL_PROVIDER_get0_name(OSSL_ENCODER_get0_provider(*b))); } static void collect_encoders(OSSL_ENCODER *encoder, void *stack) { STACK_OF(OSSL_ENCODER) *encoder_stack = stack; if (is_encoder_fetchable(encoder) && sk_OSSL_ENCODER_push(encoder_stack, encoder) > 0) OSSL_ENCODER_up_ref(encoder); } static void list_encoders(void) { STACK_OF(OSSL_ENCODER) *encoders; int i; encoders = sk_OSSL_ENCODER_new(encoder_cmp); if (encoders == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Provided ENCODERs:\n"); OSSL_ENCODER_do_all_provided(app_get0_libctx(), collect_encoders, encoders); sk_OSSL_ENCODER_sort(encoders); for (i = 0; i < sk_OSSL_ENCODER_num(encoders); i++) { OSSL_ENCODER *k = sk_OSSL_ENCODER_value(encoders, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !OSSL_ENCODER_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && OSSL_ENCODER_names_do_all(k, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s (%s)\n", OSSL_PROVIDER_get0_name(OSSL_ENCODER_get0_provider(k)), OSSL_ENCODER_get0_properties(k)); if (verbose) { const char *desc = OSSL_ENCODER_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("settable operation parameters", OSSL_ENCODER_settable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_OSSL_ENCODER_pop_free(encoders, OSSL_ENCODER_free); } DEFINE_STACK_OF(OSSL_DECODER) static int decoder_cmp(const OSSL_DECODER * const *a, const OSSL_DECODER * const *b) { return strcmp(OSSL_PROVIDER_get0_name(OSSL_DECODER_get0_provider(*a)), OSSL_PROVIDER_get0_name(OSSL_DECODER_get0_provider(*b))); } static void collect_decoders(OSSL_DECODER *decoder, void *stack) { STACK_OF(OSSL_DECODER) *decoder_stack = stack; if (is_decoder_fetchable(decoder) && sk_OSSL_DECODER_push(decoder_stack, decoder) > 0) OSSL_DECODER_up_ref(decoder); } static void list_decoders(void) { STACK_OF(OSSL_DECODER) *decoders; int i; decoders = sk_OSSL_DECODER_new(decoder_cmp); if (decoders == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Provided DECODERs:\n"); OSSL_DECODER_do_all_provided(app_get0_libctx(), collect_decoders, decoders); sk_OSSL_DECODER_sort(decoders); for (i = 0; i < sk_OSSL_DECODER_num(decoders); i++) { OSSL_DECODER *k = sk_OSSL_DECODER_value(decoders, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !OSSL_DECODER_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && OSSL_DECODER_names_do_all(k, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s (%s)\n", OSSL_PROVIDER_get0_name(OSSL_DECODER_get0_provider(k)), OSSL_DECODER_get0_properties(k)); if (verbose) { const char *desc = OSSL_DECODER_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("settable operation parameters", OSSL_DECODER_settable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_OSSL_DECODER_pop_free(decoders, OSSL_DECODER_free); } DEFINE_STACK_OF(EVP_KEYMGMT) static int keymanager_cmp(const EVP_KEYMGMT * const *a, const EVP_KEYMGMT * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_KEYMGMT_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_KEYMGMT_get0_provider(*b))); } static void collect_keymanagers(EVP_KEYMGMT *km, void *stack) { STACK_OF(EVP_KEYMGMT) *km_stack = stack; if (is_keymgmt_fetchable(km) && sk_EVP_KEYMGMT_push(km_stack, km) > 0) EVP_KEYMGMT_up_ref(km); } static void list_keymanagers(void) { int i; STACK_OF(EVP_KEYMGMT) *km_stack = sk_EVP_KEYMGMT_new(keymanager_cmp); EVP_KEYMGMT_do_all_provided(app_get0_libctx(), collect_keymanagers, km_stack); sk_EVP_KEYMGMT_sort(km_stack); for (i = 0; i < sk_EVP_KEYMGMT_num(km_stack); i++) { EVP_KEYMGMT *k = sk_EVP_KEYMGMT_value(km_stack, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_KEYMGMT_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_KEYMGMT_names_do_all(k, collect_names, names)) { const char *desc = EVP_KEYMGMT_get0_description(k); BIO_printf(bio_out, " Name: "); if (desc != NULL) BIO_printf(bio_out, "%s", desc); else BIO_printf(bio_out, "%s", sk_OPENSSL_CSTRING_value(names, 0)); BIO_printf(bio_out, "\n"); BIO_printf(bio_out, " Type: Provider Algorithm\n"); BIO_printf(bio_out, " IDs: "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_KEYMGMT_get0_provider(k))); if (verbose) { print_param_types("settable key generation parameters", EVP_KEYMGMT_gen_settable_params(k), 4); print_param_types("settable operation parameters", EVP_KEYMGMT_settable_params(k), 4); print_param_types("retrievable operation parameters", EVP_KEYMGMT_gettable_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_KEYMGMT_pop_free(km_stack, EVP_KEYMGMT_free); } DEFINE_STACK_OF(EVP_SIGNATURE) static int signature_cmp(const EVP_SIGNATURE * const *a, const EVP_SIGNATURE * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(*b))); } static void collect_signatures(EVP_SIGNATURE *sig, void *stack) { STACK_OF(EVP_SIGNATURE) *sig_stack = stack; if (is_signature_fetchable(sig) && sk_EVP_SIGNATURE_push(sig_stack, sig) > 0) EVP_SIGNATURE_up_ref(sig); } static void list_signatures(void) { int i, count = 0; STACK_OF(EVP_SIGNATURE) *sig_stack = sk_EVP_SIGNATURE_new(signature_cmp); EVP_SIGNATURE_do_all_provided(app_get0_libctx(), collect_signatures, sig_stack); sk_EVP_SIGNATURE_sort(sig_stack); for (i = 0; i < sk_EVP_SIGNATURE_num(sig_stack); i++) { EVP_SIGNATURE *k = sk_EVP_SIGNATURE_value(sig_stack, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_SIGNATURE_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_SIGNATURE_names_do_all(k, collect_names, names)) { count++; BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(k))); if (verbose) { const char *desc = EVP_SIGNATURE_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("settable operation parameters", EVP_SIGNATURE_settable_ctx_params(k), 4); print_param_types("retrievable operation parameters", EVP_SIGNATURE_gettable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_SIGNATURE_pop_free(sig_stack, EVP_SIGNATURE_free); if (count == 0) BIO_printf(bio_out, " -\n"); } DEFINE_STACK_OF(EVP_KEM) static int kem_cmp(const EVP_KEM * const *a, const EVP_KEM * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(*b))); } static void collect_kem(EVP_KEM *kem, void *stack) { STACK_OF(EVP_KEM) *kem_stack = stack; if (is_kem_fetchable(kem) && sk_EVP_KEM_push(kem_stack, kem) > 0) EVP_KEM_up_ref(kem); } static void list_kems(void) { int i, count = 0; STACK_OF(EVP_KEM) *kem_stack = sk_EVP_KEM_new(kem_cmp); EVP_KEM_do_all_provided(app_get0_libctx(), collect_kem, kem_stack); sk_EVP_KEM_sort(kem_stack); for (i = 0; i < sk_EVP_KEM_num(kem_stack); i++) { EVP_KEM *k = sk_EVP_KEM_value(kem_stack, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_KEM_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_KEM_names_do_all(k, collect_names, names)) { count++; BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(k))); if (verbose) { const char *desc = EVP_KEM_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("settable operation parameters", EVP_KEM_settable_ctx_params(k), 4); print_param_types("retrievable operation parameters", EVP_KEM_gettable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_KEM_pop_free(kem_stack, EVP_KEM_free); if (count == 0) BIO_printf(bio_out, " -\n"); } DEFINE_STACK_OF(EVP_ASYM_CIPHER) static int asymcipher_cmp(const EVP_ASYM_CIPHER * const *a, const EVP_ASYM_CIPHER * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_ASYM_CIPHER_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_ASYM_CIPHER_get0_provider(*b))); } static void collect_asymciph(EVP_ASYM_CIPHER *asym_cipher, void *stack) { STACK_OF(EVP_ASYM_CIPHER) *asym_cipher_stack = stack; if (is_asym_cipher_fetchable(asym_cipher) && sk_EVP_ASYM_CIPHER_push(asym_cipher_stack, asym_cipher) > 0) EVP_ASYM_CIPHER_up_ref(asym_cipher); } static void list_asymciphers(void) { int i, count = 0; STACK_OF(EVP_ASYM_CIPHER) *asymciph_stack = sk_EVP_ASYM_CIPHER_new(asymcipher_cmp); EVP_ASYM_CIPHER_do_all_provided(app_get0_libctx(), collect_asymciph, asymciph_stack); sk_EVP_ASYM_CIPHER_sort(asymciph_stack); for (i = 0; i < sk_EVP_ASYM_CIPHER_num(asymciph_stack); i++) { EVP_ASYM_CIPHER *k = sk_EVP_ASYM_CIPHER_value(asymciph_stack, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_ASYM_CIPHER_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_ASYM_CIPHER_names_do_all(k, collect_names, names)) { count++; BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_ASYM_CIPHER_get0_provider(k))); if (verbose) { const char *desc = EVP_ASYM_CIPHER_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("settable operation parameters", EVP_ASYM_CIPHER_settable_ctx_params(k), 4); print_param_types("retrievable operation parameters", EVP_ASYM_CIPHER_gettable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_ASYM_CIPHER_pop_free(asymciph_stack, EVP_ASYM_CIPHER_free); if (count == 0) BIO_printf(bio_out, " -\n"); } DEFINE_STACK_OF(EVP_KEYEXCH) static int kex_cmp(const EVP_KEYEXCH * const *a, const EVP_KEYEXCH * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_KEYEXCH_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_KEYEXCH_get0_provider(*b))); } static void collect_kex(EVP_KEYEXCH *kex, void *stack) { STACK_OF(EVP_KEYEXCH) *kex_stack = stack; if (is_keyexch_fetchable(kex) && sk_EVP_KEYEXCH_push(kex_stack, kex) > 0) EVP_KEYEXCH_up_ref(kex); } static void list_keyexchanges(void) { int i, count = 0; STACK_OF(EVP_KEYEXCH) *kex_stack = sk_EVP_KEYEXCH_new(kex_cmp); EVP_KEYEXCH_do_all_provided(app_get0_libctx(), collect_kex, kex_stack); sk_EVP_KEYEXCH_sort(kex_stack); for (i = 0; i < sk_EVP_KEYEXCH_num(kex_stack); i++) { EVP_KEYEXCH *k = sk_EVP_KEYEXCH_value(kex_stack, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !EVP_KEYEXCH_is_a(k, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && EVP_KEYEXCH_names_do_all(k, collect_names, names)) { count++; BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(EVP_KEYEXCH_get0_provider(k))); if (verbose) { const char *desc = EVP_KEYEXCH_get0_description(k); if (desc != NULL) BIO_printf(bio_out, " description: %s\n", desc); print_param_types("settable operation parameters", EVP_KEYEXCH_settable_ctx_params(k), 4); print_param_types("retrievable operation parameters", EVP_KEYEXCH_gettable_ctx_params(k), 4); } } sk_OPENSSL_CSTRING_free(names); } sk_EVP_KEYEXCH_pop_free(kex_stack, EVP_KEYEXCH_free); if (count == 0) BIO_printf(bio_out, " -\n"); } static void list_objects(void) { int max_nid = OBJ_new_nid(0); int i; char *oid_buf = NULL; int oid_size = 0; for (i = 1; i < max_nid; i++) { const ASN1_OBJECT *obj = OBJ_nid2obj(i); const char *sn = OBJ_nid2sn(i); const char *ln = OBJ_nid2ln(i); int n = 0; ERR_clear_error(); if (OBJ_obj2nid(obj) == NID_undef) continue; if ((n = OBJ_obj2txt(NULL, 0, obj, 1)) == 0) { BIO_printf(bio_out, "# None-OID object: %s, %s\n", sn, ln); continue; } if (n < 0) break; if (n > oid_size) { oid_buf = OPENSSL_realloc(oid_buf, n + 1); if (oid_buf == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); break; } oid_size = n + 1; } if (OBJ_obj2txt(oid_buf, oid_size, obj, 1) < 0) break; if (ln == NULL || strcmp(sn, ln) == 0) BIO_printf(bio_out, "%s = %s\n", sn, oid_buf); else BIO_printf(bio_out, "%s = %s, %s\n", sn, ln, oid_buf); } OPENSSL_free(oid_buf); } static void list_options_for_command(const char *command) { const FUNCTION *fp; const OPTIONS *o; for (fp = functions; fp->name != NULL; fp++) if (strcmp(fp->name, command) == 0) break; if (fp->name == NULL) { BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n", command); return; } if ((o = fp->help) == NULL) return; for ( ; o->name != NULL; o++) { char c = o->valtype; if (o->name == OPT_PARAM_STR) break; if (o->name == OPT_HELP_STR || o->name == OPT_MORE_STR || o->name == OPT_SECTION_STR || o->name[0] == '\0') continue; BIO_printf(bio_out, "%s %c\n", o->name, c == '\0' ? '-' : c); } BIO_printf(bio_out, "- -\n"); } static int is_md_available(const char *name) { EVP_MD *md; const char *propq = app_get0_propq(); ERR_set_mark(); md = EVP_MD_fetch(app_get0_libctx(), name, propq); ERR_pop_to_mark(); if (md != NULL) { EVP_MD_free(md); return 1; } return propq != NULL || get_digest_from_engine(name) == NULL ? 0 : 1; } static int is_cipher_available(const char *name) { EVP_CIPHER *cipher; const char *propq = app_get0_propq(); ERR_set_mark(); cipher = EVP_CIPHER_fetch(app_get0_libctx(), name, propq); ERR_pop_to_mark(); if (cipher != NULL) { EVP_CIPHER_free(cipher); return 1; } return propq != NULL || get_cipher_from_engine(name) == NULL ? 0 : 1; } static void list_type(FUNC_TYPE ft, int one) { FUNCTION *fp; int i = 0; DISPLAY_COLUMNS dc; memset(&dc, 0, sizeof(dc)); if (!one) calculate_columns(functions, &dc); for (fp = functions; fp->name != NULL; fp++) { if (fp->type != ft) continue; switch (ft) { case FT_cipher: if (!is_cipher_available(fp->name)) continue; break; case FT_md: if (!is_md_available(fp->name)) continue; break; default: break; } if (one) { BIO_printf(bio_out, "%s\n", fp->name); } else { if (i % dc.columns == 0 && i > 0) BIO_printf(bio_out, "\n"); BIO_printf(bio_out, "%-*s", dc.width, fp->name); i++; } } if (!one) BIO_printf(bio_out, "\n\n"); } static void list_pkey(void) { #ifndef OPENSSL_NO_DEPRECATED_3_0 int i; if (select_name == NULL && include_legacy()) { BIO_printf(bio_out, "Legacy:\n"); for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) { const EVP_PKEY_ASN1_METHOD *ameth; int pkey_id, pkey_base_id, pkey_flags; const char *pinfo, *pem_str; ameth = EVP_PKEY_asn1_get0(i); EVP_PKEY_asn1_get0_info(&pkey_id, &pkey_base_id, &pkey_flags, &pinfo, &pem_str, ameth); if (pkey_flags & ASN1_PKEY_ALIAS) { BIO_printf(bio_out, " Name: %s\n", OBJ_nid2ln(pkey_id)); BIO_printf(bio_out, "\tAlias for: %s\n", OBJ_nid2ln(pkey_base_id)); } else { BIO_printf(bio_out, " Name: %s\n", pinfo); BIO_printf(bio_out, "\tType: %s Algorithm\n", pkey_flags & ASN1_PKEY_DYNAMIC ? "External" : "Builtin"); BIO_printf(bio_out, "\tOID: %s\n", OBJ_nid2ln(pkey_id)); if (pem_str == NULL) pem_str = "(none)"; BIO_printf(bio_out, "\tPEM string: %s\n", pem_str); } } } #endif BIO_printf(bio_out, "Provided:\n"); BIO_printf(bio_out, " Key Managers:\n"); list_keymanagers(); } static void list_pkey_meth(void) { #ifndef OPENSSL_NO_DEPRECATED_3_0 size_t i; size_t meth_count = EVP_PKEY_meth_get_count(); if (select_name == NULL && include_legacy()) { BIO_printf(bio_out, "Legacy:\n"); for (i = 0; i < meth_count; i++) { const EVP_PKEY_METHOD *pmeth = EVP_PKEY_meth_get0(i); int pkey_id, pkey_flags; EVP_PKEY_meth_get0_info(&pkey_id, &pkey_flags, pmeth); BIO_printf(bio_out, " %s\n", OBJ_nid2ln(pkey_id)); BIO_printf(bio_out, "\tType: %s Algorithm\n", pkey_flags & ASN1_PKEY_DYNAMIC ? "External" : "Builtin"); } } #endif BIO_printf(bio_out, "Provided:\n"); BIO_printf(bio_out, " Encryption:\n"); list_asymciphers(); BIO_printf(bio_out, " Key Exchange:\n"); list_keyexchanges(); BIO_printf(bio_out, " Signatures:\n"); list_signatures(); BIO_printf(bio_out, " Key encapsulation:\n"); list_kems(); } DEFINE_STACK_OF(OSSL_STORE_LOADER) static int store_cmp(const OSSL_STORE_LOADER * const *a, const OSSL_STORE_LOADER * const *b) { return strcmp(OSSL_PROVIDER_get0_name(OSSL_STORE_LOADER_get0_provider(*a)), OSSL_PROVIDER_get0_name(OSSL_STORE_LOADER_get0_provider(*b))); } static void collect_store_loaders(OSSL_STORE_LOADER *store, void *stack) { STACK_OF(OSSL_STORE_LOADER) *store_stack = stack; if (sk_OSSL_STORE_LOADER_push(store_stack, store) > 0) OSSL_STORE_LOADER_up_ref(store); } static void list_store_loaders(void) { STACK_OF(OSSL_STORE_LOADER) *stores = sk_OSSL_STORE_LOADER_new(store_cmp); int i; if (stores == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Provided STORE LOADERs:\n"); OSSL_STORE_LOADER_do_all_provided(app_get0_libctx(), collect_store_loaders, stores); sk_OSSL_STORE_LOADER_sort(stores); for (i = 0; i < sk_OSSL_STORE_LOADER_num(stores); i++) { const OSSL_STORE_LOADER *m = sk_OSSL_STORE_LOADER_value(stores, i); STACK_OF(OPENSSL_CSTRING) *names = NULL; if (select_name != NULL && !OSSL_STORE_LOADER_is_a(m, select_name)) continue; names = sk_OPENSSL_CSTRING_new(name_cmp); if (names != NULL && OSSL_STORE_LOADER_names_do_all(m, collect_names, names)) { BIO_printf(bio_out, " "); print_names(bio_out, names); BIO_printf(bio_out, " @ %s\n", OSSL_PROVIDER_get0_name(OSSL_STORE_LOADER_get0_provider(m))); } sk_OPENSSL_CSTRING_free(names); } sk_OSSL_STORE_LOADER_pop_free(stores, OSSL_STORE_LOADER_free); } DEFINE_STACK_OF(OSSL_PROVIDER) static int provider_cmp(const OSSL_PROVIDER * const *a, const OSSL_PROVIDER * const *b) { return strcmp(OSSL_PROVIDER_get0_name(*a), OSSL_PROVIDER_get0_name(*b)); } static int collect_providers(OSSL_PROVIDER *provider, void *stack) { STACK_OF(OSSL_PROVIDER) *provider_stack = stack; return sk_OSSL_PROVIDER_push(provider_stack, provider) > 0 ? 1 : 0; } static void list_provider_info(void) { STACK_OF(OSSL_PROVIDER) *providers = sk_OSSL_PROVIDER_new(provider_cmp); OSSL_PARAM params[5]; char *name, *version, *buildinfo; int status; int i; if (providers == NULL) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } if (OSSL_PROVIDER_do_all(NULL, &collect_providers, providers) != 1) { BIO_printf(bio_err, "ERROR: Memory allocation\n"); return; } BIO_printf(bio_out, "Providers:\n"); sk_OSSL_PROVIDER_sort(providers); for (i = 0; i < sk_OSSL_PROVIDER_num(providers); i++) { const OSSL_PROVIDER *prov = sk_OSSL_PROVIDER_value(providers, i); const char *provname = OSSL_PROVIDER_get0_name(prov); BIO_printf(bio_out, " %s\n", provname); params[0] = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_NAME, &name, 0); params[1] = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_VERSION, &version, 0); params[2] = OSSL_PARAM_construct_int(OSSL_PROV_PARAM_STATUS, &status); params[3] = OSSL_PARAM_construct_utf8_ptr(OSSL_PROV_PARAM_BUILDINFO, &buildinfo, 0); params[4] = OSSL_PARAM_construct_end(); OSSL_PARAM_set_all_unmodified(params); if (!OSSL_PROVIDER_get_params(prov, params)) { BIO_printf(bio_err, "WARNING: Unable to query provider parameters for %s\n", provname); } else { if (OSSL_PARAM_modified(params)) BIO_printf(bio_out, " name: %s\n", name); if (OSSL_PARAM_modified(params + 1)) BIO_printf(bio_out, " version: %s\n", version); if (OSSL_PARAM_modified(params + 2)) BIO_printf(bio_out, " status: %sactive\n", status ? "" : "in"); if (verbose) { if (OSSL_PARAM_modified(params + 3)) BIO_printf(bio_out, " build info: %s\n", buildinfo); print_param_types("gettable provider parameters", OSSL_PROVIDER_gettable_params(prov), 4); } } } sk_OSSL_PROVIDER_free(providers); } #ifndef OPENSSL_NO_DEPRECATED_3_0 static void list_engines(void) { # ifndef OPENSSL_NO_ENGINE ENGINE *e; BIO_puts(bio_out, "Engines:\n"); e = ENGINE_get_first(); while (e) { BIO_printf(bio_out, "%s\n", ENGINE_get_id(e)); e = ENGINE_get_next(e); } # else BIO_puts(bio_out, "Engine support is disabled.\n"); # endif } #endif static void list_disabled(void) { BIO_puts(bio_out, "Disabled algorithms:\n"); #ifdef OPENSSL_NO_ARGON2 BIO_puts(bio_out, "ARGON2\n"); #endif #ifdef OPENSSL_NO_ARIA BIO_puts(bio_out, "ARIA\n"); #endif #ifdef OPENSSL_NO_BF BIO_puts(bio_out, "BF\n"); #endif #ifdef OPENSSL_NO_BLAKE2 BIO_puts(bio_out, "BLAKE2\n"); #endif #ifdef OPENSSL_NO_CAMELLIA BIO_puts(bio_out, "CAMELLIA\n"); #endif #ifdef OPENSSL_NO_CAST BIO_puts(bio_out, "CAST\n"); #endif #ifdef OPENSSL_NO_CMAC BIO_puts(bio_out, "CMAC\n"); #endif #ifdef OPENSSL_NO_CMS BIO_puts(bio_out, "CMS\n"); #endif #ifdef OPENSSL_NO_COMP BIO_puts(bio_out, "COMP\n"); #endif #ifdef OPENSSL_NO_DES BIO_puts(bio_out, "DES\n"); #endif #ifdef OPENSSL_NO_DGRAM BIO_puts(bio_out, "DGRAM\n"); #endif #ifdef OPENSSL_NO_DH BIO_puts(bio_out, "DH\n"); #endif #ifdef OPENSSL_NO_DSA BIO_puts(bio_out, "DSA\n"); #endif #if defined(OPENSSL_NO_DTLS) BIO_puts(bio_out, "DTLS\n"); #endif #if defined(OPENSSL_NO_DTLS1) BIO_puts(bio_out, "DTLS1\n"); #endif #if defined(OPENSSL_NO_DTLS1_2) BIO_puts(bio_out, "DTLS1_2\n"); #endif #ifdef OPENSSL_NO_EC BIO_puts(bio_out, "EC\n"); #endif #ifdef OPENSSL_NO_ECX BIO_puts(bio_out, "ECX\n"); #endif #ifdef OPENSSL_NO_EC2M BIO_puts(bio_out, "EC2M\n"); #endif #if defined(OPENSSL_NO_ENGINE) && !defined(OPENSSL_NO_DEPRECATED_3_0) BIO_puts(bio_out, "ENGINE\n"); #endif #ifdef OPENSSL_NO_GOST BIO_puts(bio_out, "GOST\n"); #endif #ifdef OPENSSL_NO_IDEA BIO_puts(bio_out, "IDEA\n"); #endif #ifdef OPENSSL_NO_MD2 BIO_puts(bio_out, "MD2\n"); #endif #ifdef OPENSSL_NO_MD4 BIO_puts(bio_out, "MD4\n"); #endif #ifdef OPENSSL_NO_MD5 BIO_puts(bio_out, "MD5\n"); #endif #ifdef OPENSSL_NO_MDC2 BIO_puts(bio_out, "MDC2\n"); #endif #ifdef OPENSSL_NO_OCB BIO_puts(bio_out, "OCB\n"); #endif #ifdef OPENSSL_NO_OCSP BIO_puts(bio_out, "OCSP\n"); #endif #ifdef OPENSSL_NO_PSK BIO_puts(bio_out, "PSK\n"); #endif #ifdef OPENSSL_NO_RC2 BIO_puts(bio_out, "RC2\n"); #endif #ifdef OPENSSL_NO_RC4 BIO_puts(bio_out, "RC4\n"); #endif #ifdef OPENSSL_NO_RC5 BIO_puts(bio_out, "RC5\n"); #endif #ifdef OPENSSL_NO_RMD160 BIO_puts(bio_out, "RMD160\n"); #endif #ifdef OPENSSL_NO_SCRYPT BIO_puts(bio_out, "SCRYPT\n"); #endif #ifdef OPENSSL_NO_SCTP BIO_puts(bio_out, "SCTP\n"); #endif #ifdef OPENSSL_NO_SEED BIO_puts(bio_out, "SEED\n"); #endif #ifdef OPENSSL_NO_SM2 BIO_puts(bio_out, "SM2\n"); #endif #ifdef OPENSSL_NO_SM3 BIO_puts(bio_out, "SM3\n"); #endif #ifdef OPENSSL_NO_SM4 BIO_puts(bio_out, "SM4\n"); #endif #ifdef OPENSSL_NO_SOCK BIO_puts(bio_out, "SOCK\n"); #endif #ifdef OPENSSL_NO_SRP BIO_puts(bio_out, "SRP\n"); #endif #ifdef OPENSSL_NO_SRTP BIO_puts(bio_out, "SRTP\n"); #endif #ifdef OPENSSL_NO_SSL3 BIO_puts(bio_out, "SSL3\n"); #endif #ifdef OPENSSL_NO_TLS1 BIO_puts(bio_out, "TLS1\n"); #endif #ifdef OPENSSL_NO_TLS1_1 BIO_puts(bio_out, "TLS1_1\n"); #endif #ifdef OPENSSL_NO_TLS1_2 BIO_puts(bio_out, "TLS1_2\n"); #endif #ifdef OPENSSL_NO_WHIRLPOOL BIO_puts(bio_out, "WHIRLPOOL\n"); #endif #ifdef OPENSSL_NO_ZLIB BIO_puts(bio_out, "ZLIB\n"); #endif #ifdef OPENSSL_NO_BROTLI BIO_puts(bio_out, "BROTLI\n"); #endif #ifdef OPENSSL_NO_ZSTD BIO_puts(bio_out, "ZSTD\n"); #endif } typedef enum HELPLIST_CHOICE { OPT_COMMON, OPT_ONE, OPT_VERBOSE, OPT_ALL_ARGORITHMS, OPT_COMMANDS, OPT_DIGEST_COMMANDS, OPT_MAC_ALGORITHMS, OPT_OPTIONS, OPT_DIGEST_ALGORITHMS, OPT_CIPHER_COMMANDS, OPT_CIPHER_ALGORITHMS, OPT_PK_ALGORITHMS, OPT_PK_METHOD, OPT_DISABLED, OPT_KDF_ALGORITHMS, OPT_RANDOM_INSTANCES, OPT_RANDOM_GENERATORS, OPT_ENCODERS, OPT_DECODERS, OPT_KEYMANAGERS, OPT_KEYEXCHANGE_ALGORITHMS, OPT_KEM_ALGORITHMS, OPT_SIGNATURE_ALGORITHMS, OPT_ASYM_CIPHER_ALGORITHMS, OPT_STORE_LOADERS, OPT_PROVIDER_INFO, OPT_OBJECTS, OPT_SELECT_NAME, #ifndef OPENSSL_NO_DEPRECATED_3_0 OPT_ENGINES, #endif OPT_PROV_ENUM } HELPLIST_CHOICE; const OPTIONS list_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Output"), {"1", OPT_ONE, '-', "List in one column"}, {"verbose", OPT_VERBOSE, '-', "Verbose listing"}, {"select", OPT_SELECT_NAME, 's', "Select a single algorithm"}, {"commands", OPT_COMMANDS, '-', "List of standard commands"}, {"standard-commands", OPT_COMMANDS, '-', "List of standard commands"}, {"all-algorithms", OPT_ALL_ARGORITHMS, '-', "List of all algorithms"}, #ifndef OPENSSL_NO_DEPRECATED_3_0 {"digest-commands", OPT_DIGEST_COMMANDS, '-', "List of message digest commands (deprecated)"}, #endif {"digest-algorithms", OPT_DIGEST_ALGORITHMS, '-', "List of message digest algorithms"}, {"kdf-algorithms", OPT_KDF_ALGORITHMS, '-', "List of key derivation and pseudo random function algorithms"}, {"random-instances", OPT_RANDOM_INSTANCES, '-', "List the primary, public and private random number generator details"}, {"random-generators", OPT_RANDOM_GENERATORS, '-', "List of random number generators"}, {"mac-algorithms", OPT_MAC_ALGORITHMS, '-', "List of message authentication code algorithms"}, #ifndef OPENSSL_NO_DEPRECATED_3_0 {"cipher-commands", OPT_CIPHER_COMMANDS, '-', "List of cipher commands (deprecated)"}, #endif {"cipher-algorithms", OPT_CIPHER_ALGORITHMS, '-', "List of symmetric cipher algorithms"}, {"encoders", OPT_ENCODERS, '-', "List of encoding methods" }, {"decoders", OPT_DECODERS, '-', "List of decoding methods" }, {"key-managers", OPT_KEYMANAGERS, '-', "List of key managers" }, {"key-exchange-algorithms", OPT_KEYEXCHANGE_ALGORITHMS, '-', "List of key exchange algorithms" }, {"kem-algorithms", OPT_KEM_ALGORITHMS, '-', "List of key encapsulation mechanism algorithms" }, {"signature-algorithms", OPT_SIGNATURE_ALGORITHMS, '-', "List of signature algorithms" }, {"asymcipher-algorithms", OPT_ASYM_CIPHER_ALGORITHMS, '-', "List of asymmetric cipher algorithms" }, {"public-key-algorithms", OPT_PK_ALGORITHMS, '-', "List of public key algorithms"}, {"public-key-methods", OPT_PK_METHOD, '-', "List of public key methods"}, {"store-loaders", OPT_STORE_LOADERS, '-', "List of store loaders"}, {"providers", OPT_PROVIDER_INFO, '-', "List of provider information"}, #ifndef OPENSSL_NO_DEPRECATED_3_0 {"engines", OPT_ENGINES, '-', "List of loaded engines"}, #endif {"disabled", OPT_DISABLED, '-', "List of disabled features"}, {"options", OPT_OPTIONS, 's', "List options for specified command"}, {"objects", OPT_OBJECTS, '-', "List built in objects (OID<->name mappings)"}, OPT_PROV_OPTIONS, {NULL} }; int list_main(int argc, char **argv) { char *prog; HELPLIST_CHOICE o; int one = 0, done = 0; int print_newline = 0; struct { unsigned int commands:1; unsigned int all_algorithms:1; unsigned int random_instances:1; unsigned int random_generators:1; unsigned int digest_commands:1; unsigned int digest_algorithms:1; unsigned int kdf_algorithms:1; unsigned int mac_algorithms:1; unsigned int cipher_commands:1; unsigned int cipher_algorithms:1; unsigned int encoder_algorithms:1; unsigned int decoder_algorithms:1; unsigned int keymanager_algorithms:1; unsigned int signature_algorithms:1; unsigned int keyexchange_algorithms:1; unsigned int kem_algorithms:1; unsigned int asym_cipher_algorithms:1; unsigned int pk_algorithms:1; unsigned int pk_method:1; unsigned int store_loaders:1; unsigned int provider_info:1; #ifndef OPENSSL_NO_DEPRECATED_3_0 unsigned int engines:1; #endif unsigned int disabled:1; unsigned int objects:1; unsigned int options:1; } todo = { 0, }; verbose = 0; prog = opt_init(argc, argv, list_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); return 1; case OPT_HELP: opt_help(list_options); return 0; case OPT_ONE: one = 1; break; case OPT_ALL_ARGORITHMS: todo.all_algorithms = 1; break; case OPT_COMMANDS: todo.commands = 1; break; case OPT_DIGEST_COMMANDS: todo.digest_commands = 1; break; case OPT_DIGEST_ALGORITHMS: todo.digest_algorithms = 1; break; case OPT_KDF_ALGORITHMS: todo.kdf_algorithms = 1; break; case OPT_RANDOM_INSTANCES: todo.random_instances = 1; break; case OPT_RANDOM_GENERATORS: todo.random_generators = 1; break; case OPT_MAC_ALGORITHMS: todo.mac_algorithms = 1; break; case OPT_CIPHER_COMMANDS: todo.cipher_commands = 1; break; case OPT_CIPHER_ALGORITHMS: todo.cipher_algorithms = 1; break; case OPT_ENCODERS: todo.encoder_algorithms = 1; break; case OPT_DECODERS: todo.decoder_algorithms = 1; break; case OPT_KEYMANAGERS: todo.keymanager_algorithms = 1; break; case OPT_SIGNATURE_ALGORITHMS: todo.signature_algorithms = 1; break; case OPT_KEYEXCHANGE_ALGORITHMS: todo.keyexchange_algorithms = 1; break; case OPT_KEM_ALGORITHMS: todo.kem_algorithms = 1; break; case OPT_ASYM_CIPHER_ALGORITHMS: todo.asym_cipher_algorithms = 1; break; case OPT_PK_ALGORITHMS: todo.pk_algorithms = 1; break; case OPT_PK_METHOD: todo.pk_method = 1; break; case OPT_STORE_LOADERS: todo.store_loaders = 1; break; case OPT_PROVIDER_INFO: todo.provider_info = 1; break; #ifndef OPENSSL_NO_DEPRECATED_3_0 case OPT_ENGINES: todo.engines = 1; break; #endif case OPT_DISABLED: todo.disabled = 1; break; case OPT_OBJECTS: todo.objects = 1; break; case OPT_OPTIONS: list_options_for_command(opt_arg()); break; case OPT_VERBOSE: verbose = 1; break; case OPT_SELECT_NAME: select_name = opt_arg(); break; case OPT_PROV_CASES: if (!opt_provider(o)) return 1; break; } done = 1; } if (!opt_check_rest_arg(NULL)) goto opthelp; #define MAYBE_ADD_NL(cmd) \ do { \ if (print_newline++) { \ BIO_printf(bio_out, "\n"); \ } \ cmd; \ } while(0) if (todo.commands) MAYBE_ADD_NL(list_type(FT_general, one)); if (todo.all_algorithms) { MAYBE_ADD_NL({}); BIO_printf(bio_out, "Digests:\n"); list_digests(" "); BIO_printf(bio_out, "\nSymmetric Ciphers:\n"); list_ciphers(" "); BIO_printf(bio_out, "\n"); list_kdfs(); BIO_printf(bio_out, "\n"); list_macs(); BIO_printf(bio_out, "\nProvided Asymmetric Encryption:\n"); list_asymciphers(); BIO_printf(bio_out, "\nProvided Key Exchange:\n"); list_keyexchanges(); BIO_printf(bio_out, "\nProvided Signatures:\n"); list_signatures(); BIO_printf(bio_out, "\nProvided Key encapsulation:\n"); list_kems(); BIO_printf(bio_out, "\nProvided Key managers:\n"); list_keymanagers(); BIO_printf(bio_out, "\n"); list_encoders(); BIO_printf(bio_out, "\n"); list_decoders(); BIO_printf(bio_out, "\n"); list_store_loaders(); } if (todo.random_instances) MAYBE_ADD_NL(list_random_instances()); if (todo.random_generators) MAYBE_ADD_NL(list_random_generators()); if (todo.digest_commands) MAYBE_ADD_NL(list_type(FT_md, one)); if (todo.digest_algorithms) MAYBE_ADD_NL(list_digests("")); if (todo.kdf_algorithms) MAYBE_ADD_NL(list_kdfs()); if (todo.mac_algorithms) MAYBE_ADD_NL(list_macs()); if (todo.cipher_commands) MAYBE_ADD_NL(list_type(FT_cipher, one)); if (todo.cipher_algorithms) MAYBE_ADD_NL(list_ciphers("")); if (todo.encoder_algorithms) MAYBE_ADD_NL(list_encoders()); if (todo.decoder_algorithms) MAYBE_ADD_NL(list_decoders()); if (todo.keymanager_algorithms) MAYBE_ADD_NL(list_keymanagers()); if (todo.signature_algorithms) MAYBE_ADD_NL(list_signatures()); if (todo.asym_cipher_algorithms) MAYBE_ADD_NL(list_asymciphers()); if (todo.keyexchange_algorithms) MAYBE_ADD_NL(list_keyexchanges()); if (todo.kem_algorithms) MAYBE_ADD_NL(list_kems()); if (todo.pk_algorithms) MAYBE_ADD_NL(list_pkey()); if (todo.pk_method) MAYBE_ADD_NL(list_pkey_meth()); if (todo.store_loaders) MAYBE_ADD_NL(list_store_loaders()); if (todo.provider_info) MAYBE_ADD_NL(list_provider_info()); #ifndef OPENSSL_NO_DEPRECATED_3_0 if (todo.engines) MAYBE_ADD_NL(list_engines()); #endif if (todo.disabled) MAYBE_ADD_NL(list_disabled()); if (todo.objects) MAYBE_ADD_NL(list_objects()); #undef MAYBE_ADD_NL if (!done) goto opthelp; return 0; }
apps
openssl/apps/list.c
openssl
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "apps.h" #include "progs.h" #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/evp.h> typedef enum OPTION_choice { OPT_COMMON, OPT_IN, OPT_OUT, OPT_TEXT, OPT_NOOUT, OPT_ENGINE, OPT_CHECK, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS pkeyparam_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"check", OPT_CHECK, '-', "Check key param consistency"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"text", OPT_TEXT, '-', "Print parameters as text"}, {"noout", OPT_NOOUT, '-', "Don't output encoded parameters"}, OPT_PROV_OPTIONS, {NULL} }; int pkeyparam_main(int argc, char **argv) { ENGINE *e = NULL; BIO *in = NULL, *out = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; int text = 0, noout = 0, ret = EXIT_FAILURE, check = 0, r; OPTION_CHOICE o; char *infile = NULL, *outfile = NULL, *prog; prog = opt_init(argc, argv, pkeyparam_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(pkeyparam_options); ret = 0; goto end; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_TEXT: text = 1; break; case OPT_NOOUT: noout = 1; break; case OPT_CHECK: check = 1; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; in = bio_open_default(infile, 'r', FORMAT_PEM); if (in == NULL) goto end; out = bio_open_default(outfile, 'w', FORMAT_PEM); if (out == NULL) goto end; pkey = PEM_read_bio_Parameters_ex(in, NULL, app_get0_libctx(), app_get0_propq()); if (pkey == NULL) { BIO_printf(bio_err, "Error reading parameters\n"); ERR_print_errors(bio_err); goto end; } if (check) { if (e == NULL) ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); else ctx = EVP_PKEY_CTX_new(pkey, e); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } r = EVP_PKEY_param_check(ctx); if (r == 1) { BIO_printf(out, "Parameters are valid\n"); } else { BIO_printf(bio_err, "Parameters are invalid\n"); ERR_print_errors(bio_err); goto end; } } if (!noout) PEM_write_bio_Parameters(out, pkey); if (text) EVP_PKEY_print_params(out, pkey, 0, NULL); ret = EXIT_SUCCESS; end: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); release_engine(e); BIO_free_all(out); BIO_free(in); return ret; }
apps
openssl/apps/pkeyparam.c
openssl
#if defined( __VMS) && !defined( OPENSSL_NO_DECC_INIT) && \ defined( __DECC) && !defined( __VAX) && (__CRTL_VER >= 70301000) # define USE_DECC_INIT 1 #endif #ifdef USE_DECC_INIT # include <stdio.h> # include <stdlib.h> # include <unixlib.h> int decc_init_done = -1; typedef struct { char *name; int value; } decc_feat_t; decc_feat_t decc_feat_array[] = { {"DECC$ARGV_PARSE_STYLE", 1}, {"DECC$EFS_CASE_PRESERVE", 1}, {"DECC$EFS_CHARSET", 1}, {(char *)NULL, 0} }; static void decc_init(void) { char *openssl_debug_decc_init; int verbose = 0; int feat_index; int feat_value; int feat_value_max; int feat_value_min; int i; int sts; openssl_debug_decc_init = getenv("OPENSSL_DEBUG_DECC_INIT"); if (openssl_debug_decc_init != NULL) { verbose = strtol(openssl_debug_decc_init, NULL, 10); if (verbose <= 0) { verbose = 1; } } decc_init_done = 1; for (i = 0; decc_feat_array[i].name != NULL; i++) { feat_index = decc$feature_get_index(decc_feat_array[i].name); if (feat_index >= 0) { feat_value = decc$feature_get_value(feat_index, 1); feat_value_min = decc$feature_get_value(feat_index, 2); feat_value_max = decc$feature_get_value(feat_index, 3); if ((decc_feat_array[i].value >= feat_value_min) && (decc_feat_array[i].value <= feat_value_max)) { if (feat_value != decc_feat_array[i].value) { sts = decc$feature_set_value(feat_index, 1, decc_feat_array[i].value); if (verbose > 1) { fprintf(stderr, " %s = %d, sts = %d.\n", decc_feat_array[i].name, decc_feat_array[i].value, sts); } } } else { fprintf(stderr, " INVALID DECC$FEATURE VALUE, %d: %d <= %s <= %d.\n", feat_value, feat_value_min, decc_feat_array[i].name, feat_value_max); } } else { fprintf(stderr, " UNKNOWN DECC$FEATURE: %s.\n", decc_feat_array[i].name); } } if (verbose > 0) { fprintf(stderr, " DECC_INIT complete.\n"); } } # pragma nostandard # pragma extern_model save # if __INITIAL_POINTER_SIZE == 64 # define PSECT_ALIGN 3 # else # define PSECT_ALIGN 2 # endif # pragma extern_model strict_refdef "LIB$INITIALIZ" PSECT_ALIGN, nopic, nowrt const int spare[8] = { 0 }; # pragma extern_model strict_refdef "LIB$INITIALIZE" PSECT_ALIGN, nopic, nowrt void (*const x_decc_init) () = decc_init; # pragma extern_model restore # pragma extern_model save int LIB$INITIALIZE(void); # pragma extern_model strict_refdef int dmy_lib$initialize = (int)LIB$INITIALIZE; # pragma extern_model restore # pragma standard #else int decc_init_dummy(void); #endif
apps
openssl/apps/vms_decc_init.c
openssl
#include <stdio.h> #include <string.h> #include "apps.h" #include "progs.h" #include "ec_common.h" #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/core_names.h> typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_PASSIN, OPT_PASSOUT, OPT_ENGINE, OPT_IN, OPT_OUT, OPT_PUBIN, OPT_PUBOUT, OPT_TEXT_PUB, OPT_TEXT, OPT_NOOUT, OPT_CIPHER, OPT_TRADITIONAL, OPT_CHECK, OPT_PUB_CHECK, OPT_EC_PARAM_ENC, OPT_EC_CONV_FORM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS pkey_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_PROV_OPTIONS, {"check", OPT_CHECK, '-', "Check key consistency"}, {"pubcheck", OPT_PUB_CHECK, '-', "Check public key consistency"}, OPT_SECTION("Input"), {"in", OPT_IN, 's', "Input key"}, {"inform", OPT_INFORM, 'f', "Key input format (ENGINE, other values ignored)"}, {"passin", OPT_PASSIN, 's', "Key input pass phrase source"}, {"pubin", OPT_PUBIN, '-', "Read only public components from key input"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file for encoded and/or text output"}, {"outform", OPT_OUTFORM, 'F', "Output encoding format (DER or PEM)"}, {"", OPT_CIPHER, '-', "Any supported cipher to be used for encryption"}, {"passout", OPT_PASSOUT, 's', "Output PEM file pass phrase source"}, {"traditional", OPT_TRADITIONAL, '-', "Use traditional format for private key PEM output"}, {"pubout", OPT_PUBOUT, '-', "Restrict encoded output to public components"}, {"noout", OPT_NOOUT, '-', "Do not output the key in encoded form"}, {"text", OPT_TEXT, '-', "Output key components in plaintext"}, {"text_pub", OPT_TEXT_PUB, '-', "Output only public key components in text form"}, {"ec_conv_form", OPT_EC_CONV_FORM, 's', "Specifies the EC point conversion form in the encoding"}, {"ec_param_enc", OPT_EC_PARAM_ENC, 's', "Specifies the way the EC parameters are encoded"}, {NULL} }; int pkey_main(int argc, char **argv) { BIO *out = NULL; ENGINE *e = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_CIPHER *cipher = NULL; char *infile = NULL, *outfile = NULL, *passin = NULL, *passout = NULL; char *passinarg = NULL, *passoutarg = NULL, *ciphername = NULL, *prog; OPTION_CHOICE o; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM; int pubin = 0, pubout = 0, text_pub = 0, text = 0, noout = 0, ret = 1; int private = 0, traditional = 0, check = 0, pub_check = 0; #ifndef OPENSSL_NO_EC char *asn1_encoding = NULL; char *point_format = NULL; #endif opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, pkey_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(pkey_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; 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_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_PUBIN: pubin = pubout = 1; break; case OPT_PUBOUT: pubout = 1; break; case OPT_TEXT_PUB: text_pub = 1; break; case OPT_TEXT: text = 1; break; case OPT_NOOUT: noout = 1; break; case OPT_TRADITIONAL: traditional = 1; break; case OPT_CHECK: check = 1; break; case OPT_PUB_CHECK: pub_check = 1; break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_EC_CONV_FORM: #ifdef OPENSSL_NO_EC goto opthelp; #else point_format = opt_arg(); if (!opt_string(point_format, point_format_options)) goto opthelp; break; #endif case OPT_EC_PARAM_ENC: #ifdef OPENSSL_NO_EC goto opthelp; #else asn1_encoding = opt_arg(); if (!opt_string(asn1_encoding, asn1_encoding_options)) goto opthelp; break; #endif case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (text && text_pub) BIO_printf(bio_err, "Warning: The -text option is ignored with -text_pub\n"); if (traditional && (noout || outformat != FORMAT_PEM)) BIO_printf(bio_err, "Warning: The -traditional is ignored since there is no PEM output\n"); if (!text_pub && pubout && text) { text = 0; text_pub = 1; } private = (!noout && !pubout) || (text && !text_pub); if (!opt_cipher(ciphername, &cipher)) goto opthelp; if (cipher == NULL) { if (passoutarg != NULL) BIO_printf(bio_err, "Warning: The -passout option is ignored without a cipher option\n"); } else { if (noout || outformat != FORMAT_PEM) { BIO_printf(bio_err, "Error: Cipher options are supported only for PEM output\n"); goto end; } } if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (pubin) pkey = load_pubkey(infile, informat, 1, passin, e, "Public Key"); else pkey = load_key(infile, informat, 1, passin, e, "key"); if (pkey == NULL) goto end; #ifndef OPENSSL_NO_EC if (asn1_encoding != NULL || point_format != NULL) { OSSL_PARAM params[3], *p = params; if (!EVP_PKEY_is_a(pkey, "EC")) goto end; if (asn1_encoding != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_EC_ENCODING, asn1_encoding, 0); if (point_format != NULL) *p++ = OSSL_PARAM_construct_utf8_string( OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, point_format, 0); *p = OSSL_PARAM_construct_end(); if (EVP_PKEY_set_params(pkey, params) <= 0) goto end; } #endif if (check || pub_check) { int r; ctx = EVP_PKEY_CTX_new(pkey, e); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } if (check && !pubin) r = EVP_PKEY_check(ctx); else r = EVP_PKEY_public_check(ctx); if (r == 1) { BIO_printf(out, "Key is valid\n"); } else { BIO_printf(bio_err, "Key is invalid\n"); ERR_print_errors(bio_err); goto end; } } if (!noout) { if (outformat == FORMAT_PEM) { if (pubout) { if (!PEM_write_bio_PUBKEY(out, pkey)) goto end; } else { assert(private); if (traditional) { if (!PEM_write_bio_PrivateKey_traditional(out, pkey, cipher, NULL, 0, NULL, passout)) goto end; } else { if (!PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0, NULL, passout)) goto end; } } } else if (outformat == FORMAT_ASN1) { if (text || text_pub) { BIO_printf(bio_err, "Error: Text output cannot be combined with DER output\n"); goto end; } if (pubout) { if (!i2d_PUBKEY_bio(out, pkey)) goto end; } else { assert(private); if (!i2d_PrivateKey_bio(out, pkey)) goto end; } } else { BIO_printf(bio_err, "Bad format specified for key\n"); goto end; } } if (text_pub) { if (EVP_PKEY_print_public(out, pkey, 0, NULL) <= 0) goto end; } else if (text) { assert(private); if (EVP_PKEY_print_private(out, pkey, 0, NULL) <= 0) goto end; } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); EVP_CIPHER_free(cipher); release_engine(e); BIO_free_all(out); OPENSSL_free(passin); OPENSSL_free(passout); return ret; }
apps
openssl/apps/pkey.c
openssl
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <ctype.h> #include "apps.h" #include "progs.h" #include <openssl/core_names.h> #include <openssl/bio.h> #include <openssl/evp.h> #include <openssl/conf.h> #include <openssl/err.h> #include <openssl/asn1.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/objects.h> #include <openssl/pem.h> #include <openssl/bn.h> #include <openssl/lhash.h> #include <openssl/rsa.h> #ifndef OPENSSL_NO_DSA # include <openssl/dsa.h> #endif #define BITS "default_bits" #define KEYFILE "default_keyfile" #define PROMPT "prompt" #define DISTINGUISHED_NAME "distinguished_name" #define ATTRIBUTES "attributes" #define V3_EXTENSIONS "x509_extensions" #define REQ_EXTENSIONS "req_extensions" #define STRING_MASK "string_mask" #define UTF8_IN "utf8" #define DEFAULT_KEY_LENGTH 2048 #define MIN_KEY_LENGTH 512 #define DEFAULT_DAYS 30 #define UNSET_DAYS -2 #define EXT_COPY_UNSET -1 static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj, int mutlirdn, int attribs, unsigned long chtype); static int prompt_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect, STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect, int attribs, unsigned long chtype); static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *sk, STACK_OF(CONF_VALUE) *attr, int attribs, unsigned long chtype); static int add_attribute_object(X509_REQ *req, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype); static int add_DN_object(X509_NAME *n, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype, int mval); static int build_data(char *text, const char *def, char *value, int n_min, int n_max, char *buf, const int buf_size, const char *desc1, const char *desc2); static int req_check_len(int len, int n_min, int n_max); static int check_end(const char *str, const char *end); static int join(char buf[], size_t buf_size, const char *name, const char *tail, const char *desc); static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, char **pkeytype, long *pkeylen, ENGINE *keygen_engine); static const char *section = "req"; static CONF *req_conf = NULL; static CONF *addext_conf = NULL; static int batch = 0; typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_KEYGEN_ENGINE, OPT_KEY, OPT_PUBKEY, OPT_NEW, OPT_CONFIG, OPT_KEYFORM, OPT_IN, OPT_OUT, OPT_KEYOUT, OPT_PASSIN, OPT_PASSOUT, OPT_NEWKEY, OPT_PKEYOPT, OPT_SIGOPT, OPT_VFYOPT, OPT_BATCH, OPT_NEWHDR, OPT_MODULUS, OPT_VERIFY, OPT_NOENC, OPT_NODES, OPT_NOOUT, OPT_VERBOSE, OPT_UTF8, OPT_NAMEOPT, OPT_REQOPT, OPT_SUBJ, OPT_SUBJECT, OPT_TEXT, OPT_X509, OPT_X509V1, OPT_CA, OPT_CAKEY, OPT_MULTIVALUE_RDN, OPT_DAYS, OPT_SET_SERIAL, OPT_COPY_EXTENSIONS, OPT_EXTENSIONS, OPT_REQEXTS, OPT_ADDEXT, OPT_PRECERT, OPT_MD, OPT_SECTION, OPT_QUIET, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS req_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, {"keygen_engine", OPT_KEYGEN_ENGINE, 's', "Specify engine to be used for key generation operations"}, #endif {"in", OPT_IN, '<', "X.509 request input file (default stdin)"}, {"inform", OPT_INFORM, 'F', "CSR input format to use (PEM or DER; by default try PEM first)"}, {"verify", OPT_VERIFY, '-', "Verify self-signature on the request"}, OPT_SECTION("Certificate"), {"new", OPT_NEW, '-', "New request"}, {"config", OPT_CONFIG, '<', "Request template file"}, {"section", OPT_SECTION, 's', "Config section to use (default \"req\")"}, {"utf8", OPT_UTF8, '-', "Input characters are UTF8 (default ASCII)"}, {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"reqopt", OPT_REQOPT, 's', "Various request text options"}, {"text", OPT_TEXT, '-', "Text form of request"}, {"x509", OPT_X509, '-', "Output an X.509 certificate structure instead of a cert request"}, {"x509v1", OPT_X509V1, '-', "Request cert generation with X.509 version 1"}, {"CA", OPT_CA, '<', "Issuer cert to use for signing a cert, implies -x509"}, {"CAkey", OPT_CAKEY, 's', "Issuer private key to use with -CA; default is -CA arg"}, {OPT_MORE_STR, 1, 1, "(Required by some CA's)"}, {"subj", OPT_SUBJ, 's', "Set or modify subject of request or cert"}, {"subject", OPT_SUBJECT, '-', "Print the subject of the output request or cert"}, {"multivalue-rdn", OPT_MULTIVALUE_RDN, '-', "Deprecated; multi-valued RDNs support is always on."}, {"days", OPT_DAYS, 'p', "Number of days cert is valid for"}, {"set_serial", OPT_SET_SERIAL, 's', "Serial number to use"}, {"copy_extensions", OPT_COPY_EXTENSIONS, 's', "copy extensions from request when using -x509"}, {"extensions", OPT_EXTENSIONS, 's', "Cert or request extension section (override value in config file)"}, {"reqexts", OPT_REQEXTS, 's', "An alias for -extensions"}, {"addext", OPT_ADDEXT, 's', "Additional cert extension key=value pair (may be given more than once)"}, {"precert", OPT_PRECERT, '-', "Add a poison extension to generated cert (implies -new)"}, OPT_SECTION("Keys and Signing"), {"key", OPT_KEY, 's', "Key for signing, and to include unless -in given"}, {"keyform", OPT_KEYFORM, 'f', "Key file format (ENGINE, other values ignored)"}, {"pubkey", OPT_PUBKEY, '-', "Output public key"}, {"keyout", OPT_KEYOUT, '>', "File to write private key to"}, {"passin", OPT_PASSIN, 's', "Private key and certificate password source"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"newkey", OPT_NEWKEY, 's', "Generate new key with [<alg>:]<nbits> or <alg>[:<file>] or param:<file>"}, {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"}, {"sigopt", OPT_SIGOPT, 's', "Signature parameter in n:v form"}, {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"}, {"", OPT_MD, '-', "Any supported digest"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, {"batch", OPT_BATCH, '-', "Do not ask anything during request generation"}, {"verbose", OPT_VERBOSE, '-', "Verbose output"}, {"quiet", OPT_QUIET, '-', "Terse output"}, {"noenc", OPT_NOENC, '-', "Don't encrypt private keys"}, {"nodes", OPT_NODES, '-', "Don't encrypt private keys; deprecated"}, {"noout", OPT_NOOUT, '-', "Do not output REQ"}, {"newhdr", OPT_NEWHDR, '-', "Output \"NEW\" in the header lines"}, {"modulus", OPT_MODULUS, '-', "RSA modulus"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; static unsigned long ext_name_hash(const OPENSSL_STRING *a) { return OPENSSL_LH_strhash((const char *)a); } static int ext_name_cmp(const OPENSSL_STRING *a, const OPENSSL_STRING *b) { return strcmp((const char *)a, (const char *)b); } static void exts_cleanup(OPENSSL_STRING *x) { OPENSSL_free((char *)x); } static int duplicated(LHASH_OF(OPENSSL_STRING) *addexts, char *kv) { char *p; size_t off; while (isspace(_UC(*kv))) kv++; if ((p = strchr(kv, '=')) == NULL) { BIO_printf(bio_err, "Parse error on -addext: missing '='\n"); return -2; } off = p - kv; if ((kv = OPENSSL_strdup(kv)) == NULL) return -1; for (p = kv + off; p > kv; --p) if (!isspace(_UC(p[-1]))) break; if (p == kv) { BIO_printf(bio_err, "Parse error on -addext: missing key\n"); OPENSSL_free(kv); return -2; } *p = '\0'; p = (char *)lh_OPENSSL_STRING_insert(addexts, (OPENSSL_STRING *)kv); if (p != NULL) { BIO_printf(bio_err, "Duplicate extension name: %s\n", kv); OPENSSL_free(p); return 1; } else if (lh_OPENSSL_STRING_error(addexts)) { OPENSSL_free(kv); return -1; } return 0; } int req_main(int argc, char **argv) { ASN1_INTEGER *serial = NULL; BIO *out = NULL; ENGINE *e = NULL, *gen_eng = NULL; EVP_PKEY *pkey = NULL, *CAkey = NULL; EVP_PKEY_CTX *genctx = NULL; STACK_OF(OPENSSL_STRING) *pkeyopts = NULL, *sigopts = NULL, *vfyopts = NULL; LHASH_OF(OPENSSL_STRING) *addexts = NULL; X509 *new_x509 = NULL, *CAcert = NULL; X509_REQ *req = NULL; EVP_CIPHER *cipher = NULL; int ext_copy = EXT_COPY_UNSET; BIO *addext_bio = NULL; char *extsect = NULL; const char *infile = NULL, *CAfile = NULL, *CAkeyfile = NULL; char *outfile = NULL, *keyfile = NULL, *digest = NULL; char *keyalgstr = NULL, *p, *prog, *passargin = NULL, *passargout = NULL; char *passin = NULL, *passout = NULL; char *nofree_passin = NULL, *nofree_passout = NULL; char *subj = NULL; X509_NAME *fsubj = NULL; char *template = default_config_file, *keyout = NULL; const char *keyalg = NULL; OPTION_CHOICE o; int days = UNSET_DAYS; int ret = 1, gen_x509 = 0, i = 0, newreq = 0, verbose = 0, progress = 1; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyform = FORMAT_UNDEF; int modulus = 0, multirdn = 1, verify = 0, noout = 0, text = 0; int noenc = 0, newhdr = 0, subject = 0, pubkey = 0, precert = 0, x509v1 = 0; long newkey_len = -1; unsigned long chtype = MBSTRING_ASC, reqflag = 0; #ifndef OPENSSL_NO_DES cipher = (EVP_CIPHER *)EVP_des_ede3_cbc(); #endif opt_set_unknown_name("digest"); prog = opt_init(argc, argv, req_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(req_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_KEYGEN_ENGINE: #ifndef OPENSSL_NO_ENGINE gen_eng = setup_engine(opt_arg(), 0); if (gen_eng == NULL) { BIO_printf(bio_err, "Can't find keygen engine %s\n", *argv); goto opthelp; } #endif break; case OPT_KEY: keyfile = opt_arg(); break; case OPT_PUBKEY: pubkey = 1; break; case OPT_NEW: newreq = 1; break; case OPT_CONFIG: template = opt_arg(); break; case OPT_SECTION: section = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_KEYOUT: keyout = opt_arg(); break; case OPT_PASSIN: passargin = opt_arg(); break; case OPT_PASSOUT: passargout = opt_arg(); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_NEWKEY: keyalg = opt_arg(); newreq = 1; break; case OPT_PKEYOPT: if (pkeyopts == NULL) pkeyopts = sk_OPENSSL_STRING_new_null(); if (pkeyopts == NULL || !sk_OPENSSL_STRING_push(pkeyopts, opt_arg())) goto opthelp; 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_VFYOPT: if (!vfyopts) vfyopts = sk_OPENSSL_STRING_new_null(); if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg())) goto opthelp; break; case OPT_BATCH: batch = 1; break; case OPT_NEWHDR: newhdr = 1; break; case OPT_MODULUS: modulus = 1; break; case OPT_VERIFY: verify = 1; break; case OPT_NODES: case OPT_NOENC: noenc = 1; break; case OPT_NOOUT: noout = 1; break; case OPT_VERBOSE: verbose = 1; progress = 1; break; case OPT_QUIET: verbose = 0; progress = 0; break; case OPT_UTF8: chtype = MBSTRING_UTF8; break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto opthelp; break; case OPT_REQOPT: if (!set_cert_ex(&reqflag, opt_arg())) goto opthelp; break; case OPT_TEXT: text = 1; break; case OPT_X509V1: x509v1 = 1; case OPT_X509: gen_x509 = 1; break; case OPT_CA: CAfile = opt_arg(); gen_x509 = 1; break; case OPT_CAKEY: CAkeyfile = opt_arg(); break; case OPT_DAYS: days = atoi(opt_arg()); if (days < -1) { BIO_printf(bio_err, "%s: -days parameter arg must be >= -1\n", prog); goto end; } break; case OPT_SET_SERIAL: if (serial != NULL) { BIO_printf(bio_err, "Serial number supplied twice\n"); goto opthelp; } serial = s2i_ASN1_INTEGER(NULL, opt_arg()); if (serial == NULL) goto opthelp; break; case OPT_SUBJECT: subject = 1; break; case OPT_SUBJ: subj = opt_arg(); break; case OPT_MULTIVALUE_RDN: break; case OPT_COPY_EXTENSIONS: if (!set_ext_copy(&ext_copy, opt_arg())) { BIO_printf(bio_err, "Invalid extension copy option: \"%s\"\n", opt_arg()); goto end; } break; case OPT_EXTENSIONS: case OPT_REQEXTS: extsect = opt_arg(); break; case OPT_ADDEXT: p = opt_arg(); if (addexts == NULL) { addexts = lh_OPENSSL_STRING_new(ext_name_hash, ext_name_cmp); addext_bio = BIO_new(BIO_s_mem()); if (addexts == NULL || addext_bio == NULL) goto end; } i = duplicated(addexts, p); if (i == 1) goto opthelp; if (i == -1) BIO_printf(bio_err, "Internal error handling -addext %s\n", p); if (i < 0 || BIO_printf(addext_bio, "%s\n", p) < 0) goto end; break; case OPT_PRECERT: newreq = precert = 1; break; case OPT_MD: digest = opt_unknown(); break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (!gen_x509) { if (days != UNSET_DAYS) BIO_printf(bio_err, "Ignoring -days without -x509; not generating a certificate\n"); if (ext_copy == EXT_COPY_NONE) BIO_printf(bio_err, "Ignoring -copy_extensions 'none' when -x509 is not given\n"); } if (infile == NULL) { if (gen_x509) newreq = 1; else if (!newreq) BIO_printf(bio_err, "Warning: Will read cert request from stdin since no -in option is given\n"); } if (!app_passwd(passargin, passargout, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } if ((req_conf = app_load_config_verbose(template, verbose)) == NULL) goto end; if (addext_bio != NULL) { if (verbose) BIO_printf(bio_err, "Using additional configuration from -addext options\n"); if ((addext_conf = app_load_config_bio(addext_bio, NULL)) == NULL) goto end; } if (template != default_config_file && !app_load_modules(req_conf)) goto end; if (req_conf != NULL) { p = app_conf_try_string(req_conf, NULL, "oid_file"); if (p != NULL) { BIO *oid_bio = BIO_new_file(p, "r"); if (oid_bio == NULL) { if (verbose) BIO_printf(bio_err, "Problems opening '%s' for extra OIDs\n", p); } else { OBJ_create_objects(oid_bio); BIO_free(oid_bio); } } } if (!add_oid_section(req_conf)) goto end; if (digest != NULL) { if (!opt_check_md(digest)) goto opthelp; } else { p = app_conf_try_string(req_conf, section, "default_md"); if (p != NULL) digest = p; } if (extsect == NULL) extsect = app_conf_try_string(req_conf, section, gen_x509 ? V3_EXTENSIONS : REQ_EXTENSIONS); if (extsect != NULL) { X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, req_conf); if (!X509V3_EXT_add_nconf(req_conf, &ctx, extsect, NULL)) { BIO_printf(bio_err, "Error checking %s extension section %s\n", gen_x509 ? "x509" : "request", extsect); goto end; } } if (addext_conf != NULL) { X509V3_CTX ctx; X509V3_set_ctx_test(&ctx); X509V3_set_nconf(&ctx, addext_conf); if (!X509V3_EXT_add_nconf(addext_conf, &ctx, "default", NULL)) { BIO_printf(bio_err, "Error checking extensions defined using -addext\n"); goto end; } } if (passin == NULL) passin = nofree_passin = app_conf_try_string(req_conf, section, "input_password"); if (passout == NULL) passout = nofree_passout = app_conf_try_string(req_conf, section, "output_password"); p = app_conf_try_string(req_conf, section, STRING_MASK); if (p != NULL && !ASN1_STRING_set_default_mask_asc(p)) { BIO_printf(bio_err, "Invalid global string mask setting %s\n", p); goto end; } if (chtype != MBSTRING_UTF8) { p = app_conf_try_string(req_conf, section, UTF8_IN); if (p != NULL && strcmp(p, "yes") == 0) chtype = MBSTRING_UTF8; } if (keyfile != NULL) { pkey = load_key(keyfile, keyform, 0, passin, e, "private key"); if (pkey == NULL) goto end; app_RAND_load_conf(req_conf, section); } if (keyalg != NULL && pkey != NULL) { BIO_printf(bio_err, "Warning: Not generating key via given -newkey option since -key is given\n"); } if (newreq && pkey == NULL) { app_RAND_load_conf(req_conf, section); if (!app_conf_try_number(req_conf, section, BITS, &newkey_len)) newkey_len = DEFAULT_KEY_LENGTH; genctx = set_keygen_ctx(keyalg, &keyalgstr, &newkey_len, gen_eng); if (genctx == NULL) goto end; if (newkey_len < MIN_KEY_LENGTH && (EVP_PKEY_CTX_is_a(genctx, "RSA") || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS") || EVP_PKEY_CTX_is_a(genctx, "DSA"))) { BIO_printf(bio_err, "Private key length too short, needs to be at least %d bits, not %ld.\n", MIN_KEY_LENGTH, newkey_len); goto end; } if (newkey_len > OPENSSL_RSA_MAX_MODULUS_BITS && (EVP_PKEY_CTX_is_a(genctx, "RSA") || EVP_PKEY_CTX_is_a(genctx, "RSA-PSS"))) BIO_printf(bio_err, "Warning: It is not recommended to use more than %d bit for RSA keys.\n" " Your key size is %ld! Larger key size may behave not as expected.\n", OPENSSL_RSA_MAX_MODULUS_BITS, newkey_len); #ifndef OPENSSL_NO_DSA if (EVP_PKEY_CTX_is_a(genctx, "DSA") && newkey_len > OPENSSL_DSA_MAX_MODULUS_BITS) BIO_printf(bio_err, "Warning: It is not recommended to use more than %d bit for DSA keys.\n" " Your key size is %ld! Larger key size may behave not as expected.\n", OPENSSL_DSA_MAX_MODULUS_BITS, newkey_len); #endif if (pkeyopts != NULL) { char *genopt; for (i = 0; i < sk_OPENSSL_STRING_num(pkeyopts); i++) { genopt = sk_OPENSSL_STRING_value(pkeyopts, i); if (pkey_ctrl_string(genctx, genopt) <= 0) { BIO_printf(bio_err, "Key parameter error \"%s\"\n", genopt); goto end; } } } EVP_PKEY_CTX_set_app_data(genctx, bio_err); if (progress) EVP_PKEY_CTX_set_cb(genctx, progress_cb); pkey = app_keygen(genctx, keyalgstr, newkey_len, verbose); if (pkey == NULL) goto end; EVP_PKEY_CTX_free(genctx); genctx = NULL; } if (keyout == NULL && keyfile == NULL) keyout = app_conf_try_string(req_conf, section, KEYFILE); if (pkey != NULL && (keyfile == NULL || keyout != NULL)) { if (verbose) { BIO_printf(bio_err, "Writing private key to "); if (keyout == NULL) BIO_printf(bio_err, "stdout\n"); else BIO_printf(bio_err, "'%s'\n", keyout); } out = bio_open_owner(keyout, outformat, newreq); if (out == NULL) goto end; p = app_conf_try_string(req_conf, section, "encrypt_rsa_key"); if (p == NULL) p = app_conf_try_string(req_conf, section, "encrypt_key"); if (p != NULL && strcmp(p, "no") == 0) cipher = NULL; if (noenc) cipher = NULL; i = 0; loop: if (!PEM_write_bio_PrivateKey(out, pkey, cipher, NULL, 0, NULL, passout)) { if ((ERR_GET_REASON(ERR_peek_error()) == PEM_R_PROBLEMS_GETTING_PASSWORD) && (i < 3)) { ERR_clear_error(); i++; goto loop; } goto end; } BIO_free_all(out); out = NULL; BIO_printf(bio_err, "-----\n"); } if (subj != NULL && (fsubj = parse_name(subj, chtype, multirdn, "subject")) == NULL) goto end; if (!newreq) { if (keyfile != NULL) BIO_printf(bio_err, "Warning: Not placing -key in cert or request since request is used\n"); req = load_csr_autofmt(infile , informat, vfyopts, "X509 request"); if (req == NULL) goto end; } else if (infile != NULL) { BIO_printf(bio_err, "Warning: Ignoring -in option since -new or -newkey or -precert is given\n"); } if (CAkeyfile == NULL) CAkeyfile = CAfile; if (CAkeyfile != NULL) { if (CAfile == NULL) { BIO_printf(bio_err, "Warning: Ignoring -CAkey option since no -CA option is given\n"); } else { if ((CAkey = load_key(CAkeyfile, FORMAT_UNDEF, 0, passin, e, CAkeyfile != CAfile ? "issuer private key from -CAkey arg" : "issuer private key from -CA arg")) == NULL) goto end; } } if (CAfile != NULL) { if ((CAcert = load_cert_pass(CAfile, FORMAT_UNDEF, 1, passin, "issuer cert from -CA arg")) == NULL) goto end; if (!X509_check_private_key(CAcert, CAkey)) { BIO_printf(bio_err, "Issuer CA certificate and key do not match\n"); goto end; } } if (newreq || gen_x509) { if (CAcert == NULL && pkey == NULL) { BIO_printf(bio_err, "Must provide a signature key using -key or" " provide -CA / -CAkey\n"); goto end; } if (req == NULL) { req = X509_REQ_new_ex(app_get0_libctx(), app_get0_propq()); if (req == NULL) { goto end; } if (!make_REQ(req, pkey, fsubj, multirdn, !gen_x509, chtype)) { BIO_printf(bio_err, "Error making certificate request\n"); goto end; } } if (gen_x509) { EVP_PKEY *pub_key = X509_REQ_get0_pubkey(req); EVP_PKEY *issuer_key = CAcert != NULL ? CAkey : pkey; X509V3_CTX ext_ctx; X509_NAME *issuer = CAcert != NULL ? X509_get_subject_name(CAcert) : X509_REQ_get_subject_name(req); X509_NAME *n_subj = fsubj != NULL ? fsubj : X509_REQ_get_subject_name(req); if (CAcert != NULL && keyfile != NULL) BIO_printf(bio_err, "Warning: Not using -key or -newkey for signing since -CA option is given\n"); if ((new_x509 = X509_new_ex(app_get0_libctx(), app_get0_propq())) == NULL) goto end; if (serial != NULL) { if (!X509_set_serialNumber(new_x509, serial)) goto end; } else { if (!rand_serial(NULL, X509_get_serialNumber(new_x509))) goto end; } if (!X509_set_issuer_name(new_x509, issuer)) goto end; if (days == UNSET_DAYS) { days = DEFAULT_DAYS; } if (!set_cert_times(new_x509, NULL, NULL, days)) goto end; if (!X509_set_subject_name(new_x509, n_subj)) goto end; if (!pub_key || !X509_set_pubkey(new_x509, pub_key)) goto end; if (ext_copy == EXT_COPY_UNSET) { if (infile != NULL) BIO_printf(bio_err, "Warning: No -copy_extensions given; ignoring any extensions in the request\n"); } else if (!copy_extensions(new_x509, req, ext_copy)) { BIO_printf(bio_err, "Error copying extensions from request\n"); goto end; } X509V3_set_ctx(&ext_ctx, CAcert != NULL ? CAcert : new_x509, new_x509, NULL, NULL, X509V3_CTX_REPLACE); if (CAcert == NULL) { if (!X509V3_set_issuer_pkey(&ext_ctx, issuer_key)) goto end; if (!cert_matches_key(new_x509, issuer_key)) BIO_printf(bio_err, "Warning: Signature key and public key of cert do not match\n"); } X509V3_set_nconf(&ext_ctx, req_conf); if (extsect != NULL && !X509V3_EXT_add_nconf(req_conf, &ext_ctx, extsect, new_x509)) { BIO_printf(bio_err, "Error adding x509 extensions from section %s\n", extsect); goto end; } if (addext_conf != NULL && !X509V3_EXT_add_nconf(addext_conf, &ext_ctx, "default", new_x509)) { BIO_printf(bio_err, "Error adding x509 extensions defined via -addext\n"); goto end; } if (precert) { if (X509_add1_ext_i2d(new_x509, NID_ct_precert_poison, NULL, 1, 0) != 1) { BIO_printf(bio_err, "Error adding poison extension\n"); goto end; } } i = do_X509_sign(new_x509, x509v1, issuer_key, digest, sigopts, &ext_ctx); if (!i) goto end; } else { X509V3_CTX ext_ctx; if (precert) { BIO_printf(bio_err, "Warning: Ignoring -precert flag since no cert is produced\n"); } X509V3_set_ctx(&ext_ctx, NULL, NULL, req, NULL, X509V3_CTX_REPLACE); X509V3_set_nconf(&ext_ctx, req_conf); if (extsect != NULL && !X509V3_EXT_REQ_add_nconf(req_conf, &ext_ctx, extsect, req)) { BIO_printf(bio_err, "Error adding request extensions from section %s\n", extsect); goto end; } if (addext_conf != NULL && !X509V3_EXT_REQ_add_nconf(addext_conf, &ext_ctx, "default", req)) { BIO_printf(bio_err, "Error adding request extensions defined via -addext\n"); goto end; } i = do_X509_REQ_sign(req, pkey, digest, sigopts); if (!i) goto end; } } if (subj != NULL && !newreq && !gen_x509) { if (verbose) { BIO_printf(out, "Modifying subject of certificate request\n"); print_name(out, "Old subject=", X509_REQ_get_subject_name(req)); } if (!X509_REQ_set_subject_name(req, fsubj)) { BIO_printf(bio_err, "Error modifying subject of certificate request\n"); goto end; } if (verbose) { print_name(out, "New subject=", X509_REQ_get_subject_name(req)); } } if (verify) { EVP_PKEY *tpubkey = pkey; if (tpubkey == NULL) { tpubkey = X509_REQ_get0_pubkey(req); if (tpubkey == NULL) goto end; } i = do_X509_REQ_verify(req, tpubkey, vfyopts); if (i < 0) goto end; if (i == 0) { BIO_printf(bio_err, "Certificate request self-signature verify failure\n"); goto end; } else BIO_printf(bio_out, "Certificate request self-signature verify OK\n"); } if (noout && !text && !modulus && !subject && !pubkey) { ret = 0; goto end; } out = bio_open_default(outfile, keyout != NULL && outfile != NULL && strcmp(keyout, outfile) == 0 ? 'a' : 'w', outformat); if (out == NULL) goto end; if (pubkey) { EVP_PKEY *tpubkey = X509_REQ_get0_pubkey(req); if (tpubkey == NULL) { BIO_printf(bio_err, "Error getting public key\n"); goto end; } PEM_write_bio_PUBKEY(out, tpubkey); } if (text) { if (gen_x509) ret = X509_print_ex(out, new_x509, get_nameopt(), reqflag); else ret = X509_REQ_print_ex(out, req, get_nameopt(), reqflag); if (ret == 0) { if (gen_x509) BIO_printf(bio_err, "Error printing certificate\n"); else BIO_printf(bio_err, "Error printing certificate request\n"); goto end; } } if (subject) { print_name(out, "subject=", gen_x509 ? X509_get_subject_name(new_x509) : X509_REQ_get_subject_name(req)); } if (modulus) { EVP_PKEY *tpubkey; if (gen_x509) tpubkey = X509_get0_pubkey(new_x509); else tpubkey = X509_REQ_get0_pubkey(req); if (tpubkey == NULL) { BIO_puts(bio_err, "Modulus is unavailable\n"); goto end; } BIO_puts(out, "Modulus="); if (EVP_PKEY_is_a(tpubkey, "RSA") || EVP_PKEY_is_a(tpubkey, "RSA-PSS")) { BIGNUM *n = NULL; if (!EVP_PKEY_get_bn_param(tpubkey, "n", &n)) goto end; BN_print(out, n); BN_free(n); } else { BIO_puts(out, "Wrong Algorithm type"); } BIO_puts(out, "\n"); } if (!noout && !gen_x509) { if (outformat == FORMAT_ASN1) i = i2d_X509_REQ_bio(out, req); else if (newhdr) i = PEM_write_bio_X509_REQ_NEW(out, req); else i = PEM_write_bio_X509_REQ(out, req); if (!i) { BIO_printf(bio_err, "Unable to write certificate request\n"); goto end; } } if (!noout && gen_x509 && new_x509 != NULL) { if (outformat == FORMAT_ASN1) i = i2d_X509_bio(out, new_x509); else i = PEM_write_bio_X509(out, new_x509); if (!i) { BIO_printf(bio_err, "Unable to write X509 certificate\n"); goto end; } } ret = 0; end: if (ret) { ERR_print_errors(bio_err); } NCONF_free(req_conf); NCONF_free(addext_conf); BIO_free(addext_bio); BIO_free_all(out); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(genctx); sk_OPENSSL_STRING_free(pkeyopts); sk_OPENSSL_STRING_free(sigopts); sk_OPENSSL_STRING_free(vfyopts); lh_OPENSSL_STRING_doall(addexts, exts_cleanup); lh_OPENSSL_STRING_free(addexts); #ifndef OPENSSL_NO_ENGINE release_engine(gen_eng); #endif OPENSSL_free(keyalgstr); X509_REQ_free(req); X509_NAME_free(fsubj); X509_free(new_x509); X509_free(CAcert); EVP_PKEY_free(CAkey); ASN1_INTEGER_free(serial); release_engine(e); if (passin != nofree_passin) OPENSSL_free(passin); if (passout != nofree_passout) OPENSSL_free(passout); return ret; } static int make_REQ(X509_REQ *req, EVP_PKEY *pkey, X509_NAME *fsubj, int multirdn, int attribs, unsigned long chtype) { int ret = 0, i; char no_prompt = 0; STACK_OF(CONF_VALUE) *dn_sk = NULL, *attr_sk = NULL; char *tmp, *dn_sect, *attr_sect; tmp = app_conf_try_string(req_conf, section, PROMPT); if (tmp != NULL && strcmp(tmp, "no") == 0) no_prompt = 1; dn_sect = app_conf_try_string(req_conf, section, DISTINGUISHED_NAME); if (dn_sect != NULL) { dn_sk = NCONF_get_section(req_conf, dn_sect); if (dn_sk == NULL) { BIO_printf(bio_err, "Unable to get '%s' section\n", dn_sect); goto err; } } attr_sect = app_conf_try_string(req_conf, section, ATTRIBUTES); if (attr_sect != NULL) { attr_sk = NCONF_get_section(req_conf, attr_sect); if (attr_sk == NULL) { BIO_printf(bio_err, "Unable to get '%s' section\n", attr_sect); goto err; } } if (!X509_REQ_set_version(req, X509_REQ_VERSION_1)) goto err; if (fsubj != NULL) i = X509_REQ_set_subject_name(req, fsubj); else if (no_prompt) i = auto_info(req, dn_sk, attr_sk, attribs, chtype); else i = prompt_info(req, dn_sk, dn_sect, attr_sk, attr_sect, attribs, chtype); if (!i) goto err; if (!X509_REQ_set_pubkey(req, pkey)) goto err; ret = 1; err: return ret; } static int prompt_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, const char *dn_sect, STACK_OF(CONF_VALUE) *attr_sk, const char *attr_sect, int attribs, unsigned long chtype) { int i; char *p, *q; char buf[100]; int nid, mval; long n_min, n_max; char *type, *value; const char *def; CONF_VALUE *v; X509_NAME *subj = X509_REQ_get_subject_name(req); if (!batch) { BIO_printf(bio_err, "You are about to be asked to enter information that will be incorporated\n"); BIO_printf(bio_err, "into your certificate request.\n"); BIO_printf(bio_err, "What you are about to enter is what is called a Distinguished Name or a DN.\n"); BIO_printf(bio_err, "There are quite a few fields but you can leave some blank\n"); BIO_printf(bio_err, "For some fields there will be a default value,\n"); BIO_printf(bio_err, "If you enter '.', the field will be left blank.\n"); BIO_printf(bio_err, "-----\n"); } if (sk_CONF_VALUE_num(dn_sk)) { i = -1; start: for (;;) { i++; if (sk_CONF_VALUE_num(dn_sk) <= i) break; v = sk_CONF_VALUE_value(dn_sk, i); p = q = NULL; type = v->name; if (!check_end(type, "_min") || !check_end(type, "_max") || !check_end(type, "_default") || !check_end(type, "_value")) continue; for (p = v->name; *p; p++) if ((*p == ':') || (*p == ',') || (*p == '.')) { p++; if (*p) type = p; break; } if (*type == '+') { mval = -1; type++; } else { mval = 0; } if ((nid = OBJ_txt2nid(type)) == NID_undef) goto start; if (!join(buf, sizeof(buf), v->name, "_default", "Name")) return 0; if ((def = app_conf_try_string(req_conf, dn_sect, buf)) == NULL) def = ""; if (!join(buf, sizeof(buf), v->name, "_value", "Name")) return 0; if ((value = app_conf_try_string(req_conf, dn_sect, buf)) == NULL) value = NULL; if (!join(buf, sizeof(buf), v->name, "_min", "Name")) return 0; if (!app_conf_try_number(req_conf, dn_sect, buf, &n_min)) n_min = -1; if (!join(buf, sizeof(buf), v->name, "_max", "Name")) return 0; if (!app_conf_try_number(req_conf, dn_sect, buf, &n_max)) n_max = -1; if (!add_DN_object(subj, v->value, def, value, nid, n_min, n_max, chtype, mval)) return 0; } if (X509_NAME_entry_count(subj) == 0) { BIO_printf(bio_err, "Error: No objects specified in config file\n"); return 0; } if (attribs) { if ((attr_sk != NULL) && (sk_CONF_VALUE_num(attr_sk) > 0) && (!batch)) { BIO_printf(bio_err, "\nPlease enter the following 'extra' attributes\n"); BIO_printf(bio_err, "to be sent with your certificate request\n"); } i = -1; start2: for (;;) { i++; if ((attr_sk == NULL) || (sk_CONF_VALUE_num(attr_sk) <= i)) break; v = sk_CONF_VALUE_value(attr_sk, i); type = v->name; if ((nid = OBJ_txt2nid(type)) == NID_undef) goto start2; if (!join(buf, sizeof(buf), type, "_default", "Name")) return 0; def = app_conf_try_string(req_conf, attr_sect, buf); if (def == NULL) def = ""; if (!join(buf, sizeof(buf), type, "_value", "Name")) return 0; value = app_conf_try_string(req_conf, attr_sect, buf); if (!join(buf, sizeof(buf), type, "_min", "Name")) return 0; if (!app_conf_try_number(req_conf, attr_sect, buf, &n_min)) n_min = -1; if (!join(buf, sizeof(buf), type, "_max", "Name")) return 0; if (!app_conf_try_number(req_conf, attr_sect, buf, &n_max)) n_max = -1; if (!add_attribute_object(req, v->value, def, value, nid, n_min, n_max, chtype)) return 0; } } } else { BIO_printf(bio_err, "No template, please set one up.\n"); return 0; } return 1; } static int auto_info(X509_REQ *req, STACK_OF(CONF_VALUE) *dn_sk, STACK_OF(CONF_VALUE) *attr_sk, int attribs, unsigned long chtype) { int i, spec_char, plus_char; char *p, *q; char *type; CONF_VALUE *v; X509_NAME *subj; subj = X509_REQ_get_subject_name(req); for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) { int mval; v = sk_CONF_VALUE_value(dn_sk, i); p = q = NULL; type = v->name; for (p = v->name; *p; p++) { #ifndef CHARSET_EBCDIC spec_char = (*p == ':' || *p == ',' || *p == '.'); #else spec_char = (*p == os_toascii[':'] || *p == os_toascii[','] || *p == os_toascii['.']); #endif if (spec_char) { p++; if (*p) type = p; break; } } #ifndef CHARSET_EBCDIC plus_char = (*type == '+'); #else plus_char = (*type == os_toascii['+']); #endif if (plus_char) { type++; mval = -1; } else { mval = 0; } if (!X509_NAME_add_entry_by_txt(subj, type, chtype, (unsigned char *)v->value, -1, -1, mval)) return 0; } if (!X509_NAME_entry_count(subj)) { BIO_printf(bio_err, "Error: No objects specified in config file\n"); return 0; } if (attribs) { for (i = 0; i < sk_CONF_VALUE_num(attr_sk); i++) { v = sk_CONF_VALUE_value(attr_sk, i); if (!X509_REQ_add1_attr_by_txt(req, v->name, chtype, (unsigned char *)v->value, -1)) return 0; } } return 1; } static int add_DN_object(X509_NAME *n, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype, int mval) { int ret = 0; char buf[1024]; ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf), "DN value", "DN default"); if ((ret == 0) || (ret == 1)) return ret; ret = 1; if (!X509_NAME_add_entry_by_NID(n, nid, chtype, (unsigned char *)buf, -1, -1, mval)) ret = 0; return ret; } static int add_attribute_object(X509_REQ *req, char *text, const char *def, char *value, int nid, int n_min, int n_max, unsigned long chtype) { int ret = 0; char buf[1024]; ret = build_data(text, def, value, n_min, n_max, buf, sizeof(buf), "Attribute value", "Attribute default"); if ((ret == 0) || (ret == 1)) return ret; ret = 1; if (!X509_REQ_add1_attr_by_NID(req, nid, chtype, (unsigned char *)buf, -1)) { BIO_printf(bio_err, "Error adding attribute\n"); ret = 0; } return ret; } static int build_data(char *text, const char *def, char *value, int n_min, int n_max, char *buf, const int buf_size, const char *desc1, const char *desc2) { int i; start: if (!batch) BIO_printf(bio_err, "%s [%s]:", text, def); (void)BIO_flush(bio_err); if (value != NULL) { if (!join(buf, buf_size, value, "\n", desc1)) return 0; BIO_printf(bio_err, "%s\n", value); } else { buf[0] = '\0'; if (!batch) { if (!fgets(buf, buf_size, stdin)) return 0; } else { buf[0] = '\n'; buf[1] = '\0'; } } if (buf[0] == '\0') return 0; if (buf[0] == '\n') { if ((def == NULL) || (def[0] == '\0')) return 1; if (!join(buf, buf_size, def, "\n", desc2)) return 0; } else if ((buf[0] == '.') && (buf[1] == '\n')) { return 1; } i = strlen(buf); if (buf[i - 1] != '\n') { BIO_printf(bio_err, "Missing newline at end of input\n"); return 0; } buf[--i] = '\0'; #ifdef CHARSET_EBCDIC ebcdic2ascii(buf, buf, i); #endif if (!req_check_len(i, n_min, n_max)) { if (batch || value) return 0; goto start; } return 2; } static int req_check_len(int len, int n_min, int n_max) { if (n_min > 0 && len < n_min) { BIO_printf(bio_err, "String too short, must be at least %d bytes long\n", n_min); return 0; } if (n_max >= 0 && len > n_max) { BIO_printf(bio_err, "String too long, must be at most %d bytes long\n", n_max); return 0; } return 1; } static int check_end(const char *str, const char *end) { size_t elen, slen; const char *tmp; elen = strlen(end); slen = strlen(str); if (elen > slen) return 1; tmp = str + slen - elen; return strcmp(tmp, end); } static int join(char buf[], size_t buf_size, const char *name, const char *tail, const char *desc) { const size_t name_len = strlen(name), tail_len = strlen(tail); if (name_len + tail_len + 1 > buf_size) { BIO_printf(bio_err, "%s '%s' too long\n", desc, name); return 0; } memcpy(buf, name, name_len); memcpy(buf + name_len, tail, tail_len + 1); return 1; } static EVP_PKEY_CTX *set_keygen_ctx(const char *gstr, char **pkeytype, long *pkeylen, ENGINE *keygen_engine) { EVP_PKEY_CTX *gctx = NULL; EVP_PKEY *param = NULL; long keylen = -1; BIO *pbio = NULL; const char *keytype = NULL; size_t keytypelen = 0; int expect_paramfile = 0; const char *paramfile = NULL; if (gstr == NULL) { keytype = "RSA"; keylen = *pkeylen; } else if (gstr[0] >= '0' && gstr[0] <= '9') { keytype = "RSA"; } else { const char *p = strchr(gstr, ':'); int len; if (p != NULL) len = p - gstr; else len = strlen(gstr); if (strncmp(gstr, "param", len) == 0) { expect_paramfile = 1; if (p == NULL) { BIO_printf(bio_err, "Parameter file requested but no path given: %s\n", gstr); return NULL; } } else { keytype = gstr; keytypelen = len; } if (p != NULL) gstr = gstr + len + 1; else gstr = NULL; } if (gstr != NULL) { if (!expect_paramfile && gstr[0] >= '0' && gstr[0] <= '9') keylen = atol(gstr); else paramfile = gstr; } if (paramfile != NULL) { pbio = BIO_new_file(paramfile, "r"); if (pbio == NULL) { BIO_printf(bio_err, "Cannot open parameter file %s\n", paramfile); return NULL; } param = PEM_read_bio_Parameters(pbio, NULL); if (param == NULL) { X509 *x; (void)BIO_reset(pbio); x = PEM_read_bio_X509(pbio, NULL, NULL, NULL); if (x != NULL) { param = X509_get_pubkey(x); X509_free(x); } } BIO_free(pbio); if (param == NULL) { BIO_printf(bio_err, "Error reading parameter file %s\n", paramfile); return NULL; } if (keytype == NULL) { keytype = EVP_PKEY_get0_type_name(param); if (keytype == NULL) { EVP_PKEY_free(param); BIO_puts(bio_err, "Unable to determine key type\n"); return NULL; } } } if (keytypelen > 0) *pkeytype = OPENSSL_strndup(keytype, keytypelen); else *pkeytype = OPENSSL_strdup(keytype); if (*pkeytype == NULL) { BIO_printf(bio_err, "Out of memory\n"); EVP_PKEY_free(param); return NULL; } if (keylen >= 0) *pkeylen = keylen; if (param != NULL) { if (!EVP_PKEY_is_a(param, *pkeytype)) { BIO_printf(bio_err, "Key type does not match parameters\n"); EVP_PKEY_free(param); return NULL; } if (keygen_engine != NULL) gctx = EVP_PKEY_CTX_new(param, keygen_engine); else gctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), param, app_get0_propq()); *pkeylen = EVP_PKEY_get_bits(param); EVP_PKEY_free(param); } else { if (keygen_engine != NULL) { int pkey_id = get_legacy_pkey_id(app_get0_libctx(), *pkeytype, keygen_engine); if (pkey_id != NID_undef) gctx = EVP_PKEY_CTX_new_id(pkey_id, keygen_engine); } else { gctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), *pkeytype, app_get0_propq()); } } if (gctx == NULL) { BIO_puts(bio_err, "Error allocating keygen context\n"); return NULL; } if (EVP_PKEY_keygen_init(gctx) <= 0) { BIO_puts(bio_err, "Error initializing keygen context\n"); EVP_PKEY_CTX_free(gctx); return NULL; } if (keylen == -1 && (EVP_PKEY_CTX_is_a(gctx, "RSA") || EVP_PKEY_CTX_is_a(gctx, "RSA-PSS"))) keylen = *pkeylen; if (keylen != -1) { OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; size_t bits = keylen; params[0] = OSSL_PARAM_construct_size_t(OSSL_PKEY_PARAM_BITS, &bits); if (EVP_PKEY_CTX_set_params(gctx, params) <= 0) { BIO_puts(bio_err, "Error setting keysize\n"); EVP_PKEY_CTX_free(gctx); return NULL; } } return gctx; }
apps
openssl/apps/req.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pkcs7.h> #include <openssl/pem.h> typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_NOOUT, OPT_TEXT, OPT_PRINT, OPT_PRINT_CERTS, OPT_QUIET, OPT_ENGINE, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS pkcs7_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"}, OPT_SECTION("Output"), {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, {"out", OPT_OUT, '>', "Output file"}, {"noout", OPT_NOOUT, '-', "Don't output encoded data"}, {"text", OPT_TEXT, '-', "Print full details of certificates"}, {"print", OPT_PRINT, '-', "Print out all fields of the PKCS7 structure"}, {"print_certs", OPT_PRINT_CERTS, '-', "Print_certs print any certs or crl in the input"}, {"quiet", OPT_QUIET, '-', "When used with -print_certs, it produces a cleaner output"}, OPT_PROV_OPTIONS, {NULL} }; int pkcs7_main(int argc, char **argv) { ENGINE *e = NULL; PKCS7 *p7 = NULL, *p7i; BIO *in = NULL, *out = NULL; int informat = FORMAT_PEM, outformat = FORMAT_PEM; char *infile = NULL, *outfile = NULL, *prog; int i, print_certs = 0, text = 0, noout = 0, p7_print = 0, quiet = 0, ret = 1; OPTION_CHOICE o; OSSL_LIB_CTX *libctx = app_get0_libctx(); prog = opt_init(argc, argv, pkcs7_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(pkcs7_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_NOOUT: noout = 1; break; case OPT_TEXT: text = 1; break; case OPT_PRINT: p7_print = 1; break; case OPT_PRINT_CERTS: print_certs = 1; break; case OPT_QUIET: quiet = 1; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; in = bio_open_default(infile, 'r', informat); if (in == NULL) goto end; p7 = PKCS7_new_ex(libctx, app_get0_propq()); if (p7 == NULL) { BIO_printf(bio_err, "unable to allocate PKCS7 object\n"); ERR_print_errors(bio_err); goto end; } if (informat == FORMAT_ASN1) p7i = d2i_PKCS7_bio(in, &p7); else p7i = PEM_read_bio_PKCS7(in, &p7, NULL, NULL); if (p7i == NULL) { BIO_printf(bio_err, "unable to load PKCS7 object\n"); ERR_print_errors(bio_err); goto end; } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (p7_print) PKCS7_print_ctx(out, p7, 0, NULL); if (print_certs) { STACK_OF(X509) *certs = NULL; STACK_OF(X509_CRL) *crls = NULL; i = OBJ_obj2nid(p7->type); switch (i) { case NID_pkcs7_signed: if (p7->d.sign != NULL) { certs = p7->d.sign->cert; crls = p7->d.sign->crl; } break; case NID_pkcs7_signedAndEnveloped: if (p7->d.signed_and_enveloped != NULL) { certs = p7->d.signed_and_enveloped->cert; crls = p7->d.signed_and_enveloped->crl; } break; default: break; } if (certs != NULL) { X509 *x; for (i = 0; i < sk_X509_num(certs); i++) { x = sk_X509_value(certs, i); if (text) X509_print(out, x); else if (!quiet) dump_cert_text(out, x); if (!noout) PEM_write_bio_X509(out, x); BIO_puts(out, "\n"); } } if (crls != NULL) { X509_CRL *crl; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); X509_CRL_print_ex(out, crl, get_nameopt()); if (!noout) PEM_write_bio_X509_CRL(out, crl); BIO_puts(out, "\n"); } } ret = 0; goto end; } if (!noout) { if (outformat == FORMAT_ASN1) i = i2d_PKCS7_bio(out, p7); else i = PEM_write_bio_PKCS7(out, p7); if (!i) { BIO_printf(bio_err, "unable to write pkcs7 object\n"); ERR_print_errors(bio_err); goto end; } } ret = 0; end: PKCS7_free(p7); release_engine(e); BIO_free(in); BIO_free_all(out); return ret; }
apps
openssl/apps/pkcs7.c
openssl
#include <openssl/opensslconf.h> #include "apps.h" #include "progs.h" #include <string.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/rsa.h> #define RSA_SIGN 1 #define RSA_VERIFY 2 #define RSA_ENCRYPT 3 #define RSA_DECRYPT 4 #define KEY_PRIVKEY 1 #define KEY_PUBKEY 2 #define KEY_CERT 3 typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_IN, OPT_OUT, OPT_ASN1PARSE, OPT_HEXDUMP, OPT_RSA_RAW, OPT_OAEP, OPT_PKCS, OPT_X931, OPT_SIGN, OPT_VERIFY, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT, OPT_PUBIN, OPT_CERTIN, OPT_INKEY, OPT_PASSIN, OPT_KEYFORM, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS rsautl_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"sign", OPT_SIGN, '-', "Sign with private key"}, {"verify", OPT_VERIFY, '-', "Verify with public key"}, {"encrypt", OPT_ENCRYPT, '-', "Encrypt with public key"}, {"decrypt", OPT_DECRYPT, '-', "Decrypt with private key"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"inkey", OPT_INKEY, 's', "Input key, by default an RSA private key"}, {"keyform", OPT_KEYFORM, 'E', "Private key format (ENGINE, other values ignored)"}, {"pubin", OPT_PUBIN, '-', "Input key is an RSA public pkey"}, {"certin", OPT_CERTIN, '-', "Input is a cert carrying an RSA public key"}, {"rev", OPT_REV, '-', "Reverse the order of the input buffer"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"raw", OPT_RSA_RAW, '-', "Use no padding"}, {"pkcs", OPT_PKCS, '-', "Use PKCS#1 v1.5 padding (default)"}, {"x931", OPT_X931, '-', "Use ANSI X9.31 padding"}, {"oaep", OPT_OAEP, '-', "Use PKCS#1 OAEP"}, {"asn1parse", OPT_ASN1PARSE, '-', "Run output through asn1parse; useful with -verify"}, {"hexdump", OPT_HEXDUMP, '-', "Hex dump output"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; int rsautl_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; ENGINE *e = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; X509 *x; char *infile = NULL, *outfile = NULL, *keyfile = NULL; char *passinarg = NULL, *passin = NULL, *prog; char rsa_mode = RSA_VERIFY, key_type = KEY_PRIVKEY; unsigned char *rsa_in = NULL, *rsa_out = NULL, pad = RSA_PKCS1_PADDING; size_t rsa_inlen, rsa_outlen = 0; int keyformat = FORMAT_UNDEF, keysize, ret = 1, rv; int hexdump = 0, asn1parse = 0, need_priv = 0, rev = 0; OPTION_CHOICE o; prog = opt_init(argc, argv, rsautl_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(rsautl_options); ret = 0; goto end; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_ASN1PARSE: asn1parse = 1; break; case OPT_HEXDUMP: hexdump = 1; break; case OPT_RSA_RAW: pad = RSA_NO_PADDING; break; case OPT_OAEP: pad = RSA_PKCS1_OAEP_PADDING; break; case OPT_PKCS: pad = RSA_PKCS1_PADDING; break; case OPT_X931: pad = RSA_X931_PADDING; break; case OPT_SIGN: rsa_mode = RSA_SIGN; need_priv = 1; break; case OPT_VERIFY: rsa_mode = RSA_VERIFY; break; case OPT_REV: rev = 1; break; case OPT_ENCRYPT: rsa_mode = RSA_ENCRYPT; break; case OPT_DECRYPT: rsa_mode = RSA_DECRYPT; need_priv = 1; break; case OPT_PUBIN: key_type = KEY_PUBKEY; break; case OPT_CERTIN: key_type = KEY_CERT; break; case OPT_INKEY: keyfile = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (need_priv && (key_type != KEY_PRIVKEY)) { BIO_printf(bio_err, "A private key is needed for this operation\n"); goto end; } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } switch (key_type) { case KEY_PRIVKEY: pkey = load_key(keyfile, keyformat, 0, passin, e, "private key"); break; case KEY_PUBKEY: pkey = load_pubkey(keyfile, keyformat, 0, NULL, e, "public key"); break; case KEY_CERT: x = load_cert(keyfile, FORMAT_UNDEF, "Certificate"); if (x) { pkey = X509_get_pubkey(x); X509_free(x); } break; } if (pkey == NULL) return 1; in = bio_open_default(infile, 'r', FORMAT_BINARY); if (in == NULL) goto end; out = bio_open_default(outfile, 'w', FORMAT_BINARY); if (out == NULL) goto end; keysize = EVP_PKEY_get_size(pkey); rsa_in = app_malloc(keysize * 2, "hold rsa key"); rsa_out = app_malloc(keysize, "output rsa key"); rsa_outlen = keysize; rv = BIO_read(in, rsa_in, keysize * 2); if (rv < 0) { BIO_printf(bio_err, "Error reading input Data\n"); goto end; } rsa_inlen = rv; if (rev) { size_t i; unsigned char ctmp; for (i = 0; i < rsa_inlen / 2; i++) { ctmp = rsa_in[i]; rsa_in[i] = rsa_in[rsa_inlen - 1 - i]; rsa_in[rsa_inlen - 1 - i] = ctmp; } } if ((ctx = EVP_PKEY_CTX_new_from_pkey(NULL, pkey, NULL)) == NULL) goto end; switch (rsa_mode) { case RSA_VERIFY: rv = EVP_PKEY_verify_recover_init(ctx) > 0 && EVP_PKEY_CTX_set_rsa_padding(ctx, pad) > 0 && EVP_PKEY_verify_recover(ctx, rsa_out, &rsa_outlen, rsa_in, rsa_inlen) > 0; break; case RSA_SIGN: rv = EVP_PKEY_sign_init(ctx) > 0 && EVP_PKEY_CTX_set_rsa_padding(ctx, pad) > 0 && EVP_PKEY_sign(ctx, rsa_out, &rsa_outlen, rsa_in, rsa_inlen) > 0; break; case RSA_ENCRYPT: rv = EVP_PKEY_encrypt_init(ctx) > 0 && EVP_PKEY_CTX_set_rsa_padding(ctx, pad) > 0 && EVP_PKEY_encrypt(ctx, rsa_out, &rsa_outlen, rsa_in, rsa_inlen) > 0; break; case RSA_DECRYPT: rv = EVP_PKEY_decrypt_init(ctx) > 0 && EVP_PKEY_CTX_set_rsa_padding(ctx, pad) > 0 && EVP_PKEY_decrypt(ctx, rsa_out, &rsa_outlen, rsa_in, rsa_inlen) > 0; break; } if (!rv) { BIO_printf(bio_err, "RSA operation error\n"); ERR_print_errors(bio_err); goto end; } ret = 0; if (asn1parse) { if (!ASN1_parse_dump(out, rsa_out, rsa_outlen, 1, -1)) { ERR_print_errors(bio_err); } } else if (hexdump) { BIO_dump(out, (char *)rsa_out, rsa_outlen); } else { BIO_write(out, rsa_out, rsa_outlen); } end: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); release_engine(e); BIO_free(in); BIO_free_all(out); OPENSSL_free(rsa_in); OPENSSL_free(rsa_out); OPENSSL_free(passin); return ret; }
apps
openssl/apps/rsautl.c
openssl
#include <stdio.h> #include <stdlib.h> #include "internal/common.h" #include <openssl/bio.h> #include <openssl/crypto.h> #include <openssl/trace.h> #include <openssl/lhash.h> #include <openssl/conf.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/ssl.h> #ifndef OPENSSL_NO_ENGINE # include <openssl/engine.h> #endif #include <openssl/err.h> #ifdef OPENSSL_SYS_VMS # include <unixio.h> #endif #include "apps.h" #include "progs.h" static LHASH_OF(FUNCTION) *prog_init(void); static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]); char *default_config_file = NULL; BIO *bio_in = NULL; BIO *bio_out = NULL; BIO *bio_err = NULL; static void warn_deprecated(const FUNCTION *fp) { if (fp->deprecated_version != NULL) BIO_printf(bio_err, "The command %s was deprecated in version %s.", fp->name, fp->deprecated_version); else BIO_printf(bio_err, "The command %s is deprecated.", fp->name); if (strcmp(fp->deprecated_alternative, DEPRECATED_NO_ALTERNATIVE) != 0) BIO_printf(bio_err, " Use '%s' instead.", fp->deprecated_alternative); BIO_printf(bio_err, "\n"); } static int apps_startup(void) { const char *use_libctx = NULL; #ifdef SIGPIPE signal(SIGPIPE, SIG_IGN); #endif if (!OPENSSL_init_ssl(OPENSSL_INIT_ENGINE_ALL_BUILTIN | OPENSSL_INIT_LOAD_CONFIG, NULL)) return 0; (void)setup_ui_method(); (void)setup_engine_loader(); use_libctx = getenv("OPENSSL_TEST_LIBCTX"); if (use_libctx != NULL) { if (strcmp(use_libctx, "1") == 0) { if (app_create_libctx() == NULL) return 0; } } return 1; } static void apps_shutdown(void) { app_providers_cleanup(); OSSL_LIB_CTX_free(app_get0_libctx()); destroy_engine_loader(); destroy_ui_method(); } #ifndef OPENSSL_NO_TRACE typedef struct tracedata_st { BIO *bio; unsigned int ingroup:1; } tracedata; static size_t internal_trace_cb(const char *buf, size_t cnt, int category, int cmd, void *vdata) { int ret = 0; tracedata *trace_data = vdata; char buffer[256], *hex; CRYPTO_THREAD_ID tid; switch (cmd) { case OSSL_TRACE_CTRL_BEGIN: if (trace_data->ingroup) { BIO_printf(bio_err, "ERROR: tracing already started\n"); return 0; } trace_data->ingroup = 1; tid = CRYPTO_THREAD_get_current_id(); hex = OPENSSL_buf2hexstr((const unsigned char *)&tid, sizeof(tid)); BIO_snprintf(buffer, sizeof(buffer), "TRACE[%s]:%s: ", hex == NULL ? "<null>" : hex, OSSL_trace_get_category_name(category)); OPENSSL_free(hex); BIO_set_prefix(trace_data->bio, buffer); break; case OSSL_TRACE_CTRL_WRITE: if (!trace_data->ingroup) { BIO_printf(bio_err, "ERROR: writing when tracing not started\n"); return 0; } ret = BIO_write(trace_data->bio, buf, cnt); break; case OSSL_TRACE_CTRL_END: if (!trace_data->ingroup) { BIO_printf(bio_err, "ERROR: finishing when tracing not started\n"); return 0; } trace_data->ingroup = 0; BIO_set_prefix(trace_data->bio, NULL); break; } return ret < 0 ? 0 : ret; } DEFINE_STACK_OF(tracedata) static STACK_OF(tracedata) *trace_data_stack; static void tracedata_free(tracedata *data) { BIO_free_all(data->bio); OPENSSL_free(data); } static void cleanup_trace(void) { sk_tracedata_pop_free(trace_data_stack, tracedata_free); } static void setup_trace_category(int category) { BIO *channel; tracedata *trace_data; BIO *bio = NULL; if (OSSL_trace_enabled(category)) return; bio = BIO_new(BIO_f_prefix()); channel = BIO_push(bio, dup_bio_err(FORMAT_TEXT)); trace_data = OPENSSL_zalloc(sizeof(*trace_data)); if (trace_data == NULL || bio == NULL || (trace_data->bio = channel) == NULL || OSSL_trace_set_callback(category, internal_trace_cb, trace_data) == 0 || sk_tracedata_push(trace_data_stack, trace_data) == 0) { fprintf(stderr, "warning: unable to setup trace callback for category '%s'.\n", OSSL_trace_get_category_name(category)); OSSL_trace_set_callback(category, NULL, NULL); BIO_free_all(channel); } } static void setup_trace(const char *str) { char *val; atexit(cleanup_trace); trace_data_stack = sk_tracedata_new_null(); val = OPENSSL_strdup(str); if (val != NULL) { char *valp = val; char *item; for (valp = val; (item = strtok(valp, ",")) != NULL; valp = NULL) { int category = OSSL_trace_get_category_num(item); if (category == OSSL_TRACE_CATEGORY_ALL) { while (++category < OSSL_TRACE_CATEGORY_NUM) setup_trace_category(category); break; } else if (category > 0) { setup_trace_category(category); } else { fprintf(stderr, "warning: unknown trace category: '%s'.\n", item); } } } OPENSSL_free(val); } #endif static char *help_argv[] = { "help", NULL }; static char *version_argv[] = { "version", NULL }; int main(int argc, char *argv[]) { FUNCTION f, *fp; LHASH_OF(FUNCTION) *prog = NULL; char *pname; const char *fname; ARGS arg; int global_help = 0; int global_version = 0; int ret = 0; arg.argv = NULL; arg.size = 0; bio_in = dup_bio_in(FORMAT_TEXT); bio_out = dup_bio_out(FORMAT_TEXT); bio_err = dup_bio_err(FORMAT_TEXT); #if defined(OPENSSL_SYS_VMS) && defined(__DECC) argv = copy_argv(&argc, argv); #elif defined(_WIN32) win32_utf8argv(&argc, &argv); #endif #ifndef OPENSSL_NO_TRACE setup_trace(getenv("OPENSSL_TRACE")); #endif if ((fname = "apps_startup", !apps_startup()) || (fname = "prog_init", (prog = prog_init()) == NULL)) { BIO_printf(bio_err, "FATAL: Startup failure (dev note: %s()) for %s\n", fname, argv[0]); ERR_print_errors(bio_err); ret = 1; goto end; } pname = opt_progname(argv[0]); default_config_file = CONF_get1_default_config_file(); if (default_config_file == NULL) app_bail_out("%s: could not get default config file\n", pname); f.name = pname; fp = lh_FUNCTION_retrieve(prog, &f); if (fp == NULL) { global_help = argc > 1 && (strcmp(argv[1], "-help") == 0 || strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--h") == 0); global_version = argc > 1 && (strcmp(argv[1], "-version") == 0 || strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-v") == 0 || strcmp(argv[1], "--v") == 0); argc--; argv++; opt_appname(argc == 1 || global_help ? "help" : global_version ? "version" : argv[0]); } else { argv[0] = pname; } ret = (argc == 0) || global_help ? do_cmd(prog, 1, help_argv) : global_version ? do_cmd(prog, 1, version_argv) : do_cmd(prog, argc, argv); end: OPENSSL_free(default_config_file); lh_FUNCTION_free(prog); OPENSSL_free(arg.argv); if (!app_RAND_write()) ret = EXIT_FAILURE; BIO_free(bio_in); BIO_free_all(bio_out); apps_shutdown(); BIO_free_all(bio_err); EXIT(ret); } typedef enum HELP_CHOICE { OPT_hERR = -1, OPT_hEOF = 0, OPT_hHELP } HELP_CHOICE; const OPTIONS help_options[] = { {OPT_HELP_STR, 1, '-', "Usage: help [options] [command]\n"}, OPT_SECTION("General"), {"help", OPT_hHELP, '-', "Display this summary"}, OPT_PARAMETERS(), {"command", 0, 0, "Name of command to display help (optional)"}, {NULL} }; int help_main(int argc, char **argv) { FUNCTION *fp; int i, nl; FUNC_TYPE tp; char *prog; HELP_CHOICE o; DISPLAY_COLUMNS dc; char *new_argv[3]; prog = opt_init(argc, argv, help_options); while ((o = opt_next()) != OPT_hEOF) { switch (o) { case OPT_hERR: case OPT_hEOF: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); return 1; case OPT_hHELP: opt_help(help_options); return 0; } } if (opt_num_rest() == 1) { new_argv[0] = opt_rest()[0]; new_argv[1] = "--help"; new_argv[2] = NULL; return do_cmd(prog_init(), 2, new_argv); } if (!opt_check_rest_arg(NULL)) { BIO_printf(bio_err, "Usage: %s\n", prog); return 1; } calculate_columns(functions, &dc); BIO_printf(bio_err, "%s:\n\nStandard commands", prog); i = 0; tp = FT_none; for (fp = functions; fp->name != NULL; fp++) { nl = 0; if (i++ % dc.columns == 0) { BIO_printf(bio_err, "\n"); nl = 1; } if (fp->type != tp) { tp = fp->type; if (!nl) BIO_printf(bio_err, "\n"); if (tp == FT_md) { i = 1; BIO_printf(bio_err, "\nMessage Digest commands (see the `dgst' command for more details)\n"); } else if (tp == FT_cipher) { i = 1; BIO_printf(bio_err, "\nCipher commands (see the `enc' command for more details)\n"); } } BIO_printf(bio_err, "%-*s", dc.width, fp->name); } BIO_printf(bio_err, "\n\n"); return 0; } static int do_cmd(LHASH_OF(FUNCTION) *prog, int argc, char *argv[]) { FUNCTION f, *fp; if (argc <= 0 || argv[0] == NULL) return 0; memset(&f, 0, sizeof(f)); f.name = argv[0]; fp = lh_FUNCTION_retrieve(prog, &f); if (fp == NULL) { if (EVP_get_digestbyname(argv[0])) { f.type = FT_md; f.func = dgst_main; fp = &f; } else if (EVP_get_cipherbyname(argv[0])) { f.type = FT_cipher; f.func = enc_main; fp = &f; } } if (fp != NULL) { if (fp->deprecated_alternative != NULL) warn_deprecated(fp); return fp->func(argc, argv); } f.name = argv[0]; if (CHECK_AND_SKIP_PREFIX(f.name, "no-")) { if (lh_FUNCTION_retrieve(prog, &f) == NULL) { BIO_printf(bio_out, "%s\n", argv[0]); return 0; } BIO_printf(bio_out, "%s\n", argv[0] + 3); return 1; } BIO_printf(bio_err, "Invalid command '%s'; type \"help\" for a list.\n", argv[0]); return 1; } static int function_cmp(const FUNCTION *a, const FUNCTION *b) { return strncmp(a->name, b->name, 8); } static unsigned long function_hash(const FUNCTION *a) { return OPENSSL_LH_strhash(a->name); } static int SortFnByName(const void *_f1, const void *_f2) { const FUNCTION *f1 = _f1; const FUNCTION *f2 = _f2; if (f1->type != f2->type) return f1->type - f2->type; return strcmp(f1->name, f2->name); } static LHASH_OF(FUNCTION) *prog_init(void) { static LHASH_OF(FUNCTION) *ret = NULL; static int prog_inited = 0; FUNCTION *f; size_t i; if (prog_inited) return ret; prog_inited = 1; for (i = 0, f = functions; f->name != NULL; ++f, ++i) ; qsort(functions, i, sizeof(*functions), SortFnByName); if ((ret = lh_FUNCTION_new(function_hash, function_cmp)) == NULL) return NULL; for (f = functions; f->name != NULL; f++) (void)lh_FUNCTION_insert(ret, f); return ret; }
apps
openssl/apps/openssl.c
openssl
#include "apps.h" #include "progs.h" #include <string.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/evp.h> #include <sys/stat.h> #define KEY_NONE 0 #define KEY_PRIVKEY 1 #define KEY_PUBKEY 2 #define KEY_CERT 3 static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize, const char *keyfile, int keyform, int key_type, char *passinarg, int pkey_op, ENGINE *e, const int impl, int rawin, EVP_PKEY **ppkey, EVP_MD_CTX *mctx, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq); static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file, ENGINE *e); static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op, unsigned char *out, size_t *poutlen, const unsigned char *in, size_t inlen); static int do_raw_keyop(int pkey_op, EVP_MD_CTX *mctx, EVP_PKEY *pkey, BIO *in, int filesize, unsigned char *sig, int siglen, unsigned char **out, size_t *poutlen); typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_ENGINE_IMPL, OPT_IN, OPT_OUT, OPT_PUBIN, OPT_CERTIN, OPT_ASN1PARSE, OPT_HEXDUMP, OPT_SIGN, OPT_VERIFY, OPT_VERIFYRECOVER, OPT_REV, OPT_ENCRYPT, OPT_DECRYPT, OPT_DERIVE, OPT_SIGFILE, OPT_INKEY, OPT_PEERKEY, OPT_PASSIN, OPT_PEERFORM, OPT_KEYFORM, OPT_PKEYOPT, OPT_PKEYOPT_PASSIN, OPT_KDF, OPT_KDFLEN, OPT_R_ENUM, OPT_PROV_ENUM, OPT_CONFIG, OPT_RAWIN, OPT_DIGEST } OPTION_CHOICE; const OPTIONS pkeyutl_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, {"engine_impl", OPT_ENGINE_IMPL, '-', "Also use engine given by -engine for crypto operations"}, #endif {"sign", OPT_SIGN, '-', "Sign input data with private key"}, {"verify", OPT_VERIFY, '-', "Verify with public key"}, {"encrypt", OPT_ENCRYPT, '-', "Encrypt input data with public key"}, {"decrypt", OPT_DECRYPT, '-', "Decrypt input data with private key"}, {"derive", OPT_DERIVE, '-', "Derive shared secret"}, OPT_CONFIG_OPTION, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file - default stdin"}, {"rawin", OPT_RAWIN, '-', "Indicate the input data is in raw form"}, {"inkey", OPT_INKEY, 's', "Input key, by default private key"}, {"pubin", OPT_PUBIN, '-', "Input key is a public key"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"peerkey", OPT_PEERKEY, 's', "Peer key file used in key derivation"}, {"peerform", OPT_PEERFORM, 'E', "Peer key format (DER/PEM/P12/ENGINE)"}, {"certin", OPT_CERTIN, '-', "Input is a cert with a public key"}, {"rev", OPT_REV, '-', "Reverse the order of the input buffer"}, {"sigfile", OPT_SIGFILE, '<', "Signature file (verify operation only)"}, {"keyform", OPT_KEYFORM, 'E', "Private key format (ENGINE, other values ignored)"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file - default stdout"}, {"asn1parse", OPT_ASN1PARSE, '-', "asn1parse the output data"}, {"hexdump", OPT_HEXDUMP, '-', "Hex dump output"}, {"verifyrecover", OPT_VERIFYRECOVER, '-', "Verify with public key, recover original data"}, OPT_SECTION("Signing/Derivation"), {"digest", OPT_DIGEST, 's', "Specify the digest algorithm when signing the raw input data"}, {"pkeyopt", OPT_PKEYOPT, 's', "Public key options as opt:value"}, {"pkeyopt_passin", OPT_PKEYOPT_PASSIN, 's', "Public key option that is read as a passphrase argument opt:passphrase"}, {"kdf", OPT_KDF, 's', "Use KDF algorithm"}, {"kdflen", OPT_KDFLEN, 'p', "KDF algorithm output length"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; int pkeyutl_main(int argc, char **argv) { CONF *conf = NULL; BIO *in = NULL, *out = NULL; ENGINE *e = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; char *infile = NULL, *outfile = NULL, *sigfile = NULL, *passinarg = NULL; char hexdump = 0, asn1parse = 0, rev = 0, *prog; unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL; OPTION_CHOICE o; int buf_inlen = 0, siglen = -1; int keyform = FORMAT_UNDEF, peerform = FORMAT_UNDEF; int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY; int engine_impl = 0; int ret = 1, rv = -1; size_t buf_outlen; const char *inkey = NULL; const char *peerkey = NULL; const char *kdfalg = NULL, *digestname = NULL; int kdflen = 0; STACK_OF(OPENSSL_STRING) *pkeyopts = NULL; STACK_OF(OPENSSL_STRING) *pkeyopts_passin = NULL; int rawin = 0; EVP_MD_CTX *mctx = NULL; EVP_MD *md = NULL; int filesize = -1; OSSL_LIB_CTX *libctx = app_get0_libctx(); prog = opt_init(argc, argv, pkeyutl_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(pkeyutl_options); ret = 0; goto end; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_SIGFILE: sigfile = opt_arg(); break; case OPT_ENGINE_IMPL: engine_impl = 1; break; case OPT_INKEY: inkey = opt_arg(); break; case OPT_PEERKEY: peerkey = opt_arg(); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_PEERFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &peerform)) goto opthelp; break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform)) goto opthelp; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_CONFIG: conf = app_load_config_modules(opt_arg()); if (conf == NULL) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PUBIN: key_type = KEY_PUBKEY; break; case OPT_CERTIN: key_type = KEY_CERT; break; case OPT_ASN1PARSE: asn1parse = 1; break; case OPT_HEXDUMP: hexdump = 1; break; case OPT_SIGN: pkey_op = EVP_PKEY_OP_SIGN; break; case OPT_VERIFY: pkey_op = EVP_PKEY_OP_VERIFY; break; case OPT_VERIFYRECOVER: pkey_op = EVP_PKEY_OP_VERIFYRECOVER; break; case OPT_ENCRYPT: pkey_op = EVP_PKEY_OP_ENCRYPT; break; case OPT_DECRYPT: pkey_op = EVP_PKEY_OP_DECRYPT; break; case OPT_DERIVE: pkey_op = EVP_PKEY_OP_DERIVE; break; case OPT_KDF: pkey_op = EVP_PKEY_OP_DERIVE; key_type = KEY_NONE; kdfalg = opt_arg(); break; case OPT_KDFLEN: kdflen = atoi(opt_arg()); break; case OPT_REV: rev = 1; break; case OPT_PKEYOPT: if ((pkeyopts == NULL && (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) || sk_OPENSSL_STRING_push(pkeyopts, opt_arg()) == 0) { BIO_puts(bio_err, "out of memory\n"); goto end; } break; case OPT_PKEYOPT_PASSIN: if ((pkeyopts_passin == NULL && (pkeyopts_passin = sk_OPENSSL_STRING_new_null()) == NULL) || sk_OPENSSL_STRING_push(pkeyopts_passin, opt_arg()) == 0) { BIO_puts(bio_err, "out of memory\n"); goto end; } break; case OPT_RAWIN: rawin = 1; break; case OPT_DIGEST: digestname = opt_arg(); break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (rawin && pkey_op != EVP_PKEY_OP_SIGN && pkey_op != EVP_PKEY_OP_VERIFY) { BIO_printf(bio_err, "%s: -rawin can only be used with -sign or -verify\n", prog); goto opthelp; } if (digestname != NULL && !rawin) { BIO_printf(bio_err, "%s: -digest can only be used with -rawin\n", prog); goto opthelp; } if (rawin && rev) { BIO_printf(bio_err, "%s: -rev cannot be used with raw input\n", prog); goto opthelp; } if (kdfalg != NULL) { if (kdflen == 0) { BIO_printf(bio_err, "%s: no KDF length given (-kdflen parameter).\n", prog); goto opthelp; } } else if (inkey == NULL) { BIO_printf(bio_err, "%s: no private key given (-inkey parameter).\n", prog); goto opthelp; } else if (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE) { BIO_printf(bio_err, "%s: no peer key given (-peerkey parameter).\n", prog); goto opthelp; } if (rawin) { if ((mctx = EVP_MD_CTX_new()) == NULL) { BIO_printf(bio_err, "Error: out of memory\n"); goto end; } } ctx = init_ctx(kdfalg, &keysize, inkey, keyform, key_type, passinarg, pkey_op, e, engine_impl, rawin, &pkey, mctx, digestname, libctx, app_get0_propq()); if (ctx == NULL) { BIO_printf(bio_err, "%s: Error initializing context\n", prog); goto end; } if (peerkey != NULL && !setup_peer(ctx, peerform, peerkey, e)) { BIO_printf(bio_err, "%s: Error setting up peer key\n", prog); goto end; } if (pkeyopts != NULL) { int num = sk_OPENSSL_STRING_num(pkeyopts); int i; for (i = 0; i < num; ++i) { const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i); if (pkey_ctrl_string(ctx, opt) <= 0) { BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n", prog, opt); goto end; } } } if (pkeyopts_passin != NULL) { int num = sk_OPENSSL_STRING_num(pkeyopts_passin); int i; for (i = 0; i < num; i++) { char *opt = sk_OPENSSL_STRING_value(pkeyopts_passin, i); char *passin = strchr(opt, ':'); char *passwd; if (passin == NULL) { char passwd_buf[4096]; int r; BIO_snprintf(passwd_buf, sizeof(passwd_buf), "Enter %s: ", opt); r = EVP_read_pw_string(passwd_buf, sizeof(passwd_buf) - 1, passwd_buf, 0); if (r < 0) { if (r == -2) BIO_puts(bio_err, "user abort\n"); else BIO_puts(bio_err, "entry failed\n"); goto end; } passwd = OPENSSL_strdup(passwd_buf); if (passwd == NULL) { BIO_puts(bio_err, "out of memory\n"); goto end; } } else { *passin = 0; passin++; if (app_passwd(passin, NULL, &passwd, NULL) == 0) { BIO_printf(bio_err, "failed to get '%s'\n", opt); goto end; } } if (EVP_PKEY_CTX_ctrl_str(ctx, opt, passwd) <= 0) { BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n", prog, opt); goto end; } OPENSSL_free(passwd); } } if (sigfile != NULL && (pkey_op != EVP_PKEY_OP_VERIFY)) { BIO_printf(bio_err, "%s: Signature file specified for non verify\n", prog); goto end; } if (sigfile == NULL && (pkey_op == EVP_PKEY_OP_VERIFY)) { BIO_printf(bio_err, "%s: No signature file specified for verify\n", prog); goto end; } if (pkey_op != EVP_PKEY_OP_DERIVE) { in = bio_open_default(infile, 'r', FORMAT_BINARY); if (infile != NULL) { struct stat st; if (stat(infile, &st) == 0 && st.st_size <= INT_MAX) filesize = (int)st.st_size; } if (in == NULL) goto end; } out = bio_open_default(outfile, 'w', FORMAT_BINARY); if (out == NULL) goto end; if (sigfile != NULL) { BIO *sigbio = BIO_new_file(sigfile, "rb"); if (sigbio == NULL) { 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 != NULL && !rawin) { buf_inlen = bio_to_mem(&buf_in, -1, in); if (buf_inlen < 0) { BIO_printf(bio_err, "Error reading input Data\n"); goto end; } 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 (!rawin && buf_inlen > EVP_MAX_MD_SIZE && (pkey_op == EVP_PKEY_OP_SIGN || pkey_op == EVP_PKEY_OP_VERIFY)) { BIO_printf(bio_err, "Error: The input data looks too long to be a hash\n"); goto end; } if (pkey_op == EVP_PKEY_OP_VERIFY) { if (rawin) { rv = do_raw_keyop(pkey_op, mctx, pkey, in, filesize, sig, siglen, NULL, 0); } else { 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"); } goto end; } if (rawin) { rv = do_raw_keyop(pkey_op, mctx, pkey, in, filesize, NULL, 0, &buf_out, (size_t *)&buf_outlen); } else { if (kdflen != 0) { buf_outlen = kdflen; rv = 1; } else { rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen, buf_in, (size_t)buf_inlen); } if (rv > 0 && buf_outlen != 0) { buf_out = app_malloc(buf_outlen, "buffer output"); rv = do_keyop(ctx, pkey_op, buf_out, (size_t *)&buf_outlen, buf_in, (size_t)buf_inlen); } } if (rv <= 0) { if (pkey_op != EVP_PKEY_OP_DERIVE) { BIO_puts(bio_err, "Public Key operation error\n"); } else { BIO_puts(bio_err, "Key derivation failed\n"); } 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 (ret != 0) ERR_print_errors(bio_err); EVP_MD_CTX_free(mctx); EVP_PKEY_CTX_free(ctx); EVP_MD_free(md); release_engine(e); BIO_free(in); BIO_free_all(out); OPENSSL_free(buf_in); OPENSSL_free(buf_out); OPENSSL_free(sig); sk_OPENSSL_STRING_free(pkeyopts); sk_OPENSSL_STRING_free(pkeyopts_passin); NCONF_free(conf); return ret; } static EVP_PKEY_CTX *init_ctx(const char *kdfalg, int *pkeysize, const char *keyfile, int keyform, int key_type, char *passinarg, int pkey_op, ENGINE *e, const int engine_impl, int rawin, EVP_PKEY **ppkey, EVP_MD_CTX *mctx, const char *digestname, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; ENGINE *impl = NULL; char *passin = NULL; int rv = -1; X509 *x; if (((pkey_op == EVP_PKEY_OP_SIGN) || (pkey_op == EVP_PKEY_OP_DECRYPT) || (pkey_op == EVP_PKEY_OP_DERIVE)) && (key_type != KEY_PRIVKEY && kdfalg == NULL)) { BIO_printf(bio_err, "A private key is needed for this operation\n"); goto end; } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } switch (key_type) { case KEY_PRIVKEY: pkey = load_key(keyfile, keyform, 0, passin, e, "private key"); break; case KEY_PUBKEY: pkey = load_pubkey(keyfile, keyform, 0, NULL, e, "public key"); break; case KEY_CERT: x = load_cert(keyfile, keyform, "Certificate"); if (x) { pkey = X509_get_pubkey(x); X509_free(x); } break; case KEY_NONE: break; } #ifndef OPENSSL_NO_ENGINE if (engine_impl) impl = e; #endif if (kdfalg != NULL) { int kdfnid = OBJ_sn2nid(kdfalg); if (kdfnid == NID_undef) { kdfnid = OBJ_ln2nid(kdfalg); if (kdfnid == NID_undef) { BIO_printf(bio_err, "The given KDF \"%s\" is unknown.\n", kdfalg); goto end; } } if (impl != NULL) ctx = EVP_PKEY_CTX_new_id(kdfnid, impl); else ctx = EVP_PKEY_CTX_new_from_name(libctx, kdfalg, propq); } else { if (pkey == NULL) goto end; *pkeysize = EVP_PKEY_get_size(pkey); if (impl != NULL) ctx = EVP_PKEY_CTX_new(pkey, impl); else ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (ppkey != NULL) *ppkey = pkey; EVP_PKEY_free(pkey); } if (ctx == NULL) goto end; if (rawin) { EVP_MD_CTX_set_pkey_ctx(mctx, ctx); switch (pkey_op) { case EVP_PKEY_OP_SIGN: rv = EVP_DigestSignInit_ex(mctx, NULL, digestname, libctx, propq, pkey, NULL); break; case EVP_PKEY_OP_VERIFY: rv = EVP_DigestVerifyInit_ex(mctx, NULL, digestname, libctx, propq, pkey, NULL); break; } } else { switch (pkey_op) { case EVP_PKEY_OP_SIGN: rv = EVP_PKEY_sign_init(ctx); break; case EVP_PKEY_OP_VERIFY: rv = EVP_PKEY_verify_init(ctx); break; case EVP_PKEY_OP_VERIFYRECOVER: rv = EVP_PKEY_verify_recover_init(ctx); break; case EVP_PKEY_OP_ENCRYPT: rv = EVP_PKEY_encrypt_init(ctx); break; case EVP_PKEY_OP_DECRYPT: rv = EVP_PKEY_decrypt_init(ctx); break; case EVP_PKEY_OP_DERIVE: rv = EVP_PKEY_derive_init(ctx); break; } } if (rv <= 0) { EVP_PKEY_CTX_free(ctx); ctx = NULL; } end: OPENSSL_free(passin); return ctx; } static int setup_peer(EVP_PKEY_CTX *ctx, int peerform, const char *file, ENGINE *e) { EVP_PKEY *peer = NULL; ENGINE *engine = NULL; int ret; if (peerform == FORMAT_ENGINE) engine = e; peer = load_pubkey(file, peerform, 0, NULL, engine, "peer key"); if (peer == NULL) { BIO_printf(bio_err, "Error reading peer key %s\n", file); return 0; } ret = EVP_PKEY_derive_set_peer(ctx, peer) > 0; EVP_PKEY_free(peer); return ret; } static int do_keyop(EVP_PKEY_CTX *ctx, int pkey_op, unsigned char *out, size_t *poutlen, const unsigned char *in, size_t inlen) { int rv = 0; switch (pkey_op) { case EVP_PKEY_OP_VERIFYRECOVER: rv = EVP_PKEY_verify_recover(ctx, out, poutlen, in, inlen); break; case EVP_PKEY_OP_SIGN: rv = EVP_PKEY_sign(ctx, out, poutlen, in, inlen); break; case EVP_PKEY_OP_ENCRYPT: rv = EVP_PKEY_encrypt(ctx, out, poutlen, in, inlen); break; case EVP_PKEY_OP_DECRYPT: rv = EVP_PKEY_decrypt(ctx, out, poutlen, in, inlen); break; case EVP_PKEY_OP_DERIVE: rv = EVP_PKEY_derive(ctx, out, poutlen); break; } return rv; } #define TBUF_MAXSIZE 2048 static int do_raw_keyop(int pkey_op, EVP_MD_CTX *mctx, EVP_PKEY *pkey, BIO *in, int filesize, unsigned char *sig, int siglen, unsigned char **out, size_t *poutlen) { int rv = 0; unsigned char tbuf[TBUF_MAXSIZE]; unsigned char *mbuf = NULL; int buf_len = 0; if (EVP_PKEY_get_id(pkey) == EVP_PKEY_ED25519 || EVP_PKEY_get_id(pkey) == EVP_PKEY_ED448) { if (filesize < 0) { BIO_printf(bio_err, "Error: unable to determine file size for oneshot operation\n"); goto end; } mbuf = app_malloc(filesize, "oneshot sign/verify buffer"); switch (pkey_op) { case EVP_PKEY_OP_VERIFY: buf_len = BIO_read(in, mbuf, filesize); if (buf_len != filesize) { BIO_printf(bio_err, "Error reading raw input data\n"); goto end; } rv = EVP_DigestVerify(mctx, sig, (size_t)siglen, mbuf, buf_len); break; case EVP_PKEY_OP_SIGN: buf_len = BIO_read(in, mbuf, filesize); if (buf_len != filesize) { BIO_printf(bio_err, "Error reading raw input data\n"); goto end; } rv = EVP_DigestSign(mctx, NULL, poutlen, mbuf, buf_len); if (rv == 1 && out != NULL) { *out = app_malloc(*poutlen, "buffer output"); rv = EVP_DigestSign(mctx, *out, poutlen, mbuf, buf_len); } break; } goto end; } switch (pkey_op) { case EVP_PKEY_OP_VERIFY: for (;;) { buf_len = BIO_read(in, tbuf, TBUF_MAXSIZE); if (buf_len == 0) break; if (buf_len < 0) { BIO_printf(bio_err, "Error reading raw input data\n"); goto end; } rv = EVP_DigestVerifyUpdate(mctx, tbuf, (size_t)buf_len); if (rv != 1) { BIO_printf(bio_err, "Error verifying raw input data\n"); goto end; } } rv = EVP_DigestVerifyFinal(mctx, sig, (size_t)siglen); break; case EVP_PKEY_OP_SIGN: for (;;) { buf_len = BIO_read(in, tbuf, TBUF_MAXSIZE); if (buf_len == 0) break; if (buf_len < 0) { BIO_printf(bio_err, "Error reading raw input data\n"); goto end; } rv = EVP_DigestSignUpdate(mctx, tbuf, (size_t)buf_len); if (rv != 1) { BIO_printf(bio_err, "Error signing raw input data\n"); goto end; } } rv = EVP_DigestSignFinal(mctx, NULL, poutlen); if (rv == 1 && out != NULL) { *out = app_malloc(*poutlen, "buffer output"); rv = EVP_DigestSignFinal(mctx, *out, poutlen); } break; } end: OPENSSL_free(mbuf); return rv; }
apps
openssl/apps/pkeyutl.c
openssl
#include <stdio.h> #include <string.h> #include <sys/types.h> #include "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pkcs7.h> #include <openssl/pem.h> #include <openssl/objects.h> static int add_certs_from_file(STACK_OF(X509) *stack, char *certfile); typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_NOCRL, OPT_CERTFILE, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS crl2pkcs7_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"inform", OPT_INFORM, 'F', "Input format - DER or PEM"}, {"nocrl", OPT_NOCRL, '-', "No crl to load, just certs from '-certfile'"}, {"certfile", OPT_CERTFILE, '<', "File of chain of certs to a trusted CA; can be repeated"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, OPT_PROV_OPTIONS, {NULL} }; int crl2pkcs7_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; PKCS7 *p7 = NULL; PKCS7_SIGNED *p7s = NULL; STACK_OF(OPENSSL_STRING) *certflst = NULL; STACK_OF(X509) *cert_stack = NULL; STACK_OF(X509_CRL) *crl_stack = NULL; X509_CRL *crl = NULL; char *infile = NULL, *outfile = NULL, *prog, *certfile; int i = 0, informat = FORMAT_PEM, outformat = FORMAT_PEM, ret = 1, nocrl = 0; OPTION_CHOICE o; prog = opt_init(argc, argv, crl2pkcs7_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(crl2pkcs7_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_NOCRL: nocrl = 1; break; case OPT_CERTFILE: if ((certflst == NULL) && (certflst = sk_OPENSSL_STRING_new_null()) == NULL) goto end; if (!sk_OPENSSL_STRING_push(certflst, opt_arg())) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!nocrl) { in = bio_open_default(infile, 'r', informat); if (in == NULL) goto end; if (informat == FORMAT_ASN1) crl = d2i_X509_CRL_bio(in, NULL); else if (informat == FORMAT_PEM) crl = PEM_read_bio_X509_CRL(in, NULL, NULL, NULL); if (crl == NULL) { BIO_printf(bio_err, "unable to load CRL\n"); ERR_print_errors(bio_err); goto end; } } if ((p7 = PKCS7_new()) == NULL) goto end; if ((p7s = PKCS7_SIGNED_new()) == NULL) goto end; p7->type = OBJ_nid2obj(NID_pkcs7_signed); p7->d.sign = p7s; p7s->contents->type = OBJ_nid2obj(NID_pkcs7_data); if (!ASN1_INTEGER_set(p7s->version, 1)) goto end; if (crl != NULL) { if ((crl_stack = sk_X509_CRL_new_null()) == NULL) goto end; p7s->crl = crl_stack; sk_X509_CRL_push(crl_stack, crl); crl = NULL; } if (certflst != NULL) { if ((cert_stack = sk_X509_new_null()) == NULL) goto end; p7s->cert = cert_stack; for (i = 0; i < sk_OPENSSL_STRING_num(certflst); i++) { certfile = sk_OPENSSL_STRING_value(certflst, i); if (add_certs_from_file(cert_stack, certfile) < 0) { BIO_printf(bio_err, "error loading certificates\n"); ERR_print_errors(bio_err); goto end; } } } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (outformat == FORMAT_ASN1) i = i2d_PKCS7_bio(out, p7); else if (outformat == FORMAT_PEM) i = PEM_write_bio_PKCS7(out, p7); if (!i) { BIO_printf(bio_err, "unable to write pkcs7 object\n"); ERR_print_errors(bio_err); goto end; } ret = 0; end: sk_OPENSSL_STRING_free(certflst); BIO_free(in); BIO_free_all(out); PKCS7_free(p7); X509_CRL_free(crl); return ret; } static int add_certs_from_file(STACK_OF(X509) *stack, char *certfile) { BIO *in = NULL; int count = 0; int ret = -1; STACK_OF(X509_INFO) *sk = NULL; X509_INFO *xi; in = BIO_new_file(certfile, "r"); if (in == NULL) { BIO_printf(bio_err, "error opening the file, %s\n", certfile); goto end; } sk = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL); if (sk == NULL) { BIO_printf(bio_err, "error reading the file, %s\n", certfile); goto end; } while (sk_X509_INFO_num(sk)) { xi = sk_X509_INFO_shift(sk); if (xi->x509 != NULL) { sk_X509_push(stack, xi->x509); xi->x509 = NULL; count++; } X509_INFO_free(xi); } ret = count; end: BIO_free(in); sk_X509_INFO_free(sk); return ret; }
apps
openssl/apps/crl2pkcs7.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_IN, OPT_OUTFORM, OPT_OUT, OPT_KEYFORM, OPT_KEY, OPT_ISSUER, OPT_LASTUPDATE, OPT_NEXTUPDATE, OPT_FINGERPRINT, OPT_CRLNUMBER, OPT_BADSIG, OPT_GENDELTA, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_VERIFY, OPT_DATEOPT, OPT_TEXT, OPT_HASH, OPT_HASH_OLD, OPT_NOOUT, OPT_NAMEOPT, OPT_MD, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS crl_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"verify", OPT_VERIFY, '-', "Verify CRL signature"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file - default stdin"}, {"inform", OPT_INFORM, 'F', "CRL input format (DER or PEM); has no effect"}, {"key", OPT_KEY, '<', "CRL signing Private key to use"}, {"keyform", OPT_KEYFORM, 'F', "Private key file format (DER/PEM/P12); has no effect"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "output file - default stdout"}, {"outform", OPT_OUTFORM, 'F', "Output format - default PEM"}, {"dateopt", OPT_DATEOPT, 's', "Datetime format used for printing. (rfc_822/iso_8601). Default is rfc_822."}, {"text", OPT_TEXT, '-', "Print out a text format version"}, {"hash", OPT_HASH, '-', "Print hash value"}, #ifndef OPENSSL_NO_MD5 {"hash_old", OPT_HASH_OLD, '-', "Print old-style (MD5) hash value"}, #endif {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"", OPT_MD, '-', "Any supported digest"}, OPT_SECTION("CRL"), {"issuer", OPT_ISSUER, '-', "Print issuer DN"}, {"lastupdate", OPT_LASTUPDATE, '-', "Set lastUpdate field"}, {"nextupdate", OPT_NEXTUPDATE, '-', "Set nextUpdate field"}, {"noout", OPT_NOOUT, '-', "No CRL output"}, {"fingerprint", OPT_FINGERPRINT, '-', "Print the crl fingerprint"}, {"crlnumber", OPT_CRLNUMBER, '-', "Print CRL number"}, {"badsig", OPT_BADSIG, '-', "Corrupt last byte of loaded CRL signature (for test)" }, {"gendelta", OPT_GENDELTA, '<', "Other CRL to compare/diff to the Input one"}, OPT_SECTION("Certificate"), {"CApath", OPT_CAPATH, '/', "Verify CRL using certificates in dir"}, {"CAfile", OPT_CAFILE, '<', "Verify CRL using certificates in file name"}, {"CAstore", OPT_CASTORE, ':', "Verify CRL using certificates in store URI"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, OPT_PROV_OPTIONS, {NULL} }; int crl_main(int argc, char **argv) { X509_CRL *x = NULL; BIO *out = NULL; X509_STORE *store = NULL; X509_STORE_CTX *ctx = NULL; X509_LOOKUP *lookup = NULL; X509_OBJECT *xobj = NULL; EVP_PKEY *pkey; EVP_MD *digest = (EVP_MD *)EVP_sha1(); char *infile = NULL, *outfile = NULL, *crldiff = NULL, *keyfile = NULL; char *digestname = NULL; const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL, *prog; OPTION_CHOICE o; int hash = 0, issuer = 0, lastupdate = 0, nextupdate = 0, noout = 0; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, keyformat = FORMAT_UNDEF; int ret = 1, num = 0, badsig = 0, fingerprint = 0, crlnumber = 0; int text = 0, do_ver = 0, noCAfile = 0, noCApath = 0, noCAstore = 0; unsigned long dateopt = ASN1_DTFLGS_RFC822; int i; #ifndef OPENSSL_NO_MD5 int hash_old = 0; #endif opt_set_unknown_name("digest"); prog = opt_init(argc, argv, crl_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(crl_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat)) goto opthelp; break; case OPT_KEY: keyfile = opt_arg(); break; case OPT_GENDELTA: crldiff = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); do_ver = 1; break; case OPT_CAFILE: CAfile = opt_arg(); do_ver = 1; break; case OPT_CASTORE: CAstore = opt_arg(); do_ver = 1; break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_HASH_OLD: #ifndef OPENSSL_NO_MD5 hash_old = ++num; #endif break; case OPT_VERIFY: do_ver = 1; break; case OPT_DATEOPT: if (!set_dateopt(&dateopt, opt_arg())) goto opthelp; break; case OPT_TEXT: text = 1; break; case OPT_HASH: hash = ++num; break; case OPT_ISSUER: issuer = ++num; break; case OPT_LASTUPDATE: lastupdate = ++num; break; case OPT_NEXTUPDATE: nextupdate = ++num; break; case OPT_NOOUT: noout = 1; break; case OPT_FINGERPRINT: fingerprint = ++num; break; case OPT_CRLNUMBER: crlnumber = ++num; break; case OPT_BADSIG: badsig = 1; break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto opthelp; break; case OPT_MD: digestname = opt_unknown(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!opt_md(digestname, &digest)) goto opthelp; x = load_crl(infile, informat, 1, "CRL"); if (x == NULL) goto end; if (do_ver) { if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) == NULL) goto end; lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (lookup == NULL) goto end; ctx = X509_STORE_CTX_new(); if (ctx == NULL || !X509_STORE_CTX_init(ctx, store, NULL, NULL)) { BIO_printf(bio_err, "Error initialising X509 store\n"); goto end; } xobj = X509_STORE_CTX_get_obj_by_subject(ctx, X509_LU_X509, X509_CRL_get_issuer(x)); if (xobj == NULL) { BIO_printf(bio_err, "Error getting CRL issuer certificate\n"); goto end; } pkey = X509_get_pubkey(X509_OBJECT_get0_X509(xobj)); X509_OBJECT_free(xobj); if (pkey == NULL) { BIO_printf(bio_err, "Error getting CRL issuer public key\n"); goto end; } i = X509_CRL_verify(x, pkey); EVP_PKEY_free(pkey); if (i < 0) goto end; if (i == 0) { BIO_printf(bio_err, "verify failure\n"); goto end; } else BIO_printf(bio_err, "verify OK\n"); } if (crldiff != NULL) { X509_CRL *newcrl, *delta; if (!keyfile) { BIO_puts(bio_err, "Missing CRL signing key\n"); goto end; } newcrl = load_crl(crldiff, informat, 0, "other CRL"); if (!newcrl) goto end; pkey = load_key(keyfile, keyformat, 0, NULL, NULL, "CRL signing key"); if (pkey == NULL) { X509_CRL_free(newcrl); goto end; } delta = X509_CRL_diff(x, newcrl, pkey, digest, 0); X509_CRL_free(newcrl); EVP_PKEY_free(pkey); if (delta) { X509_CRL_free(x); x = delta; } else { BIO_puts(bio_err, "Error creating delta CRL\n"); goto end; } } if (badsig) { const ASN1_BIT_STRING *sig; X509_CRL_get0_signature(x, &sig, NULL); corrupt_signature(sig); } if (num) { for (i = 1; i <= num; i++) { if (issuer == i) { print_name(bio_out, "issuer=", X509_CRL_get_issuer(x)); } if (crlnumber == i) { ASN1_INTEGER *crlnum; crlnum = X509_CRL_get_ext_d2i(x, NID_crl_number, NULL, NULL); BIO_printf(bio_out, "crlNumber="); if (crlnum) { BIO_puts(bio_out, "0x"); i2a_ASN1_INTEGER(bio_out, crlnum); ASN1_INTEGER_free(crlnum); } else { BIO_puts(bio_out, "<NONE>"); } BIO_printf(bio_out, "\n"); } if (hash == i) { int ok; unsigned long hash_value = X509_NAME_hash_ex(X509_CRL_get_issuer(x), app_get0_libctx(), app_get0_propq(), &ok); if (num > 1) BIO_printf(bio_out, "issuer name hash="); if (ok) { BIO_printf(bio_out, "%08lx\n", hash_value); } else { BIO_puts(bio_out, "<ERROR>"); goto end; } } #ifndef OPENSSL_NO_MD5 if (hash_old == i) { if (num > 1) BIO_printf(bio_out, "issuer name old hash="); BIO_printf(bio_out, "%08lx\n", X509_NAME_hash_old(X509_CRL_get_issuer(x))); } #endif if (lastupdate == i) { BIO_printf(bio_out, "lastUpdate="); ASN1_TIME_print_ex(bio_out, X509_CRL_get0_lastUpdate(x), dateopt); BIO_printf(bio_out, "\n"); } if (nextupdate == i) { BIO_printf(bio_out, "nextUpdate="); if (X509_CRL_get0_nextUpdate(x)) ASN1_TIME_print_ex(bio_out, X509_CRL_get0_nextUpdate(x), dateopt); else BIO_printf(bio_out, "NONE"); BIO_printf(bio_out, "\n"); } if (fingerprint == i) { int j; unsigned int n; unsigned char md[EVP_MAX_MD_SIZE]; if (!X509_CRL_digest(x, digest, md, &n)) { BIO_printf(bio_err, "out of memory\n"); goto end; } BIO_printf(bio_out, "%s Fingerprint=", EVP_MD_get0_name(digest)); for (j = 0; j < (int)n; j++) { BIO_printf(bio_out, "%02X%c", md[j], (j + 1 == (int)n) ? '\n' : ':'); } } } } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (text) X509_CRL_print_ex(out, x, get_nameopt()); if (noout) { ret = 0; goto end; } if (outformat == FORMAT_ASN1) i = (int)i2d_X509_CRL_bio(out, x); else i = PEM_write_bio_X509_CRL(out, x); if (!i) { BIO_printf(bio_err, "unable to write CRL\n"); goto end; } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); BIO_free_all(out); EVP_MD_free(digest); X509_CRL_free(x); X509_STORE_CTX_free(ctx); X509_STORE_free(store); return ret; }
apps
openssl/apps/crl.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/pem.h> static int cb(int ok, X509_STORE_CTX *ctx); static int check(X509_STORE *ctx, const char *file, STACK_OF(X509) *uchain, STACK_OF(X509) *tchain, STACK_OF(X509_CRL) *crls, int show_chain, STACK_OF(OPENSSL_STRING) *opts); static int v_verbose = 0, vflags = 0; typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_UNTRUSTED, OPT_TRUSTED, OPT_CRLFILE, OPT_CRL_DOWNLOAD, OPT_SHOW_CHAIN, OPT_V_ENUM, OPT_NAMEOPT, OPT_VFYOPT, OPT_VERBOSE, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS verify_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"verbose", OPT_VERBOSE, '-', "Print extra information about the operations being performed."}, {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, OPT_SECTION("Certificate chain"), {"trusted", OPT_TRUSTED, '<', "A file of trusted certificates"}, {"CAfile", OPT_CAFILE, '<', "A file of trusted certificates"}, {"CApath", OPT_CAPATH, '/', "A directory of files with trusted certificates"}, {"CAstore", OPT_CASTORE, ':', "URI to a store of trusted certificates"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default trusted certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load trusted certificates from the default directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load trusted certificates from the default certificates store"}, {"untrusted", OPT_UNTRUSTED, '<', "A file of untrusted certificates"}, {"CRLfile", OPT_CRLFILE, '<', "File containing one or more CRL's (in PEM format) to load"}, {"crl_download", OPT_CRL_DOWNLOAD, '-', "Try downloading CRL information for certificates via their CDP entries"}, {"show_chain", OPT_SHOW_CHAIN, '-', "Display information about the certificate chain"}, OPT_V_OPTIONS, {"vfyopt", OPT_VFYOPT, 's', "Verification parameter in n:v form"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"cert", 0, 0, "Certificate(s) to verify (optional; stdin used otherwise)"}, {NULL} }; int verify_main(int argc, char **argv) { ENGINE *e = NULL; STACK_OF(X509) *untrusted = NULL, *trusted = NULL; STACK_OF(X509_CRL) *crls = NULL; STACK_OF(OPENSSL_STRING) *vfyopts = NULL; X509_STORE *store = NULL; X509_VERIFY_PARAM *vpm = NULL; const char *prog, *CApath = NULL, *CAfile = NULL, *CAstore = NULL; int noCApath = 0, noCAfile = 0, noCAstore = 0; int vpmtouched = 0, crl_download = 0, show_chain = 0, i = 0, ret = 1; OPTION_CHOICE o; if ((vpm = X509_VERIFY_PARAM_new()) == NULL) goto end; prog = opt_init(argc, argv, verify_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(verify_options); BIO_printf(bio_err, "\nRecognized certificate chain purposes:\n"); for (i = 0; i < X509_PURPOSE_get_count(); i++) { X509_PURPOSE *ptmp = X509_PURPOSE_get0(i); BIO_printf(bio_err, " %-15s %s\n", X509_PURPOSE_get0_sname(ptmp), X509_PURPOSE_get0_name(ptmp)); } BIO_printf(bio_err, "Recognized certificate policy names:\n"); for (i = 0; i < X509_VERIFY_PARAM_get_count(); i++) { const X509_VERIFY_PARAM *vptmp = X509_VERIFY_PARAM_get0(i); BIO_printf(bio_err, " %s\n", X509_VERIFY_PARAM_get0_name(vptmp)); } ret = 0; goto end; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_UNTRUSTED: if (!load_certs(opt_arg(), 0, &untrusted, NULL, "untrusted certificates")) goto end; break; case OPT_TRUSTED: noCAfile = 1; noCApath = 1; noCAstore = 1; if (!load_certs(opt_arg(), 0, &trusted, NULL, "trusted certificates")) goto end; break; case OPT_CRLFILE: if (!load_crls(opt_arg(), &crls, NULL, "other CRLs")) goto end; break; case OPT_CRL_DOWNLOAD: crl_download = 1; break; case OPT_ENGINE: if ((e = setup_engine(opt_arg(), 0)) == NULL) { goto end; } break; case OPT_SHOW_CHAIN: show_chain = 1; break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto end; break; case OPT_VFYOPT: if (!vfyopts) vfyopts = sk_OPENSSL_STRING_new_null(); if (!vfyopts || !sk_OPENSSL_STRING_push(vfyopts, opt_arg())) goto opthelp; break; case OPT_VERBOSE: v_verbose = 1; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } argc = opt_num_rest(); argv = opt_rest(); if (trusted != NULL && (CAfile != NULL || CApath != NULL || CAstore != NULL)) { BIO_printf(bio_err, "%s: Cannot use -trusted with -CAfile, -CApath or -CAstore\n", prog); goto end; } if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) == NULL) goto end; X509_STORE_set_verify_cb(store, cb); if (vpmtouched) X509_STORE_set1_param(store, vpm); ERR_clear_error(); if (crl_download) store_setup_crl_download(store); ret = 0; if (argc < 1) { if (check(store, NULL, untrusted, trusted, crls, show_chain, vfyopts) != 1) ret = -1; } else { for (i = 0; i < argc; i++) if (check(store, argv[i], untrusted, trusted, crls, show_chain, vfyopts) != 1) ret = -1; } end: X509_VERIFY_PARAM_free(vpm); X509_STORE_free(store); OSSL_STACK_OF_X509_free(untrusted); OSSL_STACK_OF_X509_free(trusted); sk_X509_CRL_pop_free(crls, X509_CRL_free); sk_OPENSSL_STRING_free(vfyopts); release_engine(e); return (ret < 0 ? 2 : ret); } static int check(X509_STORE *ctx, const char *file, STACK_OF(X509) *uchain, STACK_OF(X509) *tchain, STACK_OF(X509_CRL) *crls, int show_chain, STACK_OF(OPENSSL_STRING) *opts) { X509 *x = NULL; int i = 0, ret = 0; X509_STORE_CTX *csc; STACK_OF(X509) *chain = NULL; int num_untrusted; x = load_cert(file, FORMAT_UNDEF, "certificate file"); if (x == NULL) goto end; if (opts != NULL) { for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) { char *opt = sk_OPENSSL_STRING_value(opts, i); if (x509_ctrl_string(x, opt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", opt); ERR_print_errors(bio_err); X509_free(x); return 0; } } } csc = X509_STORE_CTX_new(); if (csc == NULL) { BIO_printf(bio_err, "error %s: X.509 store context allocation failed\n", (file == NULL) ? "stdin" : file); goto end; } X509_STORE_set_flags(ctx, vflags); if (!X509_STORE_CTX_init(csc, ctx, x, uchain)) { X509_STORE_CTX_free(csc); BIO_printf(bio_err, "error %s: X.509 store context initialization failed\n", (file == NULL) ? "stdin" : file); goto end; } if (tchain != NULL) X509_STORE_CTX_set0_trusted_stack(csc, tchain); if (crls != NULL) X509_STORE_CTX_set0_crls(csc, crls); i = X509_verify_cert(csc); if (i > 0 && X509_STORE_CTX_get_error(csc) == X509_V_OK) { BIO_printf(bio_out, "%s: OK\n", (file == NULL) ? "stdin" : file); ret = 1; if (show_chain) { int j; chain = X509_STORE_CTX_get1_chain(csc); num_untrusted = X509_STORE_CTX_get_num_untrusted(csc); BIO_printf(bio_out, "Chain:\n"); for (j = 0; j < sk_X509_num(chain); j++) { X509 *cert = sk_X509_value(chain, j); BIO_printf(bio_out, "depth=%d: ", j); X509_NAME_print_ex_fp(stdout, X509_get_subject_name(cert), 0, get_nameopt()); if (j < num_untrusted) BIO_printf(bio_out, " (untrusted)"); BIO_printf(bio_out, "\n"); } OSSL_STACK_OF_X509_free(chain); } } else { BIO_printf(bio_err, "error %s: verification failed\n", (file == NULL) ? "stdin" : file); } X509_STORE_CTX_free(csc); end: if (i <= 0) ERR_print_errors(bio_err); X509_free(x); return ret; } static int cb(int ok, X509_STORE_CTX *ctx) { int cert_error = X509_STORE_CTX_get_error(ctx); X509 *current_cert = X509_STORE_CTX_get_current_cert(ctx); if (!ok) { if (current_cert != NULL) { X509_NAME_print_ex(bio_err, X509_get_subject_name(current_cert), 0, get_nameopt()); BIO_printf(bio_err, "\n"); } BIO_printf(bio_err, "%serror %d at %d depth lookup: %s\n", X509_STORE_CTX_get0_parent_ctx(ctx) ? "[CRL path] " : "", cert_error, X509_STORE_CTX_get_error_depth(ctx), X509_verify_cert_error_string(cert_error)); switch (cert_error) { case X509_V_ERR_NO_EXPLICIT_POLICY: policies_print(ctx); case X509_V_ERR_CERT_HAS_EXPIRED: case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: case X509_V_ERR_INVALID_CA: case X509_V_ERR_INVALID_NON_CA: case X509_V_ERR_PATH_LENGTH_EXCEEDED: case X509_V_ERR_CRL_HAS_EXPIRED: case X509_V_ERR_CRL_NOT_YET_VALID: case X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: case X509_V_ERR_INVALID_PURPOSE: case X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA: case X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN: case X509_V_ERR_CA_BCONS_NOT_CRITICAL: case X509_V_ERR_CA_CERT_MISSING_KEY_USAGE: case X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA: case X509_V_ERR_ISSUER_NAME_EMPTY: case X509_V_ERR_SUBJECT_NAME_EMPTY: case X509_V_ERR_EMPTY_SUBJECT_SAN_NOT_CRITICAL: case X509_V_ERR_EMPTY_SUBJECT_ALT_NAME: case X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY: case X509_V_ERR_AUTHORITY_KEY_IDENTIFIER_CRITICAL: case X509_V_ERR_SUBJECT_KEY_IDENTIFIER_CRITICAL: case X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER: case X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER: case X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3: ok = 1; } return ok; } if (cert_error == X509_V_OK && ok == 2) policies_print(ctx); if (!v_verbose) ERR_clear_error(); return ok; }
apps
openssl/apps/verify.c
openssl
#include <openssl/crypto.h> #include "apps.h" #include "progs.h" typedef enum OPTION_choice { OPT_COMMON, OPT_CONFIGDIR, OPT_ENGINESDIR, OPT_MODULESDIR, OPT_DSOEXT, OPT_DIRNAMESEP, OPT_LISTSEP, OPT_SEEDS, OPT_CPUSETTINGS } OPTION_CHOICE; const OPTIONS info_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Output"), {"configdir", OPT_CONFIGDIR, '-', "Default configuration file directory"}, {"enginesdir", OPT_ENGINESDIR, '-', "Default engine module directory"}, {"modulesdir", OPT_MODULESDIR, '-', "Default module directory (other than engine modules)"}, {"dsoext", OPT_DSOEXT, '-', "Configured extension for modules"}, {"dirnamesep", OPT_DIRNAMESEP, '-', "Directory-filename separator"}, {"listsep", OPT_LISTSEP, '-', "List separator character"}, {"seeds", OPT_SEEDS, '-', "Seed sources"}, {"cpusettings", OPT_CPUSETTINGS, '-', "CPU settings info"}, {NULL} }; int info_main(int argc, char **argv) { int ret = 1, dirty = 0, type = 0; char *prog; OPTION_CHOICE o; prog = opt_init(argc, argv, info_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { default: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(info_options); ret = 0; goto end; case OPT_CONFIGDIR: type = OPENSSL_INFO_CONFIG_DIR; dirty++; break; case OPT_ENGINESDIR: type = OPENSSL_INFO_ENGINES_DIR; dirty++; break; case OPT_MODULESDIR: type = OPENSSL_INFO_MODULES_DIR; dirty++; break; case OPT_DSOEXT: type = OPENSSL_INFO_DSO_EXTENSION; dirty++; break; case OPT_DIRNAMESEP: type = OPENSSL_INFO_DIR_FILENAME_SEPARATOR; dirty++; break; case OPT_LISTSEP: type = OPENSSL_INFO_LIST_SEPARATOR; dirty++; break; case OPT_SEEDS: type = OPENSSL_INFO_SEED_SOURCE; dirty++; break; case OPT_CPUSETTINGS: type = OPENSSL_INFO_CPU_SETTINGS; dirty++; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (dirty > 1) { BIO_printf(bio_err, "%s: Only one item allowed\n", prog); goto opthelp; } if (dirty == 0) { BIO_printf(bio_err, "%s: No items chosen\n", prog); goto opthelp; } BIO_printf(bio_out, "%s\n", OPENSSL_info(type)); ret = 0; end: return ret; }
apps
openssl/apps/info.c
openssl
#define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/opensslconf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/bn.h> #include <openssl/encoder.h> #include <openssl/core_dispatch.h> #ifndef OPENSSL_NO_RC4 # define DEFAULT_PVK_ENCR_STRENGTH 2 #else # define DEFAULT_PVK_ENCR_STRENGTH 0 #endif typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_IN, OPT_OUT, OPT_PUBIN, OPT_PUBOUT, OPT_PASSOUT, OPT_PASSIN, OPT_RSAPUBKEY_IN, OPT_RSAPUBKEY_OUT, OPT_PVK_NONE, OPT_PVK_WEAK, OPT_PVK_STRONG, OPT_NOOUT, OPT_TEXT, OPT_MODULUS, OPT_CHECK, OPT_CIPHER, OPT_PROV_ENUM, OPT_TRADITIONAL } OPTION_CHOICE; const OPTIONS rsa_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"check", OPT_CHECK, '-', "Verify key consistency"}, {"", OPT_CIPHER, '-', "Any supported cipher"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, 's', "Input file"}, {"inform", OPT_INFORM, 'f', "Input format (DER/PEM/P12/ENGINE)"}, {"pubin", OPT_PUBIN, '-', "Expect a public key in input file"}, {"RSAPublicKey_in", OPT_RSAPUBKEY_IN, '-', "Input is an RSAPublicKey"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'f', "Output format, one of DER PEM PVK"}, {"pubout", OPT_PUBOUT, '-', "Output a public key"}, {"RSAPublicKey_out", OPT_RSAPUBKEY_OUT, '-', "Output is an RSAPublicKey"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"noout", OPT_NOOUT, '-', "Don't print key out"}, {"text", OPT_TEXT, '-', "Print the key in text"}, {"modulus", OPT_MODULUS, '-', "Print the RSA key modulus"}, {"traditional", OPT_TRADITIONAL, '-', "Use traditional format for private keys"}, #ifndef OPENSSL_NO_RC4 OPT_SECTION("PVK"), {"pvk-strong", OPT_PVK_STRONG, '-', "Enable 'Strong' PVK encoding level (default)"}, {"pvk-weak", OPT_PVK_WEAK, '-', "Enable 'Weak' PVK encoding level"}, {"pvk-none", OPT_PVK_NONE, '-', "Don't enforce PVK encoding"}, #endif OPT_PROV_OPTIONS, {NULL} }; static int try_legacy_encoding(EVP_PKEY *pkey, int outformat, int pubout, BIO *out) { int ret = 0; #ifndef OPENSSL_NO_DEPRECATED_3_0 const RSA *rsa = EVP_PKEY_get0_RSA(pkey); if (rsa == NULL) return 0; if (outformat == FORMAT_ASN1) { if (pubout == 2) ret = i2d_RSAPublicKey_bio(out, rsa) > 0; else ret = i2d_RSA_PUBKEY_bio(out, rsa) > 0; } else if (outformat == FORMAT_PEM) { if (pubout == 2) ret = PEM_write_bio_RSAPublicKey(out, rsa) > 0; else ret = PEM_write_bio_RSA_PUBKEY(out, rsa) > 0; # ifndef OPENSSL_NO_DSA } else if (outformat == FORMAT_MSBLOB || outformat == FORMAT_PVK) { ret = i2b_PublicKey_bio(out, pkey) > 0; # endif } #endif return ret; } int rsa_main(int argc, char **argv) { ENGINE *e = NULL; BIO *out = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *pctx; EVP_CIPHER *enc = NULL; char *infile = NULL, *outfile = NULL, *ciphername = NULL, *prog; char *passin = NULL, *passout = NULL, *passinarg = NULL, *passoutarg = NULL; int private = 0; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, text = 0, check = 0; int noout = 0, modulus = 0, pubin = 0, pubout = 0, ret = 1; int pvk_encr = DEFAULT_PVK_ENCR_STRENGTH; OPTION_CHOICE o; int traditional = 0; const char *output_type = NULL; const char *output_structure = NULL; int selection = 0; OSSL_ENCODER_CTX *ectx = NULL; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, rsa_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(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; case OPT_PVK_STRONG: case OPT_PVK_WEAK: case OPT_PVK_NONE: pvk_encr = (o - OPT_PVK_NONE); break; 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: ciphername = opt_unknown(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_TRADITIONAL: traditional = 1; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!opt_cipher(ciphername, &enc)) goto opthelp; private = (text && !pubin) || (!pubout && !noout); 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; } if (pubin) { int tmpformat = FORMAT_UNDEF; 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) { ERR_print_errors(bio_err); goto end; } if (!EVP_PKEY_is_a(pkey, "RSA") && !EVP_PKEY_is_a(pkey, "RSA-PSS")) { BIO_printf(bio_err, "Not an RSA key\n"); goto end; } out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (text) { assert(pubin || private); if ((pubin && EVP_PKEY_print_public(out, pkey, 0, NULL) <= 0) || (!pubin && EVP_PKEY_print_private(out, pkey, 0, NULL) <= 0)) { perror(outfile); ERR_print_errors(bio_err); goto end; } } if (modulus) { BIGNUM *n = NULL; EVP_PKEY_get_bn_param(pkey, "n", &n); BIO_printf(out, "Modulus="); BN_print(out, n); BIO_printf(out, "\n"); BN_free(n); } if (check) { int r; pctx = EVP_PKEY_CTX_new_from_pkey(NULL, pkey, NULL); if (pctx == NULL) { BIO_printf(bio_err, "RSA unable to create PKEY context\n"); ERR_print_errors(bio_err); goto end; } r = EVP_PKEY_check(pctx); EVP_PKEY_CTX_free(pctx); if (r == 1) { BIO_printf(out, "RSA key ok\n"); } else if (r == 0) { BIO_printf(bio_err, "RSA key not ok\n"); ERR_print_errors(bio_err); } else if (r < 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) { output_type = "DER"; } else if (outformat == FORMAT_PEM) { output_type = "PEM"; } else if (outformat == FORMAT_MSBLOB) { output_type = "MSBLOB"; } else if (outformat == FORMAT_PVK) { if (pubin) { BIO_printf(bio_err, "PVK form impossible with public key input\n"); goto end; } output_type = "PVK"; } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (pubout || pubin) { selection = OSSL_KEYMGMT_SELECT_PUBLIC_KEY; } else { assert(private); selection = (OSSL_KEYMGMT_SELECT_KEYPAIR | OSSL_KEYMGMT_SELECT_ALL_PARAMETERS); } if (outformat == FORMAT_ASN1 || outformat == FORMAT_PEM) { if (pubout || pubin) { if (pubout == 2) output_structure = "pkcs1"; else output_structure = "SubjectPublicKeyInfo"; } else { assert(private); if (traditional) output_structure = "pkcs1"; else output_structure = "PrivateKeyInfo"; } } ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, output_type, output_structure, NULL); if (OSSL_ENCODER_CTX_get_num_encoders(ectx) == 0) { if ((!pubout && !pubin) || !try_legacy_encoding(pkey, outformat, pubout, out)) BIO_printf(bio_err, "%s format not supported\n", output_type); else ret = 0; goto end; } if (enc != NULL) OSSL_ENCODER_CTX_set_cipher(ectx, EVP_CIPHER_get0_name(enc), NULL); if (enc != NULL || outformat == FORMAT_PVK) { OSSL_ENCODER_CTX_set_passphrase_ui(ectx, get_ui_method(), NULL); if (passout != NULL) OSSL_ENCODER_CTX_set_passphrase(ectx, (const unsigned char *)passout, strlen(passout)); } if (outformat == FORMAT_PVK) { OSSL_PARAM params[2] = { OSSL_PARAM_END, OSSL_PARAM_END }; params[0] = OSSL_PARAM_construct_int("encrypt-level", &pvk_encr); if (!OSSL_ENCODER_CTX_set_params(ectx, params)) { BIO_printf(bio_err, "invalid PVK encryption level\n"); goto end; } } if (!OSSL_ENCODER_to_bio(ectx, out)) { BIO_printf(bio_err, "unable to write key\n"); ERR_print_errors(bio_err); goto end; } ret = 0; end: OSSL_ENCODER_CTX_free(ectx); release_engine(e); BIO_free_all(out); EVP_PKEY_free(pkey); EVP_CIPHER_free(enc); OPENSSL_free(passin); OPENSSL_free(passout); return ret; }
apps
openssl/apps/rsa.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/rand.h> #include <openssl/pem.h> #ifndef OPENSSL_NO_COMP # include <openssl/comp.h> #endif #include <ctype.h> #undef SIZE #undef BSIZE #define SIZE (512) #define BSIZE (8*1024) #define PBKDF2_ITER_DEFAULT 10000 #define STR(a) XSTR(a) #define XSTR(a) #a static int set_hex(const char *in, unsigned char *out, int size); static void show_ciphers(const OBJ_NAME *name, void *bio_); struct doall_enc_ciphers { BIO *bio; int n; }; typedef enum OPTION_choice { OPT_COMMON, OPT_LIST, OPT_E, OPT_IN, OPT_OUT, OPT_PASS, OPT_ENGINE, OPT_D, OPT_P, OPT_V, OPT_NOPAD, OPT_SALT, OPT_NOSALT, OPT_DEBUG, OPT_UPPER_P, OPT_UPPER_A, OPT_A, OPT_Z, OPT_BUFSIZE, OPT_K, OPT_KFILE, OPT_UPPER_K, OPT_NONE, OPT_UPPER_S, OPT_IV, OPT_MD, OPT_ITER, OPT_PBKDF2, OPT_CIPHER, OPT_SALTLEN, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS enc_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"list", OPT_LIST, '-', "List ciphers"}, #ifndef OPENSSL_NO_DEPRECATED_3_0 {"ciphers", OPT_LIST, '-', "Alias for -list"}, #endif {"e", OPT_E, '-', "Encrypt"}, {"d", OPT_D, '-', "Decrypt"}, {"p", OPT_P, '-', "Print the iv/key"}, {"P", OPT_UPPER_P, '-', "Print the iv/key and exit"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"k", OPT_K, 's', "Passphrase"}, {"kfile", OPT_KFILE, '<', "Read passphrase from file"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"pass", OPT_PASS, 's', "Passphrase source"}, {"v", OPT_V, '-', "Verbose output"}, {"a", OPT_A, '-', "Base64 encode/decode, depending on encryption flag"}, {"base64", OPT_A, '-', "Same as option -a"}, {"A", OPT_UPPER_A, '-', "Used with -[base64|a] to specify base64 buffer as a single line"}, OPT_SECTION("Encryption"), {"nopad", OPT_NOPAD, '-', "Disable standard block padding"}, {"salt", OPT_SALT, '-', "Use salt in the KDF (default)"}, {"nosalt", OPT_NOSALT, '-', "Do not use salt in the KDF"}, {"debug", OPT_DEBUG, '-', "Print debug info"}, {"bufsize", OPT_BUFSIZE, 's', "Buffer size"}, {"K", OPT_UPPER_K, 's', "Raw key, in hex"}, {"S", OPT_UPPER_S, 's', "Salt, in hex"}, {"iv", OPT_IV, 's', "IV in hex"}, {"md", OPT_MD, 's', "Use specified digest to create a key from the passphrase"}, {"iter", OPT_ITER, 'p', "Specify the iteration count and force the use of PBKDF2"}, {OPT_MORE_STR, 0, 0, "Default: " STR(PBKDF2_ITER_DEFAULT)}, {"pbkdf2", OPT_PBKDF2, '-', "Use password-based key derivation function 2 (PBKDF2)"}, {OPT_MORE_STR, 0, 0, "Use -iter to change the iteration count from " STR(PBKDF2_ITER_DEFAULT)}, {"none", OPT_NONE, '-', "Don't encrypt"}, {"saltlen", OPT_SALTLEN, 'p', "Specify the PBKDF2 salt length (in bytes)"}, {OPT_MORE_STR, 0, 0, "Default: 16"}, #ifndef OPENSSL_NO_ZLIB {"z", OPT_Z, '-', "Compress or decompress encrypted data using zlib"}, #endif {"", OPT_CIPHER, '-', "Any supported cipher"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; int enc_main(int argc, char **argv) { static char buf[128]; static const char magic[] = "Salted__"; ENGINE *e = NULL; BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio = NULL, *wbio = NULL; EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *cipher = NULL; EVP_MD *dgst = NULL; const char *digestname = NULL; char *hkey = NULL, *hiv = NULL, *hsalt = NULL, *p; char *infile = NULL, *outfile = NULL, *prog; char *str = NULL, *passarg = NULL, *pass = NULL, *strbuf = NULL; const char *ciphername = 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; int base64 = 0, informat = FORMAT_BINARY, outformat = FORMAT_BINARY; int ret = 1, inl, nopad = 0; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char *buff = NULL, salt[EVP_MAX_IV_LENGTH]; int saltlen = 0; int pbkdf2 = 0; int iter = 0; long n; int streamable = 1; int wrap = 0; struct doall_enc_ciphers dec; #ifndef OPENSSL_NO_ZLIB int do_zlib = 0; BIO *bzl = NULL; #endif int do_brotli = 0; BIO *bbrot = NULL; int do_zstd = 0; BIO *bzstd = NULL; if (strcmp(argv[0], "base64") == 0) base64 = 1; #ifndef OPENSSL_NO_ZLIB else if (strcmp(argv[0], "zlib") == 0) do_zlib = 1; #endif #ifndef OPENSSL_NO_BROTLI else if (strcmp(argv[0], "brotli") == 0) do_brotli = 1; #endif #ifndef OPENSSL_NO_ZSTD else if (strcmp(argv[0], "zstd") == 0) do_zstd = 1; #endif else if (strcmp(argv[0], "enc") != 0) ciphername = argv[0]; opt_set_unknown_name("cipher"); 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; goto end; case OPT_LIST: BIO_printf(bio_out, "Supported ciphers:\n"); dec.bio = bio_out; dec.n = 0; OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH, show_ciphers, &dec); BIO_printf(bio_out, "\n"); ret = 0; 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: e = 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: #ifndef OPENSSL_NO_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_long(opt_arg(), &n) || n < 0 || (k && n >= LONG_MAX / 1024)) 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', FORMAT_TEXT); 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: digestname = opt_arg(); break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_ITER: iter = opt_int_arg(); pbkdf2 = 1; break; case OPT_SALTLEN: if (!opt_int(opt_arg(), &saltlen)) goto opthelp; if (saltlen > (int)sizeof(salt)) saltlen = (int)sizeof(salt); break; case OPT_PBKDF2: pbkdf2 = 1; if (iter == 0) iter = PBKDF2_ITER_DEFAULT; break; case OPT_NONE: cipher = NULL; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; if (saltlen == 0 || pbkdf2 == 0) saltlen = PKCS5_SALT_LEN; if (!opt_cipher(ciphername, &cipher)) goto opthelp; if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_WRAP_MODE)) { wrap = 1; streamable = 0; } if (digestname != NULL) { if (!opt_md(digestname, &dgst)) goto opthelp; } if (dgst == NULL) dgst = (EVP_MD *)EVP_sha256(); if (iter == 0) iter = 1; if (base64 && bsize < 80) bsize = 80; if (verbose) BIO_printf(bio_err, "bufsize=%d\n", bsize); #ifndef OPENSSL_NO_ZLIB if (do_zlib) base64 = 0; #endif if (do_brotli) base64 = 0; if (do_zstd) base64 = 0; if (base64) { if (enc) outformat = FORMAT_BASE64; else informat = FORMAT_BASE64; } strbuf = app_malloc(SIZE, "strbuf"); buff = app_malloc(EVP_ENCODE_LENGTH(bsize), "evp buffer"); if (infile == NULL) { if (!streamable && printkey != 2) { BIO_printf(bio_err, "Unstreamable cipher mode\n"); goto end; } in = dup_bio_in(informat); } else { in = bio_open_default(infile, 'r', informat); } if (in == NULL) goto end; if (str == NULL && passarg != NULL) { 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)) { if (1) { #ifndef OPENSSL_NO_UI_CONSOLE for (;;) { char prompt[200]; BIO_snprintf(prompt, sizeof(prompt), "enter %s %s password:", EVP_CIPHER_get0_name(cipher), (enc) ? "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; } } } else { #endif BIO_printf(bio_err, "password required\n"); goto end; } } out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; if (debug) { BIO_set_callback_ex(in, BIO_debug_callback_ex); BIO_set_callback_ex(out, BIO_debug_callback_ex); BIO_set_callback_arg(in, (char *)bio_err); BIO_set_callback_arg(out, (char *)bio_err); } rbio = in; wbio = out; #ifndef OPENSSL_NO_COMP # ifndef OPENSSL_NO_ZLIB if (do_zlib) { if ((bzl = BIO_new(BIO_f_zlib())) == NULL) goto end; if (debug) { BIO_set_callback_ex(bzl, BIO_debug_callback_ex); BIO_set_callback_arg(bzl, (char *)bio_err); } if (enc) wbio = BIO_push(bzl, wbio); else rbio = BIO_push(bzl, rbio); } # endif if (do_brotli) { if ((bbrot = BIO_new(BIO_f_brotli())) == NULL) goto end; if (debug) { BIO_set_callback_ex(bbrot, BIO_debug_callback_ex); BIO_set_callback_arg(bbrot, (char *)bio_err); } if (enc) wbio = BIO_push(bbrot, wbio); else rbio = BIO_push(bbrot, rbio); } if (do_zstd) { if ((bzstd = BIO_new(BIO_f_zstd())) == NULL) goto end; if (debug) { BIO_set_callback_ex(bzstd, BIO_debug_callback_ex); BIO_set_callback_arg(bzstd, (char *)bio_err); } if (enc) wbio = BIO_push(bzstd, wbio); else rbio = BIO_push(bzstd, rbio); } #endif if (base64) { if ((b64 = BIO_new(BIO_f_base64())) == NULL) goto end; if (debug) { BIO_set_callback_ex(b64, BIO_debug_callback_ex); 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) { if (str != NULL) { unsigned char *sptr; size_t str_len = strlen(str); if (nosalt) { sptr = NULL; } else { if (hsalt != NULL && !set_hex(hsalt, salt, saltlen)) { BIO_printf(bio_err, "invalid hex salt value\n"); goto end; } if (enc) { if (hsalt == NULL) { if (RAND_bytes(salt, saltlen) <= 0) { BIO_printf(bio_err, "RAND_bytes failed\n"); goto end; } if ((printkey != 2) && (BIO_write(wbio, magic, sizeof(magic) - 1) != sizeof(magic) - 1 || BIO_write(wbio, (char *)salt, saltlen) != saltlen)) { BIO_printf(bio_err, "error writing output file\n"); goto end; } } } else { if (hsalt == NULL) { if (BIO_read(rbio, mbuf, sizeof(mbuf)) != sizeof(mbuf)) { BIO_printf(bio_err, "error reading input file\n"); goto end; } if (memcmp(mbuf, magic, sizeof(mbuf)) == 0) { if (BIO_read(rbio, salt, saltlen) != saltlen) { BIO_printf(bio_err, "error reading input file\n"); goto end; } } else { BIO_printf(bio_err, "bad magic number\n"); goto end; } } } sptr = salt; } if (pbkdf2 == 1) { unsigned char tmpkeyiv[EVP_MAX_KEY_LENGTH + EVP_MAX_IV_LENGTH]; int iklen = EVP_CIPHER_get_key_length(cipher); int ivlen = EVP_CIPHER_get_iv_length(cipher); int islen = (sptr != NULL ? saltlen : 0); if (!PKCS5_PBKDF2_HMAC(str, str_len, sptr, islen, iter, dgst, iklen+ivlen, tmpkeyiv)) { BIO_printf(bio_err, "PKCS5_PBKDF2_HMAC failed\n"); goto end; } memcpy(key, tmpkeyiv, iklen); memcpy(iv, tmpkeyiv+iklen, ivlen); } else { BIO_printf(bio_err, "*** WARNING : " "deprecated key derivation used.\n" "Using -iter or -pbkdf2 would be better.\n"); if (!EVP_BytesToKey(cipher, dgst, sptr, (unsigned char *)str, str_len, 1, key, iv)) { BIO_printf(bio_err, "EVP_BytesToKey failed\n"); goto end; } } if (str == strbuf) OPENSSL_cleanse(str, SIZE); else OPENSSL_cleanse(str, str_len); } if (hiv != NULL) { int siz = EVP_CIPHER_get_iv_length(cipher); if (siz == 0) { BIO_printf(bio_err, "warning: iv not used by this cipher\n"); } else if (!set_hex(hiv, iv, siz)) { BIO_printf(bio_err, "invalid hex iv value\n"); goto end; } } if ((hiv == NULL) && (str == NULL) && EVP_CIPHER_get_iv_length(cipher) != 0 && wrap == 0) { BIO_printf(bio_err, "iv undefined\n"); goto end; } if (hkey != NULL) { if (!set_hex(hkey, key, EVP_CIPHER_get_key_length(cipher))) { BIO_printf(bio_err, "invalid hex key value\n"); goto end; } cleanse(hkey); } if ((benc = BIO_new(BIO_f_cipher())) == NULL) goto end; BIO_get_cipher_ctx(benc, &ctx); if (wrap == 1) EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); if (!EVP_CipherInit_ex(ctx, cipher, e, NULL, NULL, enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_get0_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, (hiv == NULL && wrap == 1 ? NULL : iv), enc)) { BIO_printf(bio_err, "Error setting cipher %s\n", EVP_CIPHER_get0_name(cipher)); ERR_print_errors(bio_err); goto end; } if (debug) { BIO_set_callback_ex(benc, BIO_debug_callback_ex); BIO_set_callback_arg(benc, (char *)bio_err); } if (printkey) { if (!nosalt) { printf("salt="); for (i = 0; i < (int)saltlen; i++) printf("%02X", salt[i]); printf("\n"); } if (EVP_CIPHER_get_key_length(cipher) > 0) { printf("key="); for (i = 0; i < EVP_CIPHER_get_key_length(cipher); i++) printf("%02X", key[i]); printf("\n"); } if (EVP_CIPHER_get_iv_length(cipher) > 0) { printf("iv ="); for (i = 0; i < EVP_CIPHER_get_iv_length(cipher); i++) printf("%02X", iv[i]); printf("\n"); } if (printkey == 2) { ret = 0; goto end; } } } if (benc != NULL) wbio = BIO_push(benc, wbio); while (BIO_pending(rbio) || !BIO_eof(rbio)) { inl = BIO_read(rbio, (char *)buff, bsize); if (inl <= 0) break; if (!streamable && !BIO_eof(rbio)) { BIO_printf(bio_err, "Unstreamable cipher mode\n"); goto end; } if (BIO_write(wbio, (char *)buff, inl) != inl) { BIO_printf(bio_err, "error writing output file\n"); goto end; } if (!streamable) break; } if (!BIO_flush(wbio)) { if (enc) BIO_printf(bio_err, "bad encrypt\n"); else BIO_printf(bio_err, "bad decrypt\n"); goto end; } ret = 0; if (verbose) { BIO_printf(bio_err, "bytes read : %8ju\n", BIO_number_read(in)); BIO_printf(bio_err, "bytes written: %8ju\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); EVP_MD_free(dgst); EVP_CIPHER_free(cipher); #ifndef OPENSSL_NO_ZLIB BIO_free(bzl); #endif BIO_free(bbrot); BIO_free(bzstd); release_engine(e); OPENSSL_free(pass); return ret; } static void show_ciphers(const OBJ_NAME *name, void *arg) { struct doall_enc_ciphers *dec = (struct doall_enc_ciphers *)arg; const EVP_CIPHER *cipher; if (!islower((unsigned char)*name->name)) return; cipher = EVP_get_cipherbyname(name->name); if (cipher == NULL || (EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) != 0 || EVP_CIPHER_get_mode(cipher) == EVP_CIPH_XTS_MODE) return; BIO_printf(dec->bio, "-%-25s", name->name); if (++dec->n == 3) { BIO_printf(dec->bio, "\n"); dec->n = 0; } else BIO_printf(dec->bio, " "); } static int set_hex(const char *in, unsigned char *out, int size) { int i, n; unsigned char j; i = size * 2; n = strlen(in); if (n > i) { BIO_printf(bio_err, "hex string is too long, ignoring excess\n"); n = i; } else if (n < i) { BIO_printf(bio_err, "hex string is too short, padding with zero bytes to length\n"); } memset(out, 0, size); for (i = 0; i < n; i++) { j = (unsigned char)*in++; if (!isxdigit(j)) { BIO_printf(bio_err, "non-hex digit\n"); return 0; } j = (unsigned char)OPENSSL_hexchar2int(j); if (i & 1) out[i / 2] |= j; else out[i / 2] = (j << 4); } return 1; }
apps
openssl/apps/enc.c
openssl
#define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/opensslconf.h> #include "apps.h" #include "progs.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/err.h> #include <openssl/engine.h> #include <openssl/ssl.h> #include <openssl/store.h> typedef enum OPTION_choice { OPT_COMMON, OPT_C, OPT_T, OPT_TT, OPT_PRE, OPT_POST, OPT_V = 100, OPT_VV, OPT_VVV, OPT_VVVV } OPTION_CHOICE; const OPTIONS engine_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] engine...\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"t", OPT_T, '-', "Check that specified engine is available"}, {"pre", OPT_PRE, 's', "Run command against the ENGINE before loading it"}, {"post", OPT_POST, 's', "Run command against the ENGINE after loading it"}, OPT_SECTION("Output"), {"v", OPT_V, '-', "List 'control commands' For each specified engine"}, {"vv", OPT_VV, '-', "Also display each command's description"}, {"vvv", OPT_VVV, '-', "Also add the input flags for each command"}, {"vvvv", OPT_VVVV, '-', "Also show internal input flags"}, {"c", OPT_C, '-', "List the capabilities of specified engine"}, {"tt", OPT_TT, '-', "Display error trace for unavailable engines"}, {OPT_MORE_STR, OPT_EOF, 1, "Commands are like \"SO_PATH:/lib/libdriver.so\""}, OPT_PARAMETERS(), {"engine", 0, 0, "ID of engine(s) to load"}, {NULL} }; static int append_buf(char **buf, int *size, const char *s) { const int expand = 256; int len = strlen(s) + 1; char *p = *buf; if (p == NULL) { *size = ((len + expand - 1) / expand) * expand; p = *buf = app_malloc(*size, "engine buffer"); } else { const int blen = strlen(p); if (blen > 0) len += 2 + blen; if (len > *size) { *size = ((len + expand - 1) / expand) * expand; p = OPENSSL_realloc(p, *size); if (p == NULL) { OPENSSL_free(*buf); *buf = NULL; return 0; } *buf = p; } if (blen > 0) { p += blen; *p++ = ','; *p++ = ' '; } } strcpy(p, s); return 1; } static int util_flags(BIO *out, unsigned int flags, const char *indent) { int started = 0, err = 0; BIO_printf(out, "%s%s(input flags): ", indent, indent); if (flags == 0) { BIO_printf(out, "<no flags>\n"); return 1; } if (flags & ENGINE_CMD_FLAG_INTERNAL) { BIO_printf(out, "[Internal] "); } if (flags & ENGINE_CMD_FLAG_NUMERIC) { BIO_printf(out, "NUMERIC"); started = 1; } if (flags & ENGINE_CMD_FLAG_STRING) { if (started) { BIO_printf(out, "|"); err = 1; } BIO_printf(out, "STRING"); started = 1; } if (flags & ENGINE_CMD_FLAG_NO_INPUT) { if (started) { BIO_printf(out, "|"); err = 1; } BIO_printf(out, "NO_INPUT"); started = 1; } flags = flags & ~ENGINE_CMD_FLAG_NUMERIC & ~ENGINE_CMD_FLAG_STRING & ~ENGINE_CMD_FLAG_NO_INPUT & ~ENGINE_CMD_FLAG_INTERNAL; if (flags) { if (started) BIO_printf(out, "|"); BIO_printf(out, "<0x%04X>", flags); } if (err) BIO_printf(out, " <illegal flags!>"); BIO_printf(out, "\n"); return 1; } static int util_verbose(ENGINE *e, int verbose, BIO *out, const char *indent) { static const int line_wrap = 78; int num; int ret = 0; char *name = NULL; char *desc = NULL; int flags; int xpos = 0; STACK_OF(OPENSSL_STRING) *cmds = NULL; if (!ENGINE_ctrl(e, ENGINE_CTRL_HAS_CTRL_FUNCTION, 0, NULL, NULL) || ((num = ENGINE_ctrl(e, ENGINE_CTRL_GET_FIRST_CMD_TYPE, 0, NULL, NULL)) <= 0)) { return 1; } cmds = sk_OPENSSL_STRING_new_null(); if (cmds == NULL) goto err; do { int len; if ((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, num, NULL, NULL)) < 0) goto err; if (!(flags & ENGINE_CMD_FLAG_INTERNAL) || verbose >= 4) { if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_LEN_FROM_CMD, num, NULL, NULL)) <= 0) goto err; name = app_malloc(len + 1, "name buffer"); if (ENGINE_ctrl(e, ENGINE_CTRL_GET_NAME_FROM_CMD, num, name, NULL) <= 0) goto err; if ((len = ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_LEN_FROM_CMD, num, NULL, NULL)) < 0) goto err; if (len > 0) { desc = app_malloc(len + 1, "description buffer"); if (ENGINE_ctrl(e, ENGINE_CTRL_GET_DESC_FROM_CMD, num, desc, NULL) <= 0) goto err; } if (xpos == 0) xpos = BIO_puts(out, indent); else xpos += BIO_printf(out, ", "); if (verbose == 1) { if ((xpos > (int)strlen(indent)) && (xpos + (int)strlen(name) > line_wrap)) { BIO_printf(out, "\n"); xpos = BIO_puts(out, indent); } xpos += BIO_printf(out, "%s", name); } else { BIO_printf(out, "%s: %s\n", name, (desc == NULL) ? "<no description>" : desc); if ((verbose >= 3) && !util_flags(out, flags, indent)) goto err; xpos = 0; } } OPENSSL_free(name); name = NULL; OPENSSL_free(desc); desc = NULL; num = ENGINE_ctrl(e, ENGINE_CTRL_GET_NEXT_CMD_TYPE, num, NULL, NULL); } while (num > 0); if (xpos > 0) BIO_printf(out, "\n"); ret = 1; err: sk_OPENSSL_STRING_free(cmds); OPENSSL_free(name); OPENSSL_free(desc); return ret; } static void util_do_cmds(ENGINE *e, STACK_OF(OPENSSL_STRING) *cmds, BIO *out, const char *indent) { int loop, res, num = sk_OPENSSL_STRING_num(cmds); if (num < 0) { BIO_printf(out, "[Error]: internal stack error\n"); return; } for (loop = 0; loop < num; loop++) { char buf[256]; const char *cmd, *arg; cmd = sk_OPENSSL_STRING_value(cmds, loop); res = 1; if ((arg = strchr(cmd, ':')) == NULL) { if (!ENGINE_ctrl_cmd_string(e, cmd, NULL, 0)) res = 0; } else { if ((int)(arg - cmd) > 254) { BIO_printf(out, "[Error]: command name too long\n"); return; } memcpy(buf, cmd, (int)(arg - cmd)); buf[arg - cmd] = '\0'; arg++; if (!ENGINE_ctrl_cmd_string(e, buf, arg, 0)) res = 0; } if (res) { BIO_printf(out, "[Success]: %s\n", cmd); } else { BIO_printf(out, "[Failure]: %s\n", cmd); ERR_print_errors(out); } } } struct util_store_cap_data { ENGINE *engine; char **cap_buf; int *cap_size; int ok; }; static void util_store_cap(const OSSL_STORE_LOADER *loader, void *arg) { struct util_store_cap_data *ctx = arg; if (OSSL_STORE_LOADER_get0_engine(loader) == ctx->engine) { char buf[256]; BIO_snprintf(buf, sizeof(buf), "STORE(%s)", OSSL_STORE_LOADER_get0_scheme(loader)); if (!append_buf(ctx->cap_buf, ctx->cap_size, buf)) ctx->ok = 0; } } int engine_main(int argc, char **argv) { int ret = 1, i; int verbose = 0, list_cap = 0, test_avail = 0, test_avail_noise = 0; ENGINE *e; STACK_OF(OPENSSL_CSTRING) *engines = sk_OPENSSL_CSTRING_new_null(); STACK_OF(OPENSSL_STRING) *pre_cmds = sk_OPENSSL_STRING_new_null(); STACK_OF(OPENSSL_STRING) *post_cmds = sk_OPENSSL_STRING_new_null(); BIO *out; const char *indent = " "; OPTION_CHOICE o; char *prog; char *argv1; out = dup_bio_out(FORMAT_TEXT); if (engines == NULL || pre_cmds == NULL || post_cmds == NULL) goto end; prog = argv[0]; while ((argv1 = argv[1]) != NULL && *argv1 != '-') { sk_OPENSSL_CSTRING_push(engines, argv1); argc--; argv++; } argv[0] = prog; opt_init(argc, argv, engine_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(engine_options); ret = 0; goto end; case OPT_VVVV: case OPT_VVV: case OPT_VV: case OPT_V: i = (int)(o - OPT_V) + 1; if (verbose < i) verbose = i; break; case OPT_C: list_cap = 1; break; case OPT_TT: test_avail_noise++; case OPT_T: test_avail++; break; case OPT_PRE: sk_OPENSSL_STRING_push(pre_cmds, opt_arg()); break; case OPT_POST: sk_OPENSSL_STRING_push(post_cmds, opt_arg()); break; } } argc = opt_num_rest(); argv = opt_rest(); for ( ; *argv; argv++) { if (**argv == '-') { BIO_printf(bio_err, "%s: Cannot mix flags and engine names.\n", prog); BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; } sk_OPENSSL_CSTRING_push(engines, *argv); } if (sk_OPENSSL_CSTRING_num(engines) == 0) { for (e = ENGINE_get_first(); e != NULL; e = ENGINE_get_next(e)) { sk_OPENSSL_CSTRING_push(engines, ENGINE_get_id(e)); } } ret = 0; for (i = 0; i < sk_OPENSSL_CSTRING_num(engines); i++) { const char *id = sk_OPENSSL_CSTRING_value(engines, i); if ((e = ENGINE_by_id(id)) != NULL) { const char *name = ENGINE_get_name(e); BIO_printf(out, "(%s) %s\n", id, name); util_do_cmds(e, pre_cmds, out, indent); if (strcmp(ENGINE_get_id(e), id) != 0) { BIO_printf(out, "Loaded: (%s) %s\n", ENGINE_get_id(e), ENGINE_get_name(e)); } if (list_cap) { int cap_size = 256; char *cap_buf = NULL; int k, n; const int *nids; ENGINE_CIPHERS_PTR fn_c; ENGINE_DIGESTS_PTR fn_d; ENGINE_PKEY_METHS_PTR fn_pk; if (ENGINE_get_RSA(e) != NULL && !append_buf(&cap_buf, &cap_size, "RSA")) goto end; if (ENGINE_get_EC(e) != NULL && !append_buf(&cap_buf, &cap_size, "EC")) goto end; if (ENGINE_get_DSA(e) != NULL && !append_buf(&cap_buf, &cap_size, "DSA")) goto end; if (ENGINE_get_DH(e) != NULL && !append_buf(&cap_buf, &cap_size, "DH")) goto end; if (ENGINE_get_RAND(e) != NULL && !append_buf(&cap_buf, &cap_size, "RAND")) goto end; fn_c = ENGINE_get_ciphers(e); if (fn_c == NULL) goto skip_ciphers; n = fn_c(e, NULL, &nids, 0); for (k = 0; k < n; ++k) if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k]))) goto end; skip_ciphers: fn_d = ENGINE_get_digests(e); if (fn_d == NULL) goto skip_digests; n = fn_d(e, NULL, &nids, 0); for (k = 0; k < n; ++k) if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k]))) goto end; skip_digests: fn_pk = ENGINE_get_pkey_meths(e); if (fn_pk == NULL) goto skip_pmeths; n = fn_pk(e, NULL, &nids, 0); for (k = 0; k < n; ++k) if (!append_buf(&cap_buf, &cap_size, OBJ_nid2sn(nids[k]))) goto end; skip_pmeths: { struct util_store_cap_data store_ctx; store_ctx.engine = e; store_ctx.cap_buf = &cap_buf; store_ctx.cap_size = &cap_size; store_ctx.ok = 1; OSSL_STORE_do_all_loaders(util_store_cap, &store_ctx); if (!store_ctx.ok) goto end; } if (cap_buf != NULL && (*cap_buf != '\0')) BIO_printf(out, " [%s]\n", cap_buf); OPENSSL_free(cap_buf); } if (test_avail) { BIO_printf(out, "%s", indent); if (ENGINE_init(e)) { BIO_printf(out, "[ available ]\n"); util_do_cmds(e, post_cmds, out, indent); ENGINE_finish(e); } else { BIO_printf(out, "[ unavailable ]\n"); if (test_avail_noise) ERR_print_errors_fp(stdout); ERR_clear_error(); } } if ((verbose > 0) && !util_verbose(e, verbose, out, indent)) goto end; ENGINE_free(e); } else { ERR_print_errors(bio_err); if (++ret > 127) ret = 127; } } end: ERR_print_errors(bio_err); sk_OPENSSL_CSTRING_free(engines); sk_OPENSSL_STRING_free(pre_cmds); sk_OPENSSL_STRING_free(post_cmds); BIO_free_all(out); return ret; }
apps
openssl/apps/engine.c
openssl
#include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/rand.h> #if !defined(OPENSSL_NO_DES) && !defined(OPENSSL_NO_DEPRECATED_3_0) # include <openssl/des.h> #endif #include <openssl/md5.h> #include <openssl/sha.h> static const unsigned char cov_2char[64] = { 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A }; static const char ascii_dollar[] = { 0x24, 0x00 }; typedef enum { passwd_unset = 0, passwd_md5, passwd_apr1, passwd_sha256, passwd_sha512, passwd_aixmd5 } passwd_modes; static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p, char *passwd, BIO *out, int quiet, int table, int reverse, size_t pw_maxlen, passwd_modes mode); typedef enum OPTION_choice { OPT_COMMON, OPT_IN, OPT_NOVERIFY, OPT_QUIET, OPT_TABLE, OPT_REVERSE, OPT_APR1, OPT_1, OPT_5, OPT_6, OPT_AIXMD5, OPT_SALT, OPT_STDIN, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS passwd_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [password]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Read passwords from file"}, {"noverify", OPT_NOVERIFY, '-', "Never verify when reading password from terminal"}, {"stdin", OPT_STDIN, '-', "Read passwords from stdin"}, OPT_SECTION("Output"), {"quiet", OPT_QUIET, '-', "No warnings"}, {"table", OPT_TABLE, '-', "Format output as table"}, {"reverse", OPT_REVERSE, '-', "Switch table columns"}, OPT_SECTION("Cryptographic"), {"salt", OPT_SALT, 's', "Use provided salt"}, {"6", OPT_6, '-', "SHA512-based password algorithm"}, {"5", OPT_5, '-', "SHA256-based password algorithm"}, {"apr1", OPT_APR1, '-', "MD5-based password algorithm, Apache variant"}, {"1", OPT_1, '-', "MD5-based password algorithm"}, {"aixmd5", OPT_AIXMD5, '-', "AIX MD5-based password algorithm"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"password", 0, 0, "Password text to digest (optional)"}, {NULL} }; int passwd_main(int argc, char **argv) { BIO *in = NULL; char *infile = NULL, *salt = NULL, *passwd = NULL, **passwds = NULL; char *salt_malloc = NULL, *passwd_malloc = NULL, *prog; OPTION_CHOICE o; int in_stdin = 0, pw_source_defined = 0; #ifndef OPENSSL_NO_UI_CONSOLE int in_noverify = 0; #endif int passed_salt = 0, quiet = 0, table = 0, reverse = 0; int ret = 1; passwd_modes mode = passwd_unset; size_t passwd_malloc_size = 0; size_t pw_maxlen = 256; prog = opt_init(argc, argv, passwd_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(passwd_options); ret = 0; goto end; case OPT_IN: if (pw_source_defined) goto opthelp; infile = opt_arg(); pw_source_defined = 1; break; case OPT_NOVERIFY: #ifndef OPENSSL_NO_UI_CONSOLE in_noverify = 1; #endif break; case OPT_QUIET: quiet = 1; break; case OPT_TABLE: table = 1; break; case OPT_REVERSE: reverse = 1; break; case OPT_1: if (mode != passwd_unset) goto opthelp; mode = passwd_md5; break; case OPT_5: if (mode != passwd_unset) goto opthelp; mode = passwd_sha256; break; case OPT_6: if (mode != passwd_unset) goto opthelp; mode = passwd_sha512; break; case OPT_APR1: if (mode != passwd_unset) goto opthelp; mode = passwd_apr1; break; case OPT_AIXMD5: if (mode != passwd_unset) goto opthelp; mode = passwd_aixmd5; break; case OPT_SALT: passed_salt = 1; salt = opt_arg(); break; case OPT_STDIN: if (pw_source_defined) goto opthelp; in_stdin = 1; pw_source_defined = 1; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } argc = opt_num_rest(); argv = opt_rest(); if (*argv != NULL) { if (pw_source_defined) goto opthelp; pw_source_defined = 1; passwds = argv; } if (!app_RAND_load()) goto end; if (mode == passwd_unset) { mode = passwd_md5; } if (infile != NULL && in_stdin) { BIO_printf(bio_err, "%s: Can't combine -in and -stdin\n", prog); goto end; } if (infile != NULL || in_stdin) { in = bio_open_default(infile, 'r', FORMAT_TEXT); if (in == NULL) goto end; } if (passwds == NULL) { passwd_malloc_size = pw_maxlen + 2; passwd = passwd_malloc = app_malloc(passwd_malloc_size, "password buffer"); } if ((in == NULL) && (passwds == NULL)) { if (1) { #ifndef OPENSSL_NO_UI_CONSOLE static char *passwds_static[2] = { NULL, NULL }; passwds = passwds_static; if (in == NULL) { if (EVP_read_pw_string (passwd_malloc, passwd_malloc_size, "Password: ", !(passed_salt || in_noverify)) != 0) goto end; } passwds[0] = passwd_malloc; } else { #endif BIO_printf(bio_err, "password required\n"); goto end; } } if (in == NULL) { assert(passwds != NULL); assert(*passwds != NULL); do { passwd = *passwds++; if (!do_passwd(passed_salt, &salt, &salt_malloc, passwd, bio_out, quiet, table, reverse, pw_maxlen, mode)) goto end; } while (*passwds != NULL); } else { int done; assert(passwd != NULL); do { int r = BIO_gets(in, passwd, pw_maxlen + 1); if (r > 0) { char *c = (strchr(passwd, '\n')); if (c != NULL) { *c = 0; } else { char trash[BUFSIZ]; do r = BIO_gets(in, trash, sizeof(trash)); while ((r > 0) && (!strchr(trash, '\n'))); } if (!do_passwd (passed_salt, &salt, &salt_malloc, passwd, bio_out, quiet, table, reverse, pw_maxlen, mode)) goto end; } done = (r <= 0); } while (!done); } ret = 0; end: #if 0 ERR_print_errors(bio_err); #endif OPENSSL_free(salt_malloc); OPENSSL_free(passwd_malloc); BIO_free(in); return ret; } static char *md5crypt(const char *passwd, const char *magic, const char *salt) { static char out_buf[6 + 9 + 24 + 2]; unsigned char buf[MD5_DIGEST_LENGTH]; char ascii_magic[5]; char ascii_salt[9]; char *ascii_passwd = NULL; char *salt_out; int n; unsigned int i; EVP_MD_CTX *md = NULL, *md2 = NULL; size_t passwd_len, salt_len, magic_len; passwd_len = strlen(passwd); out_buf[0] = 0; magic_len = strlen(magic); OPENSSL_strlcpy(ascii_magic, magic, sizeof(ascii_magic)); #ifdef CHARSET_EBCDIC if ((magic[0] & 0x80) != 0) ebcdic2ascii(ascii_magic, ascii_magic, magic_len); #endif OPENSSL_strlcpy(ascii_salt, salt, sizeof(ascii_salt)); salt_len = strlen(ascii_salt); #ifdef CHARSET_EBCDIC ebcdic2ascii(ascii_salt, ascii_salt, salt_len); #endif #ifdef CHARSET_EBCDIC ascii_passwd = OPENSSL_strdup(passwd); if (ascii_passwd == NULL) return NULL; ebcdic2ascii(ascii_passwd, ascii_passwd, passwd_len); passwd = ascii_passwd; #endif if (magic_len > 0) { OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); if (magic_len > 4) goto err; OPENSSL_strlcat(out_buf, ascii_magic, sizeof(out_buf)); OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); } OPENSSL_strlcat(out_buf, ascii_salt, sizeof(out_buf)); if (strlen(out_buf) > 6 + 8) goto err; salt_out = out_buf; if (magic_len > 0) salt_out += 2 + magic_len; if (salt_len > 8) goto err; md = EVP_MD_CTX_new(); if (md == NULL || !EVP_DigestInit_ex(md, EVP_md5(), NULL) || !EVP_DigestUpdate(md, passwd, passwd_len)) goto err; if (magic_len > 0) if (!EVP_DigestUpdate(md, ascii_dollar, 1) || !EVP_DigestUpdate(md, ascii_magic, magic_len) || !EVP_DigestUpdate(md, ascii_dollar, 1)) goto err; if (!EVP_DigestUpdate(md, ascii_salt, salt_len)) goto err; md2 = EVP_MD_CTX_new(); if (md2 == NULL || !EVP_DigestInit_ex(md2, EVP_md5(), NULL) || !EVP_DigestUpdate(md2, passwd, passwd_len) || !EVP_DigestUpdate(md2, ascii_salt, salt_len) || !EVP_DigestUpdate(md2, passwd, passwd_len) || !EVP_DigestFinal_ex(md2, buf, NULL)) goto err; for (i = passwd_len; i > sizeof(buf); i -= sizeof(buf)) { if (!EVP_DigestUpdate(md, buf, sizeof(buf))) goto err; } if (!EVP_DigestUpdate(md, buf, i)) goto err; n = passwd_len; while (n) { if (!EVP_DigestUpdate(md, (n & 1) ? "\0" : passwd, 1)) goto err; n >>= 1; } if (!EVP_DigestFinal_ex(md, buf, NULL)) goto err; for (i = 0; i < 1000; i++) { if (!EVP_DigestInit_ex(md2, EVP_md5(), NULL)) goto err; if (!EVP_DigestUpdate(md2, (i & 1) ? (const unsigned char *)passwd : buf, (i & 1) ? passwd_len : sizeof(buf))) goto err; if (i % 3) { if (!EVP_DigestUpdate(md2, ascii_salt, salt_len)) goto err; } if (i % 7) { if (!EVP_DigestUpdate(md2, passwd, passwd_len)) goto err; } if (!EVP_DigestUpdate(md2, (i & 1) ? buf : (const unsigned char *)passwd, (i & 1) ? sizeof(buf) : passwd_len)) goto err; if (!EVP_DigestFinal_ex(md2, buf, NULL)) goto err; } EVP_MD_CTX_free(md2); EVP_MD_CTX_free(md); md2 = NULL; md = NULL; { unsigned char buf_perm[sizeof(buf)]; int dest, source; char *output; for (dest = 0, source = 0; dest < 14; dest++, source = (source + 6) % 17) buf_perm[dest] = buf[source]; buf_perm[14] = buf[5]; buf_perm[15] = buf[11]; # ifndef PEDANTIC assert(16 == sizeof(buf_perm)); # endif output = salt_out + salt_len; assert(output == out_buf + strlen(out_buf)); *output++ = ascii_dollar[0]; for (i = 0; i < 15; i += 3) { *output++ = cov_2char[buf_perm[i + 2] & 0x3f]; *output++ = cov_2char[((buf_perm[i + 1] & 0xf) << 2) | (buf_perm[i + 2] >> 6)]; *output++ = cov_2char[((buf_perm[i] & 3) << 4) | (buf_perm[i + 1] >> 4)]; *output++ = cov_2char[buf_perm[i] >> 2]; } assert(i == 15); *output++ = cov_2char[buf_perm[i] & 0x3f]; *output++ = cov_2char[buf_perm[i] >> 6]; *output = 0; assert(strlen(out_buf) < sizeof(out_buf)); #ifdef CHARSET_EBCDIC ascii2ebcdic(out_buf, out_buf, strlen(out_buf)); #endif } return out_buf; err: OPENSSL_free(ascii_passwd); EVP_MD_CTX_free(md2); EVP_MD_CTX_free(md); return NULL; } static char *shacrypt(const char *passwd, const char *magic, const char *salt) { static const char rounds_prefix[] = "rounds="; # define SALT_LEN_MAX 16 # define ROUNDS_DEFAULT 5000 # define ROUNDS_MIN 1000 # define ROUNDS_MAX 999999999 static char out_buf[3 + 17 + 17 + 86 + 1]; unsigned char buf[SHA512_DIGEST_LENGTH]; unsigned char temp_buf[SHA512_DIGEST_LENGTH]; size_t buf_size = 0; char ascii_magic[2]; char ascii_salt[17]; char *ascii_passwd = NULL; size_t n; EVP_MD_CTX *md = NULL, *md2 = NULL; const EVP_MD *sha = NULL; size_t passwd_len, salt_len, magic_len; unsigned int rounds = ROUNDS_DEFAULT; char rounds_custom = 0; char *p_bytes = NULL; char *s_bytes = NULL; char *cp = NULL; passwd_len = strlen(passwd); magic_len = strlen(magic); if (magic_len != 1) return NULL; switch (magic[0]) { case '5': sha = EVP_sha256(); buf_size = 32; break; case '6': sha = EVP_sha512(); buf_size = 64; break; default: return NULL; } if (strncmp(salt, rounds_prefix, sizeof(rounds_prefix) - 1) == 0) { const char *num = salt + sizeof(rounds_prefix) - 1; char *endp; unsigned long int srounds = strtoul (num, &endp, 10); if (*endp == '$') { salt = endp + 1; if (srounds > ROUNDS_MAX) rounds = ROUNDS_MAX; else if (srounds < ROUNDS_MIN) rounds = ROUNDS_MIN; else rounds = (unsigned int)srounds; rounds_custom = 1; } else { return NULL; } } OPENSSL_strlcpy(ascii_magic, magic, sizeof(ascii_magic)); #ifdef CHARSET_EBCDIC if ((magic[0] & 0x80) != 0) ebcdic2ascii(ascii_magic, ascii_magic, magic_len); #endif OPENSSL_strlcpy(ascii_salt, salt, sizeof(ascii_salt)); salt_len = strlen(ascii_salt); #ifdef CHARSET_EBCDIC ebcdic2ascii(ascii_salt, ascii_salt, salt_len); #endif #ifdef CHARSET_EBCDIC ascii_passwd = OPENSSL_strdup(passwd); if (ascii_passwd == NULL) return NULL; ebcdic2ascii(ascii_passwd, ascii_passwd, passwd_len); passwd = ascii_passwd; #endif out_buf[0] = 0; OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); OPENSSL_strlcat(out_buf, ascii_magic, sizeof(out_buf)); OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); if (rounds_custom) { char tmp_buf[80]; sprintf(tmp_buf, "rounds=%u", rounds); #ifdef CHARSET_EBCDIC if (tmp_buf[0] != 0x72) ebcdic2ascii(tmp_buf, tmp_buf, strlen(tmp_buf)); #endif OPENSSL_strlcat(out_buf, tmp_buf, sizeof(out_buf)); OPENSSL_strlcat(out_buf, ascii_dollar, sizeof(out_buf)); } OPENSSL_strlcat(out_buf, ascii_salt, sizeof(out_buf)); if (strlen(out_buf) > 3 + 17 * rounds_custom + salt_len) goto err; md = EVP_MD_CTX_new(); if (md == NULL || !EVP_DigestInit_ex(md, sha, NULL) || !EVP_DigestUpdate(md, passwd, passwd_len) || !EVP_DigestUpdate(md, ascii_salt, salt_len)) goto err; md2 = EVP_MD_CTX_new(); if (md2 == NULL || !EVP_DigestInit_ex(md2, sha, NULL) || !EVP_DigestUpdate(md2, passwd, passwd_len) || !EVP_DigestUpdate(md2, ascii_salt, salt_len) || !EVP_DigestUpdate(md2, passwd, passwd_len) || !EVP_DigestFinal_ex(md2, buf, NULL)) goto err; for (n = passwd_len; n > buf_size; n -= buf_size) { if (!EVP_DigestUpdate(md, buf, buf_size)) goto err; } if (!EVP_DigestUpdate(md, buf, n)) goto err; n = passwd_len; while (n) { if (!EVP_DigestUpdate(md, (n & 1) ? buf : (const unsigned char *)passwd, (n & 1) ? buf_size : passwd_len)) goto err; n >>= 1; } if (!EVP_DigestFinal_ex(md, buf, NULL)) goto err; if (!EVP_DigestInit_ex(md2, sha, NULL)) goto err; for (n = passwd_len; n > 0; n--) if (!EVP_DigestUpdate(md2, passwd, passwd_len)) goto err; if (!EVP_DigestFinal_ex(md2, temp_buf, NULL)) goto err; if ((p_bytes = OPENSSL_zalloc(passwd_len)) == NULL) goto err; for (cp = p_bytes, n = passwd_len; n > buf_size; n -= buf_size, cp += buf_size) memcpy(cp, temp_buf, buf_size); memcpy(cp, temp_buf, n); if (!EVP_DigestInit_ex(md2, sha, NULL)) goto err; for (n = 16 + buf[0]; n > 0; n--) if (!EVP_DigestUpdate(md2, ascii_salt, salt_len)) goto err; if (!EVP_DigestFinal_ex(md2, temp_buf, NULL)) goto err; if ((s_bytes = OPENSSL_zalloc(salt_len)) == NULL) goto err; for (cp = s_bytes, n = salt_len; n > buf_size; n -= buf_size, cp += buf_size) memcpy(cp, temp_buf, buf_size); memcpy(cp, temp_buf, n); for (n = 0; n < rounds; n++) { if (!EVP_DigestInit_ex(md2, sha, NULL)) goto err; if (!EVP_DigestUpdate(md2, (n & 1) ? (const unsigned char *)p_bytes : buf, (n & 1) ? passwd_len : buf_size)) goto err; if (n % 3) { if (!EVP_DigestUpdate(md2, s_bytes, salt_len)) goto err; } if (n % 7) { if (!EVP_DigestUpdate(md2, p_bytes, passwd_len)) goto err; } if (!EVP_DigestUpdate(md2, (n & 1) ? buf : (const unsigned char *)p_bytes, (n & 1) ? buf_size : passwd_len)) goto err; if (!EVP_DigestFinal_ex(md2, buf, NULL)) goto err; } EVP_MD_CTX_free(md2); EVP_MD_CTX_free(md); md2 = NULL; md = NULL; OPENSSL_free(p_bytes); OPENSSL_free(s_bytes); p_bytes = NULL; s_bytes = NULL; cp = out_buf + strlen(out_buf); *cp++ = ascii_dollar[0]; # define b64_from_24bit(B2, B1, B0, N) \ do { \ unsigned int w = ((B2) << 16) | ((B1) << 8) | (B0); \ int i = (N); \ while (i-- > 0) \ { \ *cp++ = cov_2char[w & 0x3f]; \ w >>= 6; \ } \ } while (0) switch (magic[0]) { case '5': b64_from_24bit (buf[0], buf[10], buf[20], 4); b64_from_24bit (buf[21], buf[1], buf[11], 4); b64_from_24bit (buf[12], buf[22], buf[2], 4); b64_from_24bit (buf[3], buf[13], buf[23], 4); b64_from_24bit (buf[24], buf[4], buf[14], 4); b64_from_24bit (buf[15], buf[25], buf[5], 4); b64_from_24bit (buf[6], buf[16], buf[26], 4); b64_from_24bit (buf[27], buf[7], buf[17], 4); b64_from_24bit (buf[18], buf[28], buf[8], 4); b64_from_24bit (buf[9], buf[19], buf[29], 4); b64_from_24bit (0, buf[31], buf[30], 3); break; case '6': b64_from_24bit (buf[0], buf[21], buf[42], 4); b64_from_24bit (buf[22], buf[43], buf[1], 4); b64_from_24bit (buf[44], buf[2], buf[23], 4); b64_from_24bit (buf[3], buf[24], buf[45], 4); b64_from_24bit (buf[25], buf[46], buf[4], 4); b64_from_24bit (buf[47], buf[5], buf[26], 4); b64_from_24bit (buf[6], buf[27], buf[48], 4); b64_from_24bit (buf[28], buf[49], buf[7], 4); b64_from_24bit (buf[50], buf[8], buf[29], 4); b64_from_24bit (buf[9], buf[30], buf[51], 4); b64_from_24bit (buf[31], buf[52], buf[10], 4); b64_from_24bit (buf[53], buf[11], buf[32], 4); b64_from_24bit (buf[12], buf[33], buf[54], 4); b64_from_24bit (buf[34], buf[55], buf[13], 4); b64_from_24bit (buf[56], buf[14], buf[35], 4); b64_from_24bit (buf[15], buf[36], buf[57], 4); b64_from_24bit (buf[37], buf[58], buf[16], 4); b64_from_24bit (buf[59], buf[17], buf[38], 4); b64_from_24bit (buf[18], buf[39], buf[60], 4); b64_from_24bit (buf[40], buf[61], buf[19], 4); b64_from_24bit (buf[62], buf[20], buf[41], 4); b64_from_24bit (0, 0, buf[63], 2); break; default: goto err; } *cp = '\0'; #ifdef CHARSET_EBCDIC ascii2ebcdic(out_buf, out_buf, strlen(out_buf)); #endif return out_buf; err: EVP_MD_CTX_free(md2); EVP_MD_CTX_free(md); OPENSSL_free(p_bytes); OPENSSL_free(s_bytes); OPENSSL_free(ascii_passwd); return NULL; } static int do_passwd(int passed_salt, char **salt_p, char **salt_malloc_p, char *passwd, BIO *out, int quiet, int table, int reverse, size_t pw_maxlen, passwd_modes mode) { char *hash = NULL; assert(salt_p != NULL); assert(salt_malloc_p != NULL); if (!passed_salt) { size_t saltlen = 0; size_t i; if (mode == passwd_md5 || mode == passwd_apr1 || mode == passwd_aixmd5) saltlen = 8; if (mode == passwd_sha256 || mode == passwd_sha512) saltlen = 16; assert(saltlen != 0); if (*salt_malloc_p == NULL) *salt_p = *salt_malloc_p = app_malloc(saltlen + 1, "salt buffer"); if (RAND_bytes((unsigned char *)*salt_p, saltlen) <= 0) goto end; for (i = 0; i < saltlen; i++) (*salt_p)[i] = cov_2char[(*salt_p)[i] & 0x3f]; (*salt_p)[i] = 0; # ifdef CHARSET_EBCDIC ascii2ebcdic(*salt_p, *salt_p, saltlen); # endif } assert(*salt_p != NULL); if ((strlen(passwd) > pw_maxlen)) { if (!quiet) BIO_printf(bio_err, "Warning: truncating password to %u characters\n", (unsigned)pw_maxlen); passwd[pw_maxlen] = 0; } assert(strlen(passwd) <= pw_maxlen); if (mode == passwd_md5 || mode == passwd_apr1) hash = md5crypt(passwd, (mode == passwd_md5 ? "1" : "apr1"), *salt_p); if (mode == passwd_aixmd5) hash = md5crypt(passwd, "", *salt_p); if (mode == passwd_sha256 || mode == passwd_sha512) hash = shacrypt(passwd, (mode == passwd_sha256 ? "5" : "6"), *salt_p); assert(hash != NULL); if (table && !reverse) BIO_printf(out, "%s\t%s\n", passwd, hash); else if (table && reverse) BIO_printf(out, "%s\t%s\n", hash, passwd); else BIO_printf(out, "%s\n", hash); return 1; end: return 0; }
apps
openssl/apps/passwd.c
openssl
#undef SECONDS #define SECONDS 3 #define PKEY_SECONDS 10 #define RSA_SECONDS PKEY_SECONDS #define DSA_SECONDS PKEY_SECONDS #define ECDSA_SECONDS PKEY_SECONDS #define ECDH_SECONDS PKEY_SECONDS #define EdDSA_SECONDS PKEY_SECONDS #define SM2_SECONDS PKEY_SECONDS #define FFDH_SECONDS PKEY_SECONDS #define KEM_SECONDS PKEY_SECONDS #define SIG_SECONDS PKEY_SECONDS #define MAX_ALGNAME_SUFFIX 100 #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "apps.h" #include "progs.h" #include "internal/nelem.h" #include "internal/numbers.h" #include <openssl/crypto.h> #include <openssl/rand.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/core_names.h> #include <openssl/async.h> #include <openssl/provider.h> #if !defined(OPENSSL_SYS_MSDOS) # include <unistd.h> #endif #if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include <floss.h(floss_fork)> # endif #endif #if defined(_WIN32) # include <windows.h> WINBASEAPI BOOL WINAPI VirtualLock( _In_ LPVOID lpAddress, _In_ SIZE_T dwSize ); #endif #if defined(OPENSSL_SYS_LINUX) # include <sys/mman.h> #endif #include <openssl/bn.h> #include <openssl/rsa.h> #include "./testrsa.h" #ifndef OPENSSL_NO_DH # include <openssl/dh.h> #endif #include <openssl/x509.h> #include <openssl/dsa.h> #include "./testdsa.h" #include <openssl/modes.h> #ifndef HAVE_FORK # if defined(OPENSSL_SYS_VMS) || defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_VXWORKS) # define HAVE_FORK 0 # else # define HAVE_FORK 1 # include <sys/wait.h> # endif #endif #if HAVE_FORK # undef NO_FORK #else # define NO_FORK #endif #define MAX_MISALIGNMENT 63 #define MAX_ECDH_SIZE 256 #define MISALIGN 64 #define MAX_FFDH_SIZE 1024 #ifndef RSA_DEFAULT_PRIME_NUM # define RSA_DEFAULT_PRIME_NUM 2 #endif typedef struct openssl_speed_sec_st { int sym; int rsa; int dsa; int ecdsa; int ecdh; int eddsa; int sm2; int ffdh; int kem; int sig; } openssl_speed_sec_t; static volatile int run = 0; static int mr = 0; static int usertime = 1; static double Time_F(int s); static void print_message(const char *s, int length, int tm); static void pkey_print_message(const char *str, const char *str2, unsigned int bits, int sec); static void kskey_print_message(const char *str, const char *str2, int tm); static void print_result(int alg, int run_no, int count, double time_used); #ifndef NO_FORK static int do_multi(int multi, int size_num); #endif static int domlock = 0; static const int lengths_list[] = { 16, 64, 256, 1024, 8 * 1024, 16 * 1024 }; #define SIZE_NUM OSSL_NELEM(lengths_list) static const int *lengths = lengths_list; static const int aead_lengths_list[] = { 2, 31, 136, 1024, 8 * 1024, 16 * 1024 }; #define START 0 #define STOP 1 #ifdef SIGALRM static void alarmed(ossl_unused int sig) { signal(SIGALRM, alarmed); run = 0; } static double Time_F(int s) { double ret = app_tminterval(s, usertime); if (s == STOP) alarm(0); return ret; } #elif defined(_WIN32) # define SIGALRM -1 static unsigned int lapse; static volatile unsigned int schlock; static void alarm_win32(unsigned int secs) { lapse = secs * 1000; } # define alarm alarm_win32 static DWORD WINAPI sleepy(VOID * arg) { schlock = 1; Sleep(lapse); run = 0; return 0; } static double Time_F(int s) { double ret; static HANDLE thr; if (s == START) { schlock = 0; thr = CreateThread(NULL, 4096, sleepy, NULL, 0, NULL); if (thr == NULL) { DWORD err = GetLastError(); BIO_printf(bio_err, "unable to CreateThread (%lu)", err); ExitProcess(err); } while (!schlock) Sleep(0); ret = app_tminterval(s, usertime); } else { ret = app_tminterval(s, usertime); if (run) TerminateThread(thr, 0); CloseHandle(thr); } return ret; } #else # error "SIGALRM not defined and the platform is not Windows" #endif static void multiblock_speed(const EVP_CIPHER *evp_cipher, int lengths_single, const openssl_speed_sec_t *seconds); static int opt_found(const char *name, unsigned int *result, const OPT_PAIR pairs[], unsigned int nbelem) { unsigned int idx; for (idx = 0; idx < nbelem; ++idx, pairs++) if (strcmp(name, pairs->name) == 0) { *result = pairs->retval; return 1; } return 0; } #define opt_found(value, pairs, result)\ opt_found(value, result, pairs, OSSL_NELEM(pairs)) typedef enum OPTION_choice { OPT_COMMON, OPT_ELAPSED, OPT_EVP, OPT_HMAC, OPT_DECRYPT, OPT_ENGINE, OPT_MULTI, OPT_MR, OPT_MB, OPT_MISALIGN, OPT_ASYNCJOBS, OPT_R_ENUM, OPT_PROV_ENUM, OPT_CONFIG, OPT_PRIMES, OPT_SECONDS, OPT_BYTES, OPT_AEAD, OPT_CMAC, OPT_MLOCK, OPT_KEM, OPT_SIG } OPTION_CHOICE; const OPTIONS speed_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [algorithm...]\n" "All +int options consider prefix '0' as base-8 input, " "prefix '0x'/'0X' as base-16 input.\n" }, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"mb", OPT_MB, '-', "Enable (tls1>=1) multi-block mode on EVP-named cipher"}, {"mr", OPT_MR, '-', "Produce machine readable output"}, #ifndef NO_FORK {"multi", OPT_MULTI, 'p', "Run benchmarks in parallel"}, #endif #ifndef OPENSSL_NO_ASYNC {"async_jobs", OPT_ASYNCJOBS, 'p', "Enable async mode and start specified number of jobs"}, #endif #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif {"primes", OPT_PRIMES, 'p', "Specify number of primes (for RSA only)"}, {"mlock", OPT_MLOCK, '-', "Lock memory for better result determinism"}, OPT_CONFIG_OPTION, OPT_SECTION("Selection"), {"evp", OPT_EVP, 's', "Use EVP-named cipher or digest"}, {"hmac", OPT_HMAC, 's', "HMAC using EVP-named digest"}, {"cmac", OPT_CMAC, 's', "CMAC using EVP-named cipher"}, {"decrypt", OPT_DECRYPT, '-', "Time decryption instead of encryption (only EVP)"}, {"aead", OPT_AEAD, '-', "Benchmark EVP-named AEAD cipher in TLS-like sequence"}, {"kem-algorithms", OPT_KEM, '-', "Benchmark KEM algorithms"}, {"signature-algorithms", OPT_SIG, '-', "Benchmark signature algorithms"}, OPT_SECTION("Timing"), {"elapsed", OPT_ELAPSED, '-', "Use wall-clock time instead of CPU user time as divisor"}, {"seconds", OPT_SECONDS, 'p', "Run benchmarks for specified amount of seconds"}, {"bytes", OPT_BYTES, 'p', "Run [non-PKI] benchmarks on custom-sized buffer"}, {"misalign", OPT_MISALIGN, 'p', "Use specified offset to mis-align buffers"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"algorithm", 0, 0, "Algorithm(s) to test (optional; otherwise tests all)"}, {NULL} }; enum { D_MD2, D_MDC2, D_MD4, D_MD5, D_SHA1, D_RMD160, D_SHA256, D_SHA512, D_WHIRLPOOL, D_HMAC, D_CBC_DES, D_EDE3_DES, D_RC4, D_CBC_IDEA, D_CBC_SEED, D_CBC_RC2, D_CBC_RC5, D_CBC_BF, D_CBC_CAST, D_CBC_128_AES, D_CBC_192_AES, D_CBC_256_AES, D_CBC_128_CML, D_CBC_192_CML, D_CBC_256_CML, D_EVP, D_GHASH, D_RAND, D_EVP_CMAC, D_KMAC128, D_KMAC256, ALGOR_NUM }; static const char *names[ALGOR_NUM] = { "md2", "mdc2", "md4", "md5", "sha1", "rmd160", "sha256", "sha512", "whirlpool", "hmac(sha256)", "des-cbc", "des-ede3", "rc4", "idea-cbc", "seed-cbc", "rc2-cbc", "rc5-cbc", "blowfish", "cast-cbc", "aes-128-cbc", "aes-192-cbc", "aes-256-cbc", "camellia-128-cbc", "camellia-192-cbc", "camellia-256-cbc", "evp", "ghash", "rand", "cmac", "kmac128", "kmac256" }; static const OPT_PAIR doit_choices[] = { {"md2", D_MD2}, {"mdc2", D_MDC2}, {"md4", D_MD4}, {"md5", D_MD5}, {"hmac", D_HMAC}, {"sha1", D_SHA1}, {"sha256", D_SHA256}, {"sha512", D_SHA512}, {"whirlpool", D_WHIRLPOOL}, {"ripemd", D_RMD160}, {"rmd160", D_RMD160}, {"ripemd160", D_RMD160}, {"rc4", D_RC4}, {"des-cbc", D_CBC_DES}, {"des-ede3", D_EDE3_DES}, {"aes-128-cbc", D_CBC_128_AES}, {"aes-192-cbc", D_CBC_192_AES}, {"aes-256-cbc", D_CBC_256_AES}, {"camellia-128-cbc", D_CBC_128_CML}, {"camellia-192-cbc", D_CBC_192_CML}, {"camellia-256-cbc", D_CBC_256_CML}, {"rc2-cbc", D_CBC_RC2}, {"rc2", D_CBC_RC2}, {"rc5-cbc", D_CBC_RC5}, {"rc5", D_CBC_RC5}, {"idea-cbc", D_CBC_IDEA}, {"idea", D_CBC_IDEA}, {"seed-cbc", D_CBC_SEED}, {"seed", D_CBC_SEED}, {"bf-cbc", D_CBC_BF}, {"blowfish", D_CBC_BF}, {"bf", D_CBC_BF}, {"cast-cbc", D_CBC_CAST}, {"cast", D_CBC_CAST}, {"cast5", D_CBC_CAST}, {"ghash", D_GHASH}, {"rand", D_RAND}, {"kmac128", D_KMAC128}, {"kmac256", D_KMAC256}, }; static double results[ALGOR_NUM][SIZE_NUM]; enum { R_DSA_1024, R_DSA_2048, DSA_NUM }; static const OPT_PAIR dsa_choices[DSA_NUM] = { {"dsa1024", R_DSA_1024}, {"dsa2048", R_DSA_2048} }; static double dsa_results[DSA_NUM][2]; enum { R_RSA_512, R_RSA_1024, R_RSA_2048, R_RSA_3072, R_RSA_4096, R_RSA_7680, R_RSA_15360, RSA_NUM }; static const OPT_PAIR rsa_choices[RSA_NUM] = { {"rsa512", R_RSA_512}, {"rsa1024", R_RSA_1024}, {"rsa2048", R_RSA_2048}, {"rsa3072", R_RSA_3072}, {"rsa4096", R_RSA_4096}, {"rsa7680", R_RSA_7680}, {"rsa15360", R_RSA_15360} }; static double rsa_results[RSA_NUM][4]; #ifndef OPENSSL_NO_DH enum ff_params_t { R_FFDH_2048, R_FFDH_3072, R_FFDH_4096, R_FFDH_6144, R_FFDH_8192, FFDH_NUM }; static const OPT_PAIR ffdh_choices[FFDH_NUM] = { {"ffdh2048", R_FFDH_2048}, {"ffdh3072", R_FFDH_3072}, {"ffdh4096", R_FFDH_4096}, {"ffdh6144", R_FFDH_6144}, {"ffdh8192", R_FFDH_8192}, }; static double ffdh_results[FFDH_NUM][1]; #endif enum ec_curves_t { R_EC_P160, R_EC_P192, R_EC_P224, R_EC_P256, R_EC_P384, R_EC_P521, #ifndef OPENSSL_NO_EC2M R_EC_K163, R_EC_K233, R_EC_K283, R_EC_K409, R_EC_K571, R_EC_B163, R_EC_B233, R_EC_B283, R_EC_B409, R_EC_B571, #endif R_EC_BRP256R1, R_EC_BRP256T1, R_EC_BRP384R1, R_EC_BRP384T1, R_EC_BRP512R1, R_EC_BRP512T1, ECDSA_NUM }; static const OPT_PAIR ecdsa_choices[ECDSA_NUM] = { {"ecdsap160", R_EC_P160}, {"ecdsap192", R_EC_P192}, {"ecdsap224", R_EC_P224}, {"ecdsap256", R_EC_P256}, {"ecdsap384", R_EC_P384}, {"ecdsap521", R_EC_P521}, #ifndef OPENSSL_NO_EC2M {"ecdsak163", R_EC_K163}, {"ecdsak233", R_EC_K233}, {"ecdsak283", R_EC_K283}, {"ecdsak409", R_EC_K409}, {"ecdsak571", R_EC_K571}, {"ecdsab163", R_EC_B163}, {"ecdsab233", R_EC_B233}, {"ecdsab283", R_EC_B283}, {"ecdsab409", R_EC_B409}, {"ecdsab571", R_EC_B571}, #endif {"ecdsabrp256r1", R_EC_BRP256R1}, {"ecdsabrp256t1", R_EC_BRP256T1}, {"ecdsabrp384r1", R_EC_BRP384R1}, {"ecdsabrp384t1", R_EC_BRP384T1}, {"ecdsabrp512r1", R_EC_BRP512R1}, {"ecdsabrp512t1", R_EC_BRP512T1} }; enum { #ifndef OPENSSL_NO_ECX R_EC_X25519 = ECDSA_NUM, R_EC_X448, EC_NUM #else EC_NUM = ECDSA_NUM #endif }; static const OPT_PAIR ecdh_choices[EC_NUM] = { {"ecdhp160", R_EC_P160}, {"ecdhp192", R_EC_P192}, {"ecdhp224", R_EC_P224}, {"ecdhp256", R_EC_P256}, {"ecdhp384", R_EC_P384}, {"ecdhp521", R_EC_P521}, #ifndef OPENSSL_NO_EC2M {"ecdhk163", R_EC_K163}, {"ecdhk233", R_EC_K233}, {"ecdhk283", R_EC_K283}, {"ecdhk409", R_EC_K409}, {"ecdhk571", R_EC_K571}, {"ecdhb163", R_EC_B163}, {"ecdhb233", R_EC_B233}, {"ecdhb283", R_EC_B283}, {"ecdhb409", R_EC_B409}, {"ecdhb571", R_EC_B571}, #endif {"ecdhbrp256r1", R_EC_BRP256R1}, {"ecdhbrp256t1", R_EC_BRP256T1}, {"ecdhbrp384r1", R_EC_BRP384R1}, {"ecdhbrp384t1", R_EC_BRP384T1}, {"ecdhbrp512r1", R_EC_BRP512R1}, {"ecdhbrp512t1", R_EC_BRP512T1}, #ifndef OPENSSL_NO_ECX {"ecdhx25519", R_EC_X25519}, {"ecdhx448", R_EC_X448} #endif }; static double ecdh_results[EC_NUM][1]; static double ecdsa_results[ECDSA_NUM][2]; #ifndef OPENSSL_NO_ECX enum { R_EC_Ed25519, R_EC_Ed448, EdDSA_NUM }; static const OPT_PAIR eddsa_choices[EdDSA_NUM] = { {"ed25519", R_EC_Ed25519}, {"ed448", R_EC_Ed448} }; static double eddsa_results[EdDSA_NUM][2]; #endif #ifndef OPENSSL_NO_SM2 enum { R_EC_CURVESM2, SM2_NUM }; static const OPT_PAIR sm2_choices[SM2_NUM] = { {"curveSM2", R_EC_CURVESM2} }; # define SM2_ID "TLSv1.3+GM+Cipher+Suite" # define SM2_ID_LEN sizeof("TLSv1.3+GM+Cipher+Suite") - 1 static double sm2_results[SM2_NUM][2]; #endif #define MAX_KEM_NUM 111 static size_t kems_algs_len = 0; static char *kems_algname[MAX_KEM_NUM] = { NULL }; static double kems_results[MAX_KEM_NUM][3]; #define MAX_SIG_NUM 111 static size_t sigs_algs_len = 0; static char *sigs_algname[MAX_SIG_NUM] = { NULL }; static double sigs_results[MAX_SIG_NUM][3]; #define COND(unused_cond) (run && count < INT_MAX) #define COUNT(d) (count) typedef struct loopargs_st { ASYNC_JOB *inprogress_job; ASYNC_WAIT_CTX *wait_ctx; unsigned char *buf; unsigned char *buf2; unsigned char *buf_malloc; unsigned char *buf2_malloc; unsigned char *key; size_t buflen; size_t sigsize; size_t encsize; EVP_PKEY_CTX *rsa_sign_ctx[RSA_NUM]; EVP_PKEY_CTX *rsa_verify_ctx[RSA_NUM]; EVP_PKEY_CTX *rsa_encrypt_ctx[RSA_NUM]; EVP_PKEY_CTX *rsa_decrypt_ctx[RSA_NUM]; EVP_PKEY_CTX *dsa_sign_ctx[DSA_NUM]; EVP_PKEY_CTX *dsa_verify_ctx[DSA_NUM]; EVP_PKEY_CTX *ecdsa_sign_ctx[ECDSA_NUM]; EVP_PKEY_CTX *ecdsa_verify_ctx[ECDSA_NUM]; EVP_PKEY_CTX *ecdh_ctx[EC_NUM]; #ifndef OPENSSL_NO_ECX EVP_MD_CTX *eddsa_ctx[EdDSA_NUM]; EVP_MD_CTX *eddsa_ctx2[EdDSA_NUM]; #endif #ifndef OPENSSL_NO_SM2 EVP_MD_CTX *sm2_ctx[SM2_NUM]; EVP_MD_CTX *sm2_vfy_ctx[SM2_NUM]; EVP_PKEY *sm2_pkey[SM2_NUM]; #endif unsigned char *secret_a; unsigned char *secret_b; size_t outlen[EC_NUM]; #ifndef OPENSSL_NO_DH EVP_PKEY_CTX *ffdh_ctx[FFDH_NUM]; unsigned char *secret_ff_a; unsigned char *secret_ff_b; #endif EVP_CIPHER_CTX *ctx; EVP_MAC_CTX *mctx; EVP_PKEY_CTX *kem_gen_ctx[MAX_KEM_NUM]; EVP_PKEY_CTX *kem_encaps_ctx[MAX_KEM_NUM]; EVP_PKEY_CTX *kem_decaps_ctx[MAX_KEM_NUM]; size_t kem_out_len[MAX_KEM_NUM]; size_t kem_secret_len[MAX_KEM_NUM]; unsigned char *kem_out[MAX_KEM_NUM]; unsigned char *kem_send_secret[MAX_KEM_NUM]; unsigned char *kem_rcv_secret[MAX_KEM_NUM]; EVP_PKEY_CTX *sig_gen_ctx[MAX_KEM_NUM]; EVP_PKEY_CTX *sig_sign_ctx[MAX_KEM_NUM]; EVP_PKEY_CTX *sig_verify_ctx[MAX_KEM_NUM]; size_t sig_max_sig_len[MAX_KEM_NUM]; size_t sig_act_sig_len[MAX_KEM_NUM]; unsigned char *sig_sig[MAX_KEM_NUM]; } loopargs_t; static int run_benchmark(int async_jobs, int (*loop_function) (void *), loopargs_t *loopargs); static unsigned int testnum; static char *evp_mac_mdname = "sha256"; static char *evp_hmac_name = NULL; static const char *evp_md_name = NULL; static char *evp_mac_ciphername = "aes-128-cbc"; static char *evp_cmac_name = NULL; static int have_md(const char *name) { int ret = 0; EVP_MD *md = NULL; if (opt_md_silent(name, &md)) { EVP_MD_CTX *ctx = EVP_MD_CTX_new(); if (ctx != NULL && EVP_DigestInit(ctx, md) > 0) ret = 1; EVP_MD_CTX_free(ctx); EVP_MD_free(md); } return ret; } static int have_cipher(const char *name) { int ret = 0; EVP_CIPHER *cipher = NULL; if (opt_cipher_silent(name, &cipher)) { EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); if (ctx != NULL && EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1) > 0) ret = 1; EVP_CIPHER_CTX_free(ctx); EVP_CIPHER_free(cipher); } return ret; } static int EVP_Digest_loop(const char *mdname, ossl_unused int algindex, void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char digest[EVP_MAX_MD_SIZE]; int count; EVP_MD *md = NULL; if (!opt_md_silent(mdname, &md)) return -1; for (count = 0; COND(c[algindex][testnum]); count++) { if (!EVP_Digest(buf, (size_t)lengths[testnum], digest, NULL, md, NULL)) { count = -1; break; } } EVP_MD_free(md); return count; } static int EVP_Digest_md_loop(void *args) { return EVP_Digest_loop(evp_md_name, D_EVP, args); } static int EVP_Digest_MD2_loop(void *args) { return EVP_Digest_loop("md2", D_MD2, args); } static int EVP_Digest_MDC2_loop(void *args) { return EVP_Digest_loop("mdc2", D_MDC2, args); } static int EVP_Digest_MD4_loop(void *args) { return EVP_Digest_loop("md4", D_MD4, args); } static int MD5_loop(void *args) { return EVP_Digest_loop("md5", D_MD5, args); } static int mac_setup(const char *name, EVP_MAC **mac, OSSL_PARAM params[], loopargs_t *loopargs, unsigned int loopargs_len) { unsigned int i; *mac = EVP_MAC_fetch(app_get0_libctx(), name, app_get0_propq()); if (*mac == NULL) return 0; for (i = 0; i < loopargs_len; i++) { loopargs[i].mctx = EVP_MAC_CTX_new(*mac); if (loopargs[i].mctx == NULL) return 0; if (!EVP_MAC_CTX_set_params(loopargs[i].mctx, params)) return 0; } return 1; } static void mac_teardown(EVP_MAC **mac, loopargs_t *loopargs, unsigned int loopargs_len) { unsigned int i; for (i = 0; i < loopargs_len; i++) EVP_MAC_CTX_free(loopargs[i].mctx); EVP_MAC_free(*mac); *mac = NULL; return; } static int EVP_MAC_loop(ossl_unused int algindex, void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_MAC_CTX *mctx = tempargs->mctx; unsigned char mac[EVP_MAX_MD_SIZE]; int count; for (count = 0; COND(c[algindex][testnum]); count++) { size_t outl; if (!EVP_MAC_init(mctx, NULL, 0, NULL) || !EVP_MAC_update(mctx, buf, lengths[testnum]) || !EVP_MAC_final(mctx, mac, &outl, sizeof(mac))) return -1; } return count; } static int HMAC_loop(void *args) { return EVP_MAC_loop(D_HMAC, args); } static int CMAC_loop(void *args) { return EVP_MAC_loop(D_EVP_CMAC, args); } static int KMAC128_loop(void *args) { return EVP_MAC_loop(D_KMAC128, args); } static int KMAC256_loop(void *args) { return EVP_MAC_loop(D_KMAC256, args); } static int SHA1_loop(void *args) { return EVP_Digest_loop("sha1", D_SHA1, args); } static int SHA256_loop(void *args) { return EVP_Digest_loop("sha256", D_SHA256, args); } static int SHA512_loop(void *args) { return EVP_Digest_loop("sha512", D_SHA512, args); } static int WHIRLPOOL_loop(void *args) { return EVP_Digest_loop("whirlpool", D_WHIRLPOOL, args); } static int EVP_Digest_RMD160_loop(void *args) { return EVP_Digest_loop("ripemd160", D_RMD160, args); } static int algindex; static int EVP_Cipher_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; int count; if (tempargs->ctx == NULL) return -1; for (count = 0; COND(c[algindex][testnum]); count++) if (EVP_Cipher(tempargs->ctx, buf, buf, (size_t)lengths[testnum]) <= 0) return -1; return count; } static int GHASH_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_MAC_CTX *mctx = tempargs->mctx; int count; for (count = 0; COND(c[D_GHASH][testnum]); count++) { if (!EVP_MAC_update(mctx, buf, lengths[testnum])) return -1; } return count; } #define MAX_BLOCK_SIZE 128 static unsigned char iv[2 * MAX_BLOCK_SIZE / 8]; static EVP_CIPHER_CTX *init_evp_cipher_ctx(const char *ciphername, const unsigned char *key, int keylen) { EVP_CIPHER_CTX *ctx = NULL; EVP_CIPHER *cipher = NULL; if (!opt_cipher_silent(ciphername, &cipher)) return NULL; if ((ctx = EVP_CIPHER_CTX_new()) == NULL) goto end; if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, 1)) { EVP_CIPHER_CTX_free(ctx); ctx = NULL; goto end; } if (EVP_CIPHER_CTX_set_key_length(ctx, keylen) <= 0) { EVP_CIPHER_CTX_free(ctx); ctx = NULL; goto end; } if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, 1)) { EVP_CIPHER_CTX_free(ctx); ctx = NULL; goto end; } end: EVP_CIPHER_free(cipher); return ctx; } static int RAND_bytes_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; int count; for (count = 0; COND(c[D_RAND][testnum]); count++) RAND_bytes(buf, lengths[testnum]); return count; } static int decrypt = 0; static int EVP_Update_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_CIPHER_CTX *ctx = tempargs->ctx; int outl, count, rc; if (decrypt) { for (count = 0; COND(c[D_EVP][testnum]); count++) { rc = EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]); if (rc != 1) { rc = EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1); } } } else { for (count = 0; COND(c[D_EVP][testnum]); count++) { rc = EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]); if (rc != 1) { rc = EVP_CipherInit_ex(ctx, NULL, NULL, NULL, iv, -1); } } } if (decrypt) rc = EVP_DecryptFinal_ex(ctx, buf, &outl); else rc = EVP_EncryptFinal_ex(ctx, buf, &outl); if (rc == 0) BIO_printf(bio_err, "Error finalizing cipher loop\n"); return count; } static int EVP_Update_loop_ccm(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_CIPHER_CTX *ctx = tempargs->ctx; int outl, count, realcount = 0, final; unsigned char tag[12]; if (decrypt) { for (count = 0; COND(c[D_EVP][testnum]); count++) { if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(tag), tag) > 0 && EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, iv) > 0 && EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]) > 0) realcount++; } } else { for (count = 0; COND(c[D_EVP][testnum]); count++) { if (EVP_EncryptUpdate(ctx, NULL, &outl, NULL, lengths[testnum]) > 0 && EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]) > 0) realcount++; } } if (decrypt) final = EVP_DecryptFinal_ex(ctx, buf, &outl); else final = EVP_EncryptFinal_ex(ctx, buf, &outl); if (final == 0) BIO_printf(bio_err, "Error finalizing ccm loop\n"); return realcount; } static int EVP_Update_loop_aead(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_CIPHER_CTX *ctx = tempargs->ctx; int outl, count, realcount = 0; unsigned char aad[13] = { 0xcc }; unsigned char faketag[16] = { 0xcc }; if (decrypt) { for (count = 0; COND(c[D_EVP][testnum]); count++) { if (EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, iv) > 0 && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(faketag), faketag) > 0 && EVP_DecryptUpdate(ctx, NULL, &outl, aad, sizeof(aad)) > 0 && EVP_DecryptUpdate(ctx, buf, &outl, buf, lengths[testnum]) > 0 && EVP_DecryptFinal_ex(ctx, buf + outl, &outl) >0) realcount++; } } else { for (count = 0; COND(c[D_EVP][testnum]); count++) { if (EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv) > 0 && EVP_EncryptUpdate(ctx, NULL, &outl, aad, sizeof(aad)) > 0 && EVP_EncryptUpdate(ctx, buf, &outl, buf, lengths[testnum]) > 0 && EVP_EncryptFinal_ex(ctx, buf + outl, &outl) > 0) realcount++; } } return realcount; } static int RSA_sign_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t *rsa_num = &tempargs->sigsize; EVP_PKEY_CTX **rsa_sign_ctx = tempargs->rsa_sign_ctx; int ret, count; for (count = 0; COND(rsa_c[testnum][0]); count++) { *rsa_num = tempargs->buflen; ret = EVP_PKEY_sign(rsa_sign_ctx[testnum], buf2, rsa_num, buf, 36); if (ret <= 0) { BIO_printf(bio_err, "RSA sign failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int RSA_verify_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t rsa_num = tempargs->sigsize; EVP_PKEY_CTX **rsa_verify_ctx = tempargs->rsa_verify_ctx; int ret, count; for (count = 0; COND(rsa_c[testnum][1]); count++) { ret = EVP_PKEY_verify(rsa_verify_ctx[testnum], buf2, rsa_num, buf, 36); if (ret <= 0) { BIO_printf(bio_err, "RSA verify failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int RSA_encrypt_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t *rsa_num = &tempargs->encsize; EVP_PKEY_CTX **rsa_encrypt_ctx = tempargs->rsa_encrypt_ctx; int ret, count; for (count = 0; COND(rsa_c[testnum][2]); count++) { *rsa_num = tempargs->buflen; ret = EVP_PKEY_encrypt(rsa_encrypt_ctx[testnum], buf2, rsa_num, buf, 36); if (ret <= 0) { BIO_printf(bio_err, "RSA encrypt failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int RSA_decrypt_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t rsa_num; EVP_PKEY_CTX **rsa_decrypt_ctx = tempargs->rsa_decrypt_ctx; int ret, count; for (count = 0; COND(rsa_c[testnum][3]); count++) { rsa_num = tempargs->buflen; ret = EVP_PKEY_decrypt(rsa_decrypt_ctx[testnum], buf, &rsa_num, buf2, tempargs->encsize); if (ret <= 0) { BIO_printf(bio_err, "RSA decrypt failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } #ifndef OPENSSL_NO_DH static int FFDH_derive_key_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ffdh_ctx = tempargs->ffdh_ctx[testnum]; unsigned char *derived_secret = tempargs->secret_ff_a; int count; for (count = 0; COND(ffdh_c[testnum][0]); count++) { size_t outlen = MAX_FFDH_SIZE; EVP_PKEY_derive(ffdh_ctx, derived_secret, &outlen); } return count; } #endif static int DSA_sign_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t *dsa_num = &tempargs->sigsize; EVP_PKEY_CTX **dsa_sign_ctx = tempargs->dsa_sign_ctx; int ret, count; for (count = 0; COND(dsa_c[testnum][0]); count++) { *dsa_num = tempargs->buflen; ret = EVP_PKEY_sign(dsa_sign_ctx[testnum], buf2, dsa_num, buf, 20); if (ret <= 0) { BIO_printf(bio_err, "DSA sign failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int DSA_verify_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t dsa_num = tempargs->sigsize; EVP_PKEY_CTX **dsa_verify_ctx = tempargs->dsa_verify_ctx; int ret, count; for (count = 0; COND(dsa_c[testnum][1]); count++) { ret = EVP_PKEY_verify(dsa_verify_ctx[testnum], buf2, dsa_num, buf, 20); if (ret <= 0) { BIO_printf(bio_err, "DSA verify failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int ECDSA_sign_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t *ecdsa_num = &tempargs->sigsize; EVP_PKEY_CTX **ecdsa_sign_ctx = tempargs->ecdsa_sign_ctx; int ret, count; for (count = 0; COND(ecdsa_c[testnum][0]); count++) { *ecdsa_num = tempargs->buflen; ret = EVP_PKEY_sign(ecdsa_sign_ctx[testnum], buf2, ecdsa_num, buf, 20); if (ret <= 0) { BIO_printf(bio_err, "ECDSA sign failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int ECDSA_verify_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; unsigned char *buf2 = tempargs->buf2; size_t ecdsa_num = tempargs->sigsize; EVP_PKEY_CTX **ecdsa_verify_ctx = tempargs->ecdsa_verify_ctx; int ret, count; for (count = 0; COND(ecdsa_c[testnum][1]); count++) { ret = EVP_PKEY_verify(ecdsa_verify_ctx[testnum], buf2, ecdsa_num, buf, 20); if (ret <= 0) { BIO_printf(bio_err, "ECDSA verify failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int ECDH_EVP_derive_key_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->ecdh_ctx[testnum]; unsigned char *derived_secret = tempargs->secret_a; int count; size_t *outlen = &(tempargs->outlen[testnum]); for (count = 0; COND(ecdh_c[testnum][0]); count++) EVP_PKEY_derive(ctx, derived_secret, outlen); return count; } #ifndef OPENSSL_NO_ECX static int EdDSA_sign_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_MD_CTX **edctx = tempargs->eddsa_ctx; unsigned char *eddsasig = tempargs->buf2; size_t *eddsasigsize = &tempargs->sigsize; int ret, count; for (count = 0; COND(eddsa_c[testnum][0]); count++) { ret = EVP_DigestSignInit(edctx[testnum], NULL, NULL, NULL, NULL); if (ret == 0) { BIO_printf(bio_err, "EdDSA sign init failure\n"); ERR_print_errors(bio_err); count = -1; break; } ret = EVP_DigestSign(edctx[testnum], eddsasig, eddsasigsize, buf, 20); if (ret == 0) { BIO_printf(bio_err, "EdDSA sign failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int EdDSA_verify_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_MD_CTX **edctx = tempargs->eddsa_ctx2; unsigned char *eddsasig = tempargs->buf2; size_t eddsasigsize = tempargs->sigsize; int ret, count; for (count = 0; COND(eddsa_c[testnum][1]); count++) { ret = EVP_DigestVerifyInit(edctx[testnum], NULL, NULL, NULL, NULL); if (ret == 0) { BIO_printf(bio_err, "EdDSA verify init failure\n"); ERR_print_errors(bio_err); count = -1; break; } ret = EVP_DigestVerify(edctx[testnum], eddsasig, eddsasigsize, buf, 20); if (ret != 1) { BIO_printf(bio_err, "EdDSA verify failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } #endif #ifndef OPENSSL_NO_SM2 static int SM2_sign_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_MD_CTX **sm2ctx = tempargs->sm2_ctx; unsigned char *sm2sig = tempargs->buf2; size_t sm2sigsize; int ret, count; EVP_PKEY **sm2_pkey = tempargs->sm2_pkey; const size_t max_size = EVP_PKEY_get_size(sm2_pkey[testnum]); for (count = 0; COND(sm2_c[testnum][0]); count++) { sm2sigsize = max_size; if (!EVP_DigestSignInit(sm2ctx[testnum], NULL, EVP_sm3(), NULL, sm2_pkey[testnum])) { BIO_printf(bio_err, "SM2 init sign failure\n"); ERR_print_errors(bio_err); count = -1; break; } ret = EVP_DigestSign(sm2ctx[testnum], sm2sig, &sm2sigsize, buf, 20); if (ret == 0) { BIO_printf(bio_err, "SM2 sign failure\n"); ERR_print_errors(bio_err); count = -1; break; } tempargs->sigsize = sm2sigsize; } return count; } static int SM2_verify_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; unsigned char *buf = tempargs->buf; EVP_MD_CTX **sm2ctx = tempargs->sm2_vfy_ctx; unsigned char *sm2sig = tempargs->buf2; size_t sm2sigsize = tempargs->sigsize; int ret, count; EVP_PKEY **sm2_pkey = tempargs->sm2_pkey; for (count = 0; COND(sm2_c[testnum][1]); count++) { if (!EVP_DigestVerifyInit(sm2ctx[testnum], NULL, EVP_sm3(), NULL, sm2_pkey[testnum])) { BIO_printf(bio_err, "SM2 verify init failure\n"); ERR_print_errors(bio_err); count = -1; break; } ret = EVP_DigestVerify(sm2ctx[testnum], sm2sig, sm2sigsize, buf, 20); if (ret != 1) { BIO_printf(bio_err, "SM2 verify failure\n"); ERR_print_errors(bio_err); count = -1; break; } } return count; } #endif static int KEM_keygen_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->kem_gen_ctx[testnum]; EVP_PKEY *pkey = NULL; int count; for (count = 0; COND(kems_c[testnum][0]); count++) { if (EVP_PKEY_keygen(ctx, &pkey) <= 0) return -1; EVP_PKEY_free(pkey); pkey = NULL; } return count; } static int KEM_encaps_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->kem_encaps_ctx[testnum]; size_t out_len = tempargs->kem_out_len[testnum]; size_t secret_len = tempargs->kem_secret_len[testnum]; unsigned char *out = tempargs->kem_out[testnum]; unsigned char *secret = tempargs->kem_send_secret[testnum]; int count; for (count = 0; COND(kems_c[testnum][1]); count++) { if (EVP_PKEY_encapsulate(ctx, out, &out_len, secret, &secret_len) <= 0) return -1; } return count; } static int KEM_decaps_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->kem_decaps_ctx[testnum]; size_t out_len = tempargs->kem_out_len[testnum]; size_t secret_len = tempargs->kem_secret_len[testnum]; unsigned char *out = tempargs->kem_out[testnum]; unsigned char *secret = tempargs->kem_send_secret[testnum]; int count; for (count = 0; COND(kems_c[testnum][2]); count++) { if (EVP_PKEY_decapsulate(ctx, secret, &secret_len, out, out_len) <= 0) return -1; } return count; } static int SIG_keygen_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->sig_gen_ctx[testnum]; EVP_PKEY *pkey = NULL; int count; for (count = 0; COND(kems_c[testnum][0]); count++) { EVP_PKEY_keygen(ctx, &pkey); EVP_PKEY_free(pkey); pkey = NULL; } return count; } static int SIG_sign_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->sig_sign_ctx[testnum]; unsigned char *sig = app_malloc(tempargs->sig_max_sig_len[testnum], "sig sign loop"); unsigned char md[SHA256_DIGEST_LENGTH] = { 0 }; size_t md_len = SHA256_DIGEST_LENGTH; int count; for (count = 0; COND(kems_c[testnum][1]); count++) { size_t sig_len = tempargs->sig_max_sig_len[testnum]; int ret = EVP_PKEY_sign(ctx, sig, &sig_len, md, md_len); if (ret <= 0) { BIO_printf(bio_err, "SIG sign failure at count %d\n", count); ERR_print_errors(bio_err); count = -1; break; } } OPENSSL_free(sig); return count; } static int SIG_verify_loop(void *args) { loopargs_t *tempargs = *(loopargs_t **) args; EVP_PKEY_CTX *ctx = tempargs->sig_verify_ctx[testnum]; size_t sig_len = tempargs->sig_act_sig_len[testnum]; unsigned char *sig = tempargs->sig_sig[testnum]; unsigned char md[SHA256_DIGEST_LENGTH] = { 0 }; size_t md_len = SHA256_DIGEST_LENGTH; int count; for (count = 0; COND(kems_c[testnum][2]); count++) { int ret = EVP_PKEY_verify(ctx, sig, sig_len, md, md_len); if (ret <= 0) { BIO_printf(bio_err, "SIG verify failure at count %d\n", count); ERR_print_errors(bio_err); count = -1; break; } } return count; } static int run_benchmark(int async_jobs, int (*loop_function) (void *), loopargs_t *loopargs) { int job_op_count = 0; int total_op_count = 0; int num_inprogress = 0; int error = 0, i = 0, ret = 0; OSSL_ASYNC_FD job_fd = 0; size_t num_job_fds = 0; if (async_jobs == 0) { return loop_function((void *)&loopargs); } for (i = 0; i < async_jobs && !error; i++) { loopargs_t *looparg_item = loopargs + i; ret = ASYNC_start_job(&loopargs[i].inprogress_job, loopargs[i].wait_ctx, &job_op_count, loop_function, (void *)&looparg_item, sizeof(looparg_item)); switch (ret) { case ASYNC_PAUSE: ++num_inprogress; break; case ASYNC_FINISH: if (job_op_count == -1) { error = 1; } else { total_op_count += job_op_count; } break; case ASYNC_NO_JOBS: case ASYNC_ERR: BIO_printf(bio_err, "Failure in the job\n"); ERR_print_errors(bio_err); error = 1; break; } } while (num_inprogress > 0) { #if defined(OPENSSL_SYS_WINDOWS) DWORD avail = 0; #elif defined(OPENSSL_SYS_UNIX) int select_result = 0; OSSL_ASYNC_FD max_fd = 0; fd_set waitfdset; FD_ZERO(&waitfdset); for (i = 0; i < async_jobs && num_inprogress > 0; i++) { if (loopargs[i].inprogress_job == NULL) continue; if (!ASYNC_WAIT_CTX_get_all_fds (loopargs[i].wait_ctx, NULL, &num_job_fds) || num_job_fds > 1) { BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n"); ERR_print_errors(bio_err); error = 1; break; } ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd, &num_job_fds); FD_SET(job_fd, &waitfdset); if (job_fd > max_fd) max_fd = job_fd; } if (max_fd >= (OSSL_ASYNC_FD)FD_SETSIZE) { BIO_printf(bio_err, "Error: max_fd (%d) must be smaller than FD_SETSIZE (%d). " "Decrease the value of async_jobs\n", max_fd, FD_SETSIZE); ERR_print_errors(bio_err); error = 1; break; } select_result = select(max_fd + 1, &waitfdset, NULL, NULL, NULL); if (select_result == -1 && errno == EINTR) continue; if (select_result == -1) { BIO_printf(bio_err, "Failure in the select\n"); ERR_print_errors(bio_err); error = 1; break; } if (select_result == 0) continue; #endif for (i = 0; i < async_jobs; i++) { if (loopargs[i].inprogress_job == NULL) continue; if (!ASYNC_WAIT_CTX_get_all_fds (loopargs[i].wait_ctx, NULL, &num_job_fds) || num_job_fds > 1) { BIO_printf(bio_err, "Too many fds in ASYNC_WAIT_CTX\n"); ERR_print_errors(bio_err); error = 1; break; } ASYNC_WAIT_CTX_get_all_fds(loopargs[i].wait_ctx, &job_fd, &num_job_fds); #if defined(OPENSSL_SYS_UNIX) if (num_job_fds == 1 && !FD_ISSET(job_fd, &waitfdset)) continue; #elif defined(OPENSSL_SYS_WINDOWS) if (num_job_fds == 1 && !PeekNamedPipe(job_fd, NULL, 0, NULL, &avail, NULL) && avail > 0) continue; #endif ret = ASYNC_start_job(&loopargs[i].inprogress_job, loopargs[i].wait_ctx, &job_op_count, loop_function, (void *)(loopargs + i), sizeof(loopargs_t)); switch (ret) { case ASYNC_PAUSE: break; case ASYNC_FINISH: if (job_op_count == -1) { error = 1; } else { total_op_count += job_op_count; } --num_inprogress; loopargs[i].inprogress_job = NULL; break; case ASYNC_NO_JOBS: case ASYNC_ERR: --num_inprogress; loopargs[i].inprogress_job = NULL; BIO_printf(bio_err, "Failure in the job\n"); ERR_print_errors(bio_err); error = 1; break; } } } return error ? -1 : total_op_count; } typedef struct ec_curve_st { const char *name; unsigned int nid; unsigned int bits; size_t sigsize; } EC_CURVE; static EVP_PKEY *get_ecdsa(const EC_CURVE *curve) { EVP_PKEY_CTX *kctx = NULL; EVP_PKEY *key = NULL; if (ERR_peek_error()) { BIO_printf(bio_err, "WARNING: the error queue contains previous unhandled errors.\n"); ERR_print_errors(bio_err); } kctx = EVP_PKEY_CTX_new_id(curve->nid, NULL); if (kctx == NULL) { EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *params = NULL; unsigned long error = ERR_peek_error(); if (error == ERR_peek_last_error() && ERR_GET_LIB(error) == ERR_LIB_EVP && (ERR_GET_REASON(error) == EVP_R_UNSUPPORTED_ALGORITHM || ERR_GET_REASON(error) == ERR_R_UNSUPPORTED)) ERR_get_error(); if (ERR_peek_error()) { BIO_printf(bio_err, "Unhandled error in the error queue during EC key setup.\n"); ERR_print_errors(bio_err); return NULL; } if ((pctx = EVP_PKEY_CTX_new_from_name(NULL, "EC", NULL)) == NULL || EVP_PKEY_paramgen_init(pctx) <= 0 || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, curve->nid) <= 0 || EVP_PKEY_paramgen(pctx, &params) <= 0) { BIO_printf(bio_err, "EC params init failure.\n"); ERR_print_errors(bio_err); EVP_PKEY_CTX_free(pctx); return NULL; } EVP_PKEY_CTX_free(pctx); kctx = EVP_PKEY_CTX_new(params, NULL); EVP_PKEY_free(params); } if (kctx == NULL || EVP_PKEY_keygen_init(kctx) <= 0 || EVP_PKEY_keygen(kctx, &key) <= 0) { BIO_printf(bio_err, "EC key generation failure.\n"); ERR_print_errors(bio_err); key = NULL; } EVP_PKEY_CTX_free(kctx); return key; } #define stop_it(do_it, test_num)\ memset(do_it + test_num, 0, OSSL_NELEM(do_it) - test_num); #define IS_FETCHABLE(type, TYPE) \ static int is_ ## type ## _fetchable(const TYPE *alg) \ { \ TYPE *impl; \ const char *propq = app_get0_propq(); \ OSSL_LIB_CTX *libctx = app_get0_libctx(); \ const char *name = TYPE ## _get0_name(alg); \ \ ERR_set_mark(); \ impl = TYPE ## _fetch(libctx, name, propq); \ ERR_pop_to_mark(); \ if (impl == NULL) \ return 0; \ TYPE ## _free(impl); \ return 1; \ } IS_FETCHABLE(signature, EVP_SIGNATURE) IS_FETCHABLE(kem, EVP_KEM) DEFINE_STACK_OF(EVP_KEM) static int kems_cmp(const EVP_KEM * const *a, const EVP_KEM * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_KEM_get0_provider(*b))); } static void collect_kem(EVP_KEM *kem, void *stack) { STACK_OF(EVP_KEM) *kem_stack = stack; if (is_kem_fetchable(kem) && sk_EVP_KEM_push(kem_stack, kem) > 0) { EVP_KEM_up_ref(kem); } } static int kem_locate(const char *algo, unsigned int *idx) { unsigned int i; for (i = 0; i < kems_algs_len; i++) { if (strcmp(kems_algname[i], algo) == 0) { *idx = i; return 1; } } return 0; } DEFINE_STACK_OF(EVP_SIGNATURE) static int signatures_cmp(const EVP_SIGNATURE * const *a, const EVP_SIGNATURE * const *b) { return strcmp(OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(*a)), OSSL_PROVIDER_get0_name(EVP_SIGNATURE_get0_provider(*b))); } static void collect_signatures(EVP_SIGNATURE *sig, void *stack) { STACK_OF(EVP_SIGNATURE) *sig_stack = stack; if (is_signature_fetchable(sig) && sk_EVP_SIGNATURE_push(sig_stack, sig) > 0) EVP_SIGNATURE_up_ref(sig); } static int sig_locate(const char *algo, unsigned int *idx) { unsigned int i; for (i = 0; i < sigs_algs_len; i++) { if (strcmp(sigs_algname[i], algo) == 0) { *idx = i; return 1; } } return 0; } static int get_max(const uint8_t doit[], size_t algs_len) { size_t i = 0; int maxcnt = 0; for (i = 0; i < algs_len; i++) if (maxcnt < doit[i]) maxcnt = doit[i]; return maxcnt; } int speed_main(int argc, char **argv) { CONF *conf = NULL; ENGINE *e = NULL; loopargs_t *loopargs = NULL; const char *prog; const char *engine_id = NULL; EVP_CIPHER *evp_cipher = NULL; EVP_MAC *mac = NULL; double d = 0.0; OPTION_CHOICE o; int async_init = 0, multiblock = 0, pr_header = 0; uint8_t doit[ALGOR_NUM] = { 0 }; int ret = 1, misalign = 0, lengths_single = 0, aead = 0; STACK_OF(EVP_KEM) *kem_stack = NULL; STACK_OF(EVP_SIGNATURE) *sig_stack = NULL; long count = 0; unsigned int size_num = SIZE_NUM; unsigned int i, k, loopargs_len = 0, async_jobs = 0; unsigned int idx; int keylen; int buflen; size_t declen; BIGNUM *bn = NULL; EVP_PKEY_CTX *genctx = NULL; #ifndef NO_FORK int multi = 0; #endif long op_count = 1; openssl_speed_sec_t seconds = { SECONDS, RSA_SECONDS, DSA_SECONDS, ECDSA_SECONDS, ECDH_SECONDS, EdDSA_SECONDS, SM2_SECONDS, FFDH_SECONDS, KEM_SECONDS, SIG_SECONDS }; static const unsigned char key32[32] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56 }; static const unsigned char deskey[] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34 }; static const struct { const unsigned char *data; unsigned int length; unsigned int bits; } rsa_keys[] = { { test512, sizeof(test512), 512 }, { test1024, sizeof(test1024), 1024 }, { test2048, sizeof(test2048), 2048 }, { test3072, sizeof(test3072), 3072 }, { test4096, sizeof(test4096), 4096 }, { test7680, sizeof(test7680), 7680 }, { test15360, sizeof(test15360), 15360 } }; uint8_t rsa_doit[RSA_NUM] = { 0 }; int primes = RSA_DEFAULT_PRIME_NUM; #ifndef OPENSSL_NO_DH typedef struct ffdh_params_st { const char *name; unsigned int nid; unsigned int bits; } FFDH_PARAMS; static const FFDH_PARAMS ffdh_params[FFDH_NUM] = { {"ffdh2048", NID_ffdhe2048, 2048}, {"ffdh3072", NID_ffdhe3072, 3072}, {"ffdh4096", NID_ffdhe4096, 4096}, {"ffdh6144", NID_ffdhe6144, 6144}, {"ffdh8192", NID_ffdhe8192, 8192} }; uint8_t ffdh_doit[FFDH_NUM] = { 0 }; #endif static const unsigned int dsa_bits[DSA_NUM] = { 1024, 2048 }; uint8_t dsa_doit[DSA_NUM] = { 0 }; static const EC_CURVE ec_curves[EC_NUM] = { {"secp160r1", NID_secp160r1, 160}, {"nistp192", NID_X9_62_prime192v1, 192}, {"nistp224", NID_secp224r1, 224}, {"nistp256", NID_X9_62_prime256v1, 256}, {"nistp384", NID_secp384r1, 384}, {"nistp521", NID_secp521r1, 521}, #ifndef OPENSSL_NO_EC2M {"nistk163", NID_sect163k1, 163}, {"nistk233", NID_sect233k1, 233}, {"nistk283", NID_sect283k1, 283}, {"nistk409", NID_sect409k1, 409}, {"nistk571", NID_sect571k1, 571}, {"nistb163", NID_sect163r2, 163}, {"nistb233", NID_sect233r1, 233}, {"nistb283", NID_sect283r1, 283}, {"nistb409", NID_sect409r1, 409}, {"nistb571", NID_sect571r1, 571}, #endif {"brainpoolP256r1", NID_brainpoolP256r1, 256}, {"brainpoolP256t1", NID_brainpoolP256t1, 256}, {"brainpoolP384r1", NID_brainpoolP384r1, 384}, {"brainpoolP384t1", NID_brainpoolP384t1, 384}, {"brainpoolP512r1", NID_brainpoolP512r1, 512}, {"brainpoolP512t1", NID_brainpoolP512t1, 512}, #ifndef OPENSSL_NO_ECX {"X25519", NID_X25519, 253}, {"X448", NID_X448, 448} #endif }; #ifndef OPENSSL_NO_ECX static const EC_CURVE ed_curves[EdDSA_NUM] = { {"Ed25519", NID_ED25519, 253, 64}, {"Ed448", NID_ED448, 456, 114} }; #endif #ifndef OPENSSL_NO_SM2 static const EC_CURVE sm2_curves[SM2_NUM] = { {"CurveSM2", NID_sm2, 256} }; uint8_t sm2_doit[SM2_NUM] = { 0 }; #endif uint8_t ecdsa_doit[ECDSA_NUM] = { 0 }; uint8_t ecdh_doit[EC_NUM] = { 0 }; #ifndef OPENSSL_NO_ECX uint8_t eddsa_doit[EdDSA_NUM] = { 0 }; #endif uint8_t kems_doit[MAX_KEM_NUM] = { 0 }; uint8_t sigs_doit[MAX_SIG_NUM] = { 0 }; uint8_t do_kems = 0; uint8_t do_sigs = 0; #ifndef OPENSSL_NO_ECX OPENSSL_assert(ed_curves[EdDSA_NUM - 1].nid == NID_ED448); OPENSSL_assert(strcmp(eddsa_choices[EdDSA_NUM - 1].name, "ed448") == 0); OPENSSL_assert(ec_curves[EC_NUM - 1].nid == NID_X448); OPENSSL_assert(strcmp(ecdh_choices[EC_NUM - 1].name, "ecdhx448") == 0); OPENSSL_assert(ec_curves[ECDSA_NUM - 1].nid == NID_brainpoolP512t1); OPENSSL_assert(strcmp(ecdsa_choices[ECDSA_NUM - 1].name, "ecdsabrp512t1") == 0); #endif #ifndef OPENSSL_NO_SM2 OPENSSL_assert(sm2_curves[SM2_NUM - 1].nid == NID_sm2); OPENSSL_assert(strcmp(sm2_choices[SM2_NUM - 1].name, "curveSM2") == 0); #endif prog = opt_init(argc, argv, speed_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opterr: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(speed_options); ret = 0; goto end; case OPT_ELAPSED: usertime = 0; break; case OPT_EVP: if (doit[D_EVP]) { BIO_printf(bio_err, "%s: -evp option cannot be used more than once\n", prog); goto opterr; } ERR_set_mark(); if (!opt_cipher_silent(opt_arg(), &evp_cipher)) { if (have_md(opt_arg())) evp_md_name = opt_arg(); } if (evp_cipher == NULL && evp_md_name == NULL) { ERR_clear_last_mark(); BIO_printf(bio_err, "%s: %s is an unknown cipher or digest\n", prog, opt_arg()); goto end; } ERR_pop_to_mark(); doit[D_EVP] = 1; break; case OPT_HMAC: if (!have_md(opt_arg())) { BIO_printf(bio_err, "%s: %s is an unknown digest\n", prog, opt_arg()); goto end; } evp_mac_mdname = opt_arg(); doit[D_HMAC] = 1; break; case OPT_CMAC: if (!have_cipher(opt_arg())) { BIO_printf(bio_err, "%s: %s is an unknown cipher\n", prog, opt_arg()); goto end; } evp_mac_ciphername = opt_arg(); doit[D_EVP_CMAC] = 1; break; case OPT_DECRYPT: decrypt = 1; break; case OPT_ENGINE: engine_id = opt_arg(); break; case OPT_MULTI: #ifndef NO_FORK multi = opt_int_arg(); if ((size_t)multi >= SIZE_MAX / sizeof(int)) { BIO_printf(bio_err, "%s: multi argument too large\n", prog); return 0; } #endif break; case OPT_ASYNCJOBS: #ifndef OPENSSL_NO_ASYNC async_jobs = opt_int_arg(); if (!ASYNC_is_capable()) { BIO_printf(bio_err, "%s: async_jobs specified but async not supported\n", prog); goto opterr; } if (async_jobs > 99999) { BIO_printf(bio_err, "%s: too many async_jobs\n", prog); goto opterr; } #endif break; case OPT_MISALIGN: misalign = opt_int_arg(); if (misalign > MISALIGN) { BIO_printf(bio_err, "%s: Maximum offset is %d\n", prog, MISALIGN); goto opterr; } break; case OPT_MR: mr = 1; break; case OPT_MB: multiblock = 1; #ifdef OPENSSL_NO_MULTIBLOCK BIO_printf(bio_err, "%s: -mb specified but multi-block support is disabled\n", prog); goto end; #endif break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_CONFIG: conf = app_load_config_modules(opt_arg()); if (conf == NULL) goto end; break; case OPT_PRIMES: primes = opt_int_arg(); break; case OPT_SECONDS: seconds.sym = seconds.rsa = seconds.dsa = seconds.ecdsa = seconds.ecdh = seconds.eddsa = seconds.sm2 = seconds.ffdh = seconds.kem = seconds.sig = opt_int_arg(); break; case OPT_BYTES: lengths_single = opt_int_arg(); lengths = &lengths_single; size_num = 1; break; case OPT_AEAD: aead = 1; break; case OPT_KEM: do_kems = 1; break; case OPT_SIG: do_sigs = 1; break; case OPT_MLOCK: domlock = 1; #if !defined(_WIN32) && !defined(OPENSSL_SYS_LINUX) BIO_printf(bio_err, "%s: -mlock not supported on this platform\n", prog); goto end; #endif break; } } kem_stack = sk_EVP_KEM_new(kems_cmp); EVP_KEM_do_all_provided(app_get0_libctx(), collect_kem, kem_stack); kems_algs_len = 0; for (idx = 0; idx < (unsigned int)sk_EVP_KEM_num(kem_stack); idx++) { EVP_KEM *kem = sk_EVP_KEM_value(kem_stack, idx); if (strcmp(EVP_KEM_get0_name(kem), "RSA") == 0) { if (kems_algs_len + OSSL_NELEM(rsa_choices) >= MAX_KEM_NUM) { BIO_printf(bio_err, "Too many KEMs registered. Change MAX_KEM_NUM.\n"); goto end; } for (i = 0; i < OSSL_NELEM(rsa_choices); i++) { kems_doit[kems_algs_len] = 1; kems_algname[kems_algs_len++] = OPENSSL_strdup(rsa_choices[i].name); } } else if (strcmp(EVP_KEM_get0_name(kem), "EC") == 0) { if (kems_algs_len + 3 >= MAX_KEM_NUM) { BIO_printf(bio_err, "Too many KEMs registered. Change MAX_KEM_NUM.\n"); goto end; } kems_doit[kems_algs_len] = 1; kems_algname[kems_algs_len++] = OPENSSL_strdup("ECP-256"); kems_doit[kems_algs_len] = 1; kems_algname[kems_algs_len++] = OPENSSL_strdup("ECP-384"); kems_doit[kems_algs_len] = 1; kems_algname[kems_algs_len++] = OPENSSL_strdup("ECP-521"); } else { if (kems_algs_len + 1 >= MAX_KEM_NUM) { BIO_printf(bio_err, "Too many KEMs registered. Change MAX_KEM_NUM.\n"); goto end; } kems_doit[kems_algs_len] = 1; kems_algname[kems_algs_len++] = OPENSSL_strdup(EVP_KEM_get0_name(kem)); } } sk_EVP_KEM_pop_free(kem_stack, EVP_KEM_free); kem_stack = NULL; sig_stack = sk_EVP_SIGNATURE_new(signatures_cmp); EVP_SIGNATURE_do_all_provided(app_get0_libctx(), collect_signatures, sig_stack); sigs_algs_len = 0; for (idx = 0; idx < (unsigned int)sk_EVP_SIGNATURE_num(sig_stack); idx++) { EVP_SIGNATURE *s = sk_EVP_SIGNATURE_value(sig_stack, idx); const char *sig_name = EVP_SIGNATURE_get0_name(s); if (strcmp(sig_name, "RSA") == 0) { if (sigs_algs_len + OSSL_NELEM(rsa_choices) >= MAX_SIG_NUM) { BIO_printf(bio_err, "Too many signatures registered. Change MAX_SIG_NUM.\n"); goto end; } for (i = 0; i < OSSL_NELEM(rsa_choices); i++) { sigs_doit[sigs_algs_len] = 1; sigs_algname[sigs_algs_len++] = OPENSSL_strdup(rsa_choices[i].name); } } else if (strcmp(sig_name, "DSA") == 0) { if (sigs_algs_len + DSA_NUM >= MAX_SIG_NUM) { BIO_printf(bio_err, "Too many signatures registered. Change MAX_SIG_NUM.\n"); goto end; } for (i = 0; i < DSA_NUM; i++) { sigs_doit[sigs_algs_len] = 1; sigs_algname[sigs_algs_len++] = OPENSSL_strdup(dsa_choices[i].name); } } else if (strcmp(sig_name, "ED25519") && strcmp(sig_name, "ED448") && strcmp(sig_name, "ECDSA") && strcmp(sig_name, "HMAC") && strcmp(sig_name, "SIPHASH") && strcmp(sig_name, "POLY1305") && strcmp(sig_name, "CMAC") && strcmp(sig_name, "SM2")) { if (sigs_algs_len + 1 >= MAX_SIG_NUM) { BIO_printf(bio_err, "Too many signatures registered. Change MAX_SIG_NUM.\n"); goto end; } sigs_doit[sigs_algs_len] = 1; sigs_algname[sigs_algs_len++] = OPENSSL_strdup(sig_name); } } sk_EVP_SIGNATURE_pop_free(sig_stack, EVP_SIGNATURE_free); sig_stack = NULL; argc = opt_num_rest(); argv = opt_rest(); if (!app_RAND_load()) goto end; for (; *argv; argv++) { const char *algo = *argv; int algo_found = 0; if (opt_found(algo, doit_choices, &i)) { doit[i] = 1; algo_found = 1; } if (strcmp(algo, "des") == 0) { doit[D_CBC_DES] = doit[D_EDE3_DES] = 1; algo_found = 1; } if (strcmp(algo, "sha") == 0) { doit[D_SHA1] = doit[D_SHA256] = doit[D_SHA512] = 1; algo_found = 1; } #ifndef OPENSSL_NO_DEPRECATED_3_0 if (strcmp(algo, "openssl") == 0) algo_found = 1; #endif if (HAS_PREFIX(algo, "rsa")) { if (algo[sizeof("rsa") - 1] == '\0') { memset(rsa_doit, 1, sizeof(rsa_doit)); algo_found = 1; } if (opt_found(algo, rsa_choices, &i)) { rsa_doit[i] = 1; algo_found = 1; } } #ifndef OPENSSL_NO_DH if (HAS_PREFIX(algo, "ffdh")) { if (algo[sizeof("ffdh") - 1] == '\0') { memset(ffdh_doit, 1, sizeof(ffdh_doit)); algo_found = 1; } if (opt_found(algo, ffdh_choices, &i)) { ffdh_doit[i] = 2; algo_found = 1; } } #endif if (HAS_PREFIX(algo, "dsa")) { if (algo[sizeof("dsa") - 1] == '\0') { memset(dsa_doit, 1, sizeof(dsa_doit)); algo_found = 1; } if (opt_found(algo, dsa_choices, &i)) { dsa_doit[i] = 2; algo_found = 1; } } if (strcmp(algo, "aes") == 0) { doit[D_CBC_128_AES] = doit[D_CBC_192_AES] = doit[D_CBC_256_AES] = 1; algo_found = 1; } if (strcmp(algo, "camellia") == 0) { doit[D_CBC_128_CML] = doit[D_CBC_192_CML] = doit[D_CBC_256_CML] = 1; algo_found = 1; } if (HAS_PREFIX(algo, "ecdsa")) { if (algo[sizeof("ecdsa") - 1] == '\0') { memset(ecdsa_doit, 1, sizeof(ecdsa_doit)); algo_found = 1; } if (opt_found(algo, ecdsa_choices, &i)) { ecdsa_doit[i] = 2; algo_found = 1; } } if (HAS_PREFIX(algo, "ecdh")) { if (algo[sizeof("ecdh") - 1] == '\0') { memset(ecdh_doit, 1, sizeof(ecdh_doit)); algo_found = 1; } if (opt_found(algo, ecdh_choices, &i)) { ecdh_doit[i] = 2; algo_found = 1; } } #ifndef OPENSSL_NO_ECX if (strcmp(algo, "eddsa") == 0) { memset(eddsa_doit, 1, sizeof(eddsa_doit)); algo_found = 1; } if (opt_found(algo, eddsa_choices, &i)) { eddsa_doit[i] = 2; algo_found = 1; } #endif #ifndef OPENSSL_NO_SM2 if (strcmp(algo, "sm2") == 0) { memset(sm2_doit, 1, sizeof(sm2_doit)); algo_found = 1; } if (opt_found(algo, sm2_choices, &i)) { sm2_doit[i] = 2; algo_found = 1; } #endif if (kem_locate(algo, &idx)) { kems_doit[idx]++; do_kems = 1; algo_found = 1; } if (sig_locate(algo, &idx)) { sigs_doit[idx]++; do_sigs = 1; algo_found = 1; } if (strcmp(algo, "kmac") == 0) { doit[D_KMAC128] = doit[D_KMAC256] = 1; algo_found = 1; } if (strcmp(algo, "cmac") == 0) { doit[D_EVP_CMAC] = 1; algo_found = 1; } if (!algo_found) { BIO_printf(bio_err, "%s: Unknown algorithm %s\n", prog, algo); goto end; } } if (aead) { if (evp_cipher == NULL) { BIO_printf(bio_err, "-aead can be used only with an AEAD cipher\n"); goto end; } else if (!(EVP_CIPHER_get_flags(evp_cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)) { BIO_printf(bio_err, "%s is not an AEAD cipher\n", EVP_CIPHER_get0_name(evp_cipher)); goto end; } } if (kems_algs_len > 0) { int maxcnt = get_max(kems_doit, kems_algs_len); if (maxcnt > 1) { for (i = 0; i < kems_algs_len; i++) { kems_doit[i]--; } } } if (sigs_algs_len > 0) { int maxcnt = get_max(sigs_doit, sigs_algs_len); if (maxcnt > 1) { for (i = 0; i < sigs_algs_len; i++) { sigs_doit[i]--; } } } if (multiblock) { if (evp_cipher == NULL) { BIO_printf(bio_err, "-mb can be used only with a multi-block" " capable cipher\n"); goto end; } else if (!(EVP_CIPHER_get_flags(evp_cipher) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) { BIO_printf(bio_err, "%s is not a multi-block capable\n", EVP_CIPHER_get0_name(evp_cipher)); goto end; } else if (async_jobs > 0) { BIO_printf(bio_err, "Async mode is not supported with -mb"); goto end; } } if (async_jobs > 0) { async_init = ASYNC_init_thread(async_jobs, async_jobs); if (!async_init) { BIO_printf(bio_err, "Error creating the ASYNC job pool\n"); goto end; } } loopargs_len = (async_jobs == 0 ? 1 : async_jobs); loopargs = app_malloc(loopargs_len * sizeof(loopargs_t), "array of loopargs"); memset(loopargs, 0, loopargs_len * sizeof(loopargs_t)); buflen = lengths[size_num - 1]; if (buflen < 36) buflen = 36; if (INT_MAX - (MAX_MISALIGNMENT + 1) < buflen) { BIO_printf(bio_err, "Error: buffer size too large\n"); goto end; } buflen += MAX_MISALIGNMENT + 1; for (i = 0; i < loopargs_len; i++) { if (async_jobs > 0) { loopargs[i].wait_ctx = ASYNC_WAIT_CTX_new(); if (loopargs[i].wait_ctx == NULL) { BIO_printf(bio_err, "Error creating the ASYNC_WAIT_CTX\n"); goto end; } } loopargs[i].buf_malloc = app_malloc(buflen, "input buffer"); loopargs[i].buf2_malloc = app_malloc(buflen, "input buffer"); loopargs[i].buf = loopargs[i].buf_malloc + misalign; loopargs[i].buf2 = loopargs[i].buf2_malloc + misalign; loopargs[i].buflen = buflen - misalign; loopargs[i].sigsize = buflen - misalign; loopargs[i].secret_a = app_malloc(MAX_ECDH_SIZE, "ECDH secret a"); loopargs[i].secret_b = app_malloc(MAX_ECDH_SIZE, "ECDH secret b"); #ifndef OPENSSL_NO_DH loopargs[i].secret_ff_a = app_malloc(MAX_FFDH_SIZE, "FFDH secret a"); loopargs[i].secret_ff_b = app_malloc(MAX_FFDH_SIZE, "FFDH secret b"); #endif } #ifndef NO_FORK if (multi && do_multi(multi, size_num)) goto show_res; #endif for (i = 0; i < loopargs_len; ++i) { if (domlock) { #if defined(_WIN32) (void)VirtualLock(loopargs[i].buf_malloc, buflen); (void)VirtualLock(loopargs[i].buf2_malloc, buflen); #elif defined(OPENSSL_SYS_LINUX) (void)mlock(loopargs[i].buf_malloc, buflen); (void)mlock(loopargs[i].buf_malloc, buflen); #endif } memset(loopargs[i].buf_malloc, 0, buflen); memset(loopargs[i].buf2_malloc, 0, buflen); } e = setup_engine(engine_id, 0); if (argc == 0 && !doit[D_EVP] && !doit[D_HMAC] && !doit[D_EVP_CMAC] && !do_kems && !do_sigs) { memset(doit, 1, sizeof(doit)); doit[D_EVP] = doit[D_EVP_CMAC] = 0; ERR_set_mark(); for (i = D_MD2; i <= D_WHIRLPOOL; i++) { if (!have_md(names[i])) doit[i] = 0; } for (i = D_CBC_DES; i <= D_CBC_256_CML; i++) { if (!have_cipher(names[i])) doit[i] = 0; } if ((mac = EVP_MAC_fetch(app_get0_libctx(), "GMAC", app_get0_propq())) != NULL) { EVP_MAC_free(mac); mac = NULL; } else { doit[D_GHASH] = 0; } if ((mac = EVP_MAC_fetch(app_get0_libctx(), "HMAC", app_get0_propq())) != NULL) { EVP_MAC_free(mac); mac = NULL; } else { doit[D_HMAC] = 0; } ERR_pop_to_mark(); memset(rsa_doit, 1, sizeof(rsa_doit)); #ifndef OPENSSL_NO_DH memset(ffdh_doit, 1, sizeof(ffdh_doit)); #endif memset(dsa_doit, 1, sizeof(dsa_doit)); #ifndef OPENSSL_NO_ECX memset(ecdsa_doit, 1, sizeof(ecdsa_doit)); memset(ecdh_doit, 1, sizeof(ecdh_doit)); memset(eddsa_doit, 1, sizeof(eddsa_doit)); #endif #ifndef OPENSSL_NO_SM2 memset(sm2_doit, 1, sizeof(sm2_doit)); #endif memset(kems_doit, 1, sizeof(kems_doit)); do_kems = 1; memset(sigs_doit, 1, sizeof(sigs_doit)); do_sigs = 1; } for (i = 0; i < ALGOR_NUM; i++) if (doit[i]) pr_header++; if (usertime == 0 && !mr) BIO_printf(bio_err, "You have chosen to measure elapsed time " "instead of user CPU time.\n"); #if SIGALRM > 0 signal(SIGALRM, alarmed); #endif if (doit[D_MD2]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_MD2], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_MD2_loop, loopargs); d = Time_F(STOP); print_result(D_MD2, testnum, count, d); if (count < 0) break; } } if (doit[D_MDC2]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_MDC2], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_MDC2_loop, loopargs); d = Time_F(STOP); print_result(D_MDC2, testnum, count, d); if (count < 0) break; } } if (doit[D_MD4]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_MD4], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_MD4_loop, loopargs); d = Time_F(STOP); print_result(D_MD4, testnum, count, d); if (count < 0) break; } } if (doit[D_MD5]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_MD5], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, MD5_loop, loopargs); d = Time_F(STOP); print_result(D_MD5, testnum, count, d); if (count < 0) break; } } if (doit[D_SHA1]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_SHA1], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, SHA1_loop, loopargs); d = Time_F(STOP); print_result(D_SHA1, testnum, count, d); if (count < 0) break; } } if (doit[D_SHA256]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_SHA256], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, SHA256_loop, loopargs); d = Time_F(STOP); print_result(D_SHA256, testnum, count, d); if (count < 0) break; } } if (doit[D_SHA512]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_SHA512], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, SHA512_loop, loopargs); d = Time_F(STOP); print_result(D_SHA512, testnum, count, d); if (count < 0) break; } } if (doit[D_WHIRLPOOL]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_WHIRLPOOL], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, WHIRLPOOL_loop, loopargs); d = Time_F(STOP); print_result(D_WHIRLPOOL, testnum, count, d); if (count < 0) break; } } if (doit[D_RMD160]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_RMD160], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_RMD160_loop, loopargs); d = Time_F(STOP); print_result(D_RMD160, testnum, count, d); if (count < 0) break; } } if (doit[D_HMAC]) { static const char hmac_key[] = "This is a key..."; int len = strlen(hmac_key); OSSL_PARAM params[3]; if (evp_mac_mdname == NULL) goto end; evp_hmac_name = app_malloc(sizeof("hmac()") + strlen(evp_mac_mdname), "HMAC name"); sprintf(evp_hmac_name, "hmac(%s)", evp_mac_mdname); names[D_HMAC] = evp_hmac_name; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, evp_mac_mdname, 0); params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (char *)hmac_key, len); params[2] = OSSL_PARAM_construct_end(); if (mac_setup("HMAC", &mac, params, loopargs, loopargs_len) < 1) goto end; for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_HMAC], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, HMAC_loop, loopargs); d = Time_F(STOP); print_result(D_HMAC, testnum, count, d); if (count < 0) break; } mac_teardown(&mac, loopargs, loopargs_len); } if (doit[D_CBC_DES]) { int st = 1; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ctx = init_evp_cipher_ctx("des-cbc", deskey, sizeof(deskey) / 3); st = loopargs[i].ctx != NULL; } algindex = D_CBC_DES; for (testnum = 0; st && testnum < size_num; testnum++) { print_message(names[D_CBC_DES], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs); d = Time_F(STOP); print_result(D_CBC_DES, testnum, count, d); } for (i = 0; i < loopargs_len; i++) EVP_CIPHER_CTX_free(loopargs[i].ctx); } if (doit[D_EDE3_DES]) { int st = 1; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ctx = init_evp_cipher_ctx("des-ede3-cbc", deskey, sizeof(deskey)); st = loopargs[i].ctx != NULL; } algindex = D_EDE3_DES; for (testnum = 0; st && testnum < size_num; testnum++) { print_message(names[D_EDE3_DES], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs); d = Time_F(STOP); print_result(D_EDE3_DES, testnum, count, d); } for (i = 0; i < loopargs_len; i++) EVP_CIPHER_CTX_free(loopargs[i].ctx); } for (k = 0; k < 3; k++) { algindex = D_CBC_128_AES + k; if (doit[algindex]) { int st = 1; keylen = 16 + k * 8; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ctx = init_evp_cipher_ctx(names[algindex], key32, keylen); st = loopargs[i].ctx != NULL; } for (testnum = 0; st && testnum < size_num; testnum++) { print_message(names[algindex], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs); d = Time_F(STOP); print_result(algindex, testnum, count, d); } for (i = 0; i < loopargs_len; i++) EVP_CIPHER_CTX_free(loopargs[i].ctx); } } for (k = 0; k < 3; k++) { algindex = D_CBC_128_CML + k; if (doit[algindex]) { int st = 1; keylen = 16 + k * 8; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ctx = init_evp_cipher_ctx(names[algindex], key32, keylen); st = loopargs[i].ctx != NULL; } for (testnum = 0; st && testnum < size_num; testnum++) { print_message(names[algindex], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs); d = Time_F(STOP); print_result(algindex, testnum, count, d); } for (i = 0; i < loopargs_len; i++) EVP_CIPHER_CTX_free(loopargs[i].ctx); } } for (algindex = D_RC4; algindex <= D_CBC_CAST; algindex++) { if (doit[algindex]) { int st = 1; keylen = 16; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ctx = init_evp_cipher_ctx(names[algindex], key32, keylen); st = loopargs[i].ctx != NULL; } for (testnum = 0; st && testnum < size_num; testnum++) { print_message(names[algindex], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Cipher_loop, loopargs); d = Time_F(STOP); print_result(algindex, testnum, count, d); } for (i = 0; i < loopargs_len; i++) EVP_CIPHER_CTX_free(loopargs[i].ctx); } } if (doit[D_GHASH]) { static const char gmac_iv[] = "0123456789ab"; OSSL_PARAM params[4]; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_CIPHER, "aes-128-gcm", 0); params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_IV, (char *)gmac_iv, sizeof(gmac_iv) - 1); params[2] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (void *)key32, 16); params[3] = OSSL_PARAM_construct_end(); if (mac_setup("GMAC", &mac, params, loopargs, loopargs_len) < 1) goto end; for (i = 0; i < loopargs_len; i++) { if (!EVP_MAC_init(loopargs[i].mctx, NULL, 0, NULL)) goto end; } for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_GHASH], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, GHASH_loop, loopargs); d = Time_F(STOP); print_result(D_GHASH, testnum, count, d); if (count < 0) break; } mac_teardown(&mac, loopargs, loopargs_len); } if (doit[D_RAND]) { for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_RAND], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, RAND_bytes_loop, loopargs); d = Time_F(STOP); print_result(D_RAND, testnum, count, d); } } if (doit[D_EVP]) { if (evp_cipher != NULL) { int (*loopfunc) (void *) = EVP_Update_loop; if (multiblock && (EVP_CIPHER_get_flags(evp_cipher) & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK)) { multiblock_speed(evp_cipher, lengths_single, &seconds); ret = 0; goto end; } names[D_EVP] = EVP_CIPHER_get0_name(evp_cipher); if (EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_CCM_MODE) { loopfunc = EVP_Update_loop_ccm; } else if (aead && (EVP_CIPHER_get_flags(evp_cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)) { loopfunc = EVP_Update_loop_aead; if (lengths == lengths_list) { lengths = aead_lengths_list; size_num = OSSL_NELEM(aead_lengths_list); } } for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_EVP], lengths[testnum], seconds.sym); for (k = 0; k < loopargs_len; k++) { loopargs[k].ctx = EVP_CIPHER_CTX_new(); if (loopargs[k].ctx == NULL) { BIO_printf(bio_err, "\nEVP_CIPHER_CTX_new failure\n"); exit(1); } if (!EVP_CipherInit_ex(loopargs[k].ctx, evp_cipher, NULL, NULL, iv, decrypt ? 0 : 1)) { BIO_printf(bio_err, "\nEVP_CipherInit_ex failure\n"); ERR_print_errors(bio_err); exit(1); } EVP_CIPHER_CTX_set_padding(loopargs[k].ctx, 0); keylen = EVP_CIPHER_CTX_get_key_length(loopargs[k].ctx); loopargs[k].key = app_malloc(keylen, "evp_cipher key"); EVP_CIPHER_CTX_rand_key(loopargs[k].ctx, loopargs[k].key); if (!EVP_CipherInit_ex(loopargs[k].ctx, NULL, NULL, loopargs[k].key, NULL, -1)) { BIO_printf(bio_err, "\nEVP_CipherInit_ex failure\n"); ERR_print_errors(bio_err); exit(1); } OPENSSL_clear_free(loopargs[k].key, keylen); if (EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_SIV_MODE || EVP_CIPHER_get_mode(evp_cipher) == EVP_CIPH_GCM_SIV_MODE) (void)EVP_CIPHER_CTX_ctrl(loopargs[k].ctx, EVP_CTRL_SET_SPEED, 1, NULL); } Time_F(START); count = run_benchmark(async_jobs, loopfunc, loopargs); d = Time_F(STOP); for (k = 0; k < loopargs_len; k++) EVP_CIPHER_CTX_free(loopargs[k].ctx); print_result(D_EVP, testnum, count, d); } } else if (evp_md_name != NULL) { names[D_EVP] = evp_md_name; for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_EVP], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, EVP_Digest_md_loop, loopargs); d = Time_F(STOP); print_result(D_EVP, testnum, count, d); if (count < 0) break; } } } if (doit[D_EVP_CMAC]) { OSSL_PARAM params[3]; EVP_CIPHER *cipher = NULL; if (!opt_cipher(evp_mac_ciphername, &cipher)) goto end; keylen = EVP_CIPHER_get_key_length(cipher); EVP_CIPHER_free(cipher); if (keylen <= 0 || keylen > (int)sizeof(key32)) { BIO_printf(bio_err, "\nRequested CMAC cipher with unsupported key length.\n"); goto end; } evp_cmac_name = app_malloc(sizeof("cmac()") + strlen(evp_mac_ciphername), "CMAC name"); sprintf(evp_cmac_name, "cmac(%s)", evp_mac_ciphername); names[D_EVP_CMAC] = evp_cmac_name; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_CIPHER, evp_mac_ciphername, 0); params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (char *)key32, keylen); params[2] = OSSL_PARAM_construct_end(); if (mac_setup("CMAC", &mac, params, loopargs, loopargs_len) < 1) goto end; for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_EVP_CMAC], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, CMAC_loop, loopargs); d = Time_F(STOP); print_result(D_EVP_CMAC, testnum, count, d); if (count < 0) break; } mac_teardown(&mac, loopargs, loopargs_len); } if (doit[D_KMAC128]) { OSSL_PARAM params[2]; params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (void *)key32, 16); params[1] = OSSL_PARAM_construct_end(); if (mac_setup("KMAC-128", &mac, params, loopargs, loopargs_len) < 1) goto end; for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_KMAC128], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, KMAC128_loop, loopargs); d = Time_F(STOP); print_result(D_KMAC128, testnum, count, d); if (count < 0) break; } mac_teardown(&mac, loopargs, loopargs_len); } if (doit[D_KMAC256]) { OSSL_PARAM params[2]; params[0] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, (void *)key32, 32); params[1] = OSSL_PARAM_construct_end(); if (mac_setup("KMAC-256", &mac, params, loopargs, loopargs_len) < 1) goto end; for (testnum = 0; testnum < size_num; testnum++) { print_message(names[D_KMAC256], lengths[testnum], seconds.sym); Time_F(START); count = run_benchmark(async_jobs, KMAC256_loop, loopargs); d = Time_F(STOP); print_result(D_KMAC256, testnum, count, d); if (count < 0) break; } mac_teardown(&mac, loopargs, loopargs_len); } for (i = 0; i < loopargs_len; i++) if (RAND_bytes(loopargs[i].buf, 36) <= 0) goto end; for (testnum = 0; testnum < RSA_NUM; testnum++) { EVP_PKEY *rsa_key = NULL; int st = 0; if (!rsa_doit[testnum]) continue; if (primes > RSA_DEFAULT_PRIME_NUM) { bn = BN_new(); st = bn != NULL && BN_set_word(bn, RSA_F4) && init_gen_str(&genctx, "RSA", NULL, 0, NULL, NULL) && EVP_PKEY_CTX_set_rsa_keygen_bits(genctx, rsa_keys[testnum].bits) > 0 && EVP_PKEY_CTX_set1_rsa_keygen_pubexp(genctx, bn) > 0 && EVP_PKEY_CTX_set_rsa_keygen_primes(genctx, primes) > 0 && EVP_PKEY_keygen(genctx, &rsa_key); BN_free(bn); bn = NULL; EVP_PKEY_CTX_free(genctx); genctx = NULL; } else { const unsigned char *p = rsa_keys[testnum].data; st = (rsa_key = d2i_PrivateKey(EVP_PKEY_RSA, NULL, &p, rsa_keys[testnum].length)) != NULL; } for (i = 0; st && i < loopargs_len; i++) { loopargs[i].rsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL); loopargs[i].sigsize = loopargs[i].buflen; if (loopargs[i].rsa_sign_ctx[testnum] == NULL || EVP_PKEY_sign_init(loopargs[i].rsa_sign_ctx[testnum]) <= 0 || EVP_PKEY_sign(loopargs[i].rsa_sign_ctx[testnum], loopargs[i].buf2, &loopargs[i].sigsize, loopargs[i].buf, 36) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "RSA sign setup failure. No RSA sign will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("private", "rsa sign", rsa_keys[testnum].bits, seconds.rsa); Time_F(START); count = run_benchmark(async_jobs, RSA_sign_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R1:%ld:%d:%.2f\n" : "%ld %u bits private RSA sign ops in %.2fs\n", count, rsa_keys[testnum].bits, d); rsa_results[testnum][0] = (double)count / d; op_count = count; } for (i = 0; st && i < loopargs_len; i++) { loopargs[i].rsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL); if (loopargs[i].rsa_verify_ctx[testnum] == NULL || EVP_PKEY_verify_init(loopargs[i].rsa_verify_ctx[testnum]) <= 0 || EVP_PKEY_verify(loopargs[i].rsa_verify_ctx[testnum], loopargs[i].buf2, loopargs[i].sigsize, loopargs[i].buf, 36) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "RSA verify setup failure. No RSA verify will be done.\n"); ERR_print_errors(bio_err); rsa_doit[testnum] = 0; } else { pkey_print_message("public", "rsa verify", rsa_keys[testnum].bits, seconds.rsa); Time_F(START); count = run_benchmark(async_jobs, RSA_verify_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R2:%ld:%d:%.2f\n" : "%ld %u bits public RSA verify ops in %.2fs\n", count, rsa_keys[testnum].bits, d); rsa_results[testnum][1] = (double)count / d; } for (i = 0; st && i < loopargs_len; i++) { loopargs[i].rsa_encrypt_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL); loopargs[i].encsize = loopargs[i].buflen; if (loopargs[i].rsa_encrypt_ctx[testnum] == NULL || EVP_PKEY_encrypt_init(loopargs[i].rsa_encrypt_ctx[testnum]) <= 0 || EVP_PKEY_encrypt(loopargs[i].rsa_encrypt_ctx[testnum], loopargs[i].buf2, &loopargs[i].encsize, loopargs[i].buf, 36) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "RSA encrypt setup failure. No RSA encrypt will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("private", "rsa encrypt", rsa_keys[testnum].bits, seconds.rsa); Time_F(START); count = run_benchmark(async_jobs, RSA_encrypt_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R3:%ld:%d:%.2f\n" : "%ld %u bits public RSA encrypt ops in %.2fs\n", count, rsa_keys[testnum].bits, d); rsa_results[testnum][2] = (double)count / d; op_count = count; } for (i = 0; st && i < loopargs_len; i++) { loopargs[i].rsa_decrypt_ctx[testnum] = EVP_PKEY_CTX_new(rsa_key, NULL); declen = loopargs[i].buflen; if (loopargs[i].rsa_decrypt_ctx[testnum] == NULL || EVP_PKEY_decrypt_init(loopargs[i].rsa_decrypt_ctx[testnum]) <= 0 || EVP_PKEY_decrypt(loopargs[i].rsa_decrypt_ctx[testnum], loopargs[i].buf, &declen, loopargs[i].buf2, loopargs[i].encsize) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "RSA decrypt setup failure. No RSA decrypt will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("private", "rsa decrypt", rsa_keys[testnum].bits, seconds.rsa); Time_F(START); count = run_benchmark(async_jobs, RSA_decrypt_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R4:%ld:%d:%.2f\n" : "%ld %u bits private RSA decrypt ops in %.2fs\n", count, rsa_keys[testnum].bits, d); rsa_results[testnum][3] = (double)count / d; op_count = count; } if (op_count <= 1) { stop_it(rsa_doit, testnum); } EVP_PKEY_free(rsa_key); } for (testnum = 0; testnum < DSA_NUM; testnum++) { EVP_PKEY *dsa_key = NULL; int st; if (!dsa_doit[testnum]) continue; st = (dsa_key = get_dsa(dsa_bits[testnum])) != NULL; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].dsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(dsa_key, NULL); loopargs[i].sigsize = loopargs[i].buflen; if (loopargs[i].dsa_sign_ctx[testnum] == NULL || EVP_PKEY_sign_init(loopargs[i].dsa_sign_ctx[testnum]) <= 0 || EVP_PKEY_sign(loopargs[i].dsa_sign_ctx[testnum], loopargs[i].buf2, &loopargs[i].sigsize, loopargs[i].buf, 20) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "DSA sign setup failure. No DSA sign will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("sign", "dsa", dsa_bits[testnum], seconds.dsa); Time_F(START); count = run_benchmark(async_jobs, DSA_sign_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R5:%ld:%u:%.2f\n" : "%ld %u bits DSA sign ops in %.2fs\n", count, dsa_bits[testnum], d); dsa_results[testnum][0] = (double)count / d; op_count = count; } for (i = 0; st && i < loopargs_len; i++) { loopargs[i].dsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(dsa_key, NULL); if (loopargs[i].dsa_verify_ctx[testnum] == NULL || EVP_PKEY_verify_init(loopargs[i].dsa_verify_ctx[testnum]) <= 0 || EVP_PKEY_verify(loopargs[i].dsa_verify_ctx[testnum], loopargs[i].buf2, loopargs[i].sigsize, loopargs[i].buf, 36) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "DSA verify setup failure. No DSA verify will be done.\n"); ERR_print_errors(bio_err); dsa_doit[testnum] = 0; } else { pkey_print_message("verify", "dsa", dsa_bits[testnum], seconds.dsa); Time_F(START); count = run_benchmark(async_jobs, DSA_verify_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R6:%ld:%u:%.2f\n" : "%ld %u bits DSA verify ops in %.2fs\n", count, dsa_bits[testnum], d); dsa_results[testnum][1] = (double)count / d; } if (op_count <= 1) { stop_it(dsa_doit, testnum); } EVP_PKEY_free(dsa_key); } for (testnum = 0; testnum < ECDSA_NUM; testnum++) { EVP_PKEY *ecdsa_key = NULL; int st; if (!ecdsa_doit[testnum]) continue; st = (ecdsa_key = get_ecdsa(&ec_curves[testnum])) != NULL; for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ecdsa_sign_ctx[testnum] = EVP_PKEY_CTX_new(ecdsa_key, NULL); loopargs[i].sigsize = loopargs[i].buflen; if (loopargs[i].ecdsa_sign_ctx[testnum] == NULL || EVP_PKEY_sign_init(loopargs[i].ecdsa_sign_ctx[testnum]) <= 0 || EVP_PKEY_sign(loopargs[i].ecdsa_sign_ctx[testnum], loopargs[i].buf2, &loopargs[i].sigsize, loopargs[i].buf, 20) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "ECDSA sign setup failure. No ECDSA sign will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("sign", "ecdsa", ec_curves[testnum].bits, seconds.ecdsa); Time_F(START); count = run_benchmark(async_jobs, ECDSA_sign_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R7:%ld:%u:%.2f\n" : "%ld %u bits ECDSA sign ops in %.2fs\n", count, ec_curves[testnum].bits, d); ecdsa_results[testnum][0] = (double)count / d; op_count = count; } for (i = 0; st && i < loopargs_len; i++) { loopargs[i].ecdsa_verify_ctx[testnum] = EVP_PKEY_CTX_new(ecdsa_key, NULL); if (loopargs[i].ecdsa_verify_ctx[testnum] == NULL || EVP_PKEY_verify_init(loopargs[i].ecdsa_verify_ctx[testnum]) <= 0 || EVP_PKEY_verify(loopargs[i].ecdsa_verify_ctx[testnum], loopargs[i].buf2, loopargs[i].sigsize, loopargs[i].buf, 20) <= 0) st = 0; } if (!st) { BIO_printf(bio_err, "ECDSA verify setup failure. No ECDSA verify will be done.\n"); ERR_print_errors(bio_err); ecdsa_doit[testnum] = 0; } else { pkey_print_message("verify", "ecdsa", ec_curves[testnum].bits, seconds.ecdsa); Time_F(START); count = run_benchmark(async_jobs, ECDSA_verify_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R8:%ld:%u:%.2f\n" : "%ld %u bits ECDSA verify ops in %.2fs\n", count, ec_curves[testnum].bits, d); ecdsa_results[testnum][1] = (double)count / d; } if (op_count <= 1) { stop_it(ecdsa_doit, testnum); } } for (testnum = 0; testnum < EC_NUM; testnum++) { int ecdh_checks = 1; if (!ecdh_doit[testnum]) continue; for (i = 0; i < loopargs_len; i++) { EVP_PKEY_CTX *test_ctx = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *key_A = NULL; EVP_PKEY *key_B = NULL; size_t outlen; size_t test_outlen; if ((key_A = get_ecdsa(&ec_curves[testnum])) == NULL || (key_B = get_ecdsa(&ec_curves[testnum])) == NULL || (ctx = EVP_PKEY_CTX_new(key_A, NULL)) == NULL || EVP_PKEY_derive_init(ctx) <= 0 || EVP_PKEY_derive_set_peer(ctx, key_B) <= 0 || EVP_PKEY_derive(ctx, NULL, &outlen) <= 0 || outlen == 0 || outlen > MAX_ECDH_SIZE ) { ecdh_checks = 0; BIO_printf(bio_err, "ECDH key generation failure.\n"); ERR_print_errors(bio_err); op_count = 1; break; } if ((test_ctx = EVP_PKEY_CTX_new(key_B, NULL)) == NULL || EVP_PKEY_derive_init(test_ctx) <= 0 || EVP_PKEY_derive_set_peer(test_ctx, key_A) <= 0 || EVP_PKEY_derive(test_ctx, NULL, &test_outlen) <= 0 || EVP_PKEY_derive(ctx, loopargs[i].secret_a, &outlen) <= 0 || EVP_PKEY_derive(test_ctx, loopargs[i].secret_b, &test_outlen) <= 0 || test_outlen != outlen ) { ecdh_checks = 0; BIO_printf(bio_err, "ECDH computation failure.\n"); ERR_print_errors(bio_err); op_count = 1; break; } if (CRYPTO_memcmp(loopargs[i].secret_a, loopargs[i].secret_b, outlen)) { ecdh_checks = 0; BIO_printf(bio_err, "ECDH computations don't match.\n"); ERR_print_errors(bio_err); op_count = 1; break; } loopargs[i].ecdh_ctx[testnum] = ctx; loopargs[i].outlen[testnum] = outlen; EVP_PKEY_free(key_A); EVP_PKEY_free(key_B); EVP_PKEY_CTX_free(test_ctx); test_ctx = NULL; } if (ecdh_checks != 0) { pkey_print_message("", "ecdh", ec_curves[testnum].bits, seconds.ecdh); Time_F(START); count = run_benchmark(async_jobs, ECDH_EVP_derive_key_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R9:%ld:%d:%.2f\n" : "%ld %u-bits ECDH ops in %.2fs\n", count, ec_curves[testnum].bits, d); ecdh_results[testnum][0] = (double)count / d; op_count = count; } if (op_count <= 1) { stop_it(ecdh_doit, testnum); } } #ifndef OPENSSL_NO_ECX for (testnum = 0; testnum < EdDSA_NUM; testnum++) { int st = 1; EVP_PKEY *ed_pkey = NULL; EVP_PKEY_CTX *ed_pctx = NULL; if (!eddsa_doit[testnum]) continue; for (i = 0; i < loopargs_len; i++) { loopargs[i].eddsa_ctx[testnum] = EVP_MD_CTX_new(); if (loopargs[i].eddsa_ctx[testnum] == NULL) { st = 0; break; } loopargs[i].eddsa_ctx2[testnum] = EVP_MD_CTX_new(); if (loopargs[i].eddsa_ctx2[testnum] == NULL) { st = 0; break; } if ((ed_pctx = EVP_PKEY_CTX_new_id(ed_curves[testnum].nid, NULL)) == NULL || EVP_PKEY_keygen_init(ed_pctx) <= 0 || EVP_PKEY_keygen(ed_pctx, &ed_pkey) <= 0) { st = 0; EVP_PKEY_CTX_free(ed_pctx); break; } EVP_PKEY_CTX_free(ed_pctx); if (!EVP_DigestSignInit(loopargs[i].eddsa_ctx[testnum], NULL, NULL, NULL, ed_pkey)) { st = 0; EVP_PKEY_free(ed_pkey); break; } if (!EVP_DigestVerifyInit(loopargs[i].eddsa_ctx2[testnum], NULL, NULL, NULL, ed_pkey)) { st = 0; EVP_PKEY_free(ed_pkey); break; } EVP_PKEY_free(ed_pkey); ed_pkey = NULL; } if (st == 0) { BIO_printf(bio_err, "EdDSA failure.\n"); ERR_print_errors(bio_err); op_count = 1; } else { for (i = 0; i < loopargs_len; i++) { loopargs[i].sigsize = ed_curves[testnum].sigsize; st = EVP_DigestSign(loopargs[i].eddsa_ctx[testnum], loopargs[i].buf2, &loopargs[i].sigsize, loopargs[i].buf, 20); if (st == 0) break; } if (st == 0) { BIO_printf(bio_err, "EdDSA sign failure. No EdDSA sign will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("sign", ed_curves[testnum].name, ed_curves[testnum].bits, seconds.eddsa); Time_F(START); count = run_benchmark(async_jobs, EdDSA_sign_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R10:%ld:%u:%s:%.2f\n" : "%ld %u bits %s sign ops in %.2fs \n", count, ed_curves[testnum].bits, ed_curves[testnum].name, d); eddsa_results[testnum][0] = (double)count / d; op_count = count; } for (i = 0; i < loopargs_len; i++) { st = EVP_DigestVerify(loopargs[i].eddsa_ctx2[testnum], loopargs[i].buf2, loopargs[i].sigsize, loopargs[i].buf, 20); if (st != 1) break; } if (st != 1) { BIO_printf(bio_err, "EdDSA verify failure. No EdDSA verify will be done.\n"); ERR_print_errors(bio_err); eddsa_doit[testnum] = 0; } else { pkey_print_message("verify", ed_curves[testnum].name, ed_curves[testnum].bits, seconds.eddsa); Time_F(START); count = run_benchmark(async_jobs, EdDSA_verify_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R11:%ld:%u:%s:%.2f\n" : "%ld %u bits %s verify ops in %.2fs\n", count, ed_curves[testnum].bits, ed_curves[testnum].name, d); eddsa_results[testnum][1] = (double)count / d; } if (op_count <= 1) { stop_it(eddsa_doit, testnum); } } } #endif #ifndef OPENSSL_NO_SM2 for (testnum = 0; testnum < SM2_NUM; testnum++) { int st = 1; EVP_PKEY *sm2_pkey = NULL; if (!sm2_doit[testnum]) continue; for (i = 0; i < loopargs_len; i++) { EVP_PKEY_CTX *sm2_pctx = NULL; EVP_PKEY_CTX *sm2_vfy_pctx = NULL; EVP_PKEY_CTX *pctx = NULL; st = 0; loopargs[i].sm2_ctx[testnum] = EVP_MD_CTX_new(); loopargs[i].sm2_vfy_ctx[testnum] = EVP_MD_CTX_new(); if (loopargs[i].sm2_ctx[testnum] == NULL || loopargs[i].sm2_vfy_ctx[testnum] == NULL) break; sm2_pkey = NULL; st = !((pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_SM2, NULL)) == NULL || EVP_PKEY_keygen_init(pctx) <= 0 || EVP_PKEY_CTX_set_ec_paramgen_curve_nid(pctx, sm2_curves[testnum].nid) <= 0 || EVP_PKEY_keygen(pctx, &sm2_pkey) <= 0); EVP_PKEY_CTX_free(pctx); if (st == 0) break; st = 0; loopargs[i].sm2_pkey[testnum] = sm2_pkey; loopargs[i].sigsize = EVP_PKEY_get_size(sm2_pkey); sm2_pctx = EVP_PKEY_CTX_new(sm2_pkey, NULL); sm2_vfy_pctx = EVP_PKEY_CTX_new(sm2_pkey, NULL); if (sm2_pctx == NULL || sm2_vfy_pctx == NULL) { EVP_PKEY_CTX_free(sm2_vfy_pctx); break; } EVP_MD_CTX_set_pkey_ctx(loopargs[i].sm2_ctx[testnum], sm2_pctx); EVP_MD_CTX_set_pkey_ctx(loopargs[i].sm2_vfy_ctx[testnum], sm2_vfy_pctx); if (EVP_PKEY_CTX_set1_id(sm2_pctx, SM2_ID, SM2_ID_LEN) != 1 || EVP_PKEY_CTX_set1_id(sm2_vfy_pctx, SM2_ID, SM2_ID_LEN) != 1) break; if (!EVP_DigestSignInit(loopargs[i].sm2_ctx[testnum], NULL, EVP_sm3(), NULL, sm2_pkey)) break; if (!EVP_DigestVerifyInit(loopargs[i].sm2_vfy_ctx[testnum], NULL, EVP_sm3(), NULL, sm2_pkey)) break; st = 1; } if (st == 0) { BIO_printf(bio_err, "SM2 init failure.\n"); ERR_print_errors(bio_err); op_count = 1; } else { for (i = 0; i < loopargs_len; i++) { st = EVP_DigestSign(loopargs[i].sm2_ctx[testnum], loopargs[i].buf2, &loopargs[i].sigsize, loopargs[i].buf, 20); if (st == 0) break; } if (st == 0) { BIO_printf(bio_err, "SM2 sign failure. No SM2 sign will be done.\n"); ERR_print_errors(bio_err); op_count = 1; } else { pkey_print_message("sign", sm2_curves[testnum].name, sm2_curves[testnum].bits, seconds.sm2); Time_F(START); count = run_benchmark(async_jobs, SM2_sign_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R12:%ld:%u:%s:%.2f\n" : "%ld %u bits %s sign ops in %.2fs \n", count, sm2_curves[testnum].bits, sm2_curves[testnum].name, d); sm2_results[testnum][0] = (double)count / d; op_count = count; } for (i = 0; i < loopargs_len; i++) { st = EVP_DigestVerify(loopargs[i].sm2_vfy_ctx[testnum], loopargs[i].buf2, loopargs[i].sigsize, loopargs[i].buf, 20); if (st != 1) break; } if (st != 1) { BIO_printf(bio_err, "SM2 verify failure. No SM2 verify will be done.\n"); ERR_print_errors(bio_err); sm2_doit[testnum] = 0; } else { pkey_print_message("verify", sm2_curves[testnum].name, sm2_curves[testnum].bits, seconds.sm2); Time_F(START); count = run_benchmark(async_jobs, SM2_verify_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R13:%ld:%u:%s:%.2f\n" : "%ld %u bits %s verify ops in %.2fs\n", count, sm2_curves[testnum].bits, sm2_curves[testnum].name, d); sm2_results[testnum][1] = (double)count / d; } if (op_count <= 1) { for (testnum++; testnum < SM2_NUM; testnum++) sm2_doit[testnum] = 0; } } } #endif #ifndef OPENSSL_NO_DH for (testnum = 0; testnum < FFDH_NUM; testnum++) { int ffdh_checks = 1; if (!ffdh_doit[testnum]) continue; for (i = 0; i < loopargs_len; i++) { EVP_PKEY *pkey_A = NULL; EVP_PKEY *pkey_B = NULL; EVP_PKEY_CTX *ffdh_ctx = NULL; EVP_PKEY_CTX *test_ctx = NULL; size_t secret_size; size_t test_out; if (ERR_peek_error()) { BIO_printf(bio_err, "WARNING: the error queue contains previous unhandled errors.\n"); ERR_print_errors(bio_err); } pkey_A = EVP_PKEY_new(); if (!pkey_A) { BIO_printf(bio_err, "Error while initialising EVP_PKEY (out of memory?).\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } pkey_B = EVP_PKEY_new(); if (!pkey_B) { BIO_printf(bio_err, "Error while initialising EVP_PKEY (out of memory?).\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } ffdh_ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_DH, NULL); if (!ffdh_ctx) { BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_keygen_init(ffdh_ctx) <= 0) { BIO_printf(bio_err, "Error while initialising EVP_PKEY_CTX.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_CTX_set_dh_nid(ffdh_ctx, ffdh_params[testnum].nid) <= 0) { BIO_printf(bio_err, "Error setting DH key size for keygen.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_keygen(ffdh_ctx, &pkey_A) <= 0 || EVP_PKEY_keygen(ffdh_ctx, &pkey_B) <= 0) { BIO_printf(bio_err, "FFDH key generation failure.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } EVP_PKEY_CTX_free(ffdh_ctx); ffdh_ctx = EVP_PKEY_CTX_new(pkey_A, NULL); if (ffdh_ctx == NULL) { BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_derive_init(ffdh_ctx) <= 0) { BIO_printf(bio_err, "FFDH derivation context init failure.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_derive_set_peer(ffdh_ctx, pkey_B) <= 0) { BIO_printf(bio_err, "Assigning peer key for derivation failed.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_derive(ffdh_ctx, NULL, &secret_size) <= 0) { BIO_printf(bio_err, "Checking size of shared secret failed.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (secret_size > MAX_FFDH_SIZE) { BIO_printf(bio_err, "Assertion failure: shared secret too large.\n"); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_derive(ffdh_ctx, loopargs[i].secret_ff_a, &secret_size) <= 0) { BIO_printf(bio_err, "Shared secret derive failure.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } test_ctx = EVP_PKEY_CTX_new(pkey_B, NULL); if (!test_ctx) { BIO_printf(bio_err, "Error while allocating EVP_PKEY_CTX.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } if (EVP_PKEY_derive_init(test_ctx) <= 0 || EVP_PKEY_derive_set_peer(test_ctx, pkey_A) <= 0 || EVP_PKEY_derive(test_ctx, NULL, &test_out) <= 0 || EVP_PKEY_derive(test_ctx, loopargs[i].secret_ff_b, &test_out) <= 0 || test_out != secret_size) { BIO_printf(bio_err, "FFDH computation failure.\n"); op_count = 1; ffdh_checks = 0; break; } if (CRYPTO_memcmp(loopargs[i].secret_ff_a, loopargs[i].secret_ff_b, secret_size)) { BIO_printf(bio_err, "FFDH computations don't match.\n"); ERR_print_errors(bio_err); op_count = 1; ffdh_checks = 0; break; } loopargs[i].ffdh_ctx[testnum] = ffdh_ctx; EVP_PKEY_free(pkey_A); pkey_A = NULL; EVP_PKEY_free(pkey_B); pkey_B = NULL; EVP_PKEY_CTX_free(test_ctx); test_ctx = NULL; } if (ffdh_checks != 0) { pkey_print_message("", "ffdh", ffdh_params[testnum].bits, seconds.ffdh); Time_F(START); count = run_benchmark(async_jobs, FFDH_derive_key_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R14:%ld:%d:%.2f\n" : "%ld %u-bits FFDH ops in %.2fs\n", count, ffdh_params[testnum].bits, d); ffdh_results[testnum][0] = (double)count / d; op_count = count; } if (op_count <= 1) { stop_it(ffdh_doit, testnum); } } #endif for (testnum = 0; testnum < kems_algs_len; testnum++) { int kem_checks = 1; const char *kem_name = kems_algname[testnum]; if (!kems_doit[testnum] || !do_kems) continue; for (i = 0; i < loopargs_len; i++) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *kem_gen_ctx = NULL; EVP_PKEY_CTX *kem_encaps_ctx = NULL; EVP_PKEY_CTX *kem_decaps_ctx = NULL; size_t send_secret_len, out_len; size_t rcv_secret_len; unsigned char *out = NULL, *send_secret = NULL, *rcv_secret; unsigned int bits; char *name; char sfx[MAX_ALGNAME_SUFFIX]; OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; int use_params = 0; enum kem_type_t { KEM_RSA = 1, KEM_EC, KEM_X25519, KEM_X448 } kem_type; if (strlen(kem_name) < MAX_ALGNAME_SUFFIX + 4 && sscanf(kem_name, "rsa%u%s", &bits, sfx) == 1) kem_type = KEM_RSA; else if (strncmp(kem_name, "EC", 2) == 0) kem_type = KEM_EC; else if (strcmp(kem_name, "X25519") == 0) kem_type = KEM_X25519; else if (strcmp(kem_name, "X448") == 0) kem_type = KEM_X448; else kem_type = 0; if (ERR_peek_error()) { BIO_printf(bio_err, "WARNING: the error queue contains previous unhandled errors.\n"); ERR_print_errors(bio_err); } if (kem_type == KEM_RSA) { params[0] = OSSL_PARAM_construct_uint(OSSL_PKEY_PARAM_RSA_BITS, &bits); use_params = 1; } else if (kem_type == KEM_EC) { name = (char *)(kem_name + 2); params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, name, 0); use_params = 1; } kem_gen_ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), (kem_type == KEM_RSA) ? "RSA": (kem_type == KEM_EC) ? "EC": kem_name, app_get0_propq()); if ((!kem_gen_ctx || EVP_PKEY_keygen_init(kem_gen_ctx) <= 0) || (use_params && EVP_PKEY_CTX_set_params(kem_gen_ctx, params) <= 0)) { BIO_printf(bio_err, "Error initializing keygen ctx for %s.\n", kem_name); goto kem_err_break; } if (EVP_PKEY_keygen(kem_gen_ctx, &pkey) <= 0) { BIO_printf(bio_err, "Error while generating KEM EVP_PKEY.\n"); goto kem_err_break; } kem_encaps_ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); if (kem_encaps_ctx == NULL || EVP_PKEY_encapsulate_init(kem_encaps_ctx, NULL) <= 0 || (kem_type == KEM_RSA && EVP_PKEY_CTX_set_kem_op(kem_encaps_ctx, "RSASVE") <= 0) || ((kem_type == KEM_EC || kem_type == KEM_X25519 || kem_type == KEM_X448) && EVP_PKEY_CTX_set_kem_op(kem_encaps_ctx, "DHKEM") <= 0) || EVP_PKEY_encapsulate(kem_encaps_ctx, NULL, &out_len, NULL, &send_secret_len) <= 0) { BIO_printf(bio_err, "Error while initializing encaps data structs for %s.\n", kem_name); goto kem_err_break; } out = app_malloc(out_len, "encaps result"); send_secret = app_malloc(send_secret_len, "encaps secret"); if (out == NULL || send_secret == NULL) { BIO_printf(bio_err, "MemAlloc error in encaps for %s.\n", kem_name); goto kem_err_break; } if (EVP_PKEY_encapsulate(kem_encaps_ctx, out, &out_len, send_secret, &send_secret_len) <= 0) { BIO_printf(bio_err, "Encaps error for %s.\n", kem_name); goto kem_err_break; } kem_decaps_ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); if (kem_decaps_ctx == NULL || EVP_PKEY_decapsulate_init(kem_decaps_ctx, NULL) <= 0 || (kem_type == KEM_RSA && EVP_PKEY_CTX_set_kem_op(kem_decaps_ctx, "RSASVE") <= 0) || ((kem_type == KEM_EC || kem_type == KEM_X25519 || kem_type == KEM_X448) && EVP_PKEY_CTX_set_kem_op(kem_decaps_ctx, "DHKEM") <= 0) || EVP_PKEY_decapsulate(kem_decaps_ctx, NULL, &rcv_secret_len, out, out_len) <= 0) { BIO_printf(bio_err, "Error while initializing decaps data structs for %s.\n", kem_name); goto kem_err_break; } rcv_secret = app_malloc(rcv_secret_len, "KEM decaps secret"); if (rcv_secret == NULL) { BIO_printf(bio_err, "MemAlloc failure in decaps for %s.\n", kem_name); goto kem_err_break; } if (EVP_PKEY_decapsulate(kem_decaps_ctx, rcv_secret, &rcv_secret_len, out, out_len) <= 0 || rcv_secret_len != send_secret_len || memcmp(send_secret, rcv_secret, send_secret_len)) { BIO_printf(bio_err, "Decaps error for %s.\n", kem_name); goto kem_err_break; } loopargs[i].kem_gen_ctx[testnum] = kem_gen_ctx; loopargs[i].kem_encaps_ctx[testnum] = kem_encaps_ctx; loopargs[i].kem_decaps_ctx[testnum] = kem_decaps_ctx; loopargs[i].kem_out_len[testnum] = out_len; loopargs[i].kem_secret_len[testnum] = send_secret_len; loopargs[i].kem_out[testnum] = out; loopargs[i].kem_send_secret[testnum] = send_secret; loopargs[i].kem_rcv_secret[testnum] = rcv_secret; EVP_PKEY_free(pkey); pkey = NULL; continue; kem_err_break: ERR_print_errors(bio_err); EVP_PKEY_free(pkey); op_count = 1; kem_checks = 0; break; } if (kem_checks != 0) { kskey_print_message(kem_name, "keygen", seconds.kem); Time_F(START); count = run_benchmark(async_jobs, KEM_keygen_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R15:%ld:%s:%.2f\n" : "%ld %s KEM keygen ops in %.2fs\n", count, kem_name, d); kems_results[testnum][0] = (double)count / d; op_count = count; kskey_print_message(kem_name, "encaps", seconds.kem); Time_F(START); count = run_benchmark(async_jobs, KEM_encaps_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R16:%ld:%s:%.2f\n" : "%ld %s KEM encaps ops in %.2fs\n", count, kem_name, d); kems_results[testnum][1] = (double)count / d; op_count = count; kskey_print_message(kem_name, "decaps", seconds.kem); Time_F(START); count = run_benchmark(async_jobs, KEM_decaps_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R17:%ld:%s:%.2f\n" : "%ld %s KEM decaps ops in %.2fs\n", count, kem_name, d); kems_results[testnum][2] = (double)count / d; op_count = count; } if (op_count <= 1) { stop_it(kems_doit, testnum); } } for (testnum = 0; testnum < sigs_algs_len; testnum++) { int sig_checks = 1; const char *sig_name = sigs_algname[testnum]; if (!sigs_doit[testnum] || !do_sigs) continue; for (i = 0; i < loopargs_len; i++) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx_params = NULL; EVP_PKEY* pkey_params = NULL; EVP_PKEY_CTX *sig_gen_ctx = NULL; EVP_PKEY_CTX *sig_sign_ctx = NULL; EVP_PKEY_CTX *sig_verify_ctx = NULL; unsigned char md[SHA256_DIGEST_LENGTH]; unsigned char *sig; char sfx[MAX_ALGNAME_SUFFIX]; size_t md_len = SHA256_DIGEST_LENGTH; size_t max_sig_len, sig_len; unsigned int bits; OSSL_PARAM params[] = { OSSL_PARAM_END, OSSL_PARAM_END }; int use_params = 0; memset(md, 0, SHA256_DIGEST_LENGTH); if (ERR_peek_error()) { BIO_printf(bio_err, "WARNING: the error queue contains previous unhandled errors.\n"); ERR_print_errors(bio_err); } if (strlen(sig_name) < MAX_ALGNAME_SUFFIX + 4 && sscanf(sig_name, "rsa%u%s", &bits, sfx) == 1) { params[0] = OSSL_PARAM_construct_uint(OSSL_PKEY_PARAM_RSA_BITS, &bits); use_params = 1; } if (strncmp(sig_name, "dsa", 3) == 0) { ctx_params = EVP_PKEY_CTX_new_id(EVP_PKEY_DSA, NULL); if (ctx_params == NULL || EVP_PKEY_paramgen_init(ctx_params) <= 0 || EVP_PKEY_CTX_set_dsa_paramgen_bits(ctx_params, atoi(sig_name + 3)) <= 0 || EVP_PKEY_paramgen(ctx_params, &pkey_params) <= 0 || (sig_gen_ctx = EVP_PKEY_CTX_new(pkey_params, NULL)) == NULL || EVP_PKEY_keygen_init(sig_gen_ctx) <= 0) { BIO_printf(bio_err, "Error initializing classic keygen ctx for %s.\n", sig_name); goto sig_err_break; } } if (sig_gen_ctx == NULL) sig_gen_ctx = EVP_PKEY_CTX_new_from_name(app_get0_libctx(), use_params == 1 ? "RSA" : sig_name, app_get0_propq()); if (!sig_gen_ctx || EVP_PKEY_keygen_init(sig_gen_ctx) <= 0 || (use_params && EVP_PKEY_CTX_set_params(sig_gen_ctx, params) <= 0)) { BIO_printf(bio_err, "Error initializing keygen ctx for %s.\n", sig_name); goto sig_err_break; } if (EVP_PKEY_keygen(sig_gen_ctx, &pkey) <= 0) { BIO_printf(bio_err, "Error while generating signature EVP_PKEY for %s.\n", sig_name); goto sig_err_break; } sig_sign_ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); if (sig_sign_ctx == NULL || EVP_PKEY_sign_init(sig_sign_ctx) <= 0 || (use_params == 1 && (EVP_PKEY_CTX_set_rsa_padding(sig_sign_ctx, RSA_PKCS1_PADDING) <= 0)) || EVP_PKEY_sign(sig_sign_ctx, NULL, &max_sig_len, md, md_len) <= 0) { BIO_printf(bio_err, "Error while initializing signing data structs for %s.\n", sig_name); goto sig_err_break; } sig = app_malloc(sig_len = max_sig_len, "signature buffer"); if (sig == NULL) { BIO_printf(bio_err, "MemAlloc error in sign for %s.\n", sig_name); goto sig_err_break; } if (EVP_PKEY_sign(sig_sign_ctx, sig, &sig_len, md, md_len) <= 0) { BIO_printf(bio_err, "Signing error for %s.\n", sig_name); goto sig_err_break; } memset(md, 0, SHA256_DIGEST_LENGTH); sig_verify_ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); if (sig_verify_ctx == NULL || EVP_PKEY_verify_init(sig_verify_ctx) <= 0 || (use_params == 1 && (EVP_PKEY_CTX_set_rsa_padding(sig_verify_ctx, RSA_PKCS1_PADDING) <= 0))) { BIO_printf(bio_err, "Error while initializing verify data structs for %s.\n", sig_name); goto sig_err_break; } if (EVP_PKEY_verify(sig_verify_ctx, sig, sig_len, md, md_len) <= 0) { BIO_printf(bio_err, "Verify error for %s.\n", sig_name); goto sig_err_break; } if (EVP_PKEY_verify(sig_verify_ctx, sig, sig_len, md, md_len) <= 0) { BIO_printf(bio_err, "Verify 2 error for %s.\n", sig_name); goto sig_err_break; } loopargs[i].sig_gen_ctx[testnum] = sig_gen_ctx; loopargs[i].sig_sign_ctx[testnum] = sig_sign_ctx; loopargs[i].sig_verify_ctx[testnum] = sig_verify_ctx; loopargs[i].sig_max_sig_len[testnum] = max_sig_len; loopargs[i].sig_act_sig_len[testnum] = sig_len; loopargs[i].sig_sig[testnum] = sig; EVP_PKEY_free(pkey); pkey = NULL; continue; sig_err_break: ERR_print_errors(bio_err); EVP_PKEY_free(pkey); op_count = 1; sig_checks = 0; break; } if (sig_checks != 0) { kskey_print_message(sig_name, "keygen", seconds.sig); Time_F(START); count = run_benchmark(async_jobs, SIG_keygen_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R18:%ld:%s:%.2f\n" : "%ld %s signature keygen ops in %.2fs\n", count, sig_name, d); sigs_results[testnum][0] = (double)count / d; op_count = count; kskey_print_message(sig_name, "signs", seconds.sig); Time_F(START); count = run_benchmark(async_jobs, SIG_sign_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R19:%ld:%s:%.2f\n" : "%ld %s signature sign ops in %.2fs\n", count, sig_name, d); sigs_results[testnum][1] = (double)count / d; op_count = count; kskey_print_message(sig_name, "verify", seconds.sig); Time_F(START); count = run_benchmark(async_jobs, SIG_verify_loop, loopargs); d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R20:%ld:%s:%.2f\n" : "%ld %s signature verify ops in %.2fs\n", count, sig_name, d); sigs_results[testnum][2] = (double)count / d; op_count = count; } if (op_count <= 1) stop_it(sigs_doit, testnum); } #ifndef NO_FORK show_res: #endif if (!mr) { printf("version: %s\n", OpenSSL_version(OPENSSL_FULL_VERSION_STRING)); printf("%s\n", OpenSSL_version(OPENSSL_BUILT_ON)); printf("options: %s\n", BN_options()); printf("%s\n", OpenSSL_version(OPENSSL_CFLAGS)); printf("%s\n", OpenSSL_version(OPENSSL_CPU_INFO)); } if (pr_header) { if (mr) { printf("+H"); } else { printf("The 'numbers' are in 1000s of bytes per second processed.\n"); printf("type "); } for (testnum = 0; testnum < size_num; testnum++) printf(mr ? ":%d" : "%7d bytes", lengths[testnum]); printf("\n"); } for (k = 0; k < ALGOR_NUM; k++) { const char *alg_name = names[k]; if (!doit[k]) continue; if (k == D_EVP) { if (evp_cipher == NULL) alg_name = evp_md_name; else if ((alg_name = EVP_CIPHER_get0_name(evp_cipher)) == NULL) app_bail_out("failed to get name of cipher '%s'\n", evp_cipher); } if (mr) printf("+F:%u:%s", k, alg_name); else printf("%-13s", alg_name); for (testnum = 0; testnum < size_num; testnum++) { if (results[k][testnum] > 10000 && !mr) printf(" %11.2fk", results[k][testnum] / 1e3); else printf(mr ? ":%.2f" : " %11.2f ", results[k][testnum]); } printf("\n"); } testnum = 1; for (k = 0; k < RSA_NUM; k++) { if (!rsa_doit[k]) continue; if (testnum && !mr) { printf("%19ssign verify encrypt decrypt sign/s verify/s encr./s decr./s\n", " "); testnum = 0; } if (mr) printf("+F2:%u:%u:%f:%f:%f:%f\n", k, rsa_keys[k].bits, rsa_results[k][0], rsa_results[k][1], rsa_results[k][2], rsa_results[k][3]); else printf("rsa %5u bits %8.6fs %8.6fs %8.6fs %8.6fs %8.1f %8.1f %8.1f %8.1f\n", rsa_keys[k].bits, 1.0 / rsa_results[k][0], 1.0 / rsa_results[k][1], 1.0 / rsa_results[k][2], 1.0 / rsa_results[k][3], rsa_results[k][0], rsa_results[k][1], rsa_results[k][2], rsa_results[k][3]); } testnum = 1; for (k = 0; k < DSA_NUM; k++) { if (!dsa_doit[k]) continue; if (testnum && !mr) { printf("%18ssign verify sign/s verify/s\n", " "); testnum = 0; } if (mr) printf("+F3:%u:%u:%f:%f\n", k, dsa_bits[k], dsa_results[k][0], dsa_results[k][1]); else printf("dsa %4u bits %8.6fs %8.6fs %8.1f %8.1f\n", dsa_bits[k], 1.0 / dsa_results[k][0], 1.0 / dsa_results[k][1], dsa_results[k][0], dsa_results[k][1]); } testnum = 1; for (k = 0; k < OSSL_NELEM(ecdsa_doit); k++) { if (!ecdsa_doit[k]) continue; if (testnum && !mr) { printf("%30ssign verify sign/s verify/s\n", " "); testnum = 0; } if (mr) printf("+F4:%u:%u:%f:%f\n", k, ec_curves[k].bits, ecdsa_results[k][0], ecdsa_results[k][1]); else printf("%4u bits ecdsa (%s) %8.4fs %8.4fs %8.1f %8.1f\n", ec_curves[k].bits, ec_curves[k].name, 1.0 / ecdsa_results[k][0], 1.0 / ecdsa_results[k][1], ecdsa_results[k][0], ecdsa_results[k][1]); } testnum = 1; for (k = 0; k < EC_NUM; k++) { if (!ecdh_doit[k]) continue; if (testnum && !mr) { printf("%30sop op/s\n", " "); testnum = 0; } if (mr) printf("+F5:%u:%u:%f:%f\n", k, ec_curves[k].bits, ecdh_results[k][0], 1.0 / ecdh_results[k][0]); else printf("%4u bits ecdh (%s) %8.4fs %8.1f\n", ec_curves[k].bits, ec_curves[k].name, 1.0 / ecdh_results[k][0], ecdh_results[k][0]); } #ifndef OPENSSL_NO_ECX testnum = 1; for (k = 0; k < OSSL_NELEM(eddsa_doit); k++) { if (!eddsa_doit[k]) continue; if (testnum && !mr) { printf("%30ssign verify sign/s verify/s\n", " "); testnum = 0; } if (mr) printf("+F6:%u:%u:%s:%f:%f\n", k, ed_curves[k].bits, ed_curves[k].name, eddsa_results[k][0], eddsa_results[k][1]); else printf("%4u bits EdDSA (%s) %8.4fs %8.4fs %8.1f %8.1f\n", ed_curves[k].bits, ed_curves[k].name, 1.0 / eddsa_results[k][0], 1.0 / eddsa_results[k][1], eddsa_results[k][0], eddsa_results[k][1]); } #endif #ifndef OPENSSL_NO_SM2 testnum = 1; for (k = 0; k < OSSL_NELEM(sm2_doit); k++) { if (!sm2_doit[k]) continue; if (testnum && !mr) { printf("%30ssign verify sign/s verify/s\n", " "); testnum = 0; } if (mr) printf("+F7:%u:%u:%s:%f:%f\n", k, sm2_curves[k].bits, sm2_curves[k].name, sm2_results[k][0], sm2_results[k][1]); else printf("%4u bits SM2 (%s) %8.4fs %8.4fs %8.1f %8.1f\n", sm2_curves[k].bits, sm2_curves[k].name, 1.0 / sm2_results[k][0], 1.0 / sm2_results[k][1], sm2_results[k][0], sm2_results[k][1]); } #endif #ifndef OPENSSL_NO_DH testnum = 1; for (k = 0; k < FFDH_NUM; k++) { if (!ffdh_doit[k]) continue; if (testnum && !mr) { printf("%23sop op/s\n", " "); testnum = 0; } if (mr) printf("+F8:%u:%u:%f:%f\n", k, ffdh_params[k].bits, ffdh_results[k][0], 1.0 / ffdh_results[k][0]); else printf("%4u bits ffdh %8.4fs %8.1f\n", ffdh_params[k].bits, 1.0 / ffdh_results[k][0], ffdh_results[k][0]); } #endif testnum = 1; for (k = 0; k < kems_algs_len; k++) { const char *kem_name = kems_algname[k]; if (!kems_doit[k] || !do_kems) continue; if (testnum && !mr) { printf("%31skeygen encaps decaps keygens/s encaps/s decaps/s\n", " "); testnum = 0; } if (mr) printf("+F9:%u:%f:%f:%f\n", k, kems_results[k][0], kems_results[k][1], kems_results[k][2]); else printf("%27s %8.6fs %8.6fs %8.6fs %9.1f %9.1f %9.1f\n", kem_name, 1.0 / kems_results[k][0], 1.0 / kems_results[k][1], 1.0 / kems_results[k][2], kems_results[k][0], kems_results[k][1], kems_results[k][2]); } ret = 0; testnum = 1; for (k = 0; k < sigs_algs_len; k++) { const char *sig_name = sigs_algname[k]; if (!sigs_doit[k] || !do_sigs) continue; if (testnum && !mr) { printf("%31skeygen signs verify keygens/s sign/s verify/s\n", " "); testnum = 0; } if (mr) printf("+F10:%u:%f:%f:%f\n", k, sigs_results[k][0], sigs_results[k][1], sigs_results[k][2]); else printf("%27s %8.6fs %8.6fs %8.6fs %9.1f %9.1f %9.1f\n", sig_name, 1.0 / sigs_results[k][0], 1.0 / sigs_results[k][1], 1.0 / sigs_results[k][2], sigs_results[k][0], sigs_results[k][1], sigs_results[k][2]); } ret = 0; end: ERR_print_errors(bio_err); for (i = 0; i < loopargs_len; i++) { OPENSSL_free(loopargs[i].buf_malloc); OPENSSL_free(loopargs[i].buf2_malloc); BN_free(bn); EVP_PKEY_CTX_free(genctx); for (k = 0; k < RSA_NUM; k++) { EVP_PKEY_CTX_free(loopargs[i].rsa_sign_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].rsa_verify_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].rsa_encrypt_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].rsa_decrypt_ctx[k]); } #ifndef OPENSSL_NO_DH OPENSSL_free(loopargs[i].secret_ff_a); OPENSSL_free(loopargs[i].secret_ff_b); for (k = 0; k < FFDH_NUM; k++) EVP_PKEY_CTX_free(loopargs[i].ffdh_ctx[k]); #endif for (k = 0; k < DSA_NUM; k++) { EVP_PKEY_CTX_free(loopargs[i].dsa_sign_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].dsa_verify_ctx[k]); } for (k = 0; k < ECDSA_NUM; k++) { EVP_PKEY_CTX_free(loopargs[i].ecdsa_sign_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].ecdsa_verify_ctx[k]); } for (k = 0; k < EC_NUM; k++) EVP_PKEY_CTX_free(loopargs[i].ecdh_ctx[k]); #ifndef OPENSSL_NO_ECX for (k = 0; k < EdDSA_NUM; k++) { EVP_MD_CTX_free(loopargs[i].eddsa_ctx[k]); EVP_MD_CTX_free(loopargs[i].eddsa_ctx2[k]); } #endif #ifndef OPENSSL_NO_SM2 for (k = 0; k < SM2_NUM; k++) { EVP_PKEY_CTX *pctx = NULL; if (loopargs[i].sm2_ctx[k] != NULL && (pctx = EVP_MD_CTX_get_pkey_ctx(loopargs[i].sm2_ctx[k])) != NULL) EVP_PKEY_CTX_free(pctx); EVP_MD_CTX_free(loopargs[i].sm2_ctx[k]); if (loopargs[i].sm2_vfy_ctx[k] != NULL && (pctx = EVP_MD_CTX_get_pkey_ctx(loopargs[i].sm2_vfy_ctx[k])) != NULL) EVP_PKEY_CTX_free(pctx); EVP_MD_CTX_free(loopargs[i].sm2_vfy_ctx[k]); EVP_PKEY_free(loopargs[i].sm2_pkey[k]); } #endif for (k = 0; k < kems_algs_len; k++) { EVP_PKEY_CTX_free(loopargs[i].kem_gen_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].kem_encaps_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].kem_decaps_ctx[k]); OPENSSL_free(loopargs[i].kem_out[k]); OPENSSL_free(loopargs[i].kem_send_secret[k]); OPENSSL_free(loopargs[i].kem_rcv_secret[k]); } for (k = 0; k < sigs_algs_len; k++) { EVP_PKEY_CTX_free(loopargs[i].sig_gen_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].sig_sign_ctx[k]); EVP_PKEY_CTX_free(loopargs[i].sig_verify_ctx[k]); OPENSSL_free(loopargs[i].sig_sig[k]); } OPENSSL_free(loopargs[i].secret_a); OPENSSL_free(loopargs[i].secret_b); } OPENSSL_free(evp_hmac_name); OPENSSL_free(evp_cmac_name); for (k = 0; k < kems_algs_len; k++) OPENSSL_free(kems_algname[k]); if (kem_stack != NULL) sk_EVP_KEM_pop_free(kem_stack, EVP_KEM_free); for (k = 0; k < sigs_algs_len; k++) OPENSSL_free(sigs_algname[k]); if (sig_stack != NULL) sk_EVP_SIGNATURE_pop_free(sig_stack, EVP_SIGNATURE_free); if (async_jobs > 0) { for (i = 0; i < loopargs_len; i++) ASYNC_WAIT_CTX_free(loopargs[i].wait_ctx); } if (async_init) { ASYNC_cleanup_thread(); } OPENSSL_free(loopargs); release_engine(e); EVP_CIPHER_free(evp_cipher); EVP_MAC_free(mac); NCONF_free(conf); return ret; } static void print_message(const char *s, int length, int tm) { BIO_printf(bio_err, mr ? "+DT:%s:%d:%d\n" : "Doing %s ops for %ds on %d size blocks: ", s, tm, length); (void)BIO_flush(bio_err); run = 1; alarm(tm); } static void pkey_print_message(const char *str, const char *str2, unsigned int bits, int tm) { BIO_printf(bio_err, mr ? "+DTP:%d:%s:%s:%d\n" : "Doing %u bits %s %s ops for %ds: ", bits, str, str2, tm); (void)BIO_flush(bio_err); run = 1; alarm(tm); } static void kskey_print_message(const char *str, const char *str2, int tm) { BIO_printf(bio_err, mr ? "+DTP:%s:%s:%d\n" : "Doing %s %s ops for %ds: ", str, str2, tm); (void)BIO_flush(bio_err); run = 1; alarm(tm); } static void print_result(int alg, int run_no, int count, double time_used) { if (count == -1) { BIO_printf(bio_err, "%s error!\n", names[alg]); ERR_print_errors(bio_err); return; } BIO_printf(bio_err, mr ? "+R:%d:%s:%f\n" : "%d %s ops in %.2fs\n", count, names[alg], time_used); results[alg][run_no] = ((double)count) / time_used * lengths[run_no]; } #ifndef NO_FORK static char *sstrsep(char **string, const char *delim) { char isdelim[256]; char *token = *string; memset(isdelim, 0, sizeof(isdelim)); isdelim[0] = 1; while (*delim) { isdelim[(unsigned char)(*delim)] = 1; delim++; } while (!isdelim[(unsigned char)(**string)]) (*string)++; if (**string) { **string = 0; (*string)++; } return token; } static int strtoint(const char *str, const int min_val, const int upper_val, int *res) { char *end = NULL; long int val = 0; errno = 0; val = strtol(str, &end, 10); if (errno == 0 && end != str && *end == 0 && min_val <= val && val < upper_val) { *res = (int)val; return 1; } else { return 0; } } static int do_multi(int multi, int size_num) { int n; int fd[2]; int *fds; int status; static char sep[] = ":"; fds = app_malloc(sizeof(*fds) * multi, "fd buffer for do_multi"); for (n = 0; n < multi; ++n) { if (pipe(fd) == -1) { BIO_printf(bio_err, "pipe failure\n"); exit(1); } fflush(stdout); (void)BIO_flush(bio_err); if (fork()) { close(fd[1]); fds[n] = fd[0]; } else { close(fd[0]); close(1); if (dup(fd[1]) == -1) { BIO_printf(bio_err, "dup failed\n"); exit(1); } close(fd[1]); mr = 1; usertime = 0; OPENSSL_free(fds); return 0; } printf("Forked child %d\n", n); } for (n = 0; n < multi; ++n) { FILE *f; char buf[1024]; char *p; char *tk; int k; double d; if ((f = fdopen(fds[n], "r")) == NULL) { BIO_printf(bio_err, "fdopen failure with 0x%x\n", errno); OPENSSL_free(fds); return 1; } while (fgets(buf, sizeof(buf), f)) { p = strchr(buf, '\n'); if (p) *p = '\0'; if (buf[0] != '+') { BIO_printf(bio_err, "Don't understand line '%s' from child %d\n", buf, n); continue; } printf("Got: %s from %d\n", buf, n); p = buf; if (CHECK_AND_SKIP_PREFIX(p, "+F:")) { int alg; int j; if (strtoint(sstrsep(&p, sep), 0, ALGOR_NUM, &alg)) { sstrsep(&p, sep); for (j = 0; j < size_num; ++j) results[alg][j] += atof(sstrsep(&p, sep)); } } else if (CHECK_AND_SKIP_PREFIX(p, "+F2:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(rsa_results), &k)) { sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); rsa_results[k][0] += d; d = atof(sstrsep(&p, sep)); rsa_results[k][1] += d; d = atof(sstrsep(&p, sep)); rsa_results[k][2] += d; d = atof(sstrsep(&p, sep)); rsa_results[k][3] += d; } } else if (CHECK_AND_SKIP_PREFIX(p, "+F3:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(dsa_results), &k)) { sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); dsa_results[k][0] += d; d = atof(sstrsep(&p, sep)); dsa_results[k][1] += d; } } else if (CHECK_AND_SKIP_PREFIX(p, "+F4:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(ecdsa_results), &k)) { sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); ecdsa_results[k][0] += d; d = atof(sstrsep(&p, sep)); ecdsa_results[k][1] += d; } } else if (CHECK_AND_SKIP_PREFIX(p, "+F5:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(ecdh_results), &k)) { sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); ecdh_results[k][0] += d; } # ifndef OPENSSL_NO_ECX } else if (CHECK_AND_SKIP_PREFIX(p, "+F6:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(eddsa_results), &k)) { sstrsep(&p, sep); sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); eddsa_results[k][0] += d; d = atof(sstrsep(&p, sep)); eddsa_results[k][1] += d; } # endif # ifndef OPENSSL_NO_SM2 } else if (CHECK_AND_SKIP_PREFIX(p, "+F7:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(sm2_results), &k)) { sstrsep(&p, sep); sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); sm2_results[k][0] += d; d = atof(sstrsep(&p, sep)); sm2_results[k][1] += d; } # endif # ifndef OPENSSL_NO_DH } else if (CHECK_AND_SKIP_PREFIX(p, "+F8:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(ffdh_results), &k)) { sstrsep(&p, sep); d = atof(sstrsep(&p, sep)); ffdh_results[k][0] += d; } # endif } else if (CHECK_AND_SKIP_PREFIX(p, "+F9:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(kems_results), &k)) { d = atof(sstrsep(&p, sep)); kems_results[k][0] += d; d = atof(sstrsep(&p, sep)); kems_results[k][1] += d; d = atof(sstrsep(&p, sep)); kems_results[k][2] += d; } } else if (CHECK_AND_SKIP_PREFIX(p, "+F10:")) { tk = sstrsep(&p, sep); if (strtoint(tk, 0, OSSL_NELEM(sigs_results), &k)) { d = atof(sstrsep(&p, sep)); sigs_results[k][0] += d; d = atof(sstrsep(&p, sep)); sigs_results[k][1] += d; d = atof(sstrsep(&p, sep)); sigs_results[k][2] += d; } } else if (!HAS_PREFIX(buf, "+H:")) { BIO_printf(bio_err, "Unknown type '%s' from child %d\n", buf, n); } } fclose(f); } OPENSSL_free(fds); for (n = 0; n < multi; ++n) { while (wait(&status) == -1) if (errno != EINTR) { BIO_printf(bio_err, "Waitng for child failed with 0x%x\n", errno); return 1; } if (WIFEXITED(status) && WEXITSTATUS(status)) { BIO_printf(bio_err, "Child exited with %d\n", WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { BIO_printf(bio_err, "Child terminated by signal %d\n", WTERMSIG(status)); } } return 1; } #endif static void multiblock_speed(const EVP_CIPHER *evp_cipher, int lengths_single, const openssl_speed_sec_t *seconds) { static const int mblengths_list[] = { 8 * 1024, 2 * 8 * 1024, 4 * 8 * 1024, 8 * 8 * 1024, 8 * 16 * 1024 }; const int *mblengths = mblengths_list; int j, count, keylen, num = OSSL_NELEM(mblengths_list), ciph_success = 1; const char *alg_name; unsigned char *inp = NULL, *out = NULL, *key, no_key[32], no_iv[16]; EVP_CIPHER_CTX *ctx = NULL; double d = 0.0; if (lengths_single) { mblengths = &lengths_single; num = 1; } inp = app_malloc(mblengths[num - 1], "multiblock input buffer"); out = app_malloc(mblengths[num - 1] + 1024, "multiblock output buffer"); if ((ctx = EVP_CIPHER_CTX_new()) == NULL) app_bail_out("failed to allocate cipher context\n"); if (!EVP_EncryptInit_ex(ctx, evp_cipher, NULL, NULL, no_iv)) app_bail_out("failed to initialise cipher context\n"); if ((keylen = EVP_CIPHER_CTX_get_key_length(ctx)) < 0) { BIO_printf(bio_err, "Impossible negative key length: %d\n", keylen); goto err; } key = app_malloc(keylen, "evp_cipher key"); if (EVP_CIPHER_CTX_rand_key(ctx, key) <= 0) app_bail_out("failed to generate random cipher key\n"); if (!EVP_EncryptInit_ex(ctx, NULL, NULL, key, NULL)) app_bail_out("failed to set cipher key\n"); OPENSSL_clear_free(key, keylen); if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_MAC_KEY, sizeof(no_key), no_key) <= 0) app_bail_out("failed to set AEAD key\n"); if ((alg_name = EVP_CIPHER_get0_name(evp_cipher)) == NULL) app_bail_out("failed to get cipher name\n"); for (j = 0; j < num; j++) { print_message(alg_name, mblengths[j], seconds->sym); Time_F(START); for (count = 0; run && count < INT_MAX; count++) { unsigned char aad[EVP_AEAD_TLS1_AAD_LEN]; EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param; size_t len = mblengths[j]; int packlen; memset(aad, 0, 8); aad[8] = 23; aad[9] = 3; aad[10] = 2; aad[11] = 0; aad[12] = 0; mb_param.out = NULL; mb_param.inp = aad; mb_param.len = len; mb_param.interleave = 8; packlen = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_AAD, sizeof(mb_param), &mb_param); if (packlen > 0) { mb_param.out = out; mb_param.inp = inp; mb_param.len = len; (void)EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT, sizeof(mb_param), &mb_param); } else { int pad; if (RAND_bytes(inp, 16) <= 0) app_bail_out("error setting random bytes\n"); len += 16; aad[11] = (unsigned char)(len >> 8); aad[12] = (unsigned char)(len); pad = EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, EVP_AEAD_TLS1_AAD_LEN, aad); ciph_success = EVP_Cipher(ctx, out, inp, len + pad); } } d = Time_F(STOP); BIO_printf(bio_err, mr ? "+R:%d:%s:%f\n" : "%d %s ops in %.2fs\n", count, "evp", d); if ((ciph_success <= 0) && (mr == 0)) BIO_printf(bio_err, "Error performing cipher op\n"); results[D_EVP][j] = ((double)count) / d * mblengths[j]; } if (mr) { fprintf(stdout, "+H"); for (j = 0; j < num; j++) fprintf(stdout, ":%d", mblengths[j]); fprintf(stdout, "\n"); fprintf(stdout, "+F:%d:%s", D_EVP, alg_name); for (j = 0; j < num; j++) fprintf(stdout, ":%.2f", results[D_EVP][j]); fprintf(stdout, "\n"); } else { fprintf(stdout, "The 'numbers' are in 1000s of bytes per second processed.\n"); fprintf(stdout, "type "); for (j = 0; j < num; j++) fprintf(stdout, "%7d bytes", mblengths[j]); fprintf(stdout, "\n"); fprintf(stdout, "%-24s", alg_name); for (j = 0; j < num; j++) { if (results[D_EVP][j] > 10000) fprintf(stdout, " %11.2fk", results[D_EVP][j] / 1e3); else fprintf(stdout, " %11.2f ", results[D_EVP][j]); } fprintf(stdout, "\n"); } err: OPENSSL_free(inp); OPENSSL_free(out); EVP_CIPHER_CTX_free(ctx); }
apps
openssl/apps/speed.c
openssl
#include <stdio.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/pem.h> #include <openssl/err.h> typedef enum OPTION_choice { OPT_COMMON, OPT_TOSEQ, OPT_IN, OPT_OUT, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS nseq_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, OPT_SECTION("Output"), {"toseq", OPT_TOSEQ, '-', "Output NS Sequence file"}, {"out", OPT_OUT, '>', "Output file"}, OPT_PROV_OPTIONS, {NULL} }; int nseq_main(int argc, char **argv) { BIO *in = NULL, *out = NULL; X509 *x509 = NULL; NETSCAPE_CERT_SEQUENCE *seq = NULL; OPTION_CHOICE o; int toseq = 0, ret = 1, i; char *infile = NULL, *outfile = NULL, *prog; prog = opt_init(argc, argv, nseq_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(nseq_options); goto end; case OPT_TOSEQ: toseq = 1; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; in = bio_open_default(infile, 'r', FORMAT_PEM); if (in == NULL) goto end; out = bio_open_default(outfile, 'w', FORMAT_PEM); if (out == NULL) goto end; if (toseq) { seq = NETSCAPE_CERT_SEQUENCE_new(); if (seq == NULL) goto end; seq->certs = sk_X509_new_null(); if (seq->certs == NULL) goto end; while ((x509 = PEM_read_bio_X509(in, NULL, NULL, NULL))) { if (!sk_X509_push(seq->certs, x509)) goto end; } if (!sk_X509_num(seq->certs)) { BIO_printf(bio_err, "%s: Error reading certs file %s\n", prog, infile); ERR_print_errors(bio_err); goto end; } PEM_write_bio_NETSCAPE_CERT_SEQUENCE(out, seq); ret = 0; goto end; } seq = PEM_read_bio_NETSCAPE_CERT_SEQUENCE(in, NULL, NULL, NULL); if (seq == NULL) { BIO_printf(bio_err, "%s: Error reading sequence file %s\n", prog, 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; }
apps
openssl/apps/nseq.c
openssl
#include <openssl/opensslconf.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/dsa.h> #include <openssl/x509.h> #include <openssl/pem.h> typedef enum OPTION_choice { OPT_COMMON, OPT_OUT, OPT_PASSOUT, OPT_ENGINE, OPT_CIPHER, OPT_VERBOSE, OPT_QUIET, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS gendsa_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] dsaparam-file\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output the key to the specified file"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, {"", OPT_CIPHER, '-', "Encrypt the output with any supported cipher"}, {"verbose", OPT_VERBOSE, '-', "Verbose output"}, {"quiet", OPT_QUIET, '-', "Terse output"}, OPT_PARAMETERS(), {"dsaparam-file", 0, 0, "File containing DSA parameters"}, {NULL} }; int gendsa_main(int argc, char **argv) { ENGINE *e = NULL; BIO *out = NULL, *in = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_CIPHER *enc = NULL; char *dsaparams = NULL, *ciphername = NULL; char *outfile = NULL, *passoutarg = NULL, *passout = NULL, *prog; OPTION_CHOICE o; int ret = 1, private = 0, verbose = 0, nbits; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, gendsa_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(gendsa_options); goto end; case OPT_OUT: outfile = opt_arg(); break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_VERBOSE: verbose = 1; break; case OPT_QUIET: verbose = 0; break; } } if (!opt_check_rest_arg("params file")) goto opthelp; argv = opt_rest(); dsaparams = argv[0]; if (!app_RAND_load()) goto end; if (!opt_cipher(ciphername, &enc)) goto end; private = 1; if (!app_passwd(NULL, passoutarg, NULL, &passout)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } pkey = load_keyparams(dsaparams, FORMAT_UNDEF, 1, "DSA", "DSA parameters"); out = bio_open_owner(outfile, FORMAT_PEM, private); if (out == NULL) goto end2; nbits = EVP_PKEY_get_bits(pkey); if (nbits > OPENSSL_DSA_MAX_MODULUS_BITS) BIO_printf(bio_err, "Warning: It is not recommended to use more than %d bit for DSA keys.\n" " Your key size is %d! Larger key size may behave not as expected.\n", OPENSSL_DSA_MAX_MODULUS_BITS, EVP_PKEY_get_bits(pkey)); ctx = EVP_PKEY_CTX_new_from_pkey(app_get0_libctx(), pkey, app_get0_propq()); if (ctx == NULL) { BIO_printf(bio_err, "unable to create PKEY context\n"); goto end; } EVP_PKEY_free(pkey); pkey = NULL; if (EVP_PKEY_keygen_init(ctx) <= 0) { BIO_printf(bio_err, "unable to set up for key generation\n"); goto end; } pkey = app_keygen(ctx, "DSA", nbits, verbose); if (pkey == NULL) goto end; assert(private); if (!PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, passout)) { BIO_printf(bio_err, "unable to output generated key\n"); goto end; } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); end2: BIO_free(in); BIO_free_all(out); EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(ctx); EVP_CIPHER_free(enc); release_engine(e); OPENSSL_free(passout); return ret; }
apps
openssl/apps/gendsa.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/ssl.h> typedef enum OPTION_choice { OPT_ERR = -1, OPT_EOF = 0, OPT_HELP } OPTION_CHOICE; const OPTIONS errstr_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] errnum...\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_PARAMETERS(), {"errnum", 0, 0, "Error number(s) to decode"}, {NULL} }; int errstr_main(int argc, char **argv) { OPTION_CHOICE o; char buf[256], *prog; int ret = 1; unsigned long l; prog = opt_init(argc, argv, errstr_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(errstr_options); ret = 0; goto end; } } OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); ret = 0; for (argv = opt_rest(); *argv != NULL; argv++) { if (sscanf(*argv, "%lx", &l) <= 0) { ret++; } else { ERR_error_string_n(l, buf, sizeof(buf)); BIO_printf(bio_out, "%s\n", buf); } } end: return ret; }
apps
openssl/apps/errstr.c
openssl
#include <string.h> #include <openssl/opensslconf.h> #include <openssl/evp.h> #include <openssl/encoder.h> #include <openssl/decoder.h> #include <openssl/core_names.h> #include <openssl/core_dispatch.h> #include <openssl/params.h> #include <openssl/err.h> #include "apps.h" #include "progs.h" #include "ec_common.h" typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_ENGINE, OPT_IN, OPT_OUT, OPT_NOOUT, OPT_TEXT, OPT_PARAM_OUT, OPT_PUBIN, OPT_PUBOUT, OPT_PASSIN, OPT_PASSOUT, OPT_PARAM_ENC, OPT_CONV_FORM, OPT_CIPHER, OPT_NO_PUBLIC, OPT_CHECK, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS ec_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, 's', "Input file"}, {"inform", OPT_INFORM, 'f', "Input format (DER/PEM/P12/ENGINE)"}, {"pubin", OPT_PUBIN, '-', "Expect a public key in input file"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"check", OPT_CHECK, '-', "check key consistency"}, {"", OPT_CIPHER, '-', "Any supported cipher"}, {"param_enc", OPT_PARAM_ENC, 's', "Specifies the way the ec parameters are encoded"}, {"conv_form", OPT_CONV_FORM, 's', "Specifies the point conversion form "}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"outform", OPT_OUTFORM, 'F', "Output format - DER or PEM"}, {"noout", OPT_NOOUT, '-', "Don't print key out"}, {"text", OPT_TEXT, '-', "Print the key"}, {"param_out", OPT_PARAM_OUT, '-', "Print the elliptic curve parameters"}, {"pubout", OPT_PUBOUT, '-', "Output public key, not private"}, {"no_public", OPT_NO_PUBLIC, '-', "exclude public key from private key"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, OPT_PROV_OPTIONS, {NULL} }; int ec_main(int argc, char **argv) { OSSL_ENCODER_CTX *ectx = NULL; OSSL_DECODER_CTX *dctx = NULL; EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *eckey = NULL; BIO *out = NULL; ENGINE *e = NULL; EVP_CIPHER *enc = NULL; char *infile = NULL, *outfile = NULL, *ciphername = NULL, *prog; char *passin = NULL, *passout = NULL, *passinarg = NULL, *passoutarg = NULL; OPTION_CHOICE o; int informat = FORMAT_UNDEF, outformat = FORMAT_PEM, text = 0, noout = 0; int pubin = 0, pubout = 0, param_out = 0, ret = 1, private = 0; int check = 0; char *asn1_encoding = NULL; char *point_format = NULL; int no_public = 0; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, ec_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(ec_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_PEMDER, &outformat)) goto opthelp; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_NOOUT: noout = 1; break; case OPT_TEXT: text = 1; break; case OPT_PARAM_OUT: param_out = 1; break; case OPT_PUBIN: pubin = 1; break; case OPT_PUBOUT: pubout = 1; 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_CIPHER: ciphername = opt_unknown(); break; case OPT_CONV_FORM: point_format = opt_arg(); if (!opt_string(point_format, point_format_options)) goto opthelp; break; case OPT_PARAM_ENC: asn1_encoding = opt_arg(); if (!opt_string(asn1_encoding, asn1_encoding_options)) goto opthelp; break; case OPT_NO_PUBLIC: no_public = 1; break; case OPT_CHECK: check = 1; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!opt_cipher(ciphername, &enc)) goto opthelp; private = !pubin && (text || (!param_out && !pubout)); if (!app_passwd(passinarg, passoutarg, &passin, &passout)) { BIO_printf(bio_err, "Error getting passwords\n"); goto end; } BIO_printf(bio_err, "read EC key\n"); if (pubin) eckey = load_pubkey(infile, informat, 1, passin, e, "public key"); else eckey = load_key(infile, informat, 1, passin, e, "private key"); if (eckey == NULL) { BIO_printf(bio_err, "unable to load Key\n"); goto end; } out = bio_open_owner(outfile, outformat, private); if (out == NULL) goto end; if (point_format && !EVP_PKEY_set_utf8_string_param( eckey, OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT, point_format)) { BIO_printf(bio_err, "unable to set point conversion format\n"); goto end; } if (asn1_encoding != NULL && !EVP_PKEY_set_utf8_string_param( eckey, OSSL_PKEY_PARAM_EC_ENCODING, asn1_encoding)) { BIO_printf(bio_err, "unable to set asn1 encoding format\n"); goto end; } if (no_public) { if (!EVP_PKEY_set_int_param(eckey, OSSL_PKEY_PARAM_EC_INCLUDE_PUBLIC, 0)) { BIO_printf(bio_err, "unable to disable public key encoding\n"); goto end; } } else { if (!EVP_PKEY_set_int_param(eckey, OSSL_PKEY_PARAM_EC_INCLUDE_PUBLIC, 1)) { BIO_printf(bio_err, "unable to enable public key encoding\n"); goto end; } } if (text) { assert(pubin || private); if ((pubin && EVP_PKEY_print_public(out, eckey, 0, NULL) <= 0) || (!pubin && EVP_PKEY_print_private(out, eckey, 0, NULL) <= 0)) { BIO_printf(bio_err, "unable to print EC key\n"); goto end; } } if (check) { pctx = EVP_PKEY_CTX_new_from_pkey(NULL, eckey, NULL); if (pctx == NULL) { BIO_printf(bio_err, "unable to check EC key\n"); goto end; } if (EVP_PKEY_check(pctx) <= 0) BIO_printf(bio_err, "EC Key Invalid!\n"); else BIO_printf(bio_err, "EC Key valid.\n"); ERR_print_errors(bio_err); } if (!noout) { int selection; const char *output_type = outformat == FORMAT_ASN1 ? "DER" : "PEM"; const char *output_structure = "type-specific"; BIO_printf(bio_err, "writing EC key\n"); if (param_out) { selection = OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS; } else if (pubin || pubout) { selection = OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS | OSSL_KEYMGMT_SELECT_PUBLIC_KEY; output_structure = "SubjectPublicKeyInfo"; } else { selection = OSSL_KEYMGMT_SELECT_ALL; assert(private); } ectx = OSSL_ENCODER_CTX_new_for_pkey(eckey, selection, output_type, output_structure, NULL); if (enc != NULL) { OSSL_ENCODER_CTX_set_cipher(ectx, EVP_CIPHER_get0_name(enc), NULL); OSSL_ENCODER_CTX_set_passphrase_ui(ectx, get_ui_method(), NULL); if (passout != NULL) OSSL_ENCODER_CTX_set_passphrase(ectx, (const unsigned char *)passout, strlen(passout)); } if (!OSSL_ENCODER_to_bio(ectx, out)) { BIO_printf(bio_err, "unable to write EC key\n"); goto end; } } ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); BIO_free_all(out); EVP_PKEY_free(eckey); EVP_CIPHER_free(enc); OSSL_ENCODER_CTX_free(ectx); OSSL_DECODER_CTX_free(dctx); EVP_PKEY_CTX_free(pctx); release_engine(e); if (passin != NULL) OPENSSL_clear_free(passin, strlen(passin)); if (passout != NULL) OPENSSL_clear_free(passout, strlen(passout)); return ret; }
apps
openssl/apps/ec.c
openssl
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #if defined(_WIN32) # include <windows.h> #endif #include <openssl/e_os2.h> #include <openssl/async.h> #include <openssl/ssl.h> #include <openssl/decoder.h> #ifndef OPENSSL_NO_SOCK #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT) # define __U_INT typedef unsigned int u_int; #endif #include <openssl/bn.h> #include "apps.h" #include "progs.h" #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/x509.h> #include <openssl/rand.h> #include <openssl/ocsp.h> #ifndef OPENSSL_NO_DH # include <openssl/dh.h> #endif #include <openssl/rsa.h> #include "s_apps.h" #include "timeouts.h" #ifdef CHARSET_EBCDIC #include <openssl/ebcdic.h> #endif #include "internal/sockets.h" static int not_resumable_sess_cb(SSL *s, int is_forward_secure); static int sv_body(int s, int stype, int prot, unsigned char *context); static int www_body(int s, int stype, int prot, unsigned char *context); static int rev_body(int s, int stype, int prot, unsigned char *context); static void close_accept_socket(void); static int init_ssl_connection(SSL *s); static void print_stats(BIO *bp, SSL_CTX *ctx); static int generate_session_id(SSL *ssl, unsigned char *id, unsigned int *id_len); static void init_session_cache_ctx(SSL_CTX *sctx); static void free_sessions(void); static void print_connection_info(SSL *con); static const int bufsize = 16 * 1024; static int accept_socket = -1; #define TEST_CERT "server.pem" #define TEST_CERT2 "server2.pem" static int s_nbio = 0; static int s_nbio_test = 0; static int s_crlf = 0; static SSL_CTX *ctx = NULL; static SSL_CTX *ctx2 = NULL; static int www = 0; static BIO *bio_s_out = NULL; static BIO *bio_s_msg = NULL; static int s_debug = 0; static int s_tlsextdebug = 0; static int s_msg = 0; static int s_quiet = 0; static int s_ign_eof = 0; static int s_brief = 0; static char *keymatexportlabel = NULL; static int keymatexportlen = 20; static int async = 0; static int use_sendfile = 0; static int use_zc_sendfile = 0; static const char *session_id_prefix = NULL; static const unsigned char cert_type_rpk[] = { TLSEXT_cert_type_rpk, TLSEXT_cert_type_x509 }; static int enable_client_rpk = 0; #ifndef OPENSSL_NO_DTLS static int enable_timeouts = 0; static long socket_mtu; #endif static int dtlslisten = 0; static int stateless = 0; static int early_data = 0; static SSL_SESSION *psksess = NULL; static char *psk_identity = "Client_identity"; char *psk_key = NULL; static char http_server_binmode = 0; #ifndef OPENSSL_NO_PSK static unsigned int psk_server_cb(SSL *ssl, const char *identity, unsigned char *psk, unsigned int max_psk_len) { long key_len = 0; unsigned char *key; if (s_debug) BIO_printf(bio_s_out, "psk_server_cb\n"); if (!SSL_is_dtls(ssl) && SSL_version(ssl) >= TLS1_3_VERSION) { return 0; } if (identity == NULL) { BIO_printf(bio_err, "Error: client did not send PSK identity\n"); goto out_err; } if (s_debug) BIO_printf(bio_s_out, "identity_len=%d identity=%s\n", (int)strlen(identity), identity); if (strcmp(identity, psk_identity) != 0) { BIO_printf(bio_s_out, "PSK warning: client identity not what we expected" " (got '%s' expected '%s')\n", identity, psk_identity); } else { if (s_debug) BIO_printf(bio_s_out, "PSK client identity found\n"); } key = OPENSSL_hexstr2buf(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } if (key_len > (int)max_psk_len) { BIO_printf(bio_err, "psk buffer of callback is too small (%d) for key (%ld)\n", max_psk_len, key_len); OPENSSL_free(key); return 0; } memcpy(psk, key, key_len); OPENSSL_free(key); if (s_debug) BIO_printf(bio_s_out, "fetched PSK len=%ld\n", key_len); return key_len; out_err: if (s_debug) BIO_printf(bio_err, "Error in PSK server callback\n"); (void)BIO_flush(bio_err); (void)BIO_flush(bio_s_out); return 0; } #endif static int psk_find_session_cb(SSL *ssl, const unsigned char *identity, size_t identity_len, SSL_SESSION **sess) { SSL_SESSION *tmpsess = NULL; unsigned char *key; long key_len; const SSL_CIPHER *cipher = NULL; if (strlen(psk_identity) != identity_len || memcmp(psk_identity, identity, identity_len) != 0) { *sess = NULL; return 1; } if (psksess != NULL) { SSL_SESSION_up_ref(psksess); *sess = psksess; return 1; } key = OPENSSL_hexstr2buf(psk_key, &key_len); if (key == NULL) { BIO_printf(bio_err, "Could not convert PSK key '%s' to buffer\n", psk_key); return 0; } cipher = SSL_CIPHER_find(ssl, tls13_aes128gcmsha256_id); if (cipher == NULL) { BIO_printf(bio_err, "Error finding suitable ciphersuite\n"); OPENSSL_free(key); return 0; } tmpsess = SSL_SESSION_new(); if (tmpsess == NULL || !SSL_SESSION_set1_master_key(tmpsess, key, key_len) || !SSL_SESSION_set_cipher(tmpsess, cipher) || !SSL_SESSION_set_protocol_version(tmpsess, SSL_version(ssl))) { OPENSSL_free(key); SSL_SESSION_free(tmpsess); return 0; } OPENSSL_free(key); *sess = tmpsess; return 1; } #ifndef OPENSSL_NO_SRP static srpsrvparm srp_callback_parm; #endif static int local_argc = 0; static char **local_argv; #ifdef CHARSET_EBCDIC static int ebcdic_new(BIO *bi); static int ebcdic_free(BIO *a); static int ebcdic_read(BIO *b, char *out, int outl); static int ebcdic_write(BIO *b, const char *in, int inl); static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr); static int ebcdic_gets(BIO *bp, char *buf, int size); static int ebcdic_puts(BIO *bp, const char *str); # define BIO_TYPE_EBCDIC_FILTER (18|0x0200) static BIO_METHOD *methods_ebcdic = NULL; typedef struct { size_t alloced; char buff[1]; } EBCDIC_OUTBUFF; static const BIO_METHOD *BIO_f_ebcdic_filter(void) { if (methods_ebcdic == NULL) { methods_ebcdic = BIO_meth_new(BIO_TYPE_EBCDIC_FILTER, "EBCDIC/ASCII filter"); if (methods_ebcdic == NULL || !BIO_meth_set_write(methods_ebcdic, ebcdic_write) || !BIO_meth_set_read(methods_ebcdic, ebcdic_read) || !BIO_meth_set_puts(methods_ebcdic, ebcdic_puts) || !BIO_meth_set_gets(methods_ebcdic, ebcdic_gets) || !BIO_meth_set_ctrl(methods_ebcdic, ebcdic_ctrl) || !BIO_meth_set_create(methods_ebcdic, ebcdic_new) || !BIO_meth_set_destroy(methods_ebcdic, ebcdic_free)) return NULL; } return methods_ebcdic; } static int ebcdic_new(BIO *bi) { EBCDIC_OUTBUFF *wbuf; wbuf = app_malloc(sizeof(*wbuf) + 1024, "ebcdic wbuf"); wbuf->alloced = 1024; wbuf->buff[0] = '\0'; BIO_set_data(bi, wbuf); BIO_set_init(bi, 1); return 1; } static int ebcdic_free(BIO *a) { EBCDIC_OUTBUFF *wbuf; if (a == NULL) return 0; wbuf = BIO_get_data(a); OPENSSL_free(wbuf); BIO_set_data(a, NULL); BIO_set_init(a, 0); return 1; } static int ebcdic_read(BIO *b, char *out, int outl) { int ret = 0; BIO *next = BIO_next(b); if (out == NULL || outl == 0) return 0; if (next == NULL) return 0; ret = BIO_read(next, out, outl); if (ret > 0) ascii2ebcdic(out, out, ret); return ret; } static int ebcdic_write(BIO *b, const char *in, int inl) { EBCDIC_OUTBUFF *wbuf; BIO *next = BIO_next(b); int ret = 0; int num; if ((in == NULL) || (inl <= 0)) return 0; if (next == NULL) return 0; wbuf = (EBCDIC_OUTBUFF *) BIO_get_data(b); if (inl > (num = wbuf->alloced)) { num = num + num; if (num < inl) num = inl; OPENSSL_free(wbuf); wbuf = app_malloc(sizeof(*wbuf) + num, "grow ebcdic wbuf"); wbuf->alloced = num; wbuf->buff[0] = '\0'; BIO_set_data(b, wbuf); } ebcdic2ascii(wbuf->buff, in, inl); ret = BIO_write(next, wbuf->buff, inl); return ret; } static long ebcdic_ctrl(BIO *b, int cmd, long num, void *ptr) { long ret; BIO *next = BIO_next(b); if (next == NULL) return 0; switch (cmd) { case BIO_CTRL_DUP: ret = 0L; break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static int ebcdic_gets(BIO *bp, char *buf, int size) { int i, ret = 0; BIO *next = BIO_next(bp); if (next == NULL) return 0; for (i = 0; i < size - 1; ++i) { ret = ebcdic_read(bp, &buf[i], 1); if (ret <= 0) break; else if (buf[i] == '\n') { ++i; break; } } if (i < size) buf[i] = '\0'; return (ret < 0 && i == 0) ? ret : i; } static int ebcdic_puts(BIO *bp, const char *str) { if (BIO_next(bp) == NULL) return 0; return ebcdic_write(bp, str, strlen(str)); } #endif typedef struct tlsextctx_st { char *servername; BIO *biodebug; int extension_error; } tlsextctx; static int ssl_servername_cb(SSL *s, int *ad, void *arg) { tlsextctx *p = (tlsextctx *) arg; const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name); if (servername != NULL && p->biodebug != NULL) { const char *cp = servername; unsigned char uc; BIO_printf(p->biodebug, "Hostname in TLS extension: \""); while ((uc = *cp++) != 0) BIO_printf(p->biodebug, (((uc) & ~127) == 0) && isprint(uc) ? "%c" : "\\x%02x", uc); BIO_printf(p->biodebug, "\"\n"); } if (p->servername == NULL) return SSL_TLSEXT_ERR_NOACK; if (servername != NULL) { if (OPENSSL_strcasecmp(servername, p->servername)) return p->extension_error; if (ctx2 != NULL) { BIO_printf(p->biodebug, "Switching server context.\n"); SSL_set_SSL_CTX(s, ctx2); } } return SSL_TLSEXT_ERR_OK; } typedef struct tlsextstatusctx_st { int timeout; char *respin; char *host, *path, *port; char *proxy, *no_proxy; int use_ssl; int verbose; } tlsextstatusctx; static tlsextstatusctx tlscstatp = { -1 }; #ifndef OPENSSL_NO_OCSP static int get_ocsp_resp_from_responder(SSL *s, tlsextstatusctx *srctx, OCSP_RESPONSE **resp) { char *host = NULL, *port = NULL, *path = NULL; char *proxy = NULL, *no_proxy = NULL; int use_ssl; STACK_OF(OPENSSL_STRING) *aia = NULL; X509 *x = NULL, *cert; X509_NAME *iname; STACK_OF(X509) *chain = NULL; SSL_CTX *ssl_ctx; X509_STORE_CTX *inctx = NULL; X509_OBJECT *obj; OCSP_REQUEST *req = NULL; OCSP_CERTID *id = NULL; STACK_OF(X509_EXTENSION) *exts; int ret = SSL_TLSEXT_ERR_NOACK; int i; x = SSL_get_certificate(s); iname = X509_get_issuer_name(x); aia = X509_get1_ocsp(x); if (aia != NULL) { if (!OSSL_HTTP_parse_url(sk_OPENSSL_STRING_value(aia, 0), &use_ssl, NULL, &host, &port, NULL, &path, NULL, NULL)) { BIO_puts(bio_err, "cert_status: can't parse AIA URL\n"); goto err; } if (srctx->verbose) BIO_printf(bio_err, "cert_status: AIA URL: %s\n", sk_OPENSSL_STRING_value(aia, 0)); } else { if (srctx->host == NULL) { BIO_puts(bio_err, "cert_status: no AIA and no default responder URL\n"); goto done; } host = srctx->host; path = srctx->path; port = srctx->port; use_ssl = srctx->use_ssl; } proxy = srctx->proxy; no_proxy = srctx->no_proxy; ssl_ctx = SSL_get_SSL_CTX(s); if (!SSL_CTX_get0_chain_certs(ssl_ctx, &chain)) goto err; for (i = 0; i < sk_X509_num(chain); i++) { cert = sk_X509_value(chain, i); if (X509_name_cmp(iname, X509_get_subject_name(cert)) == 0) { id = OCSP_cert_to_id(NULL, x, cert); break; } } if (id == NULL) { inctx = X509_STORE_CTX_new(); if (inctx == NULL) goto err; if (!X509_STORE_CTX_init(inctx, SSL_CTX_get_cert_store(ssl_ctx), NULL, NULL)) goto err; obj = X509_STORE_CTX_get_obj_by_subject(inctx, X509_LU_X509, iname); if (obj == NULL) { BIO_puts(bio_err, "cert_status: Can't retrieve issuer certificate.\n"); goto done; } id = OCSP_cert_to_id(NULL, x, X509_OBJECT_get0_X509(obj)); X509_OBJECT_free(obj); } if (id == NULL) goto err; req = OCSP_REQUEST_new(); if (req == NULL) goto err; if (!OCSP_request_add0_id(req, id)) goto err; id = NULL; SSL_get_tlsext_status_exts(s, &exts); for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) { X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i); if (!OCSP_REQUEST_add_ext(req, ext, -1)) goto err; } *resp = process_responder(req, host, port, path, proxy, no_proxy, use_ssl, NULL , srctx->timeout); if (*resp == NULL) { BIO_puts(bio_err, "cert_status: error querying responder\n"); goto done; } ret = SSL_TLSEXT_ERR_OK; goto done; err: ret = SSL_TLSEXT_ERR_ALERT_FATAL; done: if (aia != NULL) { OPENSSL_free(host); OPENSSL_free(path); OPENSSL_free(port); X509_email_free(aia); } OCSP_CERTID_free(id); OCSP_REQUEST_free(req); X509_STORE_CTX_free(inctx); return ret; } static int cert_status_cb(SSL *s, void *arg) { tlsextstatusctx *srctx = arg; OCSP_RESPONSE *resp = NULL; unsigned char *rspder = NULL; int rspderlen; int ret = SSL_TLSEXT_ERR_ALERT_FATAL; if (srctx->verbose) BIO_puts(bio_err, "cert_status: callback called\n"); if (srctx->respin != NULL) { BIO *derbio = bio_open_default(srctx->respin, 'r', FORMAT_ASN1); if (derbio == NULL) { BIO_puts(bio_err, "cert_status: Cannot open OCSP response file\n"); goto err; } resp = d2i_OCSP_RESPONSE_bio(derbio, NULL); BIO_free(derbio); if (resp == NULL) { BIO_puts(bio_err, "cert_status: Error reading OCSP response\n"); goto err; } } else { ret = get_ocsp_resp_from_responder(s, srctx, &resp); if (ret != SSL_TLSEXT_ERR_OK) goto err; } rspderlen = i2d_OCSP_RESPONSE(resp, &rspder); if (rspderlen <= 0) goto err; SSL_set_tlsext_status_ocsp_resp(s, rspder, rspderlen); if (srctx->verbose) { BIO_puts(bio_err, "cert_status: ocsp response sent:\n"); OCSP_RESPONSE_print(bio_err, resp, 2); } ret = SSL_TLSEXT_ERR_OK; err: if (ret != SSL_TLSEXT_ERR_OK) ERR_print_errors(bio_err); OCSP_RESPONSE_free(resp); return ret; } #endif #ifndef OPENSSL_NO_NEXTPROTONEG typedef struct tlsextnextprotoctx_st { unsigned char *data; size_t len; } tlsextnextprotoctx; static int next_proto_cb(SSL *s, const unsigned char **data, unsigned int *len, void *arg) { tlsextnextprotoctx *next_proto = arg; *data = next_proto->data; *len = next_proto->len; return SSL_TLSEXT_ERR_OK; } #endif typedef struct tlsextalpnctx_st { unsigned char *data; size_t len; } tlsextalpnctx; static int alpn_cb(SSL *s, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg) { tlsextalpnctx *alpn_ctx = arg; if (!s_quiet) { unsigned int i; BIO_printf(bio_s_out, "ALPN protocols advertised by the client: "); for (i = 0; i < inlen;) { if (i) BIO_write(bio_s_out, ", ", 2); BIO_write(bio_s_out, &in[i + 1], in[i]); i += in[i] + 1; } BIO_write(bio_s_out, "\n", 1); } if (SSL_select_next_proto ((unsigned char **)out, outlen, alpn_ctx->data, alpn_ctx->len, in, inlen) != OPENSSL_NPN_NEGOTIATED) { return SSL_TLSEXT_ERR_ALERT_FATAL; } if (!s_quiet) { BIO_printf(bio_s_out, "ALPN protocols selected: "); BIO_write(bio_s_out, *out, *outlen); BIO_write(bio_s_out, "\n", 1); } return SSL_TLSEXT_ERR_OK; } static int not_resumable_sess_cb(SSL *s, int is_forward_secure) { return is_forward_secure; } typedef enum OPTION_choice { OPT_COMMON, OPT_ENGINE, OPT_4, OPT_6, OPT_ACCEPT, OPT_PORT, OPT_UNIX, OPT_UNLINK, OPT_NACCEPT, OPT_VERIFY, OPT_NAMEOPT, OPT_UPPER_V_VERIFY, OPT_CONTEXT, OPT_CERT, OPT_CRL, OPT_CRL_DOWNLOAD, OPT_SERVERINFO, OPT_CERTFORM, OPT_KEY, OPT_KEYFORM, OPT_PASS, OPT_CERT_CHAIN, OPT_DHPARAM, OPT_DCERTFORM, OPT_DCERT, OPT_DKEYFORM, OPT_DPASS, OPT_DKEY, OPT_DCERT_CHAIN, OPT_NOCERT, OPT_CAPATH, OPT_NOCAPATH, OPT_CHAINCAPATH, OPT_VERIFYCAPATH, OPT_NO_CACHE, OPT_EXT_CACHE, OPT_CRLFORM, OPT_VERIFY_RET_ERROR, OPT_VERIFY_QUIET, OPT_BUILD_CHAIN, OPT_CAFILE, OPT_NOCAFILE, OPT_CHAINCAFILE, OPT_VERIFYCAFILE, OPT_CASTORE, OPT_NOCASTORE, OPT_CHAINCASTORE, OPT_VERIFYCASTORE, OPT_NBIO, OPT_NBIO_TEST, OPT_IGN_EOF, OPT_NO_IGN_EOF, OPT_DEBUG, OPT_TLSEXTDEBUG, OPT_STATUS, OPT_STATUS_VERBOSE, OPT_STATUS_TIMEOUT, OPT_PROXY, OPT_NO_PROXY, OPT_STATUS_URL, OPT_STATUS_FILE, OPT_MSG, OPT_MSGFILE, OPT_TRACE, OPT_SECURITY_DEBUG, OPT_SECURITY_DEBUG_VERBOSE, OPT_STATE, OPT_CRLF, OPT_QUIET, OPT_BRIEF, OPT_NO_DHE, OPT_NO_RESUME_EPHEMERAL, OPT_PSK_IDENTITY, OPT_PSK_HINT, OPT_PSK, OPT_PSK_SESS, OPT_SRPVFILE, OPT_SRPUSERSEED, OPT_REV, OPT_WWW, OPT_UPPER_WWW, OPT_HTTP, OPT_ASYNC, OPT_SSL_CONFIG, OPT_MAX_SEND_FRAG, OPT_SPLIT_SEND_FRAG, OPT_MAX_PIPELINES, OPT_READ_BUF, OPT_SSL3, OPT_TLS1_3, OPT_TLS1_2, OPT_TLS1_1, OPT_TLS1, OPT_DTLS, OPT_DTLS1, OPT_DTLS1_2, OPT_SCTP, OPT_TIMEOUT, OPT_MTU, OPT_LISTEN, OPT_STATELESS, OPT_ID_PREFIX, OPT_SERVERNAME, OPT_SERVERNAME_FATAL, OPT_CERT2, OPT_KEY2, OPT_NEXTPROTONEG, OPT_ALPN, OPT_SENDFILE, OPT_SRTP_PROFILES, OPT_KEYMATEXPORT, OPT_KEYMATEXPORTLEN, OPT_KEYLOG_FILE, OPT_MAX_EARLY, OPT_RECV_MAX_EARLY, OPT_EARLY_DATA, OPT_S_NUM_TICKETS, OPT_ANTI_REPLAY, OPT_NO_ANTI_REPLAY, OPT_SCTP_LABEL_BUG, OPT_HTTP_SERVER_BINMODE, OPT_NOCANAMES, OPT_IGNORE_UNEXPECTED_EOF, OPT_KTLS, OPT_USE_ZC_SENDFILE, OPT_TFO, OPT_CERT_COMP, OPT_ENABLE_SERVER_RPK, OPT_ENABLE_CLIENT_RPK, OPT_R_ENUM, OPT_S_ENUM, OPT_V_ENUM, OPT_X_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS s_server_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"ssl_config", OPT_SSL_CONFIG, 's', "Configure SSL_CTX using the given configuration value"}, #ifndef OPENSSL_NO_SSL_TRACE {"trace", OPT_TRACE, '-', "trace protocol messages"}, #endif #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Network"), {"port", OPT_PORT, 'p', "TCP/IP port to listen on for connections (default is " PORT ")"}, {"accept", OPT_ACCEPT, 's', "TCP/IP optional host and port to listen on for connections (default is *:" PORT ")"}, #ifdef AF_UNIX {"unix", OPT_UNIX, 's', "Unix domain socket to accept on"}, {"unlink", OPT_UNLINK, '-', "For -unix, unlink existing socket first"}, #endif {"4", OPT_4, '-', "Use IPv4 only"}, {"6", OPT_6, '-', "Use IPv6 only"}, #if defined(TCP_FASTOPEN) && !defined(OPENSSL_NO_TFO) {"tfo", OPT_TFO, '-', "Listen for TCP Fast Open connections"}, #endif OPT_SECTION("Identity"), {"context", OPT_CONTEXT, 's', "Set session ID context"}, {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"}, {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"}, {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store URI"}, {"nocert", OPT_NOCERT, '-', "Don't use any certificates (Anon-DH)"}, {"verify", OPT_VERIFY, 'n', "Turn on peer certificate verification"}, {"Verify", OPT_UPPER_V_VERIFY, 'n', "Turn on peer certificate verification, must have a cert"}, {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"cert", OPT_CERT, '<', "Server certificate file to use; default " TEST_CERT}, {"cert2", OPT_CERT2, '<', "Certificate file to use for servername; default " TEST_CERT2}, {"certform", OPT_CERTFORM, 'F', "Server certificate file format (PEM/DER/P12); has no effect"}, {"cert_chain", OPT_CERT_CHAIN, '<', "Server certificate chain file in PEM format"}, {"build_chain", OPT_BUILD_CHAIN, '-', "Build server certificate chain"}, {"serverinfo", OPT_SERVERINFO, 's', "PEM serverinfo file for certificate"}, {"key", OPT_KEY, 's', "Private key file to use; default is -cert file or else" TEST_CERT}, {"key2", OPT_KEY2, '<', "-Private Key file to use for servername if not in -cert2"}, {"keyform", OPT_KEYFORM, 'f', "Key format (ENGINE, other values ignored)"}, {"pass", OPT_PASS, 's', "Private key and cert file pass phrase source"}, {"dcert", OPT_DCERT, '<', "Second server certificate file to use (usually for DSA)"}, {"dcertform", OPT_DCERTFORM, 'F', "Second server certificate file format (PEM/DER/P12); has no effect"}, {"dcert_chain", OPT_DCERT_CHAIN, '<', "second server certificate chain file in PEM format"}, {"dkey", OPT_DKEY, '<', "Second private key file to use (usually for DSA)"}, {"dkeyform", OPT_DKEYFORM, 'f', "Second key file format (ENGINE, other values ignored)"}, {"dpass", OPT_DPASS, 's', "Second private key and cert file pass phrase source"}, {"dhparam", OPT_DHPARAM, '<', "DH parameters file to use"}, {"servername", OPT_SERVERNAME, 's', "Servername for HostName TLS extension"}, {"servername_fatal", OPT_SERVERNAME_FATAL, '-', "On servername mismatch send fatal alert (default warning alert)"}, {"nbio_test", OPT_NBIO_TEST, '-', "Test with the non-blocking test bio"}, {"crlf", OPT_CRLF, '-', "Convert LF from terminal into CRLF"}, {"quiet", OPT_QUIET, '-', "No server output"}, {"no_resume_ephemeral", OPT_NO_RESUME_EPHEMERAL, '-', "Disable caching and tickets if ephemeral (EC)DH is used"}, {"www", OPT_WWW, '-', "Respond to a 'GET /' with a status page"}, {"WWW", OPT_UPPER_WWW, '-', "Respond to a 'GET with the file ./path"}, {"ignore_unexpected_eof", OPT_IGNORE_UNEXPECTED_EOF, '-', "Do not treat lack of close_notify from a peer as an error"}, {"tlsextdebug", OPT_TLSEXTDEBUG, '-', "Hex dump of all TLS extensions received"}, {"HTTP", OPT_HTTP, '-', "Like -WWW but ./path includes HTTP headers"}, {"id_prefix", OPT_ID_PREFIX, 's', "Generate SSL/TLS session IDs prefixed by arg"}, {"keymatexport", OPT_KEYMATEXPORT, 's', "Export keying material using label"}, {"keymatexportlen", OPT_KEYMATEXPORTLEN, 'p', "Export len bytes of keying material; default 20"}, {"CRL", OPT_CRL, '<', "CRL file to use"}, {"CRLform", OPT_CRLFORM, 'F', "CRL file format (PEM or DER); default PEM"}, {"crl_download", OPT_CRL_DOWNLOAD, '-', "Download CRLs from distribution points in certificate CDP entries"}, {"chainCAfile", OPT_CHAINCAFILE, '<', "CA file for certificate chain (PEM format)"}, {"chainCApath", OPT_CHAINCAPATH, '/', "use dir as certificate store path to build CA certificate chain"}, {"chainCAstore", OPT_CHAINCASTORE, ':', "use URI as certificate store to build CA certificate chain"}, {"verifyCAfile", OPT_VERIFYCAFILE, '<', "CA file for certificate verification (PEM format)"}, {"verifyCApath", OPT_VERIFYCAPATH, '/', "use dir as certificate store path to verify CA certificate"}, {"verifyCAstore", OPT_VERIFYCASTORE, ':', "use URI as certificate store to verify CA certificate"}, {"no_cache", OPT_NO_CACHE, '-', "Disable session cache"}, {"ext_cache", OPT_EXT_CACHE, '-', "Disable internal cache, set up and use external cache"}, {"verify_return_error", OPT_VERIFY_RET_ERROR, '-', "Close connection on verification error"}, {"verify_quiet", OPT_VERIFY_QUIET, '-', "No verify output except verify errors"}, {"ign_eof", OPT_IGN_EOF, '-', "Ignore input EOF (default when -quiet)"}, {"no_ign_eof", OPT_NO_IGN_EOF, '-', "Do not ignore input EOF"}, #ifndef OPENSSL_NO_COMP_ALG {"cert_comp", OPT_CERT_COMP, '-', "Pre-compress server certificates"}, #endif #ifndef OPENSSL_NO_OCSP OPT_SECTION("OCSP"), {"status", OPT_STATUS, '-', "Request certificate status from server"}, {"status_verbose", OPT_STATUS_VERBOSE, '-', "Print more output in certificate status callback"}, {"status_timeout", OPT_STATUS_TIMEOUT, 'n', "Status request responder timeout"}, {"status_url", OPT_STATUS_URL, 's', "Status request fallback URL"}, {"proxy", OPT_PROXY, 's', "[http[s]: {"no_proxy", OPT_NO_PROXY, 's', "List of addresses of servers not to use HTTP(S) proxy for"}, {OPT_MORE_STR, 0, 0, "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"}, {"status_file", OPT_STATUS_FILE, '<', "File containing DER encoded OCSP Response"}, #endif OPT_SECTION("Debug"), {"security_debug", OPT_SECURITY_DEBUG, '-', "Print output from SSL/TLS security framework"}, {"security_debug_verbose", OPT_SECURITY_DEBUG_VERBOSE, '-', "Print more output from SSL/TLS security framework"}, {"brief", OPT_BRIEF, '-', "Restrict output to brief summary of connection parameters"}, {"rev", OPT_REV, '-', "act as an echo server that sends back received text reversed"}, {"debug", OPT_DEBUG, '-', "Print more output"}, {"msg", OPT_MSG, '-', "Show protocol messages"}, {"msgfile", OPT_MSGFILE, '>', "File to send output of -msg or -trace, instead of stdout"}, {"state", OPT_STATE, '-', "Print the SSL states"}, {"async", OPT_ASYNC, '-', "Operate in asynchronous mode"}, {"max_pipelines", OPT_MAX_PIPELINES, 'p', "Maximum number of encrypt/decrypt pipelines to be used"}, {"naccept", OPT_NACCEPT, 'p', "Terminate after #num connections"}, {"keylogfile", OPT_KEYLOG_FILE, '>', "Write TLS secrets to file"}, OPT_SECTION("Network"), {"nbio", OPT_NBIO, '-', "Use non-blocking IO"}, {"timeout", OPT_TIMEOUT, '-', "Enable timeouts"}, {"mtu", OPT_MTU, 'p', "Set link-layer MTU"}, {"read_buf", OPT_READ_BUF, 'p', "Default read buffer size to be used for connections"}, {"split_send_frag", OPT_SPLIT_SEND_FRAG, 'p', "Size used to split data for encrypt pipelines"}, {"max_send_frag", OPT_MAX_SEND_FRAG, 'p', "Maximum Size of send frames "}, OPT_SECTION("Server identity"), {"psk_identity", OPT_PSK_IDENTITY, 's', "PSK identity to expect"}, #ifndef OPENSSL_NO_PSK {"psk_hint", OPT_PSK_HINT, 's', "PSK identity hint to use"}, #endif {"psk", OPT_PSK, 's', "PSK in hex (without 0x)"}, {"psk_session", OPT_PSK_SESS, '<', "File to read PSK SSL session from"}, #ifndef OPENSSL_NO_SRP {"srpvfile", OPT_SRPVFILE, '<', "(deprecated) The verifier file for SRP"}, {"srpuserseed", OPT_SRPUSERSEED, 's', "(deprecated) A seed string for a default user salt"}, #endif OPT_SECTION("Protocol and version"), {"max_early_data", OPT_MAX_EARLY, 'n', "The maximum number of bytes of early data as advertised in tickets"}, {"recv_max_early_data", OPT_RECV_MAX_EARLY, 'n', "The maximum number of bytes of early data (hard limit)"}, {"early_data", OPT_EARLY_DATA, '-', "Attempt to read early data"}, {"num_tickets", OPT_S_NUM_TICKETS, 'n', "The number of TLSv1.3 session tickets that a server will automatically issue" }, {"anti_replay", OPT_ANTI_REPLAY, '-', "Switch on anti-replay protection (default)"}, {"no_anti_replay", OPT_NO_ANTI_REPLAY, '-', "Switch off anti-replay protection"}, {"http_server_binmode", OPT_HTTP_SERVER_BINMODE, '-', "opening files in binary mode when acting as http server (-WWW and -HTTP)"}, {"no_ca_names", OPT_NOCANAMES, '-', "Disable TLS Extension CA Names"}, {"stateless", OPT_STATELESS, '-', "Require TLSv1.3 cookies"}, #ifndef OPENSSL_NO_SSL3 {"ssl3", OPT_SSL3, '-', "Just talk SSLv3"}, #endif #ifndef OPENSSL_NO_TLS1 {"tls1", OPT_TLS1, '-', "Just talk TLSv1"}, #endif #ifndef OPENSSL_NO_TLS1_1 {"tls1_1", OPT_TLS1_1, '-', "Just talk TLSv1.1"}, #endif #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "just talk TLSv1.2"}, #endif #ifndef OPENSSL_NO_TLS1_3 {"tls1_3", OPT_TLS1_3, '-', "just talk TLSv1.3"}, #endif #ifndef OPENSSL_NO_DTLS {"dtls", OPT_DTLS, '-', "Use any DTLS version"}, {"listen", OPT_LISTEN, '-', "Listen for a DTLS ClientHello with a cookie and then connect"}, #endif #ifndef OPENSSL_NO_DTLS1 {"dtls1", OPT_DTLS1, '-', "Just talk DTLSv1"}, #endif #ifndef OPENSSL_NO_DTLS1_2 {"dtls1_2", OPT_DTLS1_2, '-', "Just talk DTLSv1.2"}, #endif #ifndef OPENSSL_NO_SCTP {"sctp", OPT_SCTP, '-', "Use SCTP"}, {"sctp_label_bug", OPT_SCTP_LABEL_BUG, '-', "Enable SCTP label length bug"}, #endif #ifndef OPENSSL_NO_SRTP {"use_srtp", OPT_SRTP_PROFILES, 's', "Offer SRTP key management with a colon-separated profile list"}, #endif {"no_dhe", OPT_NO_DHE, '-', "Disable ephemeral DH"}, #ifndef OPENSSL_NO_NEXTPROTONEG {"nextprotoneg", OPT_NEXTPROTONEG, 's', "Set the advertised protocols for the NPN extension (comma-separated list)"}, #endif {"alpn", OPT_ALPN, 's', "Set the advertised protocols for the ALPN extension (comma-separated list)"}, #ifndef OPENSSL_NO_KTLS {"ktls", OPT_KTLS, '-', "Enable Kernel TLS for sending and receiving"}, {"sendfile", OPT_SENDFILE, '-', "Use sendfile to response file with -WWW"}, {"zerocopy_sendfile", OPT_USE_ZC_SENDFILE, '-', "Use zerocopy mode of KTLS sendfile"}, #endif {"enable_server_rpk", OPT_ENABLE_SERVER_RPK, '-', "Enable raw public keys (RFC7250) from the server"}, {"enable_client_rpk", OPT_ENABLE_CLIENT_RPK, '-', "Enable raw public keys (RFC7250) from the client"}, OPT_R_OPTIONS, OPT_S_OPTIONS, OPT_V_OPTIONS, OPT_X_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; #define IS_PROT_FLAG(o) \ (o == OPT_SSL3 || o == OPT_TLS1 || o == OPT_TLS1_1 || o == OPT_TLS1_2 \ || o == OPT_TLS1_3 || o == OPT_DTLS || o == OPT_DTLS1 || o == OPT_DTLS1_2) int s_server_main(int argc, char *argv[]) { ENGINE *engine = NULL; EVP_PKEY *s_key = NULL, *s_dkey = NULL; SSL_CONF_CTX *cctx = NULL; const SSL_METHOD *meth = TLS_server_method(); SSL_EXCERT *exc = NULL; STACK_OF(OPENSSL_STRING) *ssl_args = NULL; STACK_OF(X509) *s_chain = NULL, *s_dchain = NULL; STACK_OF(X509_CRL) *crls = NULL; X509 *s_cert = NULL, *s_dcert = NULL; X509_VERIFY_PARAM *vpm = NULL; const char *CApath = NULL, *CAfile = NULL, *CAstore = NULL; const char *chCApath = NULL, *chCAfile = NULL, *chCAstore = NULL; char *dpassarg = NULL, *dpass = NULL; char *passarg = NULL, *pass = NULL; char *vfyCApath = NULL, *vfyCAfile = NULL, *vfyCAstore = NULL; char *crl_file = NULL, *prog; #ifdef AF_UNIX int unlink_unix_path = 0; #endif do_server_cb server_cb; int vpmtouched = 0, build_chain = 0, no_cache = 0, ext_cache = 0; char *dhfile = NULL; int no_dhe = 0; int nocert = 0, ret = 1; int noCApath = 0, noCAfile = 0, noCAstore = 0; int s_cert_format = FORMAT_UNDEF, s_key_format = FORMAT_UNDEF; int s_dcert_format = FORMAT_UNDEF, s_dkey_format = FORMAT_UNDEF; int rev = 0, naccept = -1, sdebug = 0; int socket_family = AF_UNSPEC, socket_type = SOCK_STREAM, protocol = 0; int state = 0, crl_format = FORMAT_UNDEF, crl_download = 0; char *host = NULL; char *port = NULL; unsigned char *context = NULL; OPTION_CHOICE o; EVP_PKEY *s_key2 = NULL; X509 *s_cert2 = NULL; tlsextctx tlsextcbp = { NULL, NULL, SSL_TLSEXT_ERR_ALERT_WARNING }; const char *ssl_config = NULL; int read_buf_len = 0; #ifndef OPENSSL_NO_NEXTPROTONEG const char *next_proto_neg_in = NULL; tlsextnextprotoctx next_proto = { NULL, 0 }; #endif const char *alpn_in = NULL; tlsextalpnctx alpn_ctx = { NULL, 0 }; #ifndef OPENSSL_NO_PSK char *psk_identity_hint = NULL; #endif char *p; #ifndef OPENSSL_NO_SRP char *srpuserseed = NULL; char *srp_verifier_file = NULL; #endif #ifndef OPENSSL_NO_SRTP char *srtp_profiles = NULL; #endif int min_version = 0, max_version = 0, prot_opt = 0, no_prot_opt = 0; int s_server_verify = SSL_VERIFY_NONE; int s_server_session_id_context = 1; const char *s_cert_file = TEST_CERT, *s_key_file = NULL, *s_chain_file = NULL; const char *s_cert_file2 = TEST_CERT2, *s_key_file2 = NULL; char *s_dcert_file = NULL, *s_dkey_file = NULL, *s_dchain_file = NULL; #ifndef OPENSSL_NO_OCSP int s_tlsextstatus = 0; #endif int no_resume_ephemeral = 0; unsigned int max_send_fragment = 0; unsigned int split_send_fragment = 0, max_pipelines = 0; const char *s_serverinfo_file = NULL; const char *keylog_file = NULL; int max_early_data = -1, recv_max_early_data = -1; char *psksessf = NULL; int no_ca_names = 0; #ifndef OPENSSL_NO_SCTP int sctp_label_bug = 0; #endif int ignore_unexpected_eof = 0; #ifndef OPENSSL_NO_KTLS int enable_ktls = 0; #endif int tfo = 0; int cert_comp = 0; int enable_server_rpk = 0; local_argc = argc; local_argv = argv; ctx = ctx2 = NULL; s_nbio = s_nbio_test = 0; www = 0; bio_s_out = NULL; s_debug = 0; s_msg = 0; s_quiet = 0; s_brief = 0; async = 0; use_sendfile = 0; use_zc_sendfile = 0; port = OPENSSL_strdup(PORT); cctx = SSL_CONF_CTX_new(); vpm = X509_VERIFY_PARAM_new(); if (port == NULL || cctx == NULL || vpm == NULL) goto end; SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER | SSL_CONF_FLAG_CMDLINE); prog = opt_init(argc, argv, s_server_options); while ((o = opt_next()) != OPT_EOF) { if (IS_PROT_FLAG(o) && ++prot_opt > 1) { BIO_printf(bio_err, "Cannot supply multiple protocol flags\n"); goto end; } if (IS_NO_PROT_FLAG(o)) no_prot_opt++; if (prot_opt == 1 && no_prot_opt) { BIO_printf(bio_err, "Cannot supply both a protocol flag and '-no_<prot>'\n"); goto end; } 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_server_options); ret = 0; goto end; case OPT_4: #ifdef AF_UNIX if (socket_family == AF_UNIX) { OPENSSL_free(host); host = NULL; OPENSSL_free(port); port = NULL; } #endif socket_family = AF_INET; break; case OPT_6: if (1) { #ifdef AF_INET6 #ifdef AF_UNIX if (socket_family == AF_UNIX) { OPENSSL_free(host); host = NULL; OPENSSL_free(port); port = NULL; } #endif socket_family = AF_INET6; } else { #endif BIO_printf(bio_err, "%s: IPv6 domain sockets unsupported\n", prog); goto end; } break; case OPT_PORT: #ifdef AF_UNIX if (socket_family == AF_UNIX) { socket_family = AF_UNSPEC; } #endif OPENSSL_free(port); port = NULL; OPENSSL_free(host); host = NULL; if (BIO_parse_hostserv(opt_arg(), NULL, &port, BIO_PARSE_PRIO_SERV) < 1) { BIO_printf(bio_err, "%s: -port argument malformed or ambiguous\n", port); goto end; } break; case OPT_ACCEPT: #ifdef AF_UNIX if (socket_family == AF_UNIX) { socket_family = AF_UNSPEC; } #endif OPENSSL_free(port); port = NULL; OPENSSL_free(host); host = NULL; if (BIO_parse_hostserv(opt_arg(), &host, &port, BIO_PARSE_PRIO_SERV) < 1) { BIO_printf(bio_err, "%s: -accept argument malformed or ambiguous\n", port); goto end; } break; #ifdef AF_UNIX case OPT_UNIX: socket_family = AF_UNIX; OPENSSL_free(host); host = OPENSSL_strdup(opt_arg()); if (host == NULL) goto end; OPENSSL_free(port); port = NULL; break; case OPT_UNLINK: unlink_unix_path = 1; break; #endif case OPT_NACCEPT: naccept = atol(opt_arg()); break; case OPT_VERIFY: s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE; verify_args.depth = atoi(opt_arg()); if (!s_quiet) BIO_printf(bio_err, "verify depth is %d\n", verify_args.depth); break; case OPT_UPPER_V_VERIFY: s_server_verify = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT | SSL_VERIFY_CLIENT_ONCE; verify_args.depth = atoi(opt_arg()); if (!s_quiet) BIO_printf(bio_err, "verify depth is %d, must return a certificate\n", verify_args.depth); break; case OPT_CONTEXT: context = (unsigned char *)opt_arg(); break; case OPT_CERT: s_cert_file = opt_arg(); break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto end; break; case OPT_CRL: crl_file = opt_arg(); break; case OPT_CRL_DOWNLOAD: crl_download = 1; break; case OPT_SERVERINFO: s_serverinfo_file = opt_arg(); break; case OPT_CERTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_cert_format)) goto opthelp; break; case OPT_KEY: s_key_file = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_key_format)) goto opthelp; break; case OPT_PASS: passarg = opt_arg(); break; case OPT_CERT_CHAIN: s_chain_file = opt_arg(); break; case OPT_DHPARAM: dhfile = opt_arg(); break; case OPT_DCERTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dcert_format)) goto opthelp; break; case OPT_DCERT: s_dcert_file = opt_arg(); break; case OPT_DKEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &s_dkey_format)) goto opthelp; break; case OPT_DPASS: dpassarg = opt_arg(); break; case OPT_DKEY: s_dkey_file = opt_arg(); break; case OPT_DCERT_CHAIN: s_dchain_file = opt_arg(); break; case OPT_NOCERT: nocert = 1; break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_CHAINCAPATH: chCApath = opt_arg(); break; case OPT_VERIFYCAPATH: vfyCApath = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_CHAINCASTORE: chCAstore = opt_arg(); break; case OPT_VERIFYCASTORE: vfyCAstore = opt_arg(); break; case OPT_NO_CACHE: no_cache = 1; break; case OPT_EXT_CACHE: ext_cache = 1; break; case OPT_CRLFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &crl_format)) goto opthelp; break; case OPT_S_CASES: case OPT_S_NUM_TICKETS: case OPT_ANTI_REPLAY: case OPT_NO_ANTI_REPLAY: if (ssl_args == NULL) ssl_args = sk_OPENSSL_STRING_new_null(); if (ssl_args == NULL || !sk_OPENSSL_STRING_push(ssl_args, opt_flag()) || !sk_OPENSSL_STRING_push(ssl_args, opt_arg())) { BIO_printf(bio_err, "%s: Memory allocation failure\n", prog); goto end; } break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_X_CASES: if (!args_excert(o, &exc)) goto end; break; case OPT_VERIFY_RET_ERROR: verify_args.return_error = 1; break; case OPT_VERIFY_QUIET: verify_args.quiet = 1; break; case OPT_BUILD_CHAIN: build_chain = 1; break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_CHAINCAFILE: chCAfile = opt_arg(); break; case OPT_VERIFYCAFILE: vfyCAfile = opt_arg(); break; case OPT_NBIO: s_nbio = 1; break; case OPT_NBIO_TEST: s_nbio = s_nbio_test = 1; break; case OPT_IGN_EOF: s_ign_eof = 1; break; case OPT_NO_IGN_EOF: s_ign_eof = 0; break; case OPT_DEBUG: s_debug = 1; break; case OPT_TLSEXTDEBUG: s_tlsextdebug = 1; break; case OPT_STATUS: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; #endif break; case OPT_STATUS_VERBOSE: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = tlscstatp.verbose = 1; #endif break; case OPT_STATUS_TIMEOUT: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; tlscstatp.timeout = atoi(opt_arg()); #endif break; case OPT_PROXY: #ifndef OPENSSL_NO_OCSP tlscstatp.proxy = opt_arg(); #endif break; case OPT_NO_PROXY: #ifndef OPENSSL_NO_OCSP tlscstatp.no_proxy = opt_arg(); #endif break; case OPT_STATUS_URL: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; if (!OSSL_HTTP_parse_url(opt_arg(), &tlscstatp.use_ssl, NULL, &tlscstatp.host, &tlscstatp.port, NULL, &tlscstatp.path, NULL, NULL)) { BIO_printf(bio_err, "Error parsing -status_url argument\n"); goto end; } #endif break; case OPT_STATUS_FILE: #ifndef OPENSSL_NO_OCSP s_tlsextstatus = 1; tlscstatp.respin = opt_arg(); #endif break; case OPT_MSG: s_msg = 1; break; case OPT_MSGFILE: bio_s_msg = BIO_new_file(opt_arg(), "w"); if (bio_s_msg == NULL) { BIO_printf(bio_err, "Error writing file %s\n", opt_arg()); goto end; } break; case OPT_TRACE: #ifndef OPENSSL_NO_SSL_TRACE s_msg = 2; #endif break; case OPT_SECURITY_DEBUG: sdebug = 1; break; case OPT_SECURITY_DEBUG_VERBOSE: sdebug = 2; break; case OPT_STATE: state = 1; break; case OPT_CRLF: s_crlf = 1; break; case OPT_QUIET: s_quiet = 1; break; case OPT_BRIEF: s_quiet = s_brief = verify_args.quiet = 1; break; case OPT_NO_DHE: no_dhe = 1; break; case OPT_NO_RESUME_EPHEMERAL: no_resume_ephemeral = 1; break; case OPT_PSK_IDENTITY: psk_identity = opt_arg(); break; case OPT_PSK_HINT: #ifndef OPENSSL_NO_PSK psk_identity_hint = opt_arg(); #endif break; case OPT_PSK: for (p = psk_key = opt_arg(); *p; p++) { if (isxdigit(_UC(*p))) continue; BIO_printf(bio_err, "Not a hex number '%s'\n", psk_key); goto end; } break; case OPT_PSK_SESS: psksessf = opt_arg(); break; case OPT_SRPVFILE: #ifndef OPENSSL_NO_SRP srp_verifier_file = opt_arg(); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; #endif break; case OPT_SRPUSERSEED: #ifndef OPENSSL_NO_SRP srpuserseed = opt_arg(); if (min_version < TLS1_VERSION) min_version = TLS1_VERSION; #endif break; case OPT_REV: rev = 1; break; case OPT_WWW: www = 1; break; case OPT_UPPER_WWW: www = 2; break; case OPT_HTTP: www = 3; break; case OPT_SSL_CONFIG: ssl_config = opt_arg(); break; case OPT_SSL3: min_version = SSL3_VERSION; max_version = SSL3_VERSION; break; case OPT_TLS1_3: min_version = TLS1_3_VERSION; max_version = TLS1_3_VERSION; break; case OPT_TLS1_2: min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; break; case OPT_TLS1_1: min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; break; case OPT_TLS1: min_version = TLS1_VERSION; max_version = TLS1_VERSION; break; case OPT_DTLS: #ifndef OPENSSL_NO_DTLS meth = DTLS_server_method(); socket_type = SOCK_DGRAM; #endif break; case OPT_DTLS1: #ifndef OPENSSL_NO_DTLS meth = DTLS_server_method(); min_version = DTLS1_VERSION; max_version = DTLS1_VERSION; socket_type = SOCK_DGRAM; #endif break; case OPT_DTLS1_2: #ifndef OPENSSL_NO_DTLS meth = DTLS_server_method(); min_version = DTLS1_2_VERSION; max_version = DTLS1_2_VERSION; socket_type = SOCK_DGRAM; #endif break; case OPT_SCTP: #ifndef OPENSSL_NO_SCTP protocol = IPPROTO_SCTP; #endif break; case OPT_SCTP_LABEL_BUG: #ifndef OPENSSL_NO_SCTP sctp_label_bug = 1; #endif break; case OPT_TIMEOUT: #ifndef OPENSSL_NO_DTLS enable_timeouts = 1; #endif break; case OPT_MTU: #ifndef OPENSSL_NO_DTLS socket_mtu = atol(opt_arg()); #endif break; case OPT_LISTEN: #ifndef OPENSSL_NO_DTLS dtlslisten = 1; #endif break; case OPT_STATELESS: stateless = 1; break; case OPT_ID_PREFIX: session_id_prefix = opt_arg(); break; case OPT_ENGINE: #ifndef OPENSSL_NO_ENGINE engine = setup_engine(opt_arg(), s_debug); #endif break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_SERVERNAME: tlsextcbp.servername = opt_arg(); break; case OPT_SERVERNAME_FATAL: tlsextcbp.extension_error = SSL_TLSEXT_ERR_ALERT_FATAL; break; case OPT_CERT2: s_cert_file2 = opt_arg(); break; case OPT_KEY2: s_key_file2 = opt_arg(); break; case OPT_NEXTPROTONEG: # ifndef OPENSSL_NO_NEXTPROTONEG next_proto_neg_in = opt_arg(); #endif break; case OPT_ALPN: alpn_in = opt_arg(); break; case OPT_SRTP_PROFILES: #ifndef OPENSSL_NO_SRTP srtp_profiles = opt_arg(); #endif break; case OPT_KEYMATEXPORT: keymatexportlabel = opt_arg(); break; case OPT_KEYMATEXPORTLEN: keymatexportlen = atoi(opt_arg()); break; case OPT_ASYNC: async = 1; break; case OPT_MAX_SEND_FRAG: max_send_fragment = atoi(opt_arg()); break; case OPT_SPLIT_SEND_FRAG: split_send_fragment = atoi(opt_arg()); break; case OPT_MAX_PIPELINES: max_pipelines = atoi(opt_arg()); break; case OPT_READ_BUF: read_buf_len = atoi(opt_arg()); break; case OPT_KEYLOG_FILE: keylog_file = opt_arg(); break; case OPT_MAX_EARLY: max_early_data = atoi(opt_arg()); if (max_early_data < 0) { BIO_printf(bio_err, "Invalid value for max_early_data\n"); goto end; } break; case OPT_RECV_MAX_EARLY: recv_max_early_data = atoi(opt_arg()); if (recv_max_early_data < 0) { BIO_printf(bio_err, "Invalid value for recv_max_early_data\n"); goto end; } break; case OPT_EARLY_DATA: early_data = 1; if (max_early_data == -1) max_early_data = SSL3_RT_MAX_PLAIN_LENGTH; break; case OPT_HTTP_SERVER_BINMODE: http_server_binmode = 1; break; case OPT_NOCANAMES: no_ca_names = 1; break; case OPT_KTLS: #ifndef OPENSSL_NO_KTLS enable_ktls = 1; #endif break; case OPT_SENDFILE: #ifndef OPENSSL_NO_KTLS use_sendfile = 1; #endif break; case OPT_USE_ZC_SENDFILE: #ifndef OPENSSL_NO_KTLS use_zc_sendfile = 1; #endif break; case OPT_IGNORE_UNEXPECTED_EOF: ignore_unexpected_eof = 1; break; case OPT_TFO: tfo = 1; break; case OPT_CERT_COMP: cert_comp = 1; break; case OPT_ENABLE_SERVER_RPK: enable_server_rpk = 1; break; case OPT_ENABLE_CLIENT_RPK: enable_client_rpk = 1; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_RAND_load()) goto end; #ifndef OPENSSL_NO_NEXTPROTONEG if (min_version == TLS1_3_VERSION && next_proto_neg_in != NULL) { BIO_printf(bio_err, "Cannot supply -nextprotoneg with TLSv1.3\n"); goto opthelp; } #endif #ifndef OPENSSL_NO_DTLS if (www && socket_type == SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -HTTP, -www or -WWW with DTLS\n"); goto end; } if (dtlslisten && socket_type != SOCK_DGRAM) { BIO_printf(bio_err, "Can only use -listen with DTLS\n"); goto end; } if (rev && socket_type == SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -rev with DTLS\n"); goto end; } #endif if (tfo && socket_type != SOCK_STREAM) { BIO_printf(bio_err, "Can only use -tfo with TLS\n"); goto end; } if (stateless && socket_type != SOCK_STREAM) { BIO_printf(bio_err, "Can only use --stateless with TLS\n"); goto end; } #ifdef AF_UNIX if (socket_family == AF_UNIX && socket_type != SOCK_STREAM) { BIO_printf(bio_err, "Can't use unix sockets and datagrams together\n"); goto end; } #endif if (early_data && (www > 0 || rev)) { BIO_printf(bio_err, "Can't use -early_data in combination with -www, -WWW, -HTTP, or -rev\n"); goto end; } #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP) { if (socket_type != SOCK_DGRAM) { BIO_printf(bio_err, "Can't use -sctp without DTLS\n"); goto end; } socket_type = SOCK_STREAM; } #endif #ifndef OPENSSL_NO_KTLS if (use_zc_sendfile && !use_sendfile) { BIO_printf(bio_out, "Warning: -zerocopy_sendfile depends on -sendfile, enabling -sendfile now.\n"); use_sendfile = 1; } if (use_sendfile && enable_ktls == 0) { BIO_printf(bio_out, "Warning: -sendfile depends on -ktls, enabling -ktls now.\n"); enable_ktls = 1; } if (use_sendfile && www <= 1) { BIO_printf(bio_err, "Can't use -sendfile without -WWW or -HTTP\n"); goto end; } #endif if (!app_passwd(passarg, dpassarg, &pass, &dpass)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (s_key_file == NULL) s_key_file = s_cert_file; if (s_key_file2 == NULL) s_key_file2 = s_cert_file2; if (!load_excert(&exc)) goto end; if (nocert == 0) { s_key = load_key(s_key_file, s_key_format, 0, pass, engine, "server certificate private key"); if (s_key == NULL) goto end; s_cert = load_cert_pass(s_cert_file, s_cert_format, 1, pass, "server certificate"); if (s_cert == NULL) goto end; if (s_chain_file != NULL) { if (!load_certs(s_chain_file, 0, &s_chain, NULL, "server certificate chain")) goto end; } if (tlsextcbp.servername != NULL) { s_key2 = load_key(s_key_file2, s_key_format, 0, pass, engine, "second server certificate private key"); if (s_key2 == NULL) goto end; s_cert2 = load_cert_pass(s_cert_file2, s_cert_format, 1, pass, "second server certificate"); if (s_cert2 == NULL) goto end; } } #if !defined(OPENSSL_NO_NEXTPROTONEG) if (next_proto_neg_in) { next_proto.data = next_protos_parse(&next_proto.len, next_proto_neg_in); if (next_proto.data == NULL) goto end; } #endif alpn_ctx.data = NULL; if (alpn_in) { alpn_ctx.data = next_protos_parse(&alpn_ctx.len, alpn_in); if (alpn_ctx.data == NULL) goto end; } if (crl_file != NULL) { X509_CRL *crl; crl = load_crl(crl_file, crl_format, 0, "CRL"); if (crl == NULL) goto end; crls = sk_X509_CRL_new_null(); if (crls == NULL || !sk_X509_CRL_push(crls, crl)) { BIO_puts(bio_err, "Error adding CRL\n"); ERR_print_errors(bio_err); X509_CRL_free(crl); goto end; } } if (s_dcert_file != NULL) { if (s_dkey_file == NULL) s_dkey_file = s_dcert_file; s_dkey = load_key(s_dkey_file, s_dkey_format, 0, dpass, engine, "second certificate private key"); if (s_dkey == NULL) goto end; s_dcert = load_cert_pass(s_dcert_file, s_dcert_format, 1, dpass, "second server certificate"); if (s_dcert == NULL) { ERR_print_errors(bio_err); goto end; } if (s_dchain_file != NULL) { if (!load_certs(s_dchain_file, 0, &s_dchain, NULL, "second server certificate chain")) goto end; } } if (bio_s_out == NULL) { if (s_quiet && !s_debug) { bio_s_out = BIO_new(BIO_s_null()); if (s_msg && bio_s_msg == NULL) { bio_s_msg = dup_bio_out(FORMAT_TEXT); if (bio_s_msg == NULL) { BIO_printf(bio_err, "Out of memory\n"); goto end; } } } else { bio_s_out = dup_bio_out(FORMAT_TEXT); } } if (bio_s_out == NULL) goto end; if (nocert) { s_cert_file = NULL; s_key_file = NULL; s_dcert_file = NULL; s_dkey_file = NULL; s_cert_file2 = NULL; s_key_file2 = NULL; } ctx = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth); if (ctx == NULL) { ERR_print_errors(bio_err); goto end; } SSL_CTX_clear_mode(ctx, SSL_MODE_AUTO_RETRY); if (sdebug) ssl_ctx_security_debug(ctx, sdebug); if (!config_ctx(cctx, ssl_args, ctx)) goto end; if (ssl_config) { if (SSL_CTX_config(ctx, ssl_config) == 0) { BIO_printf(bio_err, "Error using configuration \"%s\"\n", ssl_config); ERR_print_errors(bio_err); goto end; } } #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP && sctp_label_bug == 1) SSL_CTX_set_mode(ctx, SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG); #endif if (min_version != 0 && SSL_CTX_set_min_proto_version(ctx, min_version) == 0) goto end; if (max_version != 0 && SSL_CTX_set_max_proto_version(ctx, max_version) == 0) goto end; if (session_id_prefix) { if (strlen(session_id_prefix) >= 32) BIO_printf(bio_err, "warning: id_prefix is too long, only one new session will be possible\n"); if (!SSL_CTX_set_generate_session_id(ctx, generate_session_id)) { BIO_printf(bio_err, "error setting 'id_prefix'\n"); ERR_print_errors(bio_err); goto end; } BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix); } if (exc != NULL) ssl_ctx_set_excert(ctx, exc); if (state) SSL_CTX_set_info_callback(ctx, apps_ssl_info_callback); if (no_cache) SSL_CTX_set_session_cache_mode(ctx, SSL_SESS_CACHE_OFF); else if (ext_cache) init_session_cache_ctx(ctx); else SSL_CTX_sess_set_cache_size(ctx, 128); if (async) { SSL_CTX_set_mode(ctx, SSL_MODE_ASYNC); } if (no_ca_names) { SSL_CTX_set_options(ctx, SSL_OP_DISABLE_TLSEXT_CA_NAMES); } if (ignore_unexpected_eof) SSL_CTX_set_options(ctx, SSL_OP_IGNORE_UNEXPECTED_EOF); #ifndef OPENSSL_NO_KTLS if (enable_ktls) SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS); if (use_zc_sendfile) SSL_CTX_set_options(ctx, SSL_OP_ENABLE_KTLS_TX_ZEROCOPY_SENDFILE); #endif if (max_send_fragment > 0 && !SSL_CTX_set_max_send_fragment(ctx, max_send_fragment)) { BIO_printf(bio_err, "%s: Max send fragment size %u is out of permitted range\n", prog, max_send_fragment); goto end; } if (split_send_fragment > 0 && !SSL_CTX_set_split_send_fragment(ctx, split_send_fragment)) { BIO_printf(bio_err, "%s: Split send fragment size %u is out of permitted range\n", prog, split_send_fragment); goto end; } if (max_pipelines > 0 && !SSL_CTX_set_max_pipelines(ctx, max_pipelines)) { BIO_printf(bio_err, "%s: Max pipelines %u is out of permitted range\n", prog, max_pipelines); goto end; } if (read_buf_len > 0) { SSL_CTX_set_default_read_buffer_len(ctx, read_buf_len); } #ifndef OPENSSL_NO_SRTP if (srtp_profiles != NULL) { if (SSL_CTX_set_tlsext_use_srtp(ctx, srtp_profiles) != 0) { BIO_printf(bio_err, "Error setting SRTP profile\n"); ERR_print_errors(bio_err); goto end; } } #endif if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) { ERR_print_errors(bio_err); goto end; } if (vpmtouched && !SSL_CTX_set1_param(ctx, vpm)) { BIO_printf(bio_err, "Error setting verify params\n"); ERR_print_errors(bio_err); goto end; } ssl_ctx_add_crls(ctx, crls, 0); if (!ssl_load_stores(ctx, vfyCApath, vfyCAfile, vfyCAstore, chCApath, chCAfile, chCAstore, crls, crl_download)) { BIO_printf(bio_err, "Error loading store locations\n"); ERR_print_errors(bio_err); goto end; } if (s_cert2) { ctx2 = SSL_CTX_new_ex(app_get0_libctx(), app_get0_propq(), meth); if (ctx2 == NULL) { ERR_print_errors(bio_err); goto end; } } if (ctx2 != NULL) { BIO_printf(bio_s_out, "Setting secondary ctx parameters\n"); if (sdebug) ssl_ctx_security_debug(ctx2, sdebug); if (session_id_prefix) { if (strlen(session_id_prefix) >= 32) BIO_printf(bio_err, "warning: id_prefix is too long, only one new session will be possible\n"); if (!SSL_CTX_set_generate_session_id(ctx2, generate_session_id)) { BIO_printf(bio_err, "error setting 'id_prefix'\n"); ERR_print_errors(bio_err); goto end; } BIO_printf(bio_err, "id_prefix '%s' set.\n", session_id_prefix); } if (exc != NULL) ssl_ctx_set_excert(ctx2, exc); if (state) SSL_CTX_set_info_callback(ctx2, apps_ssl_info_callback); if (no_cache) SSL_CTX_set_session_cache_mode(ctx2, SSL_SESS_CACHE_OFF); else if (ext_cache) init_session_cache_ctx(ctx2); else SSL_CTX_sess_set_cache_size(ctx2, 128); if (async) SSL_CTX_set_mode(ctx2, SSL_MODE_ASYNC); if (!ctx_set_verify_locations(ctx2, CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) { ERR_print_errors(bio_err); goto end; } if (vpmtouched && !SSL_CTX_set1_param(ctx2, vpm)) { BIO_printf(bio_err, "Error setting verify params\n"); ERR_print_errors(bio_err); goto end; } ssl_ctx_add_crls(ctx2, crls, 0); if (!config_ctx(cctx, ssl_args, ctx2)) goto end; } #ifndef OPENSSL_NO_NEXTPROTONEG if (next_proto.data) SSL_CTX_set_next_protos_advertised_cb(ctx, next_proto_cb, &next_proto); #endif if (alpn_ctx.data) SSL_CTX_set_alpn_select_cb(ctx, alpn_cb, &alpn_ctx); if (!no_dhe) { EVP_PKEY *dhpkey = NULL; if (dhfile != NULL) dhpkey = load_keyparams(dhfile, FORMAT_UNDEF, 0, "DH", "DH parameters"); else if (s_cert_file != NULL) dhpkey = load_keyparams_suppress(s_cert_file, FORMAT_UNDEF, 0, "DH", "DH parameters", 1); if (dhpkey != NULL) { BIO_printf(bio_s_out, "Setting temp DH parameters\n"); } else { BIO_printf(bio_s_out, "Using default temp DH parameters\n"); } (void)BIO_flush(bio_s_out); if (dhpkey == NULL) { SSL_CTX_set_dh_auto(ctx, 1); } else { if (!EVP_PKEY_up_ref(dhpkey)) { EVP_PKEY_free(dhpkey); goto end; } if (!SSL_CTX_set0_tmp_dh_pkey(ctx, dhpkey)) { BIO_puts(bio_err, "Error setting temp DH parameters\n"); ERR_print_errors(bio_err); EVP_PKEY_free(dhpkey); EVP_PKEY_free(dhpkey); goto end; } } if (ctx2 != NULL) { if (dhfile != NULL) { EVP_PKEY *dhpkey2 = load_keyparams_suppress(s_cert_file2, FORMAT_UNDEF, 0, "DH", "DH parameters", 1); if (dhpkey2 != NULL) { BIO_printf(bio_s_out, "Setting temp DH parameters\n"); (void)BIO_flush(bio_s_out); EVP_PKEY_free(dhpkey); dhpkey = dhpkey2; } } if (dhpkey == NULL) { SSL_CTX_set_dh_auto(ctx2, 1); } else if (!SSL_CTX_set0_tmp_dh_pkey(ctx2, dhpkey)) { BIO_puts(bio_err, "Error setting temp DH parameters\n"); ERR_print_errors(bio_err); EVP_PKEY_free(dhpkey); goto end; } dhpkey = NULL; } EVP_PKEY_free(dhpkey); } if (!set_cert_key_stuff(ctx, s_cert, s_key, s_chain, build_chain)) goto end; if (s_serverinfo_file != NULL && !SSL_CTX_use_serverinfo_file(ctx, s_serverinfo_file)) { ERR_print_errors(bio_err); goto end; } if (ctx2 != NULL && !set_cert_key_stuff(ctx2, s_cert2, s_key2, NULL, build_chain)) goto end; if (s_dcert != NULL) { if (!set_cert_key_stuff(ctx, s_dcert, s_dkey, s_dchain, build_chain)) goto end; } if (no_resume_ephemeral) { SSL_CTX_set_not_resumable_session_callback(ctx, not_resumable_sess_cb); if (ctx2 != NULL) SSL_CTX_set_not_resumable_session_callback(ctx2, not_resumable_sess_cb); } #ifndef OPENSSL_NO_PSK if (psk_key != NULL) { if (s_debug) BIO_printf(bio_s_out, "PSK key given, setting server callback\n"); SSL_CTX_set_psk_server_callback(ctx, psk_server_cb); } if (psk_identity_hint != NULL) { if (min_version == TLS1_3_VERSION) { BIO_printf(bio_s_out, "PSK warning: there is NO identity hint in TLSv1.3\n"); } else { if (!SSL_CTX_use_psk_identity_hint(ctx, psk_identity_hint)) { BIO_printf(bio_err, "error setting PSK identity hint to context\n"); ERR_print_errors(bio_err); goto end; } } } #endif if (psksessf != NULL) { BIO *stmp = BIO_new_file(psksessf, "r"); if (stmp == NULL) { BIO_printf(bio_err, "Can't open PSK session file %s\n", psksessf); ERR_print_errors(bio_err); goto end; } psksess = PEM_read_bio_SSL_SESSION(stmp, NULL, 0, NULL); BIO_free(stmp); if (psksess == NULL) { BIO_printf(bio_err, "Can't read PSK session file %s\n", psksessf); ERR_print_errors(bio_err); goto end; } } if (psk_key != NULL || psksess != NULL) SSL_CTX_set_psk_find_session_callback(ctx, psk_find_session_cb); SSL_CTX_set_verify(ctx, s_server_verify, verify_callback); if (!SSL_CTX_set_session_id_context(ctx, (void *)&s_server_session_id_context, sizeof(s_server_session_id_context))) { BIO_printf(bio_err, "error setting session id context\n"); ERR_print_errors(bio_err); goto end; } SSL_CTX_set_cookie_generate_cb(ctx, generate_cookie_callback); SSL_CTX_set_cookie_verify_cb(ctx, verify_cookie_callback); SSL_CTX_set_stateless_cookie_generate_cb(ctx, generate_stateless_cookie_callback); SSL_CTX_set_stateless_cookie_verify_cb(ctx, verify_stateless_cookie_callback); if (ctx2 != NULL) { SSL_CTX_set_verify(ctx2, s_server_verify, verify_callback); if (!SSL_CTX_set_session_id_context(ctx2, (void *)&s_server_session_id_context, sizeof(s_server_session_id_context))) { BIO_printf(bio_err, "error setting session id context\n"); ERR_print_errors(bio_err); goto end; } tlsextcbp.biodebug = bio_s_out; SSL_CTX_set_tlsext_servername_callback(ctx2, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx2, &tlsextcbp); SSL_CTX_set_tlsext_servername_callback(ctx, ssl_servername_cb); SSL_CTX_set_tlsext_servername_arg(ctx, &tlsextcbp); } #ifndef OPENSSL_NO_SRP if (srp_verifier_file != NULL) { if (!set_up_srp_verifier_file(ctx, &srp_callback_parm, srpuserseed, srp_verifier_file)) goto end; } else #endif if (CAfile != NULL) { SSL_CTX_set_client_CA_list(ctx, SSL_load_client_CA_file(CAfile)); if (ctx2) SSL_CTX_set_client_CA_list(ctx2, SSL_load_client_CA_file(CAfile)); } #ifndef OPENSSL_NO_OCSP if (s_tlsextstatus) { SSL_CTX_set_tlsext_status_cb(ctx, cert_status_cb); SSL_CTX_set_tlsext_status_arg(ctx, &tlscstatp); if (ctx2) { SSL_CTX_set_tlsext_status_cb(ctx2, cert_status_cb); SSL_CTX_set_tlsext_status_arg(ctx2, &tlscstatp); } } #endif if (set_keylog_file(ctx, keylog_file)) goto end; if (max_early_data >= 0) SSL_CTX_set_max_early_data(ctx, max_early_data); if (recv_max_early_data >= 0) SSL_CTX_set_recv_max_early_data(ctx, recv_max_early_data); if (cert_comp) { BIO_printf(bio_s_out, "Compressing certificates\n"); if (!SSL_CTX_compress_certs(ctx, 0)) BIO_printf(bio_s_out, "Error compressing certs on ctx\n"); if (ctx2 != NULL && !SSL_CTX_compress_certs(ctx2, 0)) BIO_printf(bio_s_out, "Error compressing certs on ctx2\n"); } if (enable_server_rpk) if (!SSL_CTX_set1_server_cert_type(ctx, cert_type_rpk, sizeof(cert_type_rpk))) { BIO_printf(bio_s_out, "Error setting server certificate types\n"); goto end; } if (enable_client_rpk) if (!SSL_CTX_set1_client_cert_type(ctx, cert_type_rpk, sizeof(cert_type_rpk))) { BIO_printf(bio_s_out, "Error setting server certificate types\n"); goto end; } if (rev) server_cb = rev_body; else if (www) server_cb = www_body; else server_cb = sv_body; #ifdef AF_UNIX if (socket_family == AF_UNIX && unlink_unix_path) unlink(host); #endif if (tfo) BIO_printf(bio_s_out, "Listening for TFO\n"); do_server(&accept_socket, host, port, socket_family, socket_type, protocol, server_cb, context, naccept, bio_s_out, tfo); print_stats(bio_s_out, ctx); ret = 0; end: SSL_CTX_free(ctx); SSL_SESSION_free(psksess); set_keylog_file(NULL, NULL); X509_free(s_cert); sk_X509_CRL_pop_free(crls, X509_CRL_free); X509_free(s_dcert); EVP_PKEY_free(s_key); EVP_PKEY_free(s_dkey); OSSL_STACK_OF_X509_free(s_chain); OSSL_STACK_OF_X509_free(s_dchain); OPENSSL_free(pass); OPENSSL_free(dpass); OPENSSL_free(host); OPENSSL_free(port); X509_VERIFY_PARAM_free(vpm); free_sessions(); OPENSSL_free(tlscstatp.host); OPENSSL_free(tlscstatp.port); OPENSSL_free(tlscstatp.path); SSL_CTX_free(ctx2); X509_free(s_cert2); EVP_PKEY_free(s_key2); #ifndef OPENSSL_NO_NEXTPROTONEG OPENSSL_free(next_proto.data); #endif OPENSSL_free(alpn_ctx.data); ssl_excert_free(exc); sk_OPENSSL_STRING_free(ssl_args); SSL_CONF_CTX_free(cctx); release_engine(engine); BIO_free(bio_s_out); bio_s_out = NULL; BIO_free(bio_s_msg); bio_s_msg = NULL; #ifdef CHARSET_EBCDIC BIO_meth_free(methods_ebcdic); #endif return ret; } static void print_stats(BIO *bio, SSL_CTX *ssl_ctx) { BIO_printf(bio, "%4ld items in the session cache\n", SSL_CTX_sess_number(ssl_ctx)); BIO_printf(bio, "%4ld client connects (SSL_connect())\n", SSL_CTX_sess_connect(ssl_ctx)); BIO_printf(bio, "%4ld client renegotiates (SSL_connect())\n", SSL_CTX_sess_connect_renegotiate(ssl_ctx)); BIO_printf(bio, "%4ld client connects that finished\n", SSL_CTX_sess_connect_good(ssl_ctx)); BIO_printf(bio, "%4ld server accepts (SSL_accept())\n", SSL_CTX_sess_accept(ssl_ctx)); BIO_printf(bio, "%4ld server renegotiates (SSL_accept())\n", SSL_CTX_sess_accept_renegotiate(ssl_ctx)); BIO_printf(bio, "%4ld server accepts that finished\n", SSL_CTX_sess_accept_good(ssl_ctx)); BIO_printf(bio, "%4ld session cache hits\n", SSL_CTX_sess_hits(ssl_ctx)); BIO_printf(bio, "%4ld session cache misses\n", SSL_CTX_sess_misses(ssl_ctx)); BIO_printf(bio, "%4ld session cache timeouts\n", SSL_CTX_sess_timeouts(ssl_ctx)); BIO_printf(bio, "%4ld callback cache hits\n", SSL_CTX_sess_cb_hits(ssl_ctx)); BIO_printf(bio, "%4ld cache full overflows (%ld allowed)\n", SSL_CTX_sess_cache_full(ssl_ctx), SSL_CTX_sess_get_cache_size(ssl_ctx)); } static long int count_reads_callback(BIO *bio, int cmd, const char *argp, size_t len, int argi, long argl, int ret, size_t *processed) { unsigned int *p_counter = (unsigned int *)BIO_get_callback_arg(bio); switch (cmd) { case BIO_CB_READ: case BIO_CB_GETS: if (p_counter != NULL) ++*p_counter; break; default: break; } if (s_debug) { BIO_set_callback_arg(bio, (char *)bio_s_out); ret = (int)bio_dump_callback(bio, cmd, argp, len, argi, argl, ret, processed); BIO_set_callback_arg(bio, (char *)p_counter); } return ret; } static int sv_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL; fd_set readfds; int ret = 1, width; int k; unsigned long l; SSL *con = NULL; BIO *sbio; struct timeval timeout; #if !(defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)) struct timeval *timeoutp; #endif #ifndef OPENSSL_NO_DTLS # ifndef OPENSSL_NO_SCTP int isdtls = (stype == SOCK_DGRAM || prot == IPPROTO_SCTP); # else int isdtls = (stype == SOCK_DGRAM); # endif #endif buf = app_malloc(bufsize, "server buffer"); if (s_nbio) { if (!BIO_socket_nbio(s, 1)) ERR_print_errors(bio_err); else if (!s_quiet) BIO_printf(bio_err, "Turned on non blocking io\n"); } con = SSL_new(ctx); if (con == NULL) { ret = -1; goto err; } if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { BIO_printf(bio_err, "Error setting session id context\n"); ret = -1; goto err; } if (!SSL_clear(con)) { BIO_printf(bio_err, "Error clearing SSL connection\n"); ret = -1; goto err; } #ifndef OPENSSL_NO_DTLS if (isdtls) { # ifndef OPENSSL_NO_SCTP if (prot == IPPROTO_SCTP) sbio = BIO_new_dgram_sctp(s, BIO_NOCLOSE); else # endif sbio = BIO_new_dgram(s, BIO_NOCLOSE); if (sbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); ERR_print_errors(bio_err); goto err; } if (enable_timeouts) { timeout.tv_sec = 0; timeout.tv_usec = DGRAM_RCV_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_RECV_TIMEOUT, 0, &timeout); timeout.tv_sec = 0; timeout.tv_usec = DGRAM_SND_TIMEOUT; BIO_ctrl(sbio, BIO_CTRL_DGRAM_SET_SEND_TIMEOUT, 0, &timeout); } if (socket_mtu) { if (socket_mtu < DTLS_get_link_min_mtu(con)) { BIO_printf(bio_err, "MTU too small. Must be at least %ld\n", DTLS_get_link_min_mtu(con)); ret = -1; BIO_free(sbio); goto err; } SSL_set_options(con, SSL_OP_NO_QUERY_MTU); if (!DTLS_set_link_mtu(con, socket_mtu)) { BIO_printf(bio_err, "Failed to set MTU\n"); ret = -1; BIO_free(sbio); goto err; } } else BIO_ctrl(sbio, BIO_CTRL_DGRAM_MTU_DISCOVER, 0, NULL); # ifndef OPENSSL_NO_SCTP if (prot != IPPROTO_SCTP) # endif SSL_set_options(con, SSL_OP_COOKIE_EXCHANGE); } else #endif sbio = BIO_new_socket(s, BIO_NOCLOSE); if (sbio == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); ERR_print_errors(bio_err); goto err; } if (s_nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); if (test == NULL) { BIO_printf(bio_err, "Unable to create BIO\n"); ret = -1; BIO_free(sbio); goto err; } sbio = BIO_push(test, sbio); } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); BIO_set_callback_ex(SSL_get_rbio(con), count_reads_callback); if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out); } if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (early_data) { int write_header = 1, edret = SSL_READ_EARLY_DATA_ERROR; size_t readbytes; while (edret != SSL_READ_EARLY_DATA_FINISH) { for (;;) { edret = SSL_read_early_data(con, buf, bufsize, &readbytes); if (edret != SSL_READ_EARLY_DATA_ERROR) break; switch (SSL_get_error(con, 0)) { case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_ASYNC: case SSL_ERROR_WANT_READ: continue; default: BIO_printf(bio_err, "Error reading early data\n"); ERR_print_errors(bio_err); goto err; } } if (readbytes > 0) { if (write_header) { BIO_printf(bio_s_out, "Early data received:\n"); write_header = 0; } raw_write_stdout(buf, (unsigned int)readbytes); (void)BIO_flush(bio_s_out); } } if (write_header) { if (SSL_get_early_data_status(con) == SSL_EARLY_DATA_NOT_SENT) BIO_printf(bio_s_out, "No early data received\n"); else BIO_printf(bio_s_out, "Early data was rejected\n"); } else { BIO_printf(bio_s_out, "\nEnd of early data\n"); } if (SSL_is_init_finished(con)) print_connection_info(con); } if (fileno_stdin() > s) width = fileno_stdin() + 1; else width = s + 1; for (;;) { int i; int read_from_terminal; int read_from_sslcon; read_from_terminal = 0; read_from_sslcon = SSL_has_pending(con) || (async && SSL_waiting_for_async(con)); if (!read_from_sslcon) { FD_ZERO(&readfds); #if !defined(OPENSSL_SYS_WINDOWS) && !defined(OPENSSL_SYS_MSDOS) openssl_fdset(fileno_stdin(), &readfds); #endif openssl_fdset(s, &readfds); #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) timeout.tv_sec = 1; timeout.tv_usec = 0; i = select(width, (void *)&readfds, NULL, NULL, &timeout); if (has_stdin_waiting()) read_from_terminal = 1; if ((i < 0) || (!i && !read_from_terminal)) continue; #else if (SSL_is_dtls(con) && DTLSv1_get_timeout(con, &timeout)) timeoutp = &timeout; else timeoutp = NULL; i = select(width, (void *)&readfds, NULL, NULL, timeoutp); if ((SSL_is_dtls(con)) && DTLSv1_handle_timeout(con) > 0) BIO_printf(bio_err, "TIMEOUT occurred\n"); if (i <= 0) continue; if (FD_ISSET(fileno_stdin(), &readfds)) read_from_terminal = 1; #endif if (FD_ISSET(s, &readfds)) read_from_sslcon = 1; } if (read_from_terminal) { if (s_crlf) { int j, lf_num; i = raw_read_stdin(buf, bufsize / 2); lf_num = 0; for (j = 0; j < i; j++) if (buf[j] == '\n') lf_num++; for (j = i - 1; j >= 0; j--) { buf[j + lf_num] = buf[j]; if (buf[j] == '\n') { lf_num--; i++; buf[j + lf_num] = '\r'; } } assert(lf_num == 0); } else { i = raw_read_stdin(buf, bufsize); } if (!s_quiet && !s_brief) { if ((i <= 0) || (buf[0] == 'Q')) { BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); BIO_closesocket(s); close_accept_socket(); ret = -11; goto err; } if ((i <= 0) || (buf[0] == 'q')) { BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); if (SSL_version(con) != DTLS1_VERSION) BIO_closesocket(s); goto err; } if ((buf[0] == 'r') && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_renegotiate(con); i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); continue; } if ((buf[0] == 'R') && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_set_verify(con, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL); SSL_renegotiate(con); i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); continue; } if ((buf[0] == 'K' || buf[0] == 'k') && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_key_update(con, buf[0] == 'K' ? SSL_KEY_UPDATE_REQUESTED : SSL_KEY_UPDATE_NOT_REQUESTED); i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); continue; } if (buf[0] == 'c' && ((buf[1] == '\n') || (buf[1] == '\r'))) { SSL_set_verify(con, SSL_VERIFY_PEER, NULL); i = SSL_verify_client_post_handshake(con); if (i == 0) { printf("Failed to initiate request\n"); ERR_print_errors(bio_err); } else { i = SSL_do_handshake(con); printf("SSL_do_handshake -> %d\n", i); } continue; } if (buf[0] == 'P') { static const char str[] = "Lets print some clear text\n"; BIO_write(SSL_get_wbio(con), str, sizeof(str) -1); } if (buf[0] == 'S') { print_stats(bio_s_out, SSL_get_SSL_CTX(con)); } } #ifdef CHARSET_EBCDIC ebcdic2ascii(buf, buf, i); #endif l = k = 0; for (;;) { #ifdef RENEG static count = 0; if (++count == 100) { count = 0; SSL_renegotiate(con); } #endif k = SSL_write(con, &(buf[l]), (unsigned int)i); #ifndef OPENSSL_NO_SRP while (SSL_get_error(con, k) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during write\n"); lookup_srp_user(&srp_callback_parm, bio_s_out); k = SSL_write(con, &(buf[l]), (unsigned int)i); } #endif switch (SSL_get_error(con, k)) { case SSL_ERROR_NONE: break; case SSL_ERROR_WANT_ASYNC: BIO_printf(bio_s_out, "Write BLOCK (Async)\n"); (void)BIO_flush(bio_s_out); wait_for_async(con); break; case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_X509_LOOKUP: BIO_printf(bio_s_out, "Write BLOCK\n"); (void)BIO_flush(bio_s_out); break; case SSL_ERROR_WANT_ASYNC_JOB: case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: BIO_printf(bio_s_out, "ERROR\n"); (void)BIO_flush(bio_s_out); ERR_print_errors(bio_err); ret = 1; goto err; case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); ret = 1; goto err; } if (k > 0) { l += k; i -= k; } if (i <= 0) break; } } if (read_from_sslcon) { if ((!async || !SSL_waiting_for_async(con)) && !SSL_is_init_finished(con)) { unsigned int read_counter = 0; BIO_set_callback_arg(SSL_get_rbio(con), (char *)&read_counter); i = init_ssl_connection(con); BIO_set_callback_arg(SSL_get_rbio(con), NULL); if (i <= 0 && read_counter == 0) { ret = -1; goto err; } if (i < 0) { ret = 0; goto err; } else if (i == 0) { ret = 1; goto err; } } else { again: i = SSL_read(con, (char *)buf, bufsize); #ifndef OPENSSL_NO_SRP while (SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); lookup_srp_user(&srp_callback_parm, bio_s_out); i = SSL_read(con, (char *)buf, bufsize); } #endif switch (SSL_get_error(con, i)) { case SSL_ERROR_NONE: #ifdef CHARSET_EBCDIC ascii2ebcdic(buf, buf, i); #endif raw_write_stdout(buf, (unsigned int)i); (void)BIO_flush(bio_s_out); if (SSL_has_pending(con)) goto again; break; case SSL_ERROR_WANT_ASYNC: BIO_printf(bio_s_out, "Read BLOCK (Async)\n"); (void)BIO_flush(bio_s_out); wait_for_async(con); break; case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_READ: BIO_printf(bio_s_out, "Read BLOCK\n"); (void)BIO_flush(bio_s_out); break; case SSL_ERROR_WANT_ASYNC_JOB: case SSL_ERROR_SYSCALL: case SSL_ERROR_SSL: BIO_printf(bio_s_out, "ERROR\n"); (void)BIO_flush(bio_s_out); ERR_print_errors(bio_err); ret = 1; goto err; case SSL_ERROR_ZERO_RETURN: BIO_printf(bio_s_out, "DONE\n"); (void)BIO_flush(bio_s_out); ret = 1; goto err; } } } } err: if (con != NULL) { BIO_printf(bio_s_out, "shutting down SSL\n"); do_ssl_shutdown(con); SSL_free(con); } BIO_printf(bio_s_out, "CONNECTION CLOSED\n"); OPENSSL_clear_free(buf, bufsize); return ret; } static void close_accept_socket(void) { BIO_printf(bio_err, "shutdown accept socket\n"); if (accept_socket >= 0) { BIO_closesocket(accept_socket); } } static int is_retryable(SSL *con, int i) { int err = SSL_get_error(con, i); return (err != SSL_ERROR_SSL) && (err != SSL_ERROR_SYSCALL) && (err != SSL_ERROR_ZERO_RETURN); } static int init_ssl_connection(SSL *con) { int i; long verify_err; int retry = 0; if (dtlslisten || stateless) { BIO_ADDR *client = NULL; if (dtlslisten) { if ((client = BIO_ADDR_new()) == NULL) { BIO_printf(bio_err, "ERROR - memory\n"); return 0; } i = DTLSv1_listen(con, client); } else { i = SSL_stateless(con); } if (i > 0) { BIO *wbio; int fd = -1; if (dtlslisten) { wbio = SSL_get_wbio(con); if (wbio) { BIO_get_fd(wbio, &fd); } if (!wbio || BIO_connect(fd, client, 0) == 0) { BIO_printf(bio_err, "ERROR - unable to connect\n"); BIO_ADDR_free(client); return 0; } (void)BIO_ctrl_set_connected(wbio, client); BIO_ADDR_free(client); dtlslisten = 0; } else { stateless = 0; } i = SSL_accept(con); } else { BIO_ADDR_free(client); } } else { do { i = SSL_accept(con); if (i <= 0) retry = is_retryable(con, i); #ifdef CERT_CB_TEST_RETRY { while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP && SSL_get_state(con) == TLS_ST_SR_CLNT_HELLO) { BIO_printf(bio_err, "LOOKUP from certificate callback during accept\n"); i = SSL_accept(con); if (i <= 0) retry = is_retryable(con, i); } } #endif #ifndef OPENSSL_NO_SRP while (i <= 0 && SSL_get_error(con, i) == SSL_ERROR_WANT_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP during accept %s\n", srp_callback_parm.login); lookup_srp_user(&srp_callback_parm, bio_s_out); i = SSL_accept(con); if (i <= 0) retry = is_retryable(con, i); } #endif } while (i < 0 && SSL_waiting_for_async(con)); } if (i <= 0) { if (((dtlslisten || stateless) && i == 0) || (!dtlslisten && !stateless && retry)) { BIO_printf(bio_s_out, "DELAY\n"); return 1; } BIO_printf(bio_err, "ERROR\n"); verify_err = SSL_get_verify_result(con); if (verify_err != X509_V_OK) { BIO_printf(bio_err, "verify error:%s\n", X509_verify_cert_error_string(verify_err)); } ERR_print_errors(bio_err); return 0; } print_connection_info(con); return 1; } static void print_connection_info(SSL *con) { const char *str; X509 *peer; char buf[BUFSIZ]; #if !defined(OPENSSL_NO_NEXTPROTONEG) const unsigned char *next_proto_neg; unsigned next_proto_neg_len; #endif unsigned char *exportedkeymat; int i; if (s_brief) print_ssl_summary(con); PEM_write_bio_SSL_SESSION(bio_s_out, SSL_get_session(con)); peer = SSL_get0_peer_certificate(con); if (peer != NULL) { BIO_printf(bio_s_out, "Client certificate\n"); PEM_write_bio_X509(bio_s_out, peer); dump_cert_text(bio_s_out, peer); peer = NULL; } if (SSL_get_negotiated_server_cert_type(con) == TLSEXT_cert_type_rpk) BIO_printf(bio_s_out, "Server-to-client raw public key negotiated\n"); if (SSL_get_negotiated_client_cert_type(con) == TLSEXT_cert_type_rpk) BIO_printf(bio_s_out, "Client-to-server raw public key negotiated\n"); if (enable_client_rpk) { EVP_PKEY *client_rpk = SSL_get0_peer_rpk(con); if (client_rpk != NULL) { BIO_printf(bio_s_out, "Client raw public key\n"); EVP_PKEY_print_public(bio_s_out, client_rpk, 2, NULL); } } if (SSL_get_shared_ciphers(con, buf, sizeof(buf)) != NULL) BIO_printf(bio_s_out, "Shared ciphers:%s\n", buf); str = SSL_CIPHER_get_name(SSL_get_current_cipher(con)); ssl_print_sigalgs(bio_s_out, con); #ifndef OPENSSL_NO_EC ssl_print_point_formats(bio_s_out, con); ssl_print_groups(bio_s_out, con, 0); #endif print_ca_names(bio_s_out, con); BIO_printf(bio_s_out, "CIPHER is %s\n", (str != NULL) ? str : "(NONE)"); #if !defined(OPENSSL_NO_NEXTPROTONEG) SSL_get0_next_proto_negotiated(con, &next_proto_neg, &next_proto_neg_len); if (next_proto_neg) { BIO_printf(bio_s_out, "NEXTPROTO is "); BIO_write(bio_s_out, next_proto_neg, next_proto_neg_len); BIO_printf(bio_s_out, "\n"); } #endif #ifndef OPENSSL_NO_SRTP { SRTP_PROTECTION_PROFILE *srtp_profile = SSL_get_selected_srtp_profile(con); if (srtp_profile) BIO_printf(bio_s_out, "SRTP Extension negotiated, profile=%s\n", srtp_profile->name); } #endif if (SSL_session_reused(con)) BIO_printf(bio_s_out, "Reused session-id\n"); ssl_print_secure_renegotiation_notes(bio_s_out, con); if ((SSL_get_options(con) & SSL_OP_NO_RENEGOTIATION)) BIO_printf(bio_s_out, "Renegotiation is DISABLED\n"); if (keymatexportlabel != NULL) { BIO_printf(bio_s_out, "Keying material exporter:\n"); BIO_printf(bio_s_out, " Label: '%s'\n", keymatexportlabel); BIO_printf(bio_s_out, " Length: %i bytes\n", keymatexportlen); exportedkeymat = app_malloc(keymatexportlen, "export key"); if (SSL_export_keying_material(con, exportedkeymat, keymatexportlen, keymatexportlabel, strlen(keymatexportlabel), NULL, 0, 0) <= 0) { BIO_printf(bio_s_out, " Error\n"); } else { BIO_printf(bio_s_out, " Keying material: "); for (i = 0; i < keymatexportlen; i++) BIO_printf(bio_s_out, "%02X", exportedkeymat[i]); BIO_printf(bio_s_out, "\n"); } OPENSSL_free(exportedkeymat); } #ifndef OPENSSL_NO_KTLS if (BIO_get_ktls_send(SSL_get_wbio(con))) BIO_printf(bio_err, "Using Kernel TLS for sending\n"); if (BIO_get_ktls_recv(SSL_get_rbio(con))) BIO_printf(bio_err, "Using Kernel TLS for receiving\n"); #endif (void)BIO_flush(bio_s_out); } static int www_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL, *p; int ret = 1; int i, j, k, dot; SSL *con; const SSL_CIPHER *c; BIO *io, *ssl_bio, *sbio; #ifdef RENEG int total_bytes = 0; #endif int width; #ifndef OPENSSL_NO_KTLS int use_sendfile_for_req = use_sendfile; #endif fd_set readfds; const char *opmode; #ifdef CHARSET_EBCDIC BIO *filter; #endif width = s + 1; p = buf = app_malloc(bufsize + 1, "server www buffer"); io = BIO_new(BIO_f_buffer()); ssl_bio = BIO_new(BIO_f_ssl()); if ((io == NULL) || (ssl_bio == NULL)) goto err; if (s_nbio) { if (!BIO_socket_nbio(s, 1)) ERR_print_errors(bio_err); else if (!s_quiet) BIO_printf(bio_err, "Turned on non blocking io\n"); } if (BIO_set_write_buffer_size(io, bufsize) <= 0) goto err; if ((con = SSL_new(ctx)) == NULL) goto err; if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { SSL_free(con); goto err; } sbio = BIO_new_socket(s, BIO_NOCLOSE); if (sbio == NULL) { SSL_free(con); goto err; } if (s_nbio_test) { BIO *test; test = BIO_new(BIO_f_nbio_test()); if (test == NULL) { SSL_free(con); BIO_free(sbio); goto err; } sbio = BIO_push(test, sbio); } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); BIO_set_ssl(ssl_bio, con, BIO_CLOSE); BIO_push(io, ssl_bio); ssl_bio = NULL; #ifdef CHARSET_EBCDIC filter = BIO_new(BIO_f_ebcdic_filter()); if (filter == NULL) goto err; io = BIO_push(filter, io); #endif if (s_debug) { BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback); BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out); } if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out); } for (;;) { i = BIO_gets(io, buf, bufsize + 1); if (i < 0) { if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) { if (!s_quiet) ERR_print_errors(bio_err); goto err; } else { BIO_printf(bio_s_out, "read R BLOCK\n"); #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); lookup_srp_user(&srp_callback_parm, bio_s_out); continue; } #endif OSSL_sleep(1000); continue; } } else if (i == 0) { ret = 1; goto end; } if ((www == 1 && HAS_PREFIX(buf, "GET ")) || (www == 2 && HAS_PREFIX(buf, "GET /stats "))) { X509 *peer = NULL; STACK_OF(SSL_CIPHER) *sk; static const char *space = " "; if (www == 1 && HAS_PREFIX(buf, "GET /reneg")) { if (HAS_PREFIX(buf, "GET /renegcert")) SSL_set_verify(con, SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, NULL); i = SSL_renegotiate(con); BIO_printf(bio_s_out, "SSL_renegotiate -> %d\n", i); i = SSL_do_handshake(con); if (i <= 0) { BIO_printf(bio_s_out, "SSL_do_handshake() Retval %d\n", SSL_get_error(con, i)); ERR_print_errors(bio_err); goto err; } FD_ZERO(&readfds); openssl_fdset(s, &readfds); i = select(width, (void *)&readfds, NULL, NULL, NULL); if (i <= 0 || !FD_ISSET(s, &readfds)) { BIO_printf(bio_s_out, "Error waiting for client response\n"); ERR_print_errors(bio_err); goto err; } BIO_gets(io, buf, bufsize + 1); } BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n"); BIO_puts(io, "<HTML><BODY BGCOLOR=\"#ffffff\">\n"); BIO_puts(io, "<pre>\n"); BIO_puts(io, "\n"); for (i = 0; i < local_argc; i++) { const char *myp; for (myp = local_argv[i]; *myp; myp++) switch (*myp) { case '<': BIO_puts(io, "&lt;"); break; case '>': BIO_puts(io, "&gt;"); break; case '&': BIO_puts(io, "&amp;"); break; default: BIO_write(io, myp, 1); break; } BIO_write(io, " ", 1); } BIO_puts(io, "\n"); ssl_print_secure_renegotiation_notes(io, con); BIO_printf(io, "Ciphers supported in s_server binary\n"); sk = SSL_get_ciphers(con); j = sk_SSL_CIPHER_num(sk); for (i = 0; i < j; i++) { c = sk_SSL_CIPHER_value(sk, i); BIO_printf(io, "%-11s:%-25s ", SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c)); if ((((i + 1) % 2) == 0) && (i + 1 != j)) BIO_puts(io, "\n"); } BIO_puts(io, "\n"); p = SSL_get_shared_ciphers(con, buf, bufsize); if (p != NULL) { BIO_printf(io, "---\nCiphers common between both SSL end points:\n"); j = i = 0; while (*p) { if (*p == ':') { BIO_write(io, space, 26 - j); i++; j = 0; BIO_write(io, ((i % 3) ? " " : "\n"), 1); } else { BIO_write(io, p, 1); j++; } p++; } BIO_puts(io, "\n"); } ssl_print_sigalgs(io, con); #ifndef OPENSSL_NO_EC ssl_print_groups(io, con, 0); #endif print_ca_names(io, con); BIO_printf(io, (SSL_session_reused(con) ? "---\nReused, " : "---\nNew, ")); c = SSL_get_current_cipher(con); BIO_printf(io, "%s, Cipher is %s\n", SSL_CIPHER_get_version(c), SSL_CIPHER_get_name(c)); SSL_SESSION_print(io, SSL_get_session(con)); BIO_printf(io, "---\n"); print_stats(io, SSL_get_SSL_CTX(con)); BIO_printf(io, "---\n"); peer = SSL_get0_peer_certificate(con); if (peer != NULL) { BIO_printf(io, "Client certificate\n"); X509_print(io, peer); PEM_write_bio_X509(io, peer); peer = NULL; } else { BIO_puts(io, "no client certificate available\n"); } BIO_puts(io, "</pre></BODY></HTML>\r\n\r\n"); break; } else if ((www == 2 || www == 3) && CHECK_AND_SKIP_PREFIX(p, "GET /")) { BIO *file; char *e; static const char *text = "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n"; dot = 1; for (e = p; *e != '\0'; e++) { if (e[0] == ' ') break; if (e[0] == ':') { dot = -1; break; } switch (dot) { case 1: dot = (e[0] == '.') ? 2 : 0; break; case 2: dot = (e[0] == '.') ? 3 : 0; break; case 3: dot = (e[0] == '/' || e[0] == '\\') ? -1 : 0; break; } if (dot == 0) dot = (e[0] == '/' || e[0] == '\\') ? 1 : 0; } dot = (dot == 3) || (dot == -1); if (*e == '\0') { BIO_puts(io, text); BIO_printf(io, "'%s' is an invalid file name\r\n", p); break; } *e = '\0'; if (dot) { BIO_puts(io, text); BIO_printf(io, "'%s' contains '..' or ':'\r\n", p); break; } if (*p == '/' || *p == '\\') { BIO_puts(io, text); BIO_printf(io, "'%s' is an invalid path\r\n", p); break; } if (app_isdir(p) > 0) { BIO_puts(io, text); BIO_printf(io, "'%s' is a directory\r\n", p); break; } opmode = (http_server_binmode == 1) ? "rb" : "r"; if ((file = BIO_new_file(p, opmode)) == NULL) { BIO_puts(io, text); BIO_printf(io, "Error opening '%s' mode='%s'\r\n", p, opmode); ERR_print_errors(io); break; } if (!s_quiet) BIO_printf(bio_err, "FILE:%s\n", p); if (www == 2) { i = strlen(p); if (((i > 5) && (strcmp(&(p[i - 5]), ".html") == 0)) || ((i > 4) && (strcmp(&(p[i - 4]), ".php") == 0)) || ((i > 4) && (strcmp(&(p[i - 4]), ".htm") == 0))) BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/html\r\n\r\n"); else BIO_puts(io, "HTTP/1.0 200 ok\r\nContent-type: text/plain\r\n\r\n"); } #ifndef OPENSSL_NO_KTLS if (use_sendfile_for_req && !BIO_get_ktls_send(SSL_get_wbio(con))) { BIO_printf(bio_err, "Warning: sendfile requested but KTLS is not available\n"); use_sendfile_for_req = 0; } if (use_sendfile_for_req) { FILE *fp = NULL; int fd; struct stat st; off_t offset = 0; size_t filesize; BIO_get_fp(file, &fp); fd = fileno(fp); if (fstat(fd, &st) < 0) { BIO_printf(io, "Error fstat '%s'\r\n", p); ERR_print_errors(io); goto write_error; } filesize = st.st_size; if (((int)BIO_flush(io)) < 0) goto write_error; for (;;) { i = SSL_sendfile(con, fd, offset, filesize, 0); if (i < 0) { BIO_printf(io, "Error SSL_sendfile '%s'\r\n", p); ERR_print_errors(io); break; } else { offset += i; filesize -= i; } if (filesize <= 0) { if (!s_quiet) BIO_printf(bio_err, "KTLS SENDFILE '%s' OK\n", p); break; } } } else #endif { for (;;) { i = BIO_read(file, buf, bufsize); if (i <= 0) break; #ifdef RENEG total_bytes += i; BIO_printf(bio_err, "%d\n", i); if (total_bytes > 3 * 1024) { total_bytes = 0; BIO_printf(bio_err, "RENEGOTIATE\n"); SSL_renegotiate(con); } #endif for (j = 0; j < i;) { #ifdef RENEG static count = 0; if (++count == 13) SSL_renegotiate(con); #endif k = BIO_write(io, &(buf[j]), i - j); if (k <= 0) { if (!BIO_should_retry(io) && !SSL_waiting_for_async(con)) { goto write_error; } else { BIO_printf(bio_s_out, "rwrite W BLOCK\n"); } } else { j += k; } } } } write_error: BIO_free(file); break; } } for (;;) { i = (int)BIO_flush(io); if (i <= 0) { if (!BIO_should_retry(io)) break; } else break; } end: do_ssl_shutdown(con); err: OPENSSL_free(buf); BIO_free(ssl_bio); BIO_free_all(io); return ret; } static int rev_body(int s, int stype, int prot, unsigned char *context) { char *buf = NULL; int i; int ret = 1; SSL *con; BIO *io, *ssl_bio, *sbio; #ifdef CHARSET_EBCDIC BIO *filter; #endif buf = app_malloc(bufsize + 1, "server rev buffer"); io = BIO_new(BIO_f_buffer()); ssl_bio = BIO_new(BIO_f_ssl()); if ((io == NULL) || (ssl_bio == NULL)) goto err; if (BIO_set_write_buffer_size(io, bufsize) <= 0) goto err; if ((con = SSL_new(ctx)) == NULL) goto err; if (s_tlsextdebug) { SSL_set_tlsext_debug_callback(con, tlsext_cb); SSL_set_tlsext_debug_arg(con, bio_s_out); } if (context != NULL && !SSL_set_session_id_context(con, context, strlen((char *)context))) { SSL_free(con); ERR_print_errors(bio_err); goto err; } sbio = BIO_new_socket(s, BIO_NOCLOSE); if (sbio == NULL) { SSL_free(con); ERR_print_errors(bio_err); goto err; } SSL_set_bio(con, sbio, sbio); SSL_set_accept_state(con); BIO_set_ssl(ssl_bio, con, BIO_CLOSE); BIO_push(io, ssl_bio); ssl_bio = NULL; #ifdef CHARSET_EBCDIC filter = BIO_new(BIO_f_ebcdic_filter()); if (filter == NULL) goto err; io = BIO_push(filter, io); #endif if (s_debug) { BIO_set_callback_ex(SSL_get_rbio(con), bio_dump_callback); BIO_set_callback_arg(SSL_get_rbio(con), (char *)bio_s_out); } if (s_msg) { #ifndef OPENSSL_NO_SSL_TRACE if (s_msg == 2) SSL_set_msg_callback(con, SSL_trace); else #endif SSL_set_msg_callback(con, msg_cb); SSL_set_msg_callback_arg(con, bio_s_msg ? bio_s_msg : bio_s_out); } for (;;) { i = BIO_do_handshake(io); if (i > 0) break; if (!BIO_should_retry(io)) { BIO_puts(bio_err, "CONNECTION FAILURE\n"); ERR_print_errors(bio_err); goto end; } #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during accept\n"); lookup_srp_user(&srp_callback_parm, bio_s_out); continue; } #endif } BIO_printf(bio_err, "CONNECTION ESTABLISHED\n"); print_ssl_summary(con); for (;;) { i = BIO_gets(io, buf, bufsize + 1); if (i < 0) { if (!BIO_should_retry(io)) { if (!s_quiet) ERR_print_errors(bio_err); goto err; } else { BIO_printf(bio_s_out, "read R BLOCK\n"); #ifndef OPENSSL_NO_SRP if (BIO_should_io_special(io) && BIO_get_retry_reason(io) == BIO_RR_SSL_X509_LOOKUP) { BIO_printf(bio_s_out, "LOOKUP renego during read\n"); lookup_srp_user(&srp_callback_parm, bio_s_out); continue; } #endif OSSL_sleep(1000); continue; } } else if (i == 0) { ret = 1; BIO_printf(bio_err, "CONNECTION CLOSED\n"); goto end; } else { char *p = buf + i - 1; while (i && (*p == '\n' || *p == '\r')) { p--; i--; } if (!s_ign_eof && i == 5 && HAS_PREFIX(buf, "CLOSE")) { ret = 1; BIO_printf(bio_err, "CONNECTION CLOSED\n"); goto end; } BUF_reverse((unsigned char *)buf, NULL, i); buf[i] = '\n'; BIO_write(io, buf, i + 1); for (;;) { i = BIO_flush(io); if (i > 0) break; if (!BIO_should_retry(io)) goto end; } } } end: do_ssl_shutdown(con); err: OPENSSL_free(buf); BIO_free(ssl_bio); BIO_free_all(io); return ret; } #define MAX_SESSION_ID_ATTEMPTS 10 static int generate_session_id(SSL *ssl, unsigned char *id, unsigned int *id_len) { unsigned int count = 0; unsigned int session_id_prefix_len = strlen(session_id_prefix); do { if (RAND_bytes(id, *id_len) <= 0) return 0; memcpy(id, session_id_prefix, (session_id_prefix_len < *id_len) ? session_id_prefix_len : *id_len); } while (SSL_has_matching_session_id(ssl, id, *id_len) && (++count < MAX_SESSION_ID_ATTEMPTS)); if (count >= MAX_SESSION_ID_ATTEMPTS) return 0; return 1; } typedef struct simple_ssl_session_st { unsigned char *id; unsigned int idlen; unsigned char *der; int derlen; struct simple_ssl_session_st *next; } simple_ssl_session; static simple_ssl_session *first = NULL; static int add_session(SSL *ssl, SSL_SESSION *session) { simple_ssl_session *sess = app_malloc(sizeof(*sess), "get session"); unsigned char *p; SSL_SESSION_get_id(session, &sess->idlen); sess->derlen = i2d_SSL_SESSION(session, NULL); if (sess->derlen < 0) { BIO_printf(bio_err, "Error encoding session\n"); OPENSSL_free(sess); return 0; } sess->id = OPENSSL_memdup(SSL_SESSION_get_id(session, NULL), sess->idlen); sess->der = app_malloc(sess->derlen, "get session buffer"); if (!sess->id) { BIO_printf(bio_err, "Out of memory adding to external cache\n"); OPENSSL_free(sess->id); OPENSSL_free(sess->der); OPENSSL_free(sess); return 0; } p = sess->der; if (i2d_SSL_SESSION(session, &p) != sess->derlen) { BIO_printf(bio_err, "Unexpected session encoding length\n"); OPENSSL_free(sess->id); OPENSSL_free(sess->der); OPENSSL_free(sess); return 0; } sess->next = first; first = sess; BIO_printf(bio_err, "New session added to external cache\n"); return 0; } static SSL_SESSION *get_session(SSL *ssl, const unsigned char *id, int idlen, int *do_copy) { simple_ssl_session *sess; *do_copy = 0; for (sess = first; sess; sess = sess->next) { if (idlen == (int)sess->idlen && !memcmp(sess->id, id, idlen)) { const unsigned char *p = sess->der; BIO_printf(bio_err, "Lookup session: cache hit\n"); return d2i_SSL_SESSION_ex(NULL, &p, sess->derlen, app_get0_libctx(), app_get0_propq()); } } BIO_printf(bio_err, "Lookup session: cache miss\n"); return NULL; } static void del_session(SSL_CTX *sctx, SSL_SESSION *session) { simple_ssl_session *sess, *prev = NULL; const unsigned char *id; unsigned int idlen; id = SSL_SESSION_get_id(session, &idlen); for (sess = first; sess; sess = sess->next) { if (idlen == sess->idlen && !memcmp(sess->id, id, idlen)) { if (prev) prev->next = sess->next; else first = sess->next; OPENSSL_free(sess->id); OPENSSL_free(sess->der); OPENSSL_free(sess); return; } prev = sess; } } static void init_session_cache_ctx(SSL_CTX *sctx) { SSL_CTX_set_session_cache_mode(sctx, SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_SERVER); SSL_CTX_sess_set_new_cb(sctx, add_session); SSL_CTX_sess_set_get_cb(sctx, get_session); SSL_CTX_sess_set_remove_cb(sctx, del_session); } static void free_sessions(void) { simple_ssl_session *sess, *tsess; for (sess = first; sess;) { OPENSSL_free(sess->id); OPENSSL_free(sess->der); tsess = sess; sess = sess->next; OPENSSL_free(tsess); } first = NULL; } #endif
apps
openssl/apps/s_server.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/opensslconf.h> #ifndef OPENSSL_NO_SOCK #include "apps.h" #include "progs.h" #include <openssl/x509.h> #include <openssl/ssl.h> #include <openssl/pem.h> #include "s_apps.h" #include <openssl/err.h> #include "internal/sockets.h" #if !defined(OPENSSL_SYS_MSDOS) # include <unistd.h> #endif #define SSL_CONNECT_NAME "localhost:4433" #define SECONDS 30 #define SECONDSSTR "30" static SSL *doConnection(SSL *scon, const char *host, SSL_CTX *ctx); static const char fmt_http_get_cmd[] = "GET %s HTTP/1.0\r\n\r\n"; static const size_t fmt_http_get_cmd_size = sizeof(fmt_http_get_cmd) - 2; typedef enum OPTION_choice { OPT_COMMON, OPT_CONNECT, OPT_CIPHER, OPT_CIPHERSUITES, OPT_CERT, OPT_NAMEOPT, OPT_KEY, OPT_CAPATH, OPT_CAFILE, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_NEW, OPT_REUSE, OPT_BUGS, OPT_VERIFY, OPT_TIME, OPT_SSL3, OPT_WWW, OPT_TLS1, OPT_TLS1_1, OPT_TLS1_2, OPT_TLS1_3, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS s_time_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Connection"), {"connect", OPT_CONNECT, 's', "Where to connect as post:port (default is " SSL_CONNECT_NAME ")"}, {"new", OPT_NEW, '-', "Just time new connections"}, {"reuse", OPT_REUSE, '-', "Just time connection reuse"}, {"bugs", OPT_BUGS, '-', "Turn on SSL bug compatibility"}, {"cipher", OPT_CIPHER, 's', "TLSv1.2 and below cipher list to be used"}, {"ciphersuites", OPT_CIPHERSUITES, 's', "Specify TLSv1.3 ciphersuites to be used"}, #ifndef OPENSSL_NO_SSL3 {"ssl3", OPT_SSL3, '-', "Just use SSLv3"}, #endif #ifndef OPENSSL_NO_TLS1 {"tls1", OPT_TLS1, '-', "Just use TLSv1.0"}, #endif #ifndef OPENSSL_NO_TLS1_1 {"tls1_1", OPT_TLS1_1, '-', "Just use TLSv1.1"}, #endif #ifndef OPENSSL_NO_TLS1_2 {"tls1_2", OPT_TLS1_2, '-', "Just use TLSv1.2"}, #endif #ifndef OPENSSL_NO_TLS1_3 {"tls1_3", OPT_TLS1_3, '-', "Just use TLSv1.3"}, #endif {"verify", OPT_VERIFY, 'p', "Turn on peer certificate verification, set depth"}, {"time", OPT_TIME, 'p', "Seconds to collect data, default " SECONDSSTR}, {"www", OPT_WWW, 's', "Fetch specified page from the site"}, OPT_SECTION("Certificate"), {"nameopt", OPT_NAMEOPT, 's', "Certificate subject/issuer name printing options"}, {"cert", OPT_CERT, '<', "Cert file to use, PEM format assumed"}, {"key", OPT_KEY, '<', "File with key, PEM; default is -cert file"}, {"cafile", OPT_CAFILE, '<', "PEM format file of CA's"}, {"CAfile", OPT_CAFILE, '<', "PEM format file of CA's"}, {"CApath", OPT_CAPATH, '/', "PEM format directory of CA's"}, {"CAstore", OPT_CASTORE, ':', "URI to store of CA's"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store URI"}, OPT_PROV_OPTIONS, {NULL} }; #define START 0 #define STOP 1 static double tm_Time_F(int s) { return app_tminterval(s, 1); } 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, *CAstore = NULL; char *cipher = NULL, *ciphersuites = NULL; char *www_path = NULL; char *host = SSL_CONNECT_NAME, *certfile = NULL, *keyfile = NULL, *prog; double totalTime = 0.0; int noCApath = 0, noCAfile = 0, noCAstore = 0; int maxtime = SECONDS, nConn = 0, perform = 3, ret = 1, i, st_bugs = 0; long bytes_read = 0, finishtime = 0; OPTION_CHOICE o; int min_version = 0, max_version = 0, ver, buf_len, fd; size_t buf_size; meth = TLS_client_method(); 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: verify_args.depth = opt_int_arg(); BIO_printf(bio_err, "%s: verify depth is %d\n", prog, verify_args.depth); break; case OPT_CERT: certfile = opt_arg(); break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto end; 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_CASTORE: CAstore = opt_arg(); break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_CIPHER: cipher = opt_arg(); break; case OPT_CIPHERSUITES: ciphersuites = opt_arg(); break; case OPT_BUGS: st_bugs = 1; break; case OPT_TIME: maxtime = opt_int_arg(); break; case OPT_WWW: www_path = opt_arg(); buf_size = strlen(www_path) + fmt_http_get_cmd_size; if (buf_size > sizeof(buf)) { BIO_printf(bio_err, "%s: -www option is too long\n", prog); goto end; } break; case OPT_SSL3: min_version = SSL3_VERSION; max_version = SSL3_VERSION; break; case OPT_TLS1: min_version = TLS1_VERSION; max_version = TLS1_VERSION; break; case OPT_TLS1_1: min_version = TLS1_1_VERSION; max_version = TLS1_1_VERSION; break; case OPT_TLS1_2: min_version = TLS1_2_VERSION; max_version = TLS1_2_VERSION; break; case OPT_TLS1_3: min_version = TLS1_3_VERSION; max_version = TLS1_3_VERSION; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (cipher == NULL) cipher = getenv("SSL_CIPHER"); if ((ctx = SSL_CTX_new(meth)) == NULL) goto end; SSL_CTX_set_quiet_shutdown(ctx, 1); if (SSL_CTX_set_min_proto_version(ctx, min_version) == 0) goto end; 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 (cipher != NULL && !SSL_CTX_set_cipher_list(ctx, cipher)) goto end; if (ciphersuites != NULL && !SSL_CTX_set_ciphersuites(ctx, ciphersuites)) goto end; if (!set_cert_stuff(ctx, certfile, keyfile)) goto end; if (!ctx_set_verify_locations(ctx, CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) { ERR_print_errors(bio_err); goto end; } if (!(perform & 1)) goto next; printf("Collecting connection statistics for %d seconds\n", maxtime); 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) { buf_len = BIO_snprintf(buf, sizeof(buf), fmt_http_get_cmd, www_path); if (buf_len <= 0 || SSL_write(scon, buf, buf_len) <= 0) goto end; while ((i = SSL_read(scon, buf, sizeof(buf))) > 0) bytes_read += i; } SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); 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); 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, nConn > 0 ? bytes_read / nConn : 0l); next: if (!(perform & 2)) goto end; printf("\n\nNow timing with session id reuse.\n"); if ((scon = doConnection(NULL, host, ctx)) == NULL) { BIO_printf(bio_err, "Unable to get connection\n"); goto end; } if (www_path != NULL) { buf_len = BIO_snprintf(buf, sizeof(buf), fmt_http_get_cmd, www_path); if (buf_len <= 0 || SSL_write(scon, buf, buf_len) <= 0) goto end; while (SSL_read(scon, buf, sizeof(buf)) > 0) continue; } SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); if ((fd = SSL_get_fd(scon)) >= 0) BIO_closesocket(fd); 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 != NULL) { buf_len = BIO_snprintf(buf, sizeof(buf), fmt_http_get_cmd, www_path); if (buf_len <= 0 || SSL_write(scon, buf, buf_len) <= 0) goto end; while ((i = SSL_read(scon, buf, sizeof(buf))) > 0) bytes_read += i; } SSL_set_shutdown(scon, SSL_SENT_SHUTDOWN | SSL_RECEIVED_SHUTDOWN); if ((fd = SSL_get_fd(scon)) >= 0) BIO_closesocket(fd); 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); printf ("\n\n%d connections in %.2fs; %.2f connections/user sec, bytes read %ld\n", nConn, totalTime, ((double)nConn / totalTime), bytes_read); if (nConn > 0) printf ("%d connections in %ld real seconds, %ld bytes read per connection\n", nConn, (long)time(NULL) - finishtime + maxtime, bytes_read / nConn); else printf("0 connections in %ld real seconds\n", (long)time(NULL) - finishtime + maxtime); ret = 0; end: SSL_free(scon); SSL_CTX_free(ctx); return ret; } static SSL *doConnection(SSL *scon, const char *host, SSL_CTX *ctx) { BIO *conn; SSL *serverCon; int i; if ((conn = BIO_new(BIO_s_connect())) == NULL) return NULL; if (BIO_set_conn_hostname(conn, host) <= 0 || BIO_set_conn_mode(conn, BIO_SOCK_NODELAY) <= 0) { BIO_free(conn); return NULL; } if (scon == NULL) { serverCon = SSL_new(ctx); if (serverCon == NULL) { BIO_free(conn); return NULL; } } else { serverCon = scon; SSL_set_connect_state(serverCon); } SSL_set_bio(serverCon, conn, conn); i = SSL_connect(serverCon); if (i <= 0) { BIO_printf(bio_err, "ERROR\n"); if (verify_args.error != X509_V_OK) BIO_printf(bio_err, "verify error:%s\n", X509_verify_cert_error_string(verify_args.error)); else ERR_print_errors(bio_err); if (scon == NULL) SSL_free(serverCon); return NULL; } #if defined(SOL_SOCKET) && defined(SO_LINGER) { struct linger no_linger; int fd; no_linger.l_onoff = 1; no_linger.l_linger = 0; fd = SSL_get_fd(serverCon); if (fd >= 0) (void)setsockopt(fd, SOL_SOCKET, SO_LINGER, (char*)&no_linger, sizeof(no_linger)); } #endif return serverCon; } #endif
apps
openssl/apps/s_time.c
openssl
#include <openssl/opensslconf.h> #ifdef OPENSSL_SYS_VMS # define _XOPEN_SOURCE_EXTENDED #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <ctype.h> #include "apps.h" #include "http_server.h" #include "progs.h" #include "internal/sockets.h" #include <openssl/e_os2.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/ssl.h> #include <openssl/evp.h> #include <openssl/bn.h> #include <openssl/x509v3.h> #if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include <floss.h(floss_fork)> # endif #endif #if defined(OPENSSL_SYS_VXWORKS) int setpgid(pid_t pid, pid_t pgid) { errno = ENOSYS; return 0; } pid_t fork(void) { errno = ENOSYS; return (pid_t) -1; } #endif #define MAX_VALIDITY_PERIOD (5 * 60) static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, const EVP_MD *cert_id_md, X509 *issuer, STACK_OF(OCSP_CERTID) *ids); static int add_ocsp_serial(OCSP_REQUEST **req, char *serial, const EVP_MD *cert_id_md, X509 *issuer, STACK_OF(OCSP_CERTID) *ids); static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req, STACK_OF(OPENSSL_STRING) *names, STACK_OF(OCSP_CERTID) *ids, long nsec, long maxage); static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req, CA_DB *db, STACK_OF(X509) *ca, X509 *rcert, EVP_PKEY *rkey, const EVP_MD *md, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(X509) *rother, unsigned long flags, int nmin, int ndays, int badsig, const EVP_MD *resp_md); static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser); static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout); static int send_ocsp_response(BIO *cbio, const OCSP_RESPONSE *resp); static char *prog; #ifdef HTTP_DAEMON static int index_changed(CA_DB *); #endif typedef enum OPTION_choice { OPT_COMMON, OPT_OUTFILE, OPT_TIMEOUT, OPT_URL, OPT_HOST, OPT_PORT, #ifndef OPENSSL_NO_SOCK OPT_PROXY, OPT_NO_PROXY, #endif OPT_IGNORE_ERR, OPT_NOVERIFY, OPT_NONCE, OPT_NO_NONCE, OPT_RESP_NO_CERTS, OPT_RESP_KEY_ID, OPT_NO_CERTS, OPT_NO_SIGNATURE_VERIFY, OPT_NO_CERT_VERIFY, OPT_NO_CHAIN, OPT_NO_CERT_CHECKS, OPT_NO_EXPLICIT, OPT_TRUST_OTHER, OPT_NO_INTERN, OPT_BADSIG, OPT_TEXT, OPT_REQ_TEXT, OPT_RESP_TEXT, OPT_REQIN, OPT_RESPIN, OPT_SIGNER, OPT_VAFILE, OPT_SIGN_OTHER, OPT_VERIFY_OTHER, OPT_CAFILE, OPT_CAPATH, OPT_CASTORE, OPT_NOCAFILE, OPT_NOCAPATH, OPT_NOCASTORE, OPT_VALIDITY_PERIOD, OPT_STATUS_AGE, OPT_SIGNKEY, OPT_REQOUT, OPT_RESPOUT, OPT_PATH, OPT_ISSUER, OPT_CERT, OPT_SERIAL, OPT_INDEX, OPT_CA, OPT_NMIN, OPT_REQUEST, OPT_NDAYS, OPT_RSIGNER, OPT_RKEY, OPT_ROTHER, OPT_RMD, OPT_RSIGOPT, OPT_HEADER, OPT_PASSIN, OPT_RCID, OPT_V_ENUM, OPT_MD, OPT_MULTI, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS ocsp_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"ignore_err", OPT_IGNORE_ERR, '-', "Ignore error on OCSP request or response and continue running"}, {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"}, {"CApath", OPT_CAPATH, '<', "Trusted certificates directory"}, {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, OPT_SECTION("Responder"), {"timeout", OPT_TIMEOUT, 'p', "Connection timeout (in seconds) to the OCSP responder"}, {"resp_no_certs", OPT_RESP_NO_CERTS, '-', "Don't include any certificates in response"}, #ifdef HTTP_DAEMON {"multi", OPT_MULTI, 'p', "run multiple responder processes"}, #endif {"no_certs", OPT_NO_CERTS, '-', "Don't include any certificates in signed request"}, {"badsig", OPT_BADSIG, '-', "Corrupt last byte of loaded OCSP response signature (for test)"}, {"CA", OPT_CA, '<', "CA certificates"}, {"nmin", OPT_NMIN, 'p', "Number of minutes before next update"}, {"nrequest", OPT_REQUEST, 'p', "Number of requests to accept (default unlimited)"}, {"reqin", OPT_REQIN, 's', "File with the DER-encoded request"}, {"signer", OPT_SIGNER, '<', "Certificate to sign OCSP request with"}, {"sign_other", OPT_SIGN_OTHER, '<', "Additional certificates to include in signed request"}, {"index", OPT_INDEX, '<', "Certificate status index file"}, {"ndays", OPT_NDAYS, 'p', "Number of days before next update"}, {"rsigner", OPT_RSIGNER, '<', "Responder certificate to sign responses with"}, {"rkey", OPT_RKEY, '<', "Responder key to sign responses with"}, {"passin", OPT_PASSIN, 's', "Responder key pass phrase source"}, {"rother", OPT_ROTHER, '<', "Other certificates to include in response"}, {"rmd", OPT_RMD, 's', "Digest Algorithm to use in signature of OCSP response"}, {"rsigopt", OPT_RSIGOPT, 's', "OCSP response signature parameter in n:v form"}, {"header", OPT_HEADER, 's', "key=value header to add"}, {"rcid", OPT_RCID, 's', "Use specified algorithm for cert id in response"}, {"", OPT_MD, '-', "Any supported digest algorithm (sha1,sha256, ... )"}, OPT_SECTION("Client"), {"url", OPT_URL, 's', "Responder URL"}, {"host", OPT_HOST, 's', "TCP/IP hostname:port to connect to"}, {"port", OPT_PORT, 'N', "Port to run responder on"}, {"path", OPT_PATH, 's', "Path to use in OCSP request"}, #ifndef OPENSSL_NO_SOCK {"proxy", OPT_PROXY, 's', "[http[s]: {"no_proxy", OPT_NO_PROXY, 's', "List of addresses of servers not to use HTTP(S) proxy for"}, {OPT_MORE_STR, 0, 0, "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"}, #endif {"out", OPT_OUTFILE, '>', "Output filename"}, {"noverify", OPT_NOVERIFY, '-', "Don't verify response at all"}, {"nonce", OPT_NONCE, '-', "Add OCSP nonce to request"}, {"no_nonce", OPT_NO_NONCE, '-', "Don't add OCSP nonce to request"}, {"no_signature_verify", OPT_NO_SIGNATURE_VERIFY, '-', "Don't check signature on response"}, {"resp_key_id", OPT_RESP_KEY_ID, '-', "Identify response by signing certificate key ID"}, {"no_cert_verify", OPT_NO_CERT_VERIFY, '-', "Don't check signing certificate"}, {"text", OPT_TEXT, '-', "Print text form of request and response"}, {"req_text", OPT_REQ_TEXT, '-', "Print text form of request"}, {"resp_text", OPT_RESP_TEXT, '-', "Print text form of response"}, {"no_chain", OPT_NO_CHAIN, '-', "Don't chain verify response"}, {"no_cert_checks", OPT_NO_CERT_CHECKS, '-', "Don't do additional checks on signing certificate"}, {"no_explicit", OPT_NO_EXPLICIT, '-', "Do not explicitly check the chain, just verify the root"}, {"trust_other", OPT_TRUST_OTHER, '-', "Don't verify additional certificates"}, {"no_intern", OPT_NO_INTERN, '-', "Don't search certificates contained in response for signer"}, {"respin", OPT_RESPIN, 's', "File with the DER-encoded response"}, {"VAfile", OPT_VAFILE, '<', "Validator certificates file"}, {"verify_other", OPT_VERIFY_OTHER, '<', "Additional certificates to search for signer"}, {"cert", OPT_CERT, '<', "Certificate to check; may be given multiple times"}, {"serial", OPT_SERIAL, 's', "Serial number to check; may be given multiple times"}, {"validity_period", OPT_VALIDITY_PERIOD, 'u', "Maximum validity discrepancy in seconds"}, {"signkey", OPT_SIGNKEY, 's', "Private key to sign OCSP request with"}, {"reqout", OPT_REQOUT, 's', "Output file for the DER-encoded request"}, {"respout", OPT_RESPOUT, 's', "Output file for the DER-encoded response"}, {"issuer", OPT_ISSUER, '<', "Issuer certificate"}, {"status_age", OPT_STATUS_AGE, 'p', "Maximum status age in seconds"}, OPT_V_OPTIONS, OPT_PROV_OPTIONS, {NULL} }; int ocsp_main(int argc, char **argv) { BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL; EVP_MD *cert_id_md = NULL, *rsign_md = NULL; STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL; int trailing_md = 0; 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; STACK_OF(X509) *rca_certs = NULL; EVP_MD *resp_certid_md = NULL; X509 *signer = NULL, *rsigner = NULL; X509_STORE *store = NULL; X509_VERIFY_PARAM *vpm = NULL; const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL; char *header, *value, *respdigname = NULL; char *host = NULL, *port = NULL, *path = "/", *outfile = NULL; #ifndef OPENSSL_NO_SOCK char *opt_proxy = NULL; char *opt_no_proxy = NULL; #endif char *rca_filename = NULL, *reqin = NULL, *respin = NULL; char *reqout = NULL, *respout = NULL, *ridx_filename = NULL; char *rsignfile = NULL, *rkeyfile = NULL; char *passinarg = NULL, *passin = NULL; char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL; char *signfile = NULL, *keyfile = NULL; char *thost = NULL, *tport = NULL, *tpath = NULL; int noCAfile = 0, noCApath = 0, noCAstore = 0; 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, res, ret = 1; int req_timeout = -1; long nsec = MAX_VALIDITY_PERIOD, maxage = -1; unsigned long sign_flags = 0, verify_flags = 0, rflags = 0; OPTION_CHOICE o; if ((reqnames = sk_OPENSSL_STRING_new_null()) == NULL || (ids = sk_OCSP_CERTID_new_null()) == NULL || (vpm = X509_VERIFY_PARAM_new()) == NULL) goto end; opt_set_unknown_name("digest"); 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: #ifndef OPENSSL_NO_SOCK req_timeout = atoi(opt_arg()); #endif break; case OPT_URL: OPENSSL_free(thost); OPENSSL_free(tport); OPENSSL_free(tpath); thost = tport = tpath = NULL; if (!OSSL_HTTP_parse_url(opt_arg(), &use_ssl, NULL , &host, &port, NULL , &path, NULL , NULL )) { BIO_printf(bio_err, "%s Error parsing -url argument\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_PATH: path = opt_arg(); break; #ifndef OPENSSL_NO_SOCK case OPT_PROXY: opt_proxy = opt_arg(); break; case OPT_NO_PROXY: opt_no_proxy = opt_arg(); break; #endif 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_CASTORE: CAstore = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCASTORE: noCAstore = 1; 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_ISSUER: issuer = load_cert(opt_arg(), FORMAT_UNDEF, "issuer certificate"); if (issuer == NULL) goto end; if (issuers == NULL) { if ((issuers = sk_X509_new_null()) == NULL) goto end; } if (!sk_X509_push(issuers, issuer)) goto end; break; case OPT_CERT: reset_unknown(); X509_free(cert); cert = load_cert(opt_arg(), FORMAT_UNDEF, "certificate"); if (cert == NULL) goto end; if (cert_id_md == NULL) cert_id_md = (EVP_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; trailing_md = 0; break; case OPT_SERIAL: reset_unknown(); if (cert_id_md == NULL) cert_id_md = (EVP_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; trailing_md = 0; break; case OPT_INDEX: ridx_filename = opt_arg(); break; case OPT_CA: rca_filename = opt_arg(); break; case OPT_NMIN: nmin = opt_int_arg(); if (ndays == -1) ndays = 0; break; case OPT_REQUEST: accept_count = opt_int_arg(); 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_PASSIN: passinarg = opt_arg(); break; case OPT_ROTHER: rcertfile = opt_arg(); break; case OPT_RMD: respdigname = opt_arg(); break; case OPT_RSIGOPT: if (rsign_sigopts == NULL) rsign_sigopts = sk_OPENSSL_STRING_new_null(); if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg())) 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_RCID: if (!opt_md(opt_arg(), &resp_certid_md)) goto opthelp; break; case OPT_MD: if (trailing_md) { 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; trailing_md = 1; break; case OPT_MULTI: #ifdef HTTP_DAEMON n_responders = atoi(opt_arg()); #endif break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (trailing_md) { BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n", prog); goto opthelp; } if (respdigname != NULL) { if (!opt_md(respdigname, &rsign_md)) goto end; } if (req == NULL && reqin == NULL && respin == NULL && !(port != NULL && ridx_filename != NULL)) goto opthelp; out = bio_open_default(outfile, 'w', FORMAT_TEXT); if (out == NULL) goto end; if (req == NULL && (add_nonce != 2)) add_nonce = 0; if (req == NULL && reqin != NULL) { derbio = bio_open_default(reqin, 'r', FORMAT_ASN1); if (derbio == NULL) goto end; req = d2i_OCSP_REQUEST_bio(derbio, NULL); BIO_free(derbio); if (req == NULL) { BIO_printf(bio_err, "Error reading OCSP request\n"); goto end; } } if (req == NULL && port != NULL) { #ifndef OPENSSL_NO_SOCK acbio = http_server_init(prog, port, -1); if (acbio == NULL) goto end; #else BIO_printf(bio_err, "Cannot act as server - sockets not supported\n"); goto end; #endif } if (rsignfile != NULL) { if (rkeyfile == NULL) rkeyfile = rsignfile; rsigner = load_cert(rsignfile, FORMAT_UNDEF, "responder certificate"); if (rsigner == NULL) { BIO_printf(bio_err, "Error loading responder certificate\n"); goto end; } if (!load_certs(rca_filename, 0, &rca_certs, NULL, "CA certificates")) goto end; if (rcertfile != NULL) { if (!load_certs(rcertfile, 0, &rother, NULL, "responder other certificates")) goto end; } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } rkey = load_key(rkeyfile, FORMAT_UNDEF, 0, passin, NULL, "responder private key"); if (rkey == NULL) goto end; } if (ridx_filename != NULL && (rkey == NULL || rsigner == NULL || rca_certs == NULL)) { BIO_printf(bio_err, "Responder mode requires certificate, key, and CA.\n"); goto end; } if (ridx_filename != NULL) { rdb = load_index(ridx_filename, NULL); if (rdb == NULL || index_index(rdb) <= 0) { BIO_printf(bio_err, "Problem with index file: %s (could not load/parse file)\n", ridx_filename); ret = 1; goto end; } } #ifdef HTTP_DAEMON if (n_responders != 0 && acbio != NULL) spawn_loop(prog); if (acbio != NULL && req_timeout > 0) signal(SIGALRM, socket_timeout); #endif if (acbio != NULL) trace_log_message(-1, prog, LOG_INFO, "waiting for OCSP client connections..."); redo_accept: if (acbio != NULL) { #ifdef HTTP_DAEMON if (index_changed(rdb)) { CA_DB *newrdb = load_index(ridx_filename, NULL); if (newrdb != NULL && index_index(newrdb) > 0) { free_index(rdb); rdb = newrdb; } else { free_index(newrdb); trace_log_message(-1, prog, LOG_ERR, "error reloading updated index: %s", ridx_filename); } } #endif req = NULL; res = do_responder(&req, &cbio, acbio, req_timeout); if (res == 0) goto redo_accept; if (req == NULL) { if (res == 1) { resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL); send_ocsp_response(cbio, resp); } goto done_resp; } } if (req == NULL && (signfile != NULL || reqout != NULL || host != NULL || add_nonce || ridx_filename != NULL)) { BIO_printf(bio_err, "Need an OCSP request for this operation!\n"); goto end; } if (req != NULL && add_nonce) { if (!OCSP_request_add1_nonce(req, NULL, -1)) goto end; } if (signfile != NULL) { if (keyfile == NULL) keyfile = signfile; signer = load_cert(signfile, FORMAT_UNDEF, "signer certificate"); if (signer == NULL) { BIO_printf(bio_err, "Error loading signer certificate\n"); goto end; } if (sign_certfile != NULL) { if (!load_certs(sign_certfile, 0, &sign_other, NULL, "signer certificates")) goto end; } key = load_key(keyfile, FORMAT_UNDEF, 0, NULL, NULL, "signer private key"); if (key == NULL) 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 != NULL) OCSP_REQUEST_print(out, req, 0); if (reqout != NULL) { derbio = bio_open_default(reqout, 'w', FORMAT_ASN1); if (derbio == NULL) goto end; i2d_OCSP_REQUEST_bio(derbio, req); BIO_free(derbio); } if (rdb != NULL) { make_ocsp_response(bio_err, &resp, req, rdb, rca_certs, rsigner, rkey, rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig, resp_certid_md); if (resp == NULL) goto end; if (cbio != NULL) send_ocsp_response(cbio, resp); } else if (host != NULL) { #ifndef OPENSSL_NO_SOCK resp = process_responder(req, host, port, path, opt_proxy, opt_no_proxy, use_ssl, headers, req_timeout); if (resp == NULL) goto end; #else BIO_printf(bio_err, "Error creating connect BIO - sockets not supported\n"); goto end; #endif } else if (respin != NULL) { derbio = bio_open_default(respin, 'r', FORMAT_ASN1); if (derbio == NULL) goto end; resp = d2i_OCSP_RESPONSE_bio(derbio, NULL); BIO_free(derbio); if (resp == NULL) { BIO_printf(bio_err, "Error reading OCSP response\n"); goto end; } } else { ret = 0; goto end; } done_resp: if (respout != NULL) { derbio = bio_open_default(respout, 'w', FORMAT_ASN1); 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 end; } if (resp_text) OCSP_RESPONSE_print(out, resp, 0); if (cbio != NULL) { if (accept_count != -1 && --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 != NULL) { ret = 0; goto end; } if (store == NULL) { store = setup_verify(CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore); if (!store) goto end; } if (vpmtouched) X509_STORE_set1_param(store, vpm); if (verify_certfile != NULL) { if (!load_certs(verify_certfile, 0, &verify_other, NULL, "validator certificates")) goto end; } bs = OCSP_response_get1_basic(resp); if (bs == NULL) { BIO_printf(bio_err, "Error parsing response\n"); goto end; } ret = 0; if (!noverify) { if (req != NULL && ((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"); } } if (!print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage)) ret = 1; end: ERR_print_errors(bio_err); X509_free(signer); X509_STORE_free(store); X509_VERIFY_PARAM_free(vpm); sk_OPENSSL_STRING_free(rsign_sigopts); EVP_PKEY_free(key); EVP_PKEY_free(rkey); EVP_MD_free(cert_id_md); EVP_MD_free(rsign_md); EVP_MD_free(resp_certid_md); X509_free(cert); OSSL_STACK_OF_X509_free(issuers); X509_free(rsigner); OSSL_STACK_OF_X509_free(rca_certs); free_index(rdb); BIO_free_all(cbio); BIO_free_all(acbio); BIO_free_all(out); OCSP_REQUEST_free(req); OCSP_RESPONSE_free(resp); OCSP_BASICRESP_free(bs); sk_OPENSSL_STRING_free(reqnames); sk_OCSP_CERTID_free(ids); OSSL_STACK_OF_X509_free(sign_other); OSSL_STACK_OF_X509_free(verify_other); sk_CONF_VALUE_pop_free(headers, X509V3_conf_free); OPENSSL_free(thost); OPENSSL_free(tport); OPENSSL_free(tpath); return ret; } #ifdef HTTP_DAEMON static int index_changed(CA_DB *rdb) { struct stat sb; if (rdb != NULL && stat(rdb->dbfname, &sb) != -1) { if (rdb->dbst.st_mtime != sb.st_mtime || rdb->dbst.st_ctime != sb.st_ctime || rdb->dbst.st_ino != sb.st_ino || rdb->dbst.st_dev != sb.st_dev) { syslog(LOG_INFO, "index file changed, reloading"); return 1; } } return 0; } #endif static int add_ocsp_cert(OCSP_REQUEST **req, X509 *cert, const EVP_MD *cert_id_md, X509 *issuer, STACK_OF(OCSP_CERTID) *ids) { OCSP_CERTID *id; if (issuer == NULL) { BIO_printf(bio_err, "No issuer certificate specified\n"); return 0; } if (*req == NULL) *req = OCSP_REQUEST_new(); if (*req == NULL) goto err; id = OCSP_cert_to_id(cert_id_md, cert, issuer); if (id == NULL || !sk_OCSP_CERTID_push(ids, id)) goto err; if (!OCSP_request_add0_id(*req, id)) goto err; return 1; err: BIO_printf(bio_err, "Error Creating OCSP request\n"); return 0; } static int add_ocsp_serial(OCSP_REQUEST **req, char *serial, const EVP_MD *cert_id_md, X509 *issuer, STACK_OF(OCSP_CERTID) *ids) { OCSP_CERTID *id; const X509_NAME *iname; ASN1_BIT_STRING *ikey; ASN1_INTEGER *sno; if (issuer == NULL) { BIO_printf(bio_err, "No issuer certificate specified\n"); return 0; } if (*req == NULL) *req = OCSP_REQUEST_new(); if (*req == NULL) goto err; iname = X509_get_subject_name(issuer); ikey = X509_get0_pubkey_bitstr(issuer); sno = s2i_ASN1_INTEGER(NULL, serial); if (sno == NULL) { BIO_printf(bio_err, "Error converting serial number %s\n", serial); return 0; } id = OCSP_cert_id_new(cert_id_md, iname, ikey, sno); ASN1_INTEGER_free(sno); if (id == NULL || !sk_OCSP_CERTID_push(ids, id)) goto err; if (!OCSP_request_add0_id(*req, id)) goto err; return 1; err: BIO_printf(bio_err, "Error Creating OCSP request\n"); return 0; } static int print_ocsp_summary(BIO *out, OCSP_BASICRESP *bs, OCSP_REQUEST *req, STACK_OF(OPENSSL_STRING) *names, STACK_OF(OCSP_CERTID) *ids, long nsec, long maxage) { OCSP_CERTID *id; const char *name; int i, status, reason; ASN1_GENERALIZEDTIME *rev, *thisupd, *nextupd; int ret = 1; if (req == NULL || !sk_OPENSSL_STRING_num(names)) return 1; if (bs == NULL || !sk_OCSP_CERTID_num(ids)) return 0; for (i = 0; i < sk_OCSP_CERTID_num(ids); i++) { id = sk_OCSP_CERTID_value(ids, i); name = sk_OPENSSL_STRING_value(names, i); BIO_printf(out, "%s: ", name); if (!OCSP_resp_find_status(bs, id, &status, &reason, &rev, &thisupd, &nextupd)) { BIO_puts(out, "ERROR: No Status found.\n"); ret = 0; continue; } if (!OCSP_check_validity(thisupd, nextupd, nsec, maxage)) { BIO_puts(out, "WARNING: Status times invalid.\n"); ERR_print_errors(out); } BIO_printf(out, "%s\n", OCSP_cert_status_str(status)); BIO_puts(out, "\tThis Update: "); ASN1_GENERALIZEDTIME_print(out, thisupd); BIO_puts(out, "\n"); if (nextupd) { BIO_puts(out, "\tNext Update: "); ASN1_GENERALIZEDTIME_print(out, nextupd); BIO_puts(out, "\n"); } if (status != V_OCSP_CERTSTATUS_REVOKED) continue; if (reason != -1) BIO_printf(out, "\tReason: %s\n", OCSP_crl_reason_str(reason)); BIO_puts(out, "\tRevocation Time: "); ASN1_GENERALIZEDTIME_print(out, rev); BIO_puts(out, "\n"); } return ret; } static void make_ocsp_response(BIO *err, OCSP_RESPONSE **resp, OCSP_REQUEST *req, CA_DB *db, STACK_OF(X509) *ca, X509 *rcert, EVP_PKEY *rkey, const EVP_MD *rmd, STACK_OF(OPENSSL_STRING) *sigopts, STACK_OF(X509) *rother, unsigned long flags, int nmin, int ndays, int badsig, const EVP_MD *resp_md) { ASN1_TIME *thisupd = NULL, *nextupd = NULL; OCSP_CERTID *cid; OCSP_BASICRESP *bs = NULL; int i, id_count; EVP_MD_CTX *mctx = NULL; EVP_PKEY_CTX *pkctx = NULL; id_count = OCSP_request_onereq_count(req); if (id_count <= 0) { *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL); goto end; } bs = OCSP_BASICRESP_new(); thisupd = X509_gmtime_adj(NULL, 0); if (ndays != -1) nextupd = X509_time_adj_ex(NULL, ndays, nmin * 60, NULL); for (i = 0; i < id_count; i++) { OCSP_ONEREQ *one; ASN1_INTEGER *serial; char **inf; int jj; int found = 0; ASN1_OBJECT *cert_id_md_oid; const EVP_MD *cert_id_md; OCSP_CERTID *cid_resp_md = NULL; one = OCSP_request_onereq_get0(req, i); cid = OCSP_onereq_get0_id(one); OCSP_id_get0_info(NULL, &cert_id_md_oid, NULL, NULL, cid); cert_id_md = EVP_get_digestbyobj(cert_id_md_oid); if (cert_id_md == NULL) { *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL); goto end; } for (jj = 0; jj < sk_X509_num(ca) && !found; jj++) { X509 *ca_cert = sk_X509_value(ca, jj); OCSP_CERTID *ca_id = OCSP_cert_to_id(cert_id_md, NULL, ca_cert); if (OCSP_id_issuer_cmp(ca_id, cid) == 0) { found = 1; if (resp_md != NULL) cid_resp_md = OCSP_cert_to_id(resp_md, NULL, ca_cert); } OCSP_CERTID_free(ca_id); } OCSP_id_get0_info(NULL, NULL, NULL, &serial, cid); inf = lookup_serial(db, serial); cid = (cid_resp_md != NULL) ? cid_resp_md : cid; if (!found) { OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_UNKNOWN, 0, NULL, thisupd, nextupd); continue; } if (inf == NULL) { OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_UNKNOWN, 0, NULL, thisupd, nextupd); } else if (inf[DB_type][0] == DB_TYPE_VAL) { OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_GOOD, 0, NULL, thisupd, nextupd); } else if (inf[DB_type][0] == DB_TYPE_REV) { ASN1_OBJECT *inst = NULL; ASN1_TIME *revtm = NULL; ASN1_GENERALIZEDTIME *invtm = NULL; OCSP_SINGLERESP *single; int reason = -1; unpack_revinfo(&revtm, &reason, &inst, &invtm, inf[DB_rev_date]); single = OCSP_basic_add1_status(bs, cid, V_OCSP_CERTSTATUS_REVOKED, reason, revtm, thisupd, nextupd); if (single == NULL) { *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL); goto end; } if (invtm != NULL) OCSP_SINGLERESP_add1_ext_i2d(single, NID_invalidity_date, invtm, 0, 0); else if (inst != NULL) OCSP_SINGLERESP_add1_ext_i2d(single, NID_hold_instruction_code, inst, 0, 0); ASN1_OBJECT_free(inst); ASN1_TIME_free(revtm); ASN1_GENERALIZEDTIME_free(invtm); } OCSP_CERTID_free(cid_resp_md); } OCSP_copy_nonce(bs, req); mctx = EVP_MD_CTX_new(); if (mctx == NULL || !EVP_DigestSignInit(mctx, &pkctx, rmd, NULL, rkey)) { *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL); goto end; } for (i = 0; i < sk_OPENSSL_STRING_num(sigopts); i++) { char *sigopt = sk_OPENSSL_STRING_value(sigopts, i); if (pkey_ctrl_string(pkctx, sigopt) <= 0) { BIO_printf(err, "parameter error \"%s\"\n", sigopt); ERR_print_errors(bio_err); *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, NULL); goto end; } } if (!OCSP_basic_sign_ctx(bs, rcert, mctx, rother, flags)) { *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_INTERNALERROR, bs); goto end; } if (badsig) { const ASN1_OCTET_STRING *sig = OCSP_resp_get0_signature(bs); corrupt_signature(sig); } *resp = OCSP_response_create(OCSP_RESPONSE_STATUS_SUCCESSFUL, bs); end: EVP_MD_CTX_free(mctx); ASN1_TIME_free(thisupd); ASN1_TIME_free(nextupd); OCSP_BASICRESP_free(bs); } static char **lookup_serial(CA_DB *db, ASN1_INTEGER *ser) { int i; BIGNUM *bn = NULL; char *itmp, *row[DB_NUMBER], **rrow; for (i = 0; i < DB_NUMBER; i++) row[i] = NULL; bn = ASN1_INTEGER_to_BN(ser, NULL); OPENSSL_assert(bn); if (BN_is_zero(bn)) { itmp = OPENSSL_strdup("00"); OPENSSL_assert(itmp); } else { itmp = BN_bn2hex(bn); } row[DB_serial] = itmp; BN_free(bn); rrow = TXT_DB_get_by_index(db->db, DB_serial, row); OPENSSL_free(itmp); return rrow; } static int do_responder(OCSP_REQUEST **preq, BIO **pcbio, BIO *acbio, int timeout) { #ifndef OPENSSL_NO_SOCK return http_server_get_asn1_req(ASN1_ITEM_rptr(OCSP_REQUEST), (ASN1_VALUE **)preq, NULL, pcbio, acbio, NULL , prog, 1 , timeout); #else BIO_printf(bio_err, "Error getting OCSP request - sockets not supported\n"); *preq = NULL; return 0; #endif } static int send_ocsp_response(BIO *cbio, const OCSP_RESPONSE *resp) { #ifndef OPENSSL_NO_SOCK return http_server_send_asn1_resp(prog, cbio, 0 , "application/ocsp-response", ASN1_ITEM_rptr(OCSP_RESPONSE), (const ASN1_VALUE *)resp); #else BIO_printf(bio_err, "Error sending OCSP response - sockets not supported\n"); return 0; #endif } #ifndef OPENSSL_NO_SOCK OCSP_RESPONSE *process_responder(OCSP_REQUEST *req, const char *host, const char *port, const char *path, const char *proxy, const char *no_proxy, int use_ssl, STACK_OF(CONF_VALUE) *headers, int req_timeout) { SSL_CTX *ctx = NULL; OCSP_RESPONSE *resp = NULL; if (use_ssl == 1) { ctx = SSL_CTX_new(TLS_client_method()); if (ctx == NULL) { BIO_printf(bio_err, "Error creating SSL context.\n"); goto end; } } resp = (OCSP_RESPONSE *) app_http_post_asn1(host, port, path, proxy, no_proxy, ctx, headers, "application/ocsp-request", (ASN1_VALUE *)req, ASN1_ITEM_rptr(OCSP_REQUEST), "application/ocsp-response", req_timeout, ASN1_ITEM_rptr(OCSP_RESPONSE)); if (resp == NULL) BIO_printf(bio_err, "Error querying OCSP responder\n"); end: SSL_CTX_free(ctx); return resp; } #endif
apps
openssl/apps/ocsp.c
openssl
#include <string.h> #include <ctype.h> #include "apps.h" #include "http_server.h" #include "s_apps.h" #include "progs.h" #include "cmp_mock_srv.h" #if defined(_WIN32) && !defined(__BORLANDC__) # define access _access #endif #ifndef F_OK # define F_OK 0 #endif #include <openssl/ui.h> #include <openssl/pkcs12.h> #include <openssl/ssl.h> #include <stdlib.h> #include <openssl/cmp.h> #include <openssl/cmp_util.h> #include <openssl/crmf.h> #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/store.h> #include <openssl/objects.h> #include <openssl/x509.h> static char *prog; static char *opt_config = NULL; #define CMP_SECTION "cmp" #define SECTION_NAME_MAX 40 #define DEFAULT_SECTION "default" static char *opt_section = CMP_SECTION; static int opt_verbosity = OSSL_CMP_LOG_INFO; static int read_config(void); static CONF *conf = NULL; static OSSL_CMP_CTX *cmp_ctx = NULL; typedef enum { CMP_IR, CMP_KUR, CMP_CR, CMP_P10CR, CMP_RR, CMP_GENM } cmp_cmd_t; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) static char *opt_server = NULL; static char *opt_proxy = NULL; static char *opt_no_proxy = NULL; #endif static char *opt_recipient = NULL; static char *opt_path = NULL; static int opt_keep_alive = 1; static int opt_msg_timeout = -1; static int opt_total_timeout = -1; static char *opt_trusted = NULL; static char *opt_untrusted = NULL; static char *opt_srvcert = NULL; static char *opt_expect_sender = NULL; static int opt_ignore_keyusage = 0; static int opt_unprotected_errors = 0; static int opt_no_cache_extracerts = 0; static char *opt_srvcertout = NULL; static char *opt_extracertsout = NULL; static char *opt_cacertsout = NULL; static char *opt_oldwithold = NULL; static char *opt_newwithnew = NULL; static char *opt_newwithold = NULL; static char *opt_oldwithnew = NULL; static char *opt_ref = NULL; static char *opt_secret = NULL; static char *opt_cert = NULL; static char *opt_own_trusted = NULL; static char *opt_key = NULL; static char *opt_keypass = NULL; static char *opt_digest = NULL; static char *opt_mac = NULL; static char *opt_extracerts = NULL; static int opt_unprotected_requests = 0; static char *opt_cmd_s = NULL; static int opt_cmd = -1; static char *opt_geninfo = NULL; static char *opt_infotype_s = NULL; static int opt_infotype = NID_undef; static char *opt_profile = NULL; static char *opt_newkey = NULL; static char *opt_newkeypass = NULL; static char *opt_subject = NULL; static int opt_days = 0; static char *opt_reqexts = NULL; static char *opt_sans = NULL; static int opt_san_nodefault = 0; static char *opt_policies = NULL; static char *opt_policy_oids = NULL; static int opt_policy_oids_critical = 0; static int opt_popo = OSSL_CRMF_POPO_NONE - 1; static char *opt_csr = NULL; static char *opt_out_trusted = NULL; static int opt_implicit_confirm = 0; static int opt_disable_confirm = 0; static char *opt_certout = NULL; static char *opt_chainout = NULL; static char *opt_oldcert = NULL; static char *opt_issuer = NULL; static char *opt_serial = NULL; static int opt_revreason = CRL_REASON_NONE; static char *opt_certform_s = "PEM"; static int opt_certform = FORMAT_PEM; static char *opt_keyform_s = NULL; static int opt_keyform = FORMAT_UNDEF; static char *opt_otherpass = NULL; static char *opt_engine = NULL; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) static int opt_tls_used = 0; static char *opt_tls_cert = NULL; static char *opt_tls_key = NULL; static char *opt_tls_keypass = NULL; static char *opt_tls_extra = NULL; static char *opt_tls_trusted = NULL; static char *opt_tls_host = NULL; #endif static int opt_batch = 0; static int opt_repeat = 1; static char *opt_reqin = NULL; static int opt_reqin_new_tid = 0; static char *opt_reqout = NULL; static char *opt_reqout_only = NULL; static int reqout_only_done = 0; static char *opt_rspin = NULL; static int rspin_in_use = 0; static char *opt_rspout = NULL; static int opt_use_mock_srv = 0; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) static char *opt_port = NULL; static int opt_max_msgs = 0; #endif static char *opt_srv_ref = NULL; static char *opt_srv_secret = NULL; static char *opt_srv_cert = NULL; static char *opt_srv_key = NULL; static char *opt_srv_keypass = NULL; static char *opt_srv_trusted = NULL; static char *opt_srv_untrusted = NULL; static char *opt_ref_cert = NULL; static char *opt_rsp_cert = NULL; static char *opt_rsp_extracerts = NULL; static char *opt_rsp_capubs = NULL; static char *opt_rsp_newwithnew = NULL; static char *opt_rsp_newwithold = NULL; static char *opt_rsp_oldwithnew = NULL; static int opt_poll_count = 0; static int opt_check_after = 1; static int opt_grant_implicitconf = 0; static int opt_pkistatus = OSSL_CMP_PKISTATUS_accepted; static int opt_failure = INT_MIN; static int opt_failurebits = 0; static char *opt_statusstring = NULL; static int opt_send_error = 0; static int opt_send_unprotected = 0; static int opt_send_unprot_err = 0; static int opt_accept_unprotected = 0; static int opt_accept_unprot_err = 0; static int opt_accept_raverified = 0; static X509_VERIFY_PARAM *vpm = NULL; typedef enum OPTION_choice { OPT_COMMON, OPT_CONFIG, OPT_SECTION, OPT_VERBOSITY, OPT_CMD, OPT_INFOTYPE, OPT_PROFILE, OPT_GENINFO, OPT_NEWKEY, OPT_NEWKEYPASS, OPT_SUBJECT, OPT_DAYS, OPT_REQEXTS, OPT_SANS, OPT_SAN_NODEFAULT, OPT_POLICIES, OPT_POLICY_OIDS, OPT_POLICY_OIDS_CRITICAL, OPT_POPO, OPT_CSR, OPT_OUT_TRUSTED, OPT_IMPLICIT_CONFIRM, OPT_DISABLE_CONFIRM, OPT_CERTOUT, OPT_CHAINOUT, OPT_OLDCERT, OPT_ISSUER, OPT_SERIAL, OPT_REVREASON, #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) OPT_SERVER, OPT_PROXY, OPT_NO_PROXY, #endif OPT_RECIPIENT, OPT_PATH, OPT_KEEP_ALIVE, OPT_MSG_TIMEOUT, OPT_TOTAL_TIMEOUT, OPT_TRUSTED, OPT_UNTRUSTED, OPT_SRVCERT, OPT_EXPECT_SENDER, OPT_IGNORE_KEYUSAGE, OPT_UNPROTECTED_ERRORS, OPT_NO_CACHE_EXTRACERTS, OPT_SRVCERTOUT, OPT_EXTRACERTSOUT, OPT_CACERTSOUT, OPT_OLDWITHOLD, OPT_NEWWITHNEW, OPT_NEWWITHOLD, OPT_OLDWITHNEW, OPT_REF, OPT_SECRET, OPT_CERT, OPT_OWN_TRUSTED, OPT_KEY, OPT_KEYPASS, OPT_DIGEST, OPT_MAC, OPT_EXTRACERTS, OPT_UNPROTECTED_REQUESTS, OPT_CERTFORM, OPT_KEYFORM, OPT_OTHERPASS, #ifndef OPENSSL_NO_ENGINE OPT_ENGINE, #endif OPT_PROV_ENUM, OPT_R_ENUM, #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) OPT_TLS_USED, OPT_TLS_CERT, OPT_TLS_KEY, OPT_TLS_KEYPASS, OPT_TLS_EXTRA, OPT_TLS_TRUSTED, OPT_TLS_HOST, #endif OPT_BATCH, OPT_REPEAT, OPT_REQIN, OPT_REQIN_NEW_TID, OPT_REQOUT, OPT_REQOUT_ONLY, OPT_RSPIN, OPT_RSPOUT, OPT_USE_MOCK_SRV, #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) OPT_PORT, OPT_MAX_MSGS, #endif OPT_SRV_REF, OPT_SRV_SECRET, OPT_SRV_CERT, OPT_SRV_KEY, OPT_SRV_KEYPASS, OPT_SRV_TRUSTED, OPT_SRV_UNTRUSTED, OPT_REF_CERT, OPT_RSP_CERT, OPT_RSP_EXTRACERTS, OPT_RSP_CAPUBS, OPT_RSP_NEWWITHNEW, OPT_RSP_NEWWITHOLD, OPT_RSP_OLDWITHNEW, OPT_POLL_COUNT, OPT_CHECK_AFTER, OPT_GRANT_IMPLICITCONF, OPT_PKISTATUS, OPT_FAILURE, OPT_FAILUREBITS, OPT_STATUSSTRING, OPT_SEND_ERROR, OPT_SEND_UNPROTECTED, OPT_SEND_UNPROT_ERR, OPT_ACCEPT_UNPROTECTED, OPT_ACCEPT_UNPROT_ERR, OPT_ACCEPT_RAVERIFIED, OPT_V_ENUM } OPTION_CHOICE; const OPTIONS cmp_options[] = { {"help", OPT_HELP, '-', "Display this summary"}, {"config", OPT_CONFIG, 's', "Configuration file to use. \"\" = none. Default from env variable OPENSSL_CONF"}, {"section", OPT_SECTION, 's', "Section(s) in config file to get options from. \"\" = 'default'. Default 'cmp'"}, {"verbosity", OPT_VERBOSITY, 'N', "Log level; 3=ERR, 4=WARN, 6=INFO, 7=DEBUG, 8=TRACE. Default 6 = INFO"}, OPT_SECTION("Generic message"), {"cmd", OPT_CMD, 's', "CMP request to send: ir/cr/kur/p10cr/rr/genm"}, {"infotype", OPT_INFOTYPE, 's', "InfoType name for requesting specific info in genm, with specific support"}, {OPT_MORE_STR, 0, 0, "for 'caCerts' and 'rootCaCert'"}, {"profile", OPT_PROFILE, 's', "Certificate profile name to place in generalInfo field of request PKIHeader"}, {"geninfo", OPT_GENINFO, 's', "Comma-separated list of OID and value to place in generalInfo PKIHeader"}, {OPT_MORE_STR, 0, 0, "of form <OID>:int:<n> or <OID>:str:<s>, e.g. \'1.2.3.4:int:56789, id-kp:str:name'"}, OPT_SECTION("Certificate enrollment"), {"newkey", OPT_NEWKEY, 's', "Private or public key for the requested cert. Default: CSR key or client key"}, {"newkeypass", OPT_NEWKEYPASS, 's', "New private key pass phrase source"}, {"subject", OPT_SUBJECT, 's', "Distinguished Name (DN) of subject to use in the requested cert template"}, {OPT_MORE_STR, 0, 0, "For kur, default is subject of -csr arg or reference cert (see -oldcert)"}, {OPT_MORE_STR, 0, 0, "this default is used for ir and cr only if no Subject Alt Names are set"}, {"days", OPT_DAYS, 'N', "Requested validity time of the new certificate in number of days"}, {"reqexts", OPT_REQEXTS, 's', "Name of config file section defining certificate request extensions."}, {OPT_MORE_STR, 0, 0, "Augments or replaces any extensions contained CSR given with -csr"}, {"sans", OPT_SANS, 's', "Subject Alt Names (IPADDR/DNS/URI) to add as (critical) cert req extension"}, {"san_nodefault", OPT_SAN_NODEFAULT, '-', "Do not take default SANs from reference certificate (see -oldcert)"}, {"policies", OPT_POLICIES, 's', "Name of config file section defining policies certificate request extension"}, {"policy_oids", OPT_POLICY_OIDS, 's', "Policy OID(s) to add as policies certificate request extension"}, {"policy_oids_critical", OPT_POLICY_OIDS_CRITICAL, '-', "Flag the policy OID(s) given with -policy_oids as critical"}, {"popo", OPT_POPO, 'n', "Proof-of-Possession (POPO) method to use for ir/cr/kur where"}, {OPT_MORE_STR, 0, 0, "-1 = NONE, 0 = RAVERIFIED, 1 = SIGNATURE (default), 2 = KEYENC"}, {"csr", OPT_CSR, 's', "PKCS#10 CSR file in PEM or DER format to convert or to use in p10cr"}, {"out_trusted", OPT_OUT_TRUSTED, 's', "Certificates to trust when verifying newly enrolled certificates"}, {"implicit_confirm", OPT_IMPLICIT_CONFIRM, '-', "Request implicit confirmation of newly enrolled certificates"}, {"disable_confirm", OPT_DISABLE_CONFIRM, '-', "Do not confirm newly enrolled certificate w/o requesting implicit"}, {OPT_MORE_STR, 0, 0, "confirmation. WARNING: This leads to behavior violating RFC 4210"}, {"certout", OPT_CERTOUT, 's', "File to save newly enrolled certificate"}, {"chainout", OPT_CHAINOUT, 's', "File to save the chain of newly enrolled certificate"}, OPT_SECTION("Certificate enrollment and revocation"), {"oldcert", OPT_OLDCERT, 's', "Certificate to be updated (defaulting to -cert) or to be revoked in rr;"}, {OPT_MORE_STR, 0, 0, "also used as reference (defaulting to -cert) for subject DN and SANs."}, {OPT_MORE_STR, 0, 0, "Issuer is used as recipient unless -recipient, -srvcert, or -issuer given"}, {"issuer", OPT_ISSUER, 's', "DN of the issuer to place in the certificate template of ir/cr/kur/rr;"}, {OPT_MORE_STR, 0, 0, "also used as recipient if neither -recipient nor -srvcert are given"}, {"serial", OPT_SERIAL, 's', "Serial number of certificate to be revoked in revocation request (rr)"}, {"revreason", OPT_REVREASON, 'n', "Reason code to include in revocation request (rr); possible values:"}, {OPT_MORE_STR, 0, 0, "0..6, 8..10 (see RFC5280, 5.3.1) or -1. Default -1 = none included"}, OPT_SECTION("Message transfer"), #if defined(OPENSSL_NO_SOCK) || defined(OPENSSL_NO_HTTP) {OPT_MORE_STR, 0, 0, "NOTE: -server, -proxy, and -no_proxy not supported due to no-sock/no-http build"}, #else {"server", OPT_SERVER, 's', "[http[s]: {OPT_MORE_STR, 0, 0, "address may be a DNS name or an IP address; path can be overridden by -path"}, {"proxy", OPT_PROXY, 's', "[http[s]: {"no_proxy", OPT_NO_PROXY, 's', "List of addresses of servers not to use HTTP(S) proxy for"}, {OPT_MORE_STR, 0, 0, "Default from environment variable 'no_proxy', else 'NO_PROXY', else none"}, #endif {"recipient", OPT_RECIPIENT, 's', "DN of CA. Default: subject of -srvcert, -issuer, issuer of -oldcert or -cert"}, {"path", OPT_PATH, 's', "HTTP path (aka CMP alias) at the CMP server. Default from -server, else \"/\""}, {"keep_alive", OPT_KEEP_ALIVE, 'N', "Persistent HTTP connections. 0: no, 1 (the default): request, 2: require"}, {"msg_timeout", OPT_MSG_TIMEOUT, 'N', "Number of seconds allowed per CMP message round trip, or 0 for infinite"}, {"total_timeout", OPT_TOTAL_TIMEOUT, 'N', "Overall time an enrollment incl. polling may take. Default 0 = infinite"}, OPT_SECTION("Server authentication"), {"trusted", OPT_TRUSTED, 's', "Certificates to use as trust anchors when verifying signed CMP responses"}, {OPT_MORE_STR, 0, 0, "unless -srvcert is given"}, {"untrusted", OPT_UNTRUSTED, 's', "Intermediate CA certs for chain construction for CMP/TLS/enrolled certs"}, {"srvcert", OPT_SRVCERT, 's', "Server cert to pin and trust directly when verifying signed CMP responses"}, {"expect_sender", OPT_EXPECT_SENDER, 's', "DN of expected sender of responses. Defaults to subject of -srvcert, if any"}, {"ignore_keyusage", OPT_IGNORE_KEYUSAGE, '-', "Ignore CMP signer cert key usage, else 'digitalSignature' must be allowed"}, {"unprotected_errors", OPT_UNPROTECTED_ERRORS, '-', "Accept missing or invalid protection of regular error messages and negative"}, {OPT_MORE_STR, 0, 0, "certificate responses (ip/cp/kup), revocation responses (rp), and PKIConf"}, {OPT_MORE_STR, 0, 0, "WARNING: This setting leads to behavior allowing violation of RFC 4210"}, {"no_cache_extracerts", OPT_NO_CACHE_EXTRACERTS, '-', "Do not keep certificates received in the extraCerts CMP message field"}, { "srvcertout", OPT_SRVCERTOUT, 's', "File to save the server cert used and validated for CMP response protection"}, {"extracertsout", OPT_EXTRACERTSOUT, 's', "File to save extra certificates received in the extraCerts field"}, {"cacertsout", OPT_CACERTSOUT, 's', "File to save CA certs received in caPubs field or genp with id-it-caCerts"}, { "oldwithold", OPT_OLDWITHOLD, 's', "Root CA certificate to request update for in genm of type rootCaCert"}, { "newwithnew", OPT_NEWWITHNEW, 's', "File to save NewWithNew cert received in genp of type rootCaKeyUpdate"}, { "newwithold", OPT_NEWWITHOLD, 's', "File to save NewWithOld cert received in genp of type rootCaKeyUpdate"}, { "oldwithnew", OPT_OLDWITHNEW, 's', "File to save OldWithNew cert received in genp of type rootCaKeyUpdate"}, OPT_SECTION("Client authentication"), {"ref", OPT_REF, 's', "Reference value to use as senderKID in case no -cert is given"}, {"secret", OPT_SECRET, 's', "Prefer PBM (over signatures) for protecting msgs with given password source"}, {"cert", OPT_CERT, 's', "Client's CMP signer certificate; its public key must match the -key argument"}, {OPT_MORE_STR, 0, 0, "This also used as default reference for subject DN and SANs."}, {OPT_MORE_STR, 0, 0, "Any further certs included are appended to the untrusted certs"}, {"own_trusted", OPT_OWN_TRUSTED, 's', "Optional certs to verify chain building for own CMP signer cert"}, {"key", OPT_KEY, 's', "CMP signer private key, not used when -secret given"}, {"keypass", OPT_KEYPASS, 's', "Client private key (and cert and old cert) pass phrase source"}, {"digest", OPT_DIGEST, 's', "Digest to use in message protection and POPO signatures. Default \"sha256\""}, {"mac", OPT_MAC, 's', "MAC algorithm to use in PBM-based message protection. Default \"hmac-sha1\""}, {"extracerts", OPT_EXTRACERTS, 's', "Certificates to append in extraCerts field of outgoing messages."}, {OPT_MORE_STR, 0, 0, "This can be used as the default CMP signer cert chain to include"}, {"unprotected_requests", OPT_UNPROTECTED_REQUESTS, '-', "Send request messages without CMP-level protection"}, OPT_SECTION("Credentials format"), {"certform", OPT_CERTFORM, 's', "Format (PEM or DER) to use when saving a certificate to a file. Default PEM"}, {"keyform", OPT_KEYFORM, 's', "Format of the key input (ENGINE, other values ignored)"}, {"otherpass", OPT_OTHERPASS, 's', "Pass phrase source potentially needed for loading certificates of others"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use crypto engine with given identifier, possibly a hardware device."}, {OPT_MORE_STR, 0, 0, "Engines may also be defined in OpenSSL config file engine section."}, #endif OPT_PROV_OPTIONS, OPT_R_OPTIONS, OPT_SECTION("TLS connection"), #if defined(OPENSSL_NO_SOCK) || defined(OPENSSL_NO_HTTP) {OPT_MORE_STR, 0, 0, "NOTE: -tls_used and all other TLS options not supported due to no-sock/no-http build"}, #else {"tls_used", OPT_TLS_USED, '-', "Enable using TLS (also when other TLS options are not set)"}, {"tls_cert", OPT_TLS_CERT, 's', "Client's TLS certificate. May include chain to be provided to TLS server"}, {"tls_key", OPT_TLS_KEY, 's', "Private key for the client's TLS certificate"}, {"tls_keypass", OPT_TLS_KEYPASS, 's', "Pass phrase source for the client's private TLS key (and TLS cert)"}, {"tls_extra", OPT_TLS_EXTRA, 's', "Extra certificates to provide to TLS server during TLS handshake"}, {"tls_trusted", OPT_TLS_TRUSTED, 's', "Trusted certificates to use for verifying the TLS server certificate;"}, {OPT_MORE_STR, 0, 0, "this implies hostname validation"}, {"tls_host", OPT_TLS_HOST, 's', "Address to be checked (rather than -server) during TLS hostname validation"}, #endif OPT_SECTION("Client-side debugging"), {"batch", OPT_BATCH, '-', "Do not interactively prompt for input when a password is required etc."}, {"repeat", OPT_REPEAT, 'p', "Invoke the transaction the given positive number of times. Default 1"}, {"reqin", OPT_REQIN, 's', "Take sequence of CMP requests to send to server from file(s)"}, {"reqin_new_tid", OPT_REQIN_NEW_TID, '-', "Use fresh transactionID for CMP requests read from -reqin"}, {"reqout", OPT_REQOUT, 's', "Save sequence of CMP requests created by the client to file(s)"}, {"reqout_only", OPT_REQOUT_ONLY, 's', "Save first CMP request created by the client to file and exit"}, {"rspin", OPT_RSPIN, 's', "Process sequence of CMP responses provided in file(s), skipping server"}, {"rspout", OPT_RSPOUT, 's', "Save sequence of actually used CMP responses to file(s)"}, {"use_mock_srv", OPT_USE_MOCK_SRV, '-', "Use internal mock server at API level, bypassing socket-based HTTP"}, OPT_SECTION("Mock server"), #if defined(OPENSSL_NO_SOCK) || defined(OPENSSL_NO_HTTP) {OPT_MORE_STR, 0, 0, "NOTE: -port and -max_msgs not supported due to no-sock/no-http build"}, #else {"port", OPT_PORT, 's', "Act as HTTP-based mock server listening on given port"}, {"max_msgs", OPT_MAX_MSGS, 'N', "max number of messages handled by HTTP mock server. Default: 0 = unlimited"}, #endif {"srv_ref", OPT_SRV_REF, 's', "Reference value to use as senderKID of server in case no -srv_cert is given"}, {"srv_secret", OPT_SRV_SECRET, 's', "Password source for server authentication with a pre-shared key (secret)"}, {"srv_cert", OPT_SRV_CERT, 's', "Certificate of the server"}, {"srv_key", OPT_SRV_KEY, 's', "Private key used by the server for signing messages"}, {"srv_keypass", OPT_SRV_KEYPASS, 's', "Server private key (and cert) pass phrase source"}, {"srv_trusted", OPT_SRV_TRUSTED, 's', "Trusted certificates for client authentication"}, {"srv_untrusted", OPT_SRV_UNTRUSTED, 's', "Intermediate certs that may be useful for verifying CMP protection"}, {"ref_cert", OPT_RSP_CERT, 's', "Certificate to be expected for rr and any oldCertID in kur messages"}, {"rsp_cert", OPT_RSP_CERT, 's', "Certificate to be returned as mock enrollment result"}, {"rsp_extracerts", OPT_RSP_EXTRACERTS, 's', "Extra certificates to be included in mock certification responses"}, {"rsp_capubs", OPT_RSP_CAPUBS, 's', "CA certificates to be included in mock ip response"}, {"rsp_newwithnew", OPT_RSP_NEWWITHNEW, 's', "New root CA certificate to include in genp of type rootCaKeyUpdate"}, {"rsp_newwithold", OPT_RSP_NEWWITHOLD, 's', "NewWithOld transition cert to include in genp of type rootCaKeyUpdate"}, {"rsp_oldwithnew", OPT_RSP_OLDWITHNEW, 's', "OldWithNew transition cert to include in genp of type rootCaKeyUpdate"}, {"poll_count", OPT_POLL_COUNT, 'N', "Number of times the client must poll before receiving a certificate"}, {"check_after", OPT_CHECK_AFTER, 'N', "The check_after value (time to wait) to include in poll response"}, {"grant_implicitconf", OPT_GRANT_IMPLICITCONF, '-', "Grant implicit confirmation of newly enrolled certificate"}, {"pkistatus", OPT_PKISTATUS, 'N', "PKIStatus to be included in server response. Possible values: 0..6"}, {"failure", OPT_FAILURE, 'N', "A single failure info bit number to include in server response, 0..26"}, {"failurebits", OPT_FAILUREBITS, 'N', "Number representing failure bits to include in server response, 0..2^27 - 1"}, {"statusstring", OPT_STATUSSTRING, 's', "Status string to be included in server response"}, {"send_error", OPT_SEND_ERROR, '-', "Force server to reply with error message"}, {"send_unprotected", OPT_SEND_UNPROTECTED, '-', "Send response messages without CMP-level protection"}, {"send_unprot_err", OPT_SEND_UNPROT_ERR, '-', "In case of negative responses, server shall send unprotected error messages,"}, {OPT_MORE_STR, 0, 0, "certificate responses (ip/cp/kup), and revocation responses (rp)."}, {OPT_MORE_STR, 0, 0, "WARNING: This setting leads to behavior violating RFC 4210"}, {"accept_unprotected", OPT_ACCEPT_UNPROTECTED, '-', "Accept missing or invalid protection of requests"}, {"accept_unprot_err", OPT_ACCEPT_UNPROT_ERR, '-', "Accept unprotected error messages from client"}, {"accept_raverified", OPT_ACCEPT_RAVERIFIED, '-', "Accept RAVERIFIED as proof-of-possession (POPO)"}, OPT_V_OPTIONS, {NULL} }; typedef union { char **txt; int *num; long *num_long; } varref; static varref cmp_vars[] = { {&opt_config}, {&opt_section}, {(char **)&opt_verbosity}, {&opt_cmd_s}, {&opt_infotype_s}, {&opt_profile}, {&opt_geninfo}, {&opt_newkey}, {&opt_newkeypass}, {&opt_subject}, {(char **)&opt_days}, {&opt_reqexts}, {&opt_sans}, {(char **)&opt_san_nodefault}, {&opt_policies}, {&opt_policy_oids}, {(char **)&opt_policy_oids_critical}, {(char **)&opt_popo}, {&opt_csr}, {&opt_out_trusted}, {(char **)&opt_implicit_confirm}, {(char **)&opt_disable_confirm}, {&opt_certout}, {&opt_chainout}, {&opt_oldcert}, {&opt_issuer}, {&opt_serial}, {(char **)&opt_revreason}, #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) {&opt_server}, {&opt_proxy}, {&opt_no_proxy}, #endif {&opt_recipient}, {&opt_path}, {(char **)&opt_keep_alive}, {(char **)&opt_msg_timeout}, {(char **)&opt_total_timeout}, {&opt_trusted}, {&opt_untrusted}, {&opt_srvcert}, {&opt_expect_sender}, {(char **)&opt_ignore_keyusage}, {(char **)&opt_unprotected_errors}, {(char **)&opt_no_cache_extracerts}, {&opt_srvcertout}, {&opt_extracertsout}, {&opt_cacertsout}, {&opt_oldwithold}, {&opt_newwithnew}, {&opt_newwithold}, {&opt_oldwithnew}, {&opt_ref}, {&opt_secret}, {&opt_cert}, {&opt_own_trusted}, {&opt_key}, {&opt_keypass}, {&opt_digest}, {&opt_mac}, {&opt_extracerts}, {(char **)&opt_unprotected_requests}, {&opt_certform_s}, {&opt_keyform_s}, {&opt_otherpass}, #ifndef OPENSSL_NO_ENGINE {&opt_engine}, #endif #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) {(char **)&opt_tls_used}, {&opt_tls_cert}, {&opt_tls_key}, {&opt_tls_keypass}, {&opt_tls_extra}, {&opt_tls_trusted}, {&opt_tls_host}, #endif {(char **)&opt_batch}, {(char **)&opt_repeat}, {&opt_reqin}, {(char **)&opt_reqin_new_tid}, {&opt_reqout}, {&opt_reqout_only}, {&opt_rspin}, {&opt_rspout}, {(char **)&opt_use_mock_srv}, #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) {&opt_port}, {(char **)&opt_max_msgs}, #endif {&opt_srv_ref}, {&opt_srv_secret}, {&opt_srv_cert}, {&opt_srv_key}, {&opt_srv_keypass}, {&opt_srv_trusted}, {&opt_srv_untrusted}, {&opt_ref_cert}, {&opt_rsp_cert}, {&opt_rsp_extracerts}, {&opt_rsp_capubs}, {&opt_rsp_newwithnew}, {&opt_rsp_newwithold}, {&opt_rsp_oldwithnew}, {(char **)&opt_poll_count}, {(char **)&opt_check_after}, {(char **)&opt_grant_implicitconf}, {(char **)&opt_pkistatus}, {(char **)&opt_failure}, {(char **)&opt_failurebits}, {&opt_statusstring}, {(char **)&opt_send_error}, {(char **)&opt_send_unprotected}, {(char **)&opt_send_unprot_err}, {(char **)&opt_accept_unprotected}, {(char **)&opt_accept_unprot_err}, {(char **)&opt_accept_raverified}, {NULL} }; #define FUNC (strcmp(OPENSSL_FUNC, "(unknown function)") == 0 \ ? "CMP" : OPENSSL_FUNC) #define CMP_print(bio, level, prefix, msg, a1, a2, a3) \ ((void)(level > opt_verbosity ? 0 : \ (BIO_printf(bio, "%s:%s:%d:CMP %s: " msg "\n", \ FUNC, OPENSSL_FILE, OPENSSL_LINE, prefix, a1, a2, a3)))) #define CMP_DEBUG(m, a1, a2, a3) \ CMP_print(bio_out, OSSL_CMP_LOG_DEBUG, "debug", m, a1, a2, a3) #define CMP_debug(msg) CMP_DEBUG(msg"%s%s%s", "", "", "") #define CMP_debug1(msg, a1) CMP_DEBUG(msg"%s%s", a1, "", "") #define CMP_debug2(msg, a1, a2) CMP_DEBUG(msg"%s", a1, a2, "") #define CMP_debug3(msg, a1, a2, a3) CMP_DEBUG(msg, a1, a2, a3) #define CMP_INFO(msg, a1, a2, a3) \ CMP_print(bio_out, OSSL_CMP_LOG_INFO, "info", msg, a1, a2, a3) #define CMP_info(msg) CMP_INFO(msg"%s%s%s", "", "", "") #define CMP_info1(msg, a1) CMP_INFO(msg"%s%s", a1, "", "") #define CMP_info2(msg, a1, a2) CMP_INFO(msg"%s", a1, a2, "") #define CMP_info3(msg, a1, a2, a3) CMP_INFO(msg, a1, a2, a3) #define CMP_WARN(m, a1, a2, a3) \ CMP_print(bio_out, OSSL_CMP_LOG_WARNING, "warning", m, a1, a2, a3) #define CMP_warn(msg) CMP_WARN(msg"%s%s%s", "", "", "") #define CMP_warn1(msg, a1) CMP_WARN(msg"%s%s", a1, "", "") #define CMP_warn2(msg, a1, a2) CMP_WARN(msg"%s", a1, a2, "") #define CMP_warn3(msg, a1, a2, a3) CMP_WARN(msg, a1, a2, a3) #define CMP_ERR(msg, a1, a2, a3) \ CMP_print(bio_err, OSSL_CMP_LOG_ERR, "error", msg, a1, a2, a3) #define CMP_err(msg) CMP_ERR(msg"%s%s%s", "", "", "") #define CMP_err1(msg, a1) CMP_ERR(msg"%s%s", a1, "", "") #define CMP_err2(msg, a1, a2) CMP_ERR(msg"%s", a1, a2, "") #define CMP_err3(msg, a1, a2, a3) CMP_ERR(msg, a1, a2, a3) static int print_to_bio_out(const char *func, const char *file, int line, OSSL_CMP_severity level, const char *msg) { return OSSL_CMP_print_to_bio(bio_out, func, file, line, level, msg); } static int print_to_bio_err(const char *func, const char *file, int line, OSSL_CMP_severity level, const char *msg) { return OSSL_CMP_print_to_bio(bio_err, func, file, line, level, msg); } static int set_verbosity(int level) { if (level < OSSL_CMP_LOG_EMERG || level > OSSL_CMP_LOG_MAX) { CMP_err1("Logging verbosity level %d out of range (0 .. 8)", level); return 0; } opt_verbosity = level; return 1; } static EVP_PKEY *load_key_pwd(const char *uri, int format, const char *pass, ENGINE *eng, const char *desc) { char *pass_string = get_passwd(pass, desc); EVP_PKEY *pkey = load_key(uri, format, 0, pass_string, eng, desc); clear_free(pass_string); return pkey; } static X509 *load_cert_pwd(const char *uri, const char *pass, const char *desc) { X509 *cert; char *pass_string = get_passwd(pass, desc); cert = load_cert_pass(uri, FORMAT_UNDEF, 0, pass_string, desc); clear_free(pass_string); return cert; } static int truststore_set_host_etc(X509_STORE *ts, const char *host) { X509_VERIFY_PARAM *ts_vpm = X509_STORE_get0_param(ts); if (!X509_VERIFY_PARAM_set1_host(ts_vpm, NULL, 0) || !X509_VERIFY_PARAM_set1_ip(ts_vpm, NULL, 0) || !X509_VERIFY_PARAM_set1_email(ts_vpm, NULL, 0)) return 0; X509_VERIFY_PARAM_set_hostflags(ts_vpm, X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT | X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); return (host != NULL && X509_VERIFY_PARAM_set1_ip_asc(ts_vpm, host)) || X509_VERIFY_PARAM_set1_host(ts_vpm, host, 0); } static int write_PKIMESSAGE(const OSSL_CMP_MSG *msg, char **filenames) { char *file; if (msg == NULL || filenames == NULL) { CMP_err("NULL arg to write_PKIMESSAGE"); return 0; } if (*filenames == NULL) { CMP_err("not enough file names provided for writing PKIMessage"); return 0; } file = *filenames; *filenames = next_item(file); if (OSSL_CMP_MSG_write(file, msg) < 0) { CMP_err1("cannot write PKIMessage to file '%s'", file); return 0; } return 1; } static OSSL_CMP_MSG *read_PKIMESSAGE(const char *desc, char **filenames) { char *file; OSSL_CMP_MSG *ret; if (filenames == NULL || desc == NULL) { CMP_err("NULL arg to read_PKIMESSAGE"); return NULL; } if (*filenames == NULL) { CMP_err("not enough file names provided for reading PKIMessage"); return NULL; } file = *filenames; *filenames = next_item(file); ret = OSSL_CMP_MSG_read(file, app_get0_libctx(), app_get0_propq()); if (ret == NULL) CMP_err1("cannot read PKIMessage from file '%s'", file); else CMP_info2("%s %s", desc, file); return ret; } static OSSL_CMP_MSG *read_write_req_resp(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_MSG *req_new = NULL; OSSL_CMP_MSG *res = NULL; OSSL_CMP_PKIHEADER *hdr; const char *prev_opt_rspin = opt_rspin; if (opt_reqout_only != NULL) { if (OSSL_CMP_MSG_write(opt_reqout_only, req) < 0) CMP_err1("cannot write request PKIMessage to file '%s'", opt_reqout_only); else reqout_only_done = 1; return NULL; } if (opt_reqout != NULL && !write_PKIMESSAGE(req, &opt_reqout)) goto err; if (opt_reqin != NULL && opt_rspin == NULL) { if ((req_new = read_PKIMESSAGE("actually sending", &opt_reqin)) == NULL) goto err; if (opt_reqin_new_tid && !OSSL_CMP_MSG_update_transactionID(ctx, req_new)) goto err; if (!OSSL_CMP_MSG_update_recipNonce(ctx, req_new)) goto err; } if (opt_rspin != NULL) { res = read_PKIMESSAGE("actually using", &opt_rspin); } else { const OSSL_CMP_MSG *actual_req = req_new != NULL ? req_new : req; if (opt_use_mock_srv) { if (rspin_in_use) CMP_warn("too few -rspin filename arguments; resorting to using mock server"); res = OSSL_CMP_CTX_server_perform(ctx, actual_req); } else { #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_server == NULL) { CMP_err("missing -server or -use_mock_srv option, or too few -rspin filename arguments"); goto err; } if (rspin_in_use) CMP_warn("too few -rspin filename arguments; resorting to contacting server"); res = OSSL_CMP_MSG_http_perform(ctx, actual_req); #else CMP_err("-server not supported on no-sock/no-http build; missing -use_mock_srv option or too few -rspin filename arguments"); #endif } rspin_in_use = 0; } if (res == NULL) goto err; if (req_new != NULL || prev_opt_rspin != NULL) { ASN1_OCTET_STRING *nonce; ASN1_OCTET_STRING *tid; hdr = OSSL_CMP_MSG_get0_header(res); nonce = OSSL_CMP_HDR_get0_recipNonce(hdr); tid = OSSL_CMP_HDR_get0_transactionID(hdr); if (!OSSL_CMP_CTX_set1_senderNonce(ctx, nonce) || !OSSL_CMP_CTX_set1_transactionID(ctx, tid)) { OSSL_CMP_MSG_free(res); res = NULL; goto err; } } if (opt_rspout != NULL && !write_PKIMESSAGE(res, &opt_rspout)) { OSSL_CMP_MSG_free(res); res = NULL; } err: OSSL_CMP_MSG_free(req_new); return res; } static int set_name(const char *str, int (*set_fn) (OSSL_CMP_CTX *ctx, const X509_NAME *name), OSSL_CMP_CTX *ctx, const char *desc) { if (str != NULL) { X509_NAME *n = parse_name(str, MBSTRING_ASC, 1, desc); if (n == NULL) return 0; if (!(*set_fn) (ctx, n)) { X509_NAME_free(n); CMP_err("out of memory"); return 0; } X509_NAME_free(n); } return 1; } static int set_gennames(OSSL_CMP_CTX *ctx, char *names, const char *desc) { char *next; for (; names != NULL; names = next) { GENERAL_NAME *n; next = next_item(names); if (strcmp(names, "critical") == 0) { (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL, 1); continue; } (void)ERR_set_mark(); n = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_IPADD, names, 0); if (n == NULL) n = a2i_GENERAL_NAME(NULL, NULL, NULL, strchr(names, '@') != NULL ? GEN_EMAIL : strchr(names, ':') != NULL ? GEN_URI : GEN_DNS, names, 0); (void)ERR_pop_to_mark(); if (n == NULL) { CMP_err2("bad syntax of %s '%s'", desc, names); return 0; } if (!OSSL_CMP_CTX_push1_subjectAltName(ctx, n)) { GENERAL_NAME_free(n); CMP_err("out of memory"); return 0; } GENERAL_NAME_free(n); } return 1; } static X509_STORE *load_trusted(char *input, int for_new_cert, const char *desc) { X509_STORE *ts = load_certstore(input, opt_otherpass, desc, vpm); if (ts == NULL) return NULL; X509_STORE_set_verify_cb(ts, X509_STORE_CTX_print_verify_cb); if (X509_STORE_set1_param(ts, vpm ) && (for_new_cert || truststore_set_host_etc(ts, NULL))) return ts; BIO_printf(bio_err, "error setting verification parameters for %s\n", desc); OSSL_CMP_CTX_print_errors(cmp_ctx); X509_STORE_free(ts); return NULL; } typedef int (*add_X509_fn_t)(void *ctx, const X509 *cert); static int setup_cert(void *ctx, const char *file, const char *pass, const char *desc, add_X509_fn_t set1_fn) { X509 *cert; int ok; if (file == NULL) return 1; if ((cert = load_cert_pwd(file, pass, desc)) == NULL) return 0; ok = (*set1_fn)(ctx, cert); X509_free(cert); return ok; } typedef int (*add_X509_stack_fn_t)(void *ctx, const STACK_OF(X509) *certs); static int setup_certs(char *files, const char *desc, void *ctx, add_X509_stack_fn_t set1_fn) { STACK_OF(X509) *certs; int ok; if (files == NULL) return 1; if ((certs = load_certs_multifile(files, opt_otherpass, desc, vpm)) == NULL) return 0; ok = (*set1_fn)(ctx, certs); OSSL_STACK_OF_X509_free(certs); return ok; } static int transform_opts(void) { if (opt_cmd_s != NULL) { if (!strcmp(opt_cmd_s, "ir")) { opt_cmd = CMP_IR; } else if (!strcmp(opt_cmd_s, "kur")) { opt_cmd = CMP_KUR; } else if (!strcmp(opt_cmd_s, "cr")) { opt_cmd = CMP_CR; } else if (!strcmp(opt_cmd_s, "p10cr")) { opt_cmd = CMP_P10CR; } else if (!strcmp(opt_cmd_s, "rr")) { opt_cmd = CMP_RR; } else if (!strcmp(opt_cmd_s, "genm")) { opt_cmd = CMP_GENM; } else { CMP_err1("unknown cmp command '%s'", opt_cmd_s); return 0; } } else { CMP_err("no cmp command to execute"); return 0; } #ifndef OPENSSL_NO_ENGINE # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12 | OPT_FMT_ENGINE) #else # define FORMAT_OPTIONS (OPT_FMT_PEMDER | OPT_FMT_PKCS12) #endif if (opt_keyform_s != NULL && !opt_format(opt_keyform_s, FORMAT_OPTIONS, &opt_keyform)) { CMP_err("unknown option given for key loading format"); return 0; } #undef FORMAT_OPTIONS if (opt_certform_s != NULL && !opt_format(opt_certform_s, OPT_FMT_PEMDER, &opt_certform)) { CMP_err("unknown option given for certificate storing format"); return 0; } return 1; } static OSSL_CMP_SRV_CTX *setup_srv_ctx(ENGINE *engine) { OSSL_CMP_CTX *ctx; OSSL_CMP_SRV_CTX *srv_ctx = ossl_cmp_mock_srv_new(app_get0_libctx(), app_get0_propq()); if (srv_ctx == NULL) return NULL; ctx = OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx); if (opt_srv_ref == NULL) { if (opt_srv_cert == NULL) { CMP_err("must give -srv_ref for mock server if no -srv_cert given"); goto err; } } else { if (!OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_srv_ref, strlen(opt_srv_ref))) goto err; } if (opt_srv_secret != NULL) { int res; char *pass_str = get_passwd(opt_srv_secret, "PBMAC secret of mock server"); if (pass_str != NULL) { cleanse(opt_srv_secret); res = OSSL_CMP_CTX_set1_secretValue(ctx, (unsigned char *)pass_str, strlen(pass_str)); clear_free(pass_str); if (res == 0) goto err; } } else if (opt_srv_cert == NULL) { CMP_err("server credentials (-srv_secret or -srv_cert) must be given if -use_mock_srv or -port is used"); goto err; } else { CMP_warn("server will not be able to handle PBM-protected requests since -srv_secret is not given"); } if (opt_srv_secret == NULL && ((opt_srv_cert == NULL) != (opt_srv_key == NULL))) { CMP_err("must give both -srv_cert and -srv_key options or neither"); goto err; } if (!setup_cert(ctx, opt_srv_cert, opt_srv_keypass, "signer certificate of the mock server", (add_X509_fn_t)OSSL_CMP_CTX_set1_cert)) goto err; if (opt_srv_key != NULL) { EVP_PKEY *pkey = load_key_pwd(opt_srv_key, opt_keyform, opt_srv_keypass, engine, "private key for mock server cert"); if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) { EVP_PKEY_free(pkey); goto err; } EVP_PKEY_free(pkey); } cleanse(opt_srv_keypass); if (opt_srv_trusted != NULL) { X509_STORE *ts = load_trusted(opt_srv_trusted, 0, "certs trusted by mock server"); if (ts == NULL || !OSSL_CMP_CTX_set0_trusted(ctx, ts)) { X509_STORE_free(ts); goto err; } } else { CMP_warn("mock server will not be able to handle signature-protected requests since -srv_trusted is not given"); } if (!setup_certs(opt_srv_untrusted, "untrusted certificates for mock server", ctx, (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted)) goto err; if (!setup_cert(srv_ctx, opt_ref_cert, opt_otherpass, "reference cert to be expected by the mock server", (add_X509_fn_t)ossl_cmp_mock_srv_set1_refCert)) goto err; if (opt_rsp_cert == NULL) { CMP_warn("no -rsp_cert given for mock server"); } else { if (!setup_cert(srv_ctx, opt_rsp_cert, opt_keypass, "cert the mock server returns on certificate requests", (add_X509_fn_t)ossl_cmp_mock_srv_set1_certOut)) goto err; } if (!setup_certs(opt_rsp_extracerts, "CMP extra certificates for mock server", srv_ctx, (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_chainOut)) goto err; if (!setup_certs(opt_rsp_capubs, "caPubs for mock server", srv_ctx, (add_X509_stack_fn_t)ossl_cmp_mock_srv_set1_caPubsOut)) goto err; if (!setup_cert(srv_ctx, opt_rsp_newwithnew, opt_otherpass, "NewWithNew cert the mock server returns in rootCaKeyUpdate", (add_X509_fn_t)ossl_cmp_mock_srv_set1_newWithNew) || !setup_cert(srv_ctx, opt_rsp_newwithold, opt_otherpass, "NewWithOld cert the mock server returns in rootCaKeyUpdate", (add_X509_fn_t)ossl_cmp_mock_srv_set1_newWithOld) || !setup_cert(srv_ctx, opt_rsp_oldwithnew, opt_otherpass, "OldWithNew cert the mock server returns in rootCaKeyUpdate", (add_X509_fn_t)ossl_cmp_mock_srv_set1_oldWithNew)) goto err; (void)ossl_cmp_mock_srv_set_pollCount(srv_ctx, opt_poll_count); (void)ossl_cmp_mock_srv_set_checkAfterTime(srv_ctx, opt_check_after); if (opt_grant_implicitconf) (void)OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(srv_ctx, 1); if (opt_failure != INT_MIN) { if (opt_failure < 0 || OSSL_CMP_PKIFAILUREINFO_MAX < opt_failure) { CMP_err1("-failure out of range, should be >= 0 and <= %d", OSSL_CMP_PKIFAILUREINFO_MAX); goto err; } if (opt_failurebits != 0) CMP_warn("-failurebits overrides -failure"); else opt_failurebits = 1 << opt_failure; } if ((unsigned)opt_failurebits > OSSL_CMP_PKIFAILUREINFO_MAX_BIT_PATTERN) { CMP_err("-failurebits out of range"); goto err; } if (!ossl_cmp_mock_srv_set_statusInfo(srv_ctx, opt_pkistatus, opt_failurebits, opt_statusstring)) goto err; if (opt_send_error) (void)ossl_cmp_mock_srv_set_sendError(srv_ctx, 1); if (opt_send_unprotected) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1); if (opt_send_unprot_err) (void)OSSL_CMP_SRV_CTX_set_send_unprotected_errors(srv_ctx, 1); if (opt_accept_unprotected) (void)OSSL_CMP_SRV_CTX_set_accept_unprotected(srv_ctx, 1); if (opt_accept_unprot_err) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1); if (opt_accept_raverified) (void)OSSL_CMP_SRV_CTX_set_accept_raverified(srv_ctx, 1); return srv_ctx; err: ossl_cmp_mock_srv_free(srv_ctx); return NULL; } static int setup_verification_ctx(OSSL_CMP_CTX *ctx) { if (!setup_certs(opt_untrusted, "untrusted certificates", ctx, (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_untrusted)) return 0; if (opt_srvcert != NULL || opt_trusted != NULL) { if (opt_srvcert != NULL) { if (opt_trusted != NULL) { CMP_warn("-trusted option is ignored since -srvcert option is present"); opt_trusted = NULL; } if (opt_recipient != NULL) { CMP_warn("-recipient option is ignored since -srvcert option is present"); opt_recipient = NULL; } if (!setup_cert(ctx, opt_srvcert, opt_otherpass, "directly trusted CMP server certificate", (add_X509_fn_t)OSSL_CMP_CTX_set1_srvCert)) return 0; } if (opt_trusted != NULL) { X509_STORE *ts; ts = load_trusted(opt_trusted, 0, "certs trusted by client"); if (ts == NULL || !OSSL_CMP_CTX_set0_trusted(ctx, ts)) { X509_STORE_free(ts); return 0; } } } if (opt_unprotected_errors) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS, 1); if (opt_out_trusted != NULL) { X509_VERIFY_PARAM *out_vpm = NULL; X509_STORE *out_trusted = load_trusted(opt_out_trusted, 1, "trusted certs for verifying newly enrolled cert"); if (out_trusted == NULL) return 0; out_vpm = X509_STORE_get0_param(out_trusted); X509_VERIFY_PARAM_clear_flags(out_vpm, X509_V_FLAG_USE_CHECK_TIME); (void)OSSL_CMP_CTX_set_certConf_cb_arg(ctx, out_trusted); } if (opt_disable_confirm) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DISABLE_CONFIRM, 1); if (opt_implicit_confirm) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM, 1); return 1; } #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) static SSL_CTX *setup_ssl_ctx(OSSL_CMP_CTX *ctx, const char *host, ENGINE *engine) { STACK_OF(X509) *untrusted = OSSL_CMP_CTX_get0_untrusted(ctx); EVP_PKEY *pkey = NULL; X509_STORE *trust_store = NULL; SSL_CTX *ssl_ctx; int i; ssl_ctx = SSL_CTX_new(TLS_client_method()); if (ssl_ctx == NULL) return NULL; if (opt_tls_trusted != NULL) { trust_store = load_trusted(opt_tls_trusted, 0, "trusted TLS certs"); if (trust_store == NULL) goto err; SSL_CTX_set_cert_store(ssl_ctx, trust_store); SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL); } else { CMP_warn("-tls_used given without -tls_trusted; will not authenticate the TLS server"); } if (opt_tls_cert != NULL && opt_tls_key != NULL) { X509 *cert; STACK_OF(X509) *certs = NULL; int ok; if (!load_cert_certs(opt_tls_cert, &cert, &certs, 0, opt_tls_keypass, "TLS client certificate (optionally with chain)", vpm)) goto err; ok = SSL_CTX_use_certificate(ssl_ctx, cert) > 0; X509_free(cert); if (!ok || !SSL_CTX_set0_chain(ssl_ctx, certs)) { CMP_err1("unable to use client TLS certificate file '%s'", opt_tls_cert); OSSL_STACK_OF_X509_free(certs); goto err; } for (i = 0; i < sk_X509_num(untrusted); i++) { cert = sk_X509_value(untrusted, i); if (!SSL_CTX_add1_chain_cert(ssl_ctx, cert)) { CMP_err("could not add untrusted cert to TLS client cert chain"); goto err; } } { X509_VERIFY_PARAM *tls_vpm = NULL; unsigned long bak_flags = 0; if (trust_store != NULL) { tls_vpm = X509_STORE_get0_param(trust_store); bak_flags = X509_VERIFY_PARAM_get_flags(tls_vpm); X509_VERIFY_PARAM_clear_flags(tls_vpm, ~(X509_V_FLAG_USE_CHECK_TIME | X509_V_FLAG_NO_CHECK_TIME | X509_V_FLAG_PARTIAL_CHAIN | X509_V_FLAG_POLICY_CHECK)); } CMP_debug("trying to build cert chain for own TLS cert"); if (SSL_CTX_build_cert_chain(ssl_ctx, SSL_BUILD_CHAIN_FLAG_UNTRUSTED | SSL_BUILD_CHAIN_FLAG_NO_ROOT)) { CMP_debug("success building cert chain for own TLS cert"); } else { OSSL_CMP_CTX_print_errors(ctx); CMP_warn("could not build cert chain for own TLS cert"); } if (trust_store != NULL) X509_VERIFY_PARAM_set_flags(tls_vpm, bak_flags); } if (opt_tls_extra != NULL) { STACK_OF(X509) *tls_extra = load_certs_multifile(opt_tls_extra, opt_otherpass, "extra certificates for TLS", vpm); int res = 1; if (tls_extra == NULL) goto err; for (i = 0; i < sk_X509_num(tls_extra); i++) { cert = sk_X509_value(tls_extra, i); if (res != 0) res = SSL_CTX_add_extra_chain_cert(ssl_ctx, cert); if (res == 0) X509_free(cert); } sk_X509_free(tls_extra); if (res == 0) { BIO_printf(bio_err, "error: unable to add TLS extra certs\n"); goto err; } } pkey = load_key_pwd(opt_tls_key, opt_keyform, opt_tls_keypass, engine, "TLS client private key"); cleanse(opt_tls_keypass); if (pkey == NULL) goto err; if (!X509_check_private_key(SSL_CTX_get0_certificate(ssl_ctx), pkey)) { CMP_err2("TLS private key '%s' does not match the TLS certificate '%s'\n", opt_tls_key, opt_tls_cert); EVP_PKEY_free(pkey); pkey = NULL; goto err; } if (SSL_CTX_use_PrivateKey(ssl_ctx, pkey) <= 0) { CMP_err1("unable to use TLS client private key '%s'", opt_tls_key); EVP_PKEY_free(pkey); pkey = NULL; goto err; } EVP_PKEY_free(pkey); } else { CMP_warn("-tls_used given without -tls_key; cannot authenticate to the TLS server"); } if (trust_store != NULL) { if (!truststore_set_host_etc(trust_store, opt_tls_host != NULL ? opt_tls_host : host)) goto err; } return ssl_ctx; err: SSL_CTX_free(ssl_ctx); return NULL; } #endif static int setup_protection_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine) { if (!opt_unprotected_requests && opt_secret == NULL && opt_key == NULL) { CMP_err("must give -key or -secret unless -unprotected_requests is used"); return 0; } if (opt_ref == NULL && opt_cert == NULL && opt_subject == NULL) { CMP_err("must give -ref if no -cert and no -subject given"); return 0; } if (opt_secret == NULL && ((opt_cert == NULL) != (opt_key == NULL))) { CMP_err("must give both -cert and -key options or neither"); return 0; } if (opt_secret != NULL) { char *pass_string = get_passwd(opt_secret, "PBMAC"); int res; if (pass_string != NULL) { cleanse(opt_secret); res = OSSL_CMP_CTX_set1_secretValue(ctx, (unsigned char *)pass_string, strlen(pass_string)); clear_free(pass_string); if (res == 0) return 0; } if (opt_cert != NULL || opt_key != NULL) CMP_warn("-cert and -key not used for protection since -secret is given"); } if (opt_ref != NULL && !OSSL_CMP_CTX_set1_referenceValue(ctx, (unsigned char *)opt_ref, strlen(opt_ref))) return 0; if (opt_key != NULL) { EVP_PKEY *pkey = load_key_pwd(opt_key, opt_keyform, opt_keypass, engine, "private key for CMP client certificate"); if (pkey == NULL || !OSSL_CMP_CTX_set1_pkey(ctx, pkey)) { EVP_PKEY_free(pkey); return 0; } EVP_PKEY_free(pkey); } if (opt_secret == NULL && opt_srvcert == NULL && opt_trusted == NULL) CMP_warn("will not authenticate server due to missing -secret, -trusted, or -srvcert"); if (opt_cert != NULL) { X509 *cert; STACK_OF(X509) *certs = NULL; X509_STORE *own_trusted = NULL; int ok; if (!load_cert_certs(opt_cert, &cert, &certs, 0, opt_keypass, "CMP client certificate (optionally with chain)", vpm)) return 0; ok = OSSL_CMP_CTX_set1_cert(ctx, cert); X509_free(cert); if (!ok) { CMP_err("out of memory"); } else { if (opt_own_trusted != NULL) { own_trusted = load_trusted(opt_own_trusted, 0, "trusted certs for verifying own CMP signer cert"); ok = own_trusted != NULL; } ok = ok && OSSL_CMP_CTX_build_cert_chain(ctx, own_trusted, certs); } X509_STORE_free(own_trusted); OSSL_STACK_OF_X509_free(certs); if (!ok) return 0; } else if (opt_own_trusted != NULL) { CMP_warn("-own_trusted option is ignored without -cert"); } if (!setup_certs(opt_extracerts, "extra certificates for CMP", ctx, (add_X509_stack_fn_t)OSSL_CMP_CTX_set1_extraCertsOut)) return 0; cleanse(opt_otherpass); if (opt_unprotected_requests) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_UNPROTECTED_SEND, 1); if (opt_digest != NULL) { int digest = OBJ_ln2nid(opt_digest); if (digest == NID_undef) { CMP_err1("digest algorithm name not recognized: '%s'", opt_digest); return 0; } if (!OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_DIGEST_ALGNID, digest) || !OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_OWF_ALGNID, digest)) { CMP_err1("digest algorithm name not supported: '%s'", opt_digest); return 0; } } if (opt_mac != NULL) { int mac = OBJ_ln2nid(opt_mac); if (mac == NID_undef) { CMP_err1("MAC algorithm name not recognized: '%s'", opt_mac); return 0; } (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MAC_ALGNID, mac); } return 1; } static int set_fallback_pubkey(OSSL_CMP_CTX *ctx) { char *file = opt_reqin, *end = file, bak; OSSL_CMP_MSG *req; const X509_PUBKEY *pubkey; EVP_PKEY *pkey; EVP_PKEY *pkey1; int res = 0; while (*end != ',' && !isspace(_UC(*end)) && *end != '\0') end++; bak = *end; *end = '\0'; req = OSSL_CMP_MSG_read(file, app_get0_libctx(), app_get0_propq()); *end = bak; if (req == NULL) { CMP_err1("failed to load ir/cr/kur file '%s' attempting to get fallback public key", file); return 0; } if ((pubkey = OSSL_CMP_MSG_get0_certreq_publickey(req)) == NULL || (pkey = X509_PUBKEY_get0(pubkey)) == NULL) { CMP_err1("failed to get fallback public key from ir/cr/kur file '%s'", file); goto err; } pkey1 = EVP_PKEY_dup(pkey); if (pkey == NULL || !OSSL_CMP_CTX_set0_newPkey(ctx, 0 , pkey1)) { EVP_PKEY_free(pkey1); CMP_err1("failed to get fallback public key obtained from ir/cr/kur file '%s'", file); goto err; } res = 1; err: OSSL_CMP_MSG_free(req); return res; } static int setup_request_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine) { X509_REQ *csr = NULL; X509_EXTENSIONS *exts = NULL; X509V3_CTX ext_ctx; if (opt_subject == NULL && opt_csr == NULL && opt_oldcert == NULL && opt_cert == NULL && opt_cmd != CMP_RR && opt_cmd != CMP_GENM) CMP_warn("no -subject given; no -csr or -oldcert or -cert available for fallback"); if (!set_name(opt_issuer, OSSL_CMP_CTX_set1_issuer, ctx, "issuer")) return 0; if (opt_cmd == CMP_IR || opt_cmd == CMP_CR || opt_cmd == CMP_KUR) { if (opt_reqin == NULL && opt_newkey == NULL && opt_key == NULL && opt_csr == NULL && opt_oldcert == NULL) { CMP_err("missing -newkey (or -key) to be certified and no -csr, -oldcert, -cert, or -reqin option given, which could provide fallback public key"); return 0; } if (opt_newkey == NULL && opt_popo != OSSL_CRMF_POPO_NONE && opt_popo != OSSL_CRMF_POPO_RAVERIFIED) { if (opt_csr != NULL) { CMP_err1("no -newkey option given with private key for POPO, -csr option provides just public key%s", opt_key == NULL ? "" : ", and -key option superseded by -csr"); if (opt_reqin != NULL) CMP_info("since -reqin is used, may use -popo -1 or -popo 0 to disable the needless generation of a POPO"); return 0; } if (opt_key == NULL) { CMP_err("missing -newkey (or -key) option for key to be certified and for POPO"); return 0; } } if (opt_certout == NULL && opt_reqout_only == NULL) { CMP_err("-certout not given, nowhere to save newly enrolled certificate"); return 0; } if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject")) return 0; } else { const char *msg = "option is ignored for commands other than 'ir', 'cr', and 'kur'"; if (opt_subject != NULL) { if (opt_ref == NULL && opt_cert == NULL) { if (!set_name(opt_subject, OSSL_CMP_CTX_set1_subjectName, ctx, "subject")) return 0; } else { CMP_warn1("-subject %s since sender is taken from -ref or -cert", msg); } } if (opt_issuer != NULL && opt_cmd != CMP_RR) CMP_warn1("-issuer %s and 'rr'", msg); if (opt_reqexts != NULL) CMP_warn1("-reqexts %s", msg); if (opt_san_nodefault) CMP_warn1("-san_nodefault %s", msg); if (opt_sans != NULL) CMP_warn1("-sans %s", msg); if (opt_policies != NULL) CMP_warn1("-policies %s", msg); if (opt_policy_oids != NULL) CMP_warn1("-policy_oids %s", msg); if (opt_cmd != CMP_P10CR) { if (opt_implicit_confirm) CMP_warn1("-implicit_confirm %s, and 'p10cr'", msg); if (opt_disable_confirm) CMP_warn1("-disable_confirm %s, and 'p10cr'", msg); if (opt_certout != NULL) CMP_warn1("-certout %s, and 'p10cr'", msg); if (opt_chainout != NULL) CMP_warn1("-chainout %s, and 'p10cr'", msg); } } if (opt_cmd == CMP_KUR) { char *ref_cert = opt_oldcert != NULL ? opt_oldcert : opt_cert; if (ref_cert == NULL && opt_csr == NULL) { CMP_err("missing -oldcert for certificate to be updated and no -csr given"); return 0; } if (opt_subject != NULL) CMP_warn2("given -subject '%s' overrides the subject of '%s' for KUR", opt_subject, ref_cert != NULL ? ref_cert : opt_csr); } if (opt_cmd == CMP_RR) { if (opt_issuer == NULL && opt_serial == NULL) { if (opt_oldcert == NULL && opt_csr == NULL) { CMP_err("missing -oldcert or -issuer and -serial for certificate to be revoked and no -csr given"); return 0; } if (opt_oldcert != NULL && opt_csr != NULL) CMP_warn("ignoring -csr since certificate to be revoked is given"); } else { #define OSSL_CMP_RR_MSG "since -issuer and -serial is given for command 'rr'" if (opt_issuer == NULL || opt_serial == NULL) { CMP_err("Must give both -issuer and -serial options or neither"); return 0; } if (opt_oldcert != NULL) CMP_warn("Ignoring -oldcert " OSSL_CMP_RR_MSG); if (opt_csr != NULL) CMP_warn("Ignoring -csr " OSSL_CMP_RR_MSG); } if (opt_serial != NULL) { ASN1_INTEGER *sno; if ((sno = s2i_ASN1_INTEGER(NULL, opt_serial)) == NULL) { CMP_err1("cannot read serial number: '%s'", opt_serial); return 0; } if (!OSSL_CMP_CTX_set1_serialNumber(ctx, sno)) { ASN1_INTEGER_free(sno); CMP_err("out of memory"); return 0; } ASN1_INTEGER_free(sno); } if (opt_revreason > CRL_REASON_NONE) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_REVOCATION_REASON, opt_revreason); } else { if (opt_serial != NULL) CMP_warn("Ignoring -serial for command other than 'rr'"); } if (opt_cmd == CMP_P10CR && opt_csr == NULL) { CMP_err("missing PKCS#10 CSR for p10cr"); return 0; } if (opt_recipient == NULL && opt_srvcert == NULL && opt_issuer == NULL && opt_oldcert == NULL && opt_cert == NULL) CMP_warn("missing -recipient, -srvcert, -issuer, -oldcert or -cert; recipient for any requests not covered by -reqin will be set to \"NULL-DN\""); if (opt_cmd == CMP_P10CR || opt_cmd == CMP_RR || opt_cmd == CMP_GENM) { const char *msg = "option is ignored for 'p10cr', 'rr', and 'genm' commands"; if (opt_newkeypass != NULL) CMP_warn1("-newkeypass %s", msg); if (opt_newkey != NULL) CMP_warn1("-newkey %s", msg); if (opt_days != 0) CMP_warn1("-days %s", msg); if (opt_popo != OSSL_CRMF_POPO_NONE - 1) CMP_warn1("-popo %s", msg); if (opt_out_trusted != NULL) CMP_warn1("-out_trusted %s", msg); } else if (opt_newkey != NULL) { const char *file = opt_newkey; const int format = opt_keyform; const char *pass = opt_newkeypass; const char *desc = "new private key for cert to be enrolled"; EVP_PKEY *pkey; int priv = 1; BIO *bio_bak = bio_err; bio_err = NULL; pkey = load_key_pwd(file, format, pass, engine, desc); bio_err = bio_bak; if (pkey == NULL) { ERR_clear_error(); desc = opt_csr == NULL ? "fallback public key for cert to be enrolled" : "public key for checking cert resulting from p10cr"; pkey = load_pubkey(file, format, 0, pass, engine, desc); priv = 0; } cleanse(opt_newkeypass); if (pkey == NULL || !OSSL_CMP_CTX_set0_newPkey(ctx, priv, pkey)) { EVP_PKEY_free(pkey); return 0; } } else if (opt_reqin != NULL && opt_key == NULL && opt_csr == NULL && opt_oldcert == NULL) { if (!set_fallback_pubkey(ctx)) return 0; } if (opt_days > 0 && !OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_VALIDITY_DAYS, opt_days)) { CMP_err("could not set requested cert validity period"); return 0; } if (opt_policies != NULL && opt_policy_oids != NULL) { CMP_err("cannot have policies both via -policies and via -policy_oids"); return 0; } if (opt_csr != NULL) { if (opt_cmd == CMP_GENM) { CMP_warn("-csr option is ignored for 'genm' command"); } else { csr = load_csr_autofmt(opt_csr, FORMAT_UNDEF, NULL, "PKCS#10 CSR"); if (csr == NULL) return 0; if (!OSSL_CMP_CTX_set1_p10CSR(ctx, csr)) goto oom; } } if (opt_reqexts != NULL || opt_policies != NULL) { if ((exts = sk_X509_EXTENSION_new_null()) == NULL) goto oom; X509V3_set_ctx(&ext_ctx, NULL, NULL, csr, NULL, X509V3_CTX_REPLACE); X509V3_set_nconf(&ext_ctx, conf); if (opt_reqexts != NULL && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_reqexts, &exts)) { CMP_err1("cannot load certificate request extension section '%s'", opt_reqexts); goto exts_err; } if (opt_policies != NULL && !X509V3_EXT_add_nconf_sk(conf, &ext_ctx, opt_policies, &exts)) { CMP_err1("cannot load policy cert request extension section '%s'", opt_policies); goto exts_err; } OSSL_CMP_CTX_set0_reqExtensions(ctx, exts); } X509_REQ_free(csr); if (OSSL_CMP_CTX_reqExtensions_have_SAN(ctx) && opt_sans != NULL) { CMP_err("cannot have Subject Alternative Names both via -reqexts and via -sans"); return 0; } if (!set_gennames(ctx, opt_sans, "Subject Alternative Name")) return 0; if (opt_san_nodefault) { if (opt_sans != NULL) CMP_warn("-opt_san_nodefault has no effect when -sans is used"); (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT, 1); } if (opt_policy_oids_critical) { if (opt_policy_oids == NULL) CMP_warn("-opt_policy_oids_critical has no effect unless -policy_oids is given"); (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POLICIES_CRITICAL, 1); } while (opt_policy_oids != NULL) { ASN1_OBJECT *policy; POLICYINFO *pinfo; char *next = next_item(opt_policy_oids); if ((policy = OBJ_txt2obj(opt_policy_oids, 1)) == 0) { CMP_err1("Invalid -policy_oids arg '%s'", opt_policy_oids); return 0; } if (OBJ_obj2nid(policy) == NID_undef) CMP_warn1("Unknown -policy_oids arg: %.40s", opt_policy_oids); if ((pinfo = POLICYINFO_new()) == NULL) { ASN1_OBJECT_free(policy); return 0; } pinfo->policyid = policy; if (!OSSL_CMP_CTX_push0_policy(ctx, pinfo)) { CMP_err1("cannot add policy with OID '%s'", opt_policy_oids); POLICYINFO_free(pinfo); return 0; } opt_policy_oids = next; } if (opt_popo >= OSSL_CRMF_POPO_NONE) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_POPO_METHOD, opt_popo); if (opt_oldcert != NULL) { if (opt_cmd == CMP_GENM) { CMP_warn("-oldcert option is ignored for 'genm' command"); } else { if (!setup_cert(ctx, opt_oldcert, opt_keypass, opt_cmd == CMP_KUR ? "certificate to be updated" : opt_cmd == CMP_RR ? "certificate to be revoked" : "reference certificate (oldcert)", (add_X509_fn_t)OSSL_CMP_CTX_set1_oldCert)) return 0; } } cleanse(opt_keypass); return 1; oom: CMP_err("out of memory"); exts_err: sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); X509_REQ_free(csr); return 0; } static int add_certProfile(OSSL_CMP_CTX *ctx, const char *name) { OSSL_CMP_ITAV *itav = NULL; STACK_OF(ASN1_UTF8STRING) *sk; ASN1_UTF8STRING *utf8string; if (ctx == NULL || name == NULL) return 0; if ((sk = sk_ASN1_UTF8STRING_new_reserve(NULL, 1)) == NULL) return 0; if ((utf8string = ASN1_UTF8STRING_new()) == NULL) goto err; if (!ASN1_STRING_set(utf8string, name, (int)strlen(name))) { ASN1_STRING_free(utf8string); goto err; } (void)sk_ASN1_UTF8STRING_push(sk, utf8string); if ((itav = OSSL_CMP_ITAV_new0_certProfile(sk)) == NULL) goto err; if (OSSL_CMP_CTX_push0_geninfo_ITAV(ctx, itav)) return 1; OSSL_CMP_ITAV_free(itav); return 0; err: sk_ASN1_UTF8STRING_pop_free(sk, ASN1_UTF8STRING_free); return 0; } static int handle_opt_geninfo(OSSL_CMP_CTX *ctx) { ASN1_OBJECT *obj = NULL; ASN1_TYPE *type = NULL; long value; ASN1_INTEGER *aint = NULL; ASN1_UTF8STRING *text = NULL; OSSL_CMP_ITAV *itav; char *ptr = opt_geninfo, *oid, *end; do { while (isspace(_UC(*ptr))) ptr++; oid = ptr; if ((ptr = strchr(oid, ':')) == NULL) { CMP_err1("Missing ':' in -geninfo arg %.40s", oid); return 0; } *ptr++ = '\0'; if ((obj = OBJ_txt2obj(oid, 0)) == NULL) { CMP_err1("Invalid OID in -geninfo arg %.40s", oid); return 0; } if (OBJ_obj2nid(obj) == NID_undef) CMP_warn1("Unknown OID in -geninfo arg: %.40s", oid); if ((type = ASN1_TYPE_new()) == NULL) goto oom; if (CHECK_AND_SKIP_CASE_PREFIX(ptr, "int:")) { value = strtol(ptr, &end, 10); if (end == ptr) { CMP_err1("Cannot parse int in -geninfo arg %.40s", ptr); goto err; } ptr = end; if (*ptr != '\0') { if (*ptr != ',') { CMP_err1("Missing ',' or end of -geninfo arg after int at %.40s", ptr); goto err; } ptr++; } if ((aint = ASN1_INTEGER_new()) == NULL || !ASN1_INTEGER_set(aint, value)) goto oom; ASN1_TYPE_set(type, V_ASN1_INTEGER, aint); aint = NULL; } else if (CHECK_AND_SKIP_CASE_PREFIX(ptr, "str:")) { end = strchr(ptr, ','); if (end == NULL) end = ptr + strlen(ptr); else *end++ = '\0'; if ((text = ASN1_UTF8STRING_new()) == NULL || !ASN1_STRING_set(text, ptr, -1)) goto oom; ptr = end; ASN1_TYPE_set(type, V_ASN1_UTF8STRING, text); text = NULL; } else { CMP_err1("Missing 'int:' or 'str:' in -geninfo arg %.40s", ptr); goto err; } if ((itav = OSSL_CMP_ITAV_create(obj, type)) == NULL) { CMP_err("Unable to create 'OSSL_CMP_ITAV' structure"); goto err; } obj = NULL; type = NULL; if (!OSSL_CMP_CTX_push0_geninfo_ITAV(ctx, itav)) { CMP_err("Failed to add ITAV for geninfo of the PKI message header"); OSSL_CMP_ITAV_free(itav); return 0; } } while (*ptr != '\0'); return 1; oom: CMP_err("out of memory"); err: ASN1_OBJECT_free(obj); ASN1_TYPE_free(type); ASN1_INTEGER_free(aint); ASN1_UTF8STRING_free(text); return 0; } static int setup_client_ctx(OSSL_CMP_CTX *ctx, ENGINE *engine) { int ret = 0; char *host = NULL, *port = NULL, *path = NULL, *used_path = opt_path; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) int portnum, use_ssl; static char server_port[32] = { '\0' }; const char *proxy_host = NULL; #endif char server_buf[200] = "mock server"; char proxy_buf[200] = ""; if (!opt_use_mock_srv) strcpy(server_buf, "no server"); if (!opt_use_mock_srv && opt_rspin == NULL) { #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_server == NULL && opt_reqout_only == NULL) { CMP_err("missing -server or -use_mock_srv or -rspin option"); goto err; } #else CMP_err("missing -use_mock_srv or -rspin option; -server option is not supported due to no-sock build"); goto err; #endif } #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_server == NULL) { if (opt_proxy != NULL) CMP_warn("ignoring -proxy option since -server is not given"); if (opt_no_proxy != NULL) CMP_warn("ignoring -no_proxy option since -server is not given"); goto set_path; } if (!OSSL_HTTP_parse_url(opt_server, &use_ssl, NULL , &host, &port, &portnum, &path, NULL , NULL )) { CMP_err1("cannot parse -server URL: %s", opt_server); goto err; } if (use_ssl && !opt_tls_used) { CMP_warn("assuming -tls_used since -server URL indicates HTTPS"); opt_tls_used = 1; } if (!OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_USE_TLS, opt_tls_used)) goto err; BIO_snprintf(server_port, sizeof(server_port), "%s", port); if (opt_path == NULL) used_path = path; if (!OSSL_CMP_CTX_set1_server(ctx, host) || !OSSL_CMP_CTX_set_serverPort(ctx, portnum)) goto oom; if (opt_proxy != NULL && !OSSL_CMP_CTX_set1_proxy(ctx, opt_proxy)) goto oom; if (opt_no_proxy != NULL && !OSSL_CMP_CTX_set1_no_proxy(ctx, opt_no_proxy)) goto oom; (void)BIO_snprintf(server_buf, sizeof(server_buf), "http%s: opt_tls_used ? "s" : "", host, port, *used_path == '/' ? used_path + 1 : used_path); proxy_host = OSSL_HTTP_adapt_proxy(opt_proxy, opt_no_proxy, host, use_ssl); if (proxy_host != NULL) (void)BIO_snprintf(proxy_buf, sizeof(proxy_buf), " via %s", proxy_host); set_path: #endif if (!OSSL_CMP_CTX_set1_serverPath(ctx, used_path)) goto oom; if (!transform_opts()) goto err; if (opt_infotype_s == NULL) { if (opt_cmd == CMP_GENM) CMP_warn("no -infotype option given for genm"); } else if (opt_cmd != CMP_GENM) { CMP_warn("-infotype option is ignored for commands other than 'genm'"); } else { char id_buf[100] = "id-it-"; strncat(id_buf, opt_infotype_s, sizeof(id_buf) - strlen(id_buf) - 1); if ((opt_infotype = OBJ_sn2nid(id_buf)) == NID_undef) { CMP_err("unknown OID name in -infotype option"); goto err; } } if (opt_cmd != CMP_GENM || opt_infotype != NID_id_it_rootCaCert) { const char *msg = "option is ignored unless -cmd 'genm' and -infotype rootCaCert is given"; if (opt_oldwithold != NULL) CMP_warn1("-oldwithold %s", msg); if (opt_newwithnew != NULL) CMP_warn1("-newwithnew %s", msg); if (opt_newwithold != NULL) CMP_warn1("-newwithold %s", msg); if (opt_oldwithnew != NULL) CMP_warn1("-oldwithnew %s", msg); } if (!setup_verification_ctx(ctx)) goto err; if (opt_keep_alive != 1) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_KEEP_ALIVE, opt_keep_alive); if (opt_total_timeout > 0 && opt_msg_timeout > 0 && opt_total_timeout < opt_msg_timeout) { CMP_err2("-total_timeout argument = %d must not be < %d (-msg_timeout)", opt_total_timeout, opt_msg_timeout); goto err; } if (opt_msg_timeout >= 0) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT, opt_msg_timeout); if (opt_total_timeout >= 0) (void)OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_TOTAL_TIMEOUT, opt_total_timeout); if (opt_rspin != NULL) { rspin_in_use = 1; if (opt_reqin != NULL) CMP_warn("-reqin is ignored since -rspin is present"); } if (opt_reqin_new_tid && opt_reqin == NULL) CMP_warn("-reqin_new_tid is ignored since -reqin is not present"); if (opt_reqin != NULL || opt_reqout != NULL || opt_rspin != NULL || opt_rspout != NULL || opt_use_mock_srv) (void)OSSL_CMP_CTX_set_transfer_cb(ctx, read_write_req_resp); #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_tls_used) { APP_HTTP_TLS_INFO *info; if (opt_tls_cert != NULL || opt_tls_key != NULL || opt_tls_keypass != NULL) { if (opt_tls_key == NULL) { CMP_err("missing -tls_key option"); goto err; } else if (opt_tls_cert == NULL) { CMP_err("missing -tls_cert option"); goto err; } } if ((info = OPENSSL_zalloc(sizeof(*info))) == NULL) goto err; APP_HTTP_TLS_INFO_free(OSSL_CMP_CTX_get_http_cb_arg(ctx)); (void)OSSL_CMP_CTX_set_http_cb_arg(ctx, info); info->ssl_ctx = setup_ssl_ctx(ctx, host, engine); info->server = host; host = NULL; if ((info->port = OPENSSL_strdup(server_port)) == NULL) goto err; info->use_proxy = proxy_host != NULL; info->timeout = OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_MSG_TIMEOUT); if (info->ssl_ctx == NULL) goto err; (void)OSSL_CMP_CTX_set_http_cb(ctx, app_http_tls_cb); } #endif if (!setup_protection_ctx(ctx, engine)) goto err; if (!setup_request_ctx(ctx, engine)) goto err; if (!set_name(opt_recipient, OSSL_CMP_CTX_set1_recipient, ctx, "recipient") || !set_name(opt_expect_sender, OSSL_CMP_CTX_set1_expected_sender, ctx, "expected sender")) goto err; if (opt_geninfo != NULL && !handle_opt_geninfo(ctx)) goto err; if (opt_profile != NULL && !add_certProfile(ctx, opt_profile)) goto err; if (opt_reqout_only == NULL) CMP_info3("will contact %s%s%s ", server_buf, proxy_buf, opt_rspin == NULL ? "" : " only if -rspin argument gives too few filenames"); ret = 1; err: OPENSSL_free(host); OPENSSL_free(port); OPENSSL_free(path); return ret; oom: CMP_err("out of memory"); goto err; } static int write_cert(BIO *bio, X509 *cert) { if ((opt_certform == FORMAT_PEM && PEM_write_bio_X509(bio, cert)) || (opt_certform == FORMAT_ASN1 && i2d_X509_bio(bio, cert))) return 1; if (opt_certform != FORMAT_PEM && opt_certform != FORMAT_ASN1) BIO_printf(bio_err, "error: unsupported type '%s' for writing certificates\n", opt_certform_s); return 0; } static int save_free_certs(STACK_OF(X509) *certs, const char *file, const char *desc) { BIO *bio = NULL; int i; int n = sk_X509_num(certs ); if (n < 0) n = 0; if (file == NULL) goto end; if (certs != NULL) CMP_info3("received %d %s certificate(s), saving to file '%s'", n, desc, file); if (n > 1 && opt_certform != FORMAT_PEM) CMP_warn("saving more than one certificate in non-PEM format"); if ((bio = BIO_new(BIO_s_file())) == NULL || !BIO_write_filename(bio, (char *)file)) { CMP_err3("could not open file '%s' for %s %s certificate(s)", file, certs == NULL ? "deleting" : "writing", desc); n = -1; goto end; } for (i = 0; i < n; i++) { if (!write_cert(bio, sk_X509_value(certs, i))) { CMP_err2("cannot write %s certificate to file '%s'", desc, file); n = -1; goto end; } } end: BIO_free(bio); OSSL_STACK_OF_X509_free(certs); return n; } static int delete_file(const char *file, const char *desc) { if (file == NULL) return 1; if (unlink(file) != 0 && errno != ENOENT) { CMP_err2("Failed to delete %s, which should be done to indicate there is no %s", file, desc); return 0; } return 1; } static int save_cert_or_delete(X509 *cert, const char *file, const char *desc) { if (file == NULL) return 1; if (cert == NULL) { char desc_cert[80]; BIO_snprintf(desc_cert, sizeof(desc_cert), "%s certificate", desc); return delete_file(file, desc_cert); } else { STACK_OF(X509) *certs = sk_X509_new_null(); if (!X509_add_cert(certs, cert, X509_ADD_FLAG_UP_REF)) { sk_X509_free(certs); return 0; } return save_free_certs(certs, file, desc) >= 0; } } static int print_itavs(const STACK_OF(OSSL_CMP_ITAV) *itavs) { int i, ret = 1; int n = sk_OSSL_CMP_ITAV_num(itavs); if (n <= 0) { CMP_info("genp does not contain any ITAV"); return ret; } for (i = 1; i <= n; i++) { OSSL_CMP_ITAV *itav = sk_OSSL_CMP_ITAV_value(itavs, i - 1); ASN1_OBJECT *type = OSSL_CMP_ITAV_get0_type(itav); char name[80]; if (itav == NULL) { CMP_err1("could not get ITAV #%d from genp", i); ret = 0; continue; } if (i2t_ASN1_OBJECT(name, sizeof(name), type) <= 0) { CMP_err1("error parsing type of ITAV #%d from genp", i); ret = 0; } else { CMP_info2("ITAV #%d from genp infoType=%s", i, name); } } return ret; } static char opt_item[SECTION_NAME_MAX + 1]; static const char *prev_item(const char *opt, const char *end) { const char *beg; size_t len; if (end == opt) return NULL; beg = end; while (beg > opt) { --beg; if (beg[0] == ',' || isspace(_UC(beg[0]))) { ++beg; break; } } len = end - beg; if (len > SECTION_NAME_MAX) { CMP_warn3("using only first %d characters of section name starting with \"%.*s\"", SECTION_NAME_MAX, SECTION_NAME_MAX, beg); len = SECTION_NAME_MAX; } memcpy(opt_item, beg, len); opt_item[len] = '\0'; while (beg > opt) { --beg; if (beg[0] != ',' && !isspace(_UC(beg[0]))) { ++beg; break; } } return beg; } static char *conf_get_string(const CONF *src_conf, const char *groups, const char *name) { char *res = NULL; const char *end = groups + strlen(groups); while ((end = prev_item(groups, end)) != NULL) { if ((res = app_conf_try_string(src_conf, opt_item, name)) != NULL) return res; } return res; } static int conf_get_number_e(const CONF *conf_, const char *groups, const char *name, long *result) { char *str = conf_get_string(conf_, groups, name); char *tailptr; long res; if (str == NULL || *str == '\0') return 0; res = strtol(str, &tailptr, 10); if (res == LONG_MIN || res == LONG_MAX || *tailptr != '\0') return 0; *result = res; return 1; } static int read_config(void) { unsigned int i; long num = 0; char *txt = NULL; const OPTIONS *opt; int start_opt = OPT_VERBOSITY - OPT_HELP; int start_idx = OPT_VERBOSITY - 2; int n_options = OSSL_NELEM(cmp_options) - 1; for (opt = &cmp_options[start_opt], i = start_idx; opt->name != NULL; i++, opt++) if (!strcmp(opt->name, OPT_SECTION_STR) || !strcmp(opt->name, OPT_MORE_STR)) n_options--; OPENSSL_assert(OSSL_NELEM(cmp_vars) == n_options + OPT_PROV__FIRST + 1 - OPT_PROV__LAST + OPT_R__FIRST + 1 - OPT_R__LAST + OPT_V__FIRST + 1 - OPT_V__LAST); for (opt = &cmp_options[start_opt], i = start_idx; opt->name != NULL; i++, opt++) { int provider_option = (OPT_PROV__FIRST <= opt->retval && opt->retval < OPT_PROV__LAST); int rand_state_option = (OPT_R__FIRST <= opt->retval && opt->retval < OPT_R__LAST); int verification_option = (OPT_V__FIRST <= opt->retval && opt->retval < OPT_V__LAST); if (strcmp(opt->name, OPT_SECTION_STR) == 0 || strcmp(opt->name, OPT_MORE_STR) == 0) { i--; continue; } if (provider_option || rand_state_option || verification_option) i--; switch (opt->valtype) { case '-': case 'p': case 'n': case 'N': case 'l': if (!conf_get_number_e(conf, opt_section, opt->name, &num)) { ERR_clear_error(); continue; } if (opt->valtype == 'p' && num <= 0) { opt_printf_stderr("Non-positive number \"%ld\" for config option -%s\n", num, opt->name); return -1; } if (opt->valtype == 'N' && num < 0) { opt_printf_stderr("Negative number \"%ld\" for config option -%s\n", num, opt->name); return -1; } break; case 's': case '>': case 'M': txt = conf_get_string(conf, opt_section, opt->name); if (txt == NULL) { ERR_clear_error(); continue; } break; default: CMP_err2("internal: unsupported type '%c' for option '%s'", opt->valtype, opt->name); return 0; break; } if (provider_option || verification_option) { int conf_argc = 1; char *conf_argv[3]; char arg1[82]; BIO_snprintf(arg1, 81, "-%s", (char *)opt->name); conf_argv[0] = prog; conf_argv[1] = arg1; if (opt->valtype == '-') { if (num != 0) conf_argc = 2; } else { conf_argc = 3; conf_argv[2] = conf_get_string(conf, opt_section, opt->name); } if (conf_argc > 1) { (void)opt_init(conf_argc, conf_argv, cmp_options); if (provider_option ? !opt_provider(opt_next()) : !opt_verify(opt_next(), vpm)) { CMP_err2("for option '%s' in config file section '%s'", opt->name, opt_section); return 0; } } } else { switch (opt->valtype) { case '-': case 'p': case 'n': case 'N': if (num < INT_MIN || INT_MAX < num) { BIO_printf(bio_err, "integer value out of range for option '%s'\n", opt->name); return 0; } *cmp_vars[i].num = (int)num; break; case 'l': *cmp_vars[i].num_long = num; break; default: if (txt != NULL && txt[0] == '\0') txt = NULL; *cmp_vars[i].txt = txt; break; } } } return 1; } static char *opt_str(void) { char *arg = opt_arg(); if (arg[0] == '\0') { CMP_warn1("%s option argument is empty string, resetting option", opt_flag()); arg = NULL; } else if (arg[0] == '-') { CMP_warn1("%s option argument starts with hyphen", opt_flag()); } return arg; } static int get_opts(int argc, char **argv) { OPTION_CHOICE o; prog = opt_init(argc, argv, cmp_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); return 0; case OPT_HELP: opt_help(cmp_options); return -1; case OPT_CONFIG: case OPT_SECTION: break; case OPT_VERBOSITY: if (!set_verbosity(opt_int_arg())) goto opthelp; break; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) case OPT_SERVER: opt_server = opt_str(); break; case OPT_PROXY: opt_proxy = opt_str(); break; case OPT_NO_PROXY: opt_no_proxy = opt_str(); break; #endif case OPT_RECIPIENT: opt_recipient = opt_str(); break; case OPT_PATH: opt_path = opt_str(); break; case OPT_KEEP_ALIVE: opt_keep_alive = opt_int_arg(); if (opt_keep_alive > 2) { CMP_err("-keep_alive argument must be 0, 1, or 2"); goto opthelp; } break; case OPT_MSG_TIMEOUT: opt_msg_timeout = opt_int_arg(); break; case OPT_TOTAL_TIMEOUT: opt_total_timeout = opt_int_arg(); break; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) case OPT_TLS_USED: opt_tls_used = 1; break; case OPT_TLS_CERT: opt_tls_cert = opt_str(); break; case OPT_TLS_KEY: opt_tls_key = opt_str(); break; case OPT_TLS_KEYPASS: opt_tls_keypass = opt_str(); break; case OPT_TLS_EXTRA: opt_tls_extra = opt_str(); break; case OPT_TLS_TRUSTED: opt_tls_trusted = opt_str(); break; case OPT_TLS_HOST: opt_tls_host = opt_str(); break; #endif case OPT_REF: opt_ref = opt_str(); break; case OPT_SECRET: opt_secret = opt_str(); break; case OPT_CERT: opt_cert = opt_str(); break; case OPT_OWN_TRUSTED: opt_own_trusted = opt_str(); break; case OPT_KEY: opt_key = opt_str(); break; case OPT_KEYPASS: opt_keypass = opt_str(); break; case OPT_DIGEST: opt_digest = opt_str(); break; case OPT_MAC: opt_mac = opt_str(); break; case OPT_EXTRACERTS: opt_extracerts = opt_str(); break; case OPT_UNPROTECTED_REQUESTS: opt_unprotected_requests = 1; break; case OPT_TRUSTED: opt_trusted = opt_str(); break; case OPT_UNTRUSTED: opt_untrusted = opt_str(); break; case OPT_SRVCERT: opt_srvcert = opt_str(); break; case OPT_EXPECT_SENDER: opt_expect_sender = opt_str(); break; case OPT_IGNORE_KEYUSAGE: opt_ignore_keyusage = 1; break; case OPT_UNPROTECTED_ERRORS: opt_unprotected_errors = 1; break; case OPT_NO_CACHE_EXTRACERTS: opt_no_cache_extracerts = 1; break; case OPT_SRVCERTOUT: opt_srvcertout = opt_str(); break; case OPT_EXTRACERTSOUT: opt_extracertsout = opt_str(); break; case OPT_CACERTSOUT: opt_cacertsout = opt_str(); break; case OPT_OLDWITHOLD: opt_oldwithold = opt_str(); break; case OPT_NEWWITHNEW: opt_newwithnew = opt_str(); break; case OPT_NEWWITHOLD: opt_newwithold = opt_str(); break; case OPT_OLDWITHNEW: opt_oldwithnew = opt_str(); break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto opthelp; break; case OPT_CMD: opt_cmd_s = opt_str(); break; case OPT_INFOTYPE: opt_infotype_s = opt_str(); break; case OPT_PROFILE: opt_profile = opt_str(); break; case OPT_GENINFO: opt_geninfo = opt_str(); break; case OPT_NEWKEY: opt_newkey = opt_str(); break; case OPT_NEWKEYPASS: opt_newkeypass = opt_str(); break; case OPT_SUBJECT: opt_subject = opt_str(); break; case OPT_DAYS: opt_days = opt_int_arg(); break; case OPT_REQEXTS: opt_reqexts = opt_str(); break; case OPT_SANS: opt_sans = opt_str(); break; case OPT_SAN_NODEFAULT: opt_san_nodefault = 1; break; case OPT_POLICIES: opt_policies = opt_str(); break; case OPT_POLICY_OIDS: opt_policy_oids = opt_str(); break; case OPT_POLICY_OIDS_CRITICAL: opt_policy_oids_critical = 1; break; case OPT_POPO: opt_popo = opt_int_arg(); if (opt_popo < OSSL_CRMF_POPO_NONE || opt_popo > OSSL_CRMF_POPO_KEYENC) { CMP_err("invalid popo spec. Valid values are -1 .. 2"); goto opthelp; } break; case OPT_CSR: opt_csr = opt_str(); break; case OPT_OUT_TRUSTED: opt_out_trusted = opt_str(); break; case OPT_IMPLICIT_CONFIRM: opt_implicit_confirm = 1; break; case OPT_DISABLE_CONFIRM: opt_disable_confirm = 1; break; case OPT_CERTOUT: opt_certout = opt_str(); break; case OPT_CHAINOUT: opt_chainout = opt_str(); break; case OPT_OLDCERT: opt_oldcert = opt_str(); break; case OPT_REVREASON: opt_revreason = opt_int_arg(); if (opt_revreason < CRL_REASON_NONE || opt_revreason > CRL_REASON_AA_COMPROMISE || opt_revreason == 7) { CMP_err("invalid revreason. Valid values are -1 .. 6, 8 .. 10"); goto opthelp; } break; case OPT_ISSUER: opt_issuer = opt_str(); break; case OPT_SERIAL: opt_serial = opt_str(); break; case OPT_CERTFORM: opt_certform_s = opt_str(); break; case OPT_KEYFORM: opt_keyform_s = opt_str(); break; case OPT_OTHERPASS: opt_otherpass = opt_str(); break; #ifndef OPENSSL_NO_ENGINE case OPT_ENGINE: opt_engine = opt_str(); break; #endif case OPT_PROV_CASES: if (!opt_provider(o)) goto opthelp; break; case OPT_R_CASES: if (!opt_rand(o)) goto opthelp; break; case OPT_BATCH: opt_batch = 1; break; case OPT_REPEAT: opt_repeat = opt_int_arg(); break; case OPT_REQIN: opt_reqin = opt_str(); break; case OPT_REQIN_NEW_TID: opt_reqin_new_tid = 1; break; case OPT_REQOUT: opt_reqout = opt_str(); break; case OPT_REQOUT_ONLY: opt_reqout_only = opt_str(); break; case OPT_RSPIN: opt_rspin = opt_str(); break; case OPT_RSPOUT: opt_rspout = opt_str(); break; case OPT_USE_MOCK_SRV: opt_use_mock_srv = 1; break; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) case OPT_PORT: opt_port = opt_str(); break; case OPT_MAX_MSGS: opt_max_msgs = opt_int_arg(); break; #endif case OPT_SRV_REF: opt_srv_ref = opt_str(); break; case OPT_SRV_SECRET: opt_srv_secret = opt_str(); break; case OPT_SRV_CERT: opt_srv_cert = opt_str(); break; case OPT_SRV_KEY: opt_srv_key = opt_str(); break; case OPT_SRV_KEYPASS: opt_srv_keypass = opt_str(); break; case OPT_SRV_TRUSTED: opt_srv_trusted = opt_str(); break; case OPT_SRV_UNTRUSTED: opt_srv_untrusted = opt_str(); break; case OPT_REF_CERT: opt_ref_cert = opt_str(); break; case OPT_RSP_CERT: opt_rsp_cert = opt_str(); break; case OPT_RSP_EXTRACERTS: opt_rsp_extracerts = opt_str(); break; case OPT_RSP_CAPUBS: opt_rsp_capubs = opt_str(); break; case OPT_RSP_NEWWITHNEW: opt_rsp_newwithnew = opt_str(); break; case OPT_RSP_NEWWITHOLD: opt_rsp_newwithold = opt_str(); break; case OPT_RSP_OLDWITHNEW: opt_rsp_oldwithnew = opt_str(); break; case OPT_POLL_COUNT: opt_poll_count = opt_int_arg(); break; case OPT_CHECK_AFTER: opt_check_after = opt_int_arg(); break; case OPT_GRANT_IMPLICITCONF: opt_grant_implicitconf = 1; break; case OPT_PKISTATUS: opt_pkistatus = opt_int_arg(); break; case OPT_FAILURE: opt_failure = opt_int_arg(); break; case OPT_FAILUREBITS: opt_failurebits = opt_int_arg(); break; case OPT_STATUSSTRING: opt_statusstring = opt_str(); break; case OPT_SEND_ERROR: opt_send_error = 1; break; case OPT_SEND_UNPROTECTED: opt_send_unprotected = 1; break; case OPT_SEND_UNPROT_ERR: opt_send_unprot_err = 1; break; case OPT_ACCEPT_UNPROTECTED: opt_accept_unprotected = 1; break; case OPT_ACCEPT_UNPROT_ERR: opt_accept_unprot_err = 1; break; case OPT_ACCEPT_RAVERIFIED: opt_accept_raverified = 1; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; return 1; } #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) static int cmp_server(OSSL_CMP_CTX *srv_cmp_ctx) { BIO *acbio; BIO *cbio = NULL; int keep_alive = 0; int msgs = 0; int retry = 1; int ret = 1; if ((acbio = http_server_init(prog, opt_port, opt_verbosity)) == NULL) return 0; while (opt_max_msgs <= 0 || msgs < opt_max_msgs) { char *path = NULL; OSSL_CMP_MSG *req = NULL; OSSL_CMP_MSG *resp = NULL; ret = http_server_get_asn1_req(ASN1_ITEM_rptr(OSSL_CMP_MSG), (ASN1_VALUE **)&req, &path, &cbio, acbio, &keep_alive, prog, 0, 0); if (ret == 0) { if (retry) { OSSL_sleep(1000); retry = 0; continue; } ret = 0; goto next; } if (ret++ == -1) break; ret = 0; msgs++; if (req != NULL) { if (strcmp(path, "") != 0 && strcmp(path, "pkix/") != 0) { (void)http_server_send_status(prog, cbio, 404, "Not Found"); CMP_err1("expecting empty path or 'pkix/' but got '%s'", path); OPENSSL_free(path); OSSL_CMP_MSG_free(req); goto next; } OPENSSL_free(path); resp = OSSL_CMP_CTX_server_perform(cmp_ctx, req); OSSL_CMP_MSG_free(req); if (resp == NULL) { (void)http_server_send_status(prog, cbio, 500, "Internal Server Error"); break; } ret = http_server_send_asn1_resp(prog, cbio, keep_alive, "application/pkixcmp", ASN1_ITEM_rptr(OSSL_CMP_MSG), (const ASN1_VALUE *)resp); OSSL_CMP_MSG_free(resp); if (!ret) break; } next: if (!ret) { (void)OSSL_CMP_CTX_set1_transactionID(srv_cmp_ctx, NULL); (void)OSSL_CMP_CTX_set1_senderNonce(srv_cmp_ctx, NULL); } if (!ret || !keep_alive || OSSL_CMP_CTX_get_status(srv_cmp_ctx) != OSSL_CMP_PKISTATUS_trans ) { BIO_free_all(cbio); cbio = NULL; } } BIO_free_all(cbio); BIO_free_all(acbio); return ret; } #endif static void print_status(void) { int status = OSSL_CMP_CTX_get_status(cmp_ctx); char *buf = app_malloc(OSSL_CMP_PKISI_BUFLEN, "PKIStatusInfo buf"); const char *string = OSSL_CMP_CTX_snprint_PKIStatus(cmp_ctx, buf, OSSL_CMP_PKISI_BUFLEN); const char *from = "", *server = ""; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_server != NULL) { from = " from "; server = opt_server; } #endif CMP_print(bio_err, status == OSSL_CMP_PKISTATUS_accepted ? OSSL_CMP_LOG_INFO : status == OSSL_CMP_PKISTATUS_rejection || status == OSSL_CMP_PKISTATUS_waiting ? OSSL_CMP_LOG_ERR : OSSL_CMP_LOG_WARNING, status == OSSL_CMP_PKISTATUS_accepted ? "info" : status == OSSL_CMP_PKISTATUS_rejection ? "server error" : status == OSSL_CMP_PKISTATUS_waiting ? "internal error" : "warning", "received%s%s %s", from, server, string != NULL ? string : "<unknown PKIStatus>"); OPENSSL_free(buf); } static int do_genm(OSSL_CMP_CTX *ctx) { if (opt_infotype == NID_id_it_caCerts) { STACK_OF(X509) *cacerts = NULL; if (opt_cacertsout == NULL) { CMP_err("Missing -cacertsout option for -infotype caCerts"); return 0; } if (!OSSL_CMP_get1_caCerts(ctx, &cacerts)) return 0; if (cacerts == NULL) { CMP_warn("no CA certificates provided by server"); } else if (save_free_certs(cacerts, opt_cacertsout, "CA") < 0) { CMP_err1("Failed to store CA certificates from genp in %s", opt_cacertsout); return 0; } return 1; } else if (opt_infotype == NID_id_it_rootCaCert) { X509 *oldwithold = NULL; X509 *newwithnew = NULL; X509 *newwithold = NULL; X509 *oldwithnew = NULL; int res = 0; if (opt_newwithnew == NULL) { CMP_err("Missing -newwithnew option for -infotype rootCaCert"); return 0; } if (opt_oldwithold == NULL) { CMP_warn("No -oldwithold given, will use all certs given with -trusted as trust anchors for verifying the newWithNew cert"); } else { oldwithold = load_cert_pwd(opt_oldwithold, opt_otherpass, "OldWithOld cert for genm with -infotype rootCaCert"); if (oldwithold == NULL) goto end_upd; } if (!OSSL_CMP_get1_rootCaKeyUpdate(ctx, oldwithold, &newwithnew, &newwithold, &oldwithnew)) goto end_upd; if (newwithnew == NULL) CMP_info("no root CA certificate update available"); else if (oldwithold == NULL && oldwithnew != NULL) CMP_warn("oldWithNew certificate received in genp for verifying oldWithOld, but oldWithOld was not provided"); if (save_cert_or_delete(newwithnew, opt_newwithnew, "NewWithNew cert from genp") && save_cert_or_delete(newwithold, opt_newwithold, "NewWithOld cert from genp") && save_cert_or_delete(oldwithnew, opt_oldwithnew, "OldWithNew cert from genp")) res = 1; X509_free(newwithnew); X509_free(newwithold); X509_free(oldwithnew); end_upd: X509_free(oldwithold); return res; } else { OSSL_CMP_ITAV *req; STACK_OF(OSSL_CMP_ITAV) *itavs; if (opt_infotype != NID_undef) { CMP_warn1("No specific support for -infotype %s available", opt_infotype_s); req = OSSL_CMP_ITAV_create(OBJ_nid2obj(opt_infotype), NULL); if (req == NULL || !OSSL_CMP_CTX_push0_genm_ITAV(ctx, req)) { CMP_err1("Failed to create genm for -infotype %s", opt_infotype_s); return 0; } } if ((itavs = OSSL_CMP_exec_GENM_ses(ctx)) != NULL) { int res = print_itavs(itavs); sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free); return res; } if (OSSL_CMP_CTX_get_status(ctx) != OSSL_CMP_PKISTATUS_request) CMP_err("Did not receive response on genm or genp is not valid"); return 0; } } static int handle_opts_upfront(int argc, char **argv) { int i; prog = opt_appname(argv[0]); if (argc <= 1) { opt_help(cmp_options); return 0; } for (i = 1; i < argc - 1; i++) { if (*argv[i] == '-') { if (!strcmp(argv[i] + 1, cmp_options[OPT_CONFIG - OPT_HELP].name)) opt_config = argv[++i]; else if (!strcmp(argv[i] + 1, cmp_options[OPT_SECTION - OPT_HELP].name)) opt_section = argv[++i]; else if (strcmp(argv[i] + 1, cmp_options[OPT_VERBOSITY - OPT_HELP].name) == 0 && !set_verbosity(atoi(argv[++i]))) return 0; } } if (opt_section[0] == '\0') opt_section = DEFAULT_SECTION; return 1; } int cmp_main(int argc, char **argv) { char *configfile = NULL; int i; X509 *newcert = NULL; ENGINE *engine = NULL; OSSL_CMP_CTX *srv_cmp_ctx = NULL; int ret = 0; if (!handle_opts_upfront(argc, argv)) goto err; vpm = X509_VERIFY_PARAM_new(); if (vpm == NULL) { CMP_err("out of memory"); goto err; } configfile = opt_config != NULL ? opt_config : default_config_file; if (configfile != NULL && configfile[0] != '\0' && (configfile != default_config_file || access(configfile, F_OK) != -1)) { CMP_info2("using section(s) '%s' of OpenSSL configuration file '%s'", opt_section, configfile); conf = app_load_config(configfile); if (conf == NULL) { goto err; } else { if (strcmp(opt_section, CMP_SECTION) == 0) { if (!NCONF_get_section(conf, opt_section)) CMP_info2("no [%s] section found in config file '%s';" " will thus use just [default] and unnamed section if present", opt_section, configfile); } else { const char *end = opt_section + strlen(opt_section); while ((end = prev_item(opt_section, end)) != NULL) { if (!NCONF_get_section(conf, opt_item)) { CMP_err2("no [%s] section found in config file '%s'", opt_item, configfile); goto err; } } } ret = read_config(); if (!set_verbosity(opt_verbosity)) ret = -1; if (ret <= 0) { if (ret == -1) BIO_printf(bio_err, "Use -help for summary.\n"); goto err; } } } (void)BIO_flush(bio_err); cmp_ctx = OSSL_CMP_CTX_new(app_get0_libctx(), app_get0_propq()); if (cmp_ctx == NULL) goto err; ret = get_opts(argc, argv); if (ret <= 0) goto err; ret = 0; if (!app_RAND_load()) goto err; if (opt_batch) set_base_ui_method(UI_null()); if (opt_engine != NULL) { engine = setup_engine_methods(opt_engine, 0 , 0); if (engine == NULL) { CMP_err1("cannot load engine %s", opt_engine); goto err; } } OSSL_CMP_CTX_set_log_verbosity(cmp_ctx, opt_verbosity); if (!OSSL_CMP_CTX_set_log_cb(cmp_ctx, print_to_bio_out)) { CMP_err1("cannot set up error reporting and logging for %s", prog); goto err; } #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_tls_cert == NULL && opt_tls_key == NULL && opt_tls_keypass == NULL && opt_tls_extra == NULL && opt_tls_trusted == NULL && opt_tls_host == NULL) { if (opt_tls_used) CMP_warn("-tls_used given without any other TLS options"); } else if (!opt_tls_used) { CMP_warn("ignoring TLS options(s) since -tls_used is not given"); } if (opt_port != NULL) { if (opt_tls_used) { CMP_err("-tls_used option not supported with -port option"); goto err; } if (opt_server != NULL || opt_use_mock_srv) { CMP_err("The -port option excludes -server and -use_mock_srv"); goto err; } if (opt_reqin != NULL || opt_reqout != NULL) { CMP_err("The -port option does not support -reqin and -reqout"); goto err; } if (opt_rspin != NULL || opt_rspout != NULL) { CMP_err("The -port option does not support -rspin and -rspout"); goto err; } } if (opt_server != NULL && opt_use_mock_srv) { CMP_err("cannot use both -server and -use_mock_srv options"); goto err; } #endif if (opt_ignore_keyusage) (void)OSSL_CMP_CTX_set_option(cmp_ctx, OSSL_CMP_OPT_IGNORE_KEYUSAGE, 1); if (opt_no_cache_extracerts) (void)OSSL_CMP_CTX_set_option(cmp_ctx, OSSL_CMP_OPT_NO_CACHE_EXTRACERTS, 1); if (opt_reqout_only == NULL && (opt_use_mock_srv #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) || opt_port != NULL #endif )) { OSSL_CMP_SRV_CTX *srv_ctx; if ((srv_ctx = setup_srv_ctx(engine)) == NULL) goto err; srv_cmp_ctx = OSSL_CMP_SRV_CTX_get0_cmp_ctx(srv_ctx); OSSL_CMP_CTX_set_transfer_cb_arg(cmp_ctx, srv_ctx); if (!OSSL_CMP_CTX_set_log_cb(srv_cmp_ctx, print_to_bio_err)) { CMP_err1("cannot set up error reporting and logging for %s", prog); goto err; } OSSL_CMP_CTX_set_log_verbosity(srv_cmp_ctx, opt_verbosity); } #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_tls_used && (opt_use_mock_srv || opt_server == NULL)) { CMP_warn("ignoring -tls_used option since -use_mock_srv is given or -server is not given"); opt_tls_used = 0; } if (opt_port != NULL) { ret = cmp_server(srv_cmp_ctx); goto err; } if (opt_reqout_only != NULL) { const char *msg = "option is ignored since -reqout_only option is given"; #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (opt_server != NULL) CMP_warn1("-server %s", msg); #endif if (opt_use_mock_srv) CMP_warn1("-use_mock_srv %s", msg); if (opt_reqout != NULL) CMP_warn1("-reqout %s", msg); if (opt_rspin != NULL) CMP_warn1("-rspin %s", msg); if (opt_rspout != NULL) CMP_warn1("-rspout %s", msg); opt_reqout = opt_reqout_only; } if (opt_rspin != NULL) { if (opt_server != NULL) CMP_warn("-server option is not used if enough filenames given for -rspin"); if (opt_use_mock_srv) CMP_warn("-use_mock_srv option is not used if enough filenames given for -rspin"); } #endif if (!setup_client_ctx(cmp_ctx, engine)) { CMP_err("cannot set up CMP context"); goto err; } for (i = 0; i < opt_repeat; i++) { switch (opt_cmd) { case CMP_IR: newcert = OSSL_CMP_exec_IR_ses(cmp_ctx); if (newcert != NULL) ret = 1; break; case CMP_KUR: newcert = OSSL_CMP_exec_KUR_ses(cmp_ctx); if (newcert != NULL) ret = 1; break; case CMP_CR: newcert = OSSL_CMP_exec_CR_ses(cmp_ctx); if (newcert != NULL) ret = 1; break; case CMP_P10CR: newcert = OSSL_CMP_exec_P10CR_ses(cmp_ctx); if (newcert != NULL) ret = 1; break; case CMP_RR: ret = OSSL_CMP_exec_RR_ses(cmp_ctx); break; case CMP_GENM: ret = do_genm(cmp_ctx); default: break; } if (OSSL_CMP_CTX_get_status(cmp_ctx) < OSSL_CMP_PKISTATUS_accepted) { ret = 0; if (reqout_only_done) { ERR_clear_error(); ret = 1; } goto err; } print_status(); if (!save_cert_or_delete(OSSL_CMP_CTX_get0_validatedSrvCert(cmp_ctx), opt_srvcertout, "validated server")) ret = 0; if (!ret) goto err; ret = 0; if (save_free_certs(OSSL_CMP_CTX_get1_extraCertsIn(cmp_ctx), opt_extracertsout, "extra") < 0) goto err; if (newcert != NULL && (opt_cmd == CMP_IR || opt_cmd == CMP_CR || opt_cmd == CMP_KUR || opt_cmd == CMP_P10CR)) if (!save_cert_or_delete(newcert, opt_certout, "newly enrolled") || save_free_certs(OSSL_CMP_CTX_get1_newChain(cmp_ctx), opt_chainout, "chain") < 0 || save_free_certs(OSSL_CMP_CTX_get1_caPubs(cmp_ctx), opt_cacertsout, "CA") < 0) goto err; if (!OSSL_CMP_CTX_reinit(cmp_ctx)) goto err; } ret = 1; err: cleanse(opt_keypass); cleanse(opt_newkeypass); cleanse(opt_otherpass); #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) cleanse(opt_tls_keypass); #endif cleanse(opt_secret); cleanse(opt_srv_keypass); cleanse(opt_srv_secret); if (ret != 1) OSSL_CMP_CTX_print_errors(cmp_ctx); if (cmp_ctx != NULL) { #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) APP_HTTP_TLS_INFO *info = OSSL_CMP_CTX_get_http_cb_arg(cmp_ctx); (void)OSSL_CMP_CTX_set_http_cb_arg(cmp_ctx, NULL); #endif ossl_cmp_mock_srv_free(OSSL_CMP_CTX_get_transfer_cb_arg(cmp_ctx)); X509_STORE_free(OSSL_CMP_CTX_get_certConf_cb_arg(cmp_ctx)); OSSL_CMP_CTX_free(cmp_ctx); #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) if (info != NULL) { OPENSSL_free((char *)info->server); OPENSSL_free((char *)info->port); APP_HTTP_TLS_INFO_free(info); } #endif } X509_VERIFY_PARAM_free(vpm); release_engine(engine); NCONF_free(conf); OSSL_CMP_log_close(); return ret == 0 ? EXIT_FAILURE : EXIT_SUCCESS; }
apps
openssl/apps/cmp.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/conf.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> typedef enum OPTION_choice { OPT_COMMON, OPT_NOOUT, OPT_PUBKEY, OPT_VERIFY, OPT_IN, OPT_OUT, OPT_ENGINE, OPT_KEY, OPT_CHALLENGE, OPT_PASSIN, OPT_SPKAC, OPT_SPKSECT, OPT_KEYFORM, OPT_DIGEST, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS spkac_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"spksect", OPT_SPKSECT, 's', "Specify the name of an SPKAC-dedicated section of configuration"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), {"in", OPT_IN, '<', "Input file"}, {"key", OPT_KEY, '<', "Create SPKAC using private key"}, {"keyform", OPT_KEYFORM, 'f', "Private key file format (ENGINE, other values ignored)"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"challenge", OPT_CHALLENGE, 's', "Challenge string"}, {"spkac", OPT_SPKAC, 's', "Alternative SPKAC name"}, OPT_SECTION("Output"), {"digest", OPT_DIGEST, 's', "Sign new SPKAC with the specified digest (default: MD5)" }, {"out", OPT_OUT, '>', "Output file"}, {"noout", OPT_NOOUT, '-', "Don't print SPKAC"}, {"pubkey", OPT_PUBKEY, '-', "Output public key"}, {"verify", OPT_VERIFY, '-', "Verify SPKAC signature"}, OPT_PROV_OPTIONS, {NULL} }; int spkac_main(int argc, char **argv) { BIO *out = NULL; CONF *conf = NULL; ENGINE *e = NULL; EVP_PKEY *pkey = NULL; NETSCAPE_SPKI *spki = NULL; char *challenge = NULL, *keyfile = NULL; char *infile = NULL, *outfile = NULL, *passinarg = NULL, *passin = NULL; char *spkstr = NULL, *prog; const char *spkac = "SPKAC", *spksect = "default"; const char *digest = "MD5"; EVP_MD *md = NULL; int i, ret = 1, verify = 0, noout = 0, pubkey = 0; int keyformat = FORMAT_UNDEF; OPTION_CHOICE o; prog = opt_init(argc, argv, spkac_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(spkac_options); ret = 0; goto end; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_NOOUT: noout = 1; break; case OPT_PUBKEY: pubkey = 1; break; case OPT_VERIFY: verify = 1; break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_KEY: keyfile = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyformat)) goto opthelp; break; case OPT_CHALLENGE: challenge = opt_arg(); break; case OPT_SPKAC: spkac = opt_arg(); break; case OPT_SPKSECT: spksect = opt_arg(); break; case OPT_DIGEST: digest = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (keyfile != NULL) { if (!opt_md(digest, &md)) goto end; pkey = load_key(strcmp(keyfile, "-") ? keyfile : NULL, keyformat, 1, passin, e, "private key"); if (pkey == NULL) goto end; spki = NETSCAPE_SPKI_new(); if (spki == NULL) goto end; if (challenge != NULL && !ASN1_STRING_set(spki->spkac->challenge, challenge, (int)strlen(challenge))) goto end; if (!NETSCAPE_SPKI_set_pubkey(spki, pkey)) { BIO_printf(bio_err, "Error setting public key\n"); goto end; } i = NETSCAPE_SPKI_sign(spki, pkey, md); if (i <= 0) { BIO_printf(bio_err, "Error signing SPKAC\n"); goto end; } spkstr = NETSCAPE_SPKI_b64_encode(spki); if (spkstr == NULL) goto end; out = bio_open_default(outfile, 'w', FORMAT_TEXT); if (out == NULL) { OPENSSL_free(spkstr); goto end; } BIO_printf(out, "SPKAC=%s\n", spkstr); OPENSSL_free(spkstr); ret = 0; goto end; } if ((conf = app_load_config(infile)) == NULL) goto end; spkstr = NCONF_get_string(conf, spksect, spkac); if (spkstr == NULL) { 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 == NULL) { BIO_printf(bio_err, "Error loading SPKAC\n"); ERR_print_errors(bio_err); goto end; } out = bio_open_default(outfile, 'w', FORMAT_TEXT); if (out == NULL) 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 > 0) { 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: EVP_MD_free(md); NCONF_free(conf); NETSCAPE_SPKI_free(spki); BIO_free_all(out); EVP_PKEY_free(pkey); release_engine(e); OPENSSL_free(passin); return ret; }
apps
openssl/apps/spkac.c
openssl
#include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bn.h> typedef enum OPTION_choice { OPT_COMMON, OPT_HEX, OPT_GENERATE, OPT_BITS, OPT_SAFE, OPT_CHECKS, OPT_PROV_ENUM } OPTION_CHOICE; static int check_num(const char *s, const int is_hex) { int i; if (is_hex) { for (i = 0; ('0' <= s[i] && s[i] <= '9') || ('A' <= s[i] && s[i] <= 'F') || ('a' <= s[i] && s[i] <= 'f'); i++); } else { for (i = 0; '0' <= s[i] && s[i] <= '9'; i++); } return s[i] == 0; } const OPTIONS prime_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [number...]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"bits", OPT_BITS, 'p', "Size of number in bits"}, {"checks", OPT_CHECKS, 'p', "Number of checks"}, OPT_SECTION("Output"), {"hex", OPT_HEX, '-', "Hex output"}, {"generate", OPT_GENERATE, '-', "Generate a prime"}, {"safe", OPT_SAFE, '-', "When used with -generate, generate a safe prime"}, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"number", 0, 0, "Number(s) to check for primality if not generating"}, {NULL} }; int prime_main(int argc, char **argv) { BIGNUM *bn = NULL; int hex = 0, generate = 0, bits = 0, safe = 0, ret = 1; char *prog; OPTION_CHOICE o; prog = opt_init(argc, argv, prime_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(prime_options); ret = 0; goto end; case OPT_HEX: hex = 1; break; case OPT_GENERATE: generate = 1; break; case OPT_BITS: bits = atoi(opt_arg()); break; case OPT_SAFE: safe = 1; break; case OPT_CHECKS: opt_arg(); break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } if (generate && !opt_check_rest_arg(NULL)) goto opthelp; argc = opt_num_rest(); argv = opt_rest(); if (!generate && argc == 0) { BIO_printf(bio_err, "Missing number (s) to check\n"); goto opthelp; } if (generate) { char *s; if (!bits) { BIO_printf(bio_err, "Specify the number of bits.\n"); goto end; } bn = BN_new(); if (bn == NULL) { BIO_printf(bio_err, "Out of memory.\n"); goto end; } if (!BN_generate_prime_ex(bn, bits, safe, NULL, NULL, NULL)) { BIO_printf(bio_err, "Failed to generate prime.\n"); goto end; } s = hex ? BN_bn2hex(bn) : BN_bn2dec(bn); if (s == NULL) { BIO_printf(bio_err, "Out of memory.\n"); goto end; } BIO_printf(bio_out, "%s\n", s); OPENSSL_free(s); } else { for ( ; *argv; argv++) { int r = check_num(argv[0], hex); if (r) r = hex ? BN_hex2bn(&bn, argv[0]) : BN_dec2bn(&bn, argv[0]); if (!r) { BIO_printf(bio_err, "Failed to process value (%s)\n", argv[0]); goto end; } BN_print(bio_out, bn); BIO_printf(bio_out, " (%s) %s prime\n", argv[0], BN_check_prime(bn, NULL, NULL) ? "is" : "is not"); } } ret = 0; end: BN_free(bn); return ret; }
apps
openssl/apps/prime.c
openssl
#include <stdio.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/crypto.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/x509_vfy.h> #include <openssl/x509v3.h> #include <openssl/cms.h> static int save_certs(char *signerfile, STACK_OF(X509) *signers); static int cms_cb(int ok, X509_STORE_CTX *ctx); static void receipt_request_print(CMS_ContentInfo *cms); static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING) *rr_from); static int cms_set_pkey_param(EVP_PKEY_CTX *pctx, STACK_OF(OPENSSL_STRING) *param); #define SMIME_OP 0x100 #define SMIME_IP 0x200 #define SMIME_SIGNERS 0x400 #define SMIME_ENCRYPT (1 | SMIME_OP) #define SMIME_DECRYPT (2 | SMIME_IP) #define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS) #define SMIME_VERIFY (4 | SMIME_IP) #define SMIME_RESIGN (5 | SMIME_IP | SMIME_OP | SMIME_SIGNERS) #define SMIME_SIGN_RECEIPT (6 | SMIME_IP | SMIME_OP) #define SMIME_VERIFY_RECEIPT (7 | SMIME_IP) #define SMIME_DIGEST_CREATE (8 | SMIME_OP) #define SMIME_DIGEST_VERIFY (9 | SMIME_IP) #define SMIME_COMPRESS (10 | SMIME_OP) #define SMIME_UNCOMPRESS (11 | SMIME_IP) #define SMIME_ENCRYPTED_ENCRYPT (12 | SMIME_OP) #define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP) #define SMIME_DATA_CREATE (14 | SMIME_OP) #define SMIME_DATA_OUT (15 | SMIME_IP) #define SMIME_CMSOUT (16 | SMIME_IP | SMIME_OP) static int verify_err = 0; typedef struct cms_key_param_st cms_key_param; struct cms_key_param_st { int idx; STACK_OF(OPENSSL_STRING) *param; cms_key_param *next; }; typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_ENCRYPT, OPT_DECRYPT, OPT_SIGN, OPT_CADES, OPT_SIGN_RECEIPT, OPT_RESIGN, OPT_VERIFY, OPT_VERIFY_RETCODE, OPT_VERIFY_RECEIPT, OPT_CMSOUT, OPT_DATA_OUT, OPT_DATA_CREATE, OPT_DIGEST_VERIFY, OPT_DIGEST, OPT_DIGEST_CREATE, OPT_COMPRESS, OPT_UNCOMPRESS, OPT_ED_DECRYPT, OPT_ED_ENCRYPT, OPT_DEBUG_DECRYPT, OPT_TEXT, OPT_ASCIICRLF, OPT_NOINTERN, OPT_NOVERIFY, OPT_NOCERTS, OPT_NOATTR, OPT_NODETACH, OPT_NOSMIMECAP, OPT_BINARY, OPT_KEYID, OPT_NOSIGS, OPT_NO_CONTENT_VERIFY, OPT_NO_ATTR_VERIFY, OPT_INDEF, OPT_NOINDEF, OPT_CRLFEOL, OPT_NOOUT, OPT_RR_PRINT, OPT_RR_ALL, OPT_RR_FIRST, OPT_RCTFORM, OPT_CERTFILE, OPT_CAFILE, OPT_CAPATH, OPT_CASTORE, OPT_NOCAPATH, OPT_NOCAFILE, OPT_NOCASTORE, OPT_CONTENT, OPT_PRINT, OPT_NAMEOPT, OPT_SECRETKEY, OPT_SECRETKEYID, OPT_PWRI_PASSWORD, OPT_ECONTENT_TYPE, OPT_PASSIN, OPT_TO, OPT_FROM, OPT_SUBJECT, OPT_SIGNER, OPT_RECIP, OPT_CERTSOUT, OPT_MD, OPT_INKEY, OPT_KEYFORM, OPT_KEYOPT, OPT_RR_FROM, OPT_RR_TO, OPT_AES128_WRAP, OPT_AES192_WRAP, OPT_AES256_WRAP, OPT_3DES_WRAP, OPT_WRAP, OPT_ENGINE, OPT_R_ENUM, OPT_PROV_ENUM, OPT_CONFIG, OPT_V_ENUM, OPT_CIPHER, OPT_ORIGINATOR } OPTION_CHOICE; const OPTIONS cms_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] [cert...]\n"}, {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("General"), {"in", OPT_IN, '<', "Input file"}, {"out", OPT_OUT, '>', "Output file"}, OPT_CONFIG_OPTION, OPT_SECTION("Operation"), {"encrypt", OPT_ENCRYPT, '-', "Encrypt message"}, {"decrypt", OPT_DECRYPT, '-', "Decrypt encrypted message"}, {"sign", OPT_SIGN, '-', "Sign message"}, {"verify", OPT_VERIFY, '-', "Verify signed message"}, {"resign", OPT_RESIGN, '-', "Resign a signed message"}, {"sign_receipt", OPT_SIGN_RECEIPT, '-', "Generate a signed receipt for a message"}, {"verify_receipt", OPT_VERIFY_RECEIPT, '<', "Verify receipts; exit if receipt signatures do not verify"}, {"digest", OPT_DIGEST, 's', "Sign a pre-computed digest in hex notation"}, {"digest_create", OPT_DIGEST_CREATE, '-', "Create a CMS \"DigestedData\" object"}, {"digest_verify", OPT_DIGEST_VERIFY, '-', "Verify a CMS \"DigestedData\" object and output it"}, {"compress", OPT_COMPRESS, '-', "Create a CMS \"CompressedData\" object"}, {"uncompress", OPT_UNCOMPRESS, '-', "Uncompress a CMS \"CompressedData\" object"}, {"EncryptedData_encrypt", OPT_ED_ENCRYPT, '-', "Create CMS \"EncryptedData\" object using symmetric key"}, {"EncryptedData_decrypt", OPT_ED_DECRYPT, '-', "Decrypt CMS \"EncryptedData\" object using symmetric key"}, {"data_create", OPT_DATA_CREATE, '-', "Create a CMS \"Data\" object"}, {"data_out", OPT_DATA_OUT, '-', "Copy CMS \"Data\" object to output"}, {"cmsout", OPT_CMSOUT, '-', "Output CMS structure"}, OPT_SECTION("File format"), {"inform", OPT_INFORM, 'c', "Input format SMIME (default), PEM or DER"}, {"outform", OPT_OUTFORM, 'c', "Output format SMIME (default), PEM or DER"}, {"rctform", OPT_RCTFORM, 'F', "Receipt file format"}, {"stream", OPT_INDEF, '-', "Enable CMS streaming"}, {"indef", OPT_INDEF, '-', "Same as -stream"}, {"noindef", OPT_NOINDEF, '-', "Disable CMS streaming"}, {"binary", OPT_BINARY, '-', "Treat input as binary: do not translate to canonical form"}, {"crlfeol", OPT_CRLFEOL, '-', "Use CRLF as EOL termination instead of CR only" }, {"asciicrlf", OPT_ASCIICRLF, '-', "Perform CRLF canonicalisation when signing"}, OPT_SECTION("Keys and passwords"), {"pwri_password", OPT_PWRI_PASSWORD, 's', "Specific password for recipient"}, {"secretkey", OPT_SECRETKEY, 's', "Use specified hex-encoded key to decrypt/encrypt recipients or content"}, {"secretkeyid", OPT_SECRETKEYID, 's', "Identity of the -secretkey for CMS \"KEKRecipientInfo\" object"}, {"inkey", OPT_INKEY, 's', "Input private key (if not signer or recipient)"}, {"passin", OPT_PASSIN, 's', "Input file pass phrase source"}, {"keyopt", OPT_KEYOPT, 's', "Set public key parameters as n:v pairs"}, {"keyform", OPT_KEYFORM, 'f', "Input private key format (ENGINE, other values ignored)"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine e, possibly a hardware device"}, #endif OPT_PROV_OPTIONS, OPT_R_OPTIONS, OPT_SECTION("Encryption and decryption"), {"originator", OPT_ORIGINATOR, 's', "Originator certificate file"}, {"recip", OPT_RECIP, '<', "Recipient cert file"}, {"cert...", OPT_PARAM, '.', "Recipient certs (optional; used only when encrypting)"}, {"", OPT_CIPHER, '-', "The encryption algorithm to use (any supported cipher)"}, {"wrap", OPT_WRAP, 's', "Key wrap algorithm to use when encrypting with key agreement"}, {"aes128-wrap", OPT_AES128_WRAP, '-', "Use AES128 to wrap key"}, {"aes192-wrap", OPT_AES192_WRAP, '-', "Use AES192 to wrap key"}, {"aes256-wrap", OPT_AES256_WRAP, '-', "Use AES256 to wrap key"}, {"des3-wrap", OPT_3DES_WRAP, '-', "Use 3DES-EDE to wrap key"}, {"debug_decrypt", OPT_DEBUG_DECRYPT, '-', "Disable MMA protection, return error if no recipient found (see doc)"}, OPT_SECTION("Signing"), {"md", OPT_MD, 's', "Digest algorithm to use"}, {"signer", OPT_SIGNER, 's', "Signer certificate input file"}, {"certfile", OPT_CERTFILE, '<', "Other certificates file"}, {"cades", OPT_CADES, '-', "Include signingCertificate attribute (CAdES-BES)"}, {"nodetach", OPT_NODETACH, '-', "Use opaque signing"}, {"nocerts", OPT_NOCERTS, '-', "Don't include signer's certificate when signing"}, {"noattr", OPT_NOATTR, '-', "Don't include any signed attributes"}, {"nosmimecap", OPT_NOSMIMECAP, '-', "Omit the SMIMECapabilities attribute"}, {"receipt_request_all", OPT_RR_ALL, '-', "When signing, create a receipt request for all recipients"}, {"receipt_request_first", OPT_RR_FIRST, '-', "When signing, create a receipt request for first recipient"}, {"receipt_request_from", OPT_RR_FROM, 's', "Create signed receipt request with specified email address"}, {"receipt_request_to", OPT_RR_TO, 's', "Create signed receipt targeted to specified address"}, OPT_SECTION("Verification"), {"signer", OPT_DUP, 's', "Signer certificate(s) output file"}, {"content", OPT_CONTENT, '<', "Supply or override content for detached signature"}, {"no_content_verify", OPT_NO_CONTENT_VERIFY, '-', "Do not verify signed content signatures"}, {"no_attr_verify", OPT_NO_ATTR_VERIFY, '-', "Do not verify signed attribute signatures"}, {"nosigs", OPT_NOSIGS, '-', "Don't verify message signature"}, {"noverify", OPT_NOVERIFY, '-', "Don't verify signers certificate"}, {"nointern", OPT_NOINTERN, '-', "Don't search certificates in message for signer"}, {"cades", OPT_DUP, '-', "Check signingCertificate (CAdES-BES)"}, {"verify_retcode", OPT_VERIFY_RETCODE, '-', "Exit non-zero on verification failure"}, {"CAfile", OPT_CAFILE, '<', "Trusted certificates file"}, {"CApath", OPT_CAPATH, '/', "Trusted certificates directory"}, {"CAstore", OPT_CASTORE, ':', "Trusted certificates store URI"}, {"no-CAfile", OPT_NOCAFILE, '-', "Do not load the default certificates file"}, {"no-CApath", OPT_NOCAPATH, '-', "Do not load certificates from the default certificates directory"}, {"no-CAstore", OPT_NOCASTORE, '-', "Do not load certificates from the default certificates store"}, OPT_SECTION("Output"), {"keyid", OPT_KEYID, '-', "Use subject key identifier"}, {"econtent_type", OPT_ECONTENT_TYPE, 's', "OID for external content"}, {"text", OPT_TEXT, '-', "Include or delete text MIME headers"}, {"certsout", OPT_CERTSOUT, '>', "Certificate output file"}, {"to", OPT_TO, 's', "To address"}, {"from", OPT_FROM, 's', "From address"}, {"subject", OPT_SUBJECT, 's', "Subject"}, OPT_SECTION("Printing"), {"noout", OPT_NOOUT, '-', "For the -cmsout operation do not output the parsed CMS structure"}, {"print", OPT_PRINT, '-', "For the -cmsout operation print out all fields of the CMS structure"}, {"nameopt", OPT_NAMEOPT, 's', "For the -print option specifies various strings printing options"}, {"receipt_request_print", OPT_RR_PRINT, '-', "Print CMS Receipt Request" }, OPT_V_OPTIONS, {NULL} }; static CMS_ContentInfo *load_content_info(int informat, BIO *in, int flags, BIO **indata, const char *name) { CMS_ContentInfo *ret, *ci; ret = CMS_ContentInfo_new_ex(app_get0_libctx(), app_get0_propq()); if (ret == NULL) { BIO_printf(bio_err, "Error allocating CMS_contentinfo\n"); return NULL; } switch (informat) { case FORMAT_SMIME: ci = SMIME_read_CMS_ex(in, flags, indata, &ret); break; case FORMAT_PEM: ci = PEM_read_bio_CMS(in, &ret, NULL, NULL); break; case FORMAT_ASN1: ci = d2i_CMS_bio(in, &ret); break; default: BIO_printf(bio_err, "Bad input format for %s\n", name); goto err; } if (ci == NULL) { BIO_printf(bio_err, "Error reading %s Content Info\n", name); goto err; } return ret; err: CMS_ContentInfo_free(ret); return NULL; } int cms_main(int argc, char **argv) { CONF *conf = NULL; ASN1_OBJECT *econtent_type = NULL; BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL; CMS_ContentInfo *cms = NULL, *rcms = NULL; CMS_ReceiptRequest *rr = NULL; ENGINE *e = NULL; EVP_PKEY *key = NULL; EVP_CIPHER *cipher = NULL, *wrap_cipher = NULL; EVP_MD *sign_md = NULL; STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL; STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL; STACK_OF(X509) *encerts = sk_X509_new_null(), *other = NULL; X509 *cert = NULL, *recip = NULL, *signer = NULL, *originator = NULL; X509_STORE *store = NULL; X509_VERIFY_PARAM *vpm = X509_VERIFY_PARAM_new(); char *certfile = NULL, *keyfile = NULL, *contfile = NULL; const char *CAfile = NULL, *CApath = NULL, *CAstore = NULL; char *certsoutfile = NULL, *digestname = NULL, *wrapname = NULL; int noCAfile = 0, noCApath = 0, noCAstore = 0; char *digesthex = NULL; unsigned char *digestbin = NULL; long digestlen = 0; char *infile = NULL, *outfile = NULL, *rctfile = NULL; char *passinarg = NULL, *passin = NULL, *signerfile = NULL; char *originatorfile = NULL, *recipfile = NULL, *ciphername = NULL; char *to = NULL, *from = NULL, *subject = NULL, *prog; cms_key_param *key_first = NULL, *key_param = NULL; int flags = CMS_DETACHED, binary_files = 0; int noout = 0, print = 0, keyidx = -1, vpmtouched = 0; int informat = FORMAT_SMIME, outformat = FORMAT_SMIME; int operation = 0, ret = 1, rr_print = 0, rr_allorfirst = -1; int verify_retcode = 0, rctformat = FORMAT_SMIME, keyform = FORMAT_UNDEF; size_t secret_keylen = 0, secret_keyidlen = 0; unsigned char *pwri_pass = NULL, *pwri_tmp = NULL; unsigned char *secret_key = NULL, *secret_keyid = NULL; long ltmp; const char *mime_eol = "\n"; OPTION_CHOICE o; OSSL_LIB_CTX *libctx = app_get0_libctx(); if (encerts == NULL || vpm == NULL) goto end; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, cms_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(cms_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PDS, &informat)) goto opthelp; 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_VERIFY: operation = SMIME_VERIFY; break; case OPT_RESIGN: operation = SMIME_RESIGN; break; case OPT_SIGN_RECEIPT: operation = SMIME_SIGN_RECEIPT; break; case OPT_VERIFY_RECEIPT: operation = SMIME_VERIFY_RECEIPT; rctfile = opt_arg(); break; case OPT_VERIFY_RETCODE: verify_retcode = 1; break; case OPT_DIGEST_CREATE: operation = SMIME_DIGEST_CREATE; break; case OPT_DIGEST: digesthex = opt_arg(); break; case OPT_DIGEST_VERIFY: operation = SMIME_DIGEST_VERIFY; break; case OPT_COMPRESS: operation = SMIME_COMPRESS; break; case OPT_UNCOMPRESS: operation = SMIME_UNCOMPRESS; break; case OPT_ED_ENCRYPT: operation = SMIME_ENCRYPTED_ENCRYPT; break; case OPT_ED_DECRYPT: operation = SMIME_ENCRYPTED_DECRYPT; break; case OPT_DATA_CREATE: operation = SMIME_DATA_CREATE; break; case OPT_DATA_OUT: operation = SMIME_DATA_OUT; break; case OPT_CMSOUT: operation = SMIME_CMSOUT; break; case OPT_DEBUG_DECRYPT: flags |= CMS_DEBUG_DECRYPT; break; case OPT_TEXT: flags |= CMS_TEXT; break; case OPT_ASCIICRLF: flags |= CMS_ASCIICRLF; break; case OPT_NOINTERN: flags |= CMS_NOINTERN; break; case OPT_NOVERIFY: flags |= CMS_NO_SIGNER_CERT_VERIFY; break; case OPT_NOCERTS: flags |= CMS_NOCERTS; break; case OPT_NOATTR: flags |= CMS_NOATTR; break; case OPT_NODETACH: flags &= ~CMS_DETACHED; break; case OPT_NOSMIMECAP: flags |= CMS_NOSMIMECAP; break; case OPT_BINARY: flags |= CMS_BINARY; break; case OPT_CADES: flags |= CMS_CADES; break; case OPT_KEYID: flags |= CMS_USE_KEYID; break; case OPT_NOSIGS: flags |= CMS_NOSIGS; break; case OPT_NO_CONTENT_VERIFY: flags |= CMS_NO_CONTENT_VERIFY; break; case OPT_NO_ATTR_VERIFY: flags |= CMS_NO_ATTR_VERIFY; break; case OPT_INDEF: flags |= CMS_STREAM; break; case OPT_NOINDEF: flags &= ~CMS_STREAM; break; case OPT_CRLFEOL: mime_eol = "\r\n"; flags |= CMS_CRLFEOL; break; case OPT_NOOUT: noout = 1; break; case OPT_RR_PRINT: rr_print = 1; break; case OPT_RR_ALL: rr_allorfirst = 0; break; case OPT_RR_FIRST: rr_allorfirst = 1; break; case OPT_RCTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER | OPT_FMT_SMIME, &rctformat)) goto opthelp; break; case OPT_CERTFILE: certfile = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_CASTORE: CAstore = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_NOCASTORE: noCAstore = 1; break; case OPT_IN: infile = opt_arg(); break; case OPT_CONTENT: contfile = opt_arg(); break; case OPT_RR_FROM: if (rr_from == NULL && (rr_from = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(rr_from, opt_arg()); break; case OPT_RR_TO: if (rr_to == NULL && (rr_to = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(rr_to, opt_arg()); break; case OPT_PRINT: noout = print = 1; break; case OPT_NAMEOPT: if (!set_nameopt(opt_arg())) goto opthelp; break; case OPT_SECRETKEY: if (secret_key != NULL) { BIO_printf(bio_err, "Invalid key (supplied twice) %s\n", opt_arg()); goto opthelp; } secret_key = OPENSSL_hexstr2buf(opt_arg(), &ltmp); if (secret_key == NULL) { BIO_printf(bio_err, "Invalid key %s\n", opt_arg()); goto end; } secret_keylen = (size_t)ltmp; break; case OPT_SECRETKEYID: if (secret_keyid != NULL) { BIO_printf(bio_err, "Invalid id (supplied twice) %s\n", opt_arg()); goto opthelp; } secret_keyid = OPENSSL_hexstr2buf(opt_arg(), &ltmp); if (secret_keyid == NULL) { BIO_printf(bio_err, "Invalid id %s\n", opt_arg()); goto opthelp; } secret_keyidlen = (size_t)ltmp; break; case OPT_PWRI_PASSWORD: pwri_pass = (unsigned char *)opt_arg(); break; case OPT_ECONTENT_TYPE: if (econtent_type != NULL) { BIO_printf(bio_err, "Invalid OID (supplied twice) %s\n", opt_arg()); goto opthelp; } econtent_type = OBJ_txt2obj(opt_arg(), 0); if (econtent_type == NULL) { BIO_printf(bio_err, "Invalid OID %s\n", opt_arg()); goto opthelp; } break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_PASSIN: passinarg = opt_arg(); break; case OPT_TO: to = opt_arg(); break; case OPT_FROM: from = opt_arg(); break; case OPT_SUBJECT: subject = opt_arg(); break; case OPT_CERTSOUT: certsoutfile = opt_arg(); break; case OPT_MD: digestname = opt_arg(); break; case OPT_SIGNER: if (signerfile != NULL) { 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_ORIGINATOR: originatorfile = opt_arg(); break; case OPT_INKEY: if (keyfile != NULL) { if (signerfile == NULL) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto end; } if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); signerfile = NULL; if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(skkeys, keyfile); } keyfile = opt_arg(); break; case OPT_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &keyform)) goto opthelp; break; case OPT_RECIP: if (operation == SMIME_ENCRYPT) { cert = load_cert(opt_arg(), FORMAT_UNDEF, "recipient certificate file"); if (cert == NULL) goto end; if (!sk_X509_push(encerts, cert)) goto end; cert = NULL; } else { recipfile = opt_arg(); } break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_KEYOPT: keyidx = -1; if (operation == SMIME_ENCRYPT) { if (sk_X509_num(encerts) > 0) keyidx += sk_X509_num(encerts); } else { if (keyfile != NULL || signerfile != NULL) keyidx++; if (skkeys != NULL) keyidx += sk_OPENSSL_STRING_num(skkeys); } if (keyidx < 0) { BIO_printf(bio_err, "No key specified\n"); goto opthelp; } if (key_param == NULL || key_param->idx != keyidx) { cms_key_param *nparam; nparam = app_malloc(sizeof(*nparam), "key param buffer"); if ((nparam->param = sk_OPENSSL_STRING_new_null()) == NULL) { OPENSSL_free(nparam); goto end; } nparam->idx = keyidx; nparam->next = NULL; if (key_first == NULL) key_first = nparam; else key_param->next = nparam; key_param = nparam; } sk_OPENSSL_STRING_push(key_param->param, opt_arg()); break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_CONFIG: conf = app_load_config_modules(opt_arg()); if (conf == NULL) goto end; break; case OPT_WRAP: wrapname = opt_arg(); break; case OPT_AES128_WRAP: case OPT_AES192_WRAP: case OPT_AES256_WRAP: case OPT_3DES_WRAP: wrapname = opt_flag() + 1; break; } } if (!app_RAND_load()) goto end; if (digestname != NULL) { if (!opt_md(digestname, &sign_md)) goto end; } if (!opt_cipher_any(ciphername, &cipher)) goto end; if (wrapname != NULL) { if (!opt_cipher_any(wrapname, &wrap_cipher)) goto end; } argc = opt_num_rest(); argv = opt_rest(); if ((rr_allorfirst != -1 || rr_from != NULL) && rr_to == NULL) { BIO_puts(bio_err, "No Signed Receipts Recipients\n"); goto opthelp; } if (!(operation & SMIME_SIGNERS) && (rr_to != NULL || rr_from != NULL)) { BIO_puts(bio_err, "Signed receipts only allowed with -sign\n"); goto opthelp; } if (!(operation & SMIME_SIGNERS) && (skkeys != NULL || sksigners != NULL)) { BIO_puts(bio_err, "Multiple signers or keys not allowed\n"); goto opthelp; } if ((flags & CMS_CADES) != 0) { if ((flags & CMS_NOATTR) != 0) { BIO_puts(bio_err, "Incompatible options: " "CAdES requires signed attributes\n"); goto opthelp; } if (operation == SMIME_VERIFY && (flags & (CMS_NO_SIGNER_CERT_VERIFY | CMS_NO_ATTR_VERIFY)) != 0) { BIO_puts(bio_err, "Incompatible options: CAdES validation requires" " certs and signed attributes validations\n"); goto opthelp; } } if (operation & SMIME_SIGNERS) { if (keyfile != NULL && signerfile == NULL) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto opthelp; } if (signerfile != NULL) { if (sksigners == NULL && (sksigners = sk_OPENSSL_STRING_new_null()) == NULL) goto end; sk_OPENSSL_STRING_push(sksigners, signerfile); if (skkeys == NULL && (skkeys = sk_OPENSSL_STRING_new_null()) == NULL) goto end; if (keyfile == NULL) keyfile = signerfile; sk_OPENSSL_STRING_push(skkeys, keyfile); } if (sksigners == NULL) { BIO_printf(bio_err, "No signer certificate specified\n"); goto opthelp; } signerfile = NULL; keyfile = NULL; } else if (operation == SMIME_DECRYPT) { if (recipfile == NULL && keyfile == NULL && secret_key == NULL && pwri_pass == NULL) { BIO_printf(bio_err, "No recipient certificate or key specified\n"); goto opthelp; } } else if (operation == SMIME_ENCRYPT) { if (*argv == NULL && secret_key == NULL && pwri_pass == NULL && sk_X509_num(encerts) <= 0) { BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n"); goto opthelp; } } else if (!operation) { BIO_printf(bio_err, "No operation option (-encrypt|-decrypt|-sign|-verify|...) specified.\n"); goto opthelp; } if (!app_passwd(passinarg, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } ret = 2; if ((operation & SMIME_SIGNERS) == 0) { if ((flags & CMS_DETACHED) == 0) BIO_printf(bio_err, "Warning: -nodetach option is ignored for non-signing operation\n"); flags &= ~CMS_DETACHED; } if ((operation & SMIME_IP) == 0 && contfile != NULL) BIO_printf(bio_err, "Warning: -contfile option is ignored for the given operation\n"); if (operation != SMIME_ENCRYPT && *argv != NULL) BIO_printf(bio_err, "Warning: recipient certificate file parameters ignored for operation other than -encrypt\n"); if ((flags & CMS_BINARY) != 0) { if (!(operation & SMIME_OP)) outformat = FORMAT_BINARY; if (!(operation & SMIME_IP)) informat = FORMAT_BINARY; if ((operation & SMIME_SIGNERS) != 0 && (flags & CMS_DETACHED) != 0) binary_files = 1; if ((operation & SMIME_IP) != 0 && contfile == NULL) binary_files = 1; } if (operation == SMIME_ENCRYPT) { if (!cipher) { #ifndef OPENSSL_NO_DES cipher = (EVP_CIPHER *)EVP_des_ede3_cbc(); #else BIO_printf(bio_err, "No cipher selected\n"); goto end; #endif } if (secret_key && !secret_keyid) { BIO_printf(bio_err, "No secret key id\n"); goto end; } for (; *argv != NULL; argv++) { cert = load_cert(*argv, FORMAT_UNDEF, "recipient certificate file"); if (cert == NULL) goto end; if (!sk_X509_push(encerts, cert)) goto end; cert = NULL; } } if (certfile != NULL) { if (!load_certs(certfile, 0, &other, NULL, "certificate file")) { ERR_print_errors(bio_err); goto end; } } if (recipfile != NULL && (operation == SMIME_DECRYPT)) { if ((recip = load_cert(recipfile, FORMAT_UNDEF, "recipient certificate file")) == NULL) { ERR_print_errors(bio_err); goto end; } } if (originatorfile != NULL) { if ((originator = load_cert(originatorfile, FORMAT_UNDEF, "originator certificate file")) == NULL) { ERR_print_errors(bio_err); goto end; } } if (operation == SMIME_SIGN_RECEIPT) { if ((signer = load_cert(signerfile, FORMAT_UNDEF, "receipt signer certificate file")) == NULL) { ERR_print_errors(bio_err); goto end; } } if ((operation == SMIME_DECRYPT) || (operation == SMIME_ENCRYPT)) { if (keyfile == NULL) keyfile = recipfile; } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) { if (keyfile == NULL) keyfile = signerfile; } else { keyfile = NULL; } if (keyfile != NULL) { key = load_key(keyfile, keyform, 0, passin, e, "signing key"); if (key == NULL) goto end; } if (digesthex != NULL) { if (operation != SMIME_SIGN) { BIO_printf(bio_err, "Cannot use -digest for non-signing operation\n"); goto end; } if (infile != NULL || (flags & CMS_DETACHED) == 0 || (flags & CMS_STREAM) != 0) { BIO_printf(bio_err, "Cannot use -digest when -in, -nodetach or streaming is used\n"); goto end; } digestbin = OPENSSL_hexstr2buf(digesthex, &digestlen); if (digestbin == NULL) { BIO_printf(bio_err, "Invalid hex value after -digest\n"); goto end; } } else { in = bio_open_default(infile, 'r', binary_files ? FORMAT_BINARY : informat); if (in == NULL) goto end; } if (operation & SMIME_IP) { cms = load_content_info(informat, in, flags, &indata, "SMIME"); if (cms == NULL) goto end; if (contfile != NULL) { BIO_free(indata); if ((indata = BIO_new_file(contfile, "rb")) == NULL) { BIO_printf(bio_err, "Can't read content file %s\n", contfile); goto end; } } if (certsoutfile != NULL) { STACK_OF(X509) *allcerts; allcerts = CMS_get1_certs(cms); if (!save_certs(certsoutfile, allcerts)) { BIO_printf(bio_err, "Error writing certs to %s\n", certsoutfile); ret = 5; goto end; } OSSL_STACK_OF_X509_free(allcerts); } } if (rctfile != NULL) { char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r"; if ((rctin = BIO_new_file(rctfile, rctmode)) == NULL) { BIO_printf(bio_err, "Can't open receipt file %s\n", rctfile); goto end; } rcms = load_content_info(rctformat, rctin, 0, NULL, "receipt"); if (rcms == NULL) goto end; } out = bio_open_default(outfile, 'w', binary_files ? FORMAT_BINARY : outformat); if (out == NULL) goto end; if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) { if ((store = setup_verify(CAfile, noCAfile, CApath, noCApath, CAstore, noCAstore)) == NULL) goto end; X509_STORE_set_verify_cb(store, cms_cb); if (vpmtouched) X509_STORE_set1_param(store, vpm); } ret = 3; if (operation == SMIME_DATA_CREATE) { cms = CMS_data_create_ex(in, flags, libctx, app_get0_propq()); } else if (operation == SMIME_DIGEST_CREATE) { cms = CMS_digest_create_ex(in, sign_md, flags, libctx, app_get0_propq()); } else if (operation == SMIME_COMPRESS) { cms = CMS_compress(in, -1, flags); } else if (operation == SMIME_ENCRYPT) { int i; flags |= CMS_PARTIAL; cms = CMS_encrypt_ex(NULL, in, cipher, flags, libctx, app_get0_propq()); if (cms == NULL) goto end; for (i = 0; i < sk_X509_num(encerts); i++) { CMS_RecipientInfo *ri; cms_key_param *kparam; int tflags = flags | CMS_KEY_PARAM; EVP_PKEY_CTX *pctx; X509 *x = sk_X509_value(encerts, i); int res; for (kparam = key_first; kparam; kparam = kparam->next) { if (kparam->idx == i) { break; } } ri = CMS_add1_recipient(cms, x, key, originator, tflags); if (ri == NULL) goto end; pctx = CMS_RecipientInfo_get0_pkey_ctx(ri); if (kparam != NULL) { if (!cms_set_pkey_param(pctx, kparam->param)) goto end; } res = EVP_PKEY_CTX_ctrl(pctx, -1, -1, EVP_PKEY_CTRL_CIPHER, EVP_CIPHER_get_nid(cipher), NULL); if (res <= 0 && res != -2) goto end; if (CMS_RecipientInfo_type(ri) == CMS_RECIPINFO_AGREE && wrap_cipher != NULL) { EVP_CIPHER_CTX *wctx; wctx = CMS_RecipientInfo_kari_get0_ctx(ri); if (EVP_EncryptInit_ex(wctx, wrap_cipher, NULL, NULL, NULL) != 1) goto end; } } if (secret_key != NULL) { if (!CMS_add0_recipient_key(cms, NID_undef, secret_key, secret_keylen, secret_keyid, secret_keyidlen, NULL, NULL, NULL)) goto end; secret_key = NULL; secret_keyid = NULL; } if (pwri_pass != NULL) { pwri_tmp = (unsigned char *)OPENSSL_strdup((char *)pwri_pass); if (pwri_tmp == NULL) goto end; if (CMS_add0_recipient_password(cms, -1, NID_undef, NID_undef, pwri_tmp, -1, NULL) == NULL) goto end; pwri_tmp = NULL; } if (!(flags & CMS_STREAM)) { if (!CMS_final(cms, in, NULL, flags)) goto end; } } else if (operation == SMIME_ENCRYPTED_ENCRYPT) { cms = CMS_EncryptedData_encrypt_ex(in, cipher, secret_key, secret_keylen, flags, libctx, app_get0_propq()); } else if (operation == SMIME_SIGN_RECEIPT) { CMS_ContentInfo *srcms = NULL; STACK_OF(CMS_SignerInfo) *sis; CMS_SignerInfo *si; sis = CMS_get0_SignerInfos(cms); if (sis == NULL) goto end; si = sk_CMS_SignerInfo_value(sis, 0); srcms = CMS_sign_receipt(si, signer, key, other, flags); if (srcms == NULL) goto end; CMS_ContentInfo_free(cms); cms = srcms; } else if (operation & SMIME_SIGNERS) { int i; if (operation == SMIME_SIGN) { if ((flags & CMS_DETACHED) != 0 && digestbin == NULL) { if (outformat == FORMAT_SMIME) flags |= CMS_STREAM; } flags |= CMS_PARTIAL; cms = CMS_sign_ex(NULL, NULL, other, in, flags, libctx, app_get0_propq()); if (cms == NULL) goto end; if (econtent_type != NULL) CMS_set1_eContentType(cms, econtent_type); if (rr_to != NULL && ((rr = make_receipt_request(rr_to, rr_allorfirst, rr_from)) == NULL)) { BIO_puts(bio_err, "Signed Receipt Request Creation Error\n"); goto end; } } else { flags |= CMS_REUSE_DIGEST; } for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) { CMS_SignerInfo *si; cms_key_param *kparam; int tflags = flags; signerfile = sk_OPENSSL_STRING_value(sksigners, i); keyfile = sk_OPENSSL_STRING_value(skkeys, i); signer = load_cert(signerfile, FORMAT_UNDEF, "signer certificate"); if (signer == NULL) { ret = 2; goto end; } key = load_key(keyfile, keyform, 0, passin, e, "signing key"); if (key == NULL) { ret = 2; goto end; } for (kparam = key_first; kparam; kparam = kparam->next) { if (kparam->idx == i) { tflags |= CMS_KEY_PARAM; break; } } si = CMS_add1_signer(cms, signer, key, sign_md, tflags); if (si == NULL) goto end; if (kparam != NULL) { EVP_PKEY_CTX *pctx; pctx = CMS_SignerInfo_get0_pkey_ctx(si); if (!cms_set_pkey_param(pctx, kparam->param)) goto end; } if (rr != NULL && !CMS_add1_ReceiptRequest(si, rr)) goto end; X509_free(signer); signer = NULL; EVP_PKEY_free(key); key = NULL; } if (operation == SMIME_SIGN && digestbin != NULL && (flags & CMS_STREAM) == 0) { if (!CMS_final_digest(cms, digestbin, digestlen, NULL, flags)) goto end; } else if (operation == SMIME_SIGN && (flags & CMS_STREAM) == 0) { if (!CMS_final(cms, in, NULL, flags)) goto end; } } if (cms == NULL) { BIO_printf(bio_err, "Error creating CMS structure\n"); goto end; } ret = 4; if (operation == SMIME_DECRYPT) { if (flags & CMS_DEBUG_DECRYPT) CMS_decrypt(cms, NULL, NULL, NULL, NULL, flags); if (secret_key != NULL) { if (!CMS_decrypt_set1_key(cms, secret_key, secret_keylen, secret_keyid, secret_keyidlen)) { BIO_puts(bio_err, "Error decrypting CMS using secret key\n"); goto end; } } if (key != NULL) { if (!CMS_decrypt_set1_pkey_and_peer(cms, key, recip, originator)) { BIO_puts(bio_err, "Error decrypting CMS using private key\n"); goto end; } } if (pwri_pass != NULL) { if (!CMS_decrypt_set1_password(cms, pwri_pass, -1)) { BIO_puts(bio_err, "Error decrypting CMS using password\n"); goto end; } } if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) { BIO_printf(bio_err, "Error decrypting CMS structure\n"); goto end; } } else if (operation == SMIME_DATA_OUT) { if (!CMS_data(cms, out, flags)) goto end; } else if (operation == SMIME_UNCOMPRESS) { if (!CMS_uncompress(cms, indata, out, flags)) goto end; } else if (operation == SMIME_DIGEST_VERIFY) { if (CMS_digest_verify(cms, indata, out, flags) > 0) { BIO_printf(bio_err, "Verification successful\n"); } else { BIO_printf(bio_err, "Verification failure\n"); goto end; } } else if (operation == SMIME_ENCRYPTED_DECRYPT) { if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen, indata, out, flags)) goto end; } else if (operation == SMIME_VERIFY) { if (CMS_verify(cms, other, store, indata, out, flags) > 0) { BIO_printf(bio_err, "%s Verification successful\n", (flags & CMS_CADES) != 0 ? "CAdES" : "CMS"); } else { BIO_printf(bio_err, "%s Verification failure\n", (flags & CMS_CADES) != 0 ? "CAdES" : "CMS"); if (verify_retcode) ret = verify_err + 32; goto end; } if (signerfile != NULL) { STACK_OF(X509) *signers = CMS_get0_signers(cms); if (!save_certs(signerfile, signers)) { BIO_printf(bio_err, "Error writing signers to %s\n", signerfile); ret = 5; goto end; } sk_X509_free(signers); } if (rr_print) receipt_request_print(cms); } else if (operation == SMIME_VERIFY_RECEIPT) { if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) { BIO_printf(bio_err, "Verification successful\n"); } else { BIO_printf(bio_err, "Verification failure\n"); goto end; } } else { if (noout) { if (print) { ASN1_PCTX *pctx = NULL; if (get_nameopt() != XN_FLAG_ONELINE) { pctx = ASN1_PCTX_new(); if (pctx != NULL) { ASN1_PCTX_set_flags(pctx, ASN1_PCTX_FLAGS_SHOW_ABSENT); ASN1_PCTX_set_str_flags(pctx, get_nameopt()); ASN1_PCTX_set_nm_flags(pctx, get_nameopt()); } } CMS_ContentInfo_print_ctx(out, cms, 0, pctx); ASN1_PCTX_free(pctx); } } else if (outformat == FORMAT_SMIME) { 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 (operation == SMIME_RESIGN) ret = SMIME_write_CMS(out, cms, indata, flags); else ret = SMIME_write_CMS(out, cms, in, flags); } else if (outformat == FORMAT_PEM) { ret = PEM_write_bio_CMS_stream(out, cms, in, flags); } else if (outformat == FORMAT_ASN1) { ret = i2d_CMS_bio_stream(out, cms, in, flags); } else { BIO_printf(bio_err, "Bad output format for CMS file\n"); goto end; } if (ret <= 0) { ret = 6; goto end; } } ret = 0; end: if (ret) ERR_print_errors(bio_err); OSSL_STACK_OF_X509_free(encerts); OSSL_STACK_OF_X509_free(other); X509_VERIFY_PARAM_free(vpm); sk_OPENSSL_STRING_free(sksigners); sk_OPENSSL_STRING_free(skkeys); OPENSSL_free(secret_key); OPENSSL_free(secret_keyid); OPENSSL_free(pwri_tmp); ASN1_OBJECT_free(econtent_type); CMS_ReceiptRequest_free(rr); sk_OPENSSL_STRING_free(rr_to); sk_OPENSSL_STRING_free(rr_from); for (key_param = key_first; key_param;) { cms_key_param *tparam; sk_OPENSSL_STRING_free(key_param->param); tparam = key_param->next; OPENSSL_free(key_param); key_param = tparam; } X509_STORE_free(store); X509_free(cert); X509_free(recip); X509_free(signer); EVP_PKEY_free(key); EVP_CIPHER_free(cipher); EVP_CIPHER_free(wrap_cipher); EVP_MD_free(sign_md); CMS_ContentInfo_free(cms); CMS_ContentInfo_free(rcms); release_engine(e); BIO_free(rctin); BIO_free(in); BIO_free(indata); BIO_free_all(out); OPENSSL_free(digestbin); OPENSSL_free(passin); NCONF_free(conf); return ret; } static int save_certs(char *signerfile, STACK_OF(X509) *signers) { int i; BIO *tmp; if (signerfile == NULL) return 1; tmp = BIO_new_file(signerfile, "w"); if (tmp == NULL) return 0; for (i = 0; i < sk_X509_num(signers); i++) PEM_write_bio_X509(tmp, sk_X509_value(signers, i)); BIO_free(tmp); return 1; } static int cms_cb(int ok, X509_STORE_CTX *ctx) { int error; error = X509_STORE_CTX_get_error(ctx); verify_err = error; if ((error != X509_V_ERR_NO_EXPLICIT_POLICY) && ((error != X509_V_OK) || (ok != 2))) return ok; policies_print(ctx); return ok; } static void gnames_stack_print(STACK_OF(GENERAL_NAMES) *gns) { STACK_OF(GENERAL_NAME) *gens; GENERAL_NAME *gen; int i, j; for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) { gens = sk_GENERAL_NAMES_value(gns, i); for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) { gen = sk_GENERAL_NAME_value(gens, j); BIO_puts(bio_err, " "); GENERAL_NAME_print(bio_err, gen); BIO_puts(bio_err, "\n"); } } return; } static void receipt_request_print(CMS_ContentInfo *cms) { STACK_OF(CMS_SignerInfo) *sis; CMS_SignerInfo *si; CMS_ReceiptRequest *rr; int allorfirst; STACK_OF(GENERAL_NAMES) *rto, *rlist; ASN1_STRING *scid; int i, rv; sis = CMS_get0_SignerInfos(cms); for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) { si = sk_CMS_SignerInfo_value(sis, i); rv = CMS_get1_ReceiptRequest(si, &rr); BIO_printf(bio_err, "Signer %d:\n", i + 1); if (rv == 0) { BIO_puts(bio_err, " No Receipt Request\n"); } else if (rv < 0) { BIO_puts(bio_err, " Receipt Request Parse Error\n"); ERR_print_errors(bio_err); } else { const char *id; int idlen; CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst, &rlist, &rto); BIO_puts(bio_err, " Signed Content ID:\n"); idlen = ASN1_STRING_length(scid); id = (const char *)ASN1_STRING_get0_data(scid); BIO_dump_indent(bio_err, id, idlen, 4); BIO_puts(bio_err, " Receipts From"); if (rlist != NULL) { BIO_puts(bio_err, " List:\n"); gnames_stack_print(rlist); } else if (allorfirst == 1) { BIO_puts(bio_err, ": First Tier\n"); } else if (allorfirst == 0) { BIO_puts(bio_err, ": All\n"); } else { BIO_printf(bio_err, " Unknown (%d)\n", allorfirst); } BIO_puts(bio_err, " Receipts To:\n"); gnames_stack_print(rto); } CMS_ReceiptRequest_free(rr); } } static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns) { int i; STACK_OF(GENERAL_NAMES) *ret; GENERAL_NAMES *gens = NULL; GENERAL_NAME *gen = NULL; ret = sk_GENERAL_NAMES_new_null(); if (ret == NULL) goto err; for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) { char *str = sk_OPENSSL_STRING_value(ns, i); gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0); if (gen == NULL) goto err; gens = GENERAL_NAMES_new(); if (gens == NULL) goto err; if (!sk_GENERAL_NAME_push(gens, gen)) goto err; gen = NULL; if (!sk_GENERAL_NAMES_push(ret, gens)) goto err; gens = NULL; } return ret; err: sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free); GENERAL_NAMES_free(gens); GENERAL_NAME_free(gen); return NULL; } static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING) *rr_from) { STACK_OF(GENERAL_NAMES) *rct_to = NULL, *rct_from = NULL; CMS_ReceiptRequest *rr; rct_to = make_names_stack(rr_to); if (rct_to == NULL) goto err; if (rr_from != NULL) { rct_from = make_names_stack(rr_from); if (rct_from == NULL) goto err; } else { rct_from = NULL; } rr = CMS_ReceiptRequest_create0_ex(NULL, -1, rr_allorfirst, rct_from, rct_to, app_get0_libctx()); if (rr == NULL) goto err; return rr; err: sk_GENERAL_NAMES_pop_free(rct_to, GENERAL_NAMES_free); sk_GENERAL_NAMES_pop_free(rct_from, GENERAL_NAMES_free); return NULL; } static int cms_set_pkey_param(EVP_PKEY_CTX *pctx, STACK_OF(OPENSSL_STRING) *param) { char *keyopt; int i; if (sk_OPENSSL_STRING_num(param) <= 0) return 1; for (i = 0; i < sk_OPENSSL_STRING_num(param); i++) { keyopt = sk_OPENSSL_STRING_value(param, i); if (pkey_ctrl_string(pctx, keyopt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", keyopt); ERR_print_errors(bio_err); return 0; } } return 1; }
apps
openssl/apps/cms.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/ssl.h> typedef enum OPTION_choice { OPT_COMMON, OPT_INFORM, OPT_OUTFORM, OPT_IN, OPT_OUT, OPT_TEXT, OPT_CERT, OPT_NOOUT, OPT_CONTEXT } OPTION_CHOICE; const OPTIONS sess_id_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, {"context", OPT_CONTEXT, 's', "Set the session ID context"}, OPT_SECTION("Input"), {"in", OPT_IN, 's', "Input file - default stdin"}, {"inform", OPT_INFORM, 'F', "Input format - default PEM (DER or PEM)"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file - default stdout"}, {"outform", OPT_OUTFORM, 'f', "Output format - default PEM (PEM, DER or NSS)"}, {"text", OPT_TEXT, '-', "Print ssl session id details"}, {"cert", OPT_CERT, '-', "Output certificate "}, {"noout", OPT_NOOUT, '-', "Don't output the encoded session info"}, {NULL} }; static SSL_SESSION *load_sess_id(char *file, int format); int sess_id_main(int argc, char **argv) { SSL_SESSION *x = NULL; X509 *peer = NULL; BIO *out = NULL; char *infile = NULL, *outfile = NULL, *context = NULL, *prog; int informat = FORMAT_PEM, outformat = FORMAT_PEM; int cert = 0, noout = 0, text = 0, ret = 1, i, num = 0; OPTION_CHOICE o; prog = opt_init(argc, argv, sess_id_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(sess_id_options); ret = 0; goto end; case OPT_INFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat)) goto opthelp; break; case OPT_OUTFORM: if (!opt_format(opt_arg(), OPT_FMT_PEMDER | OPT_FMT_NSS, &outformat)) goto opthelp; break; case OPT_IN: infile = opt_arg(); break; case OPT_OUT: outfile = opt_arg(); break; case OPT_TEXT: text = ++num; break; case OPT_CERT: cert = ++num; break; case OPT_NOOUT: noout = ++num; break; case OPT_CONTEXT: context = opt_arg(); break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; x = load_sess_id(infile, informat); if (x == NULL) { goto end; } peer = SSL_SESSION_get0_peer(x); if (context != NULL) { size_t ctx_len = strlen(context); if (ctx_len > SSL_MAX_SID_CTX_LENGTH) { BIO_printf(bio_err, "Context too long\n"); goto end; } if (!SSL_SESSION_set1_id_context(x, (unsigned char *)context, ctx_len)) { BIO_printf(bio_err, "Error setting id context\n"); goto end; } } if (!noout || text) { out = bio_open_default(outfile, 'w', outformat); if (out == NULL) goto end; } if (text) { SSL_SESSION_print(out, x); if (cert) { if (peer == NULL) BIO_puts(out, "No certificate present\n"); else X509_print(out, peer); } } if (!noout && !cert) { if (outformat == FORMAT_ASN1) { i = i2d_SSL_SESSION_bio(out, x); } else if (outformat == FORMAT_PEM) { i = PEM_write_bio_SSL_SESSION(out, x); } else if (outformat == FORMAT_NSS) { i = SSL_SESSION_print_keylog(out, x); } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write SSL_SESSION\n"); goto end; } } else if (!noout && (peer != NULL)) { if (outformat == FORMAT_ASN1) { i = (int)i2d_X509_bio(out, peer); } else if (outformat == FORMAT_PEM) { i = PEM_write_bio_X509(out, peer); } else { BIO_printf(bio_err, "bad output format specified for outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write X509\n"); goto end; } } ret = 0; end: BIO_free_all(out); SSL_SESSION_free(x); return ret; } static SSL_SESSION *load_sess_id(char *infile, int format) { SSL_SESSION *x = NULL; BIO *in = NULL; in = bio_open_default(infile, 'r', format); if (in == NULL) goto end; if (format == FORMAT_ASN1) x = d2i_SSL_SESSION_bio(in, NULL); else x = PEM_read_bio_SSL_SESSION(in, NULL, NULL, NULL); if (x == NULL) { BIO_printf(bio_err, "unable to load SSL_SESSION\n"); ERR_print_errors(bio_err); goto end; } end: BIO_free(in); return x; }
apps
openssl/apps/sess_id.c
openssl
#include <openssl/opensslconf.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include "apps.h" #include "progs.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/rand.h> #define DEFBITS 2048 #define DEFPRIMES 2 static int verbose = 0; typedef enum OPTION_choice { OPT_COMMON, #ifndef OPENSSL_NO_DEPRECATED_3_0 OPT_3, #endif OPT_F4, OPT_ENGINE, OPT_OUT, OPT_PASSOUT, OPT_CIPHER, OPT_PRIMES, OPT_VERBOSE, OPT_QUIET, OPT_R_ENUM, OPT_PROV_ENUM, OPT_TRADITIONAL } OPTION_CHOICE; const OPTIONS genrsa_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] numbits\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Input"), #ifndef OPENSSL_NO_DEPRECATED_3_0 {"3", OPT_3, '-', "(deprecated) Use 3 for the E value"}, #endif {"F4", OPT_F4, '-', "Use the Fermat number F4 (0x10001) for the E value"}, {"f4", OPT_F4, '-', "Use the Fermat number F4 (0x10001) for the E value"}, OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output the key to specified file"}, {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, {"primes", OPT_PRIMES, 'p', "Specify number of primes"}, {"verbose", OPT_VERBOSE, '-', "Verbose output"}, {"quiet", OPT_QUIET, '-', "Terse output"}, {"traditional", OPT_TRADITIONAL, '-', "Use traditional format for private keys"}, {"", OPT_CIPHER, '-', "Encrypt the output with any supported cipher"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"numbits", 0, 0, "Size of key in bits"}, {NULL} }; int genrsa_main(int argc, char **argv) { BN_GENCB *cb = BN_GENCB_new(); ENGINE *eng = NULL; BIGNUM *bn = BN_new(); BIO *out = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_CIPHER *enc = NULL; int ret = 1, num = DEFBITS, private = 0, primes = DEFPRIMES; unsigned long f4 = RSA_F4; char *outfile = NULL, *passoutarg = NULL, *passout = NULL; char *prog, *hexe, *dece, *ciphername = NULL; OPTION_CHOICE o; int traditional = 0; if (bn == NULL || cb == NULL) goto end; opt_set_unknown_name("cipher"); prog = opt_init(argc, argv, genrsa_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(genrsa_options); goto end; #ifndef OPENSSL_NO_DEPRECATED_3_0 case OPT_3: f4 = RSA_3; break; #endif case OPT_F4: f4 = RSA_F4; break; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: eng = setup_engine(opt_arg(), 0); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; case OPT_PASSOUT: passoutarg = opt_arg(); break; case OPT_CIPHER: ciphername = opt_unknown(); break; case OPT_PRIMES: primes = opt_int_arg(); break; case OPT_VERBOSE: verbose = 1; break; case OPT_QUIET: verbose = 0; break; case OPT_TRADITIONAL: traditional = 1; break; } } argc = opt_num_rest(); argv = opt_rest(); if (argc == 1) { if (!opt_int(argv[0], &num) || num <= 0) goto end; if (num > OPENSSL_RSA_MAX_MODULUS_BITS) BIO_printf(bio_err, "Warning: It is not recommended to use more than %d bit for RSA keys.\n" " Your key size is %d! Larger key size may behave not as expected.\n", OPENSSL_RSA_MAX_MODULUS_BITS, num); } else if (!opt_check_rest_arg(NULL)) { goto opthelp; } if (!app_RAND_load()) goto end; private = 1; if (!opt_cipher(ciphername, &enc)) goto end; if (!app_passwd(NULL, passoutarg, NULL, &passout)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } out = bio_open_owner(outfile, FORMAT_PEM, private); if (out == NULL) goto end; if (!init_gen_str(&ctx, "RSA", eng, 0, app_get0_libctx(), app_get0_propq())) goto end; if (verbose) EVP_PKEY_CTX_set_cb(ctx, progress_cb); EVP_PKEY_CTX_set_app_data(ctx, bio_err); if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, num) <= 0) { BIO_printf(bio_err, "Error setting RSA length\n"); goto end; } if (!BN_set_word(bn, f4)) { BIO_printf(bio_err, "Error allocating RSA public exponent\n"); goto end; } if (EVP_PKEY_CTX_set1_rsa_keygen_pubexp(ctx, bn) <= 0) { BIO_printf(bio_err, "Error setting RSA public exponent\n"); goto end; } if (EVP_PKEY_CTX_set_rsa_keygen_primes(ctx, primes) <= 0) { BIO_printf(bio_err, "Error setting number of primes\n"); goto end; } pkey = app_keygen(ctx, "RSA", num, verbose); if (pkey == NULL) goto end; if (verbose) { BIGNUM *e = NULL; EVP_PKEY_get_bn_param(pkey, "e", &e); if (e == NULL) { BIO_printf(bio_err, "Error cannot access RSA e\n"); goto end; } hexe = BN_bn2hex(e); dece = BN_bn2dec(e); if (hexe && dece) { BIO_printf(bio_err, "e is %s (0x%s)\n", dece, hexe); } OPENSSL_free(hexe); OPENSSL_free(dece); BN_free(e); } if (traditional) { if (!PEM_write_bio_PrivateKey_traditional(out, pkey, enc, NULL, 0, NULL, passout)) goto end; } else { if (!PEM_write_bio_PrivateKey(out, pkey, enc, NULL, 0, NULL, passout)) goto end; } ret = 0; end: BN_free(bn); BN_GENCB_free(cb); EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); EVP_CIPHER_free(enc); BIO_free_all(out); release_engine(eng); OPENSSL_free(passout); if (ret != 0) ERR_print_errors(bio_err); return ret; }
apps
openssl/apps/genrsa.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include "progs.h" #include <openssl/evp.h> #include <openssl/crypto.h> #include <openssl/bn.h> typedef enum OPTION_choice { OPT_COMMON, OPT_B, OPT_D, OPT_E, OPT_M, OPT_F, OPT_O, OPT_P, OPT_V, OPT_A, OPT_R, OPT_C } OPTION_CHOICE; const OPTIONS version_options[] = { OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, OPT_SECTION("Output"), {"a", OPT_A, '-', "Show all data"}, {"b", OPT_B, '-', "Show build date"}, {"d", OPT_D, '-', "Show configuration directory"}, {"e", OPT_E, '-', "Show engines directory"}, {"m", OPT_M, '-', "Show modules directory"}, {"f", OPT_F, '-', "Show compiler flags used"}, {"o", OPT_O, '-', "Show some internal datatype options"}, {"p", OPT_P, '-', "Show target build platform"}, {"r", OPT_R, '-', "Show random seeding options"}, {"v", OPT_V, '-', "Show library version"}, {"c", OPT_C, '-', "Show CPU settings info"}, {NULL} }; int version_main(int argc, char **argv) { int ret = 1, dirty = 0, seed = 0; int cflags = 0, version = 0, date = 0, options = 0, platform = 0, dir = 0; int engdir = 0, moddir = 0, cpuinfo = 0; char *prog; OPTION_CHOICE o; prog = opt_init(argc, argv, version_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(version_options); ret = 0; goto end; case OPT_B: dirty = date = 1; break; case OPT_D: dirty = dir = 1; break; case OPT_E: dirty = engdir = 1; break; case OPT_M: dirty = moddir = 1; break; case OPT_F: dirty = cflags = 1; break; case OPT_O: dirty = options = 1; break; case OPT_P: dirty = platform = 1; break; case OPT_R: dirty = seed = 1; break; case OPT_V: dirty = version = 1; break; case OPT_C: dirty = cpuinfo = 1; break; case OPT_A: seed = options = cflags = version = date = platform = dir = engdir = moddir = cpuinfo = 1; break; } } if (!opt_check_rest_arg(NULL)) goto opthelp; if (!dirty) version = 1; if (version) printf("%s (Library: %s)\n", OPENSSL_VERSION_TEXT, OpenSSL_version(OPENSSL_VERSION)); if (date) printf("%s\n", OpenSSL_version(OPENSSL_BUILT_ON)); if (platform) printf("%s\n", OpenSSL_version(OPENSSL_PLATFORM)); if (options) { printf("options: "); printf(" %s", BN_options()); printf("\n"); } if (cflags) printf("%s\n", OpenSSL_version(OPENSSL_CFLAGS)); if (dir) printf("%s\n", OpenSSL_version(OPENSSL_DIR)); if (engdir) printf("%s\n", OpenSSL_version(OPENSSL_ENGINES_DIR)); if (moddir) printf("%s\n", OpenSSL_version(OPENSSL_MODULES_DIR)); if (seed) { const char *src = OPENSSL_info(OPENSSL_INFO_SEED_SOURCE); printf("Seeding source: %s\n", src ? src : "N/A"); } if (cpuinfo) printf("%s\n", OpenSSL_version(OPENSSL_CPU_INFO)); ret = 0; end: return ret; } #if defined(__TANDEM) && defined(OPENSSL_VPROC) # define OPENSSL_VPROC_STRING_(x) x##_OPENSSL # define OPENSSL_VPROC_STRING(x) OPENSSL_VPROC_STRING_(x) # define OPENSSL_VPROC_FUNC OPENSSL_VPROC_STRING(OPENSSL_VPROC) void OPENSSL_VPROC_FUNC(void) {} #endif
apps
openssl/apps/version.c
openssl
#include "apps.h" #include "progs.h" #include <ctype.h> #include <stdio.h> #include <string.h> #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/rand.h> typedef enum OPTION_choice { OPT_COMMON, OPT_OUT, OPT_ENGINE, OPT_BASE64, OPT_HEX, OPT_R_ENUM, OPT_PROV_ENUM } OPTION_CHOICE; const OPTIONS rand_options[] = { {OPT_HELP_STR, 1, '-', "Usage: %s [options] num[K|M|G|T]\n"}, OPT_SECTION("General"), {"help", OPT_HELP, '-', "Display this summary"}, #ifndef OPENSSL_NO_ENGINE {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, #endif OPT_SECTION("Output"), {"out", OPT_OUT, '>', "Output file"}, {"base64", OPT_BASE64, '-', "Base64 encode output"}, {"hex", OPT_HEX, '-', "Hex encode output"}, OPT_R_OPTIONS, OPT_PROV_OPTIONS, OPT_PARAMETERS(), {"num", 0, 0, "Number of bytes to generate"}, {NULL} }; int rand_main(int argc, char **argv) { ENGINE *e = NULL; BIO *out = NULL; char *outfile = NULL, *prog; OPTION_CHOICE o; int format = FORMAT_BINARY, r, i, ret = 1; size_t buflen = (1 << 16); long num = -1; uint64_t scaled_num = 0; uint8_t *buf = NULL; prog = opt_init(argc, argv, rand_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: opt_help(rand_options); ret = 0; goto end; case OPT_OUT: outfile = opt_arg(); break; case OPT_ENGINE: e = setup_engine(opt_arg(), 0); break; case OPT_R_CASES: if (!opt_rand(o)) goto end; break; case OPT_BASE64: format = FORMAT_BASE64; break; case OPT_HEX: format = FORMAT_TEXT; break; case OPT_PROV_CASES: if (!opt_provider(o)) goto end; break; } } argc = opt_num_rest(); argv = opt_rest(); if (argc == 1) { int factoridx = 0; int shift = 0; if (!strcmp(argv[0], "max")) { scaled_num = UINT64_MAX >> 3; } else { while (argv[0][factoridx]) { if (!isdigit((int)(argv[0][factoridx]))) { switch(argv[0][factoridx]) { case 'K': shift = 10; break; case 'M': shift = 20; break; case 'G': shift = 30; break; case 'T': shift = 40; break; default: BIO_printf(bio_err, "Invalid size suffix %s\n", &argv[0][factoridx]); goto opthelp; } break; } factoridx++; } if (shift != 0 && strlen(&argv[0][factoridx]) != 1) { BIO_printf(bio_err, "Invalid size suffix %s\n", &argv[0][factoridx]); goto opthelp; } } if (shift != 0) argv[0][factoridx] = '\0'; if ((scaled_num == 0) && (!opt_long(argv[0], &num) || num <= 0)) goto opthelp; if (shift != 0) { if ((UINT64_MAX >> shift) < (size_t)num) { BIO_printf(bio_err, "%lu bytes with suffix overflows\n", num); goto opthelp; } scaled_num = num << shift; if (scaled_num > (UINT64_MAX >> 3)) { BIO_printf(bio_err, "Request exceeds max allowed output\n"); goto opthelp; } } else { if (scaled_num == 0) scaled_num = num; } } else if (!opt_check_rest_arg(NULL)) { goto opthelp; } if (!app_RAND_load()) goto end; out = bio_open_default(outfile, 'w', format); if (out == NULL) goto end; if (format == FORMAT_BASE64) { BIO *b64 = BIO_new(BIO_f_base64()); if (b64 == NULL) goto end; out = BIO_push(b64, out); } buf = app_malloc(buflen, "buffer for output file"); while (scaled_num > 0) { int chunk; chunk = scaled_num > buflen ? (int)buflen : (int)scaled_num; r = RAND_bytes(buf, chunk); if (r <= 0) goto end; if (format != FORMAT_TEXT) { if (BIO_write(out, buf, chunk) != chunk) goto end; } else { for (i = 0; i < chunk; i++) if (BIO_printf(out, "%02x", buf[i]) != 2) goto end; } scaled_num -= chunk; } if (format == FORMAT_TEXT) BIO_puts(out, "\n"); if (BIO_flush(out) <= 0) goto end; ret = 0; end: if (ret != 0) ERR_print_errors(bio_err); OPENSSL_free(buf); release_engine(e); BIO_free_all(out); return ret; }
apps
openssl/apps/rand.c
openssl
#include <stdlib.h> #include <openssl/crypto.h> #include "platform.h" char **newargv = NULL; static void cleanup_argv(void) { OPENSSL_free(newargv); newargv = NULL; } char **copy_argv(int *argc, char *argv[]) { int i, count = *argc; char **p = newargv; cleanup_argv(); newargv = OPENSSL_malloc(sizeof(*newargv) * (count + 1)); if (newargv == NULL) return NULL; if (p == NULL) OPENSSL_atexit(cleanup_argv); for (i = 0; i < count; i++) newargv[i] = argv[i]; newargv[i] = NULL; *argc = i; return newargv; }
lib
openssl/apps/lib/vms_decc_argv.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "apps.h" #include <openssl/core_names.h> #include <openssl/params.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/x509.h> #include <openssl/ssl.h> #include <openssl/bn.h> #ifndef OPENSSL_NO_DH # include <openssl/dh.h> #endif #include "s_apps.h" #define COOKIE_SECRET_LENGTH 16 VERIFY_CB_ARGS verify_args = { -1, 0, X509_V_OK, 0 }; #ifndef OPENSSL_NO_SOCK static unsigned char cookie_secret[COOKIE_SECRET_LENGTH]; static int cookie_initialized = 0; #endif static BIO *bio_keylog = NULL; static const char *lookup(int val, const STRINT_PAIR* list, const char* def) { for ( ; list->name; ++list) if (list->retval == val) return list->name; return def; } int verify_callback(int ok, X509_STORE_CTX *ctx) { X509 *err_cert; int err, depth; err_cert = X509_STORE_CTX_get_current_cert(ctx); err = X509_STORE_CTX_get_error(ctx); depth = X509_STORE_CTX_get_error_depth(ctx); if (!verify_args.quiet || !ok) { BIO_printf(bio_err, "depth=%d ", depth); if (err_cert != NULL) { X509_NAME_print_ex(bio_err, X509_get_subject_name(err_cert), 0, get_nameopt()); BIO_puts(bio_err, "\n"); } else { BIO_puts(bio_err, "<no cert>\n"); } } if (!ok) { BIO_printf(bio_err, "verify error:num=%d:%s\n", err, X509_verify_cert_error_string(err)); if (verify_args.depth < 0 || verify_args.depth >= depth) { if (!verify_args.return_error) ok = 1; verify_args.error = err; } else { ok = 0; verify_args.error = X509_V_ERR_CERT_CHAIN_TOO_LONG; } } switch (err) { case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: if (err_cert != NULL) { BIO_puts(bio_err, "issuer= "); X509_NAME_print_ex(bio_err, X509_get_issuer_name(err_cert), 0, get_nameopt()); BIO_puts(bio_err, "\n"); } break; case X509_V_ERR_CERT_NOT_YET_VALID: case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: if (err_cert != NULL) { BIO_printf(bio_err, "notBefore="); ASN1_TIME_print(bio_err, X509_get0_notBefore(err_cert)); BIO_printf(bio_err, "\n"); } break; case X509_V_ERR_CERT_HAS_EXPIRED: case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: if (err_cert != NULL) { BIO_printf(bio_err, "notAfter="); ASN1_TIME_print(bio_err, X509_get0_notAfter(err_cert)); BIO_printf(bio_err, "\n"); } break; case X509_V_ERR_NO_EXPLICIT_POLICY: if (!verify_args.quiet) policies_print(ctx); break; } if (err == X509_V_OK && ok == 2 && !verify_args.quiet) policies_print(ctx); if (ok && !verify_args.quiet) BIO_printf(bio_err, "verify return:%d\n", ok); return ok; } int set_cert_stuff(SSL_CTX *ctx, char *cert_file, char *key_file) { if (cert_file != NULL) { if (SSL_CTX_use_certificate_file(ctx, cert_file, SSL_FILETYPE_PEM) <= 0) { BIO_printf(bio_err, "unable to get certificate from '%s'\n", cert_file); ERR_print_errors(bio_err); return 0; } if (key_file == NULL) key_file = cert_file; if (SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) <= 0) { BIO_printf(bio_err, "unable to get private key from '%s'\n", key_file); ERR_print_errors(bio_err); return 0; } if (!SSL_CTX_check_private_key(ctx)) { BIO_printf(bio_err, "Private key does not match the certificate public key\n"); return 0; } } return 1; } int set_cert_key_stuff(SSL_CTX *ctx, X509 *cert, EVP_PKEY *key, STACK_OF(X509) *chain, int build_chain) { int chflags = chain ? SSL_BUILD_CHAIN_FLAG_CHECK : 0; if (cert == NULL) return 1; if (SSL_CTX_use_certificate(ctx, cert) <= 0) { BIO_printf(bio_err, "error setting certificate\n"); ERR_print_errors(bio_err); return 0; } if (SSL_CTX_use_PrivateKey(ctx, key) <= 0) { BIO_printf(bio_err, "error setting private key\n"); ERR_print_errors(bio_err); return 0; } if (!SSL_CTX_check_private_key(ctx)) { BIO_printf(bio_err, "Private key does not match the certificate public key\n"); return 0; } if (chain && !SSL_CTX_set1_chain(ctx, chain)) { BIO_printf(bio_err, "error setting certificate chain\n"); ERR_print_errors(bio_err); return 0; } if (build_chain && !SSL_CTX_build_cert_chain(ctx, chflags)) { BIO_printf(bio_err, "error building certificate chain\n"); ERR_print_errors(bio_err); return 0; } return 1; } static STRINT_PAIR cert_type_list[] = { {"RSA sign", TLS_CT_RSA_SIGN}, {"DSA sign", TLS_CT_DSS_SIGN}, {"RSA fixed DH", TLS_CT_RSA_FIXED_DH}, {"DSS fixed DH", TLS_CT_DSS_FIXED_DH}, {"ECDSA sign", TLS_CT_ECDSA_SIGN}, {"RSA fixed ECDH", TLS_CT_RSA_FIXED_ECDH}, {"ECDSA fixed ECDH", TLS_CT_ECDSA_FIXED_ECDH}, {"GOST01 Sign", TLS_CT_GOST01_SIGN}, {"GOST12 Sign", TLS_CT_GOST12_IANA_SIGN}, {NULL} }; static void ssl_print_client_cert_types(BIO *bio, SSL *s) { const unsigned char *p; int i; int cert_type_num = SSL_get0_certificate_types(s, &p); if (!cert_type_num) return; BIO_puts(bio, "Client Certificate Types: "); for (i = 0; i < cert_type_num; i++) { unsigned char cert_type = p[i]; const char *cname = lookup((int)cert_type, cert_type_list, NULL); if (i) BIO_puts(bio, ", "); if (cname != NULL) BIO_puts(bio, cname); else BIO_printf(bio, "UNKNOWN (%d),", cert_type); } BIO_puts(bio, "\n"); } static const char *get_sigtype(int nid) { switch (nid) { case EVP_PKEY_RSA: return "RSA"; case EVP_PKEY_RSA_PSS: return "RSA-PSS"; case EVP_PKEY_DSA: return "DSA"; case EVP_PKEY_EC: return "ECDSA"; case NID_ED25519: return "Ed25519"; case NID_ED448: return "Ed448"; case NID_id_GostR3410_2001: return "gost2001"; case NID_id_GostR3410_2012_256: return "gost2012_256"; case NID_id_GostR3410_2012_512: return "gost2012_512"; default: return OBJ_nid2sn(nid); } } static int do_print_sigalgs(BIO *out, SSL *s, int shared) { int i, nsig, client; client = SSL_is_server(s) ? 0 : 1; if (shared) nsig = SSL_get_shared_sigalgs(s, 0, NULL, NULL, NULL, NULL, NULL); else nsig = SSL_get_sigalgs(s, -1, NULL, NULL, NULL, NULL, NULL); if (nsig == 0) return 1; if (shared) BIO_puts(out, "Shared "); if (client) BIO_puts(out, "Requested "); BIO_puts(out, "Signature Algorithms: "); for (i = 0; i < nsig; i++) { int hash_nid, sign_nid; unsigned char rhash, rsign; const char *sstr = NULL; if (shared) SSL_get_shared_sigalgs(s, i, &sign_nid, &hash_nid, NULL, &rsign, &rhash); else SSL_get_sigalgs(s, i, &sign_nid, &hash_nid, NULL, &rsign, &rhash); if (i) BIO_puts(out, ":"); sstr = get_sigtype(sign_nid); if (sstr) BIO_printf(out, "%s", sstr); else BIO_printf(out, "0x%02X", (int)rsign); if (hash_nid != NID_undef) BIO_printf(out, "+%s", OBJ_nid2sn(hash_nid)); else if (sstr == NULL) BIO_printf(out, "+0x%02X", (int)rhash); } BIO_puts(out, "\n"); return 1; } int ssl_print_sigalgs(BIO *out, SSL *s) { int nid; if (!SSL_is_server(s)) ssl_print_client_cert_types(out, s); do_print_sigalgs(out, s, 0); do_print_sigalgs(out, s, 1); if (SSL_get_peer_signature_nid(s, &nid) && nid != NID_undef) BIO_printf(out, "Peer signing digest: %s\n", OBJ_nid2sn(nid)); if (SSL_get_peer_signature_type_nid(s, &nid)) BIO_printf(out, "Peer signature type: %s\n", get_sigtype(nid)); return 1; } #ifndef OPENSSL_NO_EC int ssl_print_point_formats(BIO *out, SSL *s) { int i, nformats; const char *pformats; nformats = SSL_get0_ec_point_formats(s, &pformats); if (nformats <= 0) return 1; BIO_puts(out, "Supported Elliptic Curve Point Formats: "); for (i = 0; i < nformats; i++, pformats++) { if (i) BIO_puts(out, ":"); switch (*pformats) { case TLSEXT_ECPOINTFORMAT_uncompressed: BIO_puts(out, "uncompressed"); break; case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime: BIO_puts(out, "ansiX962_compressed_prime"); break; case TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2: BIO_puts(out, "ansiX962_compressed_char2"); break; default: BIO_printf(out, "unknown(%d)", (int)*pformats); break; } } BIO_puts(out, "\n"); return 1; } int ssl_print_groups(BIO *out, SSL *s, int noshared) { int i, ngroups, *groups, nid; ngroups = SSL_get1_groups(s, NULL); if (ngroups <= 0) return 1; groups = app_malloc(ngroups * sizeof(int), "groups to print"); SSL_get1_groups(s, groups); BIO_puts(out, "Supported groups: "); for (i = 0; i < ngroups; i++) { if (i) BIO_puts(out, ":"); nid = groups[i]; BIO_printf(out, "%s", SSL_group_to_name(s, nid)); } OPENSSL_free(groups); if (noshared) { BIO_puts(out, "\n"); return 1; } BIO_puts(out, "\nShared groups: "); ngroups = SSL_get_shared_group(s, -1); for (i = 0; i < ngroups; i++) { if (i) BIO_puts(out, ":"); nid = SSL_get_shared_group(s, i); BIO_printf(out, "%s", SSL_group_to_name(s, nid)); } if (ngroups == 0) BIO_puts(out, "NONE"); BIO_puts(out, "\n"); return 1; } #endif int ssl_print_tmp_key(BIO *out, SSL *s) { EVP_PKEY *key; if (!SSL_get_peer_tmp_key(s, &key)) return 1; BIO_puts(out, "Server Temp Key: "); switch (EVP_PKEY_get_id(key)) { case EVP_PKEY_RSA: BIO_printf(out, "RSA, %d bits\n", EVP_PKEY_get_bits(key)); break; case EVP_PKEY_DH: BIO_printf(out, "DH, %d bits\n", EVP_PKEY_get_bits(key)); break; #ifndef OPENSSL_NO_EC case EVP_PKEY_EC: { char name[80]; size_t name_len; if (!EVP_PKEY_get_utf8_string_param(key, OSSL_PKEY_PARAM_GROUP_NAME, name, sizeof(name), &name_len)) strcpy(name, "?"); BIO_printf(out, "ECDH, %s, %d bits\n", name, EVP_PKEY_get_bits(key)); } break; #endif default: BIO_printf(out, "%s, %d bits\n", OBJ_nid2sn(EVP_PKEY_get_id(key)), EVP_PKEY_get_bits(key)); } EVP_PKEY_free(key); return 1; } long bio_dump_callback(BIO *bio, int cmd, const char *argp, size_t len, int argi, long argl, int ret, size_t *processed) { BIO *out; BIO_MMSG_CB_ARGS *mmsgargs; size_t i; out = (BIO *)BIO_get_callback_arg(bio); if (out == NULL) return ret; switch (cmd) { case (BIO_CB_READ | BIO_CB_RETURN): if (ret > 0 && processed != NULL) { BIO_printf(out, "read from %p [%p] (%zu bytes => %zu (0x%zX))\n", (void *)bio, (void *)argp, len, *processed, *processed); BIO_dump(out, argp, (int)*processed); } else { BIO_printf(out, "read from %p [%p] (%zu bytes => %d)\n", (void *)bio, (void *)argp, len, ret); } break; case (BIO_CB_WRITE | BIO_CB_RETURN): if (ret > 0 && processed != NULL) { BIO_printf(out, "write to %p [%p] (%zu bytes => %zu (0x%zX))\n", (void *)bio, (void *)argp, len, *processed, *processed); BIO_dump(out, argp, (int)*processed); } else { BIO_printf(out, "write to %p [%p] (%zu bytes => %d)\n", (void *)bio, (void *)argp, len, ret); } break; case (BIO_CB_RECVMMSG | BIO_CB_RETURN): mmsgargs = (BIO_MMSG_CB_ARGS *)argp; if (ret > 0) { for (i = 0; i < *(mmsgargs->msgs_processed); i++) { BIO_MSG *msg = (BIO_MSG *)((char *)mmsgargs->msg + (i * mmsgargs->stride)); BIO_printf(out, "read from %p [%p] (%zu bytes => %zu (0x%zX))\n", (void *)bio, (void *)msg->data, msg->data_len, msg->data_len, msg->data_len); BIO_dump(out, msg->data, msg->data_len); } } else if (mmsgargs->num_msg > 0) { BIO_MSG *msg = mmsgargs->msg; BIO_printf(out, "read from %p [%p] (%zu bytes => %d)\n", (void *)bio, (void *)msg->data, msg->data_len, ret); } break; case (BIO_CB_SENDMMSG | BIO_CB_RETURN): mmsgargs = (BIO_MMSG_CB_ARGS *)argp; if (ret > 0) { for (i = 0; i < *(mmsgargs->msgs_processed); i++) { BIO_MSG *msg = (BIO_MSG *)((char *)mmsgargs->msg + (i * mmsgargs->stride)); BIO_printf(out, "write to %p [%p] (%zu bytes => %zu (0x%zX))\n", (void *)bio, (void *)msg->data, msg->data_len, msg->data_len, msg->data_len); BIO_dump(out, msg->data, msg->data_len); } } else if (mmsgargs->num_msg > 0) { BIO_MSG *msg = mmsgargs->msg; BIO_printf(out, "write to %p [%p] (%zu bytes => %d)\n", (void *)bio, (void *)msg->data, msg->data_len, ret); } break; default: break; } return ret; } void apps_ssl_info_callback(const SSL *s, int where, int ret) { const char *str; int w; w = where & ~SSL_ST_MASK; if (w & SSL_ST_CONNECT) str = "SSL_connect"; else if (w & SSL_ST_ACCEPT) str = "SSL_accept"; else str = "undefined"; if (where & SSL_CB_LOOP) { BIO_printf(bio_err, "%s:%s\n", str, SSL_state_string_long(s)); } else if (where & SSL_CB_ALERT) { str = (where & SSL_CB_READ) ? "read" : "write"; BIO_printf(bio_err, "SSL3 alert %s:%s:%s\n", str, SSL_alert_type_string_long(ret), SSL_alert_desc_string_long(ret)); } else if (where & SSL_CB_EXIT) { if (ret == 0) BIO_printf(bio_err, "%s:failed in %s\n", str, SSL_state_string_long(s)); else if (ret < 0) BIO_printf(bio_err, "%s:error in %s\n", str, SSL_state_string_long(s)); } } static STRINT_PAIR ssl_versions[] = { {"SSL 3.0", SSL3_VERSION}, {"TLS 1.0", TLS1_VERSION}, {"TLS 1.1", TLS1_1_VERSION}, {"TLS 1.2", TLS1_2_VERSION}, {"TLS 1.3", TLS1_3_VERSION}, {"DTLS 1.0", DTLS1_VERSION}, {"DTLS 1.0 (bad)", DTLS1_BAD_VER}, {NULL} }; static STRINT_PAIR alert_types[] = { {" close_notify", 0}, {" end_of_early_data", 1}, {" unexpected_message", 10}, {" bad_record_mac", 20}, {" decryption_failed", 21}, {" record_overflow", 22}, {" decompression_failure", 30}, {" handshake_failure", 40}, {" bad_certificate", 42}, {" unsupported_certificate", 43}, {" certificate_revoked", 44}, {" certificate_expired", 45}, {" certificate_unknown", 46}, {" illegal_parameter", 47}, {" unknown_ca", 48}, {" access_denied", 49}, {" decode_error", 50}, {" decrypt_error", 51}, {" export_restriction", 60}, {" protocol_version", 70}, {" insufficient_security", 71}, {" internal_error", 80}, {" inappropriate_fallback", 86}, {" user_canceled", 90}, {" no_renegotiation", 100}, {" missing_extension", 109}, {" unsupported_extension", 110}, {" certificate_unobtainable", 111}, {" unrecognized_name", 112}, {" bad_certificate_status_response", 113}, {" bad_certificate_hash_value", 114}, {" unknown_psk_identity", 115}, {" certificate_required", 116}, {NULL} }; static STRINT_PAIR handshakes[] = { {", HelloRequest", SSL3_MT_HELLO_REQUEST}, {", ClientHello", SSL3_MT_CLIENT_HELLO}, {", ServerHello", SSL3_MT_SERVER_HELLO}, {", HelloVerifyRequest", DTLS1_MT_HELLO_VERIFY_REQUEST}, {", NewSessionTicket", SSL3_MT_NEWSESSION_TICKET}, {", EndOfEarlyData", SSL3_MT_END_OF_EARLY_DATA}, {", EncryptedExtensions", SSL3_MT_ENCRYPTED_EXTENSIONS}, {", Certificate", SSL3_MT_CERTIFICATE}, {", ServerKeyExchange", SSL3_MT_SERVER_KEY_EXCHANGE}, {", CertificateRequest", SSL3_MT_CERTIFICATE_REQUEST}, {", ServerHelloDone", SSL3_MT_SERVER_DONE}, {", CertificateVerify", SSL3_MT_CERTIFICATE_VERIFY}, {", ClientKeyExchange", SSL3_MT_CLIENT_KEY_EXCHANGE}, {", Finished", SSL3_MT_FINISHED}, {", CertificateUrl", SSL3_MT_CERTIFICATE_URL}, {", CertificateStatus", SSL3_MT_CERTIFICATE_STATUS}, {", SupplementalData", SSL3_MT_SUPPLEMENTAL_DATA}, {", KeyUpdate", SSL3_MT_KEY_UPDATE}, {", CompressedCertificate", SSL3_MT_COMPRESSED_CERTIFICATE}, #ifndef OPENSSL_NO_NEXTPROTONEG {", NextProto", SSL3_MT_NEXT_PROTO}, #endif {", MessageHash", SSL3_MT_MESSAGE_HASH}, {NULL} }; void msg_cb(int write_p, int version, int content_type, const void *buf, size_t len, SSL *ssl, void *arg) { BIO *bio = arg; const char *str_write_p = write_p ? ">>>" : "<<<"; char tmpbuf[128]; const char *str_version, *str_content_type = "", *str_details1 = "", *str_details2 = ""; const unsigned char* bp = buf; if (version == SSL3_VERSION || version == TLS1_VERSION || version == TLS1_1_VERSION || version == TLS1_2_VERSION || version == TLS1_3_VERSION || version == DTLS1_VERSION || version == DTLS1_BAD_VER) { str_version = lookup(version, ssl_versions, "???"); switch (content_type) { case SSL3_RT_CHANGE_CIPHER_SPEC: str_content_type = ", ChangeCipherSpec"; break; case SSL3_RT_ALERT: str_content_type = ", Alert"; str_details1 = ", ???"; if (len == 2) { switch (bp[0]) { case 1: str_details1 = ", warning"; break; case 2: str_details1 = ", fatal"; break; } str_details2 = lookup((int)bp[1], alert_types, " ???"); } break; case SSL3_RT_HANDSHAKE: str_content_type = ", Handshake"; str_details1 = "???"; if (len > 0) str_details1 = lookup((int)bp[0], handshakes, "???"); break; case SSL3_RT_APPLICATION_DATA: str_content_type = ", ApplicationData"; break; case SSL3_RT_HEADER: str_content_type = ", RecordHeader"; break; case SSL3_RT_INNER_CONTENT_TYPE: str_content_type = ", InnerContent"; break; default: BIO_snprintf(tmpbuf, sizeof(tmpbuf)-1, ", Unknown (content_type=%d)", content_type); str_content_type = tmpbuf; } } else { BIO_snprintf(tmpbuf, sizeof(tmpbuf)-1, "Not TLS data or unknown version (version=%d, content_type=%d)", version, content_type); str_version = tmpbuf; } BIO_printf(bio, "%s %s%s [length %04lx]%s%s\n", str_write_p, str_version, str_content_type, (unsigned long)len, str_details1, str_details2); if (len > 0) { size_t num, i; BIO_printf(bio, " "); num = len; for (i = 0; i < num; i++) { if (i % 16 == 0 && i > 0) BIO_printf(bio, "\n "); BIO_printf(bio, " %02x", ((const unsigned char *)buf)[i]); } if (i < len) BIO_printf(bio, " ..."); BIO_printf(bio, "\n"); } (void)BIO_flush(bio); } static STRINT_PAIR tlsext_types[] = { {"server name", TLSEXT_TYPE_server_name}, {"max fragment length", TLSEXT_TYPE_max_fragment_length}, {"client certificate URL", TLSEXT_TYPE_client_certificate_url}, {"trusted CA keys", TLSEXT_TYPE_trusted_ca_keys}, {"truncated HMAC", TLSEXT_TYPE_truncated_hmac}, {"status request", TLSEXT_TYPE_status_request}, {"user mapping", TLSEXT_TYPE_user_mapping}, {"client authz", TLSEXT_TYPE_client_authz}, {"server authz", TLSEXT_TYPE_server_authz}, {"cert type", TLSEXT_TYPE_cert_type}, {"supported_groups", TLSEXT_TYPE_supported_groups}, {"EC point formats", TLSEXT_TYPE_ec_point_formats}, {"SRP", TLSEXT_TYPE_srp}, {"signature algorithms", TLSEXT_TYPE_signature_algorithms}, {"use SRTP", TLSEXT_TYPE_use_srtp}, {"session ticket", TLSEXT_TYPE_session_ticket}, {"renegotiation info", TLSEXT_TYPE_renegotiate}, {"signed certificate timestamps", TLSEXT_TYPE_signed_certificate_timestamp}, {"client cert type", TLSEXT_TYPE_client_cert_type}, {"server cert type", TLSEXT_TYPE_server_cert_type}, {"TLS padding", TLSEXT_TYPE_padding}, #ifdef TLSEXT_TYPE_next_proto_neg {"next protocol", TLSEXT_TYPE_next_proto_neg}, #endif #ifdef TLSEXT_TYPE_encrypt_then_mac {"encrypt-then-mac", TLSEXT_TYPE_encrypt_then_mac}, #endif #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation {"application layer protocol negotiation", TLSEXT_TYPE_application_layer_protocol_negotiation}, #endif #ifdef TLSEXT_TYPE_extended_master_secret {"extended master secret", TLSEXT_TYPE_extended_master_secret}, #endif {"compress certificate", TLSEXT_TYPE_compress_certificate}, {"key share", TLSEXT_TYPE_key_share}, {"supported versions", TLSEXT_TYPE_supported_versions}, {"psk", TLSEXT_TYPE_psk}, {"psk kex modes", TLSEXT_TYPE_psk_kex_modes}, {"certificate authorities", TLSEXT_TYPE_certificate_authorities}, {"post handshake auth", TLSEXT_TYPE_post_handshake_auth}, {NULL} }; static STRINT_PAIR signature_tls13_scheme_list[] = { {"rsa_pkcs1_sha1", 0x0201 }, {"ecdsa_sha1", 0x0203 }, {"rsa_pkcs1_sha256", 0x0401 }, {"ecdsa_secp256r1_sha256", 0x0403 }, {"rsa_pkcs1_sha384", 0x0501 }, {"ecdsa_secp384r1_sha384", 0x0503 }, {"rsa_pkcs1_sha512", 0x0601 }, {"ecdsa_secp521r1_sha512", 0x0603 }, {"rsa_pss_rsae_sha256", 0x0804 }, {"rsa_pss_rsae_sha384", 0x0805 }, {"rsa_pss_rsae_sha512", 0x0806 }, {"ed25519", 0x0807 }, {"ed448", 0x0808 }, {"rsa_pss_pss_sha256", 0x0809 }, {"rsa_pss_pss_sha384", 0x080a }, {"rsa_pss_pss_sha512", 0x080b }, {"gostr34102001", 0xeded }, {"gostr34102012_256", 0xeeee }, {"gostr34102012_512", 0xefef }, {NULL} }; static STRINT_PAIR signature_tls12_alg_list[] = { {"anonymous", TLSEXT_signature_anonymous }, {"RSA", TLSEXT_signature_rsa }, {"DSA", TLSEXT_signature_dsa }, {"ECDSA", TLSEXT_signature_ecdsa }, {NULL} }; static STRINT_PAIR signature_tls12_hash_list[] = { {"none", TLSEXT_hash_none }, {"MD5", TLSEXT_hash_md5 }, {"SHA1", TLSEXT_hash_sha1 }, {"SHA224", TLSEXT_hash_sha224 }, {"SHA256", TLSEXT_hash_sha256 }, {"SHA384", TLSEXT_hash_sha384 }, {"SHA512", TLSEXT_hash_sha512 }, {NULL} }; void tlsext_cb(SSL *s, int client_server, int type, const unsigned char *data, int len, void *arg) { BIO *bio = arg; const char *extname = lookup(type, tlsext_types, "unknown"); BIO_printf(bio, "TLS %s extension \"%s\" (id=%d), len=%d\n", client_server ? "server" : "client", extname, type, len); BIO_dump(bio, (const char *)data, len); (void)BIO_flush(bio); } #ifndef OPENSSL_NO_SOCK int generate_stateless_cookie_callback(SSL *ssl, unsigned char *cookie, size_t *cookie_len) { unsigned char *buffer = NULL; size_t length = 0; unsigned short port; BIO_ADDR *lpeer = NULL, *peer = NULL; int res = 0; if (!cookie_initialized) { if (RAND_bytes(cookie_secret, COOKIE_SECRET_LENGTH) <= 0) { BIO_printf(bio_err, "error setting random cookie secret\n"); return 0; } cookie_initialized = 1; } if (SSL_is_dtls(ssl)) { lpeer = peer = BIO_ADDR_new(); if (peer == NULL) { BIO_printf(bio_err, "memory full\n"); return 0; } (void)BIO_dgram_get_peer(SSL_get_rbio(ssl), peer); } else { peer = ourpeer; } if (!BIO_ADDR_rawaddress(peer, NULL, &length)) { BIO_printf(bio_err, "Failed getting peer address\n"); BIO_ADDR_free(lpeer); return 0; } OPENSSL_assert(length != 0); port = BIO_ADDR_rawport(peer); length += sizeof(port); buffer = app_malloc(length, "cookie generate buffer"); memcpy(buffer, &port, sizeof(port)); BIO_ADDR_rawaddress(peer, buffer + sizeof(port), NULL); if (EVP_Q_mac(NULL, "HMAC", NULL, "SHA1", NULL, cookie_secret, COOKIE_SECRET_LENGTH, buffer, length, cookie, DTLS1_COOKIE_LENGTH, cookie_len) == NULL) { BIO_printf(bio_err, "Error calculating HMAC-SHA1 of buffer with secret\n"); goto end; } res = 1; end: OPENSSL_free(buffer); BIO_ADDR_free(lpeer); return res; } int verify_stateless_cookie_callback(SSL *ssl, const unsigned char *cookie, size_t cookie_len) { unsigned char result[EVP_MAX_MD_SIZE]; size_t resultlength; if (cookie_initialized && generate_stateless_cookie_callback(ssl, result, &resultlength) && cookie_len == resultlength && memcmp(result, cookie, resultlength) == 0) return 1; return 0; } int generate_cookie_callback(SSL *ssl, unsigned char *cookie, unsigned int *cookie_len) { size_t temp = 0; int res = generate_stateless_cookie_callback(ssl, cookie, &temp); if (res != 0) *cookie_len = (unsigned int)temp; return res; } int verify_cookie_callback(SSL *ssl, const unsigned char *cookie, unsigned int cookie_len) { return verify_stateless_cookie_callback(ssl, cookie, cookie_len); } #endif struct ssl_excert_st { int certform; const char *certfile; int keyform; const char *keyfile; const char *chainfile; X509 *cert; EVP_PKEY *key; STACK_OF(X509) *chain; int build_chain; struct ssl_excert_st *next, *prev; }; static STRINT_PAIR chain_flags[] = { {"Overall Validity", CERT_PKEY_VALID}, {"Sign with EE key", CERT_PKEY_SIGN}, {"EE signature", CERT_PKEY_EE_SIGNATURE}, {"CA signature", CERT_PKEY_CA_SIGNATURE}, {"EE key parameters", CERT_PKEY_EE_PARAM}, {"CA key parameters", CERT_PKEY_CA_PARAM}, {"Explicitly sign with EE key", CERT_PKEY_EXPLICIT_SIGN}, {"Issuer Name", CERT_PKEY_ISSUER_NAME}, {"Certificate Type", CERT_PKEY_CERT_TYPE}, {NULL} }; static void print_chain_flags(SSL *s, int flags) { STRINT_PAIR *pp; for (pp = chain_flags; pp->name; ++pp) BIO_printf(bio_err, "\t%s: %s\n", pp->name, (flags & pp->retval) ? "OK" : "NOT OK"); BIO_printf(bio_err, "\tSuite B: "); if (SSL_set_cert_flags(s, 0) & SSL_CERT_FLAG_SUITEB_128_LOS) BIO_puts(bio_err, flags & CERT_PKEY_SUITEB ? "OK\n" : "NOT OK\n"); else BIO_printf(bio_err, "not tested\n"); } static int set_cert_cb(SSL *ssl, void *arg) { int i, rv; SSL_EXCERT *exc = arg; #ifdef CERT_CB_TEST_RETRY static int retry_cnt; if (retry_cnt < 5) { retry_cnt++; BIO_printf(bio_err, "Certificate callback retry test: count %d\n", retry_cnt); return -1; } #endif SSL_certs_clear(ssl); if (exc == NULL) return 1; while (exc->next != NULL) exc = exc->next; i = 0; while (exc != NULL) { i++; rv = SSL_check_chain(ssl, exc->cert, exc->key, exc->chain); BIO_printf(bio_err, "Checking cert chain %d:\nSubject: ", i); X509_NAME_print_ex(bio_err, X509_get_subject_name(exc->cert), 0, get_nameopt()); BIO_puts(bio_err, "\n"); print_chain_flags(ssl, rv); if (rv & CERT_PKEY_VALID) { if (!SSL_use_certificate(ssl, exc->cert) || !SSL_use_PrivateKey(ssl, exc->key)) { return 0; } if (exc->build_chain) { if (!SSL_build_cert_chain(ssl, 0)) return 0; } else if (exc->chain != NULL) { if (!SSL_set1_chain(ssl, exc->chain)) return 0; } } exc = exc->prev; } return 1; } void ssl_ctx_set_excert(SSL_CTX *ctx, SSL_EXCERT *exc) { SSL_CTX_set_cert_cb(ctx, set_cert_cb, exc); } static int ssl_excert_prepend(SSL_EXCERT **pexc) { SSL_EXCERT *exc = app_malloc(sizeof(*exc), "prepend cert"); memset(exc, 0, sizeof(*exc)); exc->next = *pexc; *pexc = exc; if (exc->next) { exc->certform = exc->next->certform; exc->keyform = exc->next->keyform; exc->next->prev = exc; } else { exc->certform = FORMAT_PEM; exc->keyform = FORMAT_PEM; } return 1; } void ssl_excert_free(SSL_EXCERT *exc) { SSL_EXCERT *curr; if (exc == NULL) return; while (exc) { X509_free(exc->cert); EVP_PKEY_free(exc->key); OSSL_STACK_OF_X509_free(exc->chain); curr = exc; exc = exc->next; OPENSSL_free(curr); } } int load_excert(SSL_EXCERT **pexc) { SSL_EXCERT *exc = *pexc; if (exc == NULL) return 1; if (exc->certfile == NULL && exc->next == NULL) { ssl_excert_free(exc); *pexc = NULL; return 1; } for (; exc; exc = exc->next) { if (exc->certfile == NULL) { BIO_printf(bio_err, "Missing filename\n"); return 0; } exc->cert = load_cert(exc->certfile, exc->certform, "Server Certificate"); if (exc->cert == NULL) return 0; if (exc->keyfile != NULL) { exc->key = load_key(exc->keyfile, exc->keyform, 0, NULL, NULL, "server key"); } else { exc->key = load_key(exc->certfile, exc->certform, 0, NULL, NULL, "server key"); } if (exc->key == NULL) return 0; if (exc->chainfile != NULL) { if (!load_certs(exc->chainfile, 0, &exc->chain, NULL, "server chain")) return 0; } } return 1; } enum range { OPT_X_ENUM }; int args_excert(int opt, SSL_EXCERT **pexc) { SSL_EXCERT *exc = *pexc; assert(opt > OPT_X__FIRST); assert(opt < OPT_X__LAST); if (exc == NULL) { if (!ssl_excert_prepend(&exc)) { BIO_printf(bio_err, " %s: Error initialising xcert\n", opt_getprog()); goto err; } *pexc = exc; } switch ((enum range)opt) { case OPT_X__FIRST: case OPT_X__LAST: return 0; case OPT_X_CERT: if (exc->certfile != NULL && !ssl_excert_prepend(&exc)) { BIO_printf(bio_err, "%s: Error adding xcert\n", opt_getprog()); goto err; } *pexc = exc; exc->certfile = opt_arg(); break; case OPT_X_KEY: if (exc->keyfile != NULL) { BIO_printf(bio_err, "%s: Key already specified\n", opt_getprog()); goto err; } exc->keyfile = opt_arg(); break; case OPT_X_CHAIN: if (exc->chainfile != NULL) { BIO_printf(bio_err, "%s: Chain already specified\n", opt_getprog()); goto err; } exc->chainfile = opt_arg(); break; case OPT_X_CHAIN_BUILD: exc->build_chain = 1; break; case OPT_X_CERTFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &exc->certform)) return 0; break; case OPT_X_KEYFORM: if (!opt_format(opt_arg(), OPT_FMT_ANY, &exc->keyform)) return 0; break; } return 1; err: ERR_print_errors(bio_err); ssl_excert_free(exc); *pexc = NULL; return 0; } static void print_raw_cipherlist(SSL *s) { const unsigned char *rlist; static const unsigned char scsv_id[] = { 0, 0xFF }; size_t i, rlistlen, num; if (!SSL_is_server(s)) return; num = SSL_get0_raw_cipherlist(s, NULL); OPENSSL_assert(num == 2); rlistlen = SSL_get0_raw_cipherlist(s, &rlist); BIO_puts(bio_err, "Client cipher list: "); for (i = 0; i < rlistlen; i += num, rlist += num) { const SSL_CIPHER *c = SSL_CIPHER_find(s, rlist); if (i) BIO_puts(bio_err, ":"); if (c != NULL) { BIO_puts(bio_err, SSL_CIPHER_get_name(c)); } else if (memcmp(rlist, scsv_id, num) == 0) { BIO_puts(bio_err, "SCSV"); } else { size_t j; BIO_puts(bio_err, "0x"); for (j = 0; j < num; j++) BIO_printf(bio_err, "%02X", rlist[j]); } } BIO_puts(bio_err, "\n"); } static char *hexencode(const unsigned char *data, size_t len) { static const char *hex = "0123456789abcdef"; char *out; char *cp; size_t outlen = 2 * len + 1; int ilen = (int) outlen; if (outlen < len || ilen < 0 || outlen != (size_t)ilen) { BIO_printf(bio_err, "%s: %zu-byte buffer too large to hexencode\n", opt_getprog(), len); exit(1); } cp = out = app_malloc(ilen, "TLSA hex data buffer"); while (len-- > 0) { *cp++ = hex[(*data >> 4) & 0x0f]; *cp++ = hex[*data++ & 0x0f]; } *cp = '\0'; return out; } void print_verify_detail(SSL *s, BIO *bio) { int mdpth; EVP_PKEY *mspki = NULL; long verify_err = SSL_get_verify_result(s); if (verify_err == X509_V_OK) { const char *peername = SSL_get0_peername(s); BIO_printf(bio, "Verification: OK\n"); if (peername != NULL) BIO_printf(bio, "Verified peername: %s\n", peername); } else { const char *reason = X509_verify_cert_error_string(verify_err); BIO_printf(bio, "Verification error: %s\n", reason); } if ((mdpth = SSL_get0_dane_authority(s, NULL, &mspki)) >= 0) { uint8_t usage, selector, mtype; const unsigned char *data = NULL; size_t dlen = 0; char *hexdata; mdpth = SSL_get0_dane_tlsa(s, &usage, &selector, &mtype, &data, &dlen); #define TLSA_TAIL_SIZE 12 if (dlen > TLSA_TAIL_SIZE) hexdata = hexencode(data + dlen - TLSA_TAIL_SIZE, TLSA_TAIL_SIZE); else hexdata = hexencode(data, dlen); BIO_printf(bio, "DANE TLSA %d %d %d %s%s ", usage, selector, mtype, (dlen > TLSA_TAIL_SIZE) ? "..." : "", hexdata); if (SSL_get0_peer_rpk(s) == NULL) BIO_printf(bio, "%s certificate at depth %d\n", (mspki != NULL) ? "signed the peer" : mdpth ? "matched the TA" : "matched the EE", mdpth); else BIO_printf(bio, "matched the peer raw public key\n"); OPENSSL_free(hexdata); } } void print_ssl_summary(SSL *s) { const SSL_CIPHER *c; X509 *peer = SSL_get0_peer_certificate(s); EVP_PKEY *peer_rpk = SSL_get0_peer_rpk(s); int nid; BIO_printf(bio_err, "Protocol version: %s\n", SSL_get_version(s)); print_raw_cipherlist(s); c = SSL_get_current_cipher(s); BIO_printf(bio_err, "Ciphersuite: %s\n", SSL_CIPHER_get_name(c)); do_print_sigalgs(bio_err, s, 0); if (peer != NULL) { BIO_puts(bio_err, "Peer certificate: "); X509_NAME_print_ex(bio_err, X509_get_subject_name(peer), 0, get_nameopt()); BIO_puts(bio_err, "\n"); if (SSL_get_peer_signature_nid(s, &nid)) BIO_printf(bio_err, "Hash used: %s\n", OBJ_nid2sn(nid)); if (SSL_get_peer_signature_type_nid(s, &nid)) BIO_printf(bio_err, "Signature type: %s\n", get_sigtype(nid)); print_verify_detail(s, bio_err); } else if (peer_rpk != NULL) { BIO_printf(bio_err, "Peer used raw public key\n"); if (SSL_get_peer_signature_type_nid(s, &nid)) BIO_printf(bio_err, "Signature type: %s\n", get_sigtype(nid)); print_verify_detail(s, bio_err); } else { BIO_puts(bio_err, "No peer certificate or raw public key\n"); } #ifndef OPENSSL_NO_EC ssl_print_point_formats(bio_err, s); if (SSL_is_server(s)) ssl_print_groups(bio_err, s, 1); else ssl_print_tmp_key(bio_err, s); #else if (!SSL_is_server(s)) ssl_print_tmp_key(bio_err, s); #endif } int config_ctx(SSL_CONF_CTX *cctx, STACK_OF(OPENSSL_STRING) *str, SSL_CTX *ctx) { int i; SSL_CONF_CTX_set_ssl_ctx(cctx, ctx); for (i = 0; i < sk_OPENSSL_STRING_num(str); i += 2) { const char *flag = sk_OPENSSL_STRING_value(str, i); const char *arg = sk_OPENSSL_STRING_value(str, i + 1); if (SSL_CONF_cmd(cctx, flag, arg) <= 0) { BIO_printf(bio_err, "Call to SSL_CONF_cmd(%s, %s) failed\n", flag, arg == NULL ? "<NULL>" : arg); ERR_print_errors(bio_err); return 0; } } if (!SSL_CONF_CTX_finish(cctx)) { BIO_puts(bio_err, "Error finishing context\n"); ERR_print_errors(bio_err); return 0; } return 1; } static int add_crls_store(X509_STORE *st, STACK_OF(X509_CRL) *crls) { X509_CRL *crl; int i, ret = 1; for (i = 0; i < sk_X509_CRL_num(crls); i++) { crl = sk_X509_CRL_value(crls, i); if (!X509_STORE_add_crl(st, crl)) ret = 0; } return ret; } int ssl_ctx_add_crls(SSL_CTX *ctx, STACK_OF(X509_CRL) *crls, int crl_download) { X509_STORE *st; st = SSL_CTX_get_cert_store(ctx); add_crls_store(st, crls); if (crl_download) store_setup_crl_download(st); return 1; } int ssl_load_stores(SSL_CTX *ctx, const char *vfyCApath, const char *vfyCAfile, const char *vfyCAstore, const char *chCApath, const char *chCAfile, const char *chCAstore, STACK_OF(X509_CRL) *crls, int crl_download) { X509_STORE *vfy = NULL, *ch = NULL; int rv = 0; if (vfyCApath != NULL || vfyCAfile != NULL || vfyCAstore != NULL) { vfy = X509_STORE_new(); if (vfy == NULL) goto err; if (vfyCAfile != NULL && !X509_STORE_load_file(vfy, vfyCAfile)) goto err; if (vfyCApath != NULL && !X509_STORE_load_path(vfy, vfyCApath)) goto err; if (vfyCAstore != NULL && !X509_STORE_load_store(vfy, vfyCAstore)) goto err; add_crls_store(vfy, crls); if (SSL_CTX_set1_verify_cert_store(ctx, vfy) == 0) goto err; if (crl_download) store_setup_crl_download(vfy); } if (chCApath != NULL || chCAfile != NULL || chCAstore != NULL) { ch = X509_STORE_new(); if (ch == NULL) goto err; if (chCAfile != NULL && !X509_STORE_load_file(ch, chCAfile)) goto err; if (chCApath != NULL && !X509_STORE_load_path(ch, chCApath)) goto err; if (chCAstore != NULL && !X509_STORE_load_store(ch, chCAstore)) goto err; if (SSL_CTX_set1_chain_cert_store(ctx, ch) == 0) goto err; } rv = 1; err: X509_STORE_free(vfy); X509_STORE_free(ch); return rv; } typedef struct { BIO *out; int verbose; int (*old_cb) (const SSL *s, const SSL_CTX *ctx, int op, int bits, int nid, void *other, void *ex); } security_debug_ex; static STRINT_PAIR callback_types[] = { {"Supported Ciphersuite", SSL_SECOP_CIPHER_SUPPORTED}, {"Shared Ciphersuite", SSL_SECOP_CIPHER_SHARED}, {"Check Ciphersuite", SSL_SECOP_CIPHER_CHECK}, #ifndef OPENSSL_NO_DH {"Temp DH key bits", SSL_SECOP_TMP_DH}, #endif {"Supported Curve", SSL_SECOP_CURVE_SUPPORTED}, {"Shared Curve", SSL_SECOP_CURVE_SHARED}, {"Check Curve", SSL_SECOP_CURVE_CHECK}, {"Supported Signature Algorithm", SSL_SECOP_SIGALG_SUPPORTED}, {"Shared Signature Algorithm", SSL_SECOP_SIGALG_SHARED}, {"Check Signature Algorithm", SSL_SECOP_SIGALG_CHECK}, {"Signature Algorithm mask", SSL_SECOP_SIGALG_MASK}, {"Certificate chain EE key", SSL_SECOP_EE_KEY}, {"Certificate chain CA key", SSL_SECOP_CA_KEY}, {"Peer Chain EE key", SSL_SECOP_PEER_EE_KEY}, {"Peer Chain CA key", SSL_SECOP_PEER_CA_KEY}, {"Certificate chain CA digest", SSL_SECOP_CA_MD}, {"Peer chain CA digest", SSL_SECOP_PEER_CA_MD}, {"SSL compression", SSL_SECOP_COMPRESSION}, {"Session ticket", SSL_SECOP_TICKET}, {NULL} }; static int security_callback_debug(const SSL *s, const SSL_CTX *ctx, int op, int bits, int nid, void *other, void *ex) { security_debug_ex *sdb = ex; int rv, show_bits = 1, cert_md = 0; const char *nm; int show_nm; rv = sdb->old_cb(s, ctx, op, bits, nid, other, ex); if (rv == 1 && sdb->verbose < 2) return 1; BIO_puts(sdb->out, "Security callback: "); nm = lookup(op, callback_types, NULL); show_nm = nm != NULL; switch (op) { case SSL_SECOP_TICKET: case SSL_SECOP_COMPRESSION: show_bits = 0; show_nm = 0; break; case SSL_SECOP_VERSION: BIO_printf(sdb->out, "Version=%s", lookup(nid, ssl_versions, "???")); show_bits = 0; show_nm = 0; break; case SSL_SECOP_CA_MD: case SSL_SECOP_PEER_CA_MD: cert_md = 1; break; case SSL_SECOP_SIGALG_SUPPORTED: case SSL_SECOP_SIGALG_SHARED: case SSL_SECOP_SIGALG_CHECK: case SSL_SECOP_SIGALG_MASK: show_nm = 0; break; } if (show_nm) BIO_printf(sdb->out, "%s=", nm); switch (op & SSL_SECOP_OTHER_TYPE) { case SSL_SECOP_OTHER_CIPHER: BIO_puts(sdb->out, SSL_CIPHER_get_name(other)); break; #ifndef OPENSSL_NO_EC case SSL_SECOP_OTHER_CURVE: { const char *cname; cname = EC_curve_nid2nist(nid); if (cname == NULL) cname = OBJ_nid2sn(nid); BIO_puts(sdb->out, cname); } break; #endif case SSL_SECOP_OTHER_CERT: { if (cert_md) { int sig_nid = X509_get_signature_nid(other); BIO_puts(sdb->out, OBJ_nid2sn(sig_nid)); } else { EVP_PKEY *pkey = X509_get0_pubkey(other); if (pkey == NULL) { BIO_printf(sdb->out, "Public key missing"); } else { const char *algname = ""; EVP_PKEY_asn1_get0_info(NULL, NULL, NULL, NULL, &algname, EVP_PKEY_get0_asn1(pkey)); BIO_printf(sdb->out, "%s, bits=%d", algname, EVP_PKEY_get_bits(pkey)); } } break; } case SSL_SECOP_OTHER_SIGALG: { const unsigned char *salg = other; const char *sname = NULL; int raw_sig_code = (salg[0] << 8) + salg[1]; if (nm != NULL) BIO_printf(sdb->out, "%s", nm); else BIO_printf(sdb->out, "s_cb.c:security_callback_debug op=0x%x", op); sname = lookup(raw_sig_code, signature_tls13_scheme_list, NULL); if (sname != NULL) { BIO_printf(sdb->out, " scheme=%s", sname); } else { int alg_code = salg[1]; int hash_code = salg[0]; const char *alg_str = lookup(alg_code, signature_tls12_alg_list, NULL); const char *hash_str = lookup(hash_code, signature_tls12_hash_list, NULL); if (alg_str != NULL && hash_str != NULL) BIO_printf(sdb->out, " digest=%s, algorithm=%s", hash_str, alg_str); else BIO_printf(sdb->out, " scheme=unknown(0x%04x)", raw_sig_code); } } } if (show_bits) BIO_printf(sdb->out, ", security bits=%d", bits); BIO_printf(sdb->out, ": %s\n", rv ? "yes" : "no"); return rv; } void ssl_ctx_security_debug(SSL_CTX *ctx, int verbose) { static security_debug_ex sdb; sdb.out = bio_err; sdb.verbose = verbose; sdb.old_cb = SSL_CTX_get_security_callback(ctx); SSL_CTX_set_security_callback(ctx, security_callback_debug); SSL_CTX_set0_security_ex_data(ctx, &sdb); } static void keylog_callback(const SSL *ssl, const char *line) { if (bio_keylog == NULL) { BIO_printf(bio_err, "Keylog callback is invoked without valid file!\n"); return; } BIO_printf(bio_keylog, "%s\n", line); (void)BIO_flush(bio_keylog); } int set_keylog_file(SSL_CTX *ctx, const char *keylog_file) { BIO_free_all(bio_keylog); bio_keylog = NULL; if (ctx == NULL || keylog_file == NULL) { return 0; } bio_keylog = BIO_new_file(keylog_file, "a"); if (bio_keylog == NULL) { BIO_printf(bio_err, "Error writing keylog file %s\n", keylog_file); return 1; } if (BIO_tell(bio_keylog) == 0) { BIO_puts(bio_keylog, "# SSL/TLS secrets log file, generated by OpenSSL\n"); (void)BIO_flush(bio_keylog); } SSL_CTX_set_keylog_callback(ctx, keylog_callback); return 0; } void print_ca_names(BIO *bio, SSL *s) { const char *cs = SSL_is_server(s) ? "server" : "client"; const STACK_OF(X509_NAME) *sk = SSL_get0_peer_CA_list(s); int i; if (sk == NULL || sk_X509_NAME_num(sk) == 0) { if (!SSL_is_server(s)) BIO_printf(bio, "---\nNo %s certificate CA names sent\n", cs); return; } BIO_printf(bio, "---\nAcceptable %s certificate CA names\n", cs); for (i = 0; i < sk_X509_NAME_num(sk); i++) { X509_NAME_print_ex(bio, sk_X509_NAME_value(sk, i), 0, get_nameopt()); BIO_write(bio, "\n", 1); } } void ssl_print_secure_renegotiation_notes(BIO *bio, SSL *s) { if (SSL_VERSION_ALLOWS_RENEGOTIATION(s)) { BIO_printf(bio, "Secure Renegotiation IS%s supported\n", SSL_get_secure_renegotiation_support(s) ? "" : " NOT"); } else { BIO_printf(bio, "This TLS version forbids renegotiation.\n"); } } int progress_cb(EVP_PKEY_CTX *ctx) { BIO *b = EVP_PKEY_CTX_get_app_data(ctx); int p = EVP_PKEY_CTX_get_keygen_info(ctx, 0); static const char symbols[] = ".+*\n"; char c = (p >= 0 && (size_t)p <= sizeof(symbols) - 1) ? symbols[p] : '?'; BIO_write(b, &c, 1); (void)BIO_flush(b); return 1; }
lib
openssl/apps/lib/s_cb.c
openssl
#if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS) # define _POSIX_C_SOURCE 2 #endif #ifndef OPENSSL_NO_ENGINE # define OPENSSL_SUPPRESS_DEPRECATED # include <openssl/engine.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #ifndef OPENSSL_NO_POSIX_IO # include <sys/stat.h> # include <fcntl.h> #endif #include <ctype.h> #include <errno.h> #include <openssl/err.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/http.h> #include <openssl/pem.h> #include <openssl/store.h> #include <openssl/pkcs12.h> #include <openssl/ui.h> #include <openssl/safestack.h> #include <openssl/rsa.h> #include <openssl/rand.h> #include <openssl/bn.h> #include <openssl/ssl.h> #include <openssl/core_names.h> #include "s_apps.h" #include "apps.h" #ifdef _WIN32 static int WIN32_rename(const char *from, const char *to); # define rename(from, to) WIN32_rename((from), (to)) #endif #if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS) # include <conio.h> #endif #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32) || defined(__BORLANDC__) # define _kbhit kbhit #endif static BIO *bio_open_default_(const char *filename, char mode, int format, int quiet); #define PASS_SOURCE_SIZE_MAX 4 DEFINE_STACK_OF(CONF) typedef struct { const char *name; unsigned long flag; unsigned long mask; } NAME_EX_TBL; static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl); static int set_multi_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl); int app_init(long mesgwin); int chopup_args(ARGS *arg, char *buf) { int quoted; char c = '\0', *p = NULL; arg->argc = 0; if (arg->size == 0) { arg->size = 20; arg->argv = app_malloc(sizeof(*arg->argv) * arg->size, "argv space"); } for (p = buf;;) { while (*p && isspace(_UC(*p))) p++; if (*p == '\0') break; if (arg->argc >= arg->size) { char **tmp; arg->size += 20; tmp = OPENSSL_realloc(arg->argv, sizeof(*arg->argv) * arg->size); if (tmp == NULL) return 0; arg->argv = tmp; } quoted = *p == '\'' || *p == '"'; if (quoted) c = *p++; arg->argv[arg->argc++] = p; if (quoted) { while (*p && *p != c) p++; *p++ = '\0'; } else { while (*p && !isspace(_UC(*p))) p++; if (*p) *p++ = '\0'; } } arg->argv[arg->argc] = NULL; return 1; } #ifndef APP_INIT int app_init(long mesgwin) { return 1; } #endif int ctx_set_verify_locations(SSL_CTX *ctx, const char *CAfile, int noCAfile, const char *CApath, int noCApath, const char *CAstore, int noCAstore) { if (CAfile == NULL && CApath == NULL && CAstore == NULL) { if (!noCAfile && SSL_CTX_set_default_verify_file(ctx) <= 0) return 0; if (!noCApath && SSL_CTX_set_default_verify_dir(ctx) <= 0) return 0; if (!noCAstore && SSL_CTX_set_default_verify_store(ctx) <= 0) return 0; return 1; } if (CAfile != NULL && !SSL_CTX_load_verify_file(ctx, CAfile)) return 0; if (CApath != NULL && !SSL_CTX_load_verify_dir(ctx, CApath)) return 0; if (CAstore != NULL && !SSL_CTX_load_verify_store(ctx, CAstore)) return 0; return 1; } #ifndef OPENSSL_NO_CT int ctx_set_ctlog_list_file(SSL_CTX *ctx, const char *path) { if (path == NULL) return SSL_CTX_set_default_ctlog_list_file(ctx); return SSL_CTX_set_ctlog_list_file(ctx, path); } #endif static unsigned long nmflag = 0; static char nmflag_set = 0; int set_nameopt(const char *arg) { int ret = set_name_ex(&nmflag, arg); if (ret) nmflag_set = 1; return ret; } unsigned long get_nameopt(void) { return nmflag_set ? nmflag : XN_FLAG_SEP_CPLUS_SPC | ASN1_STRFLGS_UTF8_CONVERT; } void dump_cert_text(BIO *out, X509 *x) { print_name(out, "subject=", X509_get_subject_name(x)); print_name(out, "issuer=", X509_get_issuer_name(x)); } int wrap_password_callback(char *buf, int bufsiz, int verify, void *userdata) { return password_callback(buf, bufsiz, verify, (PW_CB_DATA *)userdata); } static char *app_get_pass(const char *arg, int keepbio); char *get_passwd(const char *pass, const char *desc) { char *result = NULL; if (desc == NULL) desc = "<unknown>"; if (!app_passwd(pass, NULL, &result, NULL)) BIO_printf(bio_err, "Error getting password for %s\n", desc); if (pass != NULL && result == NULL) { BIO_printf(bio_err, "Trying plain input string (better precede with 'pass:')\n"); result = OPENSSL_strdup(pass); if (result == NULL) BIO_printf(bio_err, "Out of memory getting password for %s\n", desc); } return result; } int app_passwd(const char *arg1, const char *arg2, char **pass1, char **pass2) { int same = arg1 != NULL && arg2 != NULL && strcmp(arg1, arg2) == 0; if (arg1 != NULL) { *pass1 = app_get_pass(arg1, same); if (*pass1 == NULL) return 0; } else if (pass1 != NULL) { *pass1 = NULL; } if (arg2 != NULL) { *pass2 = app_get_pass(arg2, same ? 2 : 0); if (*pass2 == NULL) return 0; } else if (pass2 != NULL) { *pass2 = NULL; } return 1; } static char *app_get_pass(const char *arg, int keepbio) { static BIO *pwdbio = NULL; char *tmp, tpass[APP_PASS_LEN]; int i; if (CHECK_AND_SKIP_PREFIX(arg, "pass:")) return OPENSSL_strdup(arg); if (CHECK_AND_SKIP_PREFIX(arg, "env:")) { tmp = getenv(arg); if (tmp == NULL) { BIO_printf(bio_err, "No environment variable %s\n", arg); return NULL; } return OPENSSL_strdup(tmp); } if (!keepbio || pwdbio == NULL) { if (CHECK_AND_SKIP_PREFIX(arg, "file:")) { pwdbio = BIO_new_file(arg, "r"); if (pwdbio == NULL) { BIO_printf(bio_err, "Can't open file %s\n", arg); return NULL; } #if !defined(_WIN32) } else if (CHECK_AND_SKIP_PREFIX(arg, "fd:")) { BIO *btmp; i = atoi(arg); if (i >= 0) pwdbio = BIO_new_fd(i, BIO_NOCLOSE); if ((i < 0) || pwdbio == NULL) { BIO_printf(bio_err, "Can't access file descriptor %s\n", arg); return NULL; } btmp = BIO_new(BIO_f_buffer()); if (btmp == NULL) { BIO_free_all(pwdbio); pwdbio = NULL; BIO_printf(bio_err, "Out of memory\n"); return NULL; } pwdbio = BIO_push(btmp, pwdbio); #endif } else if (strcmp(arg, "stdin") == 0) { unbuffer(stdin); pwdbio = dup_bio_in(FORMAT_TEXT); if (pwdbio == NULL) { BIO_printf(bio_err, "Can't open BIO for stdin\n"); return NULL; } } else { tmp = strchr(arg, ':'); if (tmp == NULL || tmp - arg > PASS_SOURCE_SIZE_MAX) BIO_printf(bio_err, "Invalid password argument, missing ':' within the first %d chars\n", PASS_SOURCE_SIZE_MAX + 1); else BIO_printf(bio_err, "Invalid password argument, starting with \"%.*s\"\n", (int)(tmp - arg + 1), arg); return NULL; } } i = BIO_gets(pwdbio, tpass, APP_PASS_LEN); if (keepbio != 1) { BIO_free_all(pwdbio); pwdbio = NULL; } if (i <= 0) { BIO_printf(bio_err, "Error reading password from BIO\n"); return NULL; } tmp = strchr(tpass, '\n'); if (tmp != NULL) *tmp = 0; return OPENSSL_strdup(tpass); } char *app_conf_try_string(const CONF *conf, const char *group, const char *name) { char *res; ERR_set_mark(); res = NCONF_get_string(conf, group, name); if (res == NULL) ERR_pop_to_mark(); else ERR_clear_last_mark(); return res; } int app_conf_try_number(const CONF *conf, const char *group, const char *name, long *result) { int ok; ERR_set_mark(); ok = NCONF_get_number(conf, group, name, result); if (!ok) ERR_pop_to_mark(); else ERR_clear_last_mark(); return ok; } CONF *app_load_config_bio(BIO *in, const char *filename) { long errorline = -1; CONF *conf; int i; conf = NCONF_new_ex(app_get0_libctx(), NULL); i = NCONF_load_bio(conf, in, &errorline); if (i > 0) return conf; if (errorline <= 0) { BIO_printf(bio_err, "%s: Can't load ", opt_getprog()); } else { BIO_printf(bio_err, "%s: Error on line %ld of ", opt_getprog(), errorline); } if (filename != NULL) BIO_printf(bio_err, "config file \"%s\"\n", filename); else BIO_printf(bio_err, "config input"); NCONF_free(conf); return NULL; } CONF *app_load_config_verbose(const char *filename, int verbose) { if (verbose) { if (*filename == '\0') BIO_printf(bio_err, "No configuration used\n"); else BIO_printf(bio_err, "Using configuration from %s\n", filename); } return app_load_config_internal(filename, 0); } CONF *app_load_config_internal(const char *filename, int quiet) { BIO *in; CONF *conf; if (filename == NULL || *filename != '\0') { if ((in = bio_open_default_(filename, 'r', FORMAT_TEXT, quiet)) == NULL) return NULL; conf = app_load_config_bio(in, filename); BIO_free(in); } else { conf = NCONF_new_ex(app_get0_libctx(), NULL); } return conf; } int app_load_modules(const CONF *config) { CONF *to_free = NULL; if (config == NULL) config = to_free = app_load_config_quiet(default_config_file); if (config == NULL) return 1; if (CONF_modules_load(config, NULL, 0) <= 0) { BIO_printf(bio_err, "Error configuring OpenSSL modules\n"); ERR_print_errors(bio_err); NCONF_free(to_free); return 0; } NCONF_free(to_free); return 1; } int add_oid_section(CONF *conf) { char *p; STACK_OF(CONF_VALUE) *sktmp; CONF_VALUE *cnf; int i; if ((p = app_conf_try_string(conf, NULL, "oid_section")) == NULL) return 1; if ((sktmp = NCONF_get_section(conf, p)) == NULL) { BIO_printf(bio_err, "problem loading oid section %s\n", p); return 0; } for (i = 0; i < sk_CONF_VALUE_num(sktmp); i++) { cnf = sk_CONF_VALUE_value(sktmp, i); if (OBJ_create(cnf->value, cnf->name, cnf->name) == NID_undef) { BIO_printf(bio_err, "problem creating object %s=%s\n", cnf->name, cnf->value); return 0; } } return 1; } CONF *app_load_config_modules(const char *configfile) { CONF *conf = NULL; if (configfile != NULL) { if ((conf = app_load_config_verbose(configfile, 1)) == NULL) return NULL; if (configfile != default_config_file && !app_load_modules(conf)) { NCONF_free(conf); conf = NULL; } } return conf; } #define IS_HTTP(uri) ((uri) != NULL && HAS_PREFIX(uri, OSSL_HTTP_PREFIX)) #define IS_HTTPS(uri) ((uri) != NULL && HAS_PREFIX(uri, OSSL_HTTPS_PREFIX)) X509 *load_cert_pass(const char *uri, int format, int maybe_stdin, const char *pass, const char *desc) { X509 *cert = NULL; if (desc == NULL) desc = "certificate"; if (IS_HTTPS(uri)) { BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc); } else if (IS_HTTP(uri)) { cert = X509_load_http(uri, NULL, NULL, 0 ); if (cert == NULL) { ERR_print_errors(bio_err); BIO_printf(bio_err, "Unable to load %s from %s\n", desc, uri); } } else { (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, 0, NULL, NULL, NULL, &cert, NULL, NULL, NULL); } return cert; } X509_CRL *load_crl(const char *uri, int format, int maybe_stdin, const char *desc) { X509_CRL *crl = NULL; if (desc == NULL) desc = "CRL"; if (IS_HTTPS(uri)) { BIO_printf(bio_err, "Loading %s over HTTPS is unsupported\n", desc); } else if (IS_HTTP(uri)) { crl = X509_CRL_load_http(uri, NULL, NULL, 0 ); if (crl == NULL) { ERR_print_errors(bio_err); BIO_printf(bio_err, "Unable to load %s from %s\n", desc, uri); } } else { (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc, 0, NULL, NULL, NULL, NULL, NULL, &crl, NULL); } return crl; } X509_REQ *load_csr(const char *file, int format, const char *desc) { X509_REQ *req = NULL; BIO *in; if (format == FORMAT_UNDEF) format = FORMAT_PEM; in = bio_open_default(file, 'r', format); if (in == NULL) goto end; if (format == FORMAT_ASN1) req = d2i_X509_REQ_bio(in, NULL); else if (format == FORMAT_PEM) req = PEM_read_bio_X509_REQ(in, NULL, NULL, NULL); else print_format_error(format, OPT_FMT_PEMDER); end: if (req == NULL) { ERR_print_errors(bio_err); if (desc != NULL) BIO_printf(bio_err, "Unable to load %s\n", desc); } BIO_free(in); return req; } X509_REQ *load_csr_autofmt(const char *infile, int format, STACK_OF(OPENSSL_STRING) *vfyopts, const char *desc) { X509_REQ *csr; if (format != FORMAT_UNDEF) { csr = load_csr(infile, format, desc); } else { BIO *bio_bak = bio_err; bio_err = NULL; csr = load_csr(infile, FORMAT_PEM, NULL ); bio_err = bio_bak; if (csr == NULL) { ERR_clear_error(); csr = load_csr(infile, FORMAT_ASN1, NULL ); } if (csr == NULL) { BIO_printf(bio_err, "error: unable to load %s from file '%s'\n", desc, infile); } } if (csr != NULL) { EVP_PKEY *pkey = X509_REQ_get0_pubkey(csr); int ret = do_X509_REQ_verify(csr, pkey, vfyopts); if (pkey == NULL || ret < 0) BIO_puts(bio_err, "Warning: error while verifying CSR self-signature\n"); else if (ret == 0) BIO_puts(bio_err, "Warning: CSR self-signature does not match the contents\n"); return csr; } return csr; } void cleanse(char *str) { if (str != NULL) OPENSSL_cleanse(str, strlen(str)); } void clear_free(char *str) { if (str != NULL) OPENSSL_clear_free(str, strlen(str)); } EVP_PKEY *load_key(const char *uri, int format, int may_stdin, const char *pass, ENGINE *e, const char *desc) { EVP_PKEY *pkey = NULL; char *allocated_uri = NULL; if (desc == NULL) desc = "private key"; if (format == FORMAT_ENGINE) uri = allocated_uri = make_engine_uri(e, uri, desc); (void)load_key_certs_crls(uri, format, may_stdin, pass, desc, 0, &pkey, NULL, NULL, NULL, NULL, NULL, NULL); OPENSSL_free(allocated_uri); return pkey; } EVP_PKEY *load_pubkey(const char *uri, int format, int maybe_stdin, const char *pass, ENGINE *e, const char *desc) { EVP_PKEY *pkey = NULL; char *allocated_uri = NULL; if (desc == NULL) desc = "public key"; if (format == FORMAT_ENGINE) uri = allocated_uri = make_engine_uri(e, uri, desc); (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, 1, NULL, &pkey, NULL, NULL, NULL, NULL, NULL); if (pkey == NULL) (void)load_key_certs_crls(uri, format, maybe_stdin, pass, desc, 0, &pkey, NULL, NULL, NULL, NULL, NULL, NULL); OPENSSL_free(allocated_uri); return pkey; } EVP_PKEY *load_keyparams_suppress(const char *uri, int format, int maybe_stdin, const char *keytype, const char *desc, int suppress_decode_errors) { EVP_PKEY *params = NULL; if (desc == NULL) desc = "key parameters"; (void)load_key_certs_crls(uri, format, maybe_stdin, NULL, desc, suppress_decode_errors, NULL, NULL, &params, NULL, NULL, NULL, NULL); if (params != NULL && keytype != NULL && !EVP_PKEY_is_a(params, keytype)) { ERR_print_errors(bio_err); BIO_printf(bio_err, "Unable to load %s from %s (unexpected parameters type)\n", desc, uri); EVP_PKEY_free(params); params = NULL; } return params; } EVP_PKEY *load_keyparams(const char *uri, int format, int maybe_stdin, const char *keytype, const char *desc) { return load_keyparams_suppress(uri, format, maybe_stdin, keytype, desc, 0); } void app_bail_out(char *fmt, ...) { va_list args; va_start(args, fmt); BIO_vprintf(bio_err, fmt, args); va_end(args); ERR_print_errors(bio_err); exit(EXIT_FAILURE); } void *app_malloc(size_t sz, const char *what) { void *vp = OPENSSL_malloc(sz); if (vp == NULL) app_bail_out("%s: Could not allocate %zu bytes for %s\n", opt_getprog(), sz, what); return vp; } char *next_item(char *opt) { while (*opt != ',' && !isspace(_UC(*opt)) && *opt != '\0') opt++; if (*opt != '\0') { *opt++ = '\0'; while (isspace(_UC(*opt))) opt++; } return *opt == '\0' ? NULL : opt; } static void warn_cert_msg(const char *uri, X509 *cert, const char *msg) { char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0); BIO_printf(bio_err, "Warning: certificate from '%s' with subject '%s' %s\n", uri, subj, msg); OPENSSL_free(subj); } static void warn_cert(const char *uri, X509 *cert, int warn_EE, X509_VERIFY_PARAM *vpm) { uint32_t ex_flags = X509_get_extension_flags(cert); int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert), X509_get0_notAfter(cert)); if (res != 0) warn_cert_msg(uri, cert, res > 0 ? "has expired" : "not yet valid"); if (warn_EE && (ex_flags & EXFLAG_V1) == 0 && (ex_flags & EXFLAG_CA) == 0) warn_cert_msg(uri, cert, "is not a CA cert"); } static void warn_certs(const char *uri, STACK_OF(X509) *certs, int warn_EE, X509_VERIFY_PARAM *vpm) { int i; for (i = 0; i < sk_X509_num(certs); i++) warn_cert(uri, sk_X509_value(certs, i), warn_EE, vpm); } int load_cert_certs(const char *uri, X509 **pcert, STACK_OF(X509) **pcerts, int exclude_http, const char *pass, const char *desc, X509_VERIFY_PARAM *vpm) { int ret = 0; char *pass_string; if (desc == NULL) desc = pcerts == NULL ? "certificate" : "certificates"; if (exclude_http && (HAS_CASE_PREFIX(uri, "http: || HAS_CASE_PREFIX(uri, "https: BIO_printf(bio_err, "error: HTTP retrieval not allowed for %s\n", desc); return ret; } pass_string = get_passwd(pass, desc); ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass_string, desc, 0, NULL, NULL, NULL, pcert, pcerts, NULL, NULL); clear_free(pass_string); if (ret) { if (pcert != NULL) warn_cert(uri, *pcert, 0, vpm); if (pcerts != NULL) warn_certs(uri, *pcerts, 1, vpm); } else { if (pcerts != NULL) { OSSL_STACK_OF_X509_free(*pcerts); *pcerts = NULL; } } return ret; } STACK_OF(X509) *load_certs_multifile(char *files, const char *pass, const char *desc, X509_VERIFY_PARAM *vpm) { STACK_OF(X509) *certs = NULL; STACK_OF(X509) *result = sk_X509_new_null(); if (files == NULL) goto err; if (result == NULL) goto oom; while (files != NULL) { char *next = next_item(files); if (!load_cert_certs(files, NULL, &certs, 0, pass, desc, vpm)) goto err; if (!X509_add_certs(result, certs, X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP)) goto oom; OSSL_STACK_OF_X509_free(certs); certs = NULL; files = next; } return result; oom: BIO_printf(bio_err, "out of memory\n"); err: OSSL_STACK_OF_X509_free(certs); OSSL_STACK_OF_X509_free(result); return NULL; } static X509_STORE *sk_X509_to_store(X509_STORE *store , const STACK_OF(X509) *certs ) { int i; if (store == NULL) store = X509_STORE_new(); if (store == NULL) return NULL; for (i = 0; i < sk_X509_num(certs); i++) { if (!X509_STORE_add_cert(store, sk_X509_value(certs, i))) { X509_STORE_free(store); return NULL; } } return store; } X509_STORE *load_certstore(char *input, const char *pass, const char *desc, X509_VERIFY_PARAM *vpm) { X509_STORE *store = NULL; STACK_OF(X509) *certs = NULL; while (input != NULL) { char *next = next_item(input); int ok; if (!load_cert_certs(input, NULL, &certs, 1, pass, desc, vpm)) { X509_STORE_free(store); return NULL; } ok = (store = sk_X509_to_store(store, certs)) != NULL; OSSL_STACK_OF_X509_free(certs); certs = NULL; if (!ok) return NULL; input = next; } return store; } int load_certs(const char *uri, int maybe_stdin, STACK_OF(X509) **certs, const char *pass, const char *desc) { int ret, was_NULL = *certs == NULL; if (desc == NULL) desc = "certificates"; ret = load_key_certs_crls(uri, FORMAT_UNDEF, maybe_stdin, pass, desc, 0, NULL, NULL, NULL, NULL, certs, NULL, NULL); if (!ret && was_NULL) { OSSL_STACK_OF_X509_free(*certs); *certs = NULL; } return ret; } int load_crls(const char *uri, STACK_OF(X509_CRL) **crls, const char *pass, const char *desc) { int ret, was_NULL = *crls == NULL; if (desc == NULL) desc = "CRLs"; ret = load_key_certs_crls(uri, FORMAT_UNDEF, 0, pass, desc, 0, NULL, NULL, NULL, NULL, NULL, NULL, crls); if (!ret && was_NULL) { sk_X509_CRL_pop_free(*crls, X509_CRL_free); *crls = NULL; } return ret; } static const char *format2string(int format) { switch (format) { case FORMAT_PEM: return "PEM"; case FORMAT_ASN1: return "DER"; } return NULL; } #define SET_EXPECT(val) \ (expect = expect < 0 ? (val) : (expect == (val) ? (val) : 0)) #define SET_EXPECT1(pvar, val) \ if ((pvar) != NULL) { \ *(pvar) = NULL; \ SET_EXPECT(val); \ } #define FAIL_NAME \ (ppkey != NULL ? "private key" : ppubkey != NULL ? "public key" : \ pparams != NULL ? "key parameters" : \ pcert != NULL ? "certificate" : pcerts != NULL ? "certificates" : \ pcrl != NULL ? "CRL" : pcrls != NULL ? "CRLs" : NULL) int load_key_certs_crls(const char *uri, int format, int maybe_stdin, const char *pass, const char *desc, int quiet, EVP_PKEY **ppkey, EVP_PKEY **ppubkey, EVP_PKEY **pparams, X509 **pcert, STACK_OF(X509) **pcerts, X509_CRL **pcrl, STACK_OF(X509_CRL) **pcrls) { PW_CB_DATA uidata; OSSL_STORE_CTX *ctx = NULL; OSSL_LIB_CTX *libctx = app_get0_libctx(); const char *propq = app_get0_propq(); int ncerts = 0, ncrls = 0, expect = -1; const char *failed = FAIL_NAME; const char *input_type; OSSL_PARAM itp[2]; const OSSL_PARAM *params = NULL; if (failed == NULL) { if (!quiet) BIO_printf(bio_err, "Internal error: nothing to load from %s\n", uri != NULL ? uri : "<stdin>"); return 0; } ERR_set_mark(); SET_EXPECT1(ppkey, OSSL_STORE_INFO_PKEY); SET_EXPECT1(ppubkey, OSSL_STORE_INFO_PUBKEY); SET_EXPECT1(pparams, OSSL_STORE_INFO_PARAMS); SET_EXPECT1(pcert, OSSL_STORE_INFO_CERT); if (pcerts != NULL) { if (*pcerts == NULL && (*pcerts = sk_X509_new_null()) == NULL) { if (!quiet) BIO_printf(bio_err, "Out of memory loading"); goto end; } SET_EXPECT(OSSL_STORE_INFO_CERT); } SET_EXPECT1(pcrl, OSSL_STORE_INFO_CRL); if (pcrls != NULL) { if (*pcrls == NULL && (*pcrls = sk_X509_CRL_new_null()) == NULL) { if (!quiet) BIO_printf(bio_err, "Out of memory loading"); goto end; } SET_EXPECT(OSSL_STORE_INFO_CRL); } uidata.password = pass; uidata.prompt_info = uri; if ((input_type = format2string(format)) != NULL) { itp[0] = OSSL_PARAM_construct_utf8_string(OSSL_STORE_PARAM_INPUT_TYPE, (char *)input_type, 0); itp[1] = OSSL_PARAM_construct_end(); params = itp; } if (uri == NULL) { BIO *bio; if (!maybe_stdin) { if (!quiet) BIO_printf(bio_err, "No filename or uri specified for loading\n"); goto end; } uri = "<stdin>"; unbuffer(stdin); bio = BIO_new_fp(stdin, 0); if (bio != NULL) { ctx = OSSL_STORE_attach(bio, "file", libctx, propq, get_ui_method(), &uidata, params, NULL, NULL); BIO_free(bio); } } else { ctx = OSSL_STORE_open_ex(uri, libctx, propq, get_ui_method(), &uidata, params, NULL, NULL); } if (ctx == NULL) { if (!quiet) BIO_printf(bio_err, "Could not open file or uri for loading"); goto end; } if (expect > 0 && !OSSL_STORE_expect(ctx, expect)) { if (!quiet) BIO_printf(bio_err, "Internal error trying to load"); goto end; } failed = NULL; while ((ppkey != NULL || ppubkey != NULL || pparams != NULL || pcert != NULL || pcerts != NULL || pcrl != NULL || pcrls != NULL) && !OSSL_STORE_eof(ctx)) { OSSL_STORE_INFO *info = OSSL_STORE_load(ctx); int type, ok = 1; if (info == NULL) { continue; } type = OSSL_STORE_INFO_get_type(info); switch (type) { case OSSL_STORE_INFO_PKEY: if (ppkey != NULL) { ok = (*ppkey = OSSL_STORE_INFO_get1_PKEY(info)) != NULL; if (ok) ppkey = NULL; break; } case OSSL_STORE_INFO_PUBKEY: if (ppubkey != NULL) { ok = (*ppubkey = OSSL_STORE_INFO_get1_PUBKEY(info)) != NULL; if (ok) ppubkey = NULL; } break; case OSSL_STORE_INFO_PARAMS: if (pparams != NULL) { ok = (*pparams = OSSL_STORE_INFO_get1_PARAMS(info)) != NULL; if (ok) pparams = NULL; } break; case OSSL_STORE_INFO_CERT: if (pcert != NULL) { ok = (*pcert = OSSL_STORE_INFO_get1_CERT(info)) != NULL; if (ok) pcert = NULL; } else if (pcerts != NULL) { ok = X509_add_cert(*pcerts, OSSL_STORE_INFO_get1_CERT(info), X509_ADD_FLAG_DEFAULT); } ncerts += ok; break; case OSSL_STORE_INFO_CRL: if (pcrl != NULL) { ok = (*pcrl = OSSL_STORE_INFO_get1_CRL(info)) != NULL; if (ok) pcrl = NULL; } else if (pcrls != NULL) { ok = sk_X509_CRL_push(*pcrls, OSSL_STORE_INFO_get1_CRL(info)); } ncrls += ok; break; default: break; } OSSL_STORE_INFO_free(info); if (!ok) { failed = OSSL_STORE_INFO_type_string(type); if (!quiet) BIO_printf(bio_err, "Error reading"); break; } } end: OSSL_STORE_close(ctx); if (ncerts > 0) pcerts = NULL; if (ncrls > 0) pcrls = NULL; if (failed == NULL) { failed = FAIL_NAME; if (failed != NULL && !quiet) BIO_printf(bio_err, "Could not find"); } if (failed != NULL && !quiet) { unsigned long err = ERR_peek_last_error(); if (desc != NULL && strstr(desc, failed) != NULL) { BIO_printf(bio_err, " %s", desc); } else { BIO_printf(bio_err, " %s", failed); if (desc != NULL) BIO_printf(bio_err, " of %s", desc); } if (uri != NULL) BIO_printf(bio_err, " from %s", uri); if (ERR_SYSTEM_ERROR(err)) { BIO_printf(bio_err, ": %s", strerror(ERR_GET_REASON(err))); ERR_pop_to_mark(); ERR_set_mark(); } BIO_printf(bio_err, "\n"); ERR_print_errors(bio_err); } if (quiet || failed == NULL) ERR_pop_to_mark(); else ERR_clear_last_mark(); return failed == NULL; } #define X509V3_EXT_UNKNOWN_MASK (0xfL << 16) #define X509V3_EXT_DEFAULT 0 #define X509V3_EXT_ERROR_UNKNOWN (1L << 16) #define X509V3_EXT_PARSE_UNKNOWN (2L << 16) #define X509V3_EXT_DUMP_UNKNOWN (3L << 16) #define X509_FLAG_CA (X509_FLAG_NO_ISSUER | X509_FLAG_NO_PUBKEY | \ X509_FLAG_NO_HEADER | X509_FLAG_NO_VERSION) int set_cert_ex(unsigned long *flags, const char *arg) { static const NAME_EX_TBL cert_tbl[] = { {"compatible", X509_FLAG_COMPAT, 0xffffffffl}, {"ca_default", X509_FLAG_CA, 0xffffffffl}, {"no_header", X509_FLAG_NO_HEADER, 0}, {"no_version", X509_FLAG_NO_VERSION, 0}, {"no_serial", X509_FLAG_NO_SERIAL, 0}, {"no_signame", X509_FLAG_NO_SIGNAME, 0}, {"no_validity", X509_FLAG_NO_VALIDITY, 0}, {"no_subject", X509_FLAG_NO_SUBJECT, 0}, {"no_issuer", X509_FLAG_NO_ISSUER, 0}, {"no_pubkey", X509_FLAG_NO_PUBKEY, 0}, {"no_extensions", X509_FLAG_NO_EXTENSIONS, 0}, {"no_sigdump", X509_FLAG_NO_SIGDUMP, 0}, {"no_aux", X509_FLAG_NO_AUX, 0}, {"no_attributes", X509_FLAG_NO_ATTRIBUTES, 0}, {"ext_default", X509V3_EXT_DEFAULT, X509V3_EXT_UNKNOWN_MASK}, {"ext_error", X509V3_EXT_ERROR_UNKNOWN, X509V3_EXT_UNKNOWN_MASK}, {"ext_parse", X509V3_EXT_PARSE_UNKNOWN, X509V3_EXT_UNKNOWN_MASK}, {"ext_dump", X509V3_EXT_DUMP_UNKNOWN, X509V3_EXT_UNKNOWN_MASK}, {NULL, 0, 0} }; return set_multi_opts(flags, arg, cert_tbl); } int set_name_ex(unsigned long *flags, const char *arg) { static const NAME_EX_TBL ex_tbl[] = { {"esc_2253", ASN1_STRFLGS_ESC_2253, 0}, {"esc_2254", ASN1_STRFLGS_ESC_2254, 0}, {"esc_ctrl", ASN1_STRFLGS_ESC_CTRL, 0}, {"esc_msb", ASN1_STRFLGS_ESC_MSB, 0}, {"use_quote", ASN1_STRFLGS_ESC_QUOTE, 0}, {"utf8", ASN1_STRFLGS_UTF8_CONVERT, 0}, {"ignore_type", ASN1_STRFLGS_IGNORE_TYPE, 0}, {"show_type", ASN1_STRFLGS_SHOW_TYPE, 0}, {"dump_all", ASN1_STRFLGS_DUMP_ALL, 0}, {"dump_nostr", ASN1_STRFLGS_DUMP_UNKNOWN, 0}, {"dump_der", ASN1_STRFLGS_DUMP_DER, 0}, {"compat", XN_FLAG_COMPAT, 0xffffffffL}, {"sep_comma_plus", XN_FLAG_SEP_COMMA_PLUS, XN_FLAG_SEP_MASK}, {"sep_comma_plus_space", XN_FLAG_SEP_CPLUS_SPC, XN_FLAG_SEP_MASK}, {"sep_semi_plus_space", XN_FLAG_SEP_SPLUS_SPC, XN_FLAG_SEP_MASK}, {"sep_multiline", XN_FLAG_SEP_MULTILINE, XN_FLAG_SEP_MASK}, {"dn_rev", XN_FLAG_DN_REV, 0}, {"nofname", XN_FLAG_FN_NONE, XN_FLAG_FN_MASK}, {"sname", XN_FLAG_FN_SN, XN_FLAG_FN_MASK}, {"lname", XN_FLAG_FN_LN, XN_FLAG_FN_MASK}, {"align", XN_FLAG_FN_ALIGN, 0}, {"oid", XN_FLAG_FN_OID, XN_FLAG_FN_MASK}, {"space_eq", XN_FLAG_SPC_EQ, 0}, {"dump_unknown", XN_FLAG_DUMP_UNKNOWN_FIELDS, 0}, {"RFC2253", XN_FLAG_RFC2253, 0xffffffffL}, {"oneline", XN_FLAG_ONELINE, 0xffffffffL}, {"multiline", XN_FLAG_MULTILINE, 0xffffffffL}, {"ca_default", XN_FLAG_MULTILINE, 0xffffffffL}, {NULL, 0, 0} }; if (set_multi_opts(flags, arg, ex_tbl) == 0) return 0; if (*flags != XN_FLAG_COMPAT && (*flags & XN_FLAG_SEP_MASK) == 0) *flags |= XN_FLAG_SEP_CPLUS_SPC; return 1; } int set_dateopt(unsigned long *dateopt, const char *arg) { if (OPENSSL_strcasecmp(arg, "rfc_822") == 0) *dateopt = ASN1_DTFLGS_RFC822; else if (OPENSSL_strcasecmp(arg, "iso_8601") == 0) *dateopt = ASN1_DTFLGS_ISO8601; else return 0; return 1; } int set_ext_copy(int *copy_type, const char *arg) { if (OPENSSL_strcasecmp(arg, "none") == 0) *copy_type = EXT_COPY_NONE; else if (OPENSSL_strcasecmp(arg, "copy") == 0) *copy_type = EXT_COPY_ADD; else if (OPENSSL_strcasecmp(arg, "copyall") == 0) *copy_type = EXT_COPY_ALL; else return 0; return 1; } int copy_extensions(X509 *x, X509_REQ *req, int copy_type) { STACK_OF(X509_EXTENSION) *exts; int i, ret = 0; if (x == NULL || req == NULL) return 0; if (copy_type == EXT_COPY_NONE) return 1; exts = X509_REQ_get_extensions(req); for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) { X509_EXTENSION *ext = sk_X509_EXTENSION_value(exts, i); ASN1_OBJECT *obj = X509_EXTENSION_get_object(ext); int idx = X509_get_ext_by_OBJ(x, obj, -1); if (idx != -1) { if (copy_type == EXT_COPY_ADD) continue; do { X509_EXTENSION_free(X509_delete_ext(x, idx)); idx = X509_get_ext_by_OBJ(x, obj, -1); } while (idx != -1); } if (!X509_add_ext(x, ext, -1)) goto end; } ret = 1; end: sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free); return ret; } static int set_multi_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl) { STACK_OF(CONF_VALUE) *vals; CONF_VALUE *val; int i, ret = 1; if (!arg) return 0; vals = X509V3_parse_list(arg); for (i = 0; i < sk_CONF_VALUE_num(vals); i++) { val = sk_CONF_VALUE_value(vals, i); if (!set_table_opts(flags, val->name, in_tbl)) ret = 0; } sk_CONF_VALUE_pop_free(vals, X509V3_conf_free); return ret; } static int set_table_opts(unsigned long *flags, const char *arg, const NAME_EX_TBL *in_tbl) { char c; const NAME_EX_TBL *ptbl; c = arg[0]; if (c == '-') { c = 0; arg++; } else if (c == '+') { c = 1; arg++; } else { c = 1; } for (ptbl = in_tbl; ptbl->name; ptbl++) { if (OPENSSL_strcasecmp(arg, ptbl->name) == 0) { *flags &= ~ptbl->mask; if (c) *flags |= ptbl->flag; else *flags &= ~ptbl->flag; return 1; } } return 0; } void print_name(BIO *out, const char *title, const X509_NAME *nm) { char *buf; char mline = 0; int indent = 0; unsigned long lflags = get_nameopt(); if (out == NULL) return; if (title != NULL) BIO_puts(out, title); if ((lflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) { mline = 1; indent = 4; } if (lflags == XN_FLAG_COMPAT) { buf = X509_NAME_oneline(nm, 0, 0); BIO_puts(out, buf); BIO_puts(out, "\n"); OPENSSL_free(buf); } else { if (mline) BIO_puts(out, "\n"); X509_NAME_print_ex(out, nm, indent, lflags); BIO_puts(out, "\n"); } } void print_bignum_var(BIO *out, const BIGNUM *in, const char *var, int len, unsigned char *buffer) { BIO_printf(out, " static unsigned char %s_%d[] = {", var, len); if (BN_is_zero(in)) { BIO_printf(out, "\n 0x00"); } else { int i, l; l = BN_bn2bin(in, buffer); for (i = 0; i < l; i++) { BIO_printf(out, (i % 10) == 0 ? "\n " : " "); if (i < l - 1) BIO_printf(out, "0x%02X,", buffer[i]); else BIO_printf(out, "0x%02X", buffer[i]); } } BIO_printf(out, "\n };\n"); } void print_array(BIO *out, const char *title, int len, const unsigned char *d) { int i; BIO_printf(out, "unsigned char %s[%d] = {", title, len); for (i = 0; i < len; i++) { if ((i % 10) == 0) BIO_printf(out, "\n "); if (i < len - 1) BIO_printf(out, "0x%02X, ", d[i]); else BIO_printf(out, "0x%02X", d[i]); } BIO_printf(out, "\n};\n"); } X509_STORE *setup_verify(const char *CAfile, int noCAfile, const char *CApath, int noCApath, const char *CAstore, int noCAstore) { X509_STORE *store = X509_STORE_new(); X509_LOOKUP *lookup; OSSL_LIB_CTX *libctx = app_get0_libctx(); const char *propq = app_get0_propq(); if (store == NULL) goto end; if (CAfile != NULL || !noCAfile) { lookup = X509_STORE_add_lookup(store, X509_LOOKUP_file()); if (lookup == NULL) goto end; if (CAfile != NULL) { if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_PEM, libctx, propq) <= 0) { ERR_clear_error(); if (X509_LOOKUP_load_file_ex(lookup, CAfile, X509_FILETYPE_ASN1, libctx, propq) <= 0) { BIO_printf(bio_err, "Error loading file %s\n", CAfile); goto end; } } } else { X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT, libctx, propq); } } if (CApath != NULL || !noCApath) { lookup = X509_STORE_add_lookup(store, X509_LOOKUP_hash_dir()); if (lookup == NULL) goto end; if (CApath != NULL) { if (X509_LOOKUP_add_dir(lookup, CApath, X509_FILETYPE_PEM) <= 0) { BIO_printf(bio_err, "Error loading directory %s\n", CApath); goto end; } } else { X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT); } } if (CAstore != NULL || !noCAstore) { lookup = X509_STORE_add_lookup(store, X509_LOOKUP_store()); if (lookup == NULL) goto end; if (!X509_LOOKUP_add_store_ex(lookup, CAstore, libctx, propq)) { if (CAstore != NULL) BIO_printf(bio_err, "Error loading store URI %s\n", CAstore); goto end; } } ERR_clear_error(); return store; end: ERR_print_errors(bio_err); X509_STORE_free(store); return NULL; } static unsigned long index_serial_hash(const OPENSSL_CSTRING *a) { const char *n; n = a[DB_serial]; while (*n == '0') n++; return OPENSSL_LH_strhash(n); } static int index_serial_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b) { const char *aa, *bb; for (aa = a[DB_serial]; *aa == '0'; aa++) ; for (bb = b[DB_serial]; *bb == '0'; bb++) ; return strcmp(aa, bb); } static int index_name_qual(char **a) { return (a[0][0] == 'V'); } static unsigned long index_name_hash(const OPENSSL_CSTRING *a) { return OPENSSL_LH_strhash(a[DB_name]); } int index_name_cmp(const OPENSSL_CSTRING *a, const OPENSSL_CSTRING *b) { return strcmp(a[DB_name], b[DB_name]); } static IMPLEMENT_LHASH_HASH_FN(index_serial, OPENSSL_CSTRING) static IMPLEMENT_LHASH_COMP_FN(index_serial, OPENSSL_CSTRING) static IMPLEMENT_LHASH_HASH_FN(index_name, OPENSSL_CSTRING) static IMPLEMENT_LHASH_COMP_FN(index_name, OPENSSL_CSTRING) #undef BSIZE #define BSIZE 256 BIGNUM *load_serial(const char *serialfile, int *exists, int create, ASN1_INTEGER **retai) { BIO *in = NULL; BIGNUM *ret = NULL; char buf[1024]; ASN1_INTEGER *ai = NULL; ai = ASN1_INTEGER_new(); if (ai == NULL) goto err; in = BIO_new_file(serialfile, "r"); if (exists != NULL) *exists = in != NULL; if (in == NULL) { if (!create) { perror(serialfile); goto err; } ERR_clear_error(); ret = BN_new(); if (ret == NULL) { BIO_printf(bio_err, "Out of memory\n"); } else if (!rand_serial(ret, ai)) { BIO_printf(bio_err, "Error creating random number to store in %s\n", serialfile); BN_free(ret); ret = NULL; } } else { if (!a2i_ASN1_INTEGER(in, ai, buf, 1024)) { BIO_printf(bio_err, "Unable to load number from %s\n", serialfile); goto err; } ret = ASN1_INTEGER_to_BN(ai, NULL); if (ret == NULL) { BIO_printf(bio_err, "Error converting number from bin to BIGNUM\n"); goto err; } } if (ret != NULL && retai != NULL) { *retai = ai; ai = NULL; } err: if (ret == NULL) ERR_print_errors(bio_err); BIO_free(in); ASN1_INTEGER_free(ai); return ret; } int save_serial(const char *serialfile, const char *suffix, const BIGNUM *serial, ASN1_INTEGER **retai) { char buf[1][BSIZE]; BIO *out = NULL; int ret = 0; ASN1_INTEGER *ai = NULL; int j; if (suffix == NULL) j = strlen(serialfile); else j = strlen(serialfile) + strlen(suffix) + 1; if (j >= BSIZE) { BIO_printf(bio_err, "File name too long\n"); goto err; } if (suffix == NULL) { OPENSSL_strlcpy(buf[0], serialfile, BSIZE); } else { #ifndef OPENSSL_SYS_VMS j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, suffix); #else j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, suffix); #endif } out = BIO_new_file(buf[0], "w"); if (out == NULL) { goto err; } if ((ai = BN_to_ASN1_INTEGER(serial, NULL)) == NULL) { BIO_printf(bio_err, "error converting serial to ASN.1 format\n"); goto err; } i2a_ASN1_INTEGER(out, ai); BIO_puts(out, "\n"); ret = 1; if (retai) { *retai = ai; ai = NULL; } err: if (!ret) ERR_print_errors(bio_err); BIO_free_all(out); ASN1_INTEGER_free(ai); return ret; } int rotate_serial(const char *serialfile, const char *new_suffix, const char *old_suffix) { char buf[2][BSIZE]; int i, j; i = strlen(serialfile) + strlen(old_suffix); j = strlen(serialfile) + strlen(new_suffix); if (i > j) j = i; if (j + 1 >= BSIZE) { BIO_printf(bio_err, "File name too long\n"); goto err; } #ifndef OPENSSL_SYS_VMS j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", serialfile, new_suffix); j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", serialfile, old_suffix); #else j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", serialfile, new_suffix); j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", serialfile, old_suffix); #endif if (rename(serialfile, buf[1]) < 0 && errno != ENOENT #ifdef ENOTDIR && errno != ENOTDIR #endif ) { BIO_printf(bio_err, "Unable to rename %s to %s\n", serialfile, buf[1]); perror("reason"); goto err; } if (rename(buf[0], serialfile) < 0) { BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], serialfile); perror("reason"); rename(buf[1], serialfile); goto err; } return 1; err: ERR_print_errors(bio_err); return 0; } int rand_serial(BIGNUM *b, ASN1_INTEGER *ai) { BIGNUM *btmp; int ret = 0; btmp = b == NULL ? BN_new() : b; if (btmp == NULL) return 0; if (!BN_rand(btmp, SERIAL_RAND_BITS, BN_RAND_TOP_ANY, BN_RAND_BOTTOM_ANY)) goto error; if (ai && !BN_to_ASN1_INTEGER(btmp, ai)) goto error; ret = 1; error: if (btmp != b) BN_free(btmp); return ret; } CA_DB *load_index(const char *dbfile, DB_ATTR *db_attr) { CA_DB *retdb = NULL; TXT_DB *tmpdb = NULL; BIO *in; CONF *dbattr_conf = NULL; char buf[BSIZE]; #ifndef OPENSSL_NO_POSIX_IO FILE *dbfp; struct stat dbst; #endif in = BIO_new_file(dbfile, "r"); if (in == NULL) goto err; #ifndef OPENSSL_NO_POSIX_IO BIO_get_fp(in, &dbfp); if (fstat(fileno(dbfp), &dbst) == -1) { ERR_raise_data(ERR_LIB_SYS, errno, "calling fstat(%s)", dbfile); goto err; } #endif if ((tmpdb = TXT_DB_read(in, DB_NUMBER)) == NULL) goto err; #ifndef OPENSSL_SYS_VMS BIO_snprintf(buf, sizeof(buf), "%s.attr", dbfile); #else BIO_snprintf(buf, sizeof(buf), "%s-attr", dbfile); #endif dbattr_conf = app_load_config_quiet(buf); retdb = app_malloc(sizeof(*retdb), "new DB"); retdb->db = tmpdb; tmpdb = NULL; if (db_attr) retdb->attributes = *db_attr; else retdb->attributes.unique_subject = 1; if (dbattr_conf != NULL) { char *p = app_conf_try_string(dbattr_conf, NULL, "unique_subject"); if (p != NULL) retdb->attributes.unique_subject = parse_yesno(p, 1); } retdb->dbfname = OPENSSL_strdup(dbfile); #ifndef OPENSSL_NO_POSIX_IO retdb->dbst = dbst; #endif err: ERR_print_errors(bio_err); NCONF_free(dbattr_conf); TXT_DB_free(tmpdb); BIO_free_all(in); return retdb; } int index_index(CA_DB *db) { if (!TXT_DB_create_index(db->db, DB_serial, NULL, LHASH_HASH_FN(index_serial), LHASH_COMP_FN(index_serial))) { BIO_printf(bio_err, "Error creating serial number index:(%ld,%ld,%ld)\n", db->db->error, db->db->arg1, db->db->arg2); goto err; } if (db->attributes.unique_subject && !TXT_DB_create_index(db->db, DB_name, index_name_qual, LHASH_HASH_FN(index_name), LHASH_COMP_FN(index_name))) { BIO_printf(bio_err, "Error creating name index:(%ld,%ld,%ld)\n", db->db->error, db->db->arg1, db->db->arg2); goto err; } return 1; err: ERR_print_errors(bio_err); return 0; } int save_index(const char *dbfile, const char *suffix, CA_DB *db) { char buf[3][BSIZE]; BIO *out; int j; j = strlen(dbfile) + strlen(suffix); if (j + 6 >= BSIZE) { BIO_printf(bio_err, "File name too long\n"); goto err; } #ifndef OPENSSL_SYS_VMS j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr", dbfile); j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.attr.%s", dbfile, suffix); j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, suffix); #else j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr", dbfile); j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-attr-%s", dbfile, suffix); j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, suffix); #endif out = BIO_new_file(buf[0], "w"); if (out == NULL) { perror(dbfile); BIO_printf(bio_err, "Unable to open '%s'\n", dbfile); goto err; } j = TXT_DB_write(out, db->db); BIO_free(out); if (j <= 0) goto err; out = BIO_new_file(buf[1], "w"); if (out == NULL) { perror(buf[2]); BIO_printf(bio_err, "Unable to open '%s'\n", buf[2]); goto err; } BIO_printf(out, "unique_subject = %s\n", db->attributes.unique_subject ? "yes" : "no"); BIO_free(out); return 1; err: ERR_print_errors(bio_err); return 0; } int rotate_index(const char *dbfile, const char *new_suffix, const char *old_suffix) { char buf[5][BSIZE]; int i, j; i = strlen(dbfile) + strlen(old_suffix); j = strlen(dbfile) + strlen(new_suffix); if (i > j) j = i; if (j + 6 >= BSIZE) { BIO_printf(bio_err, "File name too long\n"); goto err; } #ifndef OPENSSL_SYS_VMS j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s.attr", dbfile); j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s.attr.%s", dbfile, old_suffix); j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s.attr.%s", dbfile, new_suffix); j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s.%s", dbfile, old_suffix); j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s.%s", dbfile, new_suffix); #else j = BIO_snprintf(buf[4], sizeof(buf[4]), "%s-attr", dbfile); j = BIO_snprintf(buf[3], sizeof(buf[3]), "%s-attr-%s", dbfile, old_suffix); j = BIO_snprintf(buf[2], sizeof(buf[2]), "%s-attr-%s", dbfile, new_suffix); j = BIO_snprintf(buf[1], sizeof(buf[1]), "%s-%s", dbfile, old_suffix); j = BIO_snprintf(buf[0], sizeof(buf[0]), "%s-%s", dbfile, new_suffix); #endif if (rename(dbfile, buf[1]) < 0 && errno != ENOENT #ifdef ENOTDIR && errno != ENOTDIR #endif ) { BIO_printf(bio_err, "Unable to rename %s to %s\n", dbfile, buf[1]); perror("reason"); goto err; } if (rename(buf[0], dbfile) < 0) { BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[0], dbfile); perror("reason"); rename(buf[1], dbfile); goto err; } if (rename(buf[4], buf[3]) < 0 && errno != ENOENT #ifdef ENOTDIR && errno != ENOTDIR #endif ) { BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[4], buf[3]); perror("reason"); rename(dbfile, buf[0]); rename(buf[1], dbfile); goto err; } if (rename(buf[2], buf[4]) < 0) { BIO_printf(bio_err, "Unable to rename %s to %s\n", buf[2], buf[4]); perror("reason"); rename(buf[3], buf[4]); rename(dbfile, buf[0]); rename(buf[1], dbfile); goto err; } return 1; err: ERR_print_errors(bio_err); return 0; } void free_index(CA_DB *db) { if (db) { TXT_DB_free(db->db); OPENSSL_free(db->dbfname); OPENSSL_free(db); } } int parse_yesno(const char *str, int def) { if (str) { switch (*str) { case 'f': case 'F': case 'n': case 'N': case '0': return 0; case 't': case 'T': case 'y': case 'Y': case '1': return 1; } } return def; } X509_NAME *parse_name(const char *cp, int chtype, int canmulti, const char *desc) { int nextismulti = 0; char *work; X509_NAME *n; if (*cp++ != '/') { BIO_printf(bio_err, "%s: %s name is expected to be in the format " "/type0=value0/type1=value1/type2=... where characters may " "be escaped by \\. This name is not in that format: '%s'\n", opt_getprog(), desc, --cp); return NULL; } n = X509_NAME_new(); if (n == NULL) { BIO_printf(bio_err, "%s: Out of memory\n", opt_getprog()); return NULL; } work = OPENSSL_strdup(cp); if (work == NULL) { BIO_printf(bio_err, "%s: Error copying %s name input\n", opt_getprog(), desc); goto err; } while (*cp != '\0') { char *bp = work; char *typestr = bp; unsigned char *valstr; int nid; int ismulti = nextismulti; nextismulti = 0; while (*cp != '\0' && *cp != '=') *bp++ = *cp++; *bp++ = '\0'; if (*cp == '\0') { BIO_printf(bio_err, "%s: Missing '=' after RDN type string '%s' in %s name string\n", opt_getprog(), typestr, desc); goto err; } ++cp; valstr = (unsigned char *)bp; for (; *cp != '\0' && *cp != '/'; *bp++ = *cp++) { if (canmulti && *cp == '+') { nextismulti = 1; break; } if (*cp == '\\' && *++cp == '\0') { BIO_printf(bio_err, "%s: Escape character at end of %s name string\n", opt_getprog(), desc); goto err; } } *bp++ = '\0'; if (*cp != '\0') ++cp; nid = OBJ_txt2nid(typestr); if (nid == NID_undef) { BIO_printf(bio_err, "%s warning: Skipping unknown %s name attribute \"%s\"\n", opt_getprog(), desc, typestr); if (ismulti) BIO_printf(bio_err, "%s hint: a '+' in a value string needs be escaped using '\\' else a new member of a multi-valued RDN is expected\n", opt_getprog()); continue; } if (*valstr == '\0') { BIO_printf(bio_err, "%s warning: No value provided for %s name attribute \"%s\", skipped\n", opt_getprog(), desc, typestr); continue; } if (!X509_NAME_add_entry_by_NID(n, nid, chtype, valstr, strlen((char *)valstr), -1, ismulti ? -1 : 0)) { ERR_print_errors(bio_err); BIO_printf(bio_err, "%s: Error adding %s name attribute \"/%s=%s\"\n", opt_getprog(), desc, typestr, valstr); goto err; } } OPENSSL_free(work); return n; err: X509_NAME_free(n); OPENSSL_free(work); return NULL; } int bio_to_mem(unsigned char **out, int maxlen, BIO *in) { BIO *mem; int len, ret; unsigned char tbuf[1024]; mem = BIO_new(BIO_s_mem()); if (mem == NULL) return -1; for (;;) { if ((maxlen != -1) && maxlen < 1024) len = maxlen; else len = 1024; len = BIO_read(in, tbuf, len); if (len < 0) { BIO_free(mem); return -1; } if (len == 0) break; if (BIO_write(mem, tbuf, len) != len) { BIO_free(mem); return -1; } if (maxlen != -1) maxlen -= len; if (maxlen == 0) break; } ret = BIO_get_mem_data(mem, (char **)out); BIO_set_flags(mem, BIO_FLAGS_MEM_RDONLY); BIO_free(mem); return ret; } int pkey_ctrl_string(EVP_PKEY_CTX *ctx, const char *value) { int rv = 0; char *stmp, *vtmp = NULL; stmp = OPENSSL_strdup(value); if (stmp == NULL) return -1; vtmp = strchr(stmp, ':'); if (vtmp == NULL) goto err; *vtmp = 0; vtmp++; rv = EVP_PKEY_CTX_ctrl_str(ctx, stmp, vtmp); err: OPENSSL_free(stmp); return rv; } static void nodes_print(const char *name, STACK_OF(X509_POLICY_NODE) *nodes) { X509_POLICY_NODE *node; int i; BIO_printf(bio_err, "%s Policies:", name); if (nodes) { BIO_puts(bio_err, "\n"); for (i = 0; i < sk_X509_POLICY_NODE_num(nodes); i++) { node = sk_X509_POLICY_NODE_value(nodes, i); X509_POLICY_NODE_print(bio_err, node, 2); } } else { BIO_puts(bio_err, " <empty>\n"); } } void policies_print(X509_STORE_CTX *ctx) { X509_POLICY_TREE *tree; int explicit_policy; tree = X509_STORE_CTX_get0_policy_tree(ctx); explicit_policy = X509_STORE_CTX_get_explicit_policy(ctx); BIO_printf(bio_err, "Require explicit Policy: %s\n", explicit_policy ? "True" : "False"); nodes_print("Authority", X509_policy_tree_get0_policies(tree)); nodes_print("User", X509_policy_tree_get0_user_policies(tree)); } unsigned char *next_protos_parse(size_t *outlen, const char *in) { size_t len; unsigned char *out; size_t i, start = 0; size_t skipped = 0; len = strlen(in); if (len == 0 || len >= 65535) return NULL; out = app_malloc(len + 1, "NPN buffer"); for (i = 0; i <= len; ++i) { if (i == len || in[i] == ',') { if (i == start) { ++start; ++skipped; continue; } if (i - start > 255) { OPENSSL_free(out); return NULL; } out[start - skipped] = (unsigned char)(i - start); start = i + 1; } else { out[i + 1 - skipped] = in[i]; } } if (len <= skipped) { OPENSSL_free(out); return NULL; } *outlen = len + 1 - skipped; return out; } int check_cert_attributes(BIO *bio, X509 *x, const char *checkhost, const char *checkemail, const char *checkip, int print) { int valid_host = 0; int valid_mail = 0; int valid_ip = 0; int ret = 1; if (x == NULL) return 0; if (checkhost != NULL) { valid_host = X509_check_host(x, checkhost, 0, 0, NULL); if (print) BIO_printf(bio, "Hostname %s does%s match certificate\n", checkhost, valid_host == 1 ? "" : " NOT"); ret = ret && valid_host; } if (checkemail != NULL) { valid_mail = X509_check_email(x, checkemail, 0, 0); if (print) BIO_printf(bio, "Email %s does%s match certificate\n", checkemail, valid_mail ? "" : " NOT"); ret = ret && valid_mail; } if (checkip != NULL) { valid_ip = X509_check_ip_asc(x, checkip, 0); if (print) BIO_printf(bio, "IP %s does%s match certificate\n", checkip, valid_ip ? "" : " NOT"); ret = ret && valid_ip; } return ret; } static int do_pkey_ctx_init(EVP_PKEY_CTX *pkctx, STACK_OF(OPENSSL_STRING) *opts) { int i; if (opts == NULL) return 1; for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) { char *opt = sk_OPENSSL_STRING_value(opts, i); if (pkey_ctrl_string(pkctx, opt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", opt); ERR_print_errors(bio_err); return 0; } } return 1; } static int do_x509_init(X509 *x, STACK_OF(OPENSSL_STRING) *opts) { int i; if (opts == NULL) return 1; for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) { char *opt = sk_OPENSSL_STRING_value(opts, i); if (x509_ctrl_string(x, opt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", opt); ERR_print_errors(bio_err); return 0; } } return 1; } static int do_x509_req_init(X509_REQ *x, STACK_OF(OPENSSL_STRING) *opts) { int i; if (opts == NULL) return 1; for (i = 0; i < sk_OPENSSL_STRING_num(opts); i++) { char *opt = sk_OPENSSL_STRING_value(opts, i); if (x509_req_ctrl_string(x, opt) <= 0) { BIO_printf(bio_err, "parameter error \"%s\"\n", opt); ERR_print_errors(bio_err); return 0; } } return 1; } static int do_sign_init(EVP_MD_CTX *ctx, EVP_PKEY *pkey, const char *md, STACK_OF(OPENSSL_STRING) *sigopts) { EVP_PKEY_CTX *pkctx = NULL; char def_md[80]; if (ctx == NULL) return 0; if (EVP_PKEY_get_default_digest_name(pkey, def_md, sizeof(def_md)) == 2 && strcmp(def_md, "UNDEF") == 0) { md = NULL; } return EVP_DigestSignInit_ex(ctx, &pkctx, md, app_get0_libctx(), app_get0_propq(), pkey, NULL) && do_pkey_ctx_init(pkctx, sigopts); } static int adapt_keyid_ext(X509 *cert, X509V3_CTX *ext_ctx, const char *name, const char *value, int add_default) { const STACK_OF(X509_EXTENSION) *exts = X509_get0_extensions(cert); X509_EXTENSION *new_ext = X509V3_EXT_nconf(NULL, ext_ctx, name, value); int idx, rv = 0; if (new_ext == NULL) return rv; idx = X509v3_get_ext_by_OBJ(exts, X509_EXTENSION_get_object(new_ext), -1); if (idx >= 0) { X509_EXTENSION *found_ext = X509v3_get_ext(exts, idx); ASN1_OCTET_STRING *encoded = X509_EXTENSION_get_data(found_ext); int disabled = ASN1_STRING_length(encoded) <= 2; if (disabled) { X509_delete_ext(cert, idx); X509_EXTENSION_free(found_ext); } rv = 1; } else { rv = !add_default || X509_add_ext(cert, new_ext, -1); } X509_EXTENSION_free(new_ext); return rv; } int cert_matches_key(const X509 *cert, const EVP_PKEY *pkey) { int match; ERR_set_mark(); match = X509_check_private_key(cert, pkey); ERR_pop_to_mark(); return match; } int do_X509_sign(X509 *cert, int force_v1, EVP_PKEY *pkey, const char *md, STACK_OF(OPENSSL_STRING) *sigopts, X509V3_CTX *ext_ctx) { EVP_MD_CTX *mctx = EVP_MD_CTX_new(); int self_sign; int rv = 0; if (!force_v1) { if (!X509_set_version(cert, X509_VERSION_3)) goto end; if (!adapt_keyid_ext(cert, ext_ctx, "subjectKeyIdentifier", "hash", 1)) goto end; self_sign = cert_matches_key(cert, pkey); if (!adapt_keyid_ext(cert, ext_ctx, "authorityKeyIdentifier", "keyid, issuer", !self_sign)) goto end; } if (mctx != NULL && do_sign_init(mctx, pkey, md, sigopts) > 0) rv = (X509_sign_ctx(cert, mctx) > 0); end: EVP_MD_CTX_free(mctx); return rv; } int do_X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const char *md, STACK_OF(OPENSSL_STRING) *sigopts) { int rv = 0; EVP_MD_CTX *mctx = EVP_MD_CTX_new(); if (do_sign_init(mctx, pkey, md, sigopts) > 0) rv = (X509_REQ_sign_ctx(x, mctx) > 0); EVP_MD_CTX_free(mctx); return rv; } int do_X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const char *md, STACK_OF(OPENSSL_STRING) *sigopts) { int rv = 0; EVP_MD_CTX *mctx = EVP_MD_CTX_new(); if (do_sign_init(mctx, pkey, md, sigopts) > 0) rv = (X509_CRL_sign_ctx(x, mctx) > 0); EVP_MD_CTX_free(mctx); return rv; } int do_X509_verify(X509 *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts) { int rv = 0; if (do_x509_init(x, vfyopts) > 0) rv = X509_verify(x, pkey); else rv = -1; return rv; } int do_X509_REQ_verify(X509_REQ *x, EVP_PKEY *pkey, STACK_OF(OPENSSL_STRING) *vfyopts) { int rv = 0; if (do_x509_req_init(x, vfyopts) > 0) rv = X509_REQ_verify_ex(x, pkey, app_get0_libctx(), app_get0_propq()); else rv = -1; return rv; } static const char *get_dp_url(DIST_POINT *dp) { GENERAL_NAMES *gens; GENERAL_NAME *gen; int i, gtype; ASN1_STRING *uri; if (!dp->distpoint || dp->distpoint->type != 0) return NULL; gens = dp->distpoint->name.fullname; for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) { gen = sk_GENERAL_NAME_value(gens, i); uri = GENERAL_NAME_get0_value(gen, &gtype); if (gtype == GEN_URI && ASN1_STRING_length(uri) > 6) { const char *uptr = (const char *)ASN1_STRING_get0_data(uri); if (IS_HTTP(uptr)) return uptr; } } return NULL; } static X509_CRL *load_crl_crldp(STACK_OF(DIST_POINT) *crldp) { int i; const char *urlptr = NULL; for (i = 0; i < sk_DIST_POINT_num(crldp); i++) { DIST_POINT *dp = sk_DIST_POINT_value(crldp, i); urlptr = get_dp_url(dp); if (urlptr != NULL) return load_crl(urlptr, FORMAT_UNDEF, 0, "CRL via CDP"); } return NULL; } static STACK_OF(X509_CRL) *crls_http_cb(const X509_STORE_CTX *ctx, const X509_NAME *nm) { X509 *x; STACK_OF(X509_CRL) *crls = NULL; X509_CRL *crl; STACK_OF(DIST_POINT) *crldp; crls = sk_X509_CRL_new_null(); if (!crls) return NULL; x = X509_STORE_CTX_get_current_cert(ctx); crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, NULL, NULL); crl = load_crl_crldp(crldp); sk_DIST_POINT_pop_free(crldp, DIST_POINT_free); if (!crl) { sk_X509_CRL_free(crls); return NULL; } sk_X509_CRL_push(crls, crl); crldp = X509_get_ext_d2i(x, NID_freshest_crl, NULL, NULL); crl = load_crl_crldp(crldp); sk_DIST_POINT_pop_free(crldp, DIST_POINT_free); if (crl) sk_X509_CRL_push(crls, crl); return crls; } void store_setup_crl_download(X509_STORE *st) { X509_STORE_set_lookup_crls_cb(st, crls_http_cb); } #if !defined(OPENSSL_NO_SOCK) && !defined(OPENSSL_NO_HTTP) static const char *tls_error_hint(void) { unsigned long err = ERR_peek_error(); if (ERR_GET_LIB(err) != ERR_LIB_SSL) err = ERR_peek_last_error(); if (ERR_GET_LIB(err) != ERR_LIB_SSL) return NULL; switch (ERR_GET_REASON(err)) { case SSL_R_WRONG_VERSION_NUMBER: return "The server does not support (a suitable version of) TLS"; case SSL_R_UNKNOWN_PROTOCOL: return "The server does not support HTTPS"; case SSL_R_CERTIFICATE_VERIFY_FAILED: return "Cannot authenticate server via its TLS certificate, likely due to mismatch with our trusted TLS certs or missing revocation status"; case SSL_AD_REASON_OFFSET + TLS1_AD_UNKNOWN_CA: return "Server did not accept our TLS certificate, likely due to mismatch with server's trust anchor or missing revocation status"; case SSL_AD_REASON_OFFSET + SSL3_AD_HANDSHAKE_FAILURE: return "TLS handshake failure. Possibly the server requires our TLS certificate but did not receive it"; default: return NULL; } } static BIO *http_tls_shutdown(BIO *bio) { if (bio != NULL) { BIO *cbio; const char *hint = tls_error_hint(); if (hint != NULL) BIO_printf(bio_err, "%s\n", hint); (void)ERR_set_mark(); BIO_ssl_shutdown(bio); cbio = BIO_pop(bio); BIO_free(bio); (void)ERR_pop_to_mark(); bio = cbio; } return bio; } BIO *app_http_tls_cb(BIO *bio, void *arg, int connect, int detail) { APP_HTTP_TLS_INFO *info = (APP_HTTP_TLS_INFO *)arg; SSL_CTX *ssl_ctx = info->ssl_ctx; if (ssl_ctx == NULL) return bio; if (connect) { SSL *ssl; BIO *sbio = NULL; X509_STORE *ts = SSL_CTX_get_cert_store(ssl_ctx); X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts); const char *host = vpm == NULL ? NULL : X509_VERIFY_PARAM_get0_host(vpm, 0 ); if ((info->use_proxy && !OSSL_HTTP_proxy_connect(bio, info->server, info->port, NULL, NULL, info->timeout, bio_err, opt_getprog())) || (sbio = BIO_new(BIO_f_ssl())) == NULL) { return NULL; } if ((ssl = SSL_new(ssl_ctx)) == NULL) { BIO_free(sbio); return NULL; } if (vpm != NULL) SSL_set_tlsext_host_name(ssl, host ); SSL_set_connect_state(ssl); BIO_set_ssl(sbio, ssl, BIO_CLOSE); bio = BIO_push(sbio, bio); } else { bio = http_tls_shutdown(bio); } return bio; } void APP_HTTP_TLS_INFO_free(APP_HTTP_TLS_INFO *info) { if (info != NULL) { SSL_CTX_free(info->ssl_ctx); OPENSSL_free(info); } } ASN1_VALUE *app_http_get_asn1(const char *url, const char *proxy, const char *no_proxy, SSL_CTX *ssl_ctx, const STACK_OF(CONF_VALUE) *headers, long timeout, const char *expected_content_type, const ASN1_ITEM *it) { APP_HTTP_TLS_INFO info; char *server; char *port; int use_ssl; BIO *mem; ASN1_VALUE *resp = NULL; if (url == NULL || it == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return NULL; } if (!OSSL_HTTP_parse_url(url, &use_ssl, NULL , &server, &port, NULL , NULL, NULL, NULL)) return NULL; if (use_ssl && ssl_ctx == NULL) { ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER, "missing SSL_CTX"); goto end; } if (!use_ssl && ssl_ctx != NULL) { ERR_raise_data(ERR_LIB_HTTP, ERR_R_PASSED_INVALID_ARGUMENT, "SSL_CTX given but use_ssl == 0"); goto end; } info.server = server; info.port = port; info.use_proxy = OSSL_HTTP_adapt_proxy(proxy, no_proxy, server, use_ssl) != NULL; info.timeout = timeout; info.ssl_ctx = ssl_ctx; mem = OSSL_HTTP_get(url, proxy, no_proxy, NULL , NULL , app_http_tls_cb, &info, 0 , headers, expected_content_type, 1 , OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout); resp = ASN1_item_d2i_bio(it, mem, NULL); BIO_free(mem); end: OPENSSL_free(server); OPENSSL_free(port); return resp; } ASN1_VALUE *app_http_post_asn1(const char *host, const char *port, const char *path, const char *proxy, const char *no_proxy, SSL_CTX *ssl_ctx, const STACK_OF(CONF_VALUE) *headers, const char *content_type, ASN1_VALUE *req, const ASN1_ITEM *req_it, const char *expected_content_type, long timeout, const ASN1_ITEM *rsp_it) { int use_ssl = ssl_ctx != NULL; APP_HTTP_TLS_INFO info; BIO *rsp, *req_mem = ASN1_item_i2d_mem_bio(req_it, req); ASN1_VALUE *res; if (req_mem == NULL) return NULL; info.server = host; info.port = port; info.use_proxy = OSSL_HTTP_adapt_proxy(proxy, no_proxy, host, use_ssl) != NULL; info.timeout = timeout; info.ssl_ctx = ssl_ctx; rsp = OSSL_HTTP_transfer(NULL, host, port, path, use_ssl, proxy, no_proxy, NULL , NULL , app_http_tls_cb, &info, 0 , headers, content_type, req_mem, expected_content_type, 1 , OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout, 0 ); BIO_free(req_mem); res = ASN1_item_d2i_bio(rsp_it, rsp, NULL); BIO_free(rsp); return res; } #endif #if defined(_WIN32) # ifdef fileno # undef fileno # define fileno(a) (int)_fileno(a) # endif # include <windows.h> # include <tchar.h> static int WIN32_rename(const char *from, const char *to) { TCHAR *tfrom = NULL, *tto; DWORD err; int ret = 0; if (sizeof(TCHAR) == 1) { tfrom = (TCHAR *)from; tto = (TCHAR *)to; } else { size_t i, flen = strlen(from) + 1, tlen = strlen(to) + 1; tfrom = malloc(sizeof(*tfrom) * (flen + tlen)); if (tfrom == NULL) goto err; tto = tfrom + flen; # if !defined(_WIN32_WCE) || _WIN32_WCE >= 101 if (!MultiByteToWideChar(CP_ACP, 0, from, flen, (WCHAR *)tfrom, flen)) # endif for (i = 0; i < flen; i++) tfrom[i] = (TCHAR)from[i]; # if !defined(_WIN32_WCE) || _WIN32_WCE >= 101 if (!MultiByteToWideChar(CP_ACP, 0, to, tlen, (WCHAR *)tto, tlen)) # endif for (i = 0; i < tlen; i++) tto[i] = (TCHAR)to[i]; } if (MoveFile(tfrom, tto)) goto ok; err = GetLastError(); if (err == ERROR_ALREADY_EXISTS || err == ERROR_FILE_EXISTS) { if (DeleteFile(tto) && MoveFile(tfrom, tto)) goto ok; err = GetLastError(); } if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) errno = ENOENT; else if (err == ERROR_ACCESS_DENIED) errno = EACCES; else errno = EINVAL; err: ret = -1; ok: if (tfrom != NULL && tfrom != (TCHAR *)from) free(tfrom); return ret; } #endif #if defined(_WIN32) double app_tminterval(int stop, int usertime) { FILETIME now; double ret = 0; static ULARGE_INTEGER tmstart; static int warning = 1; int use_GetSystemTime = 1; # ifdef _WIN32_WINNT static HANDLE proc = NULL; if (proc == NULL) { if (check_winnt()) proc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId()); if (proc == NULL) proc = (HANDLE) - 1; } if (usertime && proc != (HANDLE) - 1) { FILETIME junk; GetProcessTimes(proc, &junk, &junk, &junk, &now); use_GetSystemTime = 0; } # endif if (use_GetSystemTime) { SYSTEMTIME systime; if (usertime && warning) { BIO_printf(bio_err, "To get meaningful results, run " "this program on idle system.\n"); warning = 0; } GetSystemTime(&systime); SystemTimeToFileTime(&systime, &now); } if (stop == TM_START) { tmstart.u.LowPart = now.dwLowDateTime; tmstart.u.HighPart = now.dwHighDateTime; } else { ULARGE_INTEGER tmstop; tmstop.u.LowPart = now.dwLowDateTime; tmstop.u.HighPart = now.dwHighDateTime; ret = (__int64)(tmstop.QuadPart - tmstart.QuadPart) * 1e-7; } return ret; } #elif defined(OPENSSL_SYS_VXWORKS) # include <time.h> double app_tminterval(int stop, int usertime) { double ret = 0; # ifdef CLOCK_REALTIME static struct timespec tmstart; struct timespec now; # else static unsigned long tmstart; unsigned long now; # endif static int warning = 1; if (usertime && warning) { BIO_printf(bio_err, "To get meaningful results, run " "this program on idle system.\n"); warning = 0; } # ifdef CLOCK_REALTIME clock_gettime(CLOCK_REALTIME, &now); if (stop == TM_START) tmstart = now; else ret = ((now.tv_sec + now.tv_nsec * 1e-9) - (tmstart.tv_sec + tmstart.tv_nsec * 1e-9)); # else now = tickGet(); if (stop == TM_START) tmstart = now; else ret = (now - tmstart) / (double)sysClkRateGet(); # endif return ret; } #elif defined(_SC_CLK_TCK) # include <sys/times.h> double app_tminterval(int stop, int usertime) { double ret = 0; struct tms rus; clock_t now = times(&rus); static clock_t tmstart; if (usertime) now = rus.tms_utime; if (stop == TM_START) { tmstart = now; } else { long int tck = sysconf(_SC_CLK_TCK); ret = (now - tmstart) / (double)tck; } return ret; } #else # include <sys/time.h> # include <sys/resource.h> double app_tminterval(int stop, int usertime) { double ret = 0; struct rusage rus; struct timeval now; static struct timeval tmstart; if (usertime) getrusage(RUSAGE_SELF, &rus), now = rus.ru_utime; else gettimeofday(&now, NULL); if (stop == TM_START) tmstart = now; else ret = ((now.tv_sec + now.tv_usec * 1e-6) - (tmstart.tv_sec + tmstart.tv_usec * 1e-6)); return ret; } #endif int app_access(const char *name, int flag) { #ifdef _WIN32 return _access(name, flag); #else return access(name, flag); #endif } int app_isdir(const char *name) { return opt_isdir(name); } #if defined(__VMS) # include "vms_term_sock.h" static int stdin_sock = -1; static void close_stdin_sock(void) { TerminalSocket(TERM_SOCK_DELETE, &stdin_sock); } int fileno_stdin(void) { if (stdin_sock == -1) { TerminalSocket(TERM_SOCK_CREATE, &stdin_sock); atexit(close_stdin_sock); } return stdin_sock; } #else int fileno_stdin(void) { return fileno(stdin); } #endif int fileno_stdout(void) { return fileno(stdout); } #if defined(_WIN32) && defined(STD_INPUT_HANDLE) int raw_read_stdin(void *buf, int siz) { DWORD n; if (ReadFile(GetStdHandle(STD_INPUT_HANDLE), buf, siz, &n, NULL)) return n; else return -1; } #elif defined(__VMS) # include <sys/socket.h> int raw_read_stdin(void *buf, int siz) { return recv(fileno_stdin(), buf, siz, 0); } #else # if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include <floss.h(floss_read)> # endif # endif int raw_read_stdin(void *buf, int siz) { return read(fileno_stdin(), buf, siz); } #endif #if defined(_WIN32) && defined(STD_OUTPUT_HANDLE) int raw_write_stdout(const void *buf, int siz) { DWORD n; if (WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buf, siz, &n, NULL)) return n; else return -1; } #elif defined(OPENSSL_SYS_TANDEM) && defined(OPENSSL_THREADS) \ && defined(_SPT_MODEL_) # if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include <floss.h(floss_write)> # endif # endif int raw_write_stdout(const void *buf, int siz) { return write(fileno(stdout), (void *)buf, siz); } #else # if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include <floss.h(floss_write)> # endif # endif int raw_write_stdout(const void *buf, int siz) { return write(fileno_stdout(), buf, siz); } #endif BIO *dup_bio_in(int format) { return BIO_new_fp(stdin, BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0)); } BIO *dup_bio_out(int format) { BIO *b = BIO_new_fp(stdout, BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0)); void *prefix = NULL; if (b == NULL) return NULL; #ifdef OPENSSL_SYS_VMS if (FMT_istext(format)) b = BIO_push(BIO_new(BIO_f_linebuffer()), b); #endif if (FMT_istext(format) && (prefix = getenv("HARNESS_OSSL_PREFIX")) != NULL) { b = BIO_push(BIO_new(BIO_f_prefix()), b); BIO_set_prefix(b, prefix); } return b; } BIO *dup_bio_err(int format) { BIO *b = BIO_new_fp(stderr, BIO_NOCLOSE | (FMT_istext(format) ? BIO_FP_TEXT : 0)); #ifdef OPENSSL_SYS_VMS if (b != NULL && FMT_istext(format)) b = BIO_push(BIO_new(BIO_f_linebuffer()), b); #endif return b; } void unbuffer(FILE *fp) { #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma environment save # pragma message disable maylosedata2 #endif setbuf(fp, NULL); #if defined(OPENSSL_SYS_VMS) && defined(__DECC) # pragma environment restore #endif } static const char *modestr(char mode, int format) { OPENSSL_assert(mode == 'a' || mode == 'r' || mode == 'w'); switch (mode) { case 'a': return FMT_istext(format) ? "a" : "ab"; case 'r': return FMT_istext(format) ? "r" : "rb"; case 'w': return FMT_istext(format) ? "w" : "wb"; } return NULL; } static const char *modeverb(char mode) { switch (mode) { case 'a': return "appending"; case 'r': return "reading"; case 'w': return "writing"; } return "(doing something)"; } BIO *bio_open_owner(const char *filename, int format, int private) { FILE *fp = NULL; BIO *b = NULL; int textmode, bflags; #ifndef OPENSSL_NO_POSIX_IO int fd = -1, mode; #endif if (!private || filename == NULL || strcmp(filename, "-") == 0) return bio_open_default(filename, 'w', format); textmode = FMT_istext(format); #ifndef OPENSSL_NO_POSIX_IO mode = O_WRONLY; # ifdef O_CREAT mode |= O_CREAT; # endif # ifdef O_TRUNC mode |= O_TRUNC; # endif if (!textmode) { # ifdef O_BINARY mode |= O_BINARY; # elif defined(_O_BINARY) mode |= _O_BINARY; # endif } # ifdef OPENSSL_SYS_VMS if (!textmode) fd = open(filename, mode, 0600, "ctx=bin"); else # endif fd = open(filename, mode, 0600); if (fd < 0) goto err; fp = fdopen(fd, modestr('w', format)); #else fp = fopen(filename, modestr('w', format)); #endif if (fp == NULL) goto err; bflags = BIO_CLOSE; if (textmode) bflags |= BIO_FP_TEXT; b = BIO_new_fp(fp, bflags); if (b != NULL) return b; err: BIO_printf(bio_err, "%s: Can't open \"%s\" for writing, %s\n", opt_getprog(), filename, strerror(errno)); ERR_print_errors(bio_err); if (fp != NULL) fclose(fp); #ifndef OPENSSL_NO_POSIX_IO else if (fd >= 0) close(fd); #endif return NULL; } static BIO *bio_open_default_(const char *filename, char mode, int format, int quiet) { BIO *ret; if (filename == NULL || strcmp(filename, "-") == 0) { ret = mode == 'r' ? dup_bio_in(format) : dup_bio_out(format); if (quiet) { ERR_clear_error(); return ret; } if (ret != NULL) return ret; BIO_printf(bio_err, "Can't open %s, %s\n", mode == 'r' ? "stdin" : "stdout", strerror(errno)); } else { ret = BIO_new_file(filename, modestr(mode, format)); if (quiet) { ERR_clear_error(); return ret; } if (ret != NULL) return ret; BIO_printf(bio_err, "Can't open \"%s\" for %s, %s\n", filename, modeverb(mode), strerror(errno)); } ERR_print_errors(bio_err); return NULL; } BIO *bio_open_default(const char *filename, char mode, int format) { return bio_open_default_(filename, mode, format, 0); } BIO *bio_open_default_quiet(const char *filename, char mode, int format) { return bio_open_default_(filename, mode, format, 1); } void wait_for_async(SSL *s) { #ifndef OPENSSL_SYS_WINDOWS int width = 0; fd_set asyncfds; OSSL_ASYNC_FD *fds; size_t numfds; size_t i; if (!SSL_get_all_async_fds(s, NULL, &numfds)) return; if (numfds == 0) return; fds = app_malloc(sizeof(OSSL_ASYNC_FD) * numfds, "allocate async fds"); if (!SSL_get_all_async_fds(s, fds, &numfds)) { OPENSSL_free(fds); return; } FD_ZERO(&asyncfds); for (i = 0; i < numfds; i++) { if (width <= (int)fds[i]) width = (int)fds[i] + 1; openssl_fdset((int)fds[i], &asyncfds); } select(width, (void *)&asyncfds, NULL, NULL, NULL); OPENSSL_free(fds); #endif } #if defined(OPENSSL_SYS_MSDOS) int has_stdin_waiting(void) { # if defined(OPENSSL_SYS_WINDOWS) HANDLE inhand = GetStdHandle(STD_INPUT_HANDLE); DWORD events = 0; INPUT_RECORD inputrec; DWORD insize = 1; BOOL peeked; if (inhand == INVALID_HANDLE_VALUE) { return 0; } peeked = PeekConsoleInput(inhand, &inputrec, insize, &events); if (!peeked) { if (!feof(stdin)) { return 1; } return 0; } # endif return _kbhit(); } #endif void corrupt_signature(const ASN1_STRING *signature) { unsigned char *s = signature->data; s[signature->length - 1] ^= 0x1; } int set_cert_times(X509 *x, const char *startdate, const char *enddate, int days) { if (startdate == NULL || strcmp(startdate, "today") == 0) { if (X509_gmtime_adj(X509_getm_notBefore(x), 0) == NULL) return 0; } else { if (!ASN1_TIME_set_string_X509(X509_getm_notBefore(x), startdate)) return 0; } if (enddate == NULL) { if (X509_time_adj_ex(X509_getm_notAfter(x), days, 0, NULL) == NULL) return 0; } else if (!ASN1_TIME_set_string_X509(X509_getm_notAfter(x), enddate)) { return 0; } return 1; } int set_crl_lastupdate(X509_CRL *crl, const char *lastupdate) { int ret = 0; ASN1_TIME *tm = ASN1_TIME_new(); if (tm == NULL) goto end; if (lastupdate == NULL) { if (X509_gmtime_adj(tm, 0) == NULL) goto end; } else { if (!ASN1_TIME_set_string_X509(tm, lastupdate)) goto end; } if (!X509_CRL_set1_lastUpdate(crl, tm)) goto end; ret = 1; end: ASN1_TIME_free(tm); return ret; } int set_crl_nextupdate(X509_CRL *crl, const char *nextupdate, long days, long hours, long secs) { int ret = 0; ASN1_TIME *tm = ASN1_TIME_new(); if (tm == NULL) goto end; if (nextupdate == NULL) { if (X509_time_adj_ex(tm, days, hours * 60 * 60 + secs, NULL) == NULL) goto end; } else { if (!ASN1_TIME_set_string_X509(tm, nextupdate)) goto end; } if (!X509_CRL_set1_nextUpdate(crl, tm)) goto end; ret = 1; end: ASN1_TIME_free(tm); return ret; } void make_uppercase(char *string) { int i; for (i = 0; string[i] != '\0'; i++) string[i] = toupper((unsigned char)string[i]); } OSSL_PARAM *app_params_new_from_opts(STACK_OF(OPENSSL_STRING) *opts, const OSSL_PARAM *paramdefs) { OSSL_PARAM *params = NULL; size_t sz = (size_t)sk_OPENSSL_STRING_num(opts); size_t params_n; char *opt = "", *stmp, *vtmp = NULL; int found = 1; if (opts == NULL) return NULL; params = OPENSSL_zalloc(sizeof(OSSL_PARAM) * (sz + 1)); if (params == NULL) return NULL; for (params_n = 0; params_n < sz; params_n++) { opt = sk_OPENSSL_STRING_value(opts, (int)params_n); if ((stmp = OPENSSL_strdup(opt)) == NULL || (vtmp = strchr(stmp, ':')) == NULL) goto err; *vtmp = 0; vtmp++; if (!OSSL_PARAM_allocate_from_text(&params[params_n], paramdefs, stmp, vtmp, strlen(vtmp), &found)) goto err; OPENSSL_free(stmp); } params[params_n] = OSSL_PARAM_construct_end(); return params; err: OPENSSL_free(stmp); BIO_printf(bio_err, "Parameter %s '%s'\n", found ? "error" : "unknown", opt); ERR_print_errors(bio_err); app_params_free(params); return NULL; } void app_params_free(OSSL_PARAM *params) { int i; if (params != NULL) { for (i = 0; params[i].key != NULL; ++i) OPENSSL_free(params[i].data); OPENSSL_free(params); } } EVP_PKEY *app_keygen(EVP_PKEY_CTX *ctx, const char *alg, int bits, int verbose) { EVP_PKEY *res = NULL; if (verbose && alg != NULL) { BIO_printf(bio_err, "Generating %s key", alg); if (bits > 0) BIO_printf(bio_err, " with %d bits\n", bits); else BIO_printf(bio_err, "\n"); } if (!RAND_status()) BIO_printf(bio_err, "Warning: generating random key material may take a long time\n" "if the system has a poor entropy source\n"); if (EVP_PKEY_keygen(ctx, &res) <= 0) BIO_printf(bio_err, "%s: Error generating %s key\n", opt_getprog(), alg != NULL ? alg : "asymmetric"); return res; } EVP_PKEY *app_paramgen(EVP_PKEY_CTX *ctx, const char *alg) { EVP_PKEY *res = NULL; if (!RAND_status()) BIO_printf(bio_err, "Warning: generating random key parameters may take a long time\n" "if the system has a poor entropy source\n"); if (EVP_PKEY_paramgen(ctx, &res) <= 0) BIO_printf(bio_err, "%s: Generating %s key parameters failed\n", opt_getprog(), alg != NULL ? alg : "asymmetric"); return res; } int opt_legacy_okay(void) { int provider_options = opt_provider_option_given(); int libctx = app_get0_libctx() != NULL || app_get0_propq() != NULL; if (provider_options || libctx) return 0; return 1; }
lib
openssl/apps/lib/apps.c
openssl
#define OPENSSL_SUPPRESS_DEPRECATED #include "apps.h" #ifndef OPENSSL_NO_ENGINE # include <stdarg.h> # include <string.h> # include <openssl/engine.h> # include <openssl/store.h> struct ossl_store_loader_ctx_st { ENGINE *e; char *keyid; int expected; int loaded; }; static OSSL_STORE_LOADER_CTX *OSSL_STORE_LOADER_CTX_new(ENGINE *e, char *keyid) { OSSL_STORE_LOADER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx != NULL) { ctx->e = e; ctx->keyid = keyid; } return ctx; } static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx) { if (ctx != NULL) { ENGINE_free(ctx->e); OPENSSL_free(ctx->keyid); OPENSSL_free(ctx); } } static OSSL_STORE_LOADER_CTX *engine_open(const OSSL_STORE_LOADER *loader, const char *uri, const UI_METHOD *ui_method, void *ui_data) { const char *p = uri, *q; ENGINE *e = NULL; char *keyid = NULL; OSSL_STORE_LOADER_CTX *ctx = NULL; if (!CHECK_AND_SKIP_CASE_PREFIX(p, ENGINE_SCHEME_COLON)) return NULL; q = strchr(p, ':'); if (q != NULL && p[0] != ':' && q[1] != '\0') { char engineid[256]; size_t engineid_l = q - p; strncpy(engineid, p, engineid_l); engineid[engineid_l] = '\0'; e = ENGINE_by_id(engineid); keyid = OPENSSL_strdup(q + 1); } if (e != NULL && keyid != NULL) ctx = OSSL_STORE_LOADER_CTX_new(e, keyid); if (ctx == NULL) { OPENSSL_free(keyid); ENGINE_free(e); } return ctx; } static int engine_expect(OSSL_STORE_LOADER_CTX *ctx, int expected) { if (expected == 0 || expected == OSSL_STORE_INFO_PUBKEY || expected == OSSL_STORE_INFO_PKEY) { ctx->expected = expected; return 1; } return 0; } static OSSL_STORE_INFO *engine_load(OSSL_STORE_LOADER_CTX *ctx, const UI_METHOD *ui_method, void *ui_data) { EVP_PKEY *pkey = NULL, *pubkey = NULL; OSSL_STORE_INFO *info = NULL; if (ctx->loaded == 0) { if (ENGINE_init(ctx->e)) { if (ctx->expected == 0 || ctx->expected == OSSL_STORE_INFO_PKEY) pkey = ENGINE_load_private_key(ctx->e, ctx->keyid, (UI_METHOD *)ui_method, ui_data); if ((pkey == NULL && ctx->expected == 0) || ctx->expected == OSSL_STORE_INFO_PUBKEY) pubkey = ENGINE_load_public_key(ctx->e, ctx->keyid, (UI_METHOD *)ui_method, ui_data); ENGINE_finish(ctx->e); } } ctx->loaded = 1; if (pubkey != NULL) info = OSSL_STORE_INFO_new_PUBKEY(pubkey); else if (pkey != NULL) info = OSSL_STORE_INFO_new_PKEY(pkey); if (info == NULL) { EVP_PKEY_free(pkey); EVP_PKEY_free(pubkey); } return info; } static int engine_eof(OSSL_STORE_LOADER_CTX *ctx) { return ctx->loaded != 0; } static int engine_error(OSSL_STORE_LOADER_CTX *ctx) { return 0; } static int engine_close(OSSL_STORE_LOADER_CTX *ctx) { OSSL_STORE_LOADER_CTX_free(ctx); return 1; } int setup_engine_loader(void) { OSSL_STORE_LOADER *loader = NULL; if ((loader = OSSL_STORE_LOADER_new(NULL, ENGINE_SCHEME)) == NULL || !OSSL_STORE_LOADER_set_open(loader, engine_open) || !OSSL_STORE_LOADER_set_expect(loader, engine_expect) || !OSSL_STORE_LOADER_set_load(loader, engine_load) || !OSSL_STORE_LOADER_set_eof(loader, engine_eof) || !OSSL_STORE_LOADER_set_error(loader, engine_error) || !OSSL_STORE_LOADER_set_close(loader, engine_close) || !OSSL_STORE_register_loader(loader)) { OSSL_STORE_LOADER_free(loader); loader = NULL; } return loader != NULL; } void destroy_engine_loader(void) { OSSL_STORE_LOADER *loader = OSSL_STORE_unregister_loader(ENGINE_SCHEME); OSSL_STORE_LOADER_free(loader); } #else int setup_engine_loader(void) { return 0; } void destroy_engine_loader(void) { } #endif
lib
openssl/apps/lib/engine_loader.c
openssl
#include "opt.h" #include <openssl/ui.h> #include "apps_ui.h" int opt_printf_stderr(const char *fmt, ...) { va_list ap; int ret; va_start(ap, fmt); ret = BIO_vprintf(bio_err, fmt, ap); va_end(ap); return ret; }
lib
openssl/apps/lib/apps_opt_printf.c
openssl
#include <string.h> #include "apps.h" #include "function.h" void calculate_columns(FUNCTION *functions, DISPLAY_COLUMNS *dc) { FUNCTION *f; int len, maxlen = 0; for (f = functions; f->name != NULL; ++f) if (f->type == FT_general || f->type == FT_md || f->type == FT_cipher) if ((len = strlen(f->name)) > maxlen) maxlen = len; dc->width = maxlen + 2; dc->columns = (80 - 1) / dc->width; }
lib
openssl/apps/lib/columns.c
openssl
#include <windows.h> #include <stdlib.h> #include <string.h> #include <malloc.h> #if defined(CP_UTF8) static UINT saved_cp; static int newargc; static char **newargv; static void cleanup(void) { int i; SetConsoleOutputCP(saved_cp); for (i = 0; i < newargc; i++) free(newargv[i]); free(newargv); } static int validate_argv(int argc) { static int size = 0; if (argc >= size) { char **ptr; while (argc >= size) size += 64; ptr = realloc(newargv, size * sizeof(newargv[0])); if (ptr == NULL) return 0; (newargv = ptr)[argc] = NULL; } else { newargv[argc] = NULL; } return 1; } static int process_glob(WCHAR *wstr, int wlen) { int i, slash, udlen; WCHAR saved_char; WIN32_FIND_DATAW data; HANDLE h; for (slash = 0, i = 0; i < wlen; i++) if (wstr[i] == L'/' || wstr[i] == L'\\') slash = i + 1; for (i = slash; i < wlen; i++) if (wstr[i] == L'*' || wstr[i] == L'?') break; if (i == wlen) return 0; saved_char = wstr[wlen]; wstr[wlen] = L'\0'; h = FindFirstFileW(wstr, &data); wstr[wlen] = saved_char; if (h == INVALID_HANDLE_VALUE) return 0; if (slash) udlen = WideCharToMultiByte(CP_UTF8, 0, wstr, slash, NULL, 0, NULL, NULL); else udlen = 0; do { int uflen; char *arg; if (data.cFileName[0] == L'.') { if ((data.cFileName[1] == L'\0') || (data.cFileName[1] == L'.' && data.cFileName[2] == L'\0')) continue; } if (!validate_argv(newargc + 1)) break; uflen = WideCharToMultiByte(CP_UTF8, 0, data.cFileName, -1, NULL, 0, NULL, NULL); arg = malloc(udlen + uflen); if (arg == NULL) break; if (udlen) WideCharToMultiByte(CP_UTF8, 0, wstr, slash, arg, udlen, NULL, NULL); WideCharToMultiByte(CP_UTF8, 0, data.cFileName, -1, arg + udlen, uflen, NULL, NULL); newargv[newargc++] = arg; } while (FindNextFileW(h, &data)); CloseHandle(h); return 1; } void win32_utf8argv(int *argc, char **argv[]) { const WCHAR *wcmdline; WCHAR *warg, *wend, *p; int wlen, ulen, valid = 1; char *arg; if (GetEnvironmentVariableW(L"OPENSSL_WIN32_UTF8", NULL, 0) == 0) return; newargc = 0; newargv = NULL; if (!validate_argv(newargc)) return; wcmdline = GetCommandLineW(); if (wcmdline == NULL) return; wlen = wcslen(wcmdline); p = _alloca((wlen + 1) * sizeof(WCHAR)); wcscpy(p, wcmdline); while (*p != L'\0') { int in_quote = 0; if (*p == L' ' || *p == L'\t') { p++; continue; } warg = wend = p; while (*p != L'\0' && (in_quote || (*p != L' ' && *p != L'\t'))) { switch (*p) { case L'\\': { const WCHAR *q = p; int i; while (*p == L'\\') p++; if (*p == L'"') { int i; for (i = (p - q) / 2; i > 0; i--) *wend++ = L'\\'; if ((p - q) % 2 == 1) *wend++ = *p++; } else { for (i = p - q; i > 0; i--) *wend++ = L'\\'; } } break; case L'"': if (in_quote && p[1] == L'"') *wend++ = *p++; else in_quote = !in_quote; p++; break; default: *wend++ = *p++; } } wlen = wend - warg; if (wlen == 0 || !process_glob(warg, wlen)) { if (!validate_argv(newargc + 1)) { valid = 0; break; } ulen = 0; if (wlen > 0) { ulen = WideCharToMultiByte(CP_UTF8, 0, warg, wlen, NULL, 0, NULL, NULL); if (ulen <= 0) continue; } arg = malloc(ulen + 1); if (arg == NULL) { valid = 0; break; } if (wlen > 0) WideCharToMultiByte(CP_UTF8, 0, warg, wlen, arg, ulen, NULL, NULL); arg[ulen] = '\0'; newargv[newargc++] = arg; } } if (valid) { saved_cp = GetConsoleOutputCP(); SetConsoleOutputCP(CP_UTF8); *argc = newargc; *argv = newargv; atexit(cleanup); } else if (newargv != NULL) { int i; for (i = 0; i < newargc; i++) free(newargv[i]); free(newargv); newargc = 0; newargv = NULL; } return; } #else void win32_utf8argv(int *argc, char **argv[]) { return; } #endif
lib
openssl/apps/lib/win32_init.c
openssl
#include <string.h> #include <openssl/bio.h> #include <openssl/safestack.h> #include "names.h" #include "internal/e_os.h" int name_cmp(const char * const *a, const char * const *b) { return OPENSSL_strcasecmp(*a, *b); } void collect_names(const char *name, void *vdata) { STACK_OF(OPENSSL_CSTRING) *names = vdata; sk_OPENSSL_CSTRING_push(names, name); } void print_names(BIO *out, STACK_OF(OPENSSL_CSTRING) *names) { int i = sk_OPENSSL_CSTRING_num(names); int j; sk_OPENSSL_CSTRING_sort(names); if (i > 1) BIO_printf(out, "{ "); for (j = 0; j < i; j++) { const char *name = sk_OPENSSL_CSTRING_value(names, j); if (j > 0) BIO_printf(out, ", "); BIO_printf(out, "%s", name); } if (i > 1) BIO_printf(out, " }"); }
lib
openssl/apps/lib/names.c
openssl
#include "fmt.h" int FMT_istext(int format) { return (format & B_FORMAT_TEXT) == B_FORMAT_TEXT; }
lib
openssl/apps/lib/fmt.c
openssl
#include "apps.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/rand.h> #include <openssl/conf.h> static char *save_rand_file; static STACK_OF(OPENSSL_STRING) *randfiles; void app_RAND_load_conf(CONF *c, const char *section) { const char *randfile = app_conf_try_string(c, section, "RANDFILE"); if (randfile == NULL) return; if (RAND_load_file(randfile, -1) < 0) { BIO_printf(bio_err, "Can't load %s into RNG\n", randfile); ERR_print_errors(bio_err); } if (save_rand_file == NULL) { save_rand_file = OPENSSL_strdup(randfile); if (save_rand_file == NULL) { BIO_printf(bio_err, "Can't duplicate %s\n", randfile); ERR_print_errors(bio_err); } } } static int loadfiles(char *name) { char *p; int last, ret = 1; for (;;) { last = 0; for (p = name; *p != '\0' && *p != LIST_SEPARATOR_CHAR; p++) continue; if (*p == '\0') last = 1; *p = '\0'; if (RAND_load_file(name, -1) < 0) { BIO_printf(bio_err, "Can't load %s into RNG\n", name); ERR_print_errors(bio_err); ret = 0; } if (last) break; name = p + 1; if (*name == '\0') break; } return ret; } int app_RAND_load(void) { char *p; int i, ret = 1; for (i = 0; i < sk_OPENSSL_STRING_num(randfiles); i++) { p = sk_OPENSSL_STRING_value(randfiles, i); if (!loadfiles(p)) ret = 0; } sk_OPENSSL_STRING_free(randfiles); return ret; } int app_RAND_write(void) { int ret = 1; if (save_rand_file == NULL) return 1; if (RAND_write_file(save_rand_file) == -1) { BIO_printf(bio_err, "Cannot write random bytes:\n"); ERR_print_errors(bio_err); ret = 0; } OPENSSL_free(save_rand_file); save_rand_file = NULL; return ret; } enum r_range { OPT_R_ENUM }; int opt_rand(int opt) { switch ((enum r_range)opt) { case OPT_R__FIRST: case OPT_R__LAST: break; case OPT_R_RAND: if (randfiles == NULL && (randfiles = sk_OPENSSL_STRING_new_null()) == NULL) return 0; if (!sk_OPENSSL_STRING_push(randfiles, opt_arg())) return 0; break; case OPT_R_WRITERAND: OPENSSL_free(save_rand_file); save_rand_file = OPENSSL_strdup(opt_arg()); if (save_rand_file == NULL) return 0; break; } return 1; }
lib
openssl/apps/lib/app_rand.c
openssl
#include "apps.h" #include "app_params.h" static int describe_param_type(char *buf, size_t bufsz, const OSSL_PARAM *param) { const char *type_mod = ""; const char *type = NULL; int show_type_number = 0; int printed_len; switch (param->data_type) { case OSSL_PARAM_UNSIGNED_INTEGER: type_mod = "unsigned "; case OSSL_PARAM_INTEGER: type = "integer"; break; case OSSL_PARAM_UTF8_PTR: type_mod = "pointer to a "; case OSSL_PARAM_UTF8_STRING: type = "UTF8 encoded string"; break; case OSSL_PARAM_OCTET_PTR: type_mod = "pointer to an "; case OSSL_PARAM_OCTET_STRING: type = "octet string"; break; default: type = "unknown type"; show_type_number = 1; break; } printed_len = BIO_snprintf(buf, bufsz, "%s: ", param->key); if (printed_len > 0) { buf += printed_len; bufsz -= printed_len; } printed_len = BIO_snprintf(buf, bufsz, "%s%s", type_mod, type); if (printed_len > 0) { buf += printed_len; bufsz -= printed_len; } if (show_type_number) { printed_len = BIO_snprintf(buf, bufsz, " [%d]", param->data_type); if (printed_len > 0) { buf += printed_len; bufsz -= printed_len; } } if (param->data_size == 0) printed_len = BIO_snprintf(buf, bufsz, " (arbitrary size)"); else printed_len = BIO_snprintf(buf, bufsz, " (max %zu bytes large)", param->data_size); if (printed_len > 0) { buf += printed_len; bufsz -= printed_len; } *buf = '\0'; return 1; } int print_param_types(const char *thing, const OSSL_PARAM *pdefs, int indent) { if (pdefs == NULL) { return 1; } else if (pdefs->key == NULL) { BIO_printf(bio_out, "%*sEmpty list of %s (!!!)\n", indent, "", thing); } else { BIO_printf(bio_out, "%*s%s:\n", indent, "", thing); for (; pdefs->key != NULL; pdefs++) { char buf[200]; describe_param_type(buf, sizeof(buf), pdefs); BIO_printf(bio_out, "%*s %s\n", indent, "", buf); } } return 1; } void print_param_value(const OSSL_PARAM *p, int indent) { int64_t i; uint64_t u; printf("%*s%s: ", indent, "", p->key); switch (p->data_type) { case OSSL_PARAM_UNSIGNED_INTEGER: if (OSSL_PARAM_get_uint64(p, &u)) BIO_printf(bio_out, "%llu\n", (unsigned long long int)u); else BIO_printf(bio_out, "error getting value\n"); break; case OSSL_PARAM_INTEGER: if (OSSL_PARAM_get_int64(p, &i)) BIO_printf(bio_out, "%lld\n", (long long int)i); else BIO_printf(bio_out, "error getting value\n"); break; case OSSL_PARAM_UTF8_PTR: BIO_printf(bio_out, "'%s'\n", *(char **)(p->data)); break; case OSSL_PARAM_UTF8_STRING: BIO_printf(bio_out, "'%s'\n", (char *)p->data); break; case OSSL_PARAM_OCTET_PTR: case OSSL_PARAM_OCTET_STRING: BIO_printf(bio_out, "<%zu bytes>\n", p->data_size); break; default: BIO_printf(bio_out, "unknown type (%u) of %zu bytes\n", p->data_type, p->data_size); break; } }
lib
openssl/apps/lib/app_params.c
openssl
#include "apps.h" #include <string.h> #include <openssl/err.h> #include <openssl/provider.h> #include <openssl/safestack.h> static int provider_option_given = 0; DEFINE_STACK_OF(OSSL_PROVIDER) enum prov_range { OPT_PROV_ENUM }; static STACK_OF(OSSL_PROVIDER) *app_providers = NULL; static void provider_free(OSSL_PROVIDER *prov) { OSSL_PROVIDER_unload(prov); } int app_provider_load(OSSL_LIB_CTX *libctx, const char *provider_name) { OSSL_PROVIDER *prov; prov = OSSL_PROVIDER_load(libctx, provider_name); if (prov == NULL) { opt_printf_stderr("%s: unable to load provider %s\n" "Hint: use -provider-path option or OPENSSL_MODULES environment variable.\n", opt_getprog(), provider_name); ERR_print_errors(bio_err); return 0; } if (app_providers == NULL) app_providers = sk_OSSL_PROVIDER_new_null(); if (app_providers == NULL || !sk_OSSL_PROVIDER_push(app_providers, prov)) { app_providers_cleanup(); return 0; } return 1; } void app_providers_cleanup(void) { sk_OSSL_PROVIDER_pop_free(app_providers, provider_free); app_providers = NULL; } static int opt_provider_path(const char *path) { if (path != NULL && *path == '\0') path = NULL; return OSSL_PROVIDER_set_default_search_path(app_get0_libctx(), path); } int opt_provider(int opt) { const int given = provider_option_given; provider_option_given = 1; switch ((enum prov_range)opt) { case OPT_PROV__FIRST: case OPT_PROV__LAST: return 1; case OPT_PROV_PROVIDER: return app_provider_load(app_get0_libctx(), opt_arg()); case OPT_PROV_PROVIDER_PATH: return opt_provider_path(opt_arg()); case OPT_PROV_PROPQUERY: return app_set_propq(opt_arg()); } provider_option_given = given; return 0; } int opt_provider_option_given(void) { return provider_option_given; }
lib
openssl/apps/lib/app_provider.c
openssl
#include <string.h> #include "apps.h" #ifdef EVP_PKEY_CTRL_SET1_ID static ASN1_OCTET_STRING *mk_octet_string(void *value, size_t value_n) { ASN1_OCTET_STRING *v = ASN1_OCTET_STRING_new(); if (v == NULL) { BIO_printf(bio_err, "error: allocation failed\n"); } else if (!ASN1_OCTET_STRING_set(v, value, (int)value_n)) { ASN1_OCTET_STRING_free(v); v = NULL; } return v; } #endif static int x509_ctrl(void *object, int cmd, void *value, size_t value_n) { switch (cmd) { #ifdef EVP_PKEY_CTRL_SET1_ID case EVP_PKEY_CTRL_SET1_ID: { ASN1_OCTET_STRING *v = mk_octet_string(value, value_n); if (v == NULL) { BIO_printf(bio_err, "error: setting distinguishing ID in certificate failed\n"); return 0; } X509_set0_distinguishing_id(object, v); return 1; } #endif default: break; } return -2; } static int x509_req_ctrl(void *object, int cmd, void *value, size_t value_n) { switch (cmd) { #ifdef EVP_PKEY_CTRL_SET1_ID case EVP_PKEY_CTRL_SET1_ID: { ASN1_OCTET_STRING *v = mk_octet_string(value, value_n); if (v == NULL) { BIO_printf(bio_err, "error: setting distinguishing ID in certificate signing request failed\n"); return 0; } X509_REQ_set0_distinguishing_id(object, v); return 1; } #endif default: break; } return -2; } static int do_x509_ctrl_string(int (*ctrl)(void *object, int cmd, void *value, size_t value_n), void *object, const char *value) { int rv = 0; char *stmp, *vtmp = NULL; size_t vtmp_len = 0; int cmd = 0; stmp = OPENSSL_strdup(value); if (stmp == NULL) return -1; vtmp = strchr(stmp, ':'); if (vtmp != NULL) { *vtmp = 0; vtmp++; vtmp_len = strlen(vtmp); } if (strcmp(stmp, "distid") == 0) { #ifdef EVP_PKEY_CTRL_SET1_ID cmd = EVP_PKEY_CTRL_SET1_ID; #endif } else if (strcmp(stmp, "hexdistid") == 0) { if (vtmp != NULL) { void *hexid; long hexid_len = 0; hexid = OPENSSL_hexstr2buf((const char *)vtmp, &hexid_len); OPENSSL_free(stmp); stmp = vtmp = hexid; vtmp_len = (size_t)hexid_len; } #ifdef EVP_PKEY_CTRL_SET1_ID cmd = EVP_PKEY_CTRL_SET1_ID; #endif } rv = ctrl(object, cmd, vtmp, vtmp_len); OPENSSL_free(stmp); return rv; } int x509_ctrl_string(X509 *x, const char *value) { return do_x509_ctrl_string(x509_ctrl, x, value); } int x509_req_ctrl_string(X509_REQ *x, const char *value) { return do_x509_ctrl_string(x509_req_ctrl, x, value); }
lib
openssl/apps/lib/app_x509.c
openssl
#include <openssl/trace.h> #include "apps.h" #include "log.h" static int verbosity = LOG_INFO; int log_set_verbosity(const char *prog, int level) { if (level < LOG_EMERG || level > LOG_TRACE) { trace_log_message(-1, prog, LOG_ERR, "Invalid verbosity level %d", level); return 0; } verbosity = level; return 1; } int log_get_verbosity(void) { return verbosity; } #ifdef HTTP_DAEMON static int print_syslog(const char *str, size_t len, void *levPtr) { int level = *(int *)levPtr; int ilen = len > MAXERRLEN ? MAXERRLEN : len; syslog(level, "%.*s", ilen, str); return ilen; } #endif static void log_with_prefix(const char *prog, const char *fmt, va_list ap) { char prefix[80]; BIO *bio, *pre = BIO_new(BIO_f_prefix()); (void)BIO_snprintf(prefix, sizeof(prefix), "%s: ", prog); (void)BIO_set_prefix(pre, prefix); bio = BIO_push(pre, bio_err); (void)BIO_vprintf(bio, fmt, ap); (void)BIO_printf(bio, "\n"); (void)BIO_flush(bio); (void)BIO_pop(pre); BIO_free(pre); } #undef OSSL_NO_C99 #if !defined(__STDC_VERSION__) || __STDC_VERSION__ + 0 < 199900L # define OSSL_NO_C99 #endif void trace_log_message(int category, const char *prog, int level, const char *fmt, ...) { va_list ap; va_start(ap, fmt); #ifdef OSSL_NO_C99 if (verbosity >= level) category = -1; #endif if (category >= 0 && OSSL_trace_enabled(category)) { BIO *out = OSSL_trace_begin(category); #ifndef OSSL_NO_C99 va_list ap_copy; va_copy(ap_copy, ap); (void)BIO_vprintf(out, fmt, ap_copy); va_end(ap_copy); #else (void)BIO_vprintf(out, fmt, ap); #endif (void)BIO_printf(out, "\n"); OSSL_trace_end(category, out); } if (verbosity < level) { va_end(ap); return; } #ifdef HTTP_DAEMON if (n_responders != 0) { vsyslog(level, fmt, ap); if (level <= LOG_ERR) ERR_print_errors_cb(print_syslog, &level); } else #endif log_with_prefix(prog, fmt, ap); va_end(ap); }
lib
openssl/apps/lib/log.c
openssl
#define OPENSSL_SUPPRESS_DEPRECATED #include <string.h> #include <openssl/types.h> #include <openssl/err.h> #ifndef OPENSSL_NO_ENGINE # include <openssl/engine.h> #endif #include "apps.h" #ifndef OPENSSL_NO_ENGINE static ENGINE *try_load_engine(const char *engine) { ENGINE *e = NULL; if ((e = ENGINE_by_id("dynamic")) != NULL) { if (!ENGINE_ctrl_cmd_string(e, "SO_PATH", engine, 0) || !ENGINE_ctrl_cmd_string(e, "LOAD", NULL, 0)) { ENGINE_free(e); e = NULL; } } return e; } #endif ENGINE *setup_engine_methods(const char *id, unsigned int methods, int debug) { ENGINE *e = NULL; #ifndef OPENSSL_NO_ENGINE if (id != NULL) { if (strcmp(id, "auto") == 0) { BIO_printf(bio_err, "Enabling auto ENGINE support\n"); ENGINE_register_all_complete(); return NULL; } if ((e = ENGINE_by_id(id)) == NULL && (e = try_load_engine(id)) == NULL) { BIO_printf(bio_err, "Invalid engine \"%s\"\n", id); ERR_print_errors(bio_err); return NULL; } if (debug) (void)ENGINE_ctrl(e, ENGINE_CTRL_SET_LOGSTREAM, 0, bio_err, 0); if (!ENGINE_ctrl_cmd(e, "SET_USER_INTERFACE", 0, (void *)get_ui_method(), 0, 1) || !ENGINE_set_default(e, methods)) { BIO_printf(bio_err, "Cannot use engine \"%s\"\n", ENGINE_get_id(e)); ERR_print_errors(bio_err); ENGINE_free(e); return NULL; } BIO_printf(bio_err, "Engine \"%s\" set.\n", ENGINE_get_id(e)); } #endif return e; } void release_engine(ENGINE *e) { #ifndef OPENSSL_NO_ENGINE ENGINE_free(e); #endif } int init_engine(ENGINE *e) { int rv = 1; #ifndef OPENSSL_NO_ENGINE rv = ENGINE_init(e); #endif return rv; } int finish_engine(ENGINE *e) { int rv = 1; #ifndef OPENSSL_NO_ENGINE rv = ENGINE_finish(e); #endif return rv; } char *make_engine_uri(ENGINE *e, const char *key_id, const char *desc) { char *new_uri = NULL; #ifndef OPENSSL_NO_ENGINE if (e == NULL) { BIO_printf(bio_err, "No engine specified for loading %s\n", desc); } else if (key_id == NULL) { BIO_printf(bio_err, "No engine key id specified for loading %s\n", desc); } else { const char *engineid = ENGINE_get_id(e); size_t uri_sz = sizeof(ENGINE_SCHEME_COLON) - 1 + strlen(engineid) + 1 + strlen(key_id) + 1 ; new_uri = OPENSSL_malloc(uri_sz); if (new_uri != NULL) { OPENSSL_strlcpy(new_uri, ENGINE_SCHEME_COLON, uri_sz); OPENSSL_strlcat(new_uri, engineid, uri_sz); OPENSSL_strlcat(new_uri, ":", uri_sz); OPENSSL_strlcat(new_uri, key_id, uri_sz); } } #else BIO_printf(bio_err, "Engines not supported for loading %s\n", desc); #endif return new_uri; } int get_legacy_pkey_id(OSSL_LIB_CTX *libctx, const char *algname, ENGINE *e) { const EVP_PKEY_ASN1_METHOD *ameth; ENGINE *tmpeng = NULL; int pkey_id = NID_undef; ERR_set_mark(); ameth = EVP_PKEY_asn1_find_str(&tmpeng, algname, -1); #if !defined(OPENSSL_NO_ENGINE) ENGINE_finish(tmpeng); if (ameth == NULL && e != NULL) ameth = ENGINE_get_pkey_asn1_meth_str(e, algname, -1); else #endif if (tmpeng == NULL) ameth = NULL; ERR_pop_to_mark(); if (ameth == NULL) return NID_undef; EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL, ameth); return pkey_id; } const EVP_MD *get_digest_from_engine(const char *name) { #ifndef OPENSSL_NO_ENGINE ENGINE *eng; eng = ENGINE_get_digest_engine(OBJ_sn2nid(name)); if (eng != NULL) { ENGINE_finish(eng); return EVP_get_digestbyname(name); } #endif return NULL; } const EVP_CIPHER *get_cipher_from_engine(const char *name) { #ifndef OPENSSL_NO_ENGINE ENGINE *eng; eng = ENGINE_get_cipher_engine(OBJ_sn2nid(name)); if (eng != NULL) { ENGINE_finish(eng); return EVP_get_cipherbyname(name); } #endif return NULL; }
lib
openssl/apps/lib/engine.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <signal.h> #include <openssl/opensslconf.h> #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__U_INT) # define __U_INT typedef unsigned int u_int; #endif #ifdef _WIN32 # include <process.h> # ifdef _MSC_VER # define getpid _getpid # endif #endif #ifndef OPENSSL_NO_SOCK # include "apps.h" # include "s_apps.h" # include "internal/sockets.h" # if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include <floss.h(floss_read)> # endif # endif # include <openssl/bio.h> # include <openssl/err.h> BIO_ADDR *ourpeer = NULL; int init_client(int *sock, const char *host, const char *port, const char *bindhost, const char *bindport, int family, int type, int protocol, int tfo, int doconn, BIO_ADDR **ba_ret) { BIO_ADDRINFO *res = NULL; BIO_ADDRINFO *bindaddr = NULL; const BIO_ADDRINFO *ai = NULL; const BIO_ADDRINFO *bi = NULL; int found = 0; int ret; int options = 0; if (tfo && ba_ret != NULL) *ba_ret = NULL; if (BIO_sock_init() != 1) return 0; ret = BIO_lookup_ex(host, port, BIO_LOOKUP_CLIENT, family, type, protocol, &res); if (ret == 0) { ERR_print_errors(bio_err); return 0; } if (bindhost != NULL || bindport != NULL) { ret = BIO_lookup_ex(bindhost, bindport, BIO_LOOKUP_CLIENT, family, type, protocol, &bindaddr); if (ret == 0) { ERR_print_errors (bio_err); goto out; } } ret = 0; for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) { OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(ai)) && (type == 0 || type == BIO_ADDRINFO_socktype(ai)) && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(ai))); if (bindaddr != NULL) { for (bi = bindaddr; bi != NULL; bi = BIO_ADDRINFO_next(bi)) { if (BIO_ADDRINFO_family(bi) == BIO_ADDRINFO_family(ai)) break; } if (bi == NULL) continue; ++found; } *sock = BIO_socket(BIO_ADDRINFO_family(ai), BIO_ADDRINFO_socktype(ai), BIO_ADDRINFO_protocol(ai), 0); if (*sock == INVALID_SOCKET) { continue; } if (bi != NULL) { if (!BIO_bind(*sock, BIO_ADDRINFO_address(bi), BIO_SOCK_REUSEADDR)) { BIO_closesocket(*sock); *sock = INVALID_SOCKET; break; } } #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP) { BIO *tmpbio = BIO_new_dgram_sctp(*sock, BIO_NOCLOSE); if (tmpbio == NULL) { ERR_print_errors(bio_err); return 0; } BIO_free(tmpbio); } #endif if (BIO_ADDRINFO_protocol(ai) == IPPROTO_TCP) { options |= BIO_SOCK_NODELAY; if (tfo) options |= BIO_SOCK_TFO; } if (doconn && !BIO_connect(*sock, BIO_ADDRINFO_address(ai), options)) { BIO_closesocket(*sock); *sock = INVALID_SOCKET; continue; } if (tfo || !doconn) *ba_ret = BIO_ADDR_dup(BIO_ADDRINFO_address(ai)); break; } if (*sock == INVALID_SOCKET) { if (bindaddr != NULL && !found) { BIO_printf(bio_err, "Can't bind %saddress for %s%s%s\n", #ifdef AF_INET6 BIO_ADDRINFO_family(res) == AF_INET6 ? "IPv6 " : #endif BIO_ADDRINFO_family(res) == AF_INET ? "IPv4 " : BIO_ADDRINFO_family(res) == AF_UNIX ? "unix " : "", bindhost != NULL ? bindhost : "", bindport != NULL ? ":" : "", bindport != NULL ? bindport : ""); ERR_clear_error(); ret = 0; } ERR_print_errors(bio_err); } else { char *hostname = NULL; hostname = BIO_ADDR_hostname_string(BIO_ADDRINFO_address(ai), 1); if (hostname != NULL) { BIO_printf(bio_err, "Connecting to %s\n", hostname); OPENSSL_free(hostname); } ERR_clear_error(); ret = 1; } out: if (bindaddr != NULL) { BIO_ADDRINFO_free (bindaddr); } BIO_ADDRINFO_free(res); return ret; } void get_sock_info_address(int asock, char **hostname, char **service) { union BIO_sock_info_u info; if (hostname != NULL) *hostname = NULL; if (service != NULL) *service = NULL; if ((info.addr = BIO_ADDR_new()) != NULL && BIO_sock_info(asock, BIO_SOCK_INFO_ADDRESS, &info)) { if (hostname != NULL) *hostname = BIO_ADDR_hostname_string(info.addr, 1); if (service != NULL) *service = BIO_ADDR_service_string(info.addr, 1); } BIO_ADDR_free(info.addr); } int report_server_accept(BIO *out, int asock, int with_address, int with_pid) { int success = 1; if (BIO_printf(out, "ACCEPT") <= 0) return 0; if (with_address) { char *hostname, *service; get_sock_info_address(asock, &hostname, &service); success = hostname != NULL && service != NULL; if (success) success = BIO_printf(out, strchr(hostname, ':') == NULL ? " %s:%s" : " [%s]:%s", hostname, service) > 0; else (void)BIO_printf(out, "unknown:error\n"); OPENSSL_free(hostname); OPENSSL_free(service); } if (with_pid) success *= BIO_printf(out, " PID=%d", getpid()) > 0; success *= BIO_printf(out, "\n") > 0; (void)BIO_flush(out); return success; } int do_server(int *accept_sock, const char *host, const char *port, int family, int type, int protocol, do_server_cb cb, unsigned char *context, int naccept, BIO *bio_s_out, int tfo) { int asock = 0; int sock; int i; BIO_ADDRINFO *res = NULL; const BIO_ADDRINFO *next; int sock_family, sock_type, sock_protocol, sock_port; const BIO_ADDR *sock_address; int sock_family_fallback = AF_UNSPEC; const BIO_ADDR *sock_address_fallback = NULL; int sock_options = BIO_SOCK_REUSEADDR; int ret = 0; if (BIO_sock_init() != 1) return 0; if (!BIO_lookup_ex(host, port, BIO_LOOKUP_SERVER, family, type, protocol, &res)) { ERR_print_errors(bio_err); return 0; } OPENSSL_assert((family == AF_UNSPEC || family == BIO_ADDRINFO_family(res)) && (type == 0 || type == BIO_ADDRINFO_socktype(res)) && (protocol == 0 || protocol == BIO_ADDRINFO_protocol(res))); sock_family = BIO_ADDRINFO_family(res); sock_type = BIO_ADDRINFO_socktype(res); sock_protocol = BIO_ADDRINFO_protocol(res); sock_address = BIO_ADDRINFO_address(res); next = BIO_ADDRINFO_next(res); if (tfo && sock_type == SOCK_STREAM) sock_options |= BIO_SOCK_TFO; #ifdef AF_INET6 if (sock_family == AF_INET6) sock_options |= BIO_SOCK_V6_ONLY; if (next != NULL && BIO_ADDRINFO_socktype(next) == sock_type && BIO_ADDRINFO_protocol(next) == sock_protocol) { if (sock_family == AF_INET && BIO_ADDRINFO_family(next) == AF_INET6) { sock_family_fallback = sock_family; sock_address_fallback = sock_address; sock_family = AF_INET6; sock_address = BIO_ADDRINFO_address(next); } else if (sock_family == AF_INET6 && BIO_ADDRINFO_family(next) == AF_INET) { sock_options &= ~BIO_SOCK_V6_ONLY; } } #endif asock = BIO_socket(sock_family, sock_type, sock_protocol, 0); if (asock == INVALID_SOCKET && sock_family_fallback != AF_UNSPEC) { asock = BIO_socket(sock_family_fallback, sock_type, sock_protocol, 0); sock_address = sock_address_fallback; } if (asock == INVALID_SOCKET || !BIO_listen(asock, sock_address, sock_options)) { BIO_ADDRINFO_free(res); ERR_print_errors(bio_err); if (asock != INVALID_SOCKET) BIO_closesocket(asock); goto end; } #ifndef OPENSSL_NO_SCTP if (protocol == IPPROTO_SCTP) { BIO *tmpbio = BIO_new_dgram_sctp(asock, BIO_NOCLOSE); if (tmpbio == NULL) { BIO_closesocket(asock); ERR_print_errors(bio_err); goto end; } BIO_free(tmpbio); } #endif sock_port = BIO_ADDR_rawport(sock_address); BIO_ADDRINFO_free(res); res = NULL; if (!report_server_accept(bio_s_out, asock, sock_port == 0, 0)) { BIO_closesocket(asock); ERR_print_errors(bio_err); goto end; } if (accept_sock != NULL) *accept_sock = asock; for (;;) { char sink[64]; struct timeval timeout; fd_set readfds; if (type == SOCK_STREAM) { BIO_ADDR_free(ourpeer); ourpeer = BIO_ADDR_new(); if (ourpeer == NULL) { BIO_closesocket(asock); ERR_print_errors(bio_err); goto end; } do { sock = BIO_accept_ex(asock, ourpeer, 0); } while (sock < 0 && BIO_sock_should_retry(sock)); if (sock < 0) { ERR_print_errors(bio_err); BIO_closesocket(asock); break; } BIO_set_tcp_ndelay(sock, 1); i = (*cb)(sock, type, protocol, context); shutdown(sock, 1); timeout.tv_sec = 0; timeout.tv_usec = 500000; do { FD_ZERO(&readfds); openssl_fdset(sock, &readfds); } while (select(sock + 1, &readfds, NULL, NULL, &timeout) > 0 && readsocket(sock, sink, sizeof(sink)) > 0); BIO_closesocket(sock); } else { i = (*cb)(asock, type, protocol, context); } if (naccept != -1) naccept--; if (i < 0 || naccept == 0) { BIO_closesocket(asock); ret = i; break; } } end: # ifdef AF_UNIX if (family == AF_UNIX) unlink(host); # endif BIO_ADDR_free(ourpeer); ourpeer = NULL; return ret; } void do_ssl_shutdown(SSL *ssl) { int ret; do { ret = SSL_shutdown(ssl); if (ret < 0) { switch (SSL_get_error(ssl, ret)) { case SSL_ERROR_WANT_READ: case SSL_ERROR_WANT_WRITE: case SSL_ERROR_WANT_ASYNC: case SSL_ERROR_WANT_ASYNC_JOB: continue; } ret = 0; } } while (ret < 0); } #endif
lib
openssl/apps/lib/s_socket.c
openssl
#define OPENSSL_SUPPRESS_DEPRECATED #include <openssl/bn.h> #include <openssl/bio.h> #include <openssl/ssl.h> #include <openssl/srp.h> #include "apps_ui.h" #include "apps.h" #include "s_apps.h" static int srp_Verify_N_and_g(const BIGNUM *N, const BIGNUM *g) { BN_CTX *bn_ctx = BN_CTX_new(); BIGNUM *p = BN_new(); BIGNUM *r = BN_new(); int ret = g != NULL && N != NULL && bn_ctx != NULL && BN_is_odd(N) && BN_check_prime(N, bn_ctx, NULL) == 1 && p != NULL && BN_rshift1(p, N) && BN_check_prime(p, bn_ctx, NULL) == 1 && r != NULL && BN_mod_exp(r, g, p, N, bn_ctx) && BN_add_word(r, 1) && BN_cmp(r, N) == 0; BN_free(r); BN_free(p); BN_CTX_free(bn_ctx); return ret; } static int ssl_srp_verify_param_cb(SSL *s, void *arg) { SRP_ARG *srp_arg = (SRP_ARG *)arg; BIGNUM *N = NULL, *g = NULL; if (((N = SSL_get_srp_N(s)) == NULL) || ((g = SSL_get_srp_g(s)) == NULL)) return 0; if (srp_arg->debug || srp_arg->msg || srp_arg->amp == 1) { BIO_printf(bio_err, "SRP parameters:\n"); BIO_printf(bio_err, "\tN="); BN_print(bio_err, N); BIO_printf(bio_err, "\n\tg="); BN_print(bio_err, g); BIO_printf(bio_err, "\n"); } if (SRP_check_known_gN_param(g, N)) return 1; if (srp_arg->amp == 1) { if (srp_arg->debug) BIO_printf(bio_err, "SRP param N and g are not known params, going to check deeper.\n"); if (BN_num_bits(g) <= BN_BITS && srp_Verify_N_and_g(N, g)) return 1; } BIO_printf(bio_err, "SRP param N and g rejected.\n"); return 0; } #define PWD_STRLEN 1024 static char *ssl_give_srp_client_pwd_cb(SSL *s, void *arg) { SRP_ARG *srp_arg = (SRP_ARG *)arg; char *pass = app_malloc(PWD_STRLEN + 1, "SRP password buffer"); PW_CB_DATA cb_tmp; int l; cb_tmp.password = (char *)srp_arg->srppassin; cb_tmp.prompt_info = "SRP user"; if ((l = password_callback(pass, PWD_STRLEN, 0, &cb_tmp)) < 0) { BIO_printf(bio_err, "Can't read Password\n"); OPENSSL_free(pass); return NULL; } *(pass + l) = '\0'; return pass; } int set_up_srp_arg(SSL_CTX *ctx, SRP_ARG *srp_arg, int srp_lateuser, int c_msg, int c_debug) { if (!srp_lateuser && !SSL_CTX_set_srp_username(ctx, srp_arg->srplogin)) { BIO_printf(bio_err, "Unable to set SRP username\n"); return 0; } srp_arg->msg = c_msg; srp_arg->debug = c_debug; SSL_CTX_set_srp_cb_arg(ctx, &srp_arg); SSL_CTX_set_srp_client_pwd_callback(ctx, ssl_give_srp_client_pwd_cb); SSL_CTX_set_srp_strength(ctx, srp_arg->strength); if (c_msg || c_debug || srp_arg->amp == 0) SSL_CTX_set_srp_verify_param_callback(ctx, ssl_srp_verify_param_cb); return 1; } static char *dummy_srp(SSL *ssl, void *arg) { return ""; } void set_up_dummy_srp(SSL_CTX *ctx) { SSL_CTX_set_srp_client_pwd_callback(ctx, dummy_srp); } static int ssl_srp_server_param_cb(SSL *s, int *ad, void *arg) { srpsrvparm *p = (srpsrvparm *) arg; int ret = SSL3_AL_FATAL; if (p->login == NULL && p->user == NULL) { p->login = SSL_get_srp_username(s); BIO_printf(bio_err, "SRP username = \"%s\"\n", p->login); return -1; } if (p->user == NULL) { BIO_printf(bio_err, "User %s doesn't exist\n", p->login); goto err; } if (SSL_set_srp_server_param (s, p->user->N, p->user->g, p->user->s, p->user->v, p->user->info) < 0) { *ad = SSL_AD_INTERNAL_ERROR; goto err; } BIO_printf(bio_err, "SRP parameters set: username = \"%s\" info=\"%s\" \n", p->login, p->user->info); ret = SSL_ERROR_NONE; err: SRP_user_pwd_free(p->user); p->user = NULL; p->login = NULL; return ret; } int set_up_srp_verifier_file(SSL_CTX *ctx, srpsrvparm *srp_callback_parm, char *srpuserseed, char *srp_verifier_file) { int ret; srp_callback_parm->vb = SRP_VBASE_new(srpuserseed); srp_callback_parm->user = NULL; srp_callback_parm->login = NULL; if (srp_callback_parm->vb == NULL) { BIO_printf(bio_err, "Failed to initialize SRP verifier file \n"); return 0; } if ((ret = SRP_VBASE_init(srp_callback_parm->vb, srp_verifier_file)) != SRP_NO_ERROR) { BIO_printf(bio_err, "Cannot initialize SRP verifier file \"%s\":ret=%d\n", srp_verifier_file, ret); return 0; } SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, verify_callback); SSL_CTX_set_srp_cb_arg(ctx, &srp_callback_parm); SSL_CTX_set_srp_username_callback(ctx, ssl_srp_server_param_cb); return 1; } void lookup_srp_user(srpsrvparm *srp_callback_parm, BIO *bio_s_out) { SRP_user_pwd_free(srp_callback_parm->user); srp_callback_parm->user = SRP_VBASE_get1_by_user(srp_callback_parm->vb, srp_callback_parm->login); if (srp_callback_parm->user != NULL) BIO_printf(bio_s_out, "LOOKUP done %s\n", srp_callback_parm->user->info); else BIO_printf(bio_s_out, "LOOKUP not successful\n"); }
lib
openssl/apps/lib/tlssrp_depr.c
openssl
#include <string.h> #include <openssl/err.h> #include <openssl/ui.h> #include "apps_ui.h" static UI_METHOD *ui_method = NULL; static const UI_METHOD *ui_base_method = NULL; static int ui_open(UI *ui) { int (*opener)(UI *ui) = UI_method_get_opener(ui_base_method); if (opener != NULL) return opener(ui); return 1; } static int ui_read(UI *ui, UI_STRING *uis) { int (*reader)(UI *ui, UI_STRING *uis) = NULL; if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD && UI_get0_user_data(ui)) { switch (UI_get_string_type(uis)) { case UIT_PROMPT: case UIT_VERIFY: { const char *password = ((PW_CB_DATA *)UI_get0_user_data(ui))->password; if (password != NULL) { UI_set_result(ui, uis, password); return 1; } } break; case UIT_NONE: case UIT_BOOLEAN: case UIT_INFO: case UIT_ERROR: break; } } reader = UI_method_get_reader(ui_base_method); if (reader != NULL) return reader(ui, uis); UI_set_result(ui, uis, ""); return 1; } static int ui_write(UI *ui, UI_STRING *uis) { int (*writer)(UI *ui, UI_STRING *uis) = NULL; if (UI_get_input_flags(uis) & UI_INPUT_FLAG_DEFAULT_PWD && UI_get0_user_data(ui)) { switch (UI_get_string_type(uis)) { case UIT_PROMPT: case UIT_VERIFY: { const char *password = ((PW_CB_DATA *)UI_get0_user_data(ui))->password; if (password != NULL) return 1; } break; case UIT_NONE: case UIT_BOOLEAN: case UIT_INFO: case UIT_ERROR: break; } } writer = UI_method_get_writer(ui_base_method); if (writer != NULL) return writer(ui, uis); return 1; } static int ui_close(UI *ui) { int (*closer)(UI *ui) = UI_method_get_closer(ui_base_method); if (closer != NULL) return closer(ui); return 1; } static char *ui_prompt_construct(UI *ui, const char *phrase_desc, const char *object_name) { PW_CB_DATA *cb_data = (PW_CB_DATA *)UI_get0_user_data(ui); if (phrase_desc == NULL) phrase_desc = "pass phrase"; if (object_name == NULL && cb_data != NULL) object_name = cb_data->prompt_info; return UI_construct_prompt(NULL, phrase_desc, object_name); } int set_base_ui_method(const UI_METHOD *ui_meth) { if (ui_meth == NULL) ui_meth = UI_null(); ui_base_method = ui_meth; return 1; } int setup_ui_method(void) { ui_base_method = UI_null(); #ifndef OPENSSL_NO_UI_CONSOLE ui_base_method = UI_OpenSSL(); #endif ui_method = UI_create_method("OpenSSL application user interface"); return ui_method != NULL && 0 == UI_method_set_opener(ui_method, ui_open) && 0 == UI_method_set_reader(ui_method, ui_read) && 0 == UI_method_set_writer(ui_method, ui_write) && 0 == UI_method_set_closer(ui_method, ui_close) && 0 == UI_method_set_prompt_constructor(ui_method, ui_prompt_construct); } void destroy_ui_method(void) { if (ui_method != NULL) { UI_destroy_method(ui_method); ui_method = NULL; } } const UI_METHOD *get_ui_method(void) { return ui_method; } static void *ui_malloc(int sz, const char *what) { void *vp = OPENSSL_malloc(sz); if (vp == NULL) { BIO_printf(bio_err, "Could not allocate %d bytes for %s\n", sz, what); ERR_print_errors(bio_err); exit(1); } return vp; } int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_data) { int res = 0; UI *ui; int ok = 0; char *buff = NULL; int ui_flags = 0; const char *prompt_info = NULL; char *prompt; if ((ui = UI_new_method(ui_method)) == NULL) return 0; if (cb_data != NULL && cb_data->prompt_info != NULL) prompt_info = cb_data->prompt_info; prompt = UI_construct_prompt(ui, "pass phrase", prompt_info); if (prompt == NULL) { BIO_printf(bio_err, "Out of memory\n"); UI_free(ui); return 0; } ui_flags |= UI_INPUT_FLAG_DEFAULT_PWD; UI_ctrl(ui, UI_CTRL_PRINT_ERRORS, 1, 0, 0); (void)UI_add_user_data(ui, cb_data); ok = UI_add_input_string(ui, prompt, ui_flags, buf, PW_MIN_LENGTH, bufsiz - 1); if (ok >= 0 && verify) { buff = ui_malloc(bufsiz, "password buffer"); ok = UI_add_verify_string(ui, prompt, ui_flags, buff, PW_MIN_LENGTH, bufsiz - 1, buf); } if (ok >= 0) do { ok = UI_process(ui); } while (ok < 0 && UI_ctrl(ui, UI_CTRL_IS_REDOABLE, 0, 0, 0)); OPENSSL_clear_free(buff, (unsigned int)bufsiz); if (ok >= 0) res = strlen(buf); if (ok == -1) { BIO_printf(bio_err, "User interface error\n"); ERR_print_errors(bio_err); OPENSSL_cleanse(buf, (unsigned int)bufsiz); res = 0; } if (ok == -2) { BIO_printf(bio_err, "aborted!\n"); OPENSSL_cleanse(buf, (unsigned int)bufsiz); res = 0; } UI_free(ui); OPENSSL_free(prompt); return res; }
lib
openssl/apps/lib/apps_ui.c
openssl
#include "apps.h" #include "cmp_mock_srv.h" #include <openssl/cmp.h> #include <openssl/err.h> #include <openssl/cmperr.h> typedef struct { X509 *refCert; X509 *certOut; STACK_OF(X509) *chainOut; STACK_OF(X509) *caPubsOut; X509 *newWithNew; X509 *newWithOld; X509 *oldWithNew; OSSL_CMP_PKISI *statusOut; int sendError; OSSL_CMP_MSG *req; int pollCount; int curr_pollCount; int checkAfterTime; } mock_srv_ctx; static void mock_srv_ctx_free(mock_srv_ctx *ctx) { if (ctx == NULL) return; OSSL_CMP_PKISI_free(ctx->statusOut); X509_free(ctx->refCert); X509_free(ctx->certOut); OSSL_STACK_OF_X509_free(ctx->chainOut); OSSL_STACK_OF_X509_free(ctx->caPubsOut); OSSL_CMP_MSG_free(ctx->req); OPENSSL_free(ctx); } static mock_srv_ctx *mock_srv_ctx_new(void) { mock_srv_ctx *ctx = OPENSSL_zalloc(sizeof(mock_srv_ctx)); if (ctx == NULL) goto err; if ((ctx->statusOut = OSSL_CMP_PKISI_new()) == NULL) goto err; ctx->sendError = -1; return ctx; err: mock_srv_ctx_free(ctx); return NULL; } #define DEFINE_OSSL_SET1_CERT(FIELD) \ int ossl_cmp_mock_srv_set1_##FIELD(OSSL_CMP_SRV_CTX *srv_ctx, \ X509 *cert) \ { \ mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); \ \ if (ctx == NULL) { \ ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); \ return 0; \ } \ if (cert == NULL || X509_up_ref(cert)) { \ X509_free(ctx->FIELD); \ ctx->FIELD = cert; \ return 1; \ } \ return 0; \ } DEFINE_OSSL_SET1_CERT(refCert) DEFINE_OSSL_SET1_CERT(certOut) int ossl_cmp_mock_srv_set1_chainOut(OSSL_CMP_SRV_CTX *srv_ctx, STACK_OF(X509) *chain) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); STACK_OF(X509) *chain_copy = NULL; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (chain != NULL && (chain_copy = X509_chain_up_ref(chain)) == NULL) return 0; OSSL_STACK_OF_X509_free(ctx->chainOut); ctx->chainOut = chain_copy; return 1; } int ossl_cmp_mock_srv_set1_caPubsOut(OSSL_CMP_SRV_CTX *srv_ctx, STACK_OF(X509) *caPubs) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); STACK_OF(X509) *caPubs_copy = NULL; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (caPubs != NULL && (caPubs_copy = X509_chain_up_ref(caPubs)) == NULL) return 0; OSSL_STACK_OF_X509_free(ctx->caPubsOut); ctx->caPubsOut = caPubs_copy; return 1; } DEFINE_OSSL_SET1_CERT(newWithNew) DEFINE_OSSL_SET1_CERT(newWithOld) DEFINE_OSSL_SET1_CERT(oldWithNew) int ossl_cmp_mock_srv_set_statusInfo(OSSL_CMP_SRV_CTX *srv_ctx, int status, int fail_info, const char *text) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); OSSL_CMP_PKISI *si; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if ((si = OSSL_CMP_STATUSINFO_new(status, fail_info, text)) == NULL) return 0; OSSL_CMP_PKISI_free(ctx->statusOut); ctx->statusOut = si; return 1; } int ossl_cmp_mock_srv_set_sendError(OSSL_CMP_SRV_CTX *srv_ctx, int bodytype) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } ctx->sendError = bodytype; return 1; } int ossl_cmp_mock_srv_set_pollCount(OSSL_CMP_SRV_CTX *srv_ctx, int count) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (count < 0) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return 0; } ctx->pollCount = count; return 1; } int ossl_cmp_mock_srv_set_checkAfterTime(OSSL_CMP_SRV_CTX *srv_ctx, int sec) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } ctx->checkAfterTime = sec; return 1; } static int delayed_delivery(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); int req_type = OSSL_CMP_MSG_get_bodytype(req); if (ctx == NULL || req == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return -1; } if (req_type == OSSL_CMP_IR || req_type == OSSL_CMP_CR || req_type == OSSL_CMP_P10CR || req_type == OSSL_CMP_KUR || req_type == OSSL_CMP_ERROR) return 0; if (ctx->pollCount > 0 && ctx->curr_pollCount == 0) { if ((ctx->req = OSSL_CMP_MSG_dup(req)) == NULL) return -1; return 1; } return 0; } static int refcert_cmp(const X509 *refcert, const X509_NAME *issuer, const ASN1_INTEGER *serial) { const X509_NAME *ref_issuer; const ASN1_INTEGER *ref_serial; if (refcert == NULL) return 1; ref_issuer = X509_get_issuer_name(refcert); ref_serial = X509_get0_serialNumber(refcert); return (ref_issuer == NULL || X509_NAME_cmp(issuer, ref_issuer) == 0) && (ref_serial == NULL || ASN1_INTEGER_cmp(serial, ref_serial) == 0); } static int clean_transaction(OSSL_CMP_SRV_CTX *srv_ctx, ossl_unused const ASN1_OCTET_STRING *id) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } ctx->curr_pollCount = 0; OSSL_CMP_MSG_free(ctx->req); ctx->req = NULL; return 1; } static OSSL_CMP_PKISI *process_cert_request(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *cert_req, ossl_unused int certReqId, const OSSL_CRMF_MSG *crm, const X509_REQ *p10cr, X509 **certOut, STACK_OF(X509) **chainOut, STACK_OF(X509) **caPubs) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); int bodytype; OSSL_CMP_PKISI *si = NULL; if (ctx == NULL || cert_req == NULL || certOut == NULL || chainOut == NULL || caPubs == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } bodytype = OSSL_CMP_MSG_get_bodytype(cert_req); if (ctx->sendError == 1 || ctx->sendError == bodytype) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); return NULL; } *certOut = NULL; *chainOut = NULL; *caPubs = NULL; if (ctx->pollCount > 0 && ctx->curr_pollCount == 0) { if ((ctx->req = OSSL_CMP_MSG_dup(cert_req)) == NULL) return NULL; return OSSL_CMP_STATUSINFO_new(OSSL_CMP_PKISTATUS_waiting, 0, NULL); } if (ctx->curr_pollCount >= ctx->pollCount) ctx->curr_pollCount = 0; if (OSSL_CMP_MSG_get_bodytype(cert_req) == OSSL_CMP_CR) { STACK_OF(OSSL_CMP_ITAV) *itavs = OSSL_CMP_HDR_get0_geninfo_ITAVs(OSSL_CMP_MSG_get0_header(cert_req)); int i; for (i = 0; i < sk_OSSL_CMP_ITAV_num(itavs); i++) { OSSL_CMP_ITAV *itav = sk_OSSL_CMP_ITAV_value(itavs, i); ASN1_OBJECT *obj = OSSL_CMP_ITAV_get0_type(itav); STACK_OF(ASN1_UTF8STRING) *strs; ASN1_UTF8STRING *str; const char *data; if (OBJ_obj2nid(obj) == NID_id_it_certProfile) { if (!OSSL_CMP_ITAV_get0_certProfile(itav, &strs)) return NULL; if (sk_ASN1_UTF8STRING_num(strs) < 1) { ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_CERTPROFILE); return NULL; } str = sk_ASN1_UTF8STRING_value(strs, 0); if (str == NULL || (data = (const char *)ASN1_STRING_get0_data(str)) == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_INVALID_ARGUMENT); return NULL; } if (strcmp(data, "profile1") != 0) { ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_CERTPROFILE); return NULL; } break; } } } if (bodytype == OSSL_CMP_KUR && crm != NULL && ctx->refCert != NULL) { const OSSL_CRMF_CERTID *cid = OSSL_CRMF_MSG_get0_regCtrl_oldCertID(crm); if (cid == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_CERTID); return NULL; } if (!refcert_cmp(ctx->refCert, OSSL_CRMF_CERTID_get0_issuer(cid), OSSL_CRMF_CERTID_get0_serialNumber(cid))) { ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_CERTID); return NULL; } } if (ctx->certOut != NULL && (*certOut = X509_dup(ctx->certOut)) == NULL) goto err; if (ctx->chainOut != NULL && (*chainOut = X509_chain_up_ref(ctx->chainOut)) == NULL) goto err; if (ctx->caPubsOut != NULL && (*caPubs = X509_chain_up_ref(ctx->caPubsOut)) == NULL) goto err; if (ctx->statusOut != NULL && (si = OSSL_CMP_PKISI_dup(ctx->statusOut)) == NULL) goto err; return si; err: X509_free(*certOut); *certOut = NULL; OSSL_STACK_OF_X509_free(*chainOut); *chainOut = NULL; OSSL_STACK_OF_X509_free(*caPubs); *caPubs = NULL; return NULL; } static OSSL_CMP_PKISI *process_rr(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *rr, const X509_NAME *issuer, const ASN1_INTEGER *serial) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (ctx == NULL || rr == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } if (ctx->sendError == 1 || ctx->sendError == OSSL_CMP_MSG_get_bodytype(rr)) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); return NULL; } if ((issuer != NULL || serial != NULL) && !refcert_cmp(ctx->refCert, issuer, serial)) { ERR_raise_data(ERR_LIB_CMP, CMP_R_REQUEST_NOT_ACCEPTED, "wrong certificate to revoke"); return NULL; } return OSSL_CMP_PKISI_dup(ctx->statusOut); } static OSSL_CMP_ITAV *process_genm_itav(mock_srv_ctx *ctx, int req_nid, const OSSL_CMP_ITAV *req) { OSSL_CMP_ITAV *rsp; switch (req_nid) { case NID_id_it_caCerts: rsp = OSSL_CMP_ITAV_new_caCerts(ctx->caPubsOut); break; case NID_id_it_rootCaCert: rsp = OSSL_CMP_ITAV_new_rootCaKeyUpdate(ctx->newWithNew, ctx->newWithOld, ctx->oldWithNew); break; default: rsp = OSSL_CMP_ITAV_dup(req); } return rsp; } static int process_genm(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *genm, const STACK_OF(OSSL_CMP_ITAV) *in, STACK_OF(OSSL_CMP_ITAV) **out) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (ctx == NULL || genm == NULL || in == NULL || out == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (ctx->sendError == 1 || ctx->sendError == OSSL_CMP_MSG_get_bodytype(genm) || sk_OSSL_CMP_ITAV_num(in) > 1) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); return 0; } if (sk_OSSL_CMP_ITAV_num(in) == 1) { OSSL_CMP_ITAV *req = sk_OSSL_CMP_ITAV_value(in, 0), *rsp; ASN1_OBJECT *obj = OSSL_CMP_ITAV_get0_type(req); if ((*out = sk_OSSL_CMP_ITAV_new_reserve(NULL, 1)) == NULL) return 0; rsp = process_genm_itav(ctx, OBJ_obj2nid(obj), req); if (rsp != NULL && sk_OSSL_CMP_ITAV_push(*out, rsp)) return 1; sk_OSSL_CMP_ITAV_free(*out); return 0; } *out = sk_OSSL_CMP_ITAV_deep_copy(in, OSSL_CMP_ITAV_dup, OSSL_CMP_ITAV_free); return *out != NULL; } static void process_error(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *error, const OSSL_CMP_PKISI *statusInfo, const ASN1_INTEGER *errorCode, const OSSL_CMP_PKIFREETEXT *errorDetails) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); char buf[OSSL_CMP_PKISI_BUFLEN]; char *sibuf; int i; if (ctx == NULL || error == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return; } BIO_printf(bio_err, "mock server received error:\n"); if (statusInfo == NULL) { BIO_printf(bio_err, "pkiStatusInfo absent\n"); } else { sibuf = OSSL_CMP_snprint_PKIStatusInfo(statusInfo, buf, sizeof(buf)); BIO_printf(bio_err, "pkiStatusInfo: %s\n", sibuf != NULL ? sibuf: "<invalid>"); } if (errorCode == NULL) BIO_printf(bio_err, "errorCode absent\n"); else BIO_printf(bio_err, "errorCode: %ld\n", ASN1_INTEGER_get(errorCode)); if (sk_ASN1_UTF8STRING_num(errorDetails) <= 0) { BIO_printf(bio_err, "errorDetails absent\n"); } else { BIO_printf(bio_err, "errorDetails: "); for (i = 0; i < sk_ASN1_UTF8STRING_num(errorDetails); i++) { if (i > 0) BIO_printf(bio_err, ", "); ASN1_STRING_print_ex(bio_err, sk_ASN1_UTF8STRING_value(errorDetails, i), ASN1_STRFLGS_ESC_QUOTE); } BIO_printf(bio_err, "\n"); } } static int process_certConf(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *certConf, ossl_unused int certReqId, const ASN1_OCTET_STRING *certHash, const OSSL_CMP_PKISI *si) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); ASN1_OCTET_STRING *digest; if (ctx == NULL || certConf == NULL || certHash == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (ctx->sendError == 1 || ctx->sendError == OSSL_CMP_MSG_get_bodytype(certConf) || ctx->certOut == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); return 0; } if ((digest = X509_digest_sig(ctx->certOut, NULL, NULL)) == NULL) return 0; if (ASN1_OCTET_STRING_cmp(certHash, digest) != 0) { ASN1_OCTET_STRING_free(digest); ERR_raise(ERR_LIB_CMP, CMP_R_CERTHASH_UNMATCHED); return 0; } ASN1_OCTET_STRING_free(digest); return 1; } static int process_pollReq(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *pollReq, ossl_unused int certReqId, OSSL_CMP_MSG **req, int64_t *check_after) { mock_srv_ctx *ctx = OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx); if (req != NULL) *req = NULL; if (ctx == NULL || pollReq == NULL || req == NULL || check_after == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (ctx->sendError == 1 || ctx->sendError == OSSL_CMP_MSG_get_bodytype(pollReq)) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); return 0; } if (ctx->req == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_POLLREQ); return 0; } if (++ctx->curr_pollCount >= ctx->pollCount) { *req = ctx->req; ctx->req = NULL; *check_after = 0; } else { *check_after = ctx->checkAfterTime; } return 1; } OSSL_CMP_SRV_CTX *ossl_cmp_mock_srv_new(OSSL_LIB_CTX *libctx, const char *propq) { OSSL_CMP_SRV_CTX *srv_ctx = OSSL_CMP_SRV_CTX_new(libctx, propq); mock_srv_ctx *ctx = mock_srv_ctx_new(); if (srv_ctx != NULL && ctx != NULL && OSSL_CMP_SRV_CTX_init(srv_ctx, ctx, process_cert_request, process_rr, process_genm, process_error, process_certConf, process_pollReq) && OSSL_CMP_SRV_CTX_init_trans(srv_ctx, delayed_delivery, clean_transaction)) return srv_ctx; mock_srv_ctx_free(ctx); OSSL_CMP_SRV_CTX_free(srv_ctx); return NULL; } void ossl_cmp_mock_srv_free(OSSL_CMP_SRV_CTX *srv_ctx) { if (srv_ctx != NULL) mock_srv_ctx_free(OSSL_CMP_SRV_CTX_get0_custom_ctx(srv_ctx)); OSSL_CMP_SRV_CTX_free(srv_ctx); }
lib
openssl/apps/lib/cmp_mock_srv.c
openssl
#ifdef __VMS # define OPENSSL_SYS_VMS # pragma message disable DOLLARID # include <openssl/opensslconf.h> # if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS) # define _POSIX_C_SOURCE 2 # endif # include <stdio.h> # undef _POSIX_C_SOURCE # include <sys/types.h> # include <sys/socket.h> # include <netinet/in.h> # include <inet.h> # include <unistd.h> # include <string.h> # include <errno.h> # include <starlet.h> # include <iodef.h> # ifdef __alpha # include <iosbdef.h> # else typedef struct _iosb { # pragma __nomember_alignment __union { __struct { unsigned short int iosb$w_status; __union { __struct { unsigned short int iosb$w_bcnt; __union { unsigned int iosb$l_dev_depend; unsigned int iosb$l_pid; } iosb$r_l; } iosb$r_bcnt_16; __struct { unsigned int iosb$l_bcnt; unsigned short int iosb$w_dev_depend_high; } iosb$r_bcnt_32; } iosb$r_devdepend; } iosb$r_io_64; __struct { __union { unsigned int iosb$l_getxxi_status; unsigned int iosb$l_reg_status; } iosb$r_l_status; unsigned int iosb$l_reserved; } iosb$r_get_64; } iosb$r_io_get; } IOSB; # if !defined(__VAXC) # define iosb$w_status iosb$r_io_get.iosb$r_io_64.iosb$w_status # define iosb$w_bcnt iosb$r_io_get.iosb$r_io_64.iosb$r_devdepend.iosb$r_bcnt_16.iosb$w_bcnt # define iosb$r_l iosb$r_io_get.iosb$r_io_64.iosb$r_devdepend.iosb$r_bcnt_16.iosb$r_l # define iosb$l_dev_depend iosb$r_l.iosb$l_dev_depend # define iosb$l_pid iosb$r_l.iosb$l_pid # define iosb$l_bcnt iosb$r_io_get.iosb$r_io_64.iosb$r_devdepend.iosb$r_bcnt_32.iosb$l_bcnt # define iosb$w_dev_depend_high iosb$r_io_get.iosb$r_io_64.iosb$r_devdepend.iosb$r_bcnt_32.iosb$w_dev_depend_high # define iosb$l_getxxi_status iosb$r_io_get.iosb$r_get_64.iosb$r_l_status.iosb$l_getxxi_status # define iosb$l_reg_status iosb$r_io_get.iosb$r_get_64.iosb$r_l_status.iosb$l_reg_status # endif # endif # include <efndef.h> # include <stdlib.h> # include <ssdef.h> # include <time.h> # include <stdarg.h> # include <descrip.h> # include "vms_term_sock.h" # ifdef __alpha static struct _iosb TerminalDeviceIosb; # else IOSB TerminalDeviceIosb; # endif static char TerminalDeviceBuff[255 + 2]; static int TerminalSocketPair[2] = {0, 0}; static unsigned short TerminalDeviceChan = 0; static int CreateSocketPair (int, int, int, int *); static void SocketPairTimeoutAst (int); static int TerminalDeviceAst (int); static void LogMessage (char *, ...); # define SOCKET_PAIR_TIMEOUT_VALUE 20 typedef struct _SocketPairTimeoutBlock { unsigned short SockChan1; unsigned short SockChan2; } SPTB; # ifdef TERM_SOCK_TEST int main (int argc, char *argv[], char *envp[]) { char TermBuff[80]; int TermSock, status, len; LogMessage ("Enter 'q' or 'Q' to quit ..."); while (OPENSSL_strcasecmp (TermBuff, "Q")) { status = TerminalSocket (TERM_SOCK_CREATE, &TermSock); if (status != TERM_SOCK_SUCCESS) exit (1); LogMessage ("Waiting on terminal I/O ...\n"); len = recv (TermSock, TermBuff, sizeof(TermBuff), 0) ; TermBuff[len] = '\0'; LogMessage ("Received terminal I/O [%s]", TermBuff); status = TerminalSocket (TERM_SOCK_DELETE, &TermSock); if (status != TERM_SOCK_SUCCESS) exit (1); } return 1; } # endif int TerminalSocket (int FunctionCode, int *ReturnSocket) { int status; $DESCRIPTOR (TerminalDeviceDesc, "SYS$COMMAND"); switch (FunctionCode) { case TERM_SOCK_CREATE: status = CreateSocketPair (AF_INET, SOCK_STREAM, 0, TerminalSocketPair); if (status == -1) { LogMessage ("TerminalSocket: CreateSocketPair () - %08X", status); if (TerminalSocketPair[0]) close (TerminalSocketPair[0]); if (TerminalSocketPair[1]) close (TerminalSocketPair[1]); return TERM_SOCK_FAILURE; } status = sys$assign (&TerminalDeviceDesc, &TerminalDeviceChan, 0, 0, 0); if (! (status & 1)) { LogMessage ("TerminalSocket: SYS$ASSIGN () - %08X", status); close (TerminalSocketPair[0]); close (TerminalSocketPair[1]); return TERM_SOCK_FAILURE; } status = sys$qio (EFN$C_ENF, TerminalDeviceChan, IO$_READVBLK, &TerminalDeviceIosb, TerminalDeviceAst, 0, TerminalDeviceBuff, sizeof(TerminalDeviceBuff) - 2, 0, 0, 0, 0); if (! (status & 1)) { LogMessage ("TerminalSocket: SYS$QIO () - %08X", status); close (TerminalSocketPair[0]); close (TerminalSocketPair[1]); return TERM_SOCK_FAILURE; } *ReturnSocket = TerminalSocketPair[1]; break; case TERM_SOCK_DELETE: status = sys$cancel (TerminalDeviceChan); if (! (status & 1)) { LogMessage ("TerminalSocket: SYS$CANCEL () - %08X", status); close (TerminalSocketPair[0]); close (TerminalSocketPair[1]); return TERM_SOCK_FAILURE; } status = sys$dassgn (TerminalDeviceChan); if (! (status & 1)) { LogMessage ("TerminalSocket: SYS$DASSGN () - %08X", status); close (TerminalSocketPair[0]); close (TerminalSocketPair[1]); return TERM_SOCK_FAILURE; } close (TerminalSocketPair[0]); close (TerminalSocketPair[1]); *ReturnSocket = 0; break; default: LogMessage ("TerminalSocket: Invalid Function Code - %d", FunctionCode); return TERM_SOCK_FAILURE; break; } return TERM_SOCK_SUCCESS; } static int CreateSocketPair (int SocketFamily, int SocketType, int SocketProtocol, int *SocketPair) { struct dsc$descriptor AscTimeDesc = {0, DSC$K_DTYPE_T, DSC$K_CLASS_S, NULL}; static const char* LocalHostAddr = {"127.0.0.1"}; unsigned short TcpAcceptChan = 0, TcpDeviceChan = 0; unsigned long BinTimeBuff[2]; struct sockaddr_in sin; char AscTimeBuff[32]; short LocalHostPort; int status; unsigned int slen; # ifdef __alpha struct _iosb iosb; # else IOSB iosb; # endif int SockDesc1 = 0, SockDesc2 = 0; SPTB sptb; $DESCRIPTOR (TcpDeviceDesc, "TCPIP$DEVICE"); SockDesc1 = socket (SocketFamily, SocketType, 0); if (SockDesc1 < 0) { LogMessage ("CreateSocketPair: socket () - %d", errno); return -1; } slen = sizeof(sin); memset ((char *) &sin, 0, slen); sin.sin_family = SocketFamily; sin.sin_addr.s_addr = inet_addr (LocalHostAddr); sin.sin_port = 0; status = bind (SockDesc1, (struct sockaddr *) &sin, slen); if (status < 0) { LogMessage ("CreateSocketPair: bind () - %d", errno); close (SockDesc1); return -1; } status = getsockname (SockDesc1, (struct sockaddr *) &sin, &slen); if (status < 0) { LogMessage ("CreateSocketPair: getsockname () - %d", errno); close (SockDesc1); return -1; } else LocalHostPort = sin.sin_port; listen (SockDesc1, 5); sprintf (AscTimeBuff, "0 0:0:%02d.00", SOCKET_PAIR_TIMEOUT_VALUE); AscTimeDesc.dsc$w_length = strlen (AscTimeBuff); AscTimeDesc.dsc$a_pointer = AscTimeBuff; status = sys$bintim (&AscTimeDesc, BinTimeBuff); if (! (status & 1)) { LogMessage ("CreateSocketPair: SYS$BINTIM () - %08X", status); close (SockDesc1); return -1; } status = sys$assign (&TcpDeviceDesc, &TcpDeviceChan, 0, 0, 0); if (! (status & 1)) { LogMessage ("CreateSocketPair: SYS$ASSIGN () - %08X", status); close (SockDesc1); return -1; } TcpAcceptChan = decc$get_sdc (SockDesc1); status = sys$qio (EFN$C_ENF, TcpAcceptChan, IO$_ACCESS | IO$M_ACCEPT, &iosb, 0, 0, 0, 0, 0, &TcpDeviceChan, 0, 0); if (! (status & 1)) { LogMessage ("CreateSocketPair: SYS$QIO () - %08X", status); close (SockDesc1); sys$dassgn (TcpDeviceChan); return -1; } SockDesc2 = socket (SocketFamily, SocketType, 0); if (SockDesc2 < 0) { LogMessage ("CreateSocketPair: socket () - %d", errno); sys$cancel (TcpAcceptChan); close (SockDesc1); sys$dassgn (TcpDeviceChan); return (-1) ; } sptb.SockChan1 = TcpAcceptChan; sptb.SockChan2 = decc$get_sdc (SockDesc2); status = sys$setimr (EFN$C_ENF, BinTimeBuff, SocketPairTimeoutAst, &sptb, 0); if (! (status & 1)) { LogMessage ("CreateSocketPair: SYS$SETIMR () - %08X", status); sys$cancel (TcpAcceptChan); close (SockDesc1); close (SockDesc2); sys$dassgn (TcpDeviceChan); return -1; } memset ((char *) &sin, 0, sizeof(sin)) ; sin.sin_family = SocketFamily; sin.sin_addr.s_addr = inet_addr (LocalHostAddr) ; sin.sin_port = LocalHostPort ; status = connect (SockDesc2, (struct sockaddr *) &sin, sizeof(sin)); if (status < 0) { LogMessage ("CreateSocketPair: connect () - %d", errno); sys$cantim (&sptb, 0); sys$cancel (TcpAcceptChan); close (SockDesc1); close (SockDesc2); sys$dassgn (TcpDeviceChan); return -1; } status = sys$synch (EFN$C_ENF, &iosb); if (! (iosb.iosb$w_status & 1)) { if (iosb.iosb$w_status == SS$_ABORT) LogMessage ("CreateSocketPair: SYS$QIO(iosb) timeout"); else { LogMessage ("CreateSocketPair: SYS$QIO(iosb) - %d", iosb.iosb$w_status); sys$cantim (&sptb, 0); } close (SockDesc1); close (SockDesc2); sys$dassgn (TcpDeviceChan); return -1; } sys$cantim (&sptb, 0); close (SockDesc1) ; SocketPair[0] = SockDesc2 ; SocketPair[1] = socket_fd (TcpDeviceChan); return (0) ; } static void SocketPairTimeoutAst (int astparm) { SPTB *sptb = (SPTB *) astparm; sys$cancel (sptb->SockChan2); sys$cancel (sptb->SockChan1); return; } static int TerminalDeviceAst (int astparm) { int status; TerminalDeviceBuff[TerminalDeviceIosb.iosb$w_bcnt] = '\0'; strcat (TerminalDeviceBuff, "\n"); send (TerminalSocketPair[0], TerminalDeviceBuff, TerminalDeviceIosb.iosb$w_bcnt + 1, 0); status = sys$qio (EFN$C_ENF, TerminalDeviceChan, IO$_READVBLK, &TerminalDeviceIosb, TerminalDeviceAst, 0, TerminalDeviceBuff, sizeof(TerminalDeviceBuff) - 1, 0, 0, 0, 0); return status; } static void LogMessage (char *msg, ...) { char *Month[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; static unsigned int pid = 0; va_list args; time_t CurTime; struct tm *LocTime; char MsgBuff[256]; if (pid == 0) pid = getpid (); CurTime = time (NULL); LocTime = localtime (&CurTime); sprintf (MsgBuff, "%02d-%s-%04d %02d:%02d:%02d [%08X] %s\n", LocTime->tm_mday, Month[LocTime->tm_mon], (LocTime->tm_year + 1900), LocTime->tm_hour, LocTime->tm_min, LocTime->tm_sec, pid, msg); va_start (args, msg); vfprintf (stderr, MsgBuff, args); va_end (args); fsync (fileno (stderr)); return; } #endif
lib
openssl/apps/lib/vms_term_sock.c
openssl
#include "opt.h" #include "fmt.h" #include "app_libctx.h" #include "internal/nelem.h" #include "internal/numbers.h" #include <string.h> #if !defined(OPENSSL_SYS_MSDOS) # include <unistd.h> #endif #include <stdlib.h> #include <errno.h> #include <ctype.h> #include <limits.h> #include <openssl/err.h> #include <openssl/bio.h> #include <openssl/x509v3.h> #define MAX_OPT_HELP_WIDTH 30 const char OPT_HELP_STR[] = "-H"; const char OPT_MORE_STR[] = "-M"; const char OPT_SECTION_STR[] = "-S"; const char OPT_PARAM_STR[] = "-P"; static char **argv; static int argc; static int opt_index; static char *arg; static char *flag; static char *dunno; static const char *unknown_name; static const OPTIONS *unknown; static const OPTIONS *opts; static char prog[40]; #if defined(OPENSSL_SYS_WIN32) const char *opt_path_end(const char *filename) { const char *p; for (p = filename + strlen(filename); --p > filename; ) if (*p == '/' || *p == '\\' || *p == ':') { p++; break; } return p; } char *opt_progname(const char *argv0) { size_t i, n; const char *p; char *q; p = opt_path_end(argv0); n = strlen(p); if (n > 4 && (strcmp(&p[n - 4], ".exe") == 0 || strcmp(&p[n - 4], ".EXE") == 0)) n -= 4; if (n > sizeof(prog) - 1) n = sizeof(prog) - 1; for (q = prog, i = 0; i < n; i++, p++) *q++ = tolower((unsigned char)*p); *q = '\0'; return prog; } #elif defined(OPENSSL_SYS_VMS) const char *opt_path_end(const char *filename) { const char *p; for (p = filename + strlen(filename); --p > filename;) if (*p == ':' || *p == ']' || *p == '>') { p++; break; } return p; } char *opt_progname(const char *argv0) { const char *p, *q; p = opt_path_end(argv0); q = strrchr(p, '.'); if (prog != p) strncpy(prog, p, sizeof(prog) - 1); prog[sizeof(prog) - 1] = '\0'; if (q != NULL && q - p < sizeof(prog)) prog[q - p] = '\0'; return prog; } #else const char *opt_path_end(const char *filename) { const char *p; for (p = filename + strlen(filename); --p > filename;) if (*p == '/') { p++; break; } return p; } char *opt_progname(const char *argv0) { const char *p; p = opt_path_end(argv0); if (prog != p) strncpy(prog, p, sizeof(prog) - 1); prog[sizeof(prog) - 1] = '\0'; return prog; } #endif char *opt_appname(const char *argv0) { size_t len = strlen(prog); if (argv0 != NULL) BIO_snprintf(prog + len, sizeof(prog) - len - 1, " %s", argv0); return prog; } char *opt_getprog(void) { return prog; } char *opt_init(int ac, char **av, const OPTIONS *o) { argc = ac; argv = av; opt_begin(); opts = o; unknown = NULL; (void)opt_progname(argv[0]); for (; o->name != NULL && o->name != OPT_PARAM_STR; ++o) { #ifndef NDEBUG const OPTIONS *next; int duplicated, i; #endif if (o->name == OPT_HELP_STR || o->name == OPT_MORE_STR || o->name == OPT_SECTION_STR) continue; #ifndef NDEBUG i = o->valtype; OPENSSL_assert(o->name[0] != '-'); if (o->valtype == '.') OPENSSL_assert(o->retval == OPT_PARAM); else OPENSSL_assert(o->retval == OPT_DUP || o->retval > OPT_PARAM); switch (i) { case 0: case '-': case '.': case '/': case '<': case '>': case 'E': case 'F': case 'M': case 'U': case 'f': case 'l': case 'n': case 'p': case 's': case 'u': case 'c': case ':': case 'N': case 'A': break; default: OPENSSL_assert(0); } for (next = o + 1; next->name; ++next) { duplicated = next->retval != OPT_DUP && strcmp(o->name, next->name) == 0; if (duplicated) { opt_printf_stderr("%s: Internal error: duplicate option %s\n", prog, o->name); OPENSSL_assert(!duplicated); } } #endif if (o->name[0] == '\0') { OPENSSL_assert(unknown_name != NULL); OPENSSL_assert(unknown == NULL); unknown = o; OPENSSL_assert(unknown->valtype == 0 || unknown->valtype == '-'); } } return prog; } static OPT_PAIR formats[] = { {"pem", OPT_FMT_PEM}, {"der", OPT_FMT_DER}, {"b64", OPT_FMT_B64}, {"pkcs12", OPT_FMT_PKCS12}, {"smime", OPT_FMT_SMIME}, {"engine", OPT_FMT_ENGINE}, {"msblob", OPT_FMT_MSBLOB}, {"nss", OPT_FMT_NSS}, {"text", OPT_FMT_TEXT}, {"http", OPT_FMT_HTTP}, {"pvk", OPT_FMT_PVK}, {NULL} }; void opt_set_unknown_name(const char *name) { unknown_name = name; } static int opt_format_error(const char *s, unsigned long flags) { OPT_PAIR *ap; opt_printf_stderr("%s: Bad format \"%s\"; must be one of: ", prog, s); for (ap = formats; ap->name; ap++) if (flags & ap->retval) opt_printf_stderr(" %s", ap->name); opt_printf_stderr("\n"); return 0; } int opt_format(const char *s, unsigned long flags, int *result) { switch (*s) { default: opt_printf_stderr("%s: Bad format \"%s\"\n", prog, s); return 0; case 'B': case 'b': if (s[1] == '\0' || strcmp(s, "B64") == 0 || strcmp(s, "b64") == 0 || strcmp(s, "BASE64") == 0 || strcmp(s, "base64") == 0 ) { if ((flags & OPT_FMT_B64) == 0) return opt_format_error(s, flags); *result = FORMAT_BASE64; } else { return 0; } break; case 'D': case 'd': if ((flags & OPT_FMT_DER) == 0) return opt_format_error(s, flags); *result = FORMAT_ASN1; break; case 'T': case 't': if ((flags & OPT_FMT_TEXT) == 0) return opt_format_error(s, flags); *result = FORMAT_TEXT; break; case 'N': case 'n': if ((flags & OPT_FMT_NSS) == 0) return opt_format_error(s, flags); if (strcmp(s, "NSS") != 0 && strcmp(s, "nss") != 0) return opt_format_error(s, flags); *result = FORMAT_NSS; break; case 'S': case 's': if ((flags & OPT_FMT_SMIME) == 0) return opt_format_error(s, flags); *result = FORMAT_SMIME; break; case 'M': case 'm': if ((flags & OPT_FMT_MSBLOB) == 0) return opt_format_error(s, flags); *result = FORMAT_MSBLOB; break; case 'E': case 'e': if ((flags & OPT_FMT_ENGINE) == 0) return opt_format_error(s, flags); *result = FORMAT_ENGINE; break; case 'H': case 'h': if ((flags & OPT_FMT_HTTP) == 0) return opt_format_error(s, flags); *result = FORMAT_HTTP; break; case '1': if ((flags & OPT_FMT_PKCS12) == 0) return opt_format_error(s, flags); *result = FORMAT_PKCS12; break; case 'P': case 'p': if (s[1] == '\0' || strcmp(s, "PEM") == 0 || strcmp(s, "pem") == 0) { if ((flags & OPT_FMT_PEM) == 0) return opt_format_error(s, flags); *result = FORMAT_PEM; } else if (strcmp(s, "PVK") == 0 || strcmp(s, "pvk") == 0) { if ((flags & OPT_FMT_PVK) == 0) return opt_format_error(s, flags); *result = FORMAT_PVK; } else if (strcmp(s, "P12") == 0 || strcmp(s, "p12") == 0 || strcmp(s, "PKCS12") == 0 || strcmp(s, "pkcs12") == 0) { if ((flags & OPT_FMT_PKCS12) == 0) return opt_format_error(s, flags); *result = FORMAT_PKCS12; } else { opt_printf_stderr("%s: Bad format \"%s\"\n", prog, s); return 0; } break; } return 1; } static const char *format2str(int format) { switch (format) { default: return "(undefined)"; case FORMAT_PEM: return "PEM"; case FORMAT_ASN1: return "DER"; case FORMAT_TEXT: return "TEXT"; case FORMAT_NSS: return "NSS"; case FORMAT_SMIME: return "SMIME"; case FORMAT_MSBLOB: return "MSBLOB"; case FORMAT_ENGINE: return "ENGINE"; case FORMAT_HTTP: return "HTTP"; case FORMAT_PKCS12: return "P12"; case FORMAT_PVK: return "PVK"; } } void print_format_error(int format, unsigned long flags) { (void)opt_format_error(format2str(format), flags); } int opt_cipher_silent(const char *name, EVP_CIPHER **cipherp) { EVP_CIPHER *c; ERR_set_mark(); if ((c = EVP_CIPHER_fetch(app_get0_libctx(), name, app_get0_propq())) != NULL || (opt_legacy_okay() && (c = (EVP_CIPHER *)EVP_get_cipherbyname(name)) != NULL)) { ERR_pop_to_mark(); if (cipherp != NULL) { EVP_CIPHER_free(*cipherp); *cipherp = c; } else { EVP_CIPHER_free(c); } return 1; } ERR_clear_last_mark(); return 0; } int opt_cipher_any(const char *name, EVP_CIPHER **cipherp) { int ret; if (name == NULL) return 1; if ((ret = opt_cipher_silent(name, cipherp)) == 0) opt_printf_stderr("%s: Unknown option or cipher: %s\n", prog, name); return ret; } int opt_cipher(const char *name, EVP_CIPHER **cipherp) { int mode, ret = 0; unsigned long int flags; EVP_CIPHER *c = NULL; if (name == NULL) return 1; if (opt_cipher_any(name, &c)) { mode = EVP_CIPHER_get_mode(c); flags = EVP_CIPHER_get_flags(c); if (mode == EVP_CIPH_XTS_MODE) { opt_printf_stderr("%s XTS ciphers not supported\n", prog); } else if ((flags & EVP_CIPH_FLAG_AEAD_CIPHER) != 0) { opt_printf_stderr("%s: AEAD ciphers not supported\n", prog); } else { ret = 1; if (cipherp != NULL) *cipherp = c; } } return ret; } int opt_md_silent(const char *name, EVP_MD **mdp) { EVP_MD *md; ERR_set_mark(); if ((md = EVP_MD_fetch(app_get0_libctx(), name, app_get0_propq())) != NULL || (opt_legacy_okay() && (md = (EVP_MD *)EVP_get_digestbyname(name)) != NULL)) { ERR_pop_to_mark(); if (mdp != NULL) { EVP_MD_free(*mdp); *mdp = md; } else { EVP_MD_free(md); } return 1; } ERR_clear_last_mark(); return 0; } int opt_md(const char *name, EVP_MD **mdp) { int ret; if (name == NULL) return 1; if ((ret = opt_md_silent(name, mdp)) == 0) opt_printf_stderr("%s: Unknown option or message digest: %s\n", prog, name); return ret; } int opt_check_md(const char *name) { if (opt_md(name, NULL)) return 1; ERR_clear_error(); return 0; } int opt_pair(const char *name, const OPT_PAIR* pairs, int *result) { const OPT_PAIR *pp; for (pp = pairs; pp->name; pp++) if (strcmp(pp->name, name) == 0) { *result = pp->retval; return 1; } opt_printf_stderr("%s: Value must be one of:\n", prog); for (pp = pairs; pp->name; pp++) opt_printf_stderr("\t%s\n", pp->name); return 0; } int opt_string(const char *name, const char **options) { const char **p; for (p = options; *p != NULL; p++) if (strcmp(*p, name) == 0) return 1; opt_printf_stderr("%s: Value must be one of:\n", prog); for (p = options; *p != NULL; p++) opt_printf_stderr("\t%s\n", *p); return 0; } int opt_int(const char *value, int *result) { long l; if (!opt_long(value, &l)) return 0; *result = (int)l; if (*result != l) { opt_printf_stderr("%s: Value \"%s\" outside integer range\n", prog, value); return 0; } return 1; } int opt_int_arg(void) { int result = -1; (void)opt_int(arg, &result); return result; } static void opt_number_error(const char *v) { size_t i = 0; struct strstr_pair_st { char *prefix; char *name; } b[] = { {"0x", "a hexadecimal"}, {"0X", "a hexadecimal"}, {"0", "an octal"} }; for (i = 0; i < OSSL_NELEM(b); i++) { if (strncmp(v, b[i].prefix, strlen(b[i].prefix)) == 0) { opt_printf_stderr("%s: Can't parse \"%s\" as %s number\n", prog, v, b[i].name); return; } } opt_printf_stderr("%s: Can't parse \"%s\" as a number\n", prog, v); return; } int opt_long(const char *value, long *result) { int oerrno = errno; long l; char *endp; errno = 0; l = strtol(value, &endp, 0); if (*endp || endp == value || ((l == LONG_MAX || l == LONG_MIN) && errno == ERANGE) || (l == 0 && errno != 0)) { opt_number_error(value); errno = oerrno; return 0; } *result = l; errno = oerrno; return 1; } #if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L && \ defined(INTMAX_MAX) && defined(UINTMAX_MAX) && \ !defined(OPENSSL_NO_INTTYPES_H) int opt_intmax(const char *value, ossl_intmax_t *result) { int oerrno = errno; intmax_t m; char *endp; errno = 0; m = strtoimax(value, &endp, 0); if (*endp || endp == value || ((m == INTMAX_MAX || m == INTMAX_MIN) && errno == ERANGE) || (m == 0 && errno != 0)) { opt_number_error(value); errno = oerrno; return 0; } if (sizeof(m) > sizeof(*result) && (m < OSSL_INTMAX_MIN || m > OSSL_INTMAX_MAX)) { opt_number_error(value); return 0; } *result = (ossl_intmax_t)m; errno = oerrno; return 1; } int opt_uintmax(const char *value, ossl_uintmax_t *result) { int oerrno = errno; uintmax_t m; char *endp; errno = 0; m = strtoumax(value, &endp, 0); if (*endp || endp == value || (m == UINTMAX_MAX && errno == ERANGE) || (m == 0 && errno != 0)) { opt_number_error(value); errno = oerrno; return 0; } if (sizeof(m) > sizeof(*result) && m > OSSL_UINTMAX_MAX) { opt_number_error(value); return 0; } *result = (ossl_intmax_t)m; errno = oerrno; return 1; } #else int opt_intmax(const char *value, ossl_intmax_t *result) { long m; int ret; if ((ret = opt_long(value, &m))) *result = m; return ret; } int opt_uintmax(const char *value, ossl_uintmax_t *result) { unsigned long m; int ret; if ((ret = opt_ulong(value, &m))) *result = m; return ret; } #endif int opt_ulong(const char *value, unsigned long *result) { int oerrno = errno; char *endptr; unsigned long l; errno = 0; l = strtoul(value, &endptr, 0); if (*endptr || endptr == value || ((l == ULONG_MAX) && errno == ERANGE) || (l == 0 && errno != 0)) { opt_number_error(value); errno = oerrno; return 0; } *result = l; errno = oerrno; return 1; } enum range { OPT_V_ENUM }; int opt_verify(int opt, X509_VERIFY_PARAM *vpm) { int i; ossl_intmax_t t = 0; ASN1_OBJECT *otmp; X509_PURPOSE *xptmp; const X509_VERIFY_PARAM *vtmp; OPENSSL_assert(vpm != NULL); OPENSSL_assert(opt > OPT_V__FIRST); OPENSSL_assert(opt < OPT_V__LAST); switch ((enum range)opt) { case OPT_V__FIRST: case OPT_V__LAST: return 0; case OPT_V_POLICY: otmp = OBJ_txt2obj(opt_arg(), 0); if (otmp == NULL) { opt_printf_stderr("%s: Invalid Policy %s\n", prog, opt_arg()); return 0; } if (!X509_VERIFY_PARAM_add0_policy(vpm, otmp)) { ASN1_OBJECT_free(otmp); opt_printf_stderr("%s: Internal error adding Policy %s\n", prog, opt_arg()); return 0; } break; case OPT_V_PURPOSE: i = X509_PURPOSE_get_by_sname(opt_arg()); if (i < 0) { opt_printf_stderr("%s: Invalid purpose %s\n", prog, opt_arg()); return 0; } xptmp = X509_PURPOSE_get0(i); i = X509_PURPOSE_get_id(xptmp); if (!X509_VERIFY_PARAM_set_purpose(vpm, i)) { opt_printf_stderr("%s: Internal error setting purpose %s\n", prog, opt_arg()); return 0; } break; case OPT_V_VERIFY_NAME: vtmp = X509_VERIFY_PARAM_lookup(opt_arg()); if (vtmp == NULL) { opt_printf_stderr("%s: Invalid verify name %s\n", prog, opt_arg()); return 0; } X509_VERIFY_PARAM_set1(vpm, vtmp); break; case OPT_V_VERIFY_DEPTH: i = atoi(opt_arg()); if (i >= 0) X509_VERIFY_PARAM_set_depth(vpm, i); break; case OPT_V_VERIFY_AUTH_LEVEL: i = atoi(opt_arg()); if (i >= 0) X509_VERIFY_PARAM_set_auth_level(vpm, i); break; case OPT_V_ATTIME: if (!opt_intmax(opt_arg(), &t)) return 0; if (t != (time_t)t) { opt_printf_stderr("%s: epoch time out of range %s\n", prog, opt_arg()); return 0; } X509_VERIFY_PARAM_set_time(vpm, (time_t)t); break; case OPT_V_VERIFY_HOSTNAME: if (!X509_VERIFY_PARAM_set1_host(vpm, opt_arg(), 0)) return 0; break; case OPT_V_VERIFY_EMAIL: if (!X509_VERIFY_PARAM_set1_email(vpm, opt_arg(), 0)) return 0; break; case OPT_V_VERIFY_IP: if (!X509_VERIFY_PARAM_set1_ip_asc(vpm, opt_arg())) return 0; break; case OPT_V_IGNORE_CRITICAL: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_IGNORE_CRITICAL); break; case OPT_V_ISSUER_CHECKS: break; case OPT_V_CRL_CHECK: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_CRL_CHECK); break; case OPT_V_CRL_CHECK_ALL: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL); break; case OPT_V_POLICY_CHECK: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_POLICY_CHECK); break; case OPT_V_EXPLICIT_POLICY: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_EXPLICIT_POLICY); break; case OPT_V_INHIBIT_ANY: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_INHIBIT_ANY); break; case OPT_V_INHIBIT_MAP: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_INHIBIT_MAP); break; case OPT_V_X509_STRICT: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_X509_STRICT); break; case OPT_V_EXTENDED_CRL: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_EXTENDED_CRL_SUPPORT); break; case OPT_V_USE_DELTAS: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_USE_DELTAS); break; case OPT_V_POLICY_PRINT: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NOTIFY_POLICY); break; case OPT_V_CHECK_SS_SIG: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_CHECK_SS_SIGNATURE); break; case OPT_V_TRUSTED_FIRST: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_TRUSTED_FIRST); break; case OPT_V_SUITEB_128_ONLY: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_SUITEB_128_LOS_ONLY); break; case OPT_V_SUITEB_128: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_SUITEB_128_LOS); break; case OPT_V_SUITEB_192: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_SUITEB_192_LOS); break; case OPT_V_PARTIAL_CHAIN: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_PARTIAL_CHAIN); break; case OPT_V_NO_ALT_CHAINS: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NO_ALT_CHAINS); break; case OPT_V_NO_CHECK_TIME: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_NO_CHECK_TIME); break; case OPT_V_ALLOW_PROXY_CERTS: X509_VERIFY_PARAM_set_flags(vpm, X509_V_FLAG_ALLOW_PROXY_CERTS); break; } return 1; } void opt_begin(void) { opt_index = 1; arg = NULL; flag = NULL; } int opt_next(void) { char *p; const OPTIONS *o; int ival; long lval; unsigned long ulval; ossl_intmax_t imval; ossl_uintmax_t umval; arg = NULL; p = argv[opt_index]; if (p == NULL) return 0; if (*p != '-') return 0; opt_index++; if (strcmp(p, "--") == 0) return 0; if (*++p == '-') p++; flag = p - 1; if ((arg = strchr(p, '=')) != NULL) *arg++ = '\0'; for (o = opts; o->name; ++o) { if (!(strcmp(p, "h") == 0 && strcmp(o->name, "help") == 0) && strcmp(p, o->name) != 0) continue; if (o->valtype == 0 || o->valtype == '-') { if (arg) { opt_printf_stderr("%s: Option -%s does not take a value\n", prog, p); return -1; } return o->retval; } if (arg == NULL) { if (argv[opt_index] == NULL) { opt_printf_stderr("%s: Option -%s needs a value\n", prog, o->name); return -1; } arg = argv[opt_index++]; } switch (o->valtype) { default: case 's': case ':': break; case '.': break; case '/': if (opt_isdir(arg) > 0) break; opt_printf_stderr("%s: Not a directory: %s\n", prog, arg); return -1; case '<': break; case '>': break; case 'p': case 'n': case 'N': if (!opt_int(arg, &ival)) return -1; if (o->valtype == 'p' && ival <= 0) { opt_printf_stderr("%s: Non-positive number \"%s\" for option -%s\n", prog, arg, o->name); return -1; } if (o->valtype == 'N' && ival < 0) { opt_printf_stderr("%s: Negative number \"%s\" for option -%s\n", prog, arg, o->name); return -1; } break; case 'M': if (!opt_intmax(arg, &imval)) return -1; break; case 'U': if (!opt_uintmax(arg, &umval)) return -1; break; case 'l': if (!opt_long(arg, &lval)) return -1; break; case 'u': if (!opt_ulong(arg, &ulval)) return -1; break; case 'c': case 'E': case 'F': case 'f': case 'A': case 'a': if (opt_format(arg, o->valtype == 'c' ? OPT_FMT_PDS : o->valtype == 'E' ? OPT_FMT_PDE : o->valtype == 'F' ? OPT_FMT_PEMDER : o->valtype == 'A' ? OPT_FMT_ASN1 : OPT_FMT_ANY, &ival)) break; opt_printf_stderr("%s: Invalid format \"%s\" for option -%s\n", prog, arg, o->name); return -1; } return o->retval; } if (unknown != NULL) { if (dunno != NULL) { opt_printf_stderr("%s: Multiple %s or unknown options: -%s and -%s\n", prog, unknown_name, dunno, p); return -1; } dunno = p; return unknown->retval; } opt_printf_stderr("%s: Unknown option: -%s\n", prog, p); return -1; } char *opt_arg(void) { return arg; } char *opt_flag(void) { return flag; } char *opt_unknown(void) { return dunno; } void reset_unknown(void) { dunno = NULL; } char **opt_rest(void) { return &argv[opt_index]; } int opt_num_rest(void) { int i = 0; char **pp; for (pp = opt_rest(); *pp; pp++, i++) continue; return i; } int opt_check_rest_arg(const char *expected) { char *opt = *opt_rest(); if (opt == NULL || *opt == '\0') { if (expected == NULL) return 1; opt_printf_stderr("%s: Missing argument: %s\n", prog, expected); return 0; } if (expected != NULL) { opt = argv[opt_index + 1]; if (opt == NULL || *opt == '\0') return 1; opt_printf_stderr("%s: Extra argument after %s: \"%s\"\n", prog, expected, opt); return 0; } if (opt_unknown() == NULL) opt_printf_stderr("%s: Extra option: \"%s\"\n", prog, opt); else opt_printf_stderr("%s: Extra (unknown) options: \"%s\" \"%s\"\n", prog, opt_unknown(), opt); return 0; } static const char *valtype2param(const OPTIONS *o) { switch (o->valtype) { case 0: case '-': return ""; case ':': return "uri"; case 's': return "val"; case '/': return "dir"; case '<': return "infile"; case '>': return "outfile"; case 'p': return "+int"; case 'n': return "int"; case 'l': return "long"; case 'u': return "ulong"; case 'E': return "PEM|DER|ENGINE"; case 'F': return "PEM|DER"; case 'f': return "format"; case 'M': return "intmax"; case 'N': return "nonneg"; case 'U': return "uintmax"; } return "parm"; } static void opt_print(const OPTIONS *o, int doingparams, int width) { const char* help; char start[80 + 1]; int linelen, printlen; if (width >= (int)sizeof(start)) width = (int)sizeof(start) - 1; help = o->helpstr ? o->helpstr : "(No additional info)"; if (o->name == OPT_HELP_STR) { opt_printf_stderr(help, prog); return; } else if (o->name == OPT_SECTION_STR) { opt_printf_stderr("\n"); opt_printf_stderr(help, prog); return; } else if (o->name == OPT_PARAM_STR) { opt_printf_stderr("\nParameters:\n"); return; } memset(start, ' ', sizeof(start) - 1); start[sizeof(start) - 1] = '\0'; if (o->name == OPT_MORE_STR) { start[width] = '\0'; opt_printf_stderr("%s %s\n", start, help); return; } linelen = 0; printlen = opt_printf_stderr(" %s", !doingparams ? "-" : ""); linelen += (printlen > 0) ? printlen : MAX_OPT_HELP_WIDTH; printlen = opt_printf_stderr("%s" , o->name[0] ? o->name : "*"); linelen += (printlen > 0) ? printlen : MAX_OPT_HELP_WIDTH; if (o->valtype != '-') { printlen = opt_printf_stderr(" %s" , valtype2param(o)); linelen += (printlen > 0) ? printlen : MAX_OPT_HELP_WIDTH; } if (linelen >= MAX_OPT_HELP_WIDTH || linelen > width) { opt_printf_stderr("%s", "\n"); memset(start, ' ', sizeof(start)); linelen = 0; } width -= linelen; start[width] = '\0'; opt_printf_stderr("%s %s\n", start, help); } void opt_help(const OPTIONS *list) { const OPTIONS *o; int i, sawparams = 0, width = 5; int standard_prolog; standard_prolog = list[0].name != OPT_HELP_STR; for (o = list; o->name; o++) { if (o->name == OPT_MORE_STR) continue; i = 2 + (int)strlen(o->name); if (o->valtype != '-') i += 1 + strlen(valtype2param(o)); if (i > width) width = i; } if (width > MAX_OPT_HELP_WIDTH) width = MAX_OPT_HELP_WIDTH; if (standard_prolog) { opt_printf_stderr("Usage: %s [options]\n", prog); if (list[0].name != OPT_SECTION_STR) opt_printf_stderr("Valid options are:\n", prog); } for (o = list; o->name; o++) { if (o->name == OPT_PARAM_STR) sawparams = 1; opt_print(o, sawparams, width); } } #ifdef _WIN32 # include <windows.h> int opt_isdir(const char *name) { DWORD attr; # if defined(UNICODE) || defined(_UNICODE) size_t i, len_0 = strlen(name) + 1; WCHAR tempname[MAX_PATH]; if (len_0 > MAX_PATH) return -1; # if !defined(_WIN32_WCE) || _WIN32_WCE>=101 if (!MultiByteToWideChar(CP_ACP, 0, name, len_0, tempname, MAX_PATH)) # endif for (i = 0; i < len_0; i++) tempname[i] = (WCHAR)name[i]; attr = GetFileAttributes(tempname); # else attr = GetFileAttributes(name); # endif if (attr == INVALID_FILE_ATTRIBUTES) return -1; return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0); } #else # include <sys/stat.h> # ifndef S_ISDIR # if defined(_S_IFMT) && defined(_S_IFDIR) # define S_ISDIR(a) (((a) & _S_IFMT) == _S_IFDIR) # else # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR) # endif # endif int opt_isdir(const char *name) { # if defined(S_ISDIR) struct stat st; if (stat(name, &st) == 0) return S_ISDIR(st.st_mode); else return -1; # else return -1; # endif } #endif
lib
openssl/apps/lib/opt.c
openssl
#if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS) # define _POSIX_C_SOURCE 2 #endif #include <ctype.h> #include "http_server.h" #include "internal/sockets.h" #include <openssl/err.h> #include <openssl/trace.h> #include <openssl/rand.h> #include "s_apps.h" #include "log.h" #if defined(__TANDEM) # if defined(OPENSSL_TANDEM_FLOSS) # include <floss.h(floss_fork)> # endif #endif #define HTTP_PREFIX "HTTP/" #define HTTP_VERSION_PATT "1." #define HTTP_PREFIX_VERSION HTTP_PREFIX""HTTP_VERSION_PATT #define HTTP_1_0 HTTP_PREFIX_VERSION"0" #define HTTP_VERSION_STR " "HTTP_PREFIX_VERSION #define log_HTTP(prog, level, text) \ trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, "%s", text) #define log_HTTP1(prog, level, fmt, arg) \ trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, fmt, arg) #define log_HTTP2(prog, level, fmt, arg1, arg2) \ trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, fmt, arg1, arg2) #define log_HTTP3(prog, level, fmt, a1, a2, a3) \ trace_log_message(OSSL_TRACE_CATEGORY_HTTP, prog, level, fmt, a1, a2, a3) #ifdef HTTP_DAEMON int n_responders = 0; int acfd = (int)INVALID_SOCKET; void socket_timeout(int signum) { if (acfd != (int)INVALID_SOCKET) (void)shutdown(acfd, SHUT_RD); } static void killall(int ret, pid_t *kidpids) { int i; for (i = 0; i < n_responders; ++i) if (kidpids[i] != 0) (void)kill(kidpids[i], SIGTERM); OPENSSL_free(kidpids); OSSL_sleep(1000); exit(ret); } static int termsig = 0; static void noteterm(int sig) { termsig = sig; } void spawn_loop(const char *prog) { pid_t *kidpids = NULL; int status; int procs = 0; int i; openlog(prog, LOG_PID, LOG_DAEMON); if (setpgid(0, 0)) { log_HTTP1(prog, LOG_CRIT, "error detaching from parent process group: %s", strerror(errno)); exit(1); } kidpids = app_malloc(n_responders * sizeof(*kidpids), "child PID array"); for (i = 0; i < n_responders; ++i) kidpids[i] = 0; signal(SIGINT, noteterm); signal(SIGTERM, noteterm); while (termsig == 0) { pid_t fpid; while (termsig == 0 && procs >= n_responders) { if ((fpid = waitpid(-1, &status, 0)) > 0) { for (i = 0; i < procs; ++i) { if (kidpids[i] == fpid) { kidpids[i] = 0; --procs; break; } } if (i >= n_responders) { log_HTTP1(prog, LOG_CRIT, "internal error: no matching child slot for pid: %ld", (long)fpid); killall(1, kidpids); } if (status != 0) { if (WIFEXITED(status)) { log_HTTP2(prog, LOG_WARNING, "child process: %ld, exit status: %d", (long)fpid, WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { char *dumped = ""; # ifdef WCOREDUMP if (WCOREDUMP(status)) dumped = " (core dumped)"; # endif log_HTTP3(prog, LOG_WARNING, "child process: %ld, term signal %d%s", (long)fpid, WTERMSIG(status), dumped); } OSSL_sleep(1000); } break; } else if (errno != EINTR) { log_HTTP1(prog, LOG_CRIT, "waitpid() failed: %s", strerror(errno)); killall(1, kidpids); } } if (termsig) break; switch (fpid = fork()) { case -1: OSSL_sleep(30000); break; case 0: OPENSSL_free(kidpids); signal(SIGINT, SIG_DFL); signal(SIGTERM, SIG_DFL); if (termsig) _exit(0); if (RAND_poll() <= 0) { log_HTTP(prog, LOG_CRIT, "RAND_poll() failed"); _exit(1); } return; default: for (i = 0; i < n_responders; ++i) { if (kidpids[i] == 0) { kidpids[i] = fpid; procs++; break; } } if (i >= n_responders) { log_HTTP(prog, LOG_CRIT, "internal error: no free child slots"); killall(1, kidpids); } break; } } log_HTTP1(prog, LOG_INFO, "terminating on signal: %d", termsig); killall(0, kidpids); } #endif #ifndef OPENSSL_NO_SOCK BIO *http_server_init(const char *prog, const char *port, int verb) { BIO *acbio = NULL, *bufbio; int asock; int port_num; char name[40]; snprintf(name, sizeof(name), "*:%s", port); if (verb >= 0 && !log_set_verbosity(prog, verb)) return NULL; bufbio = BIO_new(BIO_f_buffer()); if (bufbio == NULL) goto err; acbio = BIO_new(BIO_s_accept()); if (acbio == NULL || BIO_set_bind_mode(acbio, BIO_BIND_REUSEADDR) < 0 || BIO_set_accept_name(acbio, name) < 0) { log_HTTP(prog, LOG_ERR, "error setting up accept BIO"); goto err; } BIO_set_accept_bios(acbio, bufbio); bufbio = NULL; if (BIO_do_accept(acbio) <= 0) { log_HTTP1(prog, LOG_ERR, "error setting accept on port %s", port); goto err; } BIO_get_fd(acbio, &asock); port_num = report_server_accept(bio_out, asock, 1, 1); if (port_num == 0) { log_HTTP(prog, LOG_ERR, "error printing ACCEPT string"); goto err; } return acbio; err: ERR_print_errors(bio_err); BIO_free_all(acbio); BIO_free(bufbio); return NULL; } static int urldecode(char *p) { unsigned char *out = (unsigned char *)p; unsigned char *save = out; for (; *p; p++) { if (*p != '%') { *out++ = *p; } else if (isxdigit(_UC(p[1])) && isxdigit(_UC(p[2]))) { *out++ = (OPENSSL_hexchar2int(p[1]) << 4) | OPENSSL_hexchar2int(p[2]); p += 2; } else { return -1; } } *out = '\0'; return (int)(out - save); } int http_server_get_asn1_req(const ASN1_ITEM *it, ASN1_VALUE **preq, char **ppath, BIO **pcbio, BIO *acbio, int *found_keep_alive, const char *prog, int accept_get, int timeout) { BIO *cbio = *pcbio, *getbio = NULL, *b64 = NULL; int len; char reqbuf[2048], inbuf[2048]; char *meth, *url, *end; ASN1_VALUE *req; int ret = 0; *preq = NULL; if (ppath != NULL) *ppath = NULL; if (cbio == NULL) { char *port; get_sock_info_address(BIO_get_fd(acbio, NULL), NULL, &port); if (port == NULL) { log_HTTP(prog, LOG_ERR, "cannot get port listening on"); goto fatal; } log_HTTP1(prog, LOG_DEBUG, "awaiting new connection on port %s ...", port); OPENSSL_free(port); if (BIO_do_accept(acbio) <= 0) return ret; *pcbio = cbio = BIO_pop(acbio); } else { log_HTTP(prog, LOG_DEBUG, "awaiting next request ..."); } if (cbio == NULL) { ret = -1; goto out; } # ifdef HTTP_DAEMON if (timeout > 0) { (void)BIO_get_fd(cbio, &acfd); alarm(timeout); } # endif len = BIO_gets(cbio, reqbuf, sizeof(reqbuf)); if (len == 0) return ret; ret = 1; if (len < 0) { log_HTTP(prog, LOG_WARNING, "request line read error"); (void)http_server_send_status(prog, cbio, 400, "Bad Request"); goto out; } if (((end = strchr(reqbuf, '\r')) != NULL && end[1] == '\n') || (end = strchr(reqbuf, '\n')) != NULL) *end = '\0'; if (log_get_verbosity() < LOG_TRACE) trace_log_message(-1, prog, LOG_INFO, "received request, 1st line: %s", reqbuf); log_HTTP(prog, LOG_TRACE, "received request header:"); log_HTTP1(prog, LOG_TRACE, "%s", reqbuf); if (end == NULL) { log_HTTP(prog, LOG_WARNING, "cannot parse HTTP header: missing end of line"); (void)http_server_send_status(prog, cbio, 400, "Bad Request"); goto out; } url = meth = reqbuf; if ((accept_get && CHECK_AND_SKIP_PREFIX(url, "GET ")) || CHECK_AND_SKIP_PREFIX(url, "POST ")) { url[-1] = '\0'; while (*url == ' ') url++; if (*url != '/') { log_HTTP2(prog, LOG_WARNING, "invalid %s -- URL does not begin with '/': %s", meth, url); (void)http_server_send_status(prog, cbio, 400, "Bad Request"); goto out; } url++; for (end = url; *end != '\0'; end++) if (*end == ' ') break; if (!HAS_PREFIX(end, HTTP_VERSION_STR)) { log_HTTP2(prog, LOG_WARNING, "invalid %s -- bad HTTP/version string: %s", meth, end + 1); (void)http_server_send_status(prog, cbio, 400, "Bad Request"); goto out; } *end = '\0'; if (found_keep_alive != NULL) *found_keep_alive = end[sizeof(HTTP_VERSION_STR) - 1] > '0'; if (strlen(meth) == 3 && url[0] == '\0') { (void)http_server_send_status(prog, cbio, 200, "OK"); goto out; } len = urldecode(url); if (len < 0) { log_HTTP2(prog, LOG_WARNING, "invalid %s request -- bad URL encoding: %s", meth, url); (void)http_server_send_status(prog, cbio, 400, "Bad Request"); goto out; } if (strlen(meth) == 3) { if ((getbio = BIO_new_mem_buf(url, len)) == NULL || (b64 = BIO_new(BIO_f_base64())) == NULL) { log_HTTP1(prog, LOG_ERR, "could not allocate base64 bio with size = %d", len); goto fatal; } BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); getbio = BIO_push(b64, getbio); } } else { log_HTTP2(prog, LOG_WARNING, "HTTP request does not begin with %sPOST: %s", accept_get ? "GET or " : "", reqbuf); (void)http_server_send_status(prog, cbio, 400, "Bad Request"); goto out; } while (*url == '/') url++; while (end >= url + 2 && end[-2] == '/' && end[-1] == '/') end--; *end = '\0'; for (;;) { char *key, *value; len = BIO_gets(cbio, inbuf, sizeof(inbuf)); if (len <= 0) { log_HTTP(prog, LOG_WARNING, "error reading HTTP header"); (void)http_server_send_status(prog, cbio, 400, "Bad Request"); goto out; } if (((end = strchr(inbuf, '\r')) != NULL && end[1] == '\n') || (end = strchr(inbuf, '\n')) != NULL) *end = '\0'; log_HTTP1(prog, LOG_TRACE, "%s", *inbuf == '\0' ? " " : inbuf); if (end == NULL) { log_HTTP(prog, LOG_WARNING, "error parsing HTTP header: missing end of line"); (void)http_server_send_status(prog, cbio, 400, "Bad Request"); goto out; } if (inbuf[0] == '\0') break; key = inbuf; value = strchr(key, ':'); if (value == NULL) { log_HTTP(prog, LOG_WARNING, "error parsing HTTP header: missing ':'"); (void)http_server_send_status(prog, cbio, 400, "Bad Request"); goto out; } *(value++) = '\0'; while (*value == ' ') value++; if (found_keep_alive != NULL && OPENSSL_strcasecmp(key, "Connection") == 0) { if (OPENSSL_strcasecmp(value, "keep-alive") == 0) *found_keep_alive = 1; else if (OPENSSL_strcasecmp(value, "close") == 0) *found_keep_alive = 0; } } # ifdef HTTP_DAEMON alarm(0); timeout = 0; # endif req = ASN1_item_d2i_bio(it, getbio != NULL ? getbio : cbio, NULL); if (req == NULL) { log_HTTP(prog, LOG_WARNING, "error parsing DER-encoded request content"); (void)http_server_send_status(prog, cbio, 400, "Bad Request"); } else if (ppath != NULL && (*ppath = OPENSSL_strdup(url)) == NULL) { log_HTTP1(prog, LOG_ERR, "out of memory allocating %zu bytes", strlen(url) + 1); ASN1_item_free(req, it); goto fatal; } *preq = req; out: BIO_free_all(getbio); # ifdef HTTP_DAEMON if (timeout > 0) alarm(0); acfd = (int)INVALID_SOCKET; # endif return ret; fatal: (void)http_server_send_status(prog, cbio, 500, "Internal Server Error"); if (ppath != NULL) { OPENSSL_free(*ppath); *ppath = NULL; } BIO_free_all(cbio); *pcbio = NULL; ret = -1; goto out; } int http_server_send_asn1_resp(const char *prog, BIO *cbio, int keep_alive, const char *content_type, const ASN1_ITEM *it, const ASN1_VALUE *resp) { char buf[200], *p; int ret = BIO_snprintf(buf, sizeof(buf), HTTP_1_0" 200 OK\r\n%s" "Content-type: %s\r\n" "Content-Length: %d\r\n", keep_alive ? "Connection: keep-alive\r\n" : "", content_type, ASN1_item_i2d(resp, NULL, it)); if (ret < 0 || (size_t)ret >= sizeof(buf)) return 0; if (log_get_verbosity() < LOG_TRACE && (p = strchr(buf, '\r')) != NULL) trace_log_message(-1, prog, LOG_INFO, "sending response, 1st line: %.*s", (int)(p - buf), buf); log_HTTP1(prog, LOG_TRACE, "sending response header:\n%s", buf); ret = BIO_printf(cbio, "%s\r\n", buf) > 0 && ASN1_item_i2d_bio(it, cbio, resp) > 0; (void)BIO_flush(cbio); return ret; } int http_server_send_status(const char *prog, BIO *cbio, int status, const char *reason) { char buf[200]; int ret = BIO_snprintf(buf, sizeof(buf), HTTP_1_0" %d %s\r\n\r\n", status, reason); if (ret < 0 || (size_t)ret >= sizeof(buf)) return 0; log_HTTP1(prog, LOG_TRACE, "sending response header:\n%s", buf); ret = BIO_printf(cbio, "%s\r\n", buf) > 0; (void)BIO_flush(cbio); return ret; } #endif
lib
openssl/apps/lib/http_server.c
openssl
#include "app_libctx.h" #include "apps.h" static OSSL_LIB_CTX *app_libctx = NULL; static const char *app_propq = NULL; int app_set_propq(const char *arg) { app_propq = arg; return 1; } const char *app_get0_propq(void) { return app_propq; } OSSL_LIB_CTX *app_get0_libctx(void) { return app_libctx; } OSSL_LIB_CTX *app_create_libctx(void) { if (app_libctx == NULL) { if (!app_provider_load(NULL, "null")) { opt_printf_stderr("Failed to create null provider\n"); return NULL; } app_libctx = OSSL_LIB_CTX_new(); } if (app_libctx == NULL) opt_printf_stderr("Failed to create library context\n"); return app_libctx; }
lib
openssl/apps/lib/app_libctx.c
openssl
#include <string.h> #include <stdio.h> #include <openssl/crypto.h> #include <openssl/core_names.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/cmac.h> #include <openssl/params.h> static unsigned char key[] = { 0x6c, 0xde, 0x14, 0xf5, 0xd5, 0x2a, 0x4a, 0xdf, 0x12, 0x39, 0x1e, 0xbf, 0x36, 0xf9, 0x6a, 0x46, 0x48, 0xd0, 0xb6, 0x51, 0x89, 0xfc, 0x24, 0x85, 0xa8, 0x8d, 0xdf, 0x7e, 0x80, 0x14, 0xc8, 0xce, }; static const unsigned char data[] = "To be, or not to be, that is the question,\n" "Whether tis nobler in the minde to suffer\n" "The ſlings and arrowes of outragious fortune,\n" "Or to take Armes again in a sea of troubles,\n" "And by opposing, end them, to die to sleep;\n" "No more, and by a sleep, to say we end\n" "The heart-ache, and the thousand natural shocks\n" "That flesh is heir to? tis a consumation\n" "Devoutly to be wished. To die to sleep,\n" "To sleepe, perchance to dreame, Aye, there's the rub,\n" "For in that sleep of death what dreams may come\n" "When we haue shuffled off this mortal coil\n" "Must give us pause. There's the respect\n" "That makes calamity of so long life:\n" "For who would bear the Ships and Scorns of time,\n" "The oppressor's wrong, the proud man's Contumely,\n" "The pangs of dispised love, the Law's delay,\n" ; static const unsigned char expected_output[] = { 0x67, 0x92, 0x32, 0x23, 0x50, 0x3d, 0xc5, 0xba, 0x78, 0xd4, 0x6d, 0x63, 0xf2, 0x2b, 0xe9, 0x56, }; static const char *propq = NULL; int main(void) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *library_context = NULL; EVP_MAC *mac = NULL; EVP_MAC_CTX *mctx = NULL; unsigned char *out = NULL; size_t out_len = 0; OSSL_PARAM params[4], *p = params; char cipher_name[] = "AES-256-CBC"; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto end; } mac = EVP_MAC_fetch(library_context, "CMAC", propq); if (mac == NULL) { fprintf(stderr, "EVP_MAC_fetch() returned NULL\n"); goto end; } mctx = EVP_MAC_CTX_new(mac); if (mctx == NULL) { fprintf(stderr, "EVP_MAC_CTX_new() returned NULL\n"); goto end; } *p++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_CIPHER, cipher_name, sizeof(cipher_name)); *p = OSSL_PARAM_construct_end(); if (!EVP_MAC_init(mctx, key, sizeof(key), params)) { fprintf(stderr, "EVP_MAC_init() failed\n"); goto end; } if (!EVP_MAC_update(mctx, data, sizeof(data))) { fprintf(stderr, "EVP_MAC_update() failed\n"); goto end; } if (!EVP_MAC_final(mctx, NULL, &out_len, 0)) { fprintf(stderr, "EVP_MAC_final() failed\n"); goto end; } out = OPENSSL_malloc(out_len); if (out == NULL) { fprintf(stderr, "malloc failed\n"); goto end; } if (!EVP_MAC_final(mctx, out, &out_len, out_len)) { fprintf(stderr, "EVP_MAC_final() failed\n"); goto end; } printf("Generated MAC:\n"); BIO_dump_indent_fp(stdout, out, out_len, 2); putchar('\n'); if (out_len != sizeof(expected_output)) { fprintf(stderr, "Generated MAC has an unexpected length\n"); goto end; } if (CRYPTO_memcmp(expected_output, out, sizeof(expected_output)) != 0) { fprintf(stderr, "Generated MAC does not match expected value\n"); goto end; } ret = EXIT_SUCCESS; end: if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); OPENSSL_free(out); EVP_MAC_CTX_free(mctx); EVP_MAC_free(mac); OSSL_LIB_CTX_free(library_context); return ret; }
mac
openssl/demos/mac/cmac-aes256.c
openssl
#include <stdio.h> #include <stdlib.h> #include <openssl/core_names.h> #include <openssl/evp.h> #include <openssl/params.h> #include <openssl/err.h> static unsigned char key[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f }; static unsigned char data[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e }; static const unsigned char expected_output[] = { 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1 }; static char *propq = NULL; int main(int argc, char **argv) { int ret = EXIT_FAILURE; EVP_MAC *mac = NULL; EVP_MAC_CTX *mctx = NULL; unsigned char out[8]; OSSL_PARAM params[4], *p = params; OSSL_LIB_CTX *library_context = NULL; unsigned int digest_len = 8, c_rounds = 2, d_rounds = 4; size_t out_len = 0; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto end; } mac = EVP_MAC_fetch(library_context, "SIPHASH", propq); if (mac == NULL) { fprintf(stderr, "EVP_MAC_fetch() returned NULL\n"); goto end; } mctx = EVP_MAC_CTX_new(mac); if (mctx == NULL) { fprintf(stderr, "EVP_MAC_CTX_new() returned NULL\n"); goto end; } *p++ = OSSL_PARAM_construct_uint(OSSL_MAC_PARAM_SIZE, &digest_len); *p++ = OSSL_PARAM_construct_uint(OSSL_MAC_PARAM_C_ROUNDS, &c_rounds); *p++ = OSSL_PARAM_construct_uint(OSSL_MAC_PARAM_D_ROUNDS, &d_rounds); *p = OSSL_PARAM_construct_end(); if (!EVP_MAC_init(mctx, key, sizeof(key), params)) { fprintf(stderr, "EVP_MAC_init() failed\n"); goto end; } if (!EVP_MAC_update(mctx, data, sizeof(data))) { fprintf(stderr, "EVP_MAC_update() failed\n"); goto end; } if (!EVP_MAC_final(mctx, out, &out_len, sizeof(out))) { fprintf(stderr, "EVP_MAC_final() failed\n"); goto end; } printf("Generated MAC:\n"); BIO_dump_indent_fp(stdout, out, out_len, 2); putchar('\n'); if (out_len != sizeof(expected_output)) { fprintf(stderr, "Generated MAC has an unexpected length\n"); goto end; } if (CRYPTO_memcmp(expected_output, out, sizeof(expected_output)) != 0) { fprintf(stderr, "Generated MAC does not match expected value\n"); goto end; } ret = EXIT_SUCCESS; end: EVP_MAC_CTX_free(mctx); EVP_MAC_free(mac); OSSL_LIB_CTX_free(library_context); if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); return ret; }
mac
openssl/demos/mac/siphash.c
openssl
#include <string.h> #include <stdio.h> #include <openssl/crypto.h> #include <openssl/core_names.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/hmac.h> #include <openssl/params.h> static unsigned char key[] = { 0x25, 0xfd, 0x12, 0x99, 0xdf, 0xad, 0x1a, 0x03, 0x0a, 0x81, 0x3c, 0x2d, 0xcc, 0x05, 0xd1, 0x5c, 0x17, 0x7a, 0x36, 0x73, 0x17, 0xef, 0x41, 0x75, 0x71, 0x18, 0xe0, 0x1a, 0xda, 0x99, 0xc3, 0x61, 0x38, 0xb5, 0xb1, 0xe0, 0x82, 0x2c, 0x70, 0xa4, 0xc0, 0x8e, 0x5e, 0xf9, 0x93, 0x9f, 0xcf, 0xf7, 0x32, 0x4d, 0x0c, 0xbd, 0x31, 0x12, 0x0f, 0x9a, 0x15, 0xee, 0x82, 0xdb, 0x8d, 0x29, 0x54, 0x14, }; static const unsigned char data[] = "To be, or not to be, that is the question,\n" "Whether tis nobler in the minde to suffer\n" "The ſlings and arrowes of outragious fortune,\n" "Or to take Armes again in a sea of troubles,\n" "And by opposing, end them, to die to sleep;\n" "No more, and by a sleep, to say we end\n" "The heart-ache, and the thousand natural shocks\n" "That flesh is heir to? tis a consumation\n" "Devoutly to be wished. To die to sleep,\n" "To sleepe, perchance to dreame, Aye, there's the rub,\n" "For in that sleep of death what dreams may come\n" "When we haue shuffled off this mortal coil\n" "Must give us pause. There's the respect\n" "That makes calamity of so long life:\n" "For who would bear the Ships and Scorns of time,\n" "The oppressor's wrong, the proud man's Contumely,\n" "The pangs of dispised love, the Law's delay,\n" ; static const unsigned char expected_output[] = { 0x3b, 0x77, 0x5f, 0xf1, 0x4f, 0x9e, 0xb9, 0x23, 0x8f, 0xdc, 0xa0, 0x68, 0x15, 0x7b, 0x8a, 0xf1, 0x96, 0x23, 0xaa, 0x3c, 0x1f, 0xe9, 0xdc, 0x89, 0x11, 0x7d, 0x58, 0x07, 0xe7, 0x96, 0x17, 0xe3, 0x44, 0x8b, 0x03, 0x37, 0x91, 0xc0, 0x6e, 0x06, 0x7c, 0x54, 0xe4, 0xa4, 0xcc, 0xd5, 0x16, 0xbb, 0x5e, 0x4d, 0x64, 0x7d, 0x88, 0x23, 0xc9, 0xb7, 0x25, 0xda, 0xbe, 0x4b, 0xe4, 0xd5, 0x34, 0x30, }; static const char *propq = NULL; int main(void) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *library_context = NULL; EVP_MAC *mac = NULL; EVP_MAC_CTX *mctx = NULL; EVP_MD_CTX *digest_context = NULL; unsigned char *out = NULL; size_t out_len = 0; OSSL_PARAM params[4], *p = params; char digest_name[] = "SHA3-512"; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto end; } mac = EVP_MAC_fetch(library_context, "HMAC", propq); if (mac == NULL) { fprintf(stderr, "EVP_MAC_fetch() returned NULL\n"); goto end; } mctx = EVP_MAC_CTX_new(mac); if (mctx == NULL) { fprintf(stderr, "EVP_MAC_CTX_new() returned NULL\n"); goto end; } *p++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST, digest_name, sizeof(digest_name)); *p = OSSL_PARAM_construct_end(); if (!EVP_MAC_init(mctx, key, sizeof(key), params)) { fprintf(stderr, "EVP_MAC_init() failed\n"); goto end; } if (!EVP_MAC_update(mctx, data, sizeof(data))) { fprintf(stderr, "EVP_MAC_update() failed\n"); goto end; } if (!EVP_MAC_final(mctx, NULL, &out_len, 0)) { fprintf(stderr, "EVP_MAC_final() failed\n"); goto end; } out = OPENSSL_malloc(out_len); if (out == NULL) { fprintf(stderr, "malloc failed\n"); goto end; } if (!EVP_MAC_final(mctx, out, &out_len, out_len)) { fprintf(stderr, "EVP_MAC_final() failed\n"); goto end; } printf("Generated MAC:\n"); BIO_dump_indent_fp(stdout, out, out_len, 2); putchar('\n'); if (out_len != sizeof(expected_output)) { fprintf(stderr, "Generated MAC has an unexpected length\n"); goto end; } if (CRYPTO_memcmp(expected_output, out, sizeof(expected_output)) != 0) { fprintf(stderr, "Generated MAC does not match expected value\n"); goto end; } ret = EXIT_SUCCESS; end: if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); OPENSSL_free(out); EVP_MD_CTX_free(digest_context); EVP_MAC_CTX_free(mctx); EVP_MAC_free(mac); OSSL_LIB_CTX_free(library_context); return ret; }
mac
openssl/demos/mac/hmac-sha512.c
openssl
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/core_names.h> #include <openssl/evp.h> #include <openssl/params.h> #include <openssl/err.h> static const unsigned char test_r[] = { 0x85, 0x1f, 0xc4, 0x0c, 0x34, 0x67, 0xac, 0x0b, 0xe0, 0x5c, 0xc2, 0x04, 0x04, 0xf3, 0xf7, 0x00 }; static const unsigned char test_k[] = { 0xec, 0x07, 0x4c, 0x83, 0x55, 0x80, 0x74, 0x17, 0x01, 0x42, 0x5b, 0x62, 0x32, 0x35, 0xad, 0xd6 }; static const unsigned char test_n[] = { 0xfb, 0x44, 0x73, 0x50, 0xc4, 0xe8, 0x68, 0xc5, 0x2a, 0xc3, 0x27, 0x5c, 0xf9, 0xd4, 0x32, 0x7e }; static const unsigned char test_m[] = { 0xf3, 0xf6 }; static const unsigned char expected_output[] = { 0xf4, 0xc6, 0x33, 0xc3, 0x04, 0x4f, 0xc1, 0x45, 0xf8, 0x4f, 0x33, 0x5c, 0xb8, 0x19, 0x53, 0xde }; static char *propq = NULL; int main(int argc, char **argv) { int ret = EXIT_FAILURE; EVP_CIPHER *aes = NULL; EVP_CIPHER_CTX *aesctx = NULL; EVP_MAC *mac = NULL; EVP_MAC_CTX *mctx = NULL; unsigned char composite_key[32]; unsigned char out[16]; OSSL_LIB_CTX *library_context = NULL; size_t out_len = 0; int aes_len = 0; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto end; } mac = EVP_MAC_fetch(library_context, "POLY1305", propq); if (mac == NULL) { fprintf(stderr, "EVP_MAC_fetch() returned NULL\n"); goto end; } mctx = EVP_MAC_CTX_new(mac); if (mctx == NULL) { fprintf(stderr, "EVP_MAC_CTX_new() returned NULL\n"); goto end; } aes = EVP_CIPHER_fetch(library_context, "AES-128-ECB", propq); if (aes == NULL) { fprintf(stderr, "EVP_CIPHER_fetch() returned NULL\n"); goto end; } aesctx = EVP_CIPHER_CTX_new(); if (aesctx == NULL) { fprintf(stderr, "EVP_CIPHER_CTX_new() returned NULL\n"); goto end; } if (!EVP_EncryptInit_ex(aesctx, aes, NULL, test_k, NULL)) { fprintf(stderr, "EVP_EncryptInit_ex() failed\n"); goto end; } if (!EVP_CIPHER_CTX_set_padding(aesctx, 0)) { fprintf(stderr, "EVP_CIPHER_CTX_set_padding() failed\n"); goto end; } if (!EVP_EncryptUpdate(aesctx, composite_key + 16, &aes_len, test_n, sizeof(test_n))) { fprintf(stderr, "EVP_EncryptUpdate() failed\n"); goto end; } memcpy(composite_key, test_r, 16); if (!EVP_MAC_init(mctx, composite_key, sizeof(composite_key), NULL)) { fprintf(stderr, "EVP_MAC_init() failed\n"); goto end; } if (!EVP_MAC_update(mctx, test_m, sizeof(test_m))) { fprintf(stderr, "EVP_MAC_update() failed\n"); goto end; } if (!EVP_MAC_final(mctx, out, &out_len, sizeof(out))) { fprintf(stderr, "EVP_MAC_final() failed\n"); goto end; } printf("Generated MAC:\n"); BIO_dump_indent_fp(stdout, out, out_len, 2); putchar('\n'); if (out_len != sizeof(expected_output)) { fprintf(stderr, "Generated MAC has an unexpected length\n"); goto end; } if (CRYPTO_memcmp(expected_output, out, sizeof(expected_output)) != 0) { fprintf(stderr, "Generated MAC does not match expected value\n"); goto end; } ret = EXIT_SUCCESS; end: EVP_CIPHER_CTX_free(aesctx); EVP_CIPHER_free(aes); EVP_MAC_CTX_free(mctx); EVP_MAC_free(mac); OSSL_LIB_CTX_free(library_context); if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); return ret; }
mac
openssl/demos/mac/poly1305.c
openssl
#include <stdio.h> #include <stdlib.h> #include <openssl/core_names.h> #include <openssl/evp.h> #include <openssl/params.h> #include <openssl/err.h> static unsigned char key[] = { 0x77, 0xbe, 0x63, 0x70, 0x89, 0x71, 0xc4, 0xe2, 0x40, 0xd1, 0xcb, 0x79, 0xe8, 0xd7, 0x7f, 0xeb }; static unsigned char iv[] = { 0xe0, 0xe0, 0x0f, 0x19, 0xfe, 0xd7, 0xba, 0x01, 0x36, 0xa7, 0x97, 0xf3 }; static unsigned char data[] = { 0x7a, 0x43, 0xec, 0x1d, 0x9c, 0x0a, 0x5a, 0x78, 0xa0, 0xb1, 0x65, 0x33, 0xa6, 0x21, 0x3c, 0xab }; static const unsigned char expected_output[] = { 0x20, 0x9f, 0xcc, 0x8d, 0x36, 0x75, 0xed, 0x93, 0x8e, 0x9c, 0x71, 0x66, 0x70, 0x9d, 0xd9, 0x46 }; static char *propq = NULL; int main(int argc, char **argv) { int ret = EXIT_FAILURE; EVP_MAC *mac = NULL; EVP_MAC_CTX *mctx = NULL; unsigned char out[16]; OSSL_PARAM params[4], *p = params; OSSL_LIB_CTX *library_context = NULL; size_t out_len = 0; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto end; } mac = EVP_MAC_fetch(library_context, "GMAC", propq); if (mac == NULL) { fprintf(stderr, "EVP_MAC_fetch() returned NULL\n"); goto end; } mctx = EVP_MAC_CTX_new(mac); if (mctx == NULL) { fprintf(stderr, "EVP_MAC_CTX_new() returned NULL\n"); goto end; } *p++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_CIPHER, "AES-128-GCM", 0); if (propq != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_PROPERTIES, propq, 0); *p++ = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_IV, iv, sizeof(iv)); *p = OSSL_PARAM_construct_end(); if (!EVP_MAC_init(mctx, key, sizeof(key), params)) { fprintf(stderr, "EVP_MAC_init() failed\n"); goto end; } if (!EVP_MAC_update(mctx, data, sizeof(data))) { fprintf(stderr, "EVP_MAC_update() failed\n"); goto end; } if (!EVP_MAC_final(mctx, out, &out_len, sizeof(out))) { fprintf(stderr, "EVP_MAC_final() failed\n"); goto end; } printf("Generated MAC:\n"); BIO_dump_indent_fp(stdout, out, out_len, 2); putchar('\n'); if (out_len != sizeof(expected_output)) { fprintf(stderr, "Generated MAC has an unexpected length\n"); goto end; } if (CRYPTO_memcmp(expected_output, out, sizeof(expected_output)) != 0) { fprintf(stderr, "Generated MAC does not match expected value\n"); goto end; } ret = EXIT_SUCCESS; end: EVP_MAC_CTX_free(mctx); EVP_MAC_free(mac); OSSL_LIB_CTX_free(library_context); if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); return ret; }
mac
openssl/demos/mac/gmac.c
openssl
#include <stdio.h> #include <stdlib.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/decoder.h> #include <openssl/core_names.h> #include "rsa_encrypt.h" static const unsigned char msg[] = "To be, or not to be, that is the question,\n" "Whether tis nobler in the minde to suffer\n" "The slings and arrowes of outragious fortune,\n" "Or to take Armes again in a sea of troubles"; static EVP_PKEY *get_key(OSSL_LIB_CTX *libctx, const char *propq, int public) { OSSL_DECODER_CTX *dctx = NULL; EVP_PKEY *pkey = NULL; int selection; const unsigned char *data; size_t data_len; if (public) { selection = EVP_PKEY_PUBLIC_KEY; data = pub_key_der; data_len = sizeof(pub_key_der); } else { selection = EVP_PKEY_KEYPAIR; data = priv_key_der; data_len = sizeof(priv_key_der); } dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", NULL, "RSA", selection, libctx, propq); (void)OSSL_DECODER_from_data(dctx, &data, &data_len); OSSL_DECODER_CTX_free(dctx); return pkey; } static void set_optional_params(OSSL_PARAM *p, const char *propq) { static unsigned char label[] = "label"; *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_PAD_MODE, OSSL_PKEY_RSA_PAD_MODE_OAEP, 0); *p++ = OSSL_PARAM_construct_octet_string(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL, label, sizeof(label)); *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST, "SHA256", 0); if (propq != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST_PROPS, (char *)propq, 0); *p = OSSL_PARAM_construct_end(); } static int do_encrypt(OSSL_LIB_CTX *libctx, const unsigned char *in, size_t in_len, unsigned char **out, size_t *out_len) { int ret = 0, public = 1; size_t buf_len = 0; unsigned char *buf = NULL; const char *propq = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pub_key = NULL; OSSL_PARAM params[5]; pub_key = get_key(libctx, propq, public); if (pub_key == NULL) { fprintf(stderr, "Get public key failed.\n"); goto cleanup; } ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pub_key, propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed.\n"); goto cleanup; } set_optional_params(params, propq); if (EVP_PKEY_encrypt_init_ex(ctx, params) <= 0) { fprintf(stderr, "EVP_PKEY_encrypt_init_ex() failed.\n"); goto cleanup; } if (EVP_PKEY_encrypt(ctx, NULL, &buf_len, in, in_len) <= 0) { fprintf(stderr, "EVP_PKEY_encrypt() failed.\n"); goto cleanup; } buf = OPENSSL_zalloc(buf_len); if (buf == NULL) { fprintf(stderr, "Malloc failed.\n"); goto cleanup; } if (EVP_PKEY_encrypt(ctx, buf, &buf_len, in, in_len) <= 0) { fprintf(stderr, "EVP_PKEY_encrypt() failed.\n"); goto cleanup; } *out_len = buf_len; *out = buf; fprintf(stdout, "Encrypted:\n"); BIO_dump_indent_fp(stdout, buf, buf_len, 2); fprintf(stdout, "\n"); ret = 1; cleanup: if (!ret) OPENSSL_free(buf); EVP_PKEY_free(pub_key); EVP_PKEY_CTX_free(ctx); return ret; } static int do_decrypt(OSSL_LIB_CTX *libctx, const unsigned char *in, size_t in_len, unsigned char **out, size_t *out_len) { int ret = 0, public = 0; size_t buf_len = 0; unsigned char *buf = NULL; const char *propq = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *priv_key = NULL; OSSL_PARAM params[5]; priv_key = get_key(libctx, propq, public); if (priv_key == NULL) { fprintf(stderr, "Get private key failed.\n"); goto cleanup; } ctx = EVP_PKEY_CTX_new_from_pkey(libctx, priv_key, propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed.\n"); goto cleanup; } set_optional_params(params, propq); if (EVP_PKEY_decrypt_init_ex(ctx, params) <= 0) { fprintf(stderr, "EVP_PKEY_decrypt_init_ex() failed.\n"); goto cleanup; } if (EVP_PKEY_decrypt(ctx, NULL, &buf_len, in, in_len) <= 0) { fprintf(stderr, "EVP_PKEY_decrypt() failed.\n"); goto cleanup; } buf = OPENSSL_zalloc(buf_len); if (buf == NULL) { fprintf(stderr, "Malloc failed.\n"); goto cleanup; } if (EVP_PKEY_decrypt(ctx, buf, &buf_len, in, in_len) <= 0) { fprintf(stderr, "EVP_PKEY_decrypt() failed.\n"); goto cleanup; } *out_len = buf_len; *out = buf; fprintf(stdout, "Decrypted:\n"); BIO_dump_indent_fp(stdout, buf, buf_len, 2); fprintf(stdout, "\n"); ret = 1; cleanup: if (!ret) OPENSSL_free(buf); EVP_PKEY_free(priv_key); EVP_PKEY_CTX_free(ctx); return ret; } int main(void) { int ret = EXIT_FAILURE; size_t msg_len = sizeof(msg) - 1; size_t encrypted_len = 0, decrypted_len = 0; unsigned char *encrypted = NULL, *decrypted = NULL; OSSL_LIB_CTX *libctx = NULL; if (!do_encrypt(libctx, msg, msg_len, &encrypted, &encrypted_len)) { fprintf(stderr, "encryption failed.\n"); goto cleanup; } if (!do_decrypt(libctx, encrypted, encrypted_len, &decrypted, &decrypted_len)) { fprintf(stderr, "decryption failed.\n"); goto cleanup; } if (CRYPTO_memcmp(msg, decrypted, decrypted_len) != 0) { fprintf(stderr, "Decrypted data does not match expected value\n"); goto cleanup; } ret = EXIT_SUCCESS; cleanup: OPENSSL_free(decrypted); OPENSSL_free(encrypted); OSSL_LIB_CTX_free(libctx); if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); return ret; }
encrypt
openssl/demos/encrypt/rsa_encrypt.c
openssl
#include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/core_names.h> static const unsigned char hamlet[] = "To be, or not to be, that is the question,\n" "Whether tis nobler in the minde to suffer\n" "The slings and arrowes of outragious fortune,\n" "Or to take Armes again in a sea of troubles,\n"; static int demo_sign(EVP_PKEY *priv, const unsigned char *tbs, size_t tbs_len, OSSL_LIB_CTX *libctx, unsigned char **sig_out_value, size_t *sig_out_len) { int ret = 0; size_t sig_len; unsigned char *sig_value = NULL; EVP_MD_CTX *sign_context = NULL; sign_context = EVP_MD_CTX_new(); if (sign_context == NULL) { fprintf(stderr, "EVP_MD_CTX_new failed.\n"); goto cleanup; } if (!EVP_DigestSignInit_ex(sign_context, NULL, NULL, libctx, NULL, priv, NULL)) { fprintf(stderr, "EVP_DigestSignInit_ex failed.\n"); goto cleanup; } if (!EVP_DigestSign(sign_context, NULL, &sig_len, tbs, tbs_len)) { fprintf(stderr, "EVP_DigestSign using NULL buffer failed.\n"); goto cleanup; } sig_value = OPENSSL_malloc(sig_len); if (sig_value == NULL) { fprintf(stderr, "OPENSSL_malloc failed.\n"); goto cleanup; } fprintf(stdout, "Generating signature:\n"); if (!EVP_DigestSign(sign_context, sig_value, &sig_len, tbs, tbs_len)) { fprintf(stderr, "EVP_DigestSign failed.\n"); goto cleanup; } *sig_out_len = sig_len; *sig_out_value = sig_value; BIO_dump_indent_fp(stdout, sig_value, sig_len, 2); fprintf(stdout, "\n"); ret = 1; cleanup: if (!ret) OPENSSL_free(sig_value); EVP_MD_CTX_free(sign_context); return ret; } static int demo_verify(EVP_PKEY *pub, const unsigned char *tbs, size_t tbs_len, const unsigned char *sig_value, size_t sig_len, OSSL_LIB_CTX *libctx) { int ret = 0; EVP_MD_CTX *verify_context = NULL; verify_context = EVP_MD_CTX_new(); if (verify_context == NULL) { fprintf(stderr, "EVP_MD_CTX_new failed.\n"); goto cleanup; } if (!EVP_DigestVerifyInit_ex(verify_context, NULL, NULL, libctx, NULL, pub, NULL)) { fprintf(stderr, "EVP_DigestVerifyInit_ex failed.\n"); goto cleanup; } if (!EVP_DigestVerify(verify_context, sig_value, sig_len, tbs, tbs_len)) { fprintf(stderr, "EVP_DigestVerify() failed.\n"); goto cleanup; } fprintf(stdout, "Signature verified.\n"); ret = 1; cleanup: EVP_MD_CTX_free(verify_context); return ret; } static int create_key(OSSL_LIB_CTX *libctx, EVP_PKEY **privout, EVP_PKEY **pubout) { int ret = 0; EVP_PKEY *priv = NULL, *pub = NULL; unsigned char pubdata[32]; size_t pubdata_len = 0; priv = EVP_PKEY_Q_keygen(libctx, NULL, "ED25519"); if (priv == NULL) { fprintf(stderr, "EVP_PKEY_Q_keygen() failed\n"); goto end; } if (!EVP_PKEY_get_octet_string_param(priv, OSSL_PKEY_PARAM_PUB_KEY, pubdata, sizeof(pubdata), &pubdata_len)) { fprintf(stderr, "EVP_PKEY_get_octet_string_param() failed\n"); goto end; } pub = EVP_PKEY_new_raw_public_key_ex(libctx, "ED25519", NULL, pubdata, pubdata_len); if (pub == NULL) { fprintf(stderr, "EVP_PKEY_new_raw_public_key_ex() failed\n"); goto end; } ret = 1; end: if (ret) { *pubout = pub; *privout = priv; } else { EVP_PKEY_free(priv); } return ret; } int main(void) { OSSL_LIB_CTX *libctx = NULL; size_t sig_len = 0; unsigned char *sig_value = NULL; int ret = EXIT_FAILURE; EVP_PKEY *priv = NULL, *pub = NULL; libctx = OSSL_LIB_CTX_new(); if (libctx == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto cleanup; } if (!create_key(libctx, &priv, &pub)) { fprintf(stderr, "Failed to create key.\n"); goto cleanup; } if (!demo_sign(priv, hamlet, sizeof(hamlet), libctx, &sig_value, &sig_len)) { fprintf(stderr, "demo_sign failed.\n"); goto cleanup; } if (!demo_verify(pub, hamlet, sizeof(hamlet), sig_value, sig_len, libctx)) { fprintf(stderr, "demo_verify failed.\n"); goto cleanup; } ret = EXIT_SUCCESS; cleanup: if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); EVP_PKEY_free(pub); EVP_PKEY_free(priv); OSSL_LIB_CTX_free(libctx); OPENSSL_free(sig_value); return ret; }
signature
openssl/demos/signature/EVP_ED_Signature_demo.c
openssl
#include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/decoder.h> #include "EVP_EC_Signature_demo.h" static const char *hamlet_1 = "To be, or not to be, that is the question,\n" "Whether tis nobler in the minde to suffer\n" "The slings and arrowes of outragious fortune,\n" "Or to take Armes again in a sea of troubles,\n" ; static const char *hamlet_2 = "And by opposing, end them, to die to sleep;\n" "No more, and by a sleep, to say we end\n" "The heart-ache, and the thousand natural shocks\n" "That flesh is heir to? tis a consumation\n" ; static EVP_PKEY *get_key(OSSL_LIB_CTX *libctx, const char *propq, int public) { OSSL_DECODER_CTX *dctx = NULL; EVP_PKEY *pkey = NULL; int selection; const unsigned char *data; size_t data_len; if (public) { selection = EVP_PKEY_PUBLIC_KEY; data = pub_key_der; data_len = sizeof(pub_key_der); } else { selection = EVP_PKEY_KEYPAIR; data = priv_key_der; data_len = sizeof(priv_key_der); } dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", NULL, "EC", selection, libctx, propq); (void)OSSL_DECODER_from_data(dctx, &data, &data_len); OSSL_DECODER_CTX_free(dctx); if (pkey == NULL) fprintf(stderr, "Failed to load %s key.\n", public ? "public" : "private"); return pkey; } static int demo_sign(OSSL_LIB_CTX *libctx, const char *sig_name, size_t *sig_out_len, unsigned char **sig_out_value) { int ret = 0, public = 0; size_t sig_len; unsigned char *sig_value = NULL; const char *propq = NULL; EVP_MD_CTX *sign_context = NULL; EVP_PKEY *priv_key = NULL; priv_key = get_key(libctx, propq, public); if (priv_key == NULL) { fprintf(stderr, "Get private key failed.\n"); goto cleanup; } sign_context = EVP_MD_CTX_new(); if (sign_context == NULL) { fprintf(stderr, "EVP_MD_CTX_new failed.\n"); goto cleanup; } if (!EVP_DigestSignInit_ex(sign_context, NULL, sig_name, libctx, NULL, priv_key, NULL)) { fprintf(stderr, "EVP_DigestSignInit_ex failed.\n"); goto cleanup; } if (!EVP_DigestSignUpdate(sign_context, hamlet_1, strlen(hamlet_1))) { fprintf(stderr, "EVP_DigestSignUpdate(hamlet_1) failed.\n"); goto cleanup; } if (!EVP_DigestSignUpdate(sign_context, hamlet_2, strlen(hamlet_2))) { fprintf(stderr, "EVP_DigestSignUpdate(hamlet_2) failed.\n"); goto cleanup; } if (!EVP_DigestSignFinal(sign_context, NULL, &sig_len)) { fprintf(stderr, "EVP_DigestSignFinal failed.\n"); goto cleanup; } if (sig_len <= 0) { fprintf(stderr, "EVP_DigestSignFinal returned invalid signature length.\n"); goto cleanup; } sig_value = OPENSSL_malloc(sig_len); if (sig_value == NULL) { fprintf(stderr, "No memory.\n"); goto cleanup; } if (!EVP_DigestSignFinal(sign_context, sig_value, &sig_len)) { fprintf(stderr, "EVP_DigestSignFinal failed.\n"); goto cleanup; } *sig_out_len = sig_len; *sig_out_value = sig_value; fprintf(stdout, "Generating signature:\n"); BIO_dump_indent_fp(stdout, sig_value, sig_len, 2); fprintf(stdout, "\n"); ret = 1; cleanup: if (!ret) OPENSSL_free(sig_value); EVP_PKEY_free(priv_key); EVP_MD_CTX_free(sign_context); return ret; } static int demo_verify(OSSL_LIB_CTX *libctx, const char *sig_name, size_t sig_len, unsigned char *sig_value) { int ret = 0, public = 1; const char *propq = NULL; EVP_MD_CTX *verify_context = NULL; EVP_PKEY *pub_key = NULL; verify_context = EVP_MD_CTX_new(); if (verify_context == NULL) { fprintf(stderr, "EVP_MD_CTX_new failed.\n"); goto cleanup; } pub_key = get_key(libctx, propq, public); if (pub_key == NULL) { fprintf(stderr, "Get public key failed.\n"); goto cleanup; } if (!EVP_DigestVerifyInit_ex(verify_context, NULL, sig_name, libctx, NULL, pub_key, NULL)) { fprintf(stderr, "EVP_DigestVerifyInit failed.\n"); goto cleanup; } if (!EVP_DigestVerifyUpdate(verify_context, hamlet_1, strlen(hamlet_1))) { fprintf(stderr, "EVP_DigestVerifyUpdate(hamlet_1) failed.\n"); goto cleanup; } if (!EVP_DigestVerifyUpdate(verify_context, hamlet_2, strlen(hamlet_2))) { fprintf(stderr, "EVP_DigestVerifyUpdate(hamlet_2) failed.\n"); goto cleanup; } if (EVP_DigestVerifyFinal(verify_context, sig_value, sig_len) <= 0) { fprintf(stderr, "EVP_DigestVerifyFinal failed.\n"); goto cleanup; } fprintf(stdout, "Signature verified.\n"); ret = 1; cleanup: EVP_PKEY_free(pub_key); EVP_MD_CTX_free(verify_context); return ret; } int main(void) { OSSL_LIB_CTX *libctx = NULL; const char *sig_name = "SHA3-512"; size_t sig_len = 0; unsigned char *sig_value = NULL; int ret = EXIT_FAILURE; libctx = OSSL_LIB_CTX_new(); if (libctx == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto cleanup; } if (!demo_sign(libctx, sig_name, &sig_len, &sig_value)) { fprintf(stderr, "demo_sign failed.\n"); goto cleanup; } if (!demo_verify(libctx, sig_name, sig_len, sig_value)) { fprintf(stderr, "demo_verify failed.\n"); goto cleanup; } ret = EXIT_SUCCESS; cleanup: if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); OSSL_LIB_CTX_free(libctx); OPENSSL_free(sig_value); return ret; }
signature
openssl/demos/signature/EVP_EC_Signature_demo.c
openssl
#include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/decoder.h> #include <openssl/dsa.h> static const char *hamlet_1 = "To be, or not to be, that is the question,\n" "Whether tis nobler in the minde to suffer\n" "The slings and arrowes of outragious fortune,\n" "Or to take Armes again in a sea of troubles,\n" ; static const char *hamlet_2 = "And by opposing, end them, to die to sleep;\n" "No more, and by a sleep, to say we end\n" "The heart-ache, and the thousand natural shocks\n" "That flesh is heir to? tis a consumation\n" ; static const char ALG[] = "DSA"; static const char DIGEST[] = "SHA256"; static const int NUMBITS = 2048; static const char * const PROPQUERY = NULL; static int generate_dsa_params(OSSL_LIB_CTX *libctx, EVP_PKEY **p_params) { int ret = 0; EVP_PKEY_CTX *pkey_ctx = NULL; EVP_PKEY *params = NULL; pkey_ctx = EVP_PKEY_CTX_new_from_name(libctx, ALG, PROPQUERY); if (pkey_ctx == NULL) goto end; if (EVP_PKEY_paramgen_init(pkey_ctx) <= 0) goto end; if (EVP_PKEY_CTX_set_dsa_paramgen_bits(pkey_ctx, NUMBITS) <= 0) goto end; if (EVP_PKEY_paramgen(pkey_ctx, &params) <= 0) goto end; if (params == NULL) goto end; ret = 1; end: if(ret != 1) { EVP_PKEY_free(params); params = NULL; } EVP_PKEY_CTX_free(pkey_ctx); *p_params = params; fprintf(stdout, "Params:\n"); EVP_PKEY_print_params_fp(stdout, params, 4, NULL); fprintf(stdout, "\n"); return ret; } static int generate_dsa_key(OSSL_LIB_CTX *libctx, EVP_PKEY *params, EVP_PKEY **p_pkey) { int ret = 0; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; ctx = EVP_PKEY_CTX_new_from_pkey(libctx, params, NULL); if (ctx == NULL) goto end; if (EVP_PKEY_keygen_init(ctx) <= 0) goto end; if (EVP_PKEY_keygen(ctx, &pkey) <= 0) goto end; if (pkey == NULL) goto end; ret = 1; end: if(ret != 1) { EVP_PKEY_free(pkey); pkey = NULL; } EVP_PKEY_CTX_free(ctx); *p_pkey = pkey; fprintf(stdout, "Generating public/private key pair:\n"); EVP_PKEY_print_public_fp(stdout, pkey, 4, NULL); fprintf(stdout, "\n"); EVP_PKEY_print_private_fp(stdout, pkey, 4, NULL); fprintf(stdout, "\n"); EVP_PKEY_print_params_fp(stdout, pkey, 4, NULL); fprintf(stdout, "\n"); return ret; } static int extract_public_key(const EVP_PKEY *pkey, OSSL_PARAM **p_public_key) { int ret = 0; OSSL_PARAM *public_key = NULL; if (EVP_PKEY_todata(pkey, EVP_PKEY_PUBLIC_KEY, &public_key) != 1) goto end; ret = 1; end: if (ret != 1) { OSSL_PARAM_free(public_key); public_key = NULL; } *p_public_key = public_key; return ret; } static int extract_keypair(const EVP_PKEY *pkey, OSSL_PARAM **p_keypair) { int ret = 0; OSSL_PARAM *keypair = NULL; if (EVP_PKEY_todata(pkey, EVP_PKEY_KEYPAIR, &keypair) != 1) goto end; ret = 1; end: if (ret != 1) { OSSL_PARAM_free(keypair); keypair = NULL; } *p_keypair = keypair; return ret; } static int demo_sign(OSSL_LIB_CTX *libctx, size_t *p_sig_len, unsigned char **p_sig_value, OSSL_PARAM keypair[]) { int ret = 0; size_t sig_len = 0; unsigned char *sig_value = NULL; EVP_MD_CTX *ctx = NULL; EVP_PKEY_CTX *pkey_ctx = NULL; EVP_PKEY *pkey = NULL; pkey_ctx = EVP_PKEY_CTX_new_from_name(libctx, ALG, PROPQUERY); if (pkey_ctx == NULL) goto end; if (EVP_PKEY_fromdata_init(pkey_ctx) != 1) goto end; if (EVP_PKEY_fromdata(pkey_ctx, &pkey, EVP_PKEY_KEYPAIR, keypair) != 1) goto end; ctx = EVP_MD_CTX_create(); if (ctx == NULL) goto end; if (EVP_DigestSignInit_ex(ctx, NULL, DIGEST, libctx, NULL, pkey, NULL) != 1) goto end; if (EVP_DigestSignUpdate(ctx, hamlet_1, sizeof(hamlet_1)) != 1) goto end; if (EVP_DigestSignUpdate(ctx, hamlet_2, sizeof(hamlet_2)) != 1) goto end; if (EVP_DigestSignFinal(ctx, NULL, &sig_len) != 1) goto end; if (sig_len == 0) goto end; sig_value = OPENSSL_malloc(sig_len); if (sig_value == NULL) goto end; if (EVP_DigestSignFinal(ctx, sig_value, &sig_len) != 1) goto end; ret = 1; end: EVP_MD_CTX_free(ctx); if (ret != 1) { OPENSSL_free(sig_value); sig_len = 0; sig_value = NULL; } *p_sig_len = sig_len; *p_sig_value = sig_value; EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(pkey_ctx); fprintf(stdout, "Generating signature:\n"); BIO_dump_indent_fp(stdout, sig_value, sig_len, 2); fprintf(stdout, "\n"); return ret; } static int demo_verify(OSSL_LIB_CTX *libctx, size_t sig_len, unsigned char *sig_value, OSSL_PARAM public_key[]) { int ret = 0; EVP_MD_CTX *ctx = NULL; EVP_PKEY_CTX *pkey_ctx = NULL; EVP_PKEY *pkey = NULL; pkey_ctx = EVP_PKEY_CTX_new_from_name(libctx, ALG, PROPQUERY); if (pkey_ctx == NULL) goto end; if (EVP_PKEY_fromdata_init(pkey_ctx) != 1) goto end; if (EVP_PKEY_fromdata(pkey_ctx, &pkey, EVP_PKEY_PUBLIC_KEY, public_key) != 1) goto end; ctx = EVP_MD_CTX_create(); if(ctx == NULL) goto end; if (EVP_DigestVerifyInit_ex(ctx, NULL, DIGEST, libctx, NULL, pkey, NULL) != 1) goto end; if (EVP_DigestVerifyUpdate(ctx, hamlet_1, sizeof(hamlet_1)) != 1) goto end; if (EVP_DigestVerifyUpdate(ctx, hamlet_2, sizeof(hamlet_2)) != 1) goto end; if (EVP_DigestVerifyFinal(ctx, sig_value, sig_len) != 1) goto end; ret = 1; end: EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(pkey_ctx); EVP_MD_CTX_free(ctx); return ret; } int main(void) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; EVP_PKEY *params = NULL; EVP_PKEY *pkey = NULL; OSSL_PARAM *public_key = NULL; OSSL_PARAM *keypair = NULL; size_t sig_len = 0; unsigned char *sig_value = NULL; libctx = OSSL_LIB_CTX_new(); if (libctx == NULL) goto end; if (generate_dsa_params(libctx, &params) != 1) goto end; if (generate_dsa_key(libctx, params, &pkey) != 1) goto end; if (extract_public_key(pkey, &public_key) != 1) goto end; if (extract_keypair(pkey, &keypair) != 1) goto end; if (demo_sign(libctx, &sig_len, &sig_value, keypair) != 1) goto end; if (demo_verify(libctx, sig_len, sig_value, public_key) != 1) goto end; ret = EXIT_SUCCESS; end: if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); OPENSSL_free(sig_value); EVP_PKEY_free(params); EVP_PKEY_free(pkey); OSSL_PARAM_free(public_key); OSSL_PARAM_free(keypair); OSSL_LIB_CTX_free(libctx); return ret; }
signature
openssl/demos/signature/EVP_DSA_Signature_demo.c
openssl
#include <stdio.h> #include <stdlib.h> #include <openssl/core_names.h> #include <openssl/evp.h> #include <openssl/rsa.h> #include <openssl/params.h> #include <openssl/err.h> #include <openssl/bio.h> #include "rsa_pss.h" static const unsigned char test_digest[32] = {0}; static const char *propq = NULL; static int sign(OSSL_LIB_CTX *libctx, unsigned char **sig, size_t *sig_len) { int ret = 0; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_MD *md = NULL; const unsigned char *ppriv_key = NULL; *sig = NULL; ppriv_key = rsa_priv_key; pkey = d2i_PrivateKey_ex(EVP_PKEY_RSA, NULL, &ppriv_key, sizeof(rsa_priv_key), libctx, propq); if (pkey == NULL) { fprintf(stderr, "Failed to load private key\n"); goto end; } md = EVP_MD_fetch(libctx, "SHA256", propq); if (md == NULL) { fprintf(stderr, "Failed to fetch hash algorithm\n"); goto end; } ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (ctx == NULL) { fprintf(stderr, "Failed to create signing context\n"); goto end; } if (EVP_PKEY_sign_init(ctx) == 0) { fprintf(stderr, "Failed to initialize signing context\n"); goto end; } if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) == 0) { fprintf(stderr, "Failed to configure padding\n"); goto end; } if (EVP_PKEY_CTX_set_signature_md(ctx, md) == 0) { fprintf(stderr, "Failed to configure digest type\n"); goto end; } if (EVP_PKEY_sign(ctx, NULL, sig_len, test_digest, sizeof(test_digest)) == 0) { fprintf(stderr, "Failed to get signature length\n"); goto end; } *sig = OPENSSL_malloc(*sig_len); if (*sig == NULL) { fprintf(stderr, "Failed to allocate memory for signature\n"); goto end; } if (EVP_PKEY_sign(ctx, *sig, sig_len, test_digest, sizeof(test_digest)) != 1) { fprintf(stderr, "Failed to sign\n"); goto end; } ret = 1; end: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); EVP_MD_free(md); if (ret == 0) OPENSSL_free(*sig); return ret; } static int verify(OSSL_LIB_CTX *libctx, const unsigned char *sig, size_t sig_len) { int ret = 0; const unsigned char *ppub_key = NULL; EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_MD *md = NULL; ppub_key = rsa_pub_key; pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ppub_key, sizeof(rsa_pub_key)); if (pkey == NULL) { fprintf(stderr, "Failed to load public key\n"); goto end; } md = EVP_MD_fetch(libctx, "SHA256", propq); if (md == NULL) { fprintf(stderr, "Failed to fetch hash algorithm\n"); goto end; } ctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (ctx == NULL) { fprintf(stderr, "Failed to create verification context\n"); goto end; } if (EVP_PKEY_verify_init(ctx) == 0) { fprintf(stderr, "Failed to initialize verification context\n"); goto end; } if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PSS_PADDING) == 0) { fprintf(stderr, "Failed to configure padding\n"); goto end; } if (EVP_PKEY_CTX_set_signature_md(ctx, md) == 0) { fprintf(stderr, "Failed to configure digest type\n"); goto end; } if (EVP_PKEY_verify(ctx, sig, sig_len, test_digest, sizeof(test_digest)) == 0) { fprintf(stderr, "Failed to verify signature; " "signature may be invalid\n"); goto end; } ret = 1; end: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(pkey); EVP_MD_free(md); return ret; } int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; unsigned char *sig = NULL; size_t sig_len = 0; if (sign(libctx, &sig, &sig_len) == 0) goto end; if (verify(libctx, sig, sig_len) == 0) goto end; printf("Success\n"); ret = EXIT_SUCCESS; end: OPENSSL_free(sig); OSSL_LIB_CTX_free(libctx); return ret; }
signature
openssl/demos/signature/rsa_pss_direct.c
openssl
#include <stdio.h> #include <stdlib.h> #include <openssl/core_names.h> #include <openssl/evp.h> #include <openssl/rsa.h> #include <openssl/params.h> #include <openssl/err.h> #include <openssl/bio.h> #include "rsa_pss.h" static const char test_message[] = "This is an example message to be signed."; static const char *propq = NULL; static int sign(OSSL_LIB_CTX *libctx, unsigned char **sig, size_t *sig_len) { int ret = 0; EVP_PKEY *pkey = NULL; EVP_MD_CTX *mctx = NULL; OSSL_PARAM params[2], *p = params; const unsigned char *ppriv_key = NULL; *sig = NULL; ppriv_key = rsa_priv_key; pkey = d2i_PrivateKey_ex(EVP_PKEY_RSA, NULL, &ppriv_key, sizeof(rsa_priv_key), libctx, propq); if (pkey == NULL) { fprintf(stderr, "Failed to load private key\n"); goto end; } mctx = EVP_MD_CTX_new(); if (mctx == NULL) { fprintf(stderr, "Failed to create MD context\n"); goto end; } *p++ = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE, OSSL_PKEY_RSA_PAD_MODE_PSS, 0); *p = OSSL_PARAM_construct_end(); if (EVP_DigestSignInit_ex(mctx, NULL, "SHA256", libctx, propq, pkey, params) == 0) { fprintf(stderr, "Failed to initialize signing context\n"); goto end; } if (EVP_DigestSignUpdate(mctx, test_message, sizeof(test_message)) == 0) { fprintf(stderr, "Failed to hash message into signing context\n"); goto end; } if (EVP_DigestSignFinal(mctx, NULL, sig_len) == 0) { fprintf(stderr, "Failed to get signature length\n"); goto end; } *sig = OPENSSL_malloc(*sig_len); if (*sig == NULL) { fprintf(stderr, "Failed to allocate memory for signature\n"); goto end; } if (EVP_DigestSignFinal(mctx, *sig, sig_len) == 0) { fprintf(stderr, "Failed to sign\n"); goto end; } ret = 1; end: EVP_MD_CTX_free(mctx); EVP_PKEY_free(pkey); if (ret == 0) OPENSSL_free(*sig); return ret; } static int verify(OSSL_LIB_CTX *libctx, const unsigned char *sig, size_t sig_len) { int ret = 0; EVP_PKEY *pkey = NULL; EVP_MD_CTX *mctx = NULL; OSSL_PARAM params[2], *p = params; const unsigned char *ppub_key = NULL; ppub_key = rsa_pub_key; pkey = d2i_PublicKey(EVP_PKEY_RSA, NULL, &ppub_key, sizeof(rsa_pub_key)); if (pkey == NULL) { fprintf(stderr, "Failed to load public key\n"); goto end; } mctx = EVP_MD_CTX_new(); if (mctx == NULL) { fprintf(stderr, "Failed to create MD context\n"); goto end; } *p++ = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_PAD_MODE, OSSL_PKEY_RSA_PAD_MODE_PSS, 0); *p = OSSL_PARAM_construct_end(); if (EVP_DigestVerifyInit_ex(mctx, NULL, "SHA256", libctx, propq, pkey, params) == 0) { fprintf(stderr, "Failed to initialize signing context\n"); goto end; } if (EVP_DigestVerifyUpdate(mctx, test_message, sizeof(test_message)) == 0) { fprintf(stderr, "Failed to hash message into signing context\n"); goto end; } if (EVP_DigestVerifyFinal(mctx, sig, sig_len) == 0) { fprintf(stderr, "Failed to verify signature; " "signature may be invalid\n"); goto end; } ret = 1; end: EVP_MD_CTX_free(mctx); EVP_PKEY_free(pkey); return ret; } int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; unsigned char *sig = NULL; size_t sig_len = 0; if (sign(libctx, &sig, &sig_len) == 0) goto end; if (verify(libctx, sig, sig_len) == 0) goto end; printf("Success\n"); ret = EXIT_SUCCESS; end: OPENSSL_free(sig); OSSL_LIB_CTX_free(libctx); return ret; }
signature
openssl/demos/signature/rsa_pss_hash.c
openssl
#include <stdio.h> #include <string.h> #include <openssl/core_names.h> #include <openssl/evp.h> static const char *propq = NULL; static const unsigned char peer1_privk_data[32] = { 0x80, 0x5b, 0x30, 0x20, 0x25, 0x4a, 0x70, 0x2c, 0xad, 0xa9, 0x8d, 0x7d, 0x47, 0xf8, 0x1b, 0x20, 0x89, 0xd2, 0xf9, 0x14, 0xac, 0x92, 0x27, 0xf2, 0x10, 0x7e, 0xdb, 0x21, 0xbd, 0x73, 0x73, 0x5d }; static const unsigned char peer2_privk_data[32] = { 0xf8, 0x84, 0x19, 0x69, 0x79, 0x13, 0x0d, 0xbd, 0xb1, 0x76, 0xd7, 0x0e, 0x7e, 0x0f, 0xb6, 0xf4, 0x8c, 0x4a, 0x8c, 0x5f, 0xd8, 0x15, 0x09, 0x0a, 0x71, 0x78, 0x74, 0x92, 0x0f, 0x85, 0xc8, 0x43 }; static const unsigned char expected_result[32] = { 0x19, 0x71, 0x26, 0x12, 0x74, 0xb5, 0xb1, 0xce, 0x77, 0xd0, 0x79, 0x24, 0xb6, 0x0a, 0x5c, 0x72, 0x0c, 0xa6, 0x56, 0xc0, 0x11, 0xeb, 0x43, 0x11, 0x94, 0x3b, 0x01, 0x45, 0xca, 0x19, 0xfe, 0x09 }; typedef struct peer_data_st { const char *name; EVP_PKEY *privk; unsigned char pubk_data[32]; unsigned char *secret; size_t secret_len; } PEER_DATA; static int keyexch_x25519_before( OSSL_LIB_CTX *libctx, const unsigned char *kat_privk_data, PEER_DATA *local_peer) { int ret = 0; size_t pubk_data_len = 0; if (kat_privk_data != NULL) local_peer->privk = EVP_PKEY_new_raw_private_key_ex(libctx, "X25519", propq, kat_privk_data, sizeof(peer1_privk_data)); else local_peer->privk = EVP_PKEY_Q_keygen(libctx, propq, "X25519"); if (local_peer->privk == NULL) { fprintf(stderr, "Could not load or generate private key\n"); goto end; } if (EVP_PKEY_get_octet_string_param(local_peer->privk, OSSL_PKEY_PARAM_PUB_KEY, local_peer->pubk_data, sizeof(local_peer->pubk_data), &pubk_data_len) == 0) { fprintf(stderr, "EVP_PKEY_get_octet_string_param() failed\n"); goto end; } if (pubk_data_len != 32) { fprintf(stderr, "EVP_PKEY_get_octet_string_param() " "yielded wrong length\n"); goto end; } ret = 1; end: if (ret == 0) { EVP_PKEY_free(local_peer->privk); local_peer->privk = NULL; } return ret; } static int keyexch_x25519_after( OSSL_LIB_CTX *libctx, int use_kat, PEER_DATA *local_peer, const unsigned char *remote_peer_pubk_data) { int ret = 0; EVP_PKEY *remote_peer_pubk = NULL; EVP_PKEY_CTX *ctx = NULL; local_peer->secret = NULL; remote_peer_pubk = EVP_PKEY_new_raw_public_key_ex(libctx, "X25519", propq, remote_peer_pubk_data, 32); if (remote_peer_pubk == NULL) { fprintf(stderr, "EVP_PKEY_new_raw_public_key_ex() failed\n"); goto end; } ctx = EVP_PKEY_CTX_new_from_pkey(libctx, local_peer->privk, propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed\n"); goto end; } if (EVP_PKEY_derive_init(ctx) == 0) { fprintf(stderr, "EVP_PKEY_derive_init() failed\n"); goto end; } if (EVP_PKEY_derive_set_peer(ctx, remote_peer_pubk) == 0) { fprintf(stderr, "EVP_PKEY_derive_set_peer() failed\n"); goto end; } if (EVP_PKEY_derive(ctx, NULL, &local_peer->secret_len) == 0) { fprintf(stderr, "EVP_PKEY_derive() failed\n"); goto end; } if (local_peer->secret_len != 32) { fprintf(stderr, "Secret is always 32 bytes for X25519\n"); goto end; } local_peer->secret = OPENSSL_malloc(local_peer->secret_len); if (local_peer->secret == NULL) { fprintf(stderr, "Could not allocate memory for secret\n"); goto end; } if (EVP_PKEY_derive(ctx, local_peer->secret, &local_peer->secret_len) == 0) { fprintf(stderr, "EVP_PKEY_derive() failed\n"); goto end; } printf("Shared secret (%s):\n", local_peer->name); BIO_dump_indent_fp(stdout, local_peer->secret, local_peer->secret_len, 2); putchar('\n'); ret = 1; end: EVP_PKEY_CTX_free(ctx); EVP_PKEY_free(remote_peer_pubk); if (ret == 0) { OPENSSL_clear_free(local_peer->secret, local_peer->secret_len); local_peer->secret = NULL; } return ret; } static int keyexch_x25519(int use_kat) { int ret = 0; OSSL_LIB_CTX *libctx = NULL; PEER_DATA peer1 = {"peer 1"}, peer2 = {"peer 2"}; if (keyexch_x25519_before(libctx, use_kat ? peer1_privk_data : NULL, &peer1) == 0) return 0; if (keyexch_x25519_before(libctx, use_kat ? peer2_privk_data : NULL, &peer2) == 0) return 0; if (keyexch_x25519_after(libctx, use_kat, &peer1, peer2.pubk_data) == 0) return 0; if (keyexch_x25519_after(libctx, use_kat, &peer2, peer1.pubk_data) == 0) return 0; if (CRYPTO_memcmp(peer1.secret, peer2.secret, peer1.secret_len) != 0) { fprintf(stderr, "Negotiated secrets do not match\n"); goto end; } if (use_kat && CRYPTO_memcmp(peer1.secret, expected_result, peer1.secret_len) != 0) { fprintf(stderr, "Did not get expected result\n"); goto end; } ret = 1; end: OPENSSL_clear_free(peer1.secret, peer1.secret_len); OPENSSL_clear_free(peer2.secret, peer2.secret_len); EVP_PKEY_free(peer1.privk); EVP_PKEY_free(peer2.privk); OSSL_LIB_CTX_free(libctx); return ret; } int main(int argc, char **argv) { printf("Key exchange using known answer (deterministic):\n"); if (keyexch_x25519(1) == 0) return EXIT_FAILURE; printf("Key exchange using random keys:\n"); if (keyexch_x25519(0) == 0) return EXIT_FAILURE; return EXIT_SUCCESS; }
keyexch
openssl/demos/keyexch/x25519.c
openssl
#include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <openssl/ssl.h> #include <openssl/err.h> #include <signal.h> static const int server_port = 4433; typedef unsigned char bool; #define true 1 #define false 0 static volatile bool server_running = true; int create_socket(bool isServer) { int s; int optval = 1; struct sockaddr_in addr; s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { perror("Unable to create socket"); exit(EXIT_FAILURE); } if (isServer) { addr.sin_family = AF_INET; addr.sin_port = htons(server_port); addr.sin_addr.s_addr = INADDR_ANY; if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) < 0) { perror("setsockopt(SO_REUSEADDR) failed"); exit(EXIT_FAILURE); } if (bind(s, (struct sockaddr*) &addr, sizeof(addr)) < 0) { perror("Unable to bind"); exit(EXIT_FAILURE); } if (listen(s, 1) < 0) { perror("Unable to listen"); exit(EXIT_FAILURE); } } return s; } SSL_CTX* create_context(bool isServer) { const SSL_METHOD *method; SSL_CTX *ctx; if (isServer) method = TLS_server_method(); else method = TLS_client_method(); ctx = SSL_CTX_new(method); if (ctx == NULL) { perror("Unable to create SSL context"); ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } return ctx; } void configure_server_context(SSL_CTX *ctx) { if (SSL_CTX_use_certificate_chain_file(ctx, "cert.pem") <= 0) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } if (SSL_CTX_use_PrivateKey_file(ctx, "key.pem", SSL_FILETYPE_PEM) <= 0) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } } void configure_client_context(SSL_CTX *ctx) { SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL); if (!SSL_CTX_load_verify_locations(ctx, "cert.pem", NULL)) { ERR_print_errors_fp(stderr); exit(EXIT_FAILURE); } } void usage(void) { printf("Usage: sslecho s\n"); printf(" --or--\n"); printf(" sslecho c ip\n"); printf(" c=client, s=server, ip=dotted ip of server\n"); exit(EXIT_FAILURE); } int main(int argc, char **argv) { bool isServer; int result; SSL_CTX *ssl_ctx = NULL; SSL *ssl = NULL; int server_skt = -1; int client_skt = -1; char *txbuf = NULL; size_t txcap = 0; int txlen; char rxbuf[128]; size_t rxcap = sizeof(rxbuf); int rxlen; char *rem_server_ip = NULL; struct sockaddr_in addr; unsigned int addr_len = sizeof(addr); signal(SIGPIPE, SIG_IGN); printf("\nsslecho : Simple Echo Client/Server : %s : %s\n\n", __DATE__, __TIME__); if (argc < 2) { usage(); } isServer = (argv[1][0] == 's') ? true : false; if (!isServer) { if (argc != 3) { usage(); } rem_server_ip = argv[2]; } ssl_ctx = create_context(isServer); if (isServer) { printf("We are the server on port: %d\n\n", server_port); configure_server_context(ssl_ctx); server_skt = create_socket(true); while (server_running) { client_skt = accept(server_skt, (struct sockaddr*) &addr, &addr_len); if (client_skt < 0) { perror("Unable to accept"); exit(EXIT_FAILURE); } printf("Client TCP connection accepted\n"); ssl = SSL_new(ssl_ctx); SSL_set_fd(ssl, client_skt); if (SSL_accept(ssl) <= 0) { ERR_print_errors_fp(stderr); server_running = false; } else { printf("Client SSL connection accepted\n\n"); while (true) { if ((rxlen = SSL_read(ssl, rxbuf, rxcap)) <= 0) { if (rxlen == 0) { printf("Client closed connection\n"); } else { printf("SSL_read returned %d\n", rxlen); } ERR_print_errors_fp(stderr); break; } rxbuf[rxlen] = 0; if (strcmp(rxbuf, "kill\n") == 0) { printf("Server received 'kill' command\n"); server_running = false; break; } printf("Received: %s", rxbuf); if (SSL_write(ssl, rxbuf, rxlen) <= 0) { ERR_print_errors_fp(stderr); } } } if (server_running) { SSL_shutdown(ssl); SSL_free(ssl); close(client_skt); } } printf("Server exiting...\n"); } else { printf("We are the client\n\n"); configure_client_context(ssl_ctx); client_skt = create_socket(false); addr.sin_family = AF_INET; inet_pton(AF_INET, rem_server_ip, &addr.sin_addr.s_addr); addr.sin_port = htons(server_port); if (connect(client_skt, (struct sockaddr*) &addr, sizeof(addr)) != 0) { perror("Unable to TCP connect to server"); goto exit; } else { printf("TCP connection to server successful\n"); } ssl = SSL_new(ssl_ctx); SSL_set_fd(ssl, client_skt); SSL_set_tlsext_host_name(ssl, rem_server_ip); SSL_set1_host(ssl, rem_server_ip); if (SSL_connect(ssl) == 1) { printf("SSL connection to server successful\n\n"); while (true) { txlen = getline(&txbuf, &txcap, stdin); if (txlen < 0 || txbuf == NULL) { break; } if (txbuf[0] == '\n') { break; } if ((result = SSL_write(ssl, txbuf, txlen)) <= 0) { printf("Server closed connection\n"); ERR_print_errors_fp(stderr); break; } rxlen = SSL_read(ssl, rxbuf, rxcap); if (rxlen <= 0) { printf("Server closed connection\n"); ERR_print_errors_fp(stderr); break; } else { rxbuf[rxlen] = 0; printf("Received: %s", rxbuf); } } printf("Client exiting...\n"); } else { printf("SSL connection to server failed\n\n"); ERR_print_errors_fp(stderr); } } exit: if (ssl != NULL) { SSL_shutdown(ssl); SSL_free(ssl); } SSL_CTX_free(ssl_ctx); if (client_skt != -1) close(client_skt); if (server_skt != -1) close(server_skt); if (txbuf != NULL && txcap > 0) free(txbuf); printf("sslecho exiting\n"); return EXIT_SUCCESS; }
sslecho
openssl/demos/sslecho/main.c
openssl
#include <stdio.h> #include <openssl/core_names.h> #include <openssl/crypto.h> #include <openssl/kdf.h> #include <openssl/obj_mac.h> #include <openssl/params.h> static unsigned char password[] = { 'P', 'a', 's', 's', 'w', 'o', 'r', 'd' }; static unsigned char pbkdf2_salt[] = { 'N', 'a', 'C', 'l' }; static unsigned int pbkdf2_iterations = 80000; static const unsigned char expected_output[] = { 0x4d, 0xdc, 0xd8, 0xf6, 0x0b, 0x98, 0xbe, 0x21, 0x83, 0x0c, 0xee, 0x5e, 0xf2, 0x27, 0x01, 0xf9, 0x64, 0x1a, 0x44, 0x18, 0xd0, 0x4c, 0x04, 0x14, 0xae, 0xff, 0x08, 0x87, 0x6b, 0x34, 0xab, 0x56, 0xa1, 0xd4, 0x25, 0xa1, 0x22, 0x58, 0x33, 0x54, 0x9a, 0xdb, 0x84, 0x1b, 0x51, 0xc9, 0xb3, 0x17, 0x6a, 0x27, 0x2b, 0xde, 0xbb, 0xa1, 0xd0, 0x78, 0x47, 0x8f, 0x62, 0xb3, 0x97, 0xf3, 0x3c, 0x8d }; int main(int argc, char **argv) { int ret = EXIT_FAILURE; EVP_KDF *kdf = NULL; EVP_KDF_CTX *kctx = NULL; unsigned char out[64]; OSSL_PARAM params[5], *p = params; OSSL_LIB_CTX *library_context = NULL; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto end; } kdf = EVP_KDF_fetch(library_context, "PBKDF2", NULL); if (kdf == NULL) { fprintf(stderr, "EVP_KDF_fetch() returned NULL\n"); goto end; } kctx = EVP_KDF_CTX_new(kdf); if (kctx == NULL) { fprintf(stderr, "EVP_KDF_CTX_new() returned NULL\n"); goto end; } *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, password, sizeof(password)); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, pbkdf2_salt, sizeof(pbkdf2_salt)); *p++ = OSSL_PARAM_construct_uint(OSSL_KDF_PARAM_ITER, &pbkdf2_iterations); *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, "SHA256", 0); *p = OSSL_PARAM_construct_end(); if (EVP_KDF_derive(kctx, out, sizeof(out), params) != 1) { fprintf(stderr, "EVP_KDF_derive() failed\n"); goto end; } if (CRYPTO_memcmp(expected_output, out, sizeof(expected_output)) != 0) { fprintf(stderr, "Generated key does not match expected value\n"); goto end; } printf("Success\n"); ret = EXIT_SUCCESS; end: EVP_KDF_CTX_free(kctx); EVP_KDF_free(kdf); OSSL_LIB_CTX_free(library_context); return ret; }
kdf
openssl/demos/kdf/pbkdf2.c
openssl
#include <stdio.h> #include <openssl/core_names.h> #include <openssl/crypto.h> #include <openssl/kdf.h> #include <openssl/params.h> #include <openssl/thread.h> static unsigned char password[] = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }; static unsigned char salt[] = { 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02 }; static unsigned char secret[] = { 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03 }; static unsigned char ad[] = { 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04 }; static uint32_t memory_cost = 32; static uint32_t iteration_cost = 3; static uint32_t parallel_cost = 4; static const unsigned char expected_output[] = { 0x0d, 0x64, 0x0d, 0xf5, 0x8d, 0x78, 0x76, 0x6c, 0x08, 0xc0, 0x37, 0xa3, 0x4a, 0x8b, 0x53, 0xc9, 0xd0, 0x1e, 0xf0, 0x45, 0x2d, 0x75, 0xb6, 0x5e, 0xb5, 0x25, 0x20, 0xe9, 0x6b, 0x01, 0xe6, 0x59 }; int main(int argc, char **argv) { int rv = EXIT_FAILURE; EVP_KDF *kdf = NULL; EVP_KDF_CTX *kctx = NULL; unsigned char out[32]; OSSL_PARAM params[9], *p = params; OSSL_LIB_CTX *library_context = NULL; unsigned int threads; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto end; } kdf = EVP_KDF_fetch(library_context, "argon2id", NULL); if (kdf == NULL) { fprintf(stderr, "EVP_KDF_fetch() returned NULL\n"); goto end; } kctx = EVP_KDF_CTX_new(kdf); if (kctx == NULL) { fprintf(stderr, "EVP_KDF_CTX_new() returned NULL\n"); goto end; } threads = parallel_cost; if (OSSL_set_max_threads(library_context, parallel_cost) != 1) { uint64_t max_threads = OSSL_get_max_threads(library_context); if (max_threads == 0) threads = 1; else if (max_threads < parallel_cost) threads = max_threads; } *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, password, sizeof(password)); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, salt, sizeof(salt)); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_ARGON2_AD, ad, sizeof(ad)); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SECRET, secret, sizeof(secret)); *p++ = OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ITER, &iteration_cost); *p++ = OSSL_PARAM_construct_uint(OSSL_KDF_PARAM_THREADS, &threads); *p++ = OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ARGON2_LANES, &parallel_cost); *p++ = OSSL_PARAM_construct_uint32(OSSL_KDF_PARAM_ARGON2_MEMCOST, &memory_cost); *p = OSSL_PARAM_construct_end(); if (EVP_KDF_derive(kctx, out, sizeof(out), params) != 1) { fprintf(stderr, "EVP_KDF_derive() failed\n"); goto end; } if (CRYPTO_memcmp(expected_output, out, sizeof(expected_output)) != 0) { fprintf(stderr, "Generated key does not match expected value\n"); goto end; } printf("Success\n"); rv = EXIT_SUCCESS; end: EVP_KDF_CTX_free(kctx); EVP_KDF_free(kdf); OSSL_LIB_CTX_free(library_context); return rv; }
kdf
openssl/demos/kdf/argon2.c
openssl
#include <stdio.h> #include <openssl/core_names.h> #include <openssl/crypto.h> #include <openssl/kdf.h> #include <openssl/obj_mac.h> #include <openssl/params.h> static unsigned char password[] = { 'p', 'a', 's', 's', 'w', 'o', 'r', 'd' }; static unsigned char scrypt_salt[] = { 'N', 'a', 'C', 'l' }; static unsigned int scrypt_n = 1024; static unsigned int scrypt_r = 8; static unsigned int scrypt_p = 16; static const unsigned char expected_output[] = { 0xfd, 0xba, 0xbe, 0x1c, 0x9d, 0x34, 0x72, 0x00, 0x78, 0x56, 0xe7, 0x19, 0x0d, 0x01, 0xe9, 0xfe, 0x7c, 0x6a, 0xd7, 0xcb, 0xc8, 0x23, 0x78, 0x30, 0xe7, 0x73, 0x76, 0x63, 0x4b, 0x37, 0x31, 0x62, 0x2e, 0xaf, 0x30, 0xd9, 0x2e, 0x22, 0xa3, 0x88, 0x6f, 0xf1, 0x09, 0x27, 0x9d, 0x98, 0x30, 0xda, 0xc7, 0x27, 0xaf, 0xb9, 0x4a, 0x83, 0xee, 0x6d, 0x83, 0x60, 0xcb, 0xdf, 0xa2, 0xcc, 0x06, 0x40 }; int main(int argc, char **argv) { int ret = EXIT_FAILURE; EVP_KDF *kdf = NULL; EVP_KDF_CTX *kctx = NULL; unsigned char out[64]; OSSL_PARAM params[6], *p = params; OSSL_LIB_CTX *library_context = NULL; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto end; } kdf = EVP_KDF_fetch(library_context, "SCRYPT", NULL); if (kdf == NULL) { fprintf(stderr, "EVP_KDF_fetch() returned NULL\n"); goto end; } kctx = EVP_KDF_CTX_new(kdf); if (kctx == NULL) { fprintf(stderr, "EVP_KDF_CTX_new() returned NULL\n"); goto end; } *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, password, sizeof(password)); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, scrypt_salt, sizeof(scrypt_salt)); *p++ = OSSL_PARAM_construct_uint(OSSL_KDF_PARAM_SCRYPT_N, &scrypt_n); *p++ = OSSL_PARAM_construct_uint(OSSL_KDF_PARAM_SCRYPT_R, &scrypt_r); *p++ = OSSL_PARAM_construct_uint(OSSL_KDF_PARAM_SCRYPT_P, &scrypt_p); *p = OSSL_PARAM_construct_end(); if (EVP_KDF_derive(kctx, out, sizeof(out), params) != 1) { fprintf(stderr, "EVP_KDF_derive() failed\n"); goto end; } if (CRYPTO_memcmp(expected_output, out, sizeof(expected_output)) != 0) { fprintf(stderr, "Generated key does not match expected value\n"); goto end; } printf("Success\n"); ret = EXIT_SUCCESS; end: EVP_KDF_CTX_free(kctx); EVP_KDF_free(kdf); OSSL_LIB_CTX_free(library_context); return ret; }
kdf
openssl/demos/kdf/scrypt.c
openssl
#include <stdio.h> #include <openssl/core_names.h> #include <openssl/crypto.h> #include <openssl/kdf.h> #include <openssl/obj_mac.h> #include <openssl/params.h> static unsigned char hkdf_salt[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c }; static unsigned char hkdf_ikm[] = { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b }; static unsigned char hkdf_info[] = { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 }; static unsigned char hkdf_okm[] = { 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65 }; int main(int argc, char **argv) { int ret = EXIT_FAILURE; EVP_KDF *kdf = NULL; EVP_KDF_CTX *kctx = NULL; unsigned char out[42]; OSSL_PARAM params[5], *p = params; OSSL_LIB_CTX *library_context = NULL; library_context = OSSL_LIB_CTX_new(); if (library_context == NULL) { fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n"); goto end; } kdf = EVP_KDF_fetch(library_context, "HKDF", NULL); if (kdf == NULL) { fprintf(stderr, "EVP_KDF_fetch() returned NULL\n"); goto end; } kctx = EVP_KDF_CTX_new(kdf); if (kctx == NULL) { fprintf(stderr, "EVP_KDF_CTX_new() returned NULL\n"); goto end; } *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, "SHA256", 0); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY, hkdf_ikm, sizeof(hkdf_ikm)); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_INFO, hkdf_info, sizeof(hkdf_info)); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, hkdf_salt, sizeof(hkdf_salt)); *p = OSSL_PARAM_construct_end(); if (EVP_KDF_derive(kctx, out, sizeof(out), params) != 1) { fprintf(stderr, "EVP_KDF_derive() failed\n"); goto end; } if (CRYPTO_memcmp(hkdf_okm, out, sizeof(hkdf_okm)) != 0) { fprintf(stderr, "Generated key does not match expected value\n"); goto end; } printf("Success\n"); ret = EXIT_SUCCESS; end: EVP_KDF_CTX_free(kctx); EVP_KDF_free(kdf); OSSL_LIB_CTX_free(library_context); return ret; }
kdf
openssl/demos/kdf/hkdf.c
openssl
#include <openssl/evp.h> #include "dsa.inc" EVP_PKEY *dsa_genparams(OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *dsaparamkey = NULL; EVP_PKEY_CTX *ctx = NULL; ctx = EVP_PKEY_CTX_new_from_name(libctx, "DSA", propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n"); return NULL; } if (EVP_PKEY_paramgen_init(ctx) <= 0 || EVP_PKEY_paramgen(ctx, &dsaparamkey) <= 0) { fprintf(stderr, "DSA paramgen failed\n"); goto cleanup; } cleanup: EVP_PKEY_CTX_free(ctx); return dsaparamkey; } int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; EVP_PKEY *dsaparamskey = NULL; EVP_PKEY *dsakey = NULL; EVP_PKEY_CTX *ctx = NULL; dsaparamskey = dsa_genparams(libctx, propq); if (dsaparamskey == NULL) goto cleanup; ctx = EVP_PKEY_CTX_new_from_pkey(libctx, dsaparamskey, propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed\n"); goto cleanup; } if (EVP_PKEY_keygen_init(ctx) <= 0 || EVP_PKEY_keygen(ctx, &dsakey) <= 0) { fprintf(stderr, "DSA keygen failed\n"); goto cleanup; } if (!dsa_print_key(dsakey, 1, libctx, propq)) goto cleanup; ret = EXIT_SUCCESS; cleanup: EVP_PKEY_free(dsakey); EVP_PKEY_free(dsaparamskey); EVP_PKEY_CTX_free(ctx); return ret; }
pkey
openssl/demos/pkey/EVP_PKEY_DSA_keygen.c
openssl
#include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/rsa.h> #include <openssl/core_names.h> #include <openssl/pem.h> static const char *propq = NULL; static EVP_PKEY *generate_rsa_key_long(OSSL_LIB_CTX *libctx, unsigned int bits) { EVP_PKEY_CTX *genctx = NULL; EVP_PKEY *pkey = NULL; unsigned int primes = 2; genctx = EVP_PKEY_CTX_new_from_name(libctx, "RSA", propq); if (genctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n"); goto cleanup; } if (EVP_PKEY_keygen_init(genctx) <= 0) { fprintf(stderr, "EVP_PKEY_keygen_init() failed\n"); goto cleanup; } if (EVP_PKEY_CTX_set_rsa_keygen_bits(genctx, bits) <= 0) { fprintf(stderr, "EVP_PKEY_CTX_set_rsa_keygen_bits() failed\n"); goto cleanup; } if (EVP_PKEY_CTX_set_rsa_keygen_primes(genctx, primes) <= 0) { fprintf(stderr, "EVP_PKEY_CTX_set_rsa_keygen_primes() failed\n"); goto cleanup; } fprintf(stdout, "Generating RSA key, this may take some time...\n"); if (EVP_PKEY_generate(genctx, &pkey) <= 0) { fprintf(stderr, "EVP_PKEY_generate() failed\n"); goto cleanup; } cleanup: EVP_PKEY_CTX_free(genctx); return pkey; } static EVP_PKEY *generate_rsa_key_short(OSSL_LIB_CTX *libctx, unsigned int bits) { EVP_PKEY *pkey = NULL; fprintf(stdout, "Generating RSA key, this may take some time...\n"); pkey = EVP_PKEY_Q_keygen(libctx, propq, "RSA", (size_t)bits); if (pkey == NULL) fprintf(stderr, "EVP_PKEY_Q_keygen() failed\n"); return pkey; } static int dump_key(const EVP_PKEY *pkey) { int ret = 0; int bits = 0; BIGNUM *n = NULL, *e = NULL, *d = NULL, *p = NULL, *q = NULL; if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_N, &n) == 0) { fprintf(stderr, "Failed to retrieve n\n"); goto cleanup; } if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_E, &e) == 0) { fprintf(stderr, "Failed to retrieve e\n"); goto cleanup; } if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_D, &d) == 0) { fprintf(stderr, "Failed to retrieve d\n"); goto cleanup; } if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_FACTOR1, &p) == 0) { fprintf(stderr, "Failed to retrieve p\n"); goto cleanup; } if (EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_RSA_FACTOR2, &q) == 0) { fprintf(stderr, "Failed to retrieve q\n"); goto cleanup; } if (EVP_PKEY_get_int_param(pkey, OSSL_PKEY_PARAM_BITS, &bits) == 0) { fprintf(stderr, "Failed to retrieve bits\n"); goto cleanup; } fprintf(stdout, "\nNumber of bits: %d\n\n", bits); fprintf(stdout, "Public values:\n"); fprintf(stdout, " n = 0x"); BN_print_fp(stdout, n); fprintf(stdout, "\n"); fprintf(stdout, " e = 0x"); BN_print_fp(stdout, e); fprintf(stdout, "\n\n"); fprintf(stdout, "Private values:\n"); fprintf(stdout, " d = 0x"); BN_print_fp(stdout, d); fprintf(stdout, "\n"); fprintf(stdout, " p = 0x"); BN_print_fp(stdout, p); fprintf(stdout, "\n"); fprintf(stdout, " q = 0x"); BN_print_fp(stdout, q); fprintf(stdout, "\n\n"); if (PEM_write_PUBKEY(stdout, pkey) == 0) { fprintf(stderr, "Failed to output PEM-encoded public key\n"); goto cleanup; } if (PEM_write_PrivateKey(stdout, pkey, NULL, NULL, 0, NULL, NULL) == 0) { fprintf(stderr, "Failed to output PEM-encoded private key\n"); goto cleanup; } ret = 1; cleanup: BN_free(n); BN_free(e); BN_clear_free(d); BN_clear_free(p); BN_clear_free(q); return ret; } int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; EVP_PKEY *pkey = NULL; unsigned int bits = 4096; int bits_i, use_short = 0; if (argc > 1 && strcmp(argv[1], "-s") == 0) { --argc; ++argv; use_short = 1; } if (argc > 1) { bits_i = atoi(argv[1]); if (bits < 512) { fprintf(stderr, "Invalid RSA key size\n"); return EXIT_FAILURE; } bits = (unsigned int)bits_i; } if (bits < 2048) fprintf(stderr, "Warning: very weak key size\n\n"); if (use_short) pkey = generate_rsa_key_short(libctx, bits); else pkey = generate_rsa_key_long(libctx, bits); if (pkey == NULL) goto cleanup; if (dump_key(pkey) == 0) { fprintf(stderr, "Failed to dump key\n"); goto cleanup; } ret = EXIT_SUCCESS; cleanup: EVP_PKEY_free(pkey); OSSL_LIB_CTX_free(libctx); return ret; }
pkey
openssl/demos/pkey/EVP_PKEY_RSA_keygen.c
openssl
#include <openssl/evp.h> #include <openssl/core_names.h> #include <openssl/pem.h> #include "dsa.inc" static const char dsapem[] = "-----BEGIN DSA PARAMETERS-----\n" "MIICLAKCAQEA1pobSR1FJ3+Tvi0J6Tk1PSV2owZey1Nuo847hGw/59VCS6RPQEqr\n" "vp5fhbvBjupBeVGA/AMH6rI4i4h6jlhurrqH1CqUHVcDhJzxV668bMLiP3mIxg5o\n" "9Yq8x6BnSOtH5Je0tpeE0/fEvvLjCwBUbwnwWxzjANcvDUEt9XYeRrtB2v52fr56\n" "hVYz3wMMNog4CEDOLTvx7/84eVPuUeWDRQFH1EaHMdulP34KBcatEEpEZapkepng\n" "nohm9sFSPQhq2utpkH7pNXdG0EILBtRDCvUpF5720a48LYofdggh2VEZfgElAGFk\n" "dW/CkvyBDmGIzil5aTz4MMsdudaVYgzt6wIhAPsSGC42Qa+X0AFGvonb5nmfUVm/\n" "8aC+tHk7Nb2AYLHXAoIBADx5C0H1+QHsmGKvuOaY+WKUt7aWUrEivD1zBMJAQ6bL\n" "Wv9lbCq1CFHvVzojeOVpn872NqDEpkx4HTpvqhxWL5CkbN/HaGItsQzkD59AQg3v\n" "4YsLlkesq9Jq6x/aWetJXWO36fszFv1gpD3NY3wliBvMYHx62jfc5suh9D3ZZvu7\n" "PLGH4X4kcfzK/R2b0oVbEBjVTe5GMRYZRqnvfSW2f2fA7BzI1OL83UxDDe58cL2M\n" "GcAoUYXOBAfZ37qLMm2juf+o5gCrT4CXfRPu6kbapt7V/YIc1nsNgeAOKKoFBHBQ\n" "gc5u5G6G/j79FVoSDq9DYwTJcHPsU+eHj1uWHso1AjQ=\n" "-----END DSA PARAMETERS-----\n"; static const char hexseed[] = "cba30ccd905aa7675a0b81769704bf3c" "ccf2ca1892b2eaf6b9e2b38d9bf6affc" "42ada55986d8a1772b442770954d0b65"; const int gindex = 42; const int pcounter = 363; static const char digest[] = "SHA384"; EVP_PKEY_CTX *create_merged_key(EVP_PKEY *dsaparams, const OSSL_PARAM *newparams, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY_CTX *out = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *pkey = NULL; OSSL_PARAM *mergedparams = NULL; OSSL_PARAM *loadedparams = NULL; if (EVP_PKEY_todata(dsaparams, EVP_PKEY_KEY_PARAMETERS, &loadedparams) <= 0) { fprintf(stderr, "EVP_PKEY_todata() failed\n"); goto cleanup; } mergedparams = OSSL_PARAM_merge(loadedparams, newparams); if (mergedparams == NULL) { fprintf(stderr, "OSSL_PARAM_merge() failed\n"); goto cleanup; } ctx = EVP_PKEY_CTX_new_from_name(libctx, "DSA", propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n"); goto cleanup; } if (EVP_PKEY_fromdata_init(ctx) <= 0 || EVP_PKEY_fromdata(ctx, &pkey, EVP_PKEY_KEY_PARAMETERS, mergedparams) <= 0) { fprintf(stderr, "EVP_PKEY_fromdata() failed\n"); goto cleanup; } out = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (out == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed\n"); goto cleanup; } cleanup: EVP_PKEY_free(pkey); OSSL_PARAM_free(loadedparams); OSSL_PARAM_free(mergedparams); EVP_PKEY_CTX_free(ctx); return out; } int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; EVP_PKEY *dsaparamskey = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY_CTX *ctx1 = NULL; EVP_PKEY_CTX *ctx2 = NULL; BIO *in = NULL; OSSL_PARAM params[6]; unsigned char seed[64]; size_t seedlen; if (!OPENSSL_hexstr2buf_ex(seed, sizeof(seed), &seedlen, hexseed, '\0')) goto cleanup; in = BIO_new_mem_buf(dsapem, strlen(dsapem)); if (in == NULL) { fprintf(stderr, "BIO_new_mem_buf() failed\n"); goto cleanup; } dsaparamskey = PEM_read_bio_Parameters_ex(in, NULL, libctx, propq); if (dsaparamskey == NULL) { fprintf(stderr, "Failed to load dsa params\n"); goto cleanup; } ctx = EVP_PKEY_CTX_new_from_pkey(libctx, dsaparamskey, propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_pkey() failed\n"); goto cleanup; } if (EVP_PKEY_param_check(ctx) <= 0) { fprintf(stderr, "Simple EVP_PKEY_param_check() failed \n"); goto cleanup; } params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_TYPE, "fips186_4", 0); params[1] = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_FFC_SEED, (void *)seed, seedlen); params[2] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_FFC_GINDEX, (int *)&gindex); params[3] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_FFC_PCOUNTER, (int *)&pcounter); params[4] = OSSL_PARAM_construct_end(); ctx1 = create_merged_key(dsaparamskey, params, libctx, propq); if (ctx1 == NULL) goto cleanup; if (EVP_PKEY_param_check(ctx1) > 0) { fprintf(stderr, "EVP_PKEY_param_check() should fail\n"); goto cleanup; } params[4] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_DIGEST, (char *)digest, 0); params[5] = OSSL_PARAM_construct_end(); ctx2 = create_merged_key(dsaparamskey, params, libctx, propq); if (ctx2 == NULL) goto cleanup; if (EVP_PKEY_param_check(ctx2) <= 0) { fprintf(stderr, "EVP_PKEY_param_check() failed\n"); goto cleanup; } if (!dsa_print_key(EVP_PKEY_CTX_get0_pkey(ctx2), 0, libctx, propq)) goto cleanup; ret = EXIT_SUCCESS; cleanup: EVP_PKEY_free(dsaparamskey); EVP_PKEY_CTX_free(ctx2); EVP_PKEY_CTX_free(ctx1); EVP_PKEY_CTX_free(ctx); BIO_free(in); return ret; }
pkey
openssl/demos/pkey/EVP_PKEY_DSA_paramvalidate.c
openssl
#include <openssl/param_build.h> #include <openssl/evp.h> #include <openssl/core_names.h> #include "dsa.inc" int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *dsaparamkey = NULL; OSSL_PARAM_BLD *bld = NULL; OSSL_PARAM *params = NULL; BIGNUM *p = NULL, *q = NULL, *g = NULL; p = BN_bin2bn(dsa_p, sizeof(dsa_p), NULL); q = BN_bin2bn(dsa_q, sizeof(dsa_q), NULL); g = BN_bin2bn(dsa_g, sizeof(dsa_g), NULL); if (p == NULL || q == NULL || g == NULL) goto cleanup; bld = OSSL_PARAM_BLD_new(); if (bld == NULL) goto cleanup; if (!OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_P, p) || !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_Q, q) || !OSSL_PARAM_BLD_push_BN(bld, OSSL_PKEY_PARAM_FFC_G, g)) goto cleanup; params = OSSL_PARAM_BLD_to_param(bld); if (params == NULL) goto cleanup; ctx = EVP_PKEY_CTX_new_from_name(libctx, "DSA", propq); if (ctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n"); goto cleanup; } if (EVP_PKEY_fromdata_init(ctx) <= 0 || EVP_PKEY_fromdata(ctx, &dsaparamkey, EVP_PKEY_KEY_PARAMETERS, params) <= 0) { fprintf(stderr, "EVP_PKEY_fromdata() failed\n"); goto cleanup; } if (!dsa_print_key(dsaparamkey, 0, libctx, propq)) goto cleanup; ret = EXIT_SUCCESS; cleanup: EVP_PKEY_free(dsaparamkey); EVP_PKEY_CTX_free(ctx); OSSL_PARAM_free(params); OSSL_PARAM_BLD_free(bld); BN_free(g); BN_free(q); BN_free(p); return ret; }
pkey
openssl/demos/pkey/EVP_PKEY_DSA_paramfromdata.c
openssl
#include <string.h> #include <stdio.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/core_names.h> static int get_key_values(EVP_PKEY *pkey); static EVP_PKEY *do_ec_keygen(void) { OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; EVP_PKEY *key = NULL; OSSL_PARAM params[3]; EVP_PKEY_CTX *genctx = NULL; const char *curvename = "P-256"; int use_cofactordh = 1; genctx = EVP_PKEY_CTX_new_from_name(libctx, "EC", propq); if (genctx == NULL) { fprintf(stderr, "EVP_PKEY_CTX_new_from_name() failed\n"); goto cleanup; } if (EVP_PKEY_keygen_init(genctx) <= 0) { fprintf(stderr, "EVP_PKEY_keygen_init() failed\n"); goto cleanup; } params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME, (char *)curvename, 0); params[1] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_USE_COFACTOR_ECDH, &use_cofactordh); params[2] = OSSL_PARAM_construct_end(); if (!EVP_PKEY_CTX_set_params(genctx, params)) { fprintf(stderr, "EVP_PKEY_CTX_set_params() failed\n"); goto cleanup; } fprintf(stdout, "Generating EC key\n\n"); if (EVP_PKEY_generate(genctx, &key) <= 0) { fprintf(stderr, "EVP_PKEY_generate() failed\n"); goto cleanup; } cleanup: EVP_PKEY_CTX_free(genctx); return key; } static int get_key_values(EVP_PKEY *pkey) { int ret = 0; char out_curvename[80]; unsigned char out_pubkey[80]; unsigned char out_privkey[80]; BIGNUM *out_priv = NULL; size_t out_pubkey_len, out_privkey_len = 0; if (!EVP_PKEY_get_utf8_string_param(pkey, OSSL_PKEY_PARAM_GROUP_NAME, out_curvename, sizeof(out_curvename), NULL)) { fprintf(stderr, "Failed to get curve name\n"); goto cleanup; } if (!EVP_PKEY_get_octet_string_param(pkey, OSSL_PKEY_PARAM_PUB_KEY, out_pubkey, sizeof(out_pubkey), &out_pubkey_len)) { fprintf(stderr, "Failed to get public key\n"); goto cleanup; } if (!EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_PRIV_KEY, &out_priv)) { fprintf(stderr, "Failed to get private key\n"); goto cleanup; } out_privkey_len = BN_bn2bin(out_priv, out_privkey); if (out_privkey_len <= 0 || out_privkey_len > sizeof(out_privkey)) { fprintf(stderr, "BN_bn2bin failed\n"); goto cleanup; } fprintf(stdout, "Curve name: %s\n", out_curvename); fprintf(stdout, "Public key:\n"); BIO_dump_indent_fp(stdout, out_pubkey, out_pubkey_len, 2); fprintf(stdout, "Private Key:\n"); BIO_dump_indent_fp(stdout, out_privkey, out_privkey_len, 2); ret = 1; cleanup: BN_clear_free(out_priv); return ret; } int main(void) { int ret = EXIT_FAILURE; EVP_PKEY *pkey; pkey = do_ec_keygen(); if (pkey == NULL) goto cleanup; if (!get_key_values(pkey)) goto cleanup; ret = EXIT_SUCCESS; cleanup: if (ret != EXIT_SUCCESS) ERR_print_errors_fp(stderr); EVP_PKEY_free(pkey); return ret; }
pkey
openssl/demos/pkey/EVP_PKEY_EC_keygen.c
openssl
#include <openssl/evp.h> #include "dsa.inc" int main(int argc, char **argv) { int ret = EXIT_FAILURE; OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; EVP_PKEY_CTX *ctx = NULL; EVP_PKEY *dsaparamkey = NULL; OSSL_PARAM params[7]; unsigned int pbits = 2048; unsigned int qbits = 256; int gindex = 42; ctx = EVP_PKEY_CTX_new_from_name(libctx, "DSA", propq); if (ctx == NULL) goto cleanup; params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_TYPE, "fips186_4", 0); params[1] = OSSL_PARAM_construct_uint(OSSL_PKEY_PARAM_FFC_PBITS, &pbits); params[2] = OSSL_PARAM_construct_uint(OSSL_PKEY_PARAM_FFC_QBITS, &qbits); params[3] = OSSL_PARAM_construct_int(OSSL_PKEY_PARAM_FFC_GINDEX, &gindex); params[4] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_DIGEST, "SHA384", 0); params[5] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_FFC_DIGEST_PROPS, "provider=default", 0); params[6] = OSSL_PARAM_construct_end(); if (EVP_PKEY_paramgen_init(ctx) <= 0 || EVP_PKEY_CTX_set_params(ctx, params) <= 0 || EVP_PKEY_paramgen(ctx, &dsaparamkey) <= 0) { fprintf(stderr, "DSA paramgen failed\n"); goto cleanup; } if (!dsa_print_key(dsaparamkey, 0, libctx, propq)) goto cleanup; ret = EXIT_SUCCESS; cleanup: EVP_PKEY_free(dsaparamkey); EVP_PKEY_CTX_free(ctx); return ret; }
pkey
openssl/demos/pkey/EVP_PKEY_DSA_paramgen.c
openssl