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, ¶ms_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 |
"\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <ctype.h>\n#include <sys/t(...TRUNCATED) | apps | openssl/apps/ca.c | openssl |
End of preview. Expand
in Dataset Viewer.
No dataset card yet
- Downloads last month
- 8