repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
openssl
|
openssl-master/crypto/x509/by_dir.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#if defined (__TANDEM) && defined (_SPT_MODEL_)
/*
* These definitions have to come first in SPT due to scoping of the
* declarations in c99 associated with SPT use of stat.
*/
# include <sys/types.h>
# include <sys/stat.h>
#endif
#include "internal/e_os.h"
#include "internal/cryptlib.h"
#include <stdio.h>
#include <time.h>
#include <errno.h>
#include <sys/types.h>
#ifndef OPENSSL_NO_POSIX_IO
# include <sys/stat.h>
#endif
#include <openssl/x509.h>
#include "crypto/x509.h"
#include "x509_local.h"
struct lookup_dir_hashes_st {
unsigned long hash;
int suffix;
};
struct lookup_dir_entry_st {
char *dir;
int dir_type;
STACK_OF(BY_DIR_HASH) *hashes;
};
typedef struct lookup_dir_st {
BUF_MEM *buffer;
STACK_OF(BY_DIR_ENTRY) *dirs;
CRYPTO_RWLOCK *lock;
} BY_DIR;
static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl,
char **retp);
static int new_dir(X509_LOOKUP *lu);
static void free_dir(X509_LOOKUP *lu);
static int add_cert_dir(BY_DIR *ctx, const char *dir, int type);
static int get_cert_by_subject(X509_LOOKUP *xl, X509_LOOKUP_TYPE type,
const X509_NAME *name, X509_OBJECT *ret);
static int get_cert_by_subject_ex(X509_LOOKUP *xl, X509_LOOKUP_TYPE type,
const X509_NAME *name, X509_OBJECT *ret,
OSSL_LIB_CTX *libctx, const char *propq);
static X509_LOOKUP_METHOD x509_dir_lookup = {
"Load certs from files in a directory",
new_dir, /* new_item */
free_dir, /* free */
NULL, /* init */
NULL, /* shutdown */
dir_ctrl, /* ctrl */
get_cert_by_subject, /* get_by_subject */
NULL, /* get_by_issuer_serial */
NULL, /* get_by_fingerprint */
NULL, /* get_by_alias */
get_cert_by_subject_ex, /* get_by_subject_ex */
NULL, /* ctrl_ex */
};
X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir(void)
{
return &x509_dir_lookup;
}
static int dir_ctrl(X509_LOOKUP *ctx, int cmd, const char *argp, long argl,
char **retp)
{
int ret = 0;
BY_DIR *ld = (BY_DIR *)ctx->method_data;
switch (cmd) {
case X509_L_ADD_DIR:
if (argl == X509_FILETYPE_DEFAULT) {
const char *dir = ossl_safe_getenv(X509_get_default_cert_dir_env());
if (dir)
ret = add_cert_dir(ld, dir, X509_FILETYPE_PEM);
else
ret = add_cert_dir(ld, X509_get_default_cert_dir(),
X509_FILETYPE_PEM);
if (!ret) {
ERR_raise(ERR_LIB_X509, X509_R_LOADING_CERT_DIR);
}
} else
ret = add_cert_dir(ld, argp, (int)argl);
break;
}
return ret;
}
static int new_dir(X509_LOOKUP *lu)
{
BY_DIR *a = OPENSSL_malloc(sizeof(*a));
if (a == NULL)
return 0;
if ((a->buffer = BUF_MEM_new()) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_BN_LIB);
goto err;
}
a->dirs = NULL;
a->lock = CRYPTO_THREAD_lock_new();
if (a->lock == NULL) {
BUF_MEM_free(a->buffer);
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
}
lu->method_data = a;
return 1;
err:
OPENSSL_free(a);
return 0;
}
static void by_dir_hash_free(BY_DIR_HASH *hash)
{
OPENSSL_free(hash);
}
static int by_dir_hash_cmp(const BY_DIR_HASH *const *a,
const BY_DIR_HASH *const *b)
{
if ((*a)->hash > (*b)->hash)
return 1;
if ((*a)->hash < (*b)->hash)
return -1;
return 0;
}
static void by_dir_entry_free(BY_DIR_ENTRY *ent)
{
OPENSSL_free(ent->dir);
sk_BY_DIR_HASH_pop_free(ent->hashes, by_dir_hash_free);
OPENSSL_free(ent);
}
static void free_dir(X509_LOOKUP *lu)
{
BY_DIR *a = (BY_DIR *)lu->method_data;
sk_BY_DIR_ENTRY_pop_free(a->dirs, by_dir_entry_free);
BUF_MEM_free(a->buffer);
CRYPTO_THREAD_lock_free(a->lock);
OPENSSL_free(a);
}
static int add_cert_dir(BY_DIR *ctx, const char *dir, int type)
{
int j;
size_t len;
const char *s, *ss, *p;
if (dir == NULL || *dir == '\0') {
ERR_raise(ERR_LIB_X509, X509_R_INVALID_DIRECTORY);
return 0;
}
s = dir;
p = s;
do {
if ((*p == LIST_SEPARATOR_CHAR) || (*p == '\0')) {
BY_DIR_ENTRY *ent;
ss = s;
s = p + 1;
len = p - ss;
if (len == 0)
continue;
for (j = 0; j < sk_BY_DIR_ENTRY_num(ctx->dirs); j++) {
ent = sk_BY_DIR_ENTRY_value(ctx->dirs, j);
if (strlen(ent->dir) == len && strncmp(ent->dir, ss, len) == 0)
break;
}
if (j < sk_BY_DIR_ENTRY_num(ctx->dirs))
continue;
if (ctx->dirs == NULL) {
ctx->dirs = sk_BY_DIR_ENTRY_new_null();
if (!ctx->dirs) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
return 0;
}
}
ent = OPENSSL_malloc(sizeof(*ent));
if (ent == NULL)
return 0;
ent->dir_type = type;
ent->hashes = sk_BY_DIR_HASH_new(by_dir_hash_cmp);
ent->dir = OPENSSL_strndup(ss, len);
if (ent->dir == NULL || ent->hashes == NULL) {
by_dir_entry_free(ent);
return 0;
}
if (!sk_BY_DIR_ENTRY_push(ctx->dirs, ent)) {
by_dir_entry_free(ent);
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
return 0;
}
}
} while (*p++ != '\0');
return 1;
}
static int get_cert_by_subject_ex(X509_LOOKUP *xl, X509_LOOKUP_TYPE type,
const X509_NAME *name, X509_OBJECT *ret,
OSSL_LIB_CTX *libctx, const char *propq)
{
BY_DIR *ctx;
union {
X509 st_x509;
X509_CRL crl;
} data;
int ok = 0;
int i, j, k;
unsigned long h;
BUF_MEM *b = NULL;
X509_OBJECT stmp, *tmp;
const char *postfix = "";
if (name == NULL)
return 0;
stmp.type = type;
if (type == X509_LU_X509) {
data.st_x509.cert_info.subject = (X509_NAME *)name; /* won't modify it */
stmp.data.x509 = &data.st_x509;
} else if (type == X509_LU_CRL) {
data.crl.crl.issuer = (X509_NAME *)name; /* won't modify it */
stmp.data.crl = &data.crl;
postfix = "r";
} else {
ERR_raise(ERR_LIB_X509, X509_R_WRONG_LOOKUP_TYPE);
goto finish;
}
if ((b = BUF_MEM_new()) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
goto finish;
}
ctx = (BY_DIR *)xl->method_data;
h = X509_NAME_hash_ex(name, libctx, propq, &i);
if (i == 0)
goto finish;
for (i = 0; i < sk_BY_DIR_ENTRY_num(ctx->dirs); i++) {
BY_DIR_ENTRY *ent;
int idx;
BY_DIR_HASH htmp, *hent;
ent = sk_BY_DIR_ENTRY_value(ctx->dirs, i);
j = strlen(ent->dir) + 1 + 8 + 6 + 1 + 1;
if (!BUF_MEM_grow(b, j)) {
ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
goto finish;
}
if (type == X509_LU_CRL && ent->hashes) {
htmp.hash = h;
if (!CRYPTO_THREAD_read_lock(ctx->lock))
goto finish;
idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp);
if (idx >= 0) {
hent = sk_BY_DIR_HASH_value(ent->hashes, idx);
k = hent->suffix;
} else {
hent = NULL;
k = 0;
}
CRYPTO_THREAD_unlock(ctx->lock);
} else {
k = 0;
hent = NULL;
}
for (;;) {
char c = '/';
#ifdef OPENSSL_SYS_VMS
c = ent->dir[strlen(ent->dir) - 1];
if (c != ':' && c != '>' && c != ']') {
/*
* If no separator is present, we assume the directory
* specifier is a logical name, and add a colon. We really
* should use better VMS routines for merging things like
* this, but this will do for now... -- Richard Levitte
*/
c = ':';
} else {
c = '\0';
}
if (c == '\0') {
/*
* This is special. When c == '\0', no directory separator
* should be added.
*/
BIO_snprintf(b->data, b->max,
"%s%08lx.%s%d", ent->dir, h, postfix, k);
} else
#endif
{
BIO_snprintf(b->data, b->max,
"%s%c%08lx.%s%d", ent->dir, c, h, postfix, k);
}
#ifndef OPENSSL_NO_POSIX_IO
# ifdef _WIN32
# define stat _stat
# endif
{
struct stat st;
if (stat(b->data, &st) < 0)
break;
}
#endif
/* found one. */
if (type == X509_LU_X509) {
if ((X509_load_cert_file_ex(xl, b->data, ent->dir_type, libctx,
propq)) == 0)
break;
} else if (type == X509_LU_CRL) {
if ((X509_load_crl_file(xl, b->data, ent->dir_type)) == 0)
break;
}
/* else case will caught higher up */
k++;
}
/*
* we have added it to the cache so now pull it out again
*
* Note: quadratic time find here since the objects won't generally be
* sorted and sorting the would result in O(n^2 log n) complexity.
*/
if (k > 0) {
X509_STORE_lock(xl->store_ctx);
j = sk_X509_OBJECT_find(xl->store_ctx->objs, &stmp);
tmp = sk_X509_OBJECT_value(xl->store_ctx->objs, j);
X509_STORE_unlock(xl->store_ctx);
} else {
tmp = NULL;
}
/*
* If a CRL, update the last file suffix added for this.
* We don't need to add an entry if k is 0 as this is the initial value.
* This avoids the need for a write lock and sort operation in the
* simple case where no CRL is present for a hash.
*/
if (type == X509_LU_CRL && k > 0) {
if (!CRYPTO_THREAD_write_lock(ctx->lock))
goto finish;
/*
* Look for entry again in case another thread added an entry
* first.
*/
if (hent == NULL) {
htmp.hash = h;
idx = sk_BY_DIR_HASH_find(ent->hashes, &htmp);
hent = sk_BY_DIR_HASH_value(ent->hashes, idx);
}
if (hent == NULL) {
hent = OPENSSL_malloc(sizeof(*hent));
if (hent == NULL) {
CRYPTO_THREAD_unlock(ctx->lock);
ok = 0;
goto finish;
}
hent->hash = h;
hent->suffix = k;
if (!sk_BY_DIR_HASH_push(ent->hashes, hent)) {
CRYPTO_THREAD_unlock(ctx->lock);
OPENSSL_free(hent);
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
ok = 0;
goto finish;
}
/*
* Ensure stack is sorted so that subsequent sk_BY_DIR_HASH_find
* will not mutate the stack and therefore require a write lock.
*/
sk_BY_DIR_HASH_sort(ent->hashes);
} else if (hent->suffix < k) {
hent->suffix = k;
}
CRYPTO_THREAD_unlock(ctx->lock);
}
if (tmp != NULL) {
ok = 1;
ret->type = tmp->type;
memcpy(&ret->data, &tmp->data, sizeof(ret->data));
/*
* Clear any errors that might have been raised processing empty
* or malformed files.
*/
ERR_clear_error();
goto finish;
}
}
finish:
/* If we changed anything, resort the objects for faster lookup */
if (!sk_X509_OBJECT_is_sorted(xl->store_ctx->objs)) {
X509_STORE_lock(xl->store_ctx);
sk_X509_OBJECT_sort(xl->store_ctx->objs);
X509_STORE_unlock(xl->store_ctx);
}
BUF_MEM_free(b);
return ok;
}
static int get_cert_by_subject(X509_LOOKUP *xl, X509_LOOKUP_TYPE type,
const X509_NAME *name, X509_OBJECT *ret)
{
return get_cert_by_subject_ex(xl, type, name, ret, NULL, NULL);
}
| 13,307 | 29.453089 | 81 |
c
|
openssl
|
openssl-master/crypto/x509/by_file.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <time.h>
#include <errno.h>
#include "internal/cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include "x509_local.h"
static int by_file_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc,
long argl, char **ret);
static int by_file_ctrl_ex(X509_LOOKUP *ctx, int cmd, const char *argc,
long argl, char **ret, OSSL_LIB_CTX *libctx,
const char *propq);
static X509_LOOKUP_METHOD x509_file_lookup = {
"Load file into cache",
NULL, /* new_item */
NULL, /* free */
NULL, /* init */
NULL, /* shutdown */
by_file_ctrl, /* ctrl */
NULL, /* get_by_subject */
NULL, /* get_by_issuer_serial */
NULL, /* get_by_fingerprint */
NULL, /* get_by_alias */
NULL, /* get_by_subject_ex */
by_file_ctrl_ex, /* ctrl_ex */
};
X509_LOOKUP_METHOD *X509_LOOKUP_file(void)
{
return &x509_file_lookup;
}
static int by_file_ctrl_ex(X509_LOOKUP *ctx, int cmd, const char *argp,
long argl, char **ret, OSSL_LIB_CTX *libctx,
const char *propq)
{
int ok = 0;
const char *file;
switch (cmd) {
case X509_L_FILE_LOAD:
if (argl == X509_FILETYPE_DEFAULT) {
file = ossl_safe_getenv(X509_get_default_cert_file_env());
if (file)
ok = (X509_load_cert_crl_file_ex(ctx, file, X509_FILETYPE_PEM,
libctx, propq) != 0);
else
ok = (X509_load_cert_crl_file_ex(
ctx, X509_get_default_cert_file(),
X509_FILETYPE_PEM, libctx, propq) != 0);
if (!ok) {
ERR_raise(ERR_LIB_X509, X509_R_LOADING_DEFAULTS);
}
} else {
if (argl == X509_FILETYPE_PEM)
ok = (X509_load_cert_crl_file_ex(ctx, argp, X509_FILETYPE_PEM,
libctx, propq) != 0);
else
ok = (X509_load_cert_file_ex(ctx, argp, (int)argl, libctx,
propq) != 0);
}
break;
}
return ok;
}
static int by_file_ctrl(X509_LOOKUP *ctx, int cmd,
const char *argp, long argl, char **ret)
{
return by_file_ctrl_ex(ctx, cmd, argp, argl, ret, NULL, NULL);
}
int X509_load_cert_file_ex(X509_LOOKUP *ctx, const char *file, int type,
OSSL_LIB_CTX *libctx, const char *propq)
{
int ret = 0;
BIO *in = NULL;
int i, count = 0;
X509 *x = NULL;
in = BIO_new(BIO_s_file());
if ((in == NULL) || (BIO_read_filename(in, file) <= 0)) {
ERR_raise(ERR_LIB_X509, ERR_R_SYS_LIB);
goto err;
}
if (type != X509_FILETYPE_PEM && type != X509_FILETYPE_ASN1) {
ERR_raise(ERR_LIB_X509, X509_R_BAD_X509_FILETYPE);
goto err;
}
x = X509_new_ex(libctx, propq);
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
goto err;
}
if (type == X509_FILETYPE_PEM) {
for (;;) {
ERR_set_mark();
if (PEM_read_bio_X509_AUX(in, &x, NULL, "") == NULL) {
if ((ERR_GET_REASON(ERR_peek_last_error()) ==
PEM_R_NO_START_LINE) && (count > 0)) {
ERR_pop_to_mark();
break;
} else {
ERR_clear_last_mark();
goto err;
}
}
ERR_clear_last_mark();
i = X509_STORE_add_cert(ctx->store_ctx, x);
if (!i)
goto err;
count++;
X509_free(x);
x = NULL;
}
ret = count;
} else if (type == X509_FILETYPE_ASN1) {
if (d2i_X509_bio(in, &x) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
goto err;
}
i = X509_STORE_add_cert(ctx->store_ctx, x);
if (!i)
goto err;
ret = i;
}
if (ret == 0)
ERR_raise(ERR_LIB_X509, X509_R_NO_CERTIFICATE_FOUND);
err:
X509_free(x);
BIO_free(in);
return ret;
}
int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type)
{
return X509_load_cert_file_ex(ctx, file, type, NULL, NULL);
}
int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type)
{
int ret = 0;
BIO *in = NULL;
int i, count = 0;
X509_CRL *x = NULL;
in = BIO_new(BIO_s_file());
if ((in == NULL) || (BIO_read_filename(in, file) <= 0)) {
ERR_raise(ERR_LIB_X509, ERR_R_SYS_LIB);
goto err;
}
if (type == X509_FILETYPE_PEM) {
for (;;) {
x = PEM_read_bio_X509_CRL(in, NULL, NULL, "");
if (x == NULL) {
if ((ERR_GET_REASON(ERR_peek_last_error()) ==
PEM_R_NO_START_LINE) && (count > 0)) {
ERR_clear_error();
break;
} else {
ERR_raise(ERR_LIB_X509, ERR_R_PEM_LIB);
goto err;
}
}
i = X509_STORE_add_crl(ctx->store_ctx, x);
if (!i)
goto err;
count++;
X509_CRL_free(x);
x = NULL;
}
ret = count;
} else if (type == X509_FILETYPE_ASN1) {
x = d2i_X509_CRL_bio(in, NULL);
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
goto err;
}
i = X509_STORE_add_crl(ctx->store_ctx, x);
if (!i)
goto err;
ret = i;
} else {
ERR_raise(ERR_LIB_X509, X509_R_BAD_X509_FILETYPE);
goto err;
}
if (ret == 0)
ERR_raise(ERR_LIB_X509, X509_R_NO_CRL_FOUND);
err:
X509_CRL_free(x);
BIO_free(in);
return ret;
}
int X509_load_cert_crl_file_ex(X509_LOOKUP *ctx, const char *file, int type,
OSSL_LIB_CTX *libctx, const char *propq)
{
STACK_OF(X509_INFO) *inf;
X509_INFO *itmp;
BIO *in;
int i, count = 0;
if (type != X509_FILETYPE_PEM)
return X509_load_cert_file_ex(ctx, file, type, libctx, propq);
in = BIO_new_file(file, "r");
if (!in) {
ERR_raise(ERR_LIB_X509, ERR_R_SYS_LIB);
return 0;
}
inf = PEM_X509_INFO_read_bio_ex(in, NULL, NULL, "", libctx, propq);
BIO_free(in);
if (!inf) {
ERR_raise(ERR_LIB_X509, ERR_R_PEM_LIB);
return 0;
}
for (i = 0; i < sk_X509_INFO_num(inf); i++) {
itmp = sk_X509_INFO_value(inf, i);
if (itmp->x509) {
if (!X509_STORE_add_cert(ctx->store_ctx, itmp->x509))
goto err;
count++;
}
if (itmp->crl) {
if (!X509_STORE_add_crl(ctx->store_ctx, itmp->crl))
goto err;
count++;
}
}
if (count == 0)
ERR_raise(ERR_LIB_X509, X509_R_NO_CERTIFICATE_OR_CRL_FOUND);
err:
sk_X509_INFO_pop_free(inf, X509_INFO_free);
return count;
}
int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type)
{
return X509_load_cert_crl_file_ex(ctx, file, type, NULL, NULL);
}
| 7,836 | 28.912214 | 78 |
c
|
openssl
|
openssl-master/crypto/x509/by_store.c
|
/*
* Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/store.h>
#include "internal/cryptlib.h"
#include "crypto/x509.h"
#include "x509_local.h"
/* Generic object loader, given expected type and criterion */
static int cache_objects(X509_LOOKUP *lctx, const char *uri,
const OSSL_STORE_SEARCH *criterion,
int depth, OSSL_LIB_CTX *libctx, const char *propq)
{
int ok = 0;
OSSL_STORE_CTX *ctx = NULL;
X509_STORE *xstore = X509_LOOKUP_get_store(lctx);
if ((ctx = OSSL_STORE_open_ex(uri, libctx, propq, NULL, NULL, NULL,
NULL, NULL)) == NULL)
return 0;
/*
* We try to set the criterion, but don't care if it was valid or not.
* For an OSSL_STORE, it merely serves as an optimization, the expectation
* being that if the criterion couldn't be used, we will get *everything*
* from the container that the URI represents rather than the subset that
* the criterion indicates, so the biggest harm is that we cache more
* objects certs and CRLs than we may expect, but that's ok.
*
* Specifically for OpenSSL's own file: scheme, the only workable
* criterion is the BY_NAME one, which it can only apply on directories,
* but it's possible that the URI is a single file rather than a directory,
* and in that case, the BY_NAME criterion is pointless.
*
* We could very simply not apply any criterion at all here, and just let
* the code that selects certs and CRLs from the cached objects do its job,
* but it's a nice optimization when it can be applied (such as on an
* actual directory with a thousand CA certs).
*/
if (criterion != NULL)
OSSL_STORE_find(ctx, criterion);
for (;;) {
OSSL_STORE_INFO *info = OSSL_STORE_load(ctx);
int infotype;
/* NULL means error or "end of file". Either way, we break. */
if (info == NULL)
break;
infotype = OSSL_STORE_INFO_get_type(info);
ok = 0;
if (infotype == OSSL_STORE_INFO_NAME) {
/*
* This is an entry in the "directory" represented by the current
* uri. if |depth| allows, dive into it.
*/
if (depth > 0)
ok = cache_objects(lctx, OSSL_STORE_INFO_get0_NAME(info),
criterion, depth - 1, libctx, propq);
} else {
/*
* We know that X509_STORE_add_{cert|crl} increments the object's
* refcount, so we can safely use OSSL_STORE_INFO_get0_{cert,crl}
* to get them.
*/
switch (infotype) {
case OSSL_STORE_INFO_CERT:
ok = X509_STORE_add_cert(xstore,
OSSL_STORE_INFO_get0_CERT(info));
break;
case OSSL_STORE_INFO_CRL:
ok = X509_STORE_add_crl(xstore,
OSSL_STORE_INFO_get0_CRL(info));
break;
}
}
OSSL_STORE_INFO_free(info);
if (!ok)
break;
}
OSSL_STORE_close(ctx);
return ok;
}
/* Because OPENSSL_free is a macro and for C type match */
static void free_uri(OPENSSL_STRING data)
{
OPENSSL_free(data);
}
static void by_store_free(X509_LOOKUP *ctx)
{
STACK_OF(OPENSSL_STRING) *uris = X509_LOOKUP_get_method_data(ctx);
sk_OPENSSL_STRING_pop_free(uris, free_uri);
}
static int by_store_ctrl_ex(X509_LOOKUP *ctx, int cmd, const char *argp,
long argl, char **retp, OSSL_LIB_CTX *libctx,
const char *propq)
{
switch (cmd) {
case X509_L_ADD_STORE:
/* If no URI is given, use the default cert dir as default URI */
if (argp == NULL)
argp = ossl_safe_getenv(X509_get_default_cert_dir_env());
if (argp == NULL)
argp = X509_get_default_cert_dir();
{
STACK_OF(OPENSSL_STRING) *uris = X509_LOOKUP_get_method_data(ctx);
char *data = OPENSSL_strdup(argp);
if (data == NULL) {
return 0;
}
if (uris == NULL) {
uris = sk_OPENSSL_STRING_new_null();
X509_LOOKUP_set_method_data(ctx, uris);
}
return sk_OPENSSL_STRING_push(uris, data) > 0;
}
case X509_L_LOAD_STORE:
/* This is a shortcut for quick loading of specific containers */
return cache_objects(ctx, argp, NULL, 0, libctx, propq);
}
return 0;
}
static int by_store_ctrl(X509_LOOKUP *ctx, int cmd,
const char *argp, long argl, char **retp)
{
return by_store_ctrl_ex(ctx, cmd, argp, argl, retp, NULL, NULL);
}
static int by_store(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const OSSL_STORE_SEARCH *criterion, X509_OBJECT *ret,
OSSL_LIB_CTX *libctx, const char *propq)
{
STACK_OF(OPENSSL_STRING) *uris = X509_LOOKUP_get_method_data(ctx);
int i;
int ok = 0;
for (i = 0; i < sk_OPENSSL_STRING_num(uris); i++) {
ok = cache_objects(ctx, sk_OPENSSL_STRING_value(uris, i), criterion,
1 /* depth */, libctx, propq);
if (ok)
break;
}
return ok;
}
static int by_store_subject_ex(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const X509_NAME *name, X509_OBJECT *ret,
OSSL_LIB_CTX *libctx, const char *propq)
{
OSSL_STORE_SEARCH *criterion =
OSSL_STORE_SEARCH_by_name((X509_NAME *)name); /* won't modify it */
int ok = by_store(ctx, type, criterion, ret, libctx, propq);
STACK_OF(X509_OBJECT) *store_objects =
X509_STORE_get0_objects(X509_LOOKUP_get_store(ctx));
X509_OBJECT *tmp = NULL;
OSSL_STORE_SEARCH_free(criterion);
if (ok)
tmp = X509_OBJECT_retrieve_by_subject(store_objects, type, name);
ok = 0;
if (tmp != NULL) {
/*
* This could also be done like this:
*
* if (tmp != NULL) {
* *ret = *tmp;
* ok = 1;
* }
*
* However, we want to exercise the documented API to the max, so
* we do it the hard way.
*
* To be noted is that X509_OBJECT_set1_* increment the refcount,
* but so does X509_STORE_CTX_get_by_subject upon return of this
* function, so we must ensure the refcount is decremented
* before we return, or we will get a refcount leak. We cannot do
* this with X509_OBJECT_free(), though, as that will free a bit
* too much.
*/
switch (type) {
case X509_LU_X509:
ok = X509_OBJECT_set1_X509(ret, tmp->data.x509);
if (ok)
X509_free(tmp->data.x509);
break;
case X509_LU_CRL:
ok = X509_OBJECT_set1_X509_CRL(ret, tmp->data.crl);
if (ok)
X509_CRL_free(tmp->data.crl);
break;
case X509_LU_NONE:
break;
}
}
return ok;
}
static int by_store_subject(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const X509_NAME *name, X509_OBJECT *ret)
{
return by_store_subject_ex(ctx, type, name, ret, NULL, NULL);
}
/*
* We lack the implementations for get_by_issuer_serial, get_by_fingerprint
* and get_by_alias. There's simply not enough support in the X509_LOOKUP
* or X509_STORE APIs.
*/
static X509_LOOKUP_METHOD x509_store_lookup = {
"Load certs from STORE URIs",
NULL, /* new_item */
by_store_free, /* free */
NULL, /* init */
NULL, /* shutdown */
by_store_ctrl, /* ctrl */
by_store_subject, /* get_by_subject */
NULL, /* get_by_issuer_serial */
NULL, /* get_by_fingerprint */
NULL, /* get_by_alias */
by_store_subject_ex,
by_store_ctrl_ex
};
X509_LOOKUP_METHOD *X509_LOOKUP_store(void)
{
return &x509_store_lookup;
}
| 8,569 | 33.143426 | 79 |
c
|
openssl
|
openssl-master/crypto/x509/ext_dat.h
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
int ossl_v3_name_cmp(const char *name, const char *cmp);
extern const X509V3_EXT_METHOD ossl_v3_bcons, ossl_v3_nscert, ossl_v3_key_usage, ossl_v3_ext_ku;
extern const X509V3_EXT_METHOD ossl_v3_pkey_usage_period, ossl_v3_sxnet, ossl_v3_info, ossl_v3_sinfo;
extern const X509V3_EXT_METHOD ossl_v3_ns_ia5_list[8], ossl_v3_alt[3], ossl_v3_skey_id, ossl_v3_akey_id;
extern const X509V3_EXT_METHOD ossl_v3_crl_num, ossl_v3_crl_reason, ossl_v3_crl_invdate;
extern const X509V3_EXT_METHOD ossl_v3_delta_crl, ossl_v3_cpols, ossl_v3_crld, ossl_v3_freshest_crl;
extern const X509V3_EXT_METHOD ossl_v3_ocsp_nonce, ossl_v3_ocsp_accresp, ossl_v3_ocsp_acutoff;
extern const X509V3_EXT_METHOD ossl_v3_ocsp_crlid, ossl_v3_ocsp_nocheck, ossl_v3_ocsp_serviceloc;
extern const X509V3_EXT_METHOD ossl_v3_crl_hold, ossl_v3_pci;
extern const X509V3_EXT_METHOD ossl_v3_policy_mappings, ossl_v3_policy_constraints;
extern const X509V3_EXT_METHOD ossl_v3_name_constraints, ossl_v3_inhibit_anyp, ossl_v3_idp;
extern const X509V3_EXT_METHOD ossl_v3_addr, ossl_v3_asid;
extern const X509V3_EXT_METHOD ossl_v3_ct_scts[3];
extern const X509V3_EXT_METHOD ossl_v3_tls_feature;
extern const X509V3_EXT_METHOD ossl_v3_ext_admission;
extern const X509V3_EXT_METHOD ossl_v3_utf8_list[1];
extern const X509V3_EXT_METHOD ossl_v3_issuer_sign_tool;
| 1,646 | 57.821429 | 104 |
h
|
openssl
|
openssl-master/crypto/x509/pcy_cache.c
|
/*
* Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "crypto/x509.h"
#include "pcy_local.h"
static int policy_data_cmp(const X509_POLICY_DATA *const *a,
const X509_POLICY_DATA *const *b);
static int policy_cache_set_int(long *out, ASN1_INTEGER *value);
/*
* Set cache entry according to CertificatePolicies extension. Note: this
* destroys the passed CERTIFICATEPOLICIES structure.
*/
static int policy_cache_create(X509 *x,
CERTIFICATEPOLICIES *policies, int crit)
{
int i, num, ret = 0;
X509_POLICY_CACHE *cache = x->policy_cache;
X509_POLICY_DATA *data = NULL;
POLICYINFO *policy;
if ((num = sk_POLICYINFO_num(policies)) <= 0)
goto bad_policy;
cache->data = sk_X509_POLICY_DATA_new(policy_data_cmp);
if (cache->data == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto just_cleanup;
}
for (i = 0; i < num; i++) {
policy = sk_POLICYINFO_value(policies, i);
data = ossl_policy_data_new(policy, NULL, crit);
if (data == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_X509_LIB);
goto just_cleanup;
}
/*
* Duplicate policy OIDs are illegal: reject if matches found.
*/
if (OBJ_obj2nid(data->valid_policy) == NID_any_policy) {
if (cache->anyPolicy) {
ret = -1;
goto bad_policy;
}
cache->anyPolicy = data;
} else if (sk_X509_POLICY_DATA_find(cache->data, data) >=0) {
ret = -1;
goto bad_policy;
} else if (!sk_X509_POLICY_DATA_push(cache->data, data)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto bad_policy;
}
data = NULL;
}
/* Sort so we can find more quickly */
sk_X509_POLICY_DATA_sort(cache->data);
ret = 1;
bad_policy:
if (ret == -1)
x->ex_flags |= EXFLAG_INVALID_POLICY;
ossl_policy_data_free(data);
just_cleanup:
sk_POLICYINFO_pop_free(policies, POLICYINFO_free);
if (ret <= 0) {
sk_X509_POLICY_DATA_pop_free(cache->data, ossl_policy_data_free);
cache->data = NULL;
}
return ret;
}
static int policy_cache_new(X509 *x)
{
X509_POLICY_CACHE *cache;
ASN1_INTEGER *ext_any = NULL;
POLICY_CONSTRAINTS *ext_pcons = NULL;
CERTIFICATEPOLICIES *ext_cpols = NULL;
POLICY_MAPPINGS *ext_pmaps = NULL;
int i;
if (x->policy_cache != NULL)
return 1;
cache = OPENSSL_malloc(sizeof(*cache));
if (cache == NULL)
return 0;
cache->anyPolicy = NULL;
cache->data = NULL;
cache->any_skip = -1;
cache->explicit_skip = -1;
cache->map_skip = -1;
x->policy_cache = cache;
/*
* Handle requireExplicitPolicy *first*. Need to process this even if we
* don't have any policies.
*/
ext_pcons = X509_get_ext_d2i(x, NID_policy_constraints, &i, NULL);
if (!ext_pcons) {
if (i != -1)
goto bad_cache;
} else {
if (!ext_pcons->requireExplicitPolicy
&& !ext_pcons->inhibitPolicyMapping)
goto bad_cache;
if (!policy_cache_set_int(&cache->explicit_skip,
ext_pcons->requireExplicitPolicy))
goto bad_cache;
if (!policy_cache_set_int(&cache->map_skip,
ext_pcons->inhibitPolicyMapping))
goto bad_cache;
}
/* Process CertificatePolicies */
ext_cpols = X509_get_ext_d2i(x, NID_certificate_policies, &i, NULL);
/*
* If no CertificatePolicies extension or problem decoding then there is
* no point continuing because the valid policies will be NULL.
*/
if (!ext_cpols) {
/* If not absent some problem with extension */
if (i != -1)
goto bad_cache;
return 1;
}
i = policy_cache_create(x, ext_cpols, i);
/* NB: ext_cpols freed by policy_cache_set_policies */
if (i <= 0)
return i;
ext_pmaps = X509_get_ext_d2i(x, NID_policy_mappings, &i, NULL);
if (!ext_pmaps) {
/* If not absent some problem with extension */
if (i != -1)
goto bad_cache;
} else {
i = ossl_policy_cache_set_mapping(x, ext_pmaps);
if (i <= 0)
goto bad_cache;
}
ext_any = X509_get_ext_d2i(x, NID_inhibit_any_policy, &i, NULL);
if (!ext_any) {
if (i != -1)
goto bad_cache;
} else if (!policy_cache_set_int(&cache->any_skip, ext_any))
goto bad_cache;
goto just_cleanup;
bad_cache:
x->ex_flags |= EXFLAG_INVALID_POLICY;
just_cleanup:
POLICY_CONSTRAINTS_free(ext_pcons);
ASN1_INTEGER_free(ext_any);
return 1;
}
void ossl_policy_cache_free(X509_POLICY_CACHE *cache)
{
if (!cache)
return;
ossl_policy_data_free(cache->anyPolicy);
sk_X509_POLICY_DATA_pop_free(cache->data, ossl_policy_data_free);
OPENSSL_free(cache);
}
const X509_POLICY_CACHE *ossl_policy_cache_set(X509 *x)
{
if (x->policy_cache == NULL) {
if (!CRYPTO_THREAD_write_lock(x->lock))
return NULL;
policy_cache_new(x);
CRYPTO_THREAD_unlock(x->lock);
}
return x->policy_cache;
}
X509_POLICY_DATA *ossl_policy_cache_find_data(const X509_POLICY_CACHE *cache,
const ASN1_OBJECT *id)
{
int idx;
X509_POLICY_DATA tmp;
tmp.valid_policy = (ASN1_OBJECT *)id;
idx = sk_X509_POLICY_DATA_find(cache->data, &tmp);
return sk_X509_POLICY_DATA_value(cache->data, idx);
}
static int policy_data_cmp(const X509_POLICY_DATA *const *a,
const X509_POLICY_DATA *const *b)
{
return OBJ_cmp((*a)->valid_policy, (*b)->valid_policy);
}
static int policy_cache_set_int(long *out, ASN1_INTEGER *value)
{
if (value == NULL)
return 1;
if (value->type == V_ASN1_NEG_INTEGER)
return 0;
*out = ASN1_INTEGER_get(value);
return 1;
}
| 6,413 | 27.380531 | 77 |
c
|
openssl
|
openssl-master/crypto/x509/pcy_data.c
|
/*
* Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "pcy_local.h"
/* Policy Node routines */
void ossl_policy_data_free(X509_POLICY_DATA *data)
{
if (data == NULL)
return;
ASN1_OBJECT_free(data->valid_policy);
/* Don't free qualifiers if shared */
if (!(data->flags & POLICY_DATA_FLAG_SHARED_QUALIFIERS))
sk_POLICYQUALINFO_pop_free(data->qualifier_set, POLICYQUALINFO_free);
sk_ASN1_OBJECT_pop_free(data->expected_policy_set, ASN1_OBJECT_free);
OPENSSL_free(data);
}
/*
* Create a data based on an existing policy. If 'id' is NULL use the OID in
* the policy, otherwise use 'id'. This behaviour covers the two types of
* data in RFC3280: data with from a CertificatePolicies extension and
* additional data with just the qualifiers of anyPolicy and ID from another
* source.
*/
X509_POLICY_DATA *ossl_policy_data_new(POLICYINFO *policy,
const ASN1_OBJECT *cid, int crit)
{
X509_POLICY_DATA *ret;
ASN1_OBJECT *id;
if (policy == NULL && cid == NULL)
return NULL;
if (cid) {
id = OBJ_dup(cid);
if (id == NULL)
return NULL;
} else
id = NULL;
ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL) {
ASN1_OBJECT_free(id);
return NULL;
}
ret->expected_policy_set = sk_ASN1_OBJECT_new_null();
if (ret->expected_policy_set == NULL) {
OPENSSL_free(ret);
ASN1_OBJECT_free(id);
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
return NULL;
}
if (crit)
ret->flags = POLICY_DATA_FLAG_CRITICAL;
if (id)
ret->valid_policy = id;
else {
ret->valid_policy = policy->policyid;
policy->policyid = NULL;
}
if (policy) {
ret->qualifier_set = policy->qualifiers;
policy->qualifiers = NULL;
}
return ret;
}
| 2,263 | 26.609756 | 77 |
c
|
openssl
|
openssl-master/crypto/x509/pcy_lib.c
|
/*
* Copyright 2004-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "pcy_local.h"
/* accessor functions */
/* X509_POLICY_TREE stuff */
int X509_policy_tree_level_count(const X509_POLICY_TREE *tree)
{
if (!tree)
return 0;
return tree->nlevel;
}
X509_POLICY_LEVEL *X509_policy_tree_get0_level(const X509_POLICY_TREE *tree,
int i)
{
if (!tree || (i < 0) || (i >= tree->nlevel))
return NULL;
return tree->levels + i;
}
STACK_OF(X509_POLICY_NODE) *X509_policy_tree_get0_policies(const
X509_POLICY_TREE
*tree)
{
if (!tree)
return NULL;
return tree->auth_policies;
}
STACK_OF(X509_POLICY_NODE) *X509_policy_tree_get0_user_policies(const
X509_POLICY_TREE
*tree)
{
if (!tree)
return NULL;
if (tree->flags & POLICY_FLAG_ANY_POLICY)
return tree->auth_policies;
else
return tree->user_policies;
}
/* X509_POLICY_LEVEL stuff */
int X509_policy_level_node_count(X509_POLICY_LEVEL *level)
{
int n;
if (!level)
return 0;
if (level->anyPolicy)
n = 1;
else
n = 0;
if (level->nodes)
n += sk_X509_POLICY_NODE_num(level->nodes);
return n;
}
X509_POLICY_NODE *X509_policy_level_get0_node(const X509_POLICY_LEVEL *level, int i)
{
if (!level)
return NULL;
if (level->anyPolicy) {
if (i == 0)
return level->anyPolicy;
i--;
}
return sk_X509_POLICY_NODE_value(level->nodes, i);
}
/* X509_POLICY_NODE stuff */
const ASN1_OBJECT *X509_policy_node_get0_policy(const X509_POLICY_NODE *node)
{
if (!node)
return NULL;
return node->data->valid_policy;
}
STACK_OF(POLICYQUALINFO) *X509_policy_node_get0_qualifiers(const
X509_POLICY_NODE
*node)
{
if (!node)
return NULL;
return node->data->qualifier_set;
}
const X509_POLICY_NODE *X509_policy_node_get0_parent(const X509_POLICY_NODE
*node)
{
if (!node)
return NULL;
return node->parent;
}
| 2,786 | 24.568807 | 84 |
c
|
openssl
|
openssl-master/crypto/x509/pcy_local.h
|
/*
* Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
typedef struct X509_POLICY_DATA_st X509_POLICY_DATA;
DEFINE_STACK_OF(X509_POLICY_DATA)
/* Internal structures */
/*
* This structure and the field names correspond to the Policy 'node' of
* RFC3280. NB this structure contains no pointers to parent or child data:
* X509_POLICY_NODE contains that. This means that the main policy data can
* be kept static and cached with the certificate.
*/
struct X509_POLICY_DATA_st {
unsigned int flags;
/* Policy OID and qualifiers for this data */
ASN1_OBJECT *valid_policy;
STACK_OF(POLICYQUALINFO) *qualifier_set;
STACK_OF(ASN1_OBJECT) *expected_policy_set;
};
/* X509_POLICY_DATA flags values */
/*
* This flag indicates the structure has been mapped using a policy mapping
* extension. If policy mapping is not active its references get deleted.
*/
#define POLICY_DATA_FLAG_MAPPED 0x1
/*
* This flag indicates the data doesn't correspond to a policy in Certificate
* Policies: it has been mapped to any policy.
*/
#define POLICY_DATA_FLAG_MAPPED_ANY 0x2
/* AND with flags to see if any mapping has occurred */
#define POLICY_DATA_FLAG_MAP_MASK 0x3
/* qualifiers are shared and shouldn't be freed */
#define POLICY_DATA_FLAG_SHARED_QUALIFIERS 0x4
/* Parent node is an extra node and should be freed */
#define POLICY_DATA_FLAG_EXTRA_NODE 0x8
/* Corresponding CertificatePolicies is critical */
#define POLICY_DATA_FLAG_CRITICAL 0x10
/* This structure is cached with a certificate */
struct X509_POLICY_CACHE_st {
/* anyPolicy data or NULL if no anyPolicy */
X509_POLICY_DATA *anyPolicy;
/* other policy data */
STACK_OF(X509_POLICY_DATA) *data;
/* If InhibitAnyPolicy present this is its value or -1 if absent. */
long any_skip;
/*
* If policyConstraints and requireExplicitPolicy present this is its
* value or -1 if absent.
*/
long explicit_skip;
/*
* If policyConstraints and policyMapping present this is its value or -1
* if absent.
*/
long map_skip;
};
/*
* #define POLICY_CACHE_FLAG_CRITICAL POLICY_DATA_FLAG_CRITICAL
*/
/* This structure represents the relationship between nodes */
struct X509_POLICY_NODE_st {
/* node data this refers to */
const X509_POLICY_DATA *data;
/* Parent node */
X509_POLICY_NODE *parent;
/* Number of child nodes */
int nchild;
};
struct X509_POLICY_LEVEL_st {
/* Cert for this level */
X509 *cert;
/* nodes at this level */
STACK_OF(X509_POLICY_NODE) *nodes;
/* anyPolicy node */
X509_POLICY_NODE *anyPolicy;
/* Extra data */
/*
* STACK_OF(X509_POLICY_DATA) *extra_data;
*/
unsigned int flags;
};
struct X509_POLICY_TREE_st {
/* The number of nodes in the tree */
size_t node_count;
/* The maximum number of nodes in the tree */
size_t node_maximum;
/* This is the tree 'level' data */
X509_POLICY_LEVEL *levels;
int nlevel;
/*
* Extra policy data when additional nodes (not from the certificate) are
* required.
*/
STACK_OF(X509_POLICY_DATA) *extra_data;
/* This is the authority constrained policy set */
STACK_OF(X509_POLICY_NODE) *auth_policies;
STACK_OF(X509_POLICY_NODE) *user_policies;
unsigned int flags;
};
/* Set if anyPolicy present in user policies */
#define POLICY_FLAG_ANY_POLICY 0x2
/* Useful macros */
#define node_data_critical(data) (data->flags & POLICY_DATA_FLAG_CRITICAL)
#define node_critical(node) node_data_critical(node->data)
/* Internal functions */
X509_POLICY_DATA *ossl_policy_data_new(POLICYINFO *policy, const ASN1_OBJECT *id,
int crit);
void ossl_policy_data_free(X509_POLICY_DATA *data);
X509_POLICY_DATA *ossl_policy_cache_find_data(const X509_POLICY_CACHE *cache,
const ASN1_OBJECT *id);
int ossl_policy_cache_set_mapping(X509 *x, POLICY_MAPPINGS *maps);
STACK_OF(X509_POLICY_NODE) *ossl_policy_node_cmp_new(void);
void ossl_policy_cache_free(X509_POLICY_CACHE *cache);
X509_POLICY_NODE *ossl_policy_level_find_node(const X509_POLICY_LEVEL *level,
const X509_POLICY_NODE *parent,
const ASN1_OBJECT *id);
X509_POLICY_NODE *ossl_policy_tree_find_sk(STACK_OF(X509_POLICY_NODE) *sk,
const ASN1_OBJECT *id);
X509_POLICY_NODE *ossl_policy_level_add_node(X509_POLICY_LEVEL *level,
X509_POLICY_DATA *data,
X509_POLICY_NODE *parent,
X509_POLICY_TREE *tree,
int extra_data);
void ossl_policy_node_free(X509_POLICY_NODE *node);
int ossl_policy_node_match(const X509_POLICY_LEVEL *lvl,
const X509_POLICY_NODE *node, const ASN1_OBJECT *oid);
const X509_POLICY_CACHE *ossl_policy_cache_set(X509 *x);
| 5,425 | 30.546512 | 81 |
h
|
openssl
|
openssl-master/crypto/x509/pcy_map.c
|
/*
* Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "crypto/x509.h"
#include "pcy_local.h"
/*
* Set policy mapping entries in cache. Note: this modifies the passed
* POLICY_MAPPINGS structure
*/
int ossl_policy_cache_set_mapping(X509 *x, POLICY_MAPPINGS *maps)
{
POLICY_MAPPING *map;
X509_POLICY_DATA *data;
X509_POLICY_CACHE *cache = x->policy_cache;
int i;
int ret = 0;
if (sk_POLICY_MAPPING_num(maps) == 0) {
ret = -1;
goto bad_mapping;
}
for (i = 0; i < sk_POLICY_MAPPING_num(maps); i++) {
map = sk_POLICY_MAPPING_value(maps, i);
/* Reject if map to or from anyPolicy */
if ((OBJ_obj2nid(map->subjectDomainPolicy) == NID_any_policy)
|| (OBJ_obj2nid(map->issuerDomainPolicy) == NID_any_policy)) {
ret = -1;
goto bad_mapping;
}
/* Attempt to find matching policy data */
data = ossl_policy_cache_find_data(cache, map->issuerDomainPolicy);
/* If we don't have anyPolicy can't map */
if (data == NULL && !cache->anyPolicy)
continue;
/* Create a NODE from anyPolicy */
if (data == NULL) {
data = ossl_policy_data_new(NULL, map->issuerDomainPolicy,
cache->anyPolicy->flags
& POLICY_DATA_FLAG_CRITICAL);
if (data == NULL)
goto bad_mapping;
data->qualifier_set = cache->anyPolicy->qualifier_set;
/*
* map->issuerDomainPolicy = NULL;
*/
data->flags |= POLICY_DATA_FLAG_MAPPED_ANY;
data->flags |= POLICY_DATA_FLAG_SHARED_QUALIFIERS;
if (!sk_X509_POLICY_DATA_push(cache->data, data)) {
ossl_policy_data_free(data);
goto bad_mapping;
}
} else
data->flags |= POLICY_DATA_FLAG_MAPPED;
if (!sk_ASN1_OBJECT_push(data->expected_policy_set,
map->subjectDomainPolicy))
goto bad_mapping;
map->subjectDomainPolicy = NULL;
}
ret = 1;
bad_mapping:
sk_POLICY_MAPPING_pop_free(maps, POLICY_MAPPING_free);
return ret;
}
| 2,612 | 31.6625 | 75 |
c
|
openssl
|
openssl-master/crypto/x509/pcy_node.c
|
/*
* Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/asn1.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/err.h>
#include "pcy_local.h"
static int node_cmp(const X509_POLICY_NODE *const *a,
const X509_POLICY_NODE *const *b)
{
return OBJ_cmp((*a)->data->valid_policy, (*b)->data->valid_policy);
}
STACK_OF(X509_POLICY_NODE) *ossl_policy_node_cmp_new(void)
{
return sk_X509_POLICY_NODE_new(node_cmp);
}
X509_POLICY_NODE *ossl_policy_tree_find_sk(STACK_OF(X509_POLICY_NODE) *nodes,
const ASN1_OBJECT *id)
{
X509_POLICY_DATA n;
X509_POLICY_NODE l;
int idx;
n.valid_policy = (ASN1_OBJECT *)id;
l.data = &n;
idx = sk_X509_POLICY_NODE_find(nodes, &l);
return sk_X509_POLICY_NODE_value(nodes, idx);
}
X509_POLICY_NODE *ossl_policy_level_find_node(const X509_POLICY_LEVEL *level,
const X509_POLICY_NODE *parent,
const ASN1_OBJECT *id)
{
X509_POLICY_NODE *node;
int i;
for (i = 0; i < sk_X509_POLICY_NODE_num(level->nodes); i++) {
node = sk_X509_POLICY_NODE_value(level->nodes, i);
if (node->parent == parent) {
if (!OBJ_cmp(node->data->valid_policy, id))
return node;
}
}
return NULL;
}
X509_POLICY_NODE *ossl_policy_level_add_node(X509_POLICY_LEVEL *level,
X509_POLICY_DATA *data,
X509_POLICY_NODE *parent,
X509_POLICY_TREE *tree,
int extra_data)
{
X509_POLICY_NODE *node;
/* Verify that the tree isn't too large. This mitigates CVE-2023-0464 */
if (tree->node_maximum > 0 && tree->node_count >= tree->node_maximum)
return NULL;
node = OPENSSL_zalloc(sizeof(*node));
if (node == NULL)
return NULL;
node->data = data;
node->parent = parent;
if (level != NULL) {
if (OBJ_obj2nid(data->valid_policy) == NID_any_policy) {
if (level->anyPolicy)
goto node_error;
level->anyPolicy = node;
} else {
if (level->nodes == NULL)
level->nodes = ossl_policy_node_cmp_new();
if (level->nodes == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_X509_LIB);
goto node_error;
}
if (!sk_X509_POLICY_NODE_push(level->nodes, node)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto node_error;
}
}
}
if (extra_data) {
if (tree->extra_data == NULL)
tree->extra_data = sk_X509_POLICY_DATA_new_null();
if (tree->extra_data == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto extra_data_error;
}
if (!sk_X509_POLICY_DATA_push(tree->extra_data, data)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto extra_data_error;
}
}
tree->node_count++;
if (parent)
parent->nchild++;
return node;
extra_data_error:
if (level != NULL) {
if (level->anyPolicy == node)
level->anyPolicy = NULL;
else
(void) sk_X509_POLICY_NODE_pop(level->nodes);
}
node_error:
ossl_policy_node_free(node);
return NULL;
}
void ossl_policy_node_free(X509_POLICY_NODE *node)
{
OPENSSL_free(node);
}
/*
* See if a policy node matches a policy OID. If mapping enabled look through
* expected policy set otherwise just valid policy.
*/
int ossl_policy_node_match(const X509_POLICY_LEVEL *lvl,
const X509_POLICY_NODE *node, const ASN1_OBJECT *oid)
{
int i;
ASN1_OBJECT *policy_oid;
const X509_POLICY_DATA *x = node->data;
if ((lvl->flags & X509_V_FLAG_INHIBIT_MAP)
|| !(x->flags & POLICY_DATA_FLAG_MAP_MASK)) {
if (!OBJ_cmp(x->valid_policy, oid))
return 1;
return 0;
}
for (i = 0; i < sk_ASN1_OBJECT_num(x->expected_policy_set); i++) {
policy_oid = sk_ASN1_OBJECT_value(x->expected_policy_set, i);
if (!OBJ_cmp(policy_oid, oid))
return 1;
}
return 0;
}
| 4,652 | 28.08125 | 80 |
c
|
openssl
|
openssl-master/crypto/x509/pcy_tree.c
|
/*
* Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/cryptlib.h"
#include <openssl/trace.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "pcy_local.h"
/*
* If the maximum number of nodes in the policy tree isn't defined, set it to
* a generous default of 1000 nodes.
*
* Defining this to be zero means unlimited policy tree growth which opens the
* door on CVE-2023-0464.
*/
#ifndef OPENSSL_POLICY_TREE_NODES_MAX
# define OPENSSL_POLICY_TREE_NODES_MAX 1000
#endif
static void exnode_free(X509_POLICY_NODE *node);
static void expected_print(BIO *channel,
X509_POLICY_LEVEL *lev, X509_POLICY_NODE *node,
int indent)
{
if ((lev->flags & X509_V_FLAG_INHIBIT_MAP)
|| !(node->data->flags & POLICY_DATA_FLAG_MAP_MASK))
BIO_puts(channel, " Not Mapped\n");
else {
int i;
STACK_OF(ASN1_OBJECT) *pset = node->data->expected_policy_set;
ASN1_OBJECT *oid;
BIO_puts(channel, " Expected: ");
for (i = 0; i < sk_ASN1_OBJECT_num(pset); i++) {
oid = sk_ASN1_OBJECT_value(pset, i);
if (i)
BIO_puts(channel, ", ");
i2a_ASN1_OBJECT(channel, oid);
}
BIO_puts(channel, "\n");
}
}
static void tree_print(BIO *channel,
char *str, X509_POLICY_TREE *tree,
X509_POLICY_LEVEL *curr)
{
X509_POLICY_LEVEL *plev;
if (!curr)
curr = tree->levels + tree->nlevel;
else
curr++;
BIO_printf(channel, "Level print after %s\n", str);
BIO_printf(channel, "Printing Up to Level %ld\n",
(long)(curr - tree->levels));
for (plev = tree->levels; plev != curr; plev++) {
int i;
BIO_printf(channel, "Level %ld, flags = %x\n",
(long)(plev - tree->levels), plev->flags);
for (i = 0; i < sk_X509_POLICY_NODE_num(plev->nodes); i++) {
X509_POLICY_NODE *node =
sk_X509_POLICY_NODE_value(plev->nodes, i);
X509_POLICY_NODE_print(channel, node, 2);
expected_print(channel, plev, node, 2);
BIO_printf(channel, " Flags: %x\n", node->data->flags);
}
if (plev->anyPolicy)
X509_POLICY_NODE_print(channel, plev->anyPolicy, 2);
}
}
#define TREE_PRINT(str, tree, curr) \
OSSL_TRACE_BEGIN(X509V3_POLICY) { \
tree_print(trc_out, "before tree_prune()", tree, curr); \
} OSSL_TRACE_END(X509V3_POLICY)
/*-
* Return value: <= 0 on error, or positive bit mask:
*
* X509_PCY_TREE_VALID: valid tree
* X509_PCY_TREE_EMPTY: empty tree (including bare TA case)
* X509_PCY_TREE_EXPLICIT: explicit policy required
*/
static int tree_init(X509_POLICY_TREE **ptree, STACK_OF(X509) *certs,
unsigned int flags)
{
X509_POLICY_TREE *tree;
X509_POLICY_LEVEL *level;
const X509_POLICY_CACHE *cache;
X509_POLICY_DATA *data = NULL;
int ret = X509_PCY_TREE_VALID;
int n = sk_X509_num(certs) - 1; /* RFC5280 paths omit the TA */
int explicit_policy = (flags & X509_V_FLAG_EXPLICIT_POLICY) ? 0 : n+1;
int any_skip = (flags & X509_V_FLAG_INHIBIT_ANY) ? 0 : n+1;
int map_skip = (flags & X509_V_FLAG_INHIBIT_MAP) ? 0 : n+1;
int i;
*ptree = NULL;
/* Can't do anything with just a trust anchor */
if (n == 0)
return X509_PCY_TREE_EMPTY;
/*
* First setup the policy cache in all n non-TA certificates, this will be
* used in X509_verify_cert() which will invoke the verify callback for all
* certificates with invalid policy extensions.
*/
for (i = n - 1; i >= 0; i--) {
X509 *x = sk_X509_value(certs, i);
/* Call for side-effect of computing hash and caching extensions */
X509_check_purpose(x, -1, 0);
/* If cache is NULL, likely ENOMEM: return immediately */
if (ossl_policy_cache_set(x) == NULL)
return X509_PCY_TREE_INTERNAL;
}
/*
* At this point check for invalid policies and required explicit policy.
* Note that the explicit_policy counter is a count-down to zero, with the
* requirement kicking in if and once it does that. The counter is
* decremented for every non-self-issued certificate in the path, but may
* be further reduced by policy constraints in a non-leaf certificate.
*
* The ultimate policy set is the intersection of all the policies along
* the path, if we hit a certificate with an empty policy set, and explicit
* policy is required we're done.
*/
for (i = n - 1;
i >= 0 && (explicit_policy > 0 || (ret & X509_PCY_TREE_EMPTY) == 0);
i--) {
X509 *x = sk_X509_value(certs, i);
uint32_t ex_flags = X509_get_extension_flags(x);
/* All the policies are already cached, we can return early */
if (ex_flags & EXFLAG_INVALID_POLICY)
return X509_PCY_TREE_INVALID;
/* Access the cache which we now know exists */
cache = ossl_policy_cache_set(x);
if ((ret & X509_PCY_TREE_VALID) && cache->data == NULL)
ret = X509_PCY_TREE_EMPTY;
if (explicit_policy > 0) {
if (!(ex_flags & EXFLAG_SI))
explicit_policy--;
if ((cache->explicit_skip >= 0)
&& (cache->explicit_skip < explicit_policy))
explicit_policy = cache->explicit_skip;
}
}
if (explicit_policy == 0)
ret |= X509_PCY_TREE_EXPLICIT;
if ((ret & X509_PCY_TREE_VALID) == 0)
return ret;
/* If we get this far initialize the tree */
if ((tree = OPENSSL_zalloc(sizeof(*tree))) == NULL)
return X509_PCY_TREE_INTERNAL;
/* Limit the growth of the tree to mitigate CVE-2023-0464 */
tree->node_maximum = OPENSSL_POLICY_TREE_NODES_MAX;
/*
* http://tools.ietf.org/html/rfc5280#section-6.1.2, figure 3.
*
* The top level is implicitly for the trust anchor with valid expected
* policies of anyPolicy. (RFC 5280 has the TA at depth 0 and the leaf at
* depth n, we have the leaf at depth 0 and the TA at depth n).
*/
if ((tree->levels = OPENSSL_zalloc(sizeof(*tree->levels)*(n+1))) == NULL) {
OPENSSL_free(tree);
return X509_PCY_TREE_INTERNAL;
}
tree->nlevel = n+1;
level = tree->levels;
if ((data = ossl_policy_data_new(NULL,
OBJ_nid2obj(NID_any_policy), 0)) == NULL)
goto bad_tree;
if (ossl_policy_level_add_node(level, data, NULL, tree, 1) == NULL) {
ossl_policy_data_free(data);
goto bad_tree;
}
/*
* In this pass initialize all the tree levels and whether anyPolicy and
* policy mapping are inhibited at each level.
*/
for (i = n - 1; i >= 0; i--) {
X509 *x = sk_X509_value(certs, i);
uint32_t ex_flags = X509_get_extension_flags(x);
/* Access the cache which we now know exists */
cache = ossl_policy_cache_set(x);
X509_up_ref(x);
(++level)->cert = x;
if (!cache->anyPolicy)
level->flags |= X509_V_FLAG_INHIBIT_ANY;
/* Determine inhibit any and inhibit map flags */
if (any_skip == 0) {
/*
* Any matching allowed only if certificate is self issued and not
* the last in the chain.
*/
if (!(ex_flags & EXFLAG_SI) || (i == 0))
level->flags |= X509_V_FLAG_INHIBIT_ANY;
} else {
if (!(ex_flags & EXFLAG_SI))
any_skip--;
if ((cache->any_skip >= 0) && (cache->any_skip < any_skip))
any_skip = cache->any_skip;
}
if (map_skip == 0)
level->flags |= X509_V_FLAG_INHIBIT_MAP;
else {
if (!(ex_flags & EXFLAG_SI))
map_skip--;
if ((cache->map_skip >= 0) && (cache->map_skip < map_skip))
map_skip = cache->map_skip;
}
}
*ptree = tree;
return ret;
bad_tree:
X509_policy_tree_free(tree);
return X509_PCY_TREE_INTERNAL;
}
/*
* Return value: 1 on success, 0 otherwise
*/
static int tree_link_matching_nodes(X509_POLICY_LEVEL *curr,
X509_POLICY_DATA *data,
X509_POLICY_TREE *tree)
{
X509_POLICY_LEVEL *last = curr - 1;
int i, matched = 0;
/* Iterate through all in nodes linking matches */
for (i = 0; i < sk_X509_POLICY_NODE_num(last->nodes); i++) {
X509_POLICY_NODE *node = sk_X509_POLICY_NODE_value(last->nodes, i);
if (ossl_policy_node_match(last, node, data->valid_policy)) {
if (ossl_policy_level_add_node(curr, data, node, tree, 0) == NULL)
return 0;
matched = 1;
}
}
if (!matched && last->anyPolicy) {
if (ossl_policy_level_add_node(curr, data, last->anyPolicy, tree, 0) == NULL)
return 0;
}
return 1;
}
/*
* This corresponds to RFC3280 6.1.3(d)(1): link any data from
* CertificatePolicies onto matching parent or anyPolicy if no match.
*
* Return value: 1 on success, 0 otherwise.
*/
static int tree_link_nodes(X509_POLICY_LEVEL *curr,
const X509_POLICY_CACHE *cache,
X509_POLICY_TREE *tree)
{
int i;
for (i = 0; i < sk_X509_POLICY_DATA_num(cache->data); i++) {
X509_POLICY_DATA *data = sk_X509_POLICY_DATA_value(cache->data, i);
/* Look for matching nodes in previous level */
if (!tree_link_matching_nodes(curr, data, tree))
return 0;
}
return 1;
}
/*
* This corresponds to RFC3280 6.1.3(d)(2): Create new data for any unmatched
* policies in the parent and link to anyPolicy.
*
* Return value: 1 on success, 0 otherwise.
*/
static int tree_add_unmatched(X509_POLICY_LEVEL *curr,
const X509_POLICY_CACHE *cache,
const ASN1_OBJECT *id,
X509_POLICY_NODE *node, X509_POLICY_TREE *tree)
{
X509_POLICY_DATA *data;
if (id == NULL)
id = node->data->valid_policy;
/*
* Create a new node with qualifiers from anyPolicy and id from unmatched
* node.
*/
if ((data = ossl_policy_data_new(NULL, id, node_critical(node))) == NULL)
return 0;
/* Curr may not have anyPolicy */
data->qualifier_set = cache->anyPolicy->qualifier_set;
data->flags |= POLICY_DATA_FLAG_SHARED_QUALIFIERS;
if (ossl_policy_level_add_node(curr, data, node, tree, 1) == NULL) {
ossl_policy_data_free(data);
return 0;
}
return 1;
}
/*
* Return value: 1 on success, 0 otherwise.
*/
static int tree_link_unmatched(X509_POLICY_LEVEL *curr,
const X509_POLICY_CACHE *cache,
X509_POLICY_NODE *node, X509_POLICY_TREE *tree)
{
const X509_POLICY_LEVEL *last = curr - 1;
int i;
if ((last->flags & X509_V_FLAG_INHIBIT_MAP)
|| !(node->data->flags & POLICY_DATA_FLAG_MAPPED)) {
/* If no policy mapping: matched if one child present */
if (node->nchild)
return 1;
if (!tree_add_unmatched(curr, cache, NULL, node, tree))
return 0;
/* Add it */
} else {
/* If mapping: matched if one child per expected policy set */
STACK_OF(ASN1_OBJECT) *expset = node->data->expected_policy_set;
if (node->nchild == sk_ASN1_OBJECT_num(expset))
return 1;
/* Locate unmatched nodes */
for (i = 0; i < sk_ASN1_OBJECT_num(expset); i++) {
ASN1_OBJECT *oid = sk_ASN1_OBJECT_value(expset, i);
if (ossl_policy_level_find_node(curr, node, oid))
continue;
if (!tree_add_unmatched(curr, cache, oid, node, tree))
return 0;
}
}
return 1;
}
/*
* Return value: 1 on success, 0 otherwise
*/
static int tree_link_any(X509_POLICY_LEVEL *curr,
const X509_POLICY_CACHE *cache,
X509_POLICY_TREE *tree)
{
int i;
X509_POLICY_NODE *node;
X509_POLICY_LEVEL *last = curr - 1;
for (i = 0; i < sk_X509_POLICY_NODE_num(last->nodes); i++) {
node = sk_X509_POLICY_NODE_value(last->nodes, i);
if (!tree_link_unmatched(curr, cache, node, tree))
return 0;
}
/* Finally add link to anyPolicy */
if (last->anyPolicy &&
ossl_policy_level_add_node(curr, cache->anyPolicy,
last->anyPolicy, tree, 0) == NULL)
return 0;
return 1;
}
/*-
* Prune the tree: delete any child mapped child data on the current level then
* proceed up the tree deleting any data with no children. If we ever have no
* data on a level we can halt because the tree will be empty.
*
* Return value: <= 0 error, otherwise one of:
*
* X509_PCY_TREE_VALID: valid tree
* X509_PCY_TREE_EMPTY: empty tree
*/
static int tree_prune(X509_POLICY_TREE *tree, X509_POLICY_LEVEL *curr)
{
STACK_OF(X509_POLICY_NODE) *nodes;
X509_POLICY_NODE *node;
int i;
nodes = curr->nodes;
if (curr->flags & X509_V_FLAG_INHIBIT_MAP) {
for (i = sk_X509_POLICY_NODE_num(nodes) - 1; i >= 0; i--) {
node = sk_X509_POLICY_NODE_value(nodes, i);
/* Delete any mapped data: see RFC3280 XXXX */
if (node->data->flags & POLICY_DATA_FLAG_MAP_MASK) {
node->parent->nchild--;
OPENSSL_free(node);
(void)sk_X509_POLICY_NODE_delete(nodes, i);
}
}
}
for (;;) {
--curr;
nodes = curr->nodes;
for (i = sk_X509_POLICY_NODE_num(nodes) - 1; i >= 0; i--) {
node = sk_X509_POLICY_NODE_value(nodes, i);
if (node->nchild == 0) {
node->parent->nchild--;
OPENSSL_free(node);
(void)sk_X509_POLICY_NODE_delete(nodes, i);
}
}
if (curr->anyPolicy && !curr->anyPolicy->nchild) {
if (curr->anyPolicy->parent)
curr->anyPolicy->parent->nchild--;
OPENSSL_free(curr->anyPolicy);
curr->anyPolicy = NULL;
}
if (curr == tree->levels) {
/* If we zapped anyPolicy at top then tree is empty */
if (!curr->anyPolicy)
return X509_PCY_TREE_EMPTY;
break;
}
}
return X509_PCY_TREE_VALID;
}
/*
* Return value: 1 on success, 0 otherwise.
*/
static int tree_add_auth_node(STACK_OF(X509_POLICY_NODE) **pnodes,
X509_POLICY_NODE *pcy)
{
if (*pnodes == NULL &&
(*pnodes = ossl_policy_node_cmp_new()) == NULL)
return 0;
if (sk_X509_POLICY_NODE_find(*pnodes, pcy) >= 0)
return 1;
return sk_X509_POLICY_NODE_push(*pnodes, pcy) != 0;
}
#define TREE_CALC_FAILURE 0
#define TREE_CALC_OK_NOFREE 1
#define TREE_CALC_OK_DOFREE 2
/*-
* Calculate the authority set based on policy tree. The 'pnodes' parameter is
* used as a store for the set of policy nodes used to calculate the user set.
* If the authority set is not anyPolicy then pnodes will just point to the
* authority set. If however the authority set is anyPolicy then the set of
* valid policies (other than anyPolicy) is store in pnodes.
*
* Return value:
* TREE_CALC_FAILURE on failure,
* TREE_CALC_OK_NOFREE on success and pnodes need not be freed,
* TREE_CALC_OK_DOFREE on success and pnodes needs to be freed
*/
static int tree_calculate_authority_set(X509_POLICY_TREE *tree,
STACK_OF(X509_POLICY_NODE) **pnodes)
{
X509_POLICY_LEVEL *curr;
X509_POLICY_NODE *node, *anyptr;
STACK_OF(X509_POLICY_NODE) **addnodes;
int i, j;
curr = tree->levels + tree->nlevel - 1;
/* If last level contains anyPolicy set is anyPolicy */
if (curr->anyPolicy) {
if (!tree_add_auth_node(&tree->auth_policies, curr->anyPolicy))
return TREE_CALC_FAILURE;
addnodes = pnodes;
} else
/* Add policies to authority set */
addnodes = &tree->auth_policies;
curr = tree->levels;
for (i = 1; i < tree->nlevel; i++) {
/*
* If no anyPolicy node on this level it can't appear on lower
* levels so end search.
*/
if ((anyptr = curr->anyPolicy) == NULL)
break;
curr++;
for (j = 0; j < sk_X509_POLICY_NODE_num(curr->nodes); j++) {
node = sk_X509_POLICY_NODE_value(curr->nodes, j);
if ((node->parent == anyptr)
&& !tree_add_auth_node(addnodes, node)) {
if (addnodes == pnodes) {
sk_X509_POLICY_NODE_free(*pnodes);
*pnodes = NULL;
}
return TREE_CALC_FAILURE;
}
}
}
if (addnodes == pnodes)
return TREE_CALC_OK_DOFREE;
*pnodes = tree->auth_policies;
return TREE_CALC_OK_NOFREE;
}
/*
* Return value: 1 on success, 0 otherwise.
*/
static int tree_calculate_user_set(X509_POLICY_TREE *tree,
STACK_OF(ASN1_OBJECT) *policy_oids,
STACK_OF(X509_POLICY_NODE) *auth_nodes)
{
int i;
X509_POLICY_NODE *node;
ASN1_OBJECT *oid;
X509_POLICY_NODE *anyPolicy;
X509_POLICY_DATA *extra;
/*
* Check if anyPolicy present in authority constrained policy set: this
* will happen if it is a leaf node.
*/
if (sk_ASN1_OBJECT_num(policy_oids) <= 0)
return 1;
anyPolicy = tree->levels[tree->nlevel - 1].anyPolicy;
for (i = 0; i < sk_ASN1_OBJECT_num(policy_oids); i++) {
oid = sk_ASN1_OBJECT_value(policy_oids, i);
if (OBJ_obj2nid(oid) == NID_any_policy) {
tree->flags |= POLICY_FLAG_ANY_POLICY;
return 1;
}
}
for (i = 0; i < sk_ASN1_OBJECT_num(policy_oids); i++) {
oid = sk_ASN1_OBJECT_value(policy_oids, i);
node = ossl_policy_tree_find_sk(auth_nodes, oid);
if (!node) {
if (!anyPolicy)
continue;
/*
* Create a new node with policy ID from user set and qualifiers
* from anyPolicy.
*/
extra = ossl_policy_data_new(NULL, oid, node_critical(anyPolicy));
if (extra == NULL)
return 0;
extra->qualifier_set = anyPolicy->data->qualifier_set;
extra->flags = POLICY_DATA_FLAG_SHARED_QUALIFIERS
| POLICY_DATA_FLAG_EXTRA_NODE;
node = ossl_policy_level_add_node(NULL, extra, anyPolicy->parent,
tree, 1);
if (node == NULL) {
ossl_policy_data_free(extra);
return 0;
}
}
if (!tree->user_policies) {
tree->user_policies = sk_X509_POLICY_NODE_new_null();
if (!tree->user_policies) {
exnode_free(node);
return 0;
}
}
if (!sk_X509_POLICY_NODE_push(tree->user_policies, node)) {
exnode_free(node);
return 0;
}
}
return 1;
}
/*-
* Return value: <= 0 error, otherwise one of:
* X509_PCY_TREE_VALID: valid tree
* X509_PCY_TREE_EMPTY: empty tree
* (see tree_prune()).
*/
static int tree_evaluate(X509_POLICY_TREE *tree)
{
int ret, i;
X509_POLICY_LEVEL *curr = tree->levels + 1;
const X509_POLICY_CACHE *cache;
for (i = 1; i < tree->nlevel; i++, curr++) {
cache = ossl_policy_cache_set(curr->cert);
if (!tree_link_nodes(curr, cache, tree))
return X509_PCY_TREE_INTERNAL;
if (!(curr->flags & X509_V_FLAG_INHIBIT_ANY)
&& !tree_link_any(curr, cache, tree))
return X509_PCY_TREE_INTERNAL;
TREE_PRINT("before tree_prune()", tree, curr);
ret = tree_prune(tree, curr);
if (ret != X509_PCY_TREE_VALID)
return ret;
}
return X509_PCY_TREE_VALID;
}
static void exnode_free(X509_POLICY_NODE *node)
{
if (node->data && (node->data->flags & POLICY_DATA_FLAG_EXTRA_NODE))
OPENSSL_free(node);
}
void X509_policy_tree_free(X509_POLICY_TREE *tree)
{
X509_POLICY_LEVEL *curr;
int i;
if (!tree)
return;
sk_X509_POLICY_NODE_free(tree->auth_policies);
sk_X509_POLICY_NODE_pop_free(tree->user_policies, exnode_free);
for (i = 0, curr = tree->levels; i < tree->nlevel; i++, curr++) {
X509_free(curr->cert);
sk_X509_POLICY_NODE_pop_free(curr->nodes, ossl_policy_node_free);
ossl_policy_node_free(curr->anyPolicy);
}
sk_X509_POLICY_DATA_pop_free(tree->extra_data, ossl_policy_data_free);
OPENSSL_free(tree->levels);
OPENSSL_free(tree);
}
/*-
* Application policy checking function.
* Return codes:
* X509_PCY_TREE_FAILURE: Failure to satisfy explicit policy
* X509_PCY_TREE_INVALID: Inconsistent or invalid extensions
* X509_PCY_TREE_INTERNAL: Internal error, most likely malloc
* X509_PCY_TREE_VALID: Success (null tree if empty or bare TA)
*/
int X509_policy_check(X509_POLICY_TREE **ptree, int *pexplicit_policy,
STACK_OF(X509) *certs,
STACK_OF(ASN1_OBJECT) *policy_oids, unsigned int flags)
{
int init_ret;
int ret;
int calc_ret;
X509_POLICY_TREE *tree = NULL;
STACK_OF(X509_POLICY_NODE) *nodes, *auth_nodes = NULL;
*ptree = NULL;
*pexplicit_policy = 0;
init_ret = tree_init(&tree, certs, flags);
if (init_ret <= 0)
return init_ret;
if ((init_ret & X509_PCY_TREE_EXPLICIT) == 0) {
if (init_ret & X509_PCY_TREE_EMPTY) {
X509_policy_tree_free(tree);
return X509_PCY_TREE_VALID;
}
} else {
*pexplicit_policy = 1;
/* Tree empty and requireExplicit True: Error */
if (init_ret & X509_PCY_TREE_EMPTY)
return X509_PCY_TREE_FAILURE;
}
ret = tree_evaluate(tree);
TREE_PRINT("tree_evaluate()", tree, NULL);
if (ret <= 0)
goto error;
if (ret == X509_PCY_TREE_EMPTY) {
X509_policy_tree_free(tree);
if (init_ret & X509_PCY_TREE_EXPLICIT)
return X509_PCY_TREE_FAILURE;
return X509_PCY_TREE_VALID;
}
/* Tree is not empty: continue */
if ((calc_ret = tree_calculate_authority_set(tree, &auth_nodes)) == 0)
goto error;
sk_X509_POLICY_NODE_sort(auth_nodes);
ret = tree_calculate_user_set(tree, policy_oids, auth_nodes);
if (calc_ret == TREE_CALC_OK_DOFREE)
sk_X509_POLICY_NODE_free(auth_nodes);
if (!ret)
goto error;
*ptree = tree;
if (init_ret & X509_PCY_TREE_EXPLICIT) {
nodes = X509_policy_tree_get0_user_policies(tree);
if (sk_X509_POLICY_NODE_num(nodes) <= 0)
return X509_PCY_TREE_FAILURE;
}
return X509_PCY_TREE_VALID;
error:
X509_policy_tree_free(tree);
return X509_PCY_TREE_INTERNAL;
}
| 23,466 | 31.50277 | 85 |
c
|
openssl
|
openssl-master/crypto/x509/standard_exts.h
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This table will be searched using OBJ_bsearch so it *must* kept in order
* of the ext_nid values.
*/
static const X509V3_EXT_METHOD *standard_exts[] = {
&ossl_v3_nscert,
&ossl_v3_ns_ia5_list[0],
&ossl_v3_ns_ia5_list[1],
&ossl_v3_ns_ia5_list[2],
&ossl_v3_ns_ia5_list[3],
&ossl_v3_ns_ia5_list[4],
&ossl_v3_ns_ia5_list[5],
&ossl_v3_ns_ia5_list[6],
&ossl_v3_skey_id,
&ossl_v3_key_usage,
&ossl_v3_pkey_usage_period,
&ossl_v3_alt[0],
&ossl_v3_alt[1],
&ossl_v3_bcons,
&ossl_v3_crl_num,
&ossl_v3_cpols,
&ossl_v3_akey_id,
&ossl_v3_crld,
&ossl_v3_ext_ku,
&ossl_v3_delta_crl,
&ossl_v3_crl_reason,
#ifndef OPENSSL_NO_OCSP
&ossl_v3_crl_invdate,
#endif
&ossl_v3_sxnet,
&ossl_v3_info,
#ifndef OPENSSL_NO_RFC3779
&ossl_v3_addr,
&ossl_v3_asid,
#endif
#ifndef OPENSSL_NO_OCSP
&ossl_v3_ocsp_nonce,
&ossl_v3_ocsp_crlid,
&ossl_v3_ocsp_accresp,
&ossl_v3_ocsp_nocheck,
&ossl_v3_ocsp_acutoff,
&ossl_v3_ocsp_serviceloc,
#endif
&ossl_v3_sinfo,
&ossl_v3_policy_constraints,
#ifndef OPENSSL_NO_OCSP
&ossl_v3_crl_hold,
#endif
&ossl_v3_pci,
&ossl_v3_name_constraints,
&ossl_v3_policy_mappings,
&ossl_v3_inhibit_anyp,
&ossl_v3_idp,
&ossl_v3_alt[2],
&ossl_v3_freshest_crl,
#ifndef OPENSSL_NO_CT
&ossl_v3_ct_scts[0],
&ossl_v3_ct_scts[1],
&ossl_v3_ct_scts[2],
#endif
&ossl_v3_utf8_list[0],
&ossl_v3_issuer_sign_tool,
&ossl_v3_tls_feature,
&ossl_v3_ext_admission
};
/* Number of standard extensions */
#define STANDARD_EXTENSION_COUNT OSSL_NELEM(standard_exts)
| 1,971 | 23.345679 | 75 |
h
|
openssl
|
openssl-master/crypto/x509/t_crl.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/bn.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#ifndef OPENSSL_NO_STDIO
int X509_CRL_print_fp(FILE *fp, X509_CRL *x)
{
BIO *b;
int ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
return 0;
}
BIO_set_fp(b, fp, BIO_NOCLOSE);
ret = X509_CRL_print(b, x);
BIO_free(b);
return ret;
}
#endif
int X509_CRL_print(BIO *out, X509_CRL *x)
{
return X509_CRL_print_ex(out, x, XN_FLAG_COMPAT);
}
int X509_CRL_print_ex(BIO *out, X509_CRL *x, unsigned long nmflag)
{
STACK_OF(X509_REVOKED) *rev;
X509_REVOKED *r;
const X509_ALGOR *sig_alg;
const ASN1_BIT_STRING *sig;
long l;
int i;
BIO_printf(out, "Certificate Revocation List (CRL):\n");
l = X509_CRL_get_version(x);
if (l >= X509_CRL_VERSION_1 && l <= X509_CRL_VERSION_2)
BIO_printf(out, "%8sVersion %ld (0x%lx)\n", "", l + 1, (unsigned long)l);
else
BIO_printf(out, "%8sVersion unknown (%ld)\n", "", l);
X509_CRL_get0_signature(x, &sig, &sig_alg);
BIO_puts(out, " ");
X509_signature_print(out, sig_alg, NULL);
BIO_printf(out, "%8sIssuer: ", "");
X509_NAME_print_ex(out, X509_CRL_get_issuer(x), 0, nmflag);
BIO_puts(out, "\n");
BIO_printf(out, "%8sLast Update: ", "");
ASN1_TIME_print(out, X509_CRL_get0_lastUpdate(x));
BIO_printf(out, "\n%8sNext Update: ", "");
if (X509_CRL_get0_nextUpdate(x))
ASN1_TIME_print(out, X509_CRL_get0_nextUpdate(x));
else
BIO_printf(out, "NONE");
BIO_printf(out, "\n");
X509V3_extensions_print(out, "CRL extensions",
X509_CRL_get0_extensions(x), 0, 8);
rev = X509_CRL_get_REVOKED(x);
if (sk_X509_REVOKED_num(rev) > 0)
BIO_printf(out, "Revoked Certificates:\n");
else
BIO_printf(out, "No Revoked Certificates.\n");
for (i = 0; i < sk_X509_REVOKED_num(rev); i++) {
r = sk_X509_REVOKED_value(rev, i);
BIO_printf(out, " Serial Number: ");
i2a_ASN1_INTEGER(out, X509_REVOKED_get0_serialNumber(r));
BIO_printf(out, "\n Revocation Date: ");
ASN1_TIME_print(out, X509_REVOKED_get0_revocationDate(r));
BIO_printf(out, "\n");
X509V3_extensions_print(out, "CRL entry extensions",
X509_REVOKED_get0_extensions(r), 0, 8);
}
X509_signature_print(out, sig_alg, sig);
return 1;
}
| 2,903 | 29.568421 | 81 |
c
|
openssl
|
openssl-master/crypto/x509/t_req.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/bn.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/rsa.h>
#include <openssl/dsa.h>
#ifndef OPENSSL_NO_STDIO
int X509_REQ_print_fp(FILE *fp, X509_REQ *x)
{
BIO *b;
int ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
return 0;
}
BIO_set_fp(b, fp, BIO_NOCLOSE);
ret = X509_REQ_print(b, x);
BIO_free(b);
return ret;
}
#endif
int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflags,
unsigned long cflag)
{
long l;
int i;
EVP_PKEY *pkey;
STACK_OF(X509_EXTENSION) *exts;
char mlch = ' ';
int nmindent = 0;
if ((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
mlch = '\n';
nmindent = 12;
}
if (nmflags == X509_FLAG_COMPAT)
nmindent = 16;
if (!(cflag & X509_FLAG_NO_HEADER)) {
if (BIO_write(bp, "Certificate Request:\n", 21) <= 0)
goto err;
if (BIO_write(bp, " Data:\n", 10) <= 0)
goto err;
}
if (!(cflag & X509_FLAG_NO_VERSION)) {
l = X509_REQ_get_version(x);
if (l == X509_REQ_VERSION_1) {
if (BIO_printf(bp, "%8sVersion: %ld (0x%lx)\n", "", l + 1, (unsigned long)l) <= 0)
goto err;
} else {
if (BIO_printf(bp, "%8sVersion: Unknown (%ld)\n", "", l) <= 0)
goto err;
}
}
if (!(cflag & X509_FLAG_NO_SUBJECT)) {
if (BIO_printf(bp, " Subject:%c", mlch) <= 0)
goto err;
if (X509_NAME_print_ex(bp, X509_REQ_get_subject_name(x),
nmindent, nmflags) < 0)
goto err;
if (BIO_write(bp, "\n", 1) <= 0)
goto err;
}
if (!(cflag & X509_FLAG_NO_PUBKEY)) {
X509_PUBKEY *xpkey;
ASN1_OBJECT *koid;
if (BIO_write(bp, " Subject Public Key Info:\n", 33) <= 0)
goto err;
if (BIO_printf(bp, "%12sPublic Key Algorithm: ", "") <= 0)
goto err;
xpkey = X509_REQ_get_X509_PUBKEY(x);
X509_PUBKEY_get0_param(&koid, NULL, NULL, NULL, xpkey);
if (i2a_ASN1_OBJECT(bp, koid) <= 0)
goto err;
if (BIO_puts(bp, "\n") <= 0)
goto err;
pkey = X509_REQ_get0_pubkey(x);
if (pkey == NULL) {
if (BIO_printf(bp, "%12sUnable to load Public Key\n", "") <= 0)
goto err;
ERR_print_errors(bp);
} else {
if (EVP_PKEY_print_public(bp, pkey, 16, NULL) <= 0)
goto err;
}
}
if (!(cflag & X509_FLAG_NO_ATTRIBUTES)) {
/* may not be */
if (BIO_printf(bp, "%8sAttributes:\n", "") <= 0)
goto err;
if (X509_REQ_get_attr_count(x) == 0) {
if (BIO_printf(bp, "%12s(none)\n", "") <= 0)
goto err;
} else {
for (i = 0; i < X509_REQ_get_attr_count(x); i++) {
ASN1_TYPE *at;
X509_ATTRIBUTE *a;
ASN1_BIT_STRING *bs = NULL;
ASN1_OBJECT *aobj;
int j, type = 0, count = 1, ii = 0;
a = X509_REQ_get_attr(x, i);
aobj = X509_ATTRIBUTE_get0_object(a);
if (X509_REQ_extension_nid(OBJ_obj2nid(aobj)))
continue;
if (BIO_printf(bp, "%12s", "") <= 0)
goto err;
if ((j = i2a_ASN1_OBJECT(bp, aobj)) > 0) {
ii = 0;
count = X509_ATTRIBUTE_count(a);
if (count == 0) {
ERR_raise(ERR_LIB_X509, X509_R_INVALID_ATTRIBUTES);
return 0;
}
get_next:
at = X509_ATTRIBUTE_get0_type(a, ii);
type = at->type;
bs = at->value.asn1_string;
}
for (j = 25 - j; j > 0; j--)
if (BIO_write(bp, " ", 1) != 1)
goto err;
if (BIO_puts(bp, ":") <= 0)
goto err;
switch (type) {
case V_ASN1_PRINTABLESTRING:
case V_ASN1_T61STRING:
case V_ASN1_NUMERICSTRING:
case V_ASN1_UTF8STRING:
case V_ASN1_IA5STRING:
if (BIO_write(bp, (char *)bs->data, bs->length)
!= bs->length)
goto err;
if (BIO_puts(bp, "\n") <= 0)
goto err;
break;
default:
if (BIO_puts(bp, "unable to print attribute\n") <= 0)
goto err;
break;
}
if (++ii < count)
goto get_next;
}
}
}
if (!(cflag & X509_FLAG_NO_EXTENSIONS)) {
exts = X509_REQ_get_extensions(x);
if (exts) {
if (BIO_printf(bp, "%12sRequested Extensions:\n", "") <= 0)
goto err;
for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
ASN1_OBJECT *obj;
X509_EXTENSION *ex;
int critical;
ex = sk_X509_EXTENSION_value(exts, i);
if (BIO_printf(bp, "%16s", "") <= 0)
goto err;
obj = X509_EXTENSION_get_object(ex);
if (i2a_ASN1_OBJECT(bp, obj) <= 0)
goto err;
critical = X509_EXTENSION_get_critical(ex);
if (BIO_printf(bp, ": %s\n", critical ? "critical" : "") <= 0)
goto err;
if (!X509V3_EXT_print(bp, ex, cflag, 20)) {
if (BIO_printf(bp, "%20s", "") <= 0
|| ASN1_STRING_print(bp,
X509_EXTENSION_get_data(ex)) <= 0)
goto err;
}
if (BIO_write(bp, "\n", 1) <= 0)
goto err;
}
sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
}
}
if (!(cflag & X509_FLAG_NO_SIGDUMP)) {
const X509_ALGOR *sig_alg;
const ASN1_BIT_STRING *sig;
X509_REQ_get0_signature(x, &sig, &sig_alg);
if (!X509_signature_print(bp, sig_alg, sig))
goto err;
}
return 1;
err:
ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
return 0;
}
int X509_REQ_print(BIO *bp, X509_REQ *x)
{
return X509_REQ_print_ex(bp, x, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
}
| 7,073 | 31.902326 | 94 |
c
|
openssl
|
openssl-master/crypto/x509/t_x509.c
|
/*
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/bn.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "crypto/asn1.h"
#include "crypto/x509.h"
void OSSL_STACK_OF_X509_free(STACK_OF(X509) *certs)
{
sk_X509_pop_free(certs, X509_free);
}
#ifndef OPENSSL_NO_STDIO
int X509_print_fp(FILE *fp, X509 *x)
{
return X509_print_ex_fp(fp, x, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
}
int X509_print_ex_fp(FILE *fp, X509 *x, unsigned long nmflag,
unsigned long cflag)
{
BIO *b;
int ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
return 0;
}
BIO_set_fp(b, fp, BIO_NOCLOSE);
ret = X509_print_ex(b, x, nmflag, cflag);
BIO_free(b);
return ret;
}
#endif
int X509_print(BIO *bp, X509 *x)
{
return X509_print_ex(bp, x, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
}
int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflags,
unsigned long cflag)
{
long l;
int ret = 0, i;
char mlch = ' ';
int nmindent = 0, printok = 0;
EVP_PKEY *pkey = NULL;
const char *neg;
if ((nmflags & XN_FLAG_SEP_MASK) == XN_FLAG_SEP_MULTILINE) {
mlch = '\n';
nmindent = 12;
}
if (nmflags == X509_FLAG_COMPAT) {
nmindent = 16;
printok = 1;
}
if (!(cflag & X509_FLAG_NO_HEADER)) {
if (BIO_write(bp, "Certificate:\n", 13) <= 0)
goto err;
if (BIO_write(bp, " Data:\n", 10) <= 0)
goto err;
}
if (!(cflag & X509_FLAG_NO_VERSION)) {
l = X509_get_version(x);
if (l >= X509_VERSION_1 && l <= X509_VERSION_3) {
if (BIO_printf(bp, "%8sVersion: %ld (0x%lx)\n", "", l + 1, (unsigned long)l) <= 0)
goto err;
} else {
if (BIO_printf(bp, "%8sVersion: Unknown (%ld)\n", "", l) <= 0)
goto err;
}
}
if (!(cflag & X509_FLAG_NO_SERIAL)) {
const ASN1_INTEGER *bs = X509_get0_serialNumber(x);
if (BIO_write(bp, " Serial Number:", 22) <= 0)
goto err;
if (bs->length <= (int)sizeof(long)) {
ERR_set_mark();
l = ASN1_INTEGER_get(bs);
ERR_pop_to_mark();
} else {
l = -1;
}
if (l != -1) {
unsigned long ul;
if (bs->type == V_ASN1_NEG_INTEGER) {
ul = 0 - (unsigned long)l;
neg = "-";
} else {
ul = l;
neg = "";
}
if (BIO_printf(bp, " %s%lu (%s0x%lx)\n", neg, ul, neg, ul) <= 0)
goto err;
} else {
neg = (bs->type == V_ASN1_NEG_INTEGER) ? " (Negative)" : "";
if (BIO_printf(bp, "\n%12s%s", "", neg) <= 0)
goto err;
for (i = 0; i < bs->length; i++) {
if (BIO_printf(bp, "%02x%c", bs->data[i],
((i + 1 == bs->length) ? '\n' : ':')) <= 0)
goto err;
}
}
}
if (!(cflag & X509_FLAG_NO_SIGNAME)) {
const X509_ALGOR *tsig_alg = X509_get0_tbs_sigalg(x);
if (BIO_puts(bp, " ") <= 0)
goto err;
if (X509_signature_print(bp, tsig_alg, NULL) <= 0)
goto err;
}
if (!(cflag & X509_FLAG_NO_ISSUER)) {
if (BIO_printf(bp, " Issuer:%c", mlch) <= 0)
goto err;
if (X509_NAME_print_ex(bp, X509_get_issuer_name(x), nmindent, nmflags)
< printok)
goto err;
if (BIO_write(bp, "\n", 1) <= 0)
goto err;
}
if (!(cflag & X509_FLAG_NO_VALIDITY)) {
if (BIO_write(bp, " Validity\n", 17) <= 0)
goto err;
if (BIO_write(bp, " Not Before: ", 24) <= 0)
goto err;
if (ossl_asn1_time_print_ex(bp, X509_get0_notBefore(x), ASN1_DTFLGS_RFC822) == 0)
goto err;
if (BIO_write(bp, "\n Not After : ", 25) <= 0)
goto err;
if (ossl_asn1_time_print_ex(bp, X509_get0_notAfter(x), ASN1_DTFLGS_RFC822) == 0)
goto err;
if (BIO_write(bp, "\n", 1) <= 0)
goto err;
}
if (!(cflag & X509_FLAG_NO_SUBJECT)) {
if (BIO_printf(bp, " Subject:%c", mlch) <= 0)
goto err;
if (X509_NAME_print_ex
(bp, X509_get_subject_name(x), nmindent, nmflags) < printok)
goto err;
if (BIO_write(bp, "\n", 1) <= 0)
goto err;
}
if (!(cflag & X509_FLAG_NO_PUBKEY)) {
X509_PUBKEY *xpkey = X509_get_X509_PUBKEY(x);
ASN1_OBJECT *xpoid;
X509_PUBKEY_get0_param(&xpoid, NULL, NULL, NULL, xpkey);
if (BIO_write(bp, " Subject Public Key Info:\n", 33) <= 0)
goto err;
if (BIO_printf(bp, "%12sPublic Key Algorithm: ", "") <= 0)
goto err;
if (i2a_ASN1_OBJECT(bp, xpoid) <= 0)
goto err;
if (BIO_puts(bp, "\n") <= 0)
goto err;
pkey = X509_get0_pubkey(x);
if (pkey == NULL) {
BIO_printf(bp, "%12sUnable to load Public Key\n", "");
ERR_print_errors(bp);
} else {
EVP_PKEY_print_public(bp, pkey, 16, NULL);
}
}
if (!(cflag & X509_FLAG_NO_IDS)) {
const ASN1_BIT_STRING *iuid, *suid;
X509_get0_uids(x, &iuid, &suid);
if (iuid != NULL) {
if (BIO_printf(bp, "%8sIssuer Unique ID: ", "") <= 0)
goto err;
if (!X509_signature_dump(bp, iuid, 12))
goto err;
}
if (suid != NULL) {
if (BIO_printf(bp, "%8sSubject Unique ID: ", "") <= 0)
goto err;
if (!X509_signature_dump(bp, suid, 12))
goto err;
}
}
if (!(cflag & X509_FLAG_NO_EXTENSIONS)
&& !X509V3_extensions_print(bp, "X509v3 extensions",
X509_get0_extensions(x), cflag, 8))
goto err;
if (!(cflag & X509_FLAG_NO_SIGDUMP)) {
const X509_ALGOR *sig_alg;
const ASN1_BIT_STRING *sig;
X509_get0_signature(&sig, &sig_alg, x);
if (X509_signature_print(bp, sig_alg, sig) <= 0)
goto err;
}
if (!(cflag & X509_FLAG_NO_AUX)) {
if (!X509_aux_print(bp, x, 0))
goto err;
}
ret = 1;
err:
return ret;
}
int X509_ocspid_print(BIO *bp, X509 *x)
{
unsigned char *der = NULL;
unsigned char *dertmp;
int derlen;
int i;
unsigned char SHA1md[SHA_DIGEST_LENGTH];
ASN1_BIT_STRING *keybstr;
const X509_NAME *subj;
EVP_MD *md = NULL;
if (x == NULL || bp == NULL)
return 0;
/*
* display the hash of the subject as it would appear in OCSP requests
*/
if (BIO_printf(bp, " Subject OCSP hash: ") <= 0)
goto err;
subj = X509_get_subject_name(x);
derlen = i2d_X509_NAME(subj, NULL);
if (derlen <= 0)
goto err;
if ((der = dertmp = OPENSSL_malloc(derlen)) == NULL)
goto err;
i2d_X509_NAME(subj, &dertmp);
md = EVP_MD_fetch(x->libctx, SN_sha1, x->propq);
if (md == NULL)
goto err;
if (!EVP_Digest(der, derlen, SHA1md, NULL, md, NULL))
goto err;
for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
if (BIO_printf(bp, "%02X", SHA1md[i]) <= 0)
goto err;
}
OPENSSL_free(der);
der = NULL;
/*
* display the hash of the public key as it would appear in OCSP requests
*/
if (BIO_printf(bp, "\n Public key OCSP hash: ") <= 0)
goto err;
keybstr = X509_get0_pubkey_bitstr(x);
if (keybstr == NULL)
goto err;
if (!EVP_Digest(ASN1_STRING_get0_data(keybstr),
ASN1_STRING_length(keybstr), SHA1md, NULL, md, NULL))
goto err;
for (i = 0; i < SHA_DIGEST_LENGTH; i++) {
if (BIO_printf(bp, "%02X", SHA1md[i]) <= 0)
goto err;
}
BIO_printf(bp, "\n");
EVP_MD_free(md);
return 1;
err:
OPENSSL_free(der);
EVP_MD_free(md);
return 0;
}
int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent)
{
const unsigned char *s;
int i, n;
n = sig->length;
s = sig->data;
for (i = 0; i < n; i++) {
if ((i % 18) == 0) {
if (i > 0 && BIO_write(bp, "\n", 1) <= 0)
return 0;
if (BIO_indent(bp, indent, indent) <= 0)
return 0;
}
if (BIO_printf(bp, "%02x%s", s[i], ((i + 1) == n) ? "" : ":") <= 0)
return 0;
}
if (BIO_write(bp, "\n", 1) != 1)
return 0;
return 1;
}
int X509_signature_print(BIO *bp, const X509_ALGOR *sigalg,
const ASN1_STRING *sig)
{
int sig_nid;
int indent = 4;
if (BIO_printf(bp, "%*sSignature Algorithm: ", indent, "") <= 0)
return 0;
if (i2a_ASN1_OBJECT(bp, sigalg->algorithm) <= 0)
return 0;
if (sig && BIO_printf(bp, "\n%*sSignature Value:", indent, "") <= 0)
return 0;
sig_nid = OBJ_obj2nid(sigalg->algorithm);
if (sig_nid != NID_undef) {
int pkey_nid, dig_nid;
const EVP_PKEY_ASN1_METHOD *ameth;
if (OBJ_find_sigid_algs(sig_nid, &dig_nid, &pkey_nid)) {
ameth = EVP_PKEY_asn1_find(NULL, pkey_nid);
if (ameth && ameth->sig_print)
return ameth->sig_print(bp, sigalg, sig, indent + 4, 0);
}
}
if (BIO_write(bp, "\n", 1) != 1)
return 0;
if (sig)
return X509_signature_dump(bp, sig, indent + 4);
return 1;
}
int X509_aux_print(BIO *out, X509 *x, int indent)
{
char oidstr[80], first;
STACK_OF(ASN1_OBJECT) *trust, *reject;
const unsigned char *alias, *keyid;
int keyidlen;
int i;
if (X509_trusted(x) == 0)
return 1;
trust = X509_get0_trust_objects(x);
reject = X509_get0_reject_objects(x);
if (trust) {
first = 1;
BIO_printf(out, "%*sTrusted Uses:\n%*s", indent, "", indent + 2, "");
for (i = 0; i < sk_ASN1_OBJECT_num(trust); i++) {
if (!first)
BIO_puts(out, ", ");
else
first = 0;
OBJ_obj2txt(oidstr, sizeof(oidstr),
sk_ASN1_OBJECT_value(trust, i), 0);
BIO_puts(out, oidstr);
}
BIO_puts(out, "\n");
} else
BIO_printf(out, "%*sNo Trusted Uses.\n", indent, "");
if (reject) {
first = 1;
BIO_printf(out, "%*sRejected Uses:\n%*s", indent, "", indent + 2, "");
for (i = 0; i < sk_ASN1_OBJECT_num(reject); i++) {
if (!first)
BIO_puts(out, ", ");
else
first = 0;
OBJ_obj2txt(oidstr, sizeof(oidstr),
sk_ASN1_OBJECT_value(reject, i), 0);
BIO_puts(out, oidstr);
}
BIO_puts(out, "\n");
} else
BIO_printf(out, "%*sNo Rejected Uses.\n", indent, "");
alias = X509_alias_get0(x, &i);
if (alias)
BIO_printf(out, "%*sAlias: %.*s\n", indent, "", i, alias);
keyid = X509_keyid_get0(x, &keyidlen);
if (keyid) {
BIO_printf(out, "%*sKey Id: ", indent, "");
for (i = 0; i < keyidlen; i++)
BIO_printf(out, "%s%02X", i ? ":" : "", keyid[i]);
BIO_write(out, "\n", 1);
}
return 1;
}
/*
* Helper functions for improving certificate verification error diagnostics
*/
int ossl_x509_print_ex_brief(BIO *bio, X509 *cert, unsigned long neg_cflags)
{
unsigned long flags = ASN1_STRFLGS_RFC2253 | ASN1_STRFLGS_ESC_QUOTE |
XN_FLAG_SEP_CPLUS_SPC | XN_FLAG_FN_SN;
if (cert == NULL)
return BIO_printf(bio, " (no certificate)\n") > 0;
if (BIO_printf(bio, " certificate\n") <= 0
|| !X509_print_ex(bio, cert, flags, ~X509_FLAG_NO_SUBJECT))
return 0;
if (X509_check_issued((X509 *)cert, cert) == X509_V_OK) {
if (BIO_printf(bio, " self-issued\n") <= 0)
return 0;
} else {
if (BIO_printf(bio, " ") <= 0
|| !X509_print_ex(bio, cert, flags, ~X509_FLAG_NO_ISSUER))
return 0;
}
if (!X509_print_ex(bio, cert, flags,
~(X509_FLAG_NO_SERIAL | X509_FLAG_NO_VALIDITY)))
return 0;
if (X509_cmp_current_time(X509_get0_notBefore(cert)) > 0)
if (BIO_printf(bio, " not yet valid\n") <= 0)
return 0;
if (X509_cmp_current_time(X509_get0_notAfter(cert)) < 0)
if (BIO_printf(bio, " no more valid\n") <= 0)
return 0;
return X509_print_ex(bio, cert, flags,
~neg_cflags & ~X509_FLAG_EXTENSIONS_ONLY_KID);
}
static int print_certs(BIO *bio, const STACK_OF(X509) *certs)
{
int i;
if (certs == NULL || sk_X509_num(certs) <= 0)
return BIO_printf(bio, " (no certificates)\n") >= 0;
for (i = 0; i < sk_X509_num(certs); i++) {
X509 *cert = sk_X509_value(certs, i);
if (cert != NULL) {
if (!ossl_x509_print_ex_brief(bio, cert, 0))
return 0;
if (!X509V3_extensions_print(bio, NULL,
X509_get0_extensions(cert),
X509_FLAG_EXTENSIONS_ONLY_KID, 8))
return 0;
}
}
return 1;
}
static int print_store_certs(BIO *bio, X509_STORE *store)
{
if (store != NULL) {
STACK_OF(X509) *certs = X509_STORE_get1_all_certs(store);
int ret = print_certs(bio, certs);
OSSL_STACK_OF_X509_free(certs);
return ret;
} else {
return BIO_printf(bio, " (no trusted store)\n") >= 0;
}
}
/* Extend the error queue with details on a failed cert verification */
int X509_STORE_CTX_print_verify_cb(int ok, X509_STORE_CTX *ctx)
{
if (ok == 0 && ctx != NULL) {
int cert_error = X509_STORE_CTX_get_error(ctx);
BIO *bio = BIO_new(BIO_s_mem()); /* may be NULL */
if (bio == NULL)
return 0;
BIO_printf(bio, "%s at depth = %d error = %d (%s)\n",
X509_STORE_CTX_get0_parent_ctx(ctx) != NULL
? "CRL path validation"
: "Certificate verification",
X509_STORE_CTX_get_error_depth(ctx),
cert_error, X509_verify_cert_error_string(cert_error));
{
X509_STORE *ts = X509_STORE_CTX_get0_store(ctx);
X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts);
char *str;
int idx = 0;
switch (cert_error) {
case X509_V_ERR_HOSTNAME_MISMATCH:
BIO_printf(bio, "Expected hostname(s) = ");
while ((str = X509_VERIFY_PARAM_get0_host(vpm, idx++)) != NULL)
BIO_printf(bio, "%s%s", idx == 1 ? "" : ", ", str);
BIO_printf(bio, "\n");
break;
case X509_V_ERR_EMAIL_MISMATCH:
str = X509_VERIFY_PARAM_get0_email(vpm);
if (str != NULL)
BIO_printf(bio, "Expected email address = %s\n", str);
break;
case X509_V_ERR_IP_ADDRESS_MISMATCH:
str = X509_VERIFY_PARAM_get1_ip_asc(vpm);
if (str != NULL)
BIO_printf(bio, "Expected IP address = %s\n", str);
OPENSSL_free(str);
break;
default:
break;
}
}
BIO_printf(bio, "Failure for:\n");
ossl_x509_print_ex_brief(bio, X509_STORE_CTX_get_current_cert(ctx),
X509_FLAG_NO_EXTENSIONS);
if (cert_error == X509_V_ERR_CERT_UNTRUSTED
|| cert_error == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT
|| cert_error == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN
|| cert_error == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT
|| cert_error == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY
|| cert_error == X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER
|| cert_error == X509_V_ERR_STORE_LOOKUP) {
BIO_printf(bio, "Non-trusted certs:\n");
print_certs(bio, X509_STORE_CTX_get0_untrusted(ctx));
BIO_printf(bio, "Certs in trust store:\n");
print_store_certs(bio, X509_STORE_CTX_get0_store(ctx));
}
ERR_raise(ERR_LIB_X509, X509_R_CERTIFICATE_VERIFICATION_FAILED);
ERR_add_error_mem_bio("\n", bio);
BIO_free(bio);
}
return ok;
}
| 17,031 | 30.776119 | 94 |
c
|
openssl
|
openssl-master/crypto/x509/v3_admis.c
|
/*
* Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/types.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
#include <openssl/safestack.h>
#include "v3_admis.h"
#include "ext_dat.h"
ASN1_SEQUENCE(NAMING_AUTHORITY) = {
ASN1_OPT(NAMING_AUTHORITY, namingAuthorityId, ASN1_OBJECT),
ASN1_OPT(NAMING_AUTHORITY, namingAuthorityUrl, ASN1_IA5STRING),
ASN1_OPT(NAMING_AUTHORITY, namingAuthorityText, DIRECTORYSTRING),
} ASN1_SEQUENCE_END(NAMING_AUTHORITY)
ASN1_SEQUENCE(PROFESSION_INFO) = {
ASN1_EXP_OPT(PROFESSION_INFO, namingAuthority, NAMING_AUTHORITY, 0),
ASN1_SEQUENCE_OF(PROFESSION_INFO, professionItems, DIRECTORYSTRING),
ASN1_SEQUENCE_OF_OPT(PROFESSION_INFO, professionOIDs, ASN1_OBJECT),
ASN1_OPT(PROFESSION_INFO, registrationNumber, ASN1_PRINTABLESTRING),
ASN1_OPT(PROFESSION_INFO, addProfessionInfo, ASN1_OCTET_STRING),
} ASN1_SEQUENCE_END(PROFESSION_INFO)
ASN1_SEQUENCE(ADMISSIONS) = {
ASN1_EXP_OPT(ADMISSIONS, admissionAuthority, GENERAL_NAME, 0),
ASN1_EXP_OPT(ADMISSIONS, namingAuthority, NAMING_AUTHORITY, 1),
ASN1_SEQUENCE_OF(ADMISSIONS, professionInfos, PROFESSION_INFO),
} ASN1_SEQUENCE_END(ADMISSIONS)
ASN1_SEQUENCE(ADMISSION_SYNTAX) = {
ASN1_OPT(ADMISSION_SYNTAX, admissionAuthority, GENERAL_NAME),
ASN1_SEQUENCE_OF(ADMISSION_SYNTAX, contentsOfAdmissions, ADMISSIONS),
} ASN1_SEQUENCE_END(ADMISSION_SYNTAX)
IMPLEMENT_ASN1_FUNCTIONS(NAMING_AUTHORITY)
IMPLEMENT_ASN1_FUNCTIONS(PROFESSION_INFO)
IMPLEMENT_ASN1_FUNCTIONS(ADMISSIONS)
IMPLEMENT_ASN1_FUNCTIONS(ADMISSION_SYNTAX)
static int i2r_ADMISSION_SYNTAX(const struct v3_ext_method *method, void *in,
BIO *bp, int ind);
const X509V3_EXT_METHOD ossl_v3_ext_admission = {
NID_x509ExtAdmission, /* .ext_nid = */
0, /* .ext_flags = */
ASN1_ITEM_ref(ADMISSION_SYNTAX), /* .it = */
NULL, NULL, NULL, NULL,
NULL, /* .i2s = */
NULL, /* .s2i = */
NULL, /* .i2v = */
NULL, /* .v2i = */
&i2r_ADMISSION_SYNTAX, /* .i2r = */
NULL, /* .r2i = */
NULL /* extension-specific data */
};
static int i2r_NAMING_AUTHORITY(const struct v3_ext_method *method, void *in,
BIO *bp, int ind)
{
NAMING_AUTHORITY * namingAuthority = (NAMING_AUTHORITY*) in;
if (namingAuthority == NULL)
return 0;
if (namingAuthority->namingAuthorityId == NULL
&& namingAuthority->namingAuthorityText == NULL
&& namingAuthority->namingAuthorityUrl == NULL)
return 0;
if (BIO_printf(bp, "%*snamingAuthority: ", ind, "") <= 0)
goto err;
if (namingAuthority->namingAuthorityId != NULL) {
char objbuf[128];
const char *ln = OBJ_nid2ln(OBJ_obj2nid(namingAuthority->namingAuthorityId));
if (BIO_printf(bp, "%*s admissionAuthorityId: ", ind, "") <= 0)
goto err;
OBJ_obj2txt(objbuf, sizeof(objbuf), namingAuthority->namingAuthorityId, 1);
if (BIO_printf(bp, "%s%s%s%s\n", ln ? ln : "",
ln ? " (" : "", objbuf, ln ? ")" : "") <= 0)
goto err;
}
if (namingAuthority->namingAuthorityText != NULL) {
if (BIO_printf(bp, "%*s namingAuthorityText: ", ind, "") <= 0
|| ASN1_STRING_print(bp, namingAuthority->namingAuthorityText) <= 0
|| BIO_printf(bp, "\n") <= 0)
goto err;
}
if (namingAuthority->namingAuthorityUrl != NULL) {
if (BIO_printf(bp, "%*s namingAuthorityUrl: ", ind, "") <= 0
|| ASN1_STRING_print(bp, namingAuthority->namingAuthorityUrl) <= 0
|| BIO_printf(bp, "\n") <= 0)
goto err;
}
return 1;
err:
return 0;
}
static int i2r_ADMISSION_SYNTAX(const struct v3_ext_method *method, void *in,
BIO *bp, int ind)
{
ADMISSION_SYNTAX * admission = (ADMISSION_SYNTAX *)in;
int i, j, k;
if (admission->admissionAuthority != NULL) {
if (BIO_printf(bp, "%*sadmissionAuthority:\n", ind, "") <= 0
|| BIO_printf(bp, "%*s ", ind, "") <= 0
|| GENERAL_NAME_print(bp, admission->admissionAuthority) <= 0
|| BIO_printf(bp, "\n") <= 0)
goto err;
}
for (i = 0; i < sk_ADMISSIONS_num(admission->contentsOfAdmissions); i++) {
ADMISSIONS* entry = sk_ADMISSIONS_value(admission->contentsOfAdmissions, i);
if (BIO_printf(bp, "%*sEntry %0d:\n", ind, "", 1 + i) <= 0) goto err;
if (entry->admissionAuthority != NULL) {
if (BIO_printf(bp, "%*s admissionAuthority:\n", ind, "") <= 0
|| BIO_printf(bp, "%*s ", ind, "") <= 0
|| GENERAL_NAME_print(bp, entry->admissionAuthority) <= 0
|| BIO_printf(bp, "\n") <= 0)
goto err;
}
if (entry->namingAuthority != NULL) {
if (i2r_NAMING_AUTHORITY(method, entry->namingAuthority, bp, ind) <= 0)
goto err;
}
for (j = 0; j < sk_PROFESSION_INFO_num(entry->professionInfos); j++) {
PROFESSION_INFO* pinfo = sk_PROFESSION_INFO_value(entry->professionInfos, j);
if (BIO_printf(bp, "%*s Profession Info Entry %0d:\n", ind, "", 1 + j) <= 0)
goto err;
if (pinfo->registrationNumber != NULL) {
if (BIO_printf(bp, "%*s registrationNumber: ", ind, "") <= 0
|| ASN1_STRING_print(bp, pinfo->registrationNumber) <= 0
|| BIO_printf(bp, "\n") <= 0)
goto err;
}
if (pinfo->namingAuthority != NULL) {
if (i2r_NAMING_AUTHORITY(method, pinfo->namingAuthority, bp, ind + 2) <= 0)
goto err;
}
if (pinfo->professionItems != NULL) {
if (BIO_printf(bp, "%*s Info Entries:\n", ind, "") <= 0)
goto err;
for (k = 0; k < sk_ASN1_STRING_num(pinfo->professionItems); k++) {
ASN1_STRING* val = sk_ASN1_STRING_value(pinfo->professionItems, k);
if (BIO_printf(bp, "%*s ", ind, "") <= 0
|| ASN1_STRING_print(bp, val) <= 0
|| BIO_printf(bp, "\n") <= 0)
goto err;
}
}
if (pinfo->professionOIDs != NULL) {
if (BIO_printf(bp, "%*s Profession OIDs:\n", ind, "") <= 0)
goto err;
for (k = 0; k < sk_ASN1_OBJECT_num(pinfo->professionOIDs); k++) {
ASN1_OBJECT* obj = sk_ASN1_OBJECT_value(pinfo->professionOIDs, k);
const char *ln = OBJ_nid2ln(OBJ_obj2nid(obj));
char objbuf[128];
OBJ_obj2txt(objbuf, sizeof(objbuf), obj, 1);
if (BIO_printf(bp, "%*s %s%s%s%s\n", ind, "",
ln ? ln : "", ln ? " (" : "",
objbuf, ln ? ")" : "") <= 0)
goto err;
}
}
}
}
return 1;
err:
return 0;
}
const ASN1_OBJECT *NAMING_AUTHORITY_get0_authorityId(const NAMING_AUTHORITY *n)
{
return n->namingAuthorityId;
}
void NAMING_AUTHORITY_set0_authorityId(NAMING_AUTHORITY *n, ASN1_OBJECT* id)
{
ASN1_OBJECT_free(n->namingAuthorityId);
n->namingAuthorityId = id;
}
const ASN1_IA5STRING *NAMING_AUTHORITY_get0_authorityURL(
const NAMING_AUTHORITY *n)
{
return n->namingAuthorityUrl;
}
void NAMING_AUTHORITY_set0_authorityURL(NAMING_AUTHORITY *n, ASN1_IA5STRING* u)
{
ASN1_IA5STRING_free(n->namingAuthorityUrl);
n->namingAuthorityUrl = u;
}
const ASN1_STRING *NAMING_AUTHORITY_get0_authorityText(
const NAMING_AUTHORITY *n)
{
return n->namingAuthorityText;
}
void NAMING_AUTHORITY_set0_authorityText(NAMING_AUTHORITY *n, ASN1_STRING* t)
{
ASN1_IA5STRING_free(n->namingAuthorityText);
n->namingAuthorityText = t;
}
const GENERAL_NAME *ADMISSION_SYNTAX_get0_admissionAuthority(const ADMISSION_SYNTAX *as)
{
return as->admissionAuthority;
}
void ADMISSION_SYNTAX_set0_admissionAuthority(ADMISSION_SYNTAX *as,
GENERAL_NAME *aa)
{
GENERAL_NAME_free(as->admissionAuthority);
as->admissionAuthority = aa;
}
const STACK_OF(ADMISSIONS) *ADMISSION_SYNTAX_get0_contentsOfAdmissions(const ADMISSION_SYNTAX *as)
{
return as->contentsOfAdmissions;
}
void ADMISSION_SYNTAX_set0_contentsOfAdmissions(ADMISSION_SYNTAX *as,
STACK_OF(ADMISSIONS) *a)
{
sk_ADMISSIONS_pop_free(as->contentsOfAdmissions, ADMISSIONS_free);
as->contentsOfAdmissions = a;
}
const GENERAL_NAME *ADMISSIONS_get0_admissionAuthority(const ADMISSIONS *a)
{
return a->admissionAuthority;
}
void ADMISSIONS_set0_admissionAuthority(ADMISSIONS *a, GENERAL_NAME *aa)
{
GENERAL_NAME_free(a->admissionAuthority);
a->admissionAuthority = aa;
}
const NAMING_AUTHORITY *ADMISSIONS_get0_namingAuthority(const ADMISSIONS *a)
{
return a->namingAuthority;
}
void ADMISSIONS_set0_namingAuthority(ADMISSIONS *a, NAMING_AUTHORITY *na)
{
NAMING_AUTHORITY_free(a->namingAuthority);
a->namingAuthority = na;
}
const PROFESSION_INFOS *ADMISSIONS_get0_professionInfos(const ADMISSIONS *a)
{
return a->professionInfos;
}
void ADMISSIONS_set0_professionInfos(ADMISSIONS *a, PROFESSION_INFOS *pi)
{
sk_PROFESSION_INFO_pop_free(a->professionInfos, PROFESSION_INFO_free);
a->professionInfos = pi;
}
const ASN1_OCTET_STRING *PROFESSION_INFO_get0_addProfessionInfo(const PROFESSION_INFO *pi)
{
return pi->addProfessionInfo;
}
void PROFESSION_INFO_set0_addProfessionInfo(PROFESSION_INFO *pi,
ASN1_OCTET_STRING *aos)
{
ASN1_OCTET_STRING_free(pi->addProfessionInfo);
pi->addProfessionInfo = aos;
}
const NAMING_AUTHORITY *PROFESSION_INFO_get0_namingAuthority(const PROFESSION_INFO *pi)
{
return pi->namingAuthority;
}
void PROFESSION_INFO_set0_namingAuthority(PROFESSION_INFO *pi,
NAMING_AUTHORITY *na)
{
NAMING_AUTHORITY_free(pi->namingAuthority);
pi->namingAuthority = na;
}
const STACK_OF(ASN1_STRING) *PROFESSION_INFO_get0_professionItems(const PROFESSION_INFO *pi)
{
return pi->professionItems;
}
void PROFESSION_INFO_set0_professionItems(PROFESSION_INFO *pi,
STACK_OF(ASN1_STRING) *as)
{
sk_ASN1_STRING_pop_free(pi->professionItems, ASN1_STRING_free);
pi->professionItems = as;
}
const STACK_OF(ASN1_OBJECT) *PROFESSION_INFO_get0_professionOIDs(const PROFESSION_INFO *pi)
{
return pi->professionOIDs;
}
void PROFESSION_INFO_set0_professionOIDs(PROFESSION_INFO *pi,
STACK_OF(ASN1_OBJECT) *po)
{
sk_ASN1_OBJECT_pop_free(pi->professionOIDs, ASN1_OBJECT_free);
pi->professionOIDs = po;
}
const ASN1_PRINTABLESTRING *PROFESSION_INFO_get0_registrationNumber(const PROFESSION_INFO *pi)
{
return pi->registrationNumber;
}
void PROFESSION_INFO_set0_registrationNumber(PROFESSION_INFO *pi,
ASN1_PRINTABLESTRING *rn)
{
ASN1_PRINTABLESTRING_free(pi->registrationNumber);
pi->registrationNumber = rn;
}
| 11,864 | 32.328652 | 98 |
c
|
openssl
|
openssl-master/crypto/x509/v3_admis.h
|
/*
* Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#ifndef OSSL_CRYPTO_X509_V3_ADMIS_H
# define OSSL_CRYPTO_X509_V3_ADMIS_H
struct NamingAuthority_st {
ASN1_OBJECT* namingAuthorityId;
ASN1_IA5STRING* namingAuthorityUrl;
ASN1_STRING* namingAuthorityText; /* i.e. DIRECTORYSTRING */
};
struct ProfessionInfo_st {
NAMING_AUTHORITY* namingAuthority;
STACK_OF(ASN1_STRING)* professionItems; /* i.e. DIRECTORYSTRING */
STACK_OF(ASN1_OBJECT)* professionOIDs;
ASN1_PRINTABLESTRING* registrationNumber;
ASN1_OCTET_STRING* addProfessionInfo;
};
struct Admissions_st {
GENERAL_NAME* admissionAuthority;
NAMING_AUTHORITY* namingAuthority;
STACK_OF(PROFESSION_INFO)* professionInfos;
};
struct AdmissionSyntax_st {
GENERAL_NAME* admissionAuthority;
STACK_OF(ADMISSIONS)* contentsOfAdmissions;
};
#endif
| 1,145 | 28.384615 | 74 |
h
|
openssl
|
openssl-master/crypto/x509/v3_akeya.c
|
/*
* Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
ASN1_SEQUENCE(AUTHORITY_KEYID) = {
ASN1_IMP_OPT(AUTHORITY_KEYID, keyid, ASN1_OCTET_STRING, 0),
ASN1_IMP_SEQUENCE_OF_OPT(AUTHORITY_KEYID, issuer, GENERAL_NAME, 1),
ASN1_IMP_OPT(AUTHORITY_KEYID, serial, ASN1_INTEGER, 2)
} ASN1_SEQUENCE_END(AUTHORITY_KEYID)
IMPLEMENT_ASN1_FUNCTIONS(AUTHORITY_KEYID)
| 817 | 33.083333 | 75 |
c
|
openssl
|
openssl-master/crypto/x509/v3_akid.c
|
/*
* Copyright 1999-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
#include "crypto/x509.h"
#include "ext_dat.h"
static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
AUTHORITY_KEYID *akeyid,
STACK_OF(CONF_VALUE)
*extlist);
static AUTHORITY_KEYID *v2i_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *values);
const X509V3_EXT_METHOD ossl_v3_akey_id = {
NID_authority_key_identifier,
X509V3_EXT_MULTILINE, ASN1_ITEM_ref(AUTHORITY_KEYID),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_AUTHORITY_KEYID,
(X509V3_EXT_V2I)v2i_AUTHORITY_KEYID,
0, 0,
NULL
};
static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
AUTHORITY_KEYID *akeyid,
STACK_OF(CONF_VALUE)
*extlist)
{
char *tmp = NULL;
STACK_OF(CONF_VALUE) *origextlist = extlist, *tmpextlist;
if (akeyid->keyid) {
tmp = i2s_ASN1_OCTET_STRING(NULL, akeyid->keyid);
if (tmp == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
return NULL;
}
if (!X509V3_add_value((akeyid->issuer || akeyid->serial) ? "keyid" : NULL,
tmp, &extlist)) {
OPENSSL_free(tmp);
ERR_raise(ERR_LIB_X509V3, ERR_R_X509_LIB);
goto err;
}
OPENSSL_free(tmp);
}
if (akeyid->issuer) {
tmpextlist = i2v_GENERAL_NAMES(NULL, akeyid->issuer, extlist);
if (tmpextlist == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_X509_LIB);
goto err;
}
extlist = tmpextlist;
}
if (akeyid->serial) {
tmp = i2s_ASN1_OCTET_STRING(NULL, akeyid->serial);
if (tmp == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
if (!X509V3_add_value("serial", tmp, &extlist)) {
OPENSSL_free(tmp);
goto err;
}
OPENSSL_free(tmp);
}
return extlist;
err:
if (origextlist == NULL)
sk_CONF_VALUE_pop_free(extlist, X509V3_conf_free);
return NULL;
}
/*-
* Three explicit tags may be given, where 'keyid' and 'issuer' may be combined:
* 'none': do not add any authority key identifier.
* 'keyid': use the issuer's subject keyid; the option 'always' means its is
* an error if the issuer certificate doesn't have a subject key id.
* 'issuer': use the issuer's cert issuer and serial number. The default is
* to only use this if 'keyid' is not present. With the option 'always'
* this is always included.
*/
static AUTHORITY_KEYID *v2i_AUTHORITY_KEYID(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *values)
{
char keyid = 0, issuer = 0;
int i, n = sk_CONF_VALUE_num(values);
CONF_VALUE *cnf;
ASN1_OCTET_STRING *ikeyid = NULL;
X509_NAME *isname = NULL;
GENERAL_NAMES *gens = NULL;
GENERAL_NAME *gen = NULL;
ASN1_INTEGER *serial = NULL;
X509_EXTENSION *ext;
X509 *issuer_cert;
int same_issuer, ss;
AUTHORITY_KEYID *akeyid = AUTHORITY_KEYID_new();
if (akeyid == NULL)
goto err;
if (n == 1 && strcmp(sk_CONF_VALUE_value(values, 0)->name, "none") == 0) {
return akeyid;
}
for (i = 0; i < n; i++) {
cnf = sk_CONF_VALUE_value(values, i);
if (cnf->value != NULL && strcmp(cnf->value, "always") != 0) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_UNKNOWN_OPTION,
"name=%s option=%s", cnf->name, cnf->value);
goto err;
}
if (strcmp(cnf->name, "keyid") == 0 && keyid == 0) {
keyid = 1;
if (cnf->value != NULL)
keyid = 2;
} else if (strcmp(cnf->name, "issuer") == 0 && issuer == 0) {
issuer = 1;
if (cnf->value != NULL)
issuer = 2;
} else if (strcmp(cnf->name, "none") == 0
|| strcmp(cnf->name, "keyid") == 0
|| strcmp(cnf->name, "issuer") == 0) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_BAD_VALUE,
"name=%s", cnf->name);
goto err;
} else {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_UNKNOWN_VALUE,
"name=%s", cnf->name);
goto err;
}
}
if (ctx != NULL && (ctx->flags & X509V3_CTX_TEST) != 0)
return akeyid;
if (ctx == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_NULL_PARAMETER);
goto err;
}
if ((issuer_cert = ctx->issuer_cert) == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_NO_ISSUER_CERTIFICATE);
goto err;
}
same_issuer = ctx->subject_cert == ctx->issuer_cert;
ERR_set_mark();
if (ctx->issuer_pkey != NULL)
ss = X509_check_private_key(ctx->subject_cert, ctx->issuer_pkey);
else
ss = same_issuer;
ERR_pop_to_mark();
/* unless forced with "always", AKID is suppressed for self-signed certs */
if (keyid == 2 || (keyid == 1 && !ss)) {
/*
* prefer any pre-existing subject key identifier of the issuer cert
* except issuer cert is same as subject cert and is not self-signed
*/
i = X509_get_ext_by_NID(issuer_cert, NID_subject_key_identifier, -1);
if (i >= 0 && (ext = X509_get_ext(issuer_cert, i)) != NULL
&& !(same_issuer && !ss)) {
ikeyid = X509V3_EXT_d2i(ext);
if (ASN1_STRING_length(ikeyid) == 0) /* indicating "none" */ {
ASN1_OCTET_STRING_free(ikeyid);
ikeyid = NULL;
}
}
if (ikeyid == NULL && same_issuer && ctx->issuer_pkey != NULL) {
/* generate fallback AKID, emulating s2i_skey_id(..., "hash") */
X509_PUBKEY *pubkey = NULL;
if (X509_PUBKEY_set(&pubkey, ctx->issuer_pkey))
ikeyid = ossl_x509_pubkey_hash(pubkey);
X509_PUBKEY_free(pubkey);
}
if (keyid == 2 && ikeyid == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_UNABLE_TO_GET_ISSUER_KEYID);
goto err;
}
}
if (issuer == 2 || (issuer == 1 && !ss && ikeyid == NULL)) {
isname = X509_NAME_dup(X509_get_issuer_name(issuer_cert));
serial = ASN1_INTEGER_dup(X509_get0_serialNumber(issuer_cert));
if (isname == NULL || serial == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS);
goto err;
}
}
if (isname != NULL) {
if ((gens = sk_GENERAL_NAME_new_null()) == NULL
|| (gen = GENERAL_NAME_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
if (!sk_GENERAL_NAME_push(gens, gen)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
gen->type = GEN_DIRNAME;
gen->d.dirn = isname;
}
akeyid->issuer = gens;
gen = NULL;
gens = NULL;
akeyid->serial = serial;
akeyid->keyid = ikeyid;
return akeyid;
err:
sk_GENERAL_NAME_free(gens);
GENERAL_NAME_free(gen);
X509_NAME_free(isname);
ASN1_INTEGER_free(serial);
ASN1_OCTET_STRING_free(ikeyid);
AUTHORITY_KEYID_free(akeyid);
return NULL;
}
| 8,141 | 33.5 | 82 |
c
|
openssl
|
openssl-master/crypto/x509/v3_bcons.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
#include "x509_local.h"
static STACK_OF(CONF_VALUE) *i2v_BASIC_CONSTRAINTS(X509V3_EXT_METHOD *method,
BASIC_CONSTRAINTS *bcons,
STACK_OF(CONF_VALUE)
*extlist);
static BASIC_CONSTRAINTS *v2i_BASIC_CONSTRAINTS(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *values);
const X509V3_EXT_METHOD ossl_v3_bcons = {
NID_basic_constraints, 0,
ASN1_ITEM_ref(BASIC_CONSTRAINTS),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_BASIC_CONSTRAINTS,
(X509V3_EXT_V2I)v2i_BASIC_CONSTRAINTS,
NULL, NULL,
NULL
};
ASN1_SEQUENCE(BASIC_CONSTRAINTS) = {
ASN1_OPT(BASIC_CONSTRAINTS, ca, ASN1_FBOOLEAN),
ASN1_OPT(BASIC_CONSTRAINTS, pathlen, ASN1_INTEGER)
} ASN1_SEQUENCE_END(BASIC_CONSTRAINTS)
IMPLEMENT_ASN1_FUNCTIONS(BASIC_CONSTRAINTS)
static STACK_OF(CONF_VALUE) *i2v_BASIC_CONSTRAINTS(X509V3_EXT_METHOD *method,
BASIC_CONSTRAINTS *bcons,
STACK_OF(CONF_VALUE)
*extlist)
{
X509V3_add_value_bool("CA", bcons->ca, &extlist);
X509V3_add_value_int("pathlen", bcons->pathlen, &extlist);
return extlist;
}
static BASIC_CONSTRAINTS *v2i_BASIC_CONSTRAINTS(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *values)
{
BASIC_CONSTRAINTS *bcons = NULL;
CONF_VALUE *val;
int i;
if ((bcons = BASIC_CONSTRAINTS_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(values); i++) {
val = sk_CONF_VALUE_value(values, i);
if (strcmp(val->name, "CA") == 0) {
if (!X509V3_get_value_bool(val, &bcons->ca))
goto err;
} else if (strcmp(val->name, "pathlen") == 0) {
if (!X509V3_get_value_int(val, &bcons->pathlen))
goto err;
} else {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NAME);
X509V3_conf_add_error_name_value(val);
goto err;
}
}
return bcons;
err:
BASIC_CONSTRAINTS_free(bcons);
return NULL;
}
| 3,005 | 33.953488 | 78 |
c
|
openssl
|
openssl-master/crypto/x509/v3_bitst.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
static BIT_STRING_BITNAME ns_cert_type_table[] = {
{0, "SSL Client", "client"},
{1, "SSL Server", "server"},
{2, "S/MIME", "email"},
{3, "Object Signing", "objsign"},
{4, "Unused", "reserved"},
{5, "SSL CA", "sslCA"},
{6, "S/MIME CA", "emailCA"},
{7, "Object Signing CA", "objCA"},
{-1, NULL, NULL}
};
static BIT_STRING_BITNAME key_usage_type_table[] = {
{0, "Digital Signature", "digitalSignature"},
{1, "Non Repudiation", "nonRepudiation"},
{2, "Key Encipherment", "keyEncipherment"},
{3, "Data Encipherment", "dataEncipherment"},
{4, "Key Agreement", "keyAgreement"},
{5, "Certificate Sign", "keyCertSign"},
{6, "CRL Sign", "cRLSign"},
{7, "Encipher Only", "encipherOnly"},
{8, "Decipher Only", "decipherOnly"},
{-1, NULL, NULL}
};
const X509V3_EXT_METHOD ossl_v3_nscert =
EXT_BITSTRING(NID_netscape_cert_type, ns_cert_type_table);
const X509V3_EXT_METHOD ossl_v3_key_usage =
EXT_BITSTRING(NID_key_usage, key_usage_type_table);
STACK_OF(CONF_VALUE) *i2v_ASN1_BIT_STRING(X509V3_EXT_METHOD *method,
ASN1_BIT_STRING *bits,
STACK_OF(CONF_VALUE) *ret)
{
BIT_STRING_BITNAME *bnam;
for (bnam = method->usr_data; bnam->lname; bnam++) {
if (ASN1_BIT_STRING_get_bit(bits, bnam->bitnum))
X509V3_add_value(bnam->lname, NULL, &ret);
}
return ret;
}
ASN1_BIT_STRING *v2i_ASN1_BIT_STRING(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval)
{
CONF_VALUE *val;
ASN1_BIT_STRING *bs;
int i;
BIT_STRING_BITNAME *bnam;
if ((bs = ASN1_BIT_STRING_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
val = sk_CONF_VALUE_value(nval, i);
for (bnam = method->usr_data; bnam->lname; bnam++) {
if (strcmp(bnam->sname, val->name) == 0
|| strcmp(bnam->lname, val->name) == 0) {
if (!ASN1_BIT_STRING_set_bit(bs, bnam->bitnum, 1)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
ASN1_BIT_STRING_free(bs);
return NULL;
}
break;
}
}
if (!bnam->lname) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_UNKNOWN_BIT_STRING_ARGUMENT,
"%s", val->name);
ASN1_BIT_STRING_free(bs);
return NULL;
}
}
return bs;
}
| 3,093 | 32.630435 | 80 |
c
|
openssl
|
openssl-master/crypto/x509/v3_conf.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* extension creation utilities */
#include <stdio.h>
#include "crypto/ctype.h"
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
#include <openssl/x509v3.h>
static int v3_check_critical(const char **value);
static int v3_check_generic(const char **value);
static X509_EXTENSION *do_ext_nconf(CONF *conf, X509V3_CTX *ctx, int ext_nid,
int crit, const char *value);
static X509_EXTENSION *v3_generic_extension(const char *ext, const char *value,
int crit, int type,
X509V3_CTX *ctx);
static char *conf_lhash_get_string(void *db, const char *section, const char *value);
static STACK_OF(CONF_VALUE) *conf_lhash_get_section(void *db, const char *section);
static X509_EXTENSION *do_ext_i2d(const X509V3_EXT_METHOD *method,
int ext_nid, int crit, void *ext_struc);
static unsigned char *generic_asn1(const char *value, X509V3_CTX *ctx,
long *ext_len);
static X509_EXTENSION *X509V3_EXT_nconf_int(CONF *conf, X509V3_CTX *ctx,
const char *section,
const char *name, const char *value)
{
int crit;
int ext_type;
X509_EXTENSION *ret;
crit = v3_check_critical(&value);
if ((ext_type = v3_check_generic(&value)))
return v3_generic_extension(name, value, crit, ext_type, ctx);
ret = do_ext_nconf(conf, ctx, OBJ_sn2nid(name), crit, value);
if (!ret) {
if (section != NULL)
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_ERROR_IN_EXTENSION,
"section=%s, name=%s, value=%s",
section, name, value);
else
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_ERROR_IN_EXTENSION,
"name=%s, value=%s", name, value);
}
return ret;
}
X509_EXTENSION *X509V3_EXT_nconf(CONF *conf, X509V3_CTX *ctx, const char *name,
const char *value)
{
return X509V3_EXT_nconf_int(conf, ctx, NULL, name, value);
}
X509_EXTENSION *X509V3_EXT_nconf_nid(CONF *conf, X509V3_CTX *ctx, int ext_nid,
const char *value)
{
int crit;
int ext_type;
crit = v3_check_critical(&value);
if ((ext_type = v3_check_generic(&value)))
return v3_generic_extension(OBJ_nid2sn(ext_nid),
value, crit, ext_type, ctx);
return do_ext_nconf(conf, ctx, ext_nid, crit, value);
}
/* CONF *conf: Config file */
/* char *value: Value */
static X509_EXTENSION *do_ext_nconf(CONF *conf, X509V3_CTX *ctx, int ext_nid,
int crit, const char *value)
{
const X509V3_EXT_METHOD *method;
X509_EXTENSION *ext;
STACK_OF(CONF_VALUE) *nval;
void *ext_struc;
if (ext_nid == NID_undef) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_UNKNOWN_EXTENSION_NAME);
return NULL;
}
if ((method = X509V3_EXT_get_nid(ext_nid)) == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_UNKNOWN_EXTENSION);
return NULL;
}
/* Now get internal extension representation based on type */
if (method->v2i) {
if (*value == '@')
nval = NCONF_get_section(conf, value + 1);
else
nval = X509V3_parse_list(value);
if (nval == NULL || sk_CONF_VALUE_num(nval) <= 0) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_INVALID_EXTENSION_STRING,
"name=%s,section=%s", OBJ_nid2sn(ext_nid), value);
if (*value != '@')
sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
return NULL;
}
ext_struc = method->v2i(method, ctx, nval);
if (*value != '@')
sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
if (!ext_struc)
return NULL;
} else if (method->s2i) {
if ((ext_struc = method->s2i(method, ctx, value)) == NULL)
return NULL;
} else if (method->r2i) {
if (!ctx->db || !ctx->db_meth) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_NO_CONFIG_DATABASE);
return NULL;
}
if ((ext_struc = method->r2i(method, ctx, value)) == NULL)
return NULL;
} else {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_EXTENSION_SETTING_NOT_SUPPORTED,
"name=%s", OBJ_nid2sn(ext_nid));
return NULL;
}
ext = do_ext_i2d(method, ext_nid, crit, ext_struc);
if (method->it)
ASN1_item_free(ext_struc, ASN1_ITEM_ptr(method->it));
else
method->ext_free(ext_struc);
return ext;
}
static X509_EXTENSION *do_ext_i2d(const X509V3_EXT_METHOD *method,
int ext_nid, int crit, void *ext_struc)
{
unsigned char *ext_der = NULL;
int ext_len;
ASN1_OCTET_STRING *ext_oct = NULL;
X509_EXTENSION *ext;
/* Convert internal representation to DER */
if (method->it) {
ext_der = NULL;
ext_len =
ASN1_item_i2d(ext_struc, &ext_der, ASN1_ITEM_ptr(method->it));
if (ext_len < 0) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
} else {
unsigned char *p;
ext_len = method->i2d(ext_struc, NULL);
if (ext_len <= 0) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
if ((ext_der = OPENSSL_malloc(ext_len)) == NULL)
goto err;
p = ext_der;
method->i2d(ext_struc, &p);
}
if ((ext_oct = ASN1_OCTET_STRING_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
ext_oct->data = ext_der;
ext_der = NULL;
ext_oct->length = ext_len;
ext = X509_EXTENSION_create_by_NID(NULL, ext_nid, crit, ext_oct);
if (!ext) {
ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB);
goto err;
}
ASN1_OCTET_STRING_free(ext_oct);
return ext;
err:
OPENSSL_free(ext_der);
ASN1_OCTET_STRING_free(ext_oct);
return NULL;
}
/* Given an internal structure, nid and critical flag create an extension */
X509_EXTENSION *X509V3_EXT_i2d(int ext_nid, int crit, void *ext_struc)
{
const X509V3_EXT_METHOD *method;
if ((method = X509V3_EXT_get_nid(ext_nid)) == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_UNKNOWN_EXTENSION);
return NULL;
}
return do_ext_i2d(method, ext_nid, crit, ext_struc);
}
/* Check the extension string for critical flag */
static int v3_check_critical(const char **value)
{
const char *p = *value;
if (!CHECK_AND_SKIP_PREFIX(p, "critical,"))
return 0;
while (ossl_isspace(*p))
p++;
*value = p;
return 1;
}
/* Check extension string for generic extension and return the type */
static int v3_check_generic(const char **value)
{
int gen_type = 0;
const char *p = *value;
if (CHECK_AND_SKIP_PREFIX(p, "DER:")) {
gen_type = 1;
} else if (CHECK_AND_SKIP_PREFIX(p, "ASN1:")) {
gen_type = 2;
} else
return 0;
while (ossl_isspace(*p))
p++;
*value = p;
return gen_type;
}
/* Create a generic extension: for now just handle DER type */
static X509_EXTENSION *v3_generic_extension(const char *ext, const char *value,
int crit, int gen_type,
X509V3_CTX *ctx)
{
unsigned char *ext_der = NULL;
long ext_len = 0;
ASN1_OBJECT *obj = NULL;
ASN1_OCTET_STRING *oct = NULL;
X509_EXTENSION *extension = NULL;
if ((obj = OBJ_txt2obj(ext, 0)) == NULL) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_EXTENSION_NAME_ERROR,
"name=%s", ext);
goto err;
}
if (gen_type == 1)
ext_der = OPENSSL_hexstr2buf(value, &ext_len);
else if (gen_type == 2)
ext_der = generic_asn1(value, ctx, &ext_len);
if (ext_der == NULL) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR,
"value=%s", value);
goto err;
}
if ((oct = ASN1_OCTET_STRING_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
oct->data = ext_der;
oct->length = ext_len;
ext_der = NULL;
extension = X509_EXTENSION_create_by_OBJ(NULL, obj, crit, oct);
err:
ASN1_OBJECT_free(obj);
ASN1_OCTET_STRING_free(oct);
OPENSSL_free(ext_der);
return extension;
}
static unsigned char *generic_asn1(const char *value, X509V3_CTX *ctx,
long *ext_len)
{
ASN1_TYPE *typ;
unsigned char *ext_der = NULL;
typ = ASN1_generate_v3(value, ctx);
if (typ == NULL)
return NULL;
*ext_len = i2d_ASN1_TYPE(typ, &ext_der);
ASN1_TYPE_free(typ);
return ext_der;
}
static void delete_ext(STACK_OF(X509_EXTENSION) *sk, X509_EXTENSION *dext)
{
int idx;
ASN1_OBJECT *obj;
obj = X509_EXTENSION_get_object(dext);
while ((idx = X509v3_get_ext_by_OBJ(sk, obj, -1)) >= 0)
X509_EXTENSION_free(X509v3_delete_ext(sk, idx));
}
/*
* This is the main function: add a bunch of extensions based on a config
* file section to an extension STACK. Just check in case sk == NULL.
* Note that on error new elements may have been added to *sk if sk != NULL.
*/
int X509V3_EXT_add_nconf_sk(CONF *conf, X509V3_CTX *ctx, const char *section,
STACK_OF(X509_EXTENSION) **sk)
{
X509_EXTENSION *ext;
STACK_OF(CONF_VALUE) *nval;
const CONF_VALUE *val;
int i, akid = -1, skid = -1;
if ((nval = NCONF_get_section(conf, section)) == NULL)
return 0;
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
val = sk_CONF_VALUE_value(nval, i);
if (strcmp(val->name, "authorityKeyIdentifier") == 0)
akid = i;
else if (strcmp(val->name, "subjectKeyIdentifier") == 0)
skid = i;
}
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
val = sk_CONF_VALUE_value(nval, i);
if (skid > akid && akid >= 0) {
/* make sure SKID is handled before AKID */
if (i == akid)
val = sk_CONF_VALUE_value(nval, skid);
else if (i == skid)
val = sk_CONF_VALUE_value(nval, akid);
}
if ((ext = X509V3_EXT_nconf_int(conf, ctx, val->section,
val->name, val->value)) == NULL)
return 0;
if (sk != NULL) {
if (ctx->flags == X509V3_CTX_REPLACE)
delete_ext(*sk, ext);
if (X509v3_add_ext(sk, ext, -1) == NULL) {
X509_EXTENSION_free(ext);
return 0;
}
}
X509_EXTENSION_free(ext);
}
return 1;
}
/*
* Add extensions to a certificate. Just check in case cert == NULL.
* Note that on error new elements may remain added to cert if cert != NULL.
*/
int X509V3_EXT_add_nconf(CONF *conf, X509V3_CTX *ctx, const char *section,
X509 *cert)
{
STACK_OF(X509_EXTENSION) **sk = NULL;
if (cert != NULL)
sk = &cert->cert_info.extensions;
return X509V3_EXT_add_nconf_sk(conf, ctx, section, sk);
}
/*
* Add extensions to a CRL. Just check in case crl == NULL.
* Note that on error new elements may remain added to crl if crl != NULL.
*/
int X509V3_EXT_CRL_add_nconf(CONF *conf, X509V3_CTX *ctx, const char *section,
X509_CRL *crl)
{
STACK_OF(X509_EXTENSION) **sk = NULL;
if (crl != NULL)
sk = &crl->crl.extensions;
return X509V3_EXT_add_nconf_sk(conf, ctx, section, sk);
}
/*
* Add extensions to certificate request. Just check in case req is NULL.
* Note that on error new elements may remain added to req if req != NULL.
*/
int X509V3_EXT_REQ_add_nconf(CONF *conf, X509V3_CTX *ctx, const char *section,
X509_REQ *req)
{
STACK_OF(X509_EXTENSION) *exts = NULL;
int ret = X509V3_EXT_add_nconf_sk(conf, ctx, section, &exts);
if (ret && req != NULL && exts != NULL)
ret = X509_REQ_add_extensions(req, exts);
sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
return ret;
}
/* Config database functions */
char *X509V3_get_string(X509V3_CTX *ctx, const char *name, const char *section)
{
if (!ctx->db || !ctx->db_meth || !ctx->db_meth->get_string) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_OPERATION_NOT_DEFINED);
return NULL;
}
if (ctx->db_meth->get_string)
return ctx->db_meth->get_string(ctx->db, name, section);
return NULL;
}
STACK_OF(CONF_VALUE) *X509V3_get_section(X509V3_CTX *ctx, const char *section)
{
if (!ctx->db || !ctx->db_meth || !ctx->db_meth->get_section) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_OPERATION_NOT_DEFINED);
return NULL;
}
if (ctx->db_meth->get_section)
return ctx->db_meth->get_section(ctx->db, section);
return NULL;
}
void X509V3_string_free(X509V3_CTX *ctx, char *str)
{
if (!str)
return;
if (ctx->db_meth->free_string)
ctx->db_meth->free_string(ctx->db, str);
}
void X509V3_section_free(X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *section)
{
if (!section)
return;
if (ctx->db_meth->free_section)
ctx->db_meth->free_section(ctx->db, section);
}
static char *nconf_get_string(void *db, const char *section, const char *value)
{
return NCONF_get_string(db, section, value);
}
static STACK_OF(CONF_VALUE) *nconf_get_section(void *db, const char *section)
{
return NCONF_get_section(db, section);
}
static X509V3_CONF_METHOD nconf_method = {
nconf_get_string,
nconf_get_section,
NULL,
NULL
};
void X509V3_set_nconf(X509V3_CTX *ctx, CONF *conf)
{
if (ctx == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_NULL_PARAMETER);
return;
}
ctx->db_meth = &nconf_method;
ctx->db = conf;
}
void X509V3_set_ctx(X509V3_CTX *ctx, X509 *issuer, X509 *subj, X509_REQ *req,
X509_CRL *crl, int flags)
{
if (ctx == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_NULL_PARAMETER);
return;
}
ctx->flags = flags;
ctx->issuer_cert = issuer;
ctx->subject_cert = subj;
ctx->subject_req = req;
ctx->crl = crl;
ctx->db_meth = NULL;
ctx->db = NULL;
ctx->issuer_pkey = NULL;
}
/* For API backward compatibility, this is separate from X509V3_set_ctx() */
int X509V3_set_issuer_pkey(X509V3_CTX *ctx, EVP_PKEY *pkey)
{
if (ctx == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (ctx->subject_cert == NULL && pkey != NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
ctx->issuer_pkey = pkey;
return 1;
}
/* Old conf compatibility functions */
X509_EXTENSION *X509V3_EXT_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
const char *name, const char *value)
{
CONF *ctmp;
X509_EXTENSION *ret;
if ((ctmp = NCONF_new(NULL)) == NULL)
return NULL;
CONF_set_nconf(ctmp, conf);
ret = X509V3_EXT_nconf(ctmp, ctx, name, value);
CONF_set_nconf(ctmp, NULL);
NCONF_free(ctmp);
return ret;
}
X509_EXTENSION *X509V3_EXT_conf_nid(LHASH_OF(CONF_VALUE) *conf,
X509V3_CTX *ctx, int ext_nid, const char *value)
{
CONF *ctmp;
X509_EXTENSION *ret;
if ((ctmp = NCONF_new(NULL)) == NULL)
return NULL;
CONF_set_nconf(ctmp, conf);
ret = X509V3_EXT_nconf_nid(ctmp, ctx, ext_nid, value);
CONF_set_nconf(ctmp, NULL);
NCONF_free(ctmp);
return ret;
}
static char *conf_lhash_get_string(void *db, const char *section, const char *value)
{
return CONF_get_string(db, section, value);
}
static STACK_OF(CONF_VALUE) *conf_lhash_get_section(void *db, const char *section)
{
return CONF_get_section(db, section);
}
static X509V3_CONF_METHOD conf_lhash_method = {
conf_lhash_get_string,
conf_lhash_get_section,
NULL,
NULL
};
void X509V3_set_conf_lhash(X509V3_CTX *ctx, LHASH_OF(CONF_VALUE) *lhash)
{
if (ctx == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_NULL_PARAMETER);
return;
}
ctx->db_meth = &conf_lhash_method;
ctx->db = lhash;
}
int X509V3_EXT_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
const char *section, X509 *cert)
{
CONF *ctmp;
int ret;
if ((ctmp = NCONF_new(NULL)) == NULL)
return 0;
CONF_set_nconf(ctmp, conf);
ret = X509V3_EXT_add_nconf(ctmp, ctx, section, cert);
CONF_set_nconf(ctmp, NULL);
NCONF_free(ctmp);
return ret;
}
/* Same as above but for a CRL */
int X509V3_EXT_CRL_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
const char *section, X509_CRL *crl)
{
CONF *ctmp;
int ret;
if ((ctmp = NCONF_new(NULL)) == NULL)
return 0;
CONF_set_nconf(ctmp, conf);
ret = X509V3_EXT_CRL_add_nconf(ctmp, ctx, section, crl);
CONF_set_nconf(ctmp, NULL);
NCONF_free(ctmp);
return ret;
}
/* Add extensions to certificate request */
int X509V3_EXT_REQ_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
const char *section, X509_REQ *req)
{
CONF *ctmp;
int ret;
if ((ctmp = NCONF_new(NULL)) == NULL)
return 0;
CONF_set_nconf(ctmp, conf);
ret = X509V3_EXT_REQ_add_nconf(ctmp, ctx, section, req);
CONF_set_nconf(ctmp, NULL);
NCONF_free(ctmp);
return ret;
}
| 18,060 | 28.951907 | 85 |
c
|
openssl
|
openssl-master/crypto/x509/v3_cpols.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
#include "x509_local.h"
#include "pcy_local.h"
#include "ext_dat.h"
/* Certificate policies extension support: this one is a bit complex... */
static int i2r_certpol(X509V3_EXT_METHOD *method, STACK_OF(POLICYINFO) *pol,
BIO *out, int indent);
static STACK_OF(POLICYINFO) *r2i_certpol(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, const char *value);
static void print_qualifiers(BIO *out, STACK_OF(POLICYQUALINFO) *quals,
int indent);
static void print_notice(BIO *out, USERNOTICE *notice, int indent);
static POLICYINFO *policy_section(X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *polstrs, int ia5org);
static POLICYQUALINFO *notice_section(X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *unot, int ia5org);
static int nref_nos(STACK_OF(ASN1_INTEGER) *nnums, STACK_OF(CONF_VALUE) *nos);
static int displaytext_str2tag(const char *tagstr, unsigned int *tag_len);
static int displaytext_get_tag_len(const char *tagstr);
const X509V3_EXT_METHOD ossl_v3_cpols = {
NID_certificate_policies, 0, ASN1_ITEM_ref(CERTIFICATEPOLICIES),
0, 0, 0, 0,
0, 0,
0, 0,
(X509V3_EXT_I2R)i2r_certpol,
(X509V3_EXT_R2I)r2i_certpol,
NULL
};
ASN1_ITEM_TEMPLATE(CERTIFICATEPOLICIES) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, CERTIFICATEPOLICIES, POLICYINFO)
ASN1_ITEM_TEMPLATE_END(CERTIFICATEPOLICIES)
IMPLEMENT_ASN1_FUNCTIONS(CERTIFICATEPOLICIES)
ASN1_SEQUENCE(POLICYINFO) = {
ASN1_SIMPLE(POLICYINFO, policyid, ASN1_OBJECT),
ASN1_SEQUENCE_OF_OPT(POLICYINFO, qualifiers, POLICYQUALINFO)
} ASN1_SEQUENCE_END(POLICYINFO)
IMPLEMENT_ASN1_FUNCTIONS(POLICYINFO)
ASN1_ADB_TEMPLATE(policydefault) = ASN1_SIMPLE(POLICYQUALINFO, d.other, ASN1_ANY);
ASN1_ADB(POLICYQUALINFO) = {
ADB_ENTRY(NID_id_qt_cps, ASN1_SIMPLE(POLICYQUALINFO, d.cpsuri, ASN1_IA5STRING)),
ADB_ENTRY(NID_id_qt_unotice, ASN1_SIMPLE(POLICYQUALINFO, d.usernotice, USERNOTICE))
} ASN1_ADB_END(POLICYQUALINFO, 0, pqualid, 0, &policydefault_tt, NULL);
ASN1_SEQUENCE(POLICYQUALINFO) = {
ASN1_SIMPLE(POLICYQUALINFO, pqualid, ASN1_OBJECT),
ASN1_ADB_OBJECT(POLICYQUALINFO)
} ASN1_SEQUENCE_END(POLICYQUALINFO)
IMPLEMENT_ASN1_FUNCTIONS(POLICYQUALINFO)
ASN1_SEQUENCE(USERNOTICE) = {
ASN1_OPT(USERNOTICE, noticeref, NOTICEREF),
ASN1_OPT(USERNOTICE, exptext, DISPLAYTEXT)
} ASN1_SEQUENCE_END(USERNOTICE)
IMPLEMENT_ASN1_FUNCTIONS(USERNOTICE)
ASN1_SEQUENCE(NOTICEREF) = {
ASN1_SIMPLE(NOTICEREF, organization, DISPLAYTEXT),
ASN1_SEQUENCE_OF(NOTICEREF, noticenos, ASN1_INTEGER)
} ASN1_SEQUENCE_END(NOTICEREF)
IMPLEMENT_ASN1_FUNCTIONS(NOTICEREF)
static STACK_OF(POLICYINFO) *r2i_certpol(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, const char *value)
{
STACK_OF(POLICYINFO) *pols;
char *pstr;
POLICYINFO *pol;
ASN1_OBJECT *pobj;
STACK_OF(CONF_VALUE) *vals = X509V3_parse_list(value);
CONF_VALUE *cnf;
const int num = sk_CONF_VALUE_num(vals);
int i, ia5org;
if (vals == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB);
return NULL;
}
pols = sk_POLICYINFO_new_reserve(NULL, num);
if (pols == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
ia5org = 0;
for (i = 0; i < num; i++) {
cnf = sk_CONF_VALUE_value(vals, i);
if (cnf->value != NULL || cnf->name == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_POLICY_IDENTIFIER);
X509V3_conf_add_error_name_value(cnf);
goto err;
}
pstr = cnf->name;
if (strcmp(pstr, "ia5org") == 0) {
ia5org = 1;
continue;
} else if (*pstr == '@') {
STACK_OF(CONF_VALUE) *polsect;
polsect = X509V3_get_section(ctx, pstr + 1);
if (polsect == NULL) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_INVALID_SECTION,
"%s", cnf->name);
goto err;
}
pol = policy_section(ctx, polsect, ia5org);
X509V3_section_free(ctx, polsect);
if (pol == NULL)
goto err;
} else {
if ((pobj = OBJ_txt2obj(cnf->name, 0)) == NULL) {
ERR_raise_data(ERR_LIB_X509V3,
X509V3_R_INVALID_OBJECT_IDENTIFIER,
"%s", cnf->name);
goto err;
}
pol = POLICYINFO_new();
if (pol == NULL) {
ASN1_OBJECT_free(pobj);
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
pol->policyid = pobj;
}
if (!sk_POLICYINFO_push(pols, pol)) {
POLICYINFO_free(pol);
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
}
sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
return pols;
err:
sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
sk_POLICYINFO_pop_free(pols, POLICYINFO_free);
return NULL;
}
static POLICYINFO *policy_section(X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *polstrs, int ia5org)
{
int i;
CONF_VALUE *cnf;
POLICYINFO *pol;
POLICYQUALINFO *qual;
if ((pol = POLICYINFO_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
for (i = 0; i < sk_CONF_VALUE_num(polstrs); i++) {
cnf = sk_CONF_VALUE_value(polstrs, i);
if (strcmp(cnf->name, "policyIdentifier") == 0) {
ASN1_OBJECT *pobj;
if ((pobj = OBJ_txt2obj(cnf->value, 0)) == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER);
X509V3_conf_err(cnf);
goto err;
}
pol->policyid = pobj;
} else if (!ossl_v3_name_cmp(cnf->name, "CPS")) {
if (pol->qualifiers == NULL)
pol->qualifiers = sk_POLICYQUALINFO_new_null();
if ((qual = POLICYQUALINFO_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
if (!sk_POLICYQUALINFO_push(pol->qualifiers, qual)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
if ((qual->pqualid = OBJ_nid2obj(NID_id_qt_cps)) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_INTERNAL_ERROR);
goto err;
}
if ((qual->d.cpsuri = ASN1_IA5STRING_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
if (!ASN1_STRING_set(qual->d.cpsuri, cnf->value,
strlen(cnf->value))) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
} else if (!ossl_v3_name_cmp(cnf->name, "userNotice")) {
STACK_OF(CONF_VALUE) *unot;
if (*cnf->value != '@') {
ERR_raise(ERR_LIB_X509V3, X509V3_R_EXPECTED_A_SECTION_NAME);
X509V3_conf_err(cnf);
goto err;
}
unot = X509V3_get_section(ctx, cnf->value + 1);
if (!unot) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_SECTION);
X509V3_conf_err(cnf);
goto err;
}
qual = notice_section(ctx, unot, ia5org);
X509V3_section_free(ctx, unot);
if (!qual)
goto err;
if (pol->qualifiers == NULL)
pol->qualifiers = sk_POLICYQUALINFO_new_null();
if (!sk_POLICYQUALINFO_push(pol->qualifiers, qual)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
} else {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_OPTION);
X509V3_conf_err(cnf);
goto err;
}
}
if (pol->policyid == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_NO_POLICY_IDENTIFIER);
goto err;
}
return pol;
err:
POLICYINFO_free(pol);
return NULL;
}
static int displaytext_get_tag_len(const char *tagstr)
{
char *colon = strchr(tagstr, ':');
return (colon == NULL) ? -1 : colon - tagstr;
}
static int displaytext_str2tag(const char *tagstr, unsigned int *tag_len)
{
int len;
*tag_len = 0;
len = displaytext_get_tag_len(tagstr);
if (len == -1)
return V_ASN1_VISIBLESTRING;
*tag_len = len;
if (len == sizeof("UTF8") - 1 && HAS_PREFIX(tagstr, "UTF8"))
return V_ASN1_UTF8STRING;
if (len == sizeof("UTF8String") - 1 && HAS_PREFIX(tagstr, "UTF8String"))
return V_ASN1_UTF8STRING;
if (len == sizeof("BMP") - 1 && HAS_PREFIX(tagstr, "BMP"))
return V_ASN1_BMPSTRING;
if (len == sizeof("BMPSTRING") - 1 && HAS_PREFIX(tagstr, "BMPSTRING"))
return V_ASN1_BMPSTRING;
if (len == sizeof("VISIBLE") - 1 && HAS_PREFIX(tagstr, "VISIBLE"))
return V_ASN1_VISIBLESTRING;
if (len == sizeof("VISIBLESTRING") - 1 && HAS_PREFIX(tagstr, "VISIBLESTRING"))
return V_ASN1_VISIBLESTRING;
*tag_len = 0;
return V_ASN1_VISIBLESTRING;
}
static POLICYQUALINFO *notice_section(X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *unot, int ia5org)
{
int i, ret, len, tag;
unsigned int tag_len;
CONF_VALUE *cnf;
USERNOTICE *not;
POLICYQUALINFO *qual;
char *value = NULL;
if ((qual = POLICYQUALINFO_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
if ((qual->pqualid = OBJ_nid2obj(NID_id_qt_unotice)) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_INTERNAL_ERROR);
goto err;
}
if ((not = USERNOTICE_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
qual->d.usernotice = not;
for (i = 0; i < sk_CONF_VALUE_num(unot); i++) {
cnf = sk_CONF_VALUE_value(unot, i);
value = cnf->value;
if (strcmp(cnf->name, "explicitText") == 0) {
tag = displaytext_str2tag(value, &tag_len);
if ((not->exptext = ASN1_STRING_type_new(tag)) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
if (tag_len != 0)
value += tag_len + 1;
len = strlen(value);
if (!ASN1_STRING_set(not->exptext, value, len)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
} else if (strcmp(cnf->name, "organization") == 0) {
NOTICEREF *nref;
if (!not->noticeref) {
if ((nref = NOTICEREF_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
not->noticeref = nref;
} else
nref = not->noticeref;
if (ia5org)
nref->organization->type = V_ASN1_IA5STRING;
else
nref->organization->type = V_ASN1_VISIBLESTRING;
if (!ASN1_STRING_set(nref->organization, cnf->value,
strlen(cnf->value))) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
} else if (strcmp(cnf->name, "noticeNumbers") == 0) {
NOTICEREF *nref;
STACK_OF(CONF_VALUE) *nos;
if (!not->noticeref) {
if ((nref = NOTICEREF_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
not->noticeref = nref;
} else
nref = not->noticeref;
nos = X509V3_parse_list(cnf->value);
if (!nos || !sk_CONF_VALUE_num(nos)) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NUMBERS);
X509V3_conf_add_error_name_value(cnf);
sk_CONF_VALUE_pop_free(nos, X509V3_conf_free);
goto err;
}
ret = nref_nos(nref->noticenos, nos);
sk_CONF_VALUE_pop_free(nos, X509V3_conf_free);
if (!ret)
goto err;
} else {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_OPTION);
X509V3_conf_add_error_name_value(cnf);
goto err;
}
}
if (not->noticeref &&
(!not->noticeref->noticenos || !not->noticeref->organization)) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_NEED_ORGANIZATION_AND_NUMBERS);
goto err;
}
return qual;
err:
POLICYQUALINFO_free(qual);
return NULL;
}
static int nref_nos(STACK_OF(ASN1_INTEGER) *nnums, STACK_OF(CONF_VALUE) *nos)
{
CONF_VALUE *cnf;
ASN1_INTEGER *aint;
int i;
for (i = 0; i < sk_CONF_VALUE_num(nos); i++) {
cnf = sk_CONF_VALUE_value(nos, i);
if ((aint = s2i_ASN1_INTEGER(NULL, cnf->name)) == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NUMBER);
return 0;
}
if (!sk_ASN1_INTEGER_push(nnums, aint)) {
ASN1_INTEGER_free(aint);
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
return 0;
}
}
return 1;
}
static int i2r_certpol(X509V3_EXT_METHOD *method, STACK_OF(POLICYINFO) *pol,
BIO *out, int indent)
{
int i;
POLICYINFO *pinfo;
/* First print out the policy OIDs */
for (i = 0; i < sk_POLICYINFO_num(pol); i++) {
if (i > 0)
BIO_puts(out, "\n");
pinfo = sk_POLICYINFO_value(pol, i);
BIO_printf(out, "%*sPolicy: ", indent, "");
i2a_ASN1_OBJECT(out, pinfo->policyid);
if (pinfo->qualifiers) {
BIO_puts(out, "\n");
print_qualifiers(out, pinfo->qualifiers, indent + 2);
}
}
return 1;
}
static void print_qualifiers(BIO *out, STACK_OF(POLICYQUALINFO) *quals,
int indent)
{
POLICYQUALINFO *qualinfo;
int i;
for (i = 0; i < sk_POLICYQUALINFO_num(quals); i++) {
if (i > 0)
BIO_puts(out, "\n");
qualinfo = sk_POLICYQUALINFO_value(quals, i);
switch (OBJ_obj2nid(qualinfo->pqualid)) {
case NID_id_qt_cps:
BIO_printf(out, "%*sCPS: %.*s", indent, "",
qualinfo->d.cpsuri->length,
qualinfo->d.cpsuri->data);
break;
case NID_id_qt_unotice:
BIO_printf(out, "%*sUser Notice:\n", indent, "");
print_notice(out, qualinfo->d.usernotice, indent + 2);
break;
default:
BIO_printf(out, "%*sUnknown Qualifier: ", indent + 2, "");
i2a_ASN1_OBJECT(out, qualinfo->pqualid);
break;
}
}
}
static void print_notice(BIO *out, USERNOTICE *notice, int indent)
{
int i;
if (notice->noticeref) {
NOTICEREF *ref;
ref = notice->noticeref;
BIO_printf(out, "%*sOrganization: %.*s\n", indent, "",
ref->organization->length,
ref->organization->data);
BIO_printf(out, "%*sNumber%s: ", indent, "",
sk_ASN1_INTEGER_num(ref->noticenos) > 1 ? "s" : "");
for (i = 0; i < sk_ASN1_INTEGER_num(ref->noticenos); i++) {
ASN1_INTEGER *num;
char *tmp;
num = sk_ASN1_INTEGER_value(ref->noticenos, i);
if (i)
BIO_puts(out, ", ");
if (num == NULL)
BIO_puts(out, "(null)");
else {
tmp = i2s_ASN1_INTEGER(NULL, num);
if (tmp == NULL)
return;
BIO_puts(out, tmp);
OPENSSL_free(tmp);
}
}
if (notice->exptext)
BIO_puts(out, "\n");
}
if (notice->exptext)
BIO_printf(out, "%*sExplicit Text: %.*s", indent, "",
notice->exptext->length,
notice->exptext->data);
}
void X509_POLICY_NODE_print(BIO *out, X509_POLICY_NODE *node, int indent)
{
const X509_POLICY_DATA *dat = node->data;
BIO_printf(out, "%*sPolicy: ", indent, "");
i2a_ASN1_OBJECT(out, dat->valid_policy);
BIO_puts(out, "\n");
BIO_printf(out, "%*s%s\n", indent + 2, "",
node_data_critical(dat) ? "Critical" : "Non Critical");
if (dat->qualifier_set) {
print_qualifiers(out, dat->qualifier_set, indent + 2);
BIO_puts(out, "\n");
}
else
BIO_printf(out, "%*sNo Qualifiers\n", indent + 2, "");
}
| 17,318 | 32.499033 | 91 |
c
|
openssl
|
openssl-master/crypto/x509/v3_crld.c
|
/*
* Copyright 1999-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
#include "crypto/x509.h"
#include "ext_dat.h"
#include "x509_local.h"
static void *v2i_crld(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval);
static int i2r_crldp(const X509V3_EXT_METHOD *method, void *pcrldp, BIO *out,
int indent);
const X509V3_EXT_METHOD ossl_v3_crld = {
NID_crl_distribution_points, 0, ASN1_ITEM_ref(CRL_DIST_POINTS),
0, 0, 0, 0,
0, 0,
0,
v2i_crld,
i2r_crldp, 0,
NULL
};
const X509V3_EXT_METHOD ossl_v3_freshest_crl = {
NID_freshest_crl, 0, ASN1_ITEM_ref(CRL_DIST_POINTS),
0, 0, 0, 0,
0, 0,
0,
v2i_crld,
i2r_crldp, 0,
NULL
};
static STACK_OF(GENERAL_NAME) *gnames_from_sectname(X509V3_CTX *ctx,
char *sect)
{
STACK_OF(CONF_VALUE) *gnsect;
STACK_OF(GENERAL_NAME) *gens;
if (*sect == '@')
gnsect = X509V3_get_section(ctx, sect + 1);
else
gnsect = X509V3_parse_list(sect);
if (!gnsect) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_SECTION_NOT_FOUND);
return NULL;
}
gens = v2i_GENERAL_NAMES(NULL, ctx, gnsect);
if (*sect == '@')
X509V3_section_free(ctx, gnsect);
else
sk_CONF_VALUE_pop_free(gnsect, X509V3_conf_free);
return gens;
}
static int set_dist_point_name(DIST_POINT_NAME **pdp, X509V3_CTX *ctx,
CONF_VALUE *cnf)
{
STACK_OF(GENERAL_NAME) *fnm = NULL;
STACK_OF(X509_NAME_ENTRY) *rnm = NULL;
if (HAS_PREFIX(cnf->name, "fullname")) {
fnm = gnames_from_sectname(ctx, cnf->value);
if (!fnm)
goto err;
} else if (strcmp(cnf->name, "relativename") == 0) {
int ret;
STACK_OF(CONF_VALUE) *dnsect;
X509_NAME *nm;
nm = X509_NAME_new();
if (nm == NULL)
return -1;
dnsect = X509V3_get_section(ctx, cnf->value);
if (!dnsect) {
X509_NAME_free(nm);
ERR_raise(ERR_LIB_X509V3, X509V3_R_SECTION_NOT_FOUND);
return -1;
}
ret = X509V3_NAME_from_section(nm, dnsect, MBSTRING_ASC);
X509V3_section_free(ctx, dnsect);
rnm = nm->entries;
nm->entries = NULL;
X509_NAME_free(nm);
if (!ret || sk_X509_NAME_ENTRY_num(rnm) <= 0)
goto err;
/*
* Since its a name fragment can't have more than one RDNSequence
*/
if (sk_X509_NAME_ENTRY_value(rnm,
sk_X509_NAME_ENTRY_num(rnm) - 1)->set) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_MULTIPLE_RDNS);
goto err;
}
} else
return 0;
if (*pdp) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_DISTPOINT_ALREADY_SET);
goto err;
}
*pdp = DIST_POINT_NAME_new();
if (*pdp == NULL)
goto err;
if (fnm) {
(*pdp)->type = 0;
(*pdp)->name.fullname = fnm;
} else {
(*pdp)->type = 1;
(*pdp)->name.relativename = rnm;
}
return 1;
err:
sk_GENERAL_NAME_pop_free(fnm, GENERAL_NAME_free);
sk_X509_NAME_ENTRY_pop_free(rnm, X509_NAME_ENTRY_free);
return -1;
}
static const BIT_STRING_BITNAME reason_flags[] = {
{0, "Unused", "unused"},
{1, "Key Compromise", "keyCompromise"},
{2, "CA Compromise", "CACompromise"},
{3, "Affiliation Changed", "affiliationChanged"},
{4, "Superseded", "superseded"},
{5, "Cessation Of Operation", "cessationOfOperation"},
{6, "Certificate Hold", "certificateHold"},
{7, "Privilege Withdrawn", "privilegeWithdrawn"},
{8, "AA Compromise", "AACompromise"},
{-1, NULL, NULL}
};
static int set_reasons(ASN1_BIT_STRING **preas, char *value)
{
STACK_OF(CONF_VALUE) *rsk = NULL;
const BIT_STRING_BITNAME *pbn;
const char *bnam;
int i, ret = 0;
rsk = X509V3_parse_list(value);
if (rsk == NULL)
return 0;
if (*preas != NULL)
goto err;
for (i = 0; i < sk_CONF_VALUE_num(rsk); i++) {
bnam = sk_CONF_VALUE_value(rsk, i)->name;
if (*preas == NULL) {
*preas = ASN1_BIT_STRING_new();
if (*preas == NULL)
goto err;
}
for (pbn = reason_flags; pbn->lname; pbn++) {
if (strcmp(pbn->sname, bnam) == 0) {
if (!ASN1_BIT_STRING_set_bit(*preas, pbn->bitnum, 1))
goto err;
break;
}
}
if (pbn->lname == NULL)
goto err;
}
ret = 1;
err:
sk_CONF_VALUE_pop_free(rsk, X509V3_conf_free);
return ret;
}
static int print_reasons(BIO *out, const char *rname,
ASN1_BIT_STRING *rflags, int indent)
{
int first = 1;
const BIT_STRING_BITNAME *pbn;
BIO_printf(out, "%*s%s:\n%*s", indent, "", rname, indent + 2, "");
for (pbn = reason_flags; pbn->lname; pbn++) {
if (ASN1_BIT_STRING_get_bit(rflags, pbn->bitnum)) {
if (first)
first = 0;
else
BIO_puts(out, ", ");
BIO_puts(out, pbn->lname);
}
}
if (first)
BIO_puts(out, "<EMPTY>\n");
else
BIO_puts(out, "\n");
return 1;
}
static DIST_POINT *crldp_from_section(X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval)
{
int i;
CONF_VALUE *cnf;
DIST_POINT *point = DIST_POINT_new();
if (point == NULL)
goto err;
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
int ret;
cnf = sk_CONF_VALUE_value(nval, i);
ret = set_dist_point_name(&point->distpoint, ctx, cnf);
if (ret > 0)
continue;
if (ret < 0)
goto err;
if (strcmp(cnf->name, "reasons") == 0) {
if (!set_reasons(&point->reasons, cnf->value))
goto err;
} else if (strcmp(cnf->name, "CRLissuer") == 0) {
point->CRLissuer = gnames_from_sectname(ctx, cnf->value);
if (point->CRLissuer == NULL)
goto err;
}
}
return point;
err:
DIST_POINT_free(point);
return NULL;
}
static void *v2i_crld(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval)
{
STACK_OF(DIST_POINT) *crld;
GENERAL_NAMES *gens = NULL;
GENERAL_NAME *gen = NULL;
CONF_VALUE *cnf;
const int num = sk_CONF_VALUE_num(nval);
int i;
crld = sk_DIST_POINT_new_reserve(NULL, num);
if (crld == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
for (i = 0; i < num; i++) {
DIST_POINT *point;
cnf = sk_CONF_VALUE_value(nval, i);
if (cnf->value == NULL) {
STACK_OF(CONF_VALUE) *dpsect;
dpsect = X509V3_get_section(ctx, cnf->name);
if (!dpsect)
goto err;
point = crldp_from_section(ctx, dpsect);
X509V3_section_free(ctx, dpsect);
if (point == NULL)
goto err;
sk_DIST_POINT_push(crld, point); /* no failure as it was reserved */
} else {
if ((gen = v2i_GENERAL_NAME(method, ctx, cnf)) == NULL)
goto err;
if ((gens = GENERAL_NAMES_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
if (!sk_GENERAL_NAME_push(gens, gen)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
gen = NULL;
if ((point = DIST_POINT_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
sk_DIST_POINT_push(crld, point); /* no failure as it was reserved */
if ((point->distpoint = DIST_POINT_NAME_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
point->distpoint->name.fullname = gens;
point->distpoint->type = 0;
gens = NULL;
}
}
return crld;
err:
GENERAL_NAME_free(gen);
GENERAL_NAMES_free(gens);
sk_DIST_POINT_pop_free(crld, DIST_POINT_free);
return NULL;
}
static int dpn_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
void *exarg)
{
DIST_POINT_NAME *dpn = (DIST_POINT_NAME *)*pval;
switch (operation) {
case ASN1_OP_NEW_POST:
dpn->dpname = NULL;
break;
case ASN1_OP_FREE_POST:
X509_NAME_free(dpn->dpname);
break;
}
return 1;
}
ASN1_CHOICE_cb(DIST_POINT_NAME, dpn_cb) = {
ASN1_IMP_SEQUENCE_OF(DIST_POINT_NAME, name.fullname, GENERAL_NAME, 0),
ASN1_IMP_SET_OF(DIST_POINT_NAME, name.relativename, X509_NAME_ENTRY, 1)
} ASN1_CHOICE_END_cb(DIST_POINT_NAME, DIST_POINT_NAME, type)
IMPLEMENT_ASN1_FUNCTIONS(DIST_POINT_NAME)
ASN1_SEQUENCE(DIST_POINT) = {
ASN1_EXP_OPT(DIST_POINT, distpoint, DIST_POINT_NAME, 0),
ASN1_IMP_OPT(DIST_POINT, reasons, ASN1_BIT_STRING, 1),
ASN1_IMP_SEQUENCE_OF_OPT(DIST_POINT, CRLissuer, GENERAL_NAME, 2)
} ASN1_SEQUENCE_END(DIST_POINT)
IMPLEMENT_ASN1_FUNCTIONS(DIST_POINT)
ASN1_ITEM_TEMPLATE(CRL_DIST_POINTS) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, CRLDistributionPoints, DIST_POINT)
ASN1_ITEM_TEMPLATE_END(CRL_DIST_POINTS)
IMPLEMENT_ASN1_FUNCTIONS(CRL_DIST_POINTS)
ASN1_SEQUENCE(ISSUING_DIST_POINT) = {
ASN1_EXP_OPT(ISSUING_DIST_POINT, distpoint, DIST_POINT_NAME, 0),
ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyuser, ASN1_FBOOLEAN, 1),
ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyCA, ASN1_FBOOLEAN, 2),
ASN1_IMP_OPT(ISSUING_DIST_POINT, onlysomereasons, ASN1_BIT_STRING, 3),
ASN1_IMP_OPT(ISSUING_DIST_POINT, indirectCRL, ASN1_FBOOLEAN, 4),
ASN1_IMP_OPT(ISSUING_DIST_POINT, onlyattr, ASN1_FBOOLEAN, 5)
} ASN1_SEQUENCE_END(ISSUING_DIST_POINT)
IMPLEMENT_ASN1_FUNCTIONS(ISSUING_DIST_POINT)
static int i2r_idp(const X509V3_EXT_METHOD *method, void *pidp, BIO *out,
int indent);
static void *v2i_idp(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval);
const X509V3_EXT_METHOD ossl_v3_idp = {
NID_issuing_distribution_point, X509V3_EXT_MULTILINE,
ASN1_ITEM_ref(ISSUING_DIST_POINT),
0, 0, 0, 0,
0, 0,
0,
v2i_idp,
i2r_idp, 0,
NULL
};
static void *v2i_idp(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval)
{
ISSUING_DIST_POINT *idp = NULL;
CONF_VALUE *cnf;
char *name, *val;
int i, ret;
idp = ISSUING_DIST_POINT_new();
if (idp == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
cnf = sk_CONF_VALUE_value(nval, i);
name = cnf->name;
val = cnf->value;
ret = set_dist_point_name(&idp->distpoint, ctx, cnf);
if (ret > 0)
continue;
if (ret < 0)
goto err;
if (strcmp(name, "onlyuser") == 0) {
if (!X509V3_get_value_bool(cnf, &idp->onlyuser))
goto err;
} else if (strcmp(name, "onlyCA") == 0) {
if (!X509V3_get_value_bool(cnf, &idp->onlyCA))
goto err;
} else if (strcmp(name, "onlyAA") == 0) {
if (!X509V3_get_value_bool(cnf, &idp->onlyattr))
goto err;
} else if (strcmp(name, "indirectCRL") == 0) {
if (!X509V3_get_value_bool(cnf, &idp->indirectCRL))
goto err;
} else if (strcmp(name, "onlysomereasons") == 0) {
if (!set_reasons(&idp->onlysomereasons, val))
goto err;
} else {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NAME);
X509V3_conf_add_error_name_value(cnf);
goto err;
}
}
return idp;
err:
ISSUING_DIST_POINT_free(idp);
return NULL;
}
static int print_gens(BIO *out, STACK_OF(GENERAL_NAME) *gens, int indent)
{
int i;
for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
if (i > 0)
BIO_puts(out, "\n");
BIO_printf(out, "%*s", indent + 2, "");
GENERAL_NAME_print(out, sk_GENERAL_NAME_value(gens, i));
}
return 1;
}
static int print_distpoint(BIO *out, DIST_POINT_NAME *dpn, int indent)
{
if (dpn->type == 0) {
BIO_printf(out, "%*sFull Name:\n", indent, "");
print_gens(out, dpn->name.fullname, indent);
} else {
X509_NAME ntmp;
ntmp.entries = dpn->name.relativename;
BIO_printf(out, "%*sRelative Name:\n%*s", indent, "", indent + 2, "");
X509_NAME_print_ex(out, &ntmp, 0, XN_FLAG_ONELINE);
BIO_puts(out, "\n");
}
return 1;
}
static int i2r_idp(const X509V3_EXT_METHOD *method, void *pidp, BIO *out,
int indent)
{
ISSUING_DIST_POINT *idp = pidp;
if (idp->distpoint)
print_distpoint(out, idp->distpoint, indent);
if (idp->onlyuser > 0)
BIO_printf(out, "%*sOnly User Certificates\n", indent, "");
if (idp->onlyCA > 0)
BIO_printf(out, "%*sOnly CA Certificates\n", indent, "");
if (idp->indirectCRL > 0)
BIO_printf(out, "%*sIndirect CRL\n", indent, "");
if (idp->onlysomereasons)
print_reasons(out, "Only Some Reasons", idp->onlysomereasons, indent);
if (idp->onlyattr > 0)
BIO_printf(out, "%*sOnly Attribute Certificates\n", indent, "");
if (!idp->distpoint && (idp->onlyuser <= 0) && (idp->onlyCA <= 0)
&& (idp->indirectCRL <= 0) && !idp->onlysomereasons
&& (idp->onlyattr <= 0))
BIO_printf(out, "%*s<EMPTY>\n", indent, "");
return 1;
}
static int i2r_crldp(const X509V3_EXT_METHOD *method, void *pcrldp, BIO *out,
int indent)
{
STACK_OF(DIST_POINT) *crld = pcrldp;
DIST_POINT *point;
int i;
for (i = 0; i < sk_DIST_POINT_num(crld); i++) {
if (i > 0)
BIO_puts(out, "\n");
point = sk_DIST_POINT_value(crld, i);
if (point->distpoint)
print_distpoint(out, point->distpoint, indent);
if (point->reasons)
print_reasons(out, "Reasons", point->reasons, indent);
if (point->CRLissuer) {
BIO_printf(out, "%*sCRL Issuer:\n", indent, "");
print_gens(out, point->CRLissuer, indent);
}
}
return 1;
}
/* Append any nameRelativeToCRLIssuer in dpn to iname, set in dpn->dpname */
int DIST_POINT_set_dpname(DIST_POINT_NAME *dpn, const X509_NAME *iname)
{
int i;
STACK_OF(X509_NAME_ENTRY) *frag;
X509_NAME_ENTRY *ne;
if (dpn == NULL || dpn->type != 1)
return 1;
frag = dpn->name.relativename;
X509_NAME_free(dpn->dpname); /* just in case it was already set */
dpn->dpname = X509_NAME_dup(iname);
if (dpn->dpname == NULL)
return 0;
for (i = 0; i < sk_X509_NAME_ENTRY_num(frag); i++) {
ne = sk_X509_NAME_ENTRY_value(frag, i);
if (!X509_NAME_add_entry(dpn->dpname, ne, -1, i ? 0 : 1))
goto err;
}
/* generate cached encoding of name */
if (i2d_X509_NAME(dpn->dpname, NULL) >= 0)
return 1;
err:
X509_NAME_free(dpn->dpname);
dpn->dpname = NULL;
return 0;
}
| 15,838 | 29.636364 | 90 |
c
|
openssl
|
openssl-master/crypto/x509/v3_enum.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/x509v3.h>
#include "ext_dat.h"
static ENUMERATED_NAMES crl_reasons[] = {
{CRL_REASON_UNSPECIFIED, "Unspecified", "unspecified"},
{CRL_REASON_KEY_COMPROMISE, "Key Compromise", "keyCompromise"},
{CRL_REASON_CA_COMPROMISE, "CA Compromise", "CACompromise"},
{CRL_REASON_AFFILIATION_CHANGED, "Affiliation Changed",
"affiliationChanged"},
{CRL_REASON_SUPERSEDED, "Superseded", "superseded"},
{CRL_REASON_CESSATION_OF_OPERATION,
"Cessation Of Operation", "cessationOfOperation"},
{CRL_REASON_CERTIFICATE_HOLD, "Certificate Hold", "certificateHold"},
{CRL_REASON_REMOVE_FROM_CRL, "Remove From CRL", "removeFromCRL"},
{CRL_REASON_PRIVILEGE_WITHDRAWN, "Privilege Withdrawn",
"privilegeWithdrawn"},
{CRL_REASON_AA_COMPROMISE, "AA Compromise", "AACompromise"},
{-1, NULL, NULL}
};
const X509V3_EXT_METHOD ossl_v3_crl_reason = {
NID_crl_reason, 0, ASN1_ITEM_ref(ASN1_ENUMERATED),
0, 0, 0, 0,
(X509V3_EXT_I2S)i2s_ASN1_ENUMERATED_TABLE,
0,
0, 0, 0, 0,
crl_reasons
};
char *i2s_ASN1_ENUMERATED_TABLE(X509V3_EXT_METHOD *method,
const ASN1_ENUMERATED *e)
{
ENUMERATED_NAMES *enam;
long strval;
strval = ASN1_ENUMERATED_get(e);
for (enam = method->usr_data; enam->lname; enam++) {
if (strval == enam->bitnum)
return OPENSSL_strdup(enam->lname);
}
return i2s_ASN1_ENUMERATED(method, e);
}
| 1,837 | 33.037037 | 74 |
c
|
openssl
|
openssl-master/crypto/x509/v3_extku.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
static void *v2i_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval);
static STACK_OF(CONF_VALUE) *i2v_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD
*method, void *eku, STACK_OF(CONF_VALUE)
*extlist);
const X509V3_EXT_METHOD ossl_v3_ext_ku = {
NID_ext_key_usage, 0,
ASN1_ITEM_ref(EXTENDED_KEY_USAGE),
0, 0, 0, 0,
0, 0,
i2v_EXTENDED_KEY_USAGE,
v2i_EXTENDED_KEY_USAGE,
0, 0,
NULL
};
/* NB OCSP acceptable responses also is a SEQUENCE OF OBJECT */
const X509V3_EXT_METHOD ossl_v3_ocsp_accresp = {
NID_id_pkix_OCSP_acceptableResponses, 0,
ASN1_ITEM_ref(EXTENDED_KEY_USAGE),
0, 0, 0, 0,
0, 0,
i2v_EXTENDED_KEY_USAGE,
v2i_EXTENDED_KEY_USAGE,
0, 0,
NULL
};
ASN1_ITEM_TEMPLATE(EXTENDED_KEY_USAGE) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, EXTENDED_KEY_USAGE, ASN1_OBJECT)
ASN1_ITEM_TEMPLATE_END(EXTENDED_KEY_USAGE)
IMPLEMENT_ASN1_FUNCTIONS(EXTENDED_KEY_USAGE)
static STACK_OF(CONF_VALUE) *i2v_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD
*method, void *a, STACK_OF(CONF_VALUE)
*ext_list)
{
EXTENDED_KEY_USAGE *eku = a;
int i;
ASN1_OBJECT *obj;
char obj_tmp[80];
for (i = 0; i < sk_ASN1_OBJECT_num(eku); i++) {
obj = sk_ASN1_OBJECT_value(eku, i);
i2t_ASN1_OBJECT(obj_tmp, 80, obj);
X509V3_add_value(NULL, obj_tmp, &ext_list);
}
return ext_list;
}
static void *v2i_EXTENDED_KEY_USAGE(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval)
{
EXTENDED_KEY_USAGE *extku;
char *extval;
ASN1_OBJECT *objtmp;
CONF_VALUE *val;
const int num = sk_CONF_VALUE_num(nval);
int i;
extku = sk_ASN1_OBJECT_new_reserve(NULL, num);
if (extku == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
sk_ASN1_OBJECT_free(extku);
return NULL;
}
for (i = 0; i < num; i++) {
val = sk_CONF_VALUE_value(nval, i);
if (val->value)
extval = val->value;
else
extval = val->name;
if ((objtmp = OBJ_txt2obj(extval, 0)) == NULL) {
sk_ASN1_OBJECT_pop_free(extku, ASN1_OBJECT_free);
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER,
"%s", extval);
return NULL;
}
sk_ASN1_OBJECT_push(extku, objtmp); /* no failure as it was reserved */
}
return extku;
}
| 3,279 | 30.84466 | 92 |
c
|
openssl
|
openssl-master/crypto/x509/v3_genn.c
|
/*
* Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
ASN1_SEQUENCE(OTHERNAME) = {
ASN1_SIMPLE(OTHERNAME, type_id, ASN1_OBJECT),
/* Maybe have a true ANY DEFINED BY later */
ASN1_EXP(OTHERNAME, value, ASN1_ANY, 0)
} ASN1_SEQUENCE_END(OTHERNAME)
IMPLEMENT_ASN1_FUNCTIONS(OTHERNAME)
ASN1_SEQUENCE(EDIPARTYNAME) = {
/* DirectoryString is a CHOICE type so use explicit tagging */
ASN1_EXP_OPT(EDIPARTYNAME, nameAssigner, DIRECTORYSTRING, 0),
ASN1_EXP(EDIPARTYNAME, partyName, DIRECTORYSTRING, 1)
} ASN1_SEQUENCE_END(EDIPARTYNAME)
IMPLEMENT_ASN1_FUNCTIONS(EDIPARTYNAME)
ASN1_CHOICE(GENERAL_NAME) = {
ASN1_IMP(GENERAL_NAME, d.otherName, OTHERNAME, GEN_OTHERNAME),
ASN1_IMP(GENERAL_NAME, d.rfc822Name, ASN1_IA5STRING, GEN_EMAIL),
ASN1_IMP(GENERAL_NAME, d.dNSName, ASN1_IA5STRING, GEN_DNS),
/* Don't decode this */
ASN1_IMP(GENERAL_NAME, d.x400Address, ASN1_SEQUENCE, GEN_X400),
/* X509_NAME is a CHOICE type so use EXPLICIT */
ASN1_EXP(GENERAL_NAME, d.directoryName, X509_NAME, GEN_DIRNAME),
ASN1_IMP(GENERAL_NAME, d.ediPartyName, EDIPARTYNAME, GEN_EDIPARTY),
ASN1_IMP(GENERAL_NAME, d.uniformResourceIdentifier, ASN1_IA5STRING, GEN_URI),
ASN1_IMP(GENERAL_NAME, d.iPAddress, ASN1_OCTET_STRING, GEN_IPADD),
ASN1_IMP(GENERAL_NAME, d.registeredID, ASN1_OBJECT, GEN_RID)
} ASN1_CHOICE_END(GENERAL_NAME)
IMPLEMENT_ASN1_FUNCTIONS(GENERAL_NAME)
ASN1_ITEM_TEMPLATE(GENERAL_NAMES) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, GeneralNames, GENERAL_NAME)
ASN1_ITEM_TEMPLATE_END(GENERAL_NAMES)
IMPLEMENT_ASN1_FUNCTIONS(GENERAL_NAMES)
GENERAL_NAME *GENERAL_NAME_dup(const GENERAL_NAME *a)
{
return (GENERAL_NAME *)ASN1_dup((i2d_of_void *)i2d_GENERAL_NAME,
(d2i_of_void *)d2i_GENERAL_NAME,
(char *)a);
}
static int edipartyname_cmp(const EDIPARTYNAME *a, const EDIPARTYNAME *b)
{
int res;
if (a == NULL || b == NULL) {
/*
* Shouldn't be possible in a valid GENERAL_NAME, but we handle it
* anyway. OTHERNAME_cmp treats NULL != NULL so we do the same here
*/
return -1;
}
if (a->nameAssigner == NULL && b->nameAssigner != NULL)
return -1;
if (a->nameAssigner != NULL && b->nameAssigner == NULL)
return 1;
/* If we get here then both have nameAssigner set, or both unset */
if (a->nameAssigner != NULL) {
res = ASN1_STRING_cmp(a->nameAssigner, b->nameAssigner);
if (res != 0)
return res;
}
/*
* partyName is required, so these should never be NULL. We treat it in
* the same way as the a == NULL || b == NULL case above
*/
if (a->partyName == NULL || b->partyName == NULL)
return -1;
return ASN1_STRING_cmp(a->partyName, b->partyName);
}
/* Returns 0 if they are equal, != 0 otherwise. */
int GENERAL_NAME_cmp(GENERAL_NAME *a, GENERAL_NAME *b)
{
int result = -1;
if (!a || !b || a->type != b->type)
return -1;
switch (a->type) {
case GEN_X400:
result = ASN1_STRING_cmp(a->d.x400Address, b->d.x400Address);
break;
case GEN_EDIPARTY:
result = edipartyname_cmp(a->d.ediPartyName, b->d.ediPartyName);
break;
case GEN_OTHERNAME:
result = OTHERNAME_cmp(a->d.otherName, b->d.otherName);
break;
case GEN_EMAIL:
case GEN_DNS:
case GEN_URI:
result = ASN1_STRING_cmp(a->d.ia5, b->d.ia5);
break;
case GEN_DIRNAME:
result = X509_NAME_cmp(a->d.dirn, b->d.dirn);
break;
case GEN_IPADD:
result = ASN1_OCTET_STRING_cmp(a->d.ip, b->d.ip);
break;
case GEN_RID:
result = OBJ_cmp(a->d.rid, b->d.rid);
break;
}
return result;
}
/* Returns 0 if they are equal, != 0 otherwise. */
int OTHERNAME_cmp(OTHERNAME *a, OTHERNAME *b)
{
int result = -1;
if (!a || !b)
return -1;
/* Check their type first. */
if ((result = OBJ_cmp(a->type_id, b->type_id)) != 0)
return result;
/* Check the value. */
result = ASN1_TYPE_cmp(a->value, b->value);
return result;
}
void GENERAL_NAME_set0_value(GENERAL_NAME *a, int type, void *value)
{
switch (type) {
case GEN_X400:
a->d.x400Address = value;
break;
case GEN_EDIPARTY:
a->d.ediPartyName = value;
break;
case GEN_OTHERNAME:
a->d.otherName = value;
break;
case GEN_EMAIL:
case GEN_DNS:
case GEN_URI:
a->d.ia5 = value;
break;
case GEN_DIRNAME:
a->d.dirn = value;
break;
case GEN_IPADD:
a->d.ip = value;
break;
case GEN_RID:
a->d.rid = value;
break;
}
a->type = type;
}
void *GENERAL_NAME_get0_value(const GENERAL_NAME *a, int *ptype)
{
if (ptype)
*ptype = a->type;
switch (a->type) {
case GEN_X400:
return a->d.x400Address;
case GEN_EDIPARTY:
return a->d.ediPartyName;
case GEN_OTHERNAME:
return a->d.otherName;
case GEN_EMAIL:
case GEN_DNS:
case GEN_URI:
return a->d.ia5;
case GEN_DIRNAME:
return a->d.dirn;
case GEN_IPADD:
return a->d.ip;
case GEN_RID:
return a->d.rid;
default:
return NULL;
}
}
int GENERAL_NAME_set0_othername(GENERAL_NAME *gen,
ASN1_OBJECT *oid, ASN1_TYPE *value)
{
OTHERNAME *oth;
oth = OTHERNAME_new();
if (oth == NULL)
return 0;
ASN1_TYPE_free(oth->value);
oth->type_id = oid;
oth->value = value;
GENERAL_NAME_set0_value(gen, GEN_OTHERNAME, oth);
return 1;
}
int GENERAL_NAME_get0_otherName(const GENERAL_NAME *gen,
ASN1_OBJECT **poid, ASN1_TYPE **pvalue)
{
if (gen->type != GEN_OTHERNAME)
return 0;
if (poid)
*poid = gen->d.otherName->type_id;
if (pvalue)
*pvalue = gen->d.otherName->value;
return 1;
}
| 6,496 | 25.847107 | 85 |
c
|
openssl
|
openssl-master/crypto/x509/v3_ia5.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
const X509V3_EXT_METHOD ossl_v3_ns_ia5_list[8] = {
EXT_IA5STRING(NID_netscape_base_url),
EXT_IA5STRING(NID_netscape_revocation_url),
EXT_IA5STRING(NID_netscape_ca_revocation_url),
EXT_IA5STRING(NID_netscape_renewal_url),
EXT_IA5STRING(NID_netscape_ca_policy_url),
EXT_IA5STRING(NID_netscape_ssl_server_name),
EXT_IA5STRING(NID_netscape_comment),
EXT_END
};
char *i2s_ASN1_IA5STRING(X509V3_EXT_METHOD *method, ASN1_IA5STRING *ia5)
{
char *tmp;
if (ia5 == NULL || ia5->length <= 0)
return NULL;
if ((tmp = OPENSSL_malloc(ia5->length + 1)) == NULL)
return NULL;
memcpy(tmp, ia5->data, ia5->length);
tmp[ia5->length] = 0;
return tmp;
}
ASN1_IA5STRING *s2i_ASN1_IA5STRING(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, const char *str)
{
ASN1_IA5STRING *ia5;
if (str == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NULL_ARGUMENT);
return NULL;
}
if ((ia5 = ASN1_IA5STRING_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
return NULL;
}
if (!ASN1_STRING_set((ASN1_STRING *)ia5, str, strlen(str))) {
ASN1_IA5STRING_free(ia5);
return NULL;
}
#ifdef CHARSET_EBCDIC
ebcdic2ascii(ia5->data, ia5->data, ia5->length);
#endif /* CHARSET_EBCDIC */
return ia5;
}
| 1,870 | 29.177419 | 74 |
c
|
openssl
|
openssl-master/crypto/x509/v3_info.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD
*method, AUTHORITY_INFO_ACCESS
*ainfo, STACK_OF(CONF_VALUE)
*ret);
static AUTHORITY_INFO_ACCESS *v2i_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD
*method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE)
*nval);
const X509V3_EXT_METHOD ossl_v3_info = { NID_info_access, X509V3_EXT_MULTILINE,
ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_AUTHORITY_INFO_ACCESS,
(X509V3_EXT_V2I)v2i_AUTHORITY_INFO_ACCESS,
0, 0,
NULL
};
const X509V3_EXT_METHOD ossl_v3_sinfo = { NID_sinfo_access, X509V3_EXT_MULTILINE,
ASN1_ITEM_ref(AUTHORITY_INFO_ACCESS),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_AUTHORITY_INFO_ACCESS,
(X509V3_EXT_V2I)v2i_AUTHORITY_INFO_ACCESS,
0, 0,
NULL
};
ASN1_SEQUENCE(ACCESS_DESCRIPTION) = {
ASN1_SIMPLE(ACCESS_DESCRIPTION, method, ASN1_OBJECT),
ASN1_SIMPLE(ACCESS_DESCRIPTION, location, GENERAL_NAME)
} ASN1_SEQUENCE_END(ACCESS_DESCRIPTION)
IMPLEMENT_ASN1_FUNCTIONS(ACCESS_DESCRIPTION)
ASN1_ITEM_TEMPLATE(AUTHORITY_INFO_ACCESS) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, GeneralNames, ACCESS_DESCRIPTION)
ASN1_ITEM_TEMPLATE_END(AUTHORITY_INFO_ACCESS)
IMPLEMENT_ASN1_FUNCTIONS(AUTHORITY_INFO_ACCESS)
static STACK_OF(CONF_VALUE) *i2v_AUTHORITY_INFO_ACCESS(
X509V3_EXT_METHOD *method, AUTHORITY_INFO_ACCESS *ainfo,
STACK_OF(CONF_VALUE) *ret)
{
ACCESS_DESCRIPTION *desc;
int i, nlen;
char objtmp[80], *ntmp;
CONF_VALUE *vtmp;
STACK_OF(CONF_VALUE) *tret = ret;
for (i = 0; i < sk_ACCESS_DESCRIPTION_num(ainfo); i++) {
STACK_OF(CONF_VALUE) *tmp;
desc = sk_ACCESS_DESCRIPTION_value(ainfo, i);
tmp = i2v_GENERAL_NAME(method, desc->location, tret);
if (tmp == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
tret = tmp;
vtmp = sk_CONF_VALUE_value(tret, i);
i2t_ASN1_OBJECT(objtmp, sizeof(objtmp), desc->method);
nlen = strlen(objtmp) + 3 + strlen(vtmp->name) + 1;
ntmp = OPENSSL_malloc(nlen);
if (ntmp == NULL)
goto err;
BIO_snprintf(ntmp, nlen, "%s - %s", objtmp, vtmp->name);
OPENSSL_free(vtmp->name);
vtmp->name = ntmp;
}
if (ret == NULL && tret == NULL)
return sk_CONF_VALUE_new_null();
return tret;
err:
if (ret == NULL && tret != NULL)
sk_CONF_VALUE_pop_free(tret, X509V3_conf_free);
return NULL;
}
static AUTHORITY_INFO_ACCESS *v2i_AUTHORITY_INFO_ACCESS(X509V3_EXT_METHOD
*method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE)
*nval)
{
AUTHORITY_INFO_ACCESS *ainfo = NULL;
CONF_VALUE *cnf, ctmp;
ACCESS_DESCRIPTION *acc;
int i;
const int num = sk_CONF_VALUE_num(nval);
char *objtmp, *ptmp;
if ((ainfo = sk_ACCESS_DESCRIPTION_new_reserve(NULL, num)) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
return NULL;
}
for (i = 0; i < num; i++) {
cnf = sk_CONF_VALUE_value(nval, i);
if ((acc = ACCESS_DESCRIPTION_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
sk_ACCESS_DESCRIPTION_push(ainfo, acc); /* Cannot fail due to reserve */
ptmp = strchr(cnf->name, ';');
if (ptmp == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_SYNTAX);
goto err;
}
ctmp.name = ptmp + 1;
ctmp.value = cnf->value;
if (!v2i_GENERAL_NAME_ex(acc->location, method, ctx, &ctmp, 0))
goto err;
if ((objtmp = OPENSSL_strndup(cnf->name, ptmp - cnf->name)) == NULL)
goto err;
acc->method = OBJ_txt2obj(objtmp, 0);
if (!acc->method) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_BAD_OBJECT,
"value=%s", objtmp);
OPENSSL_free(objtmp);
goto err;
}
OPENSSL_free(objtmp);
}
return ainfo;
err:
sk_ACCESS_DESCRIPTION_pop_free(ainfo, ACCESS_DESCRIPTION_free);
return NULL;
}
int i2a_ACCESS_DESCRIPTION(BIO *bp, const ACCESS_DESCRIPTION *a)
{
i2a_ASN1_OBJECT(bp, a->method);
return 2;
}
| 5,348 | 33.288462 | 89 |
c
|
openssl
|
openssl-master/crypto/x509/v3_int.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/x509v3.h>
#include "ext_dat.h"
const X509V3_EXT_METHOD ossl_v3_crl_num = {
NID_crl_number, 0, ASN1_ITEM_ref(ASN1_INTEGER),
0, 0, 0, 0,
(X509V3_EXT_I2S)i2s_ASN1_INTEGER,
0,
0, 0, 0, 0, NULL
};
const X509V3_EXT_METHOD ossl_v3_delta_crl = {
NID_delta_crl, 0, ASN1_ITEM_ref(ASN1_INTEGER),
0, 0, 0, 0,
(X509V3_EXT_I2S)i2s_ASN1_INTEGER,
0,
0, 0, 0, 0, NULL
};
static void *s2i_asn1_int(X509V3_EXT_METHOD *meth, X509V3_CTX *ctx,
const char *value)
{
return s2i_ASN1_INTEGER(meth, value);
}
const X509V3_EXT_METHOD ossl_v3_inhibit_anyp = {
NID_inhibit_any_policy, 0, ASN1_ITEM_ref(ASN1_INTEGER),
0, 0, 0, 0,
(X509V3_EXT_I2S)i2s_ASN1_INTEGER,
(X509V3_EXT_S2I)s2i_asn1_int,
0, 0, 0, 0, NULL
};
| 1,183 | 25.909091 | 74 |
c
|
openssl
|
openssl-master/crypto/x509/v3_ist.c
|
/*
* Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
/*
* Issuer Sign Tool (1.2.643.100.112) The name of the tool used to signs the subject (ASN1_SEQUENCE)
* This extension is required to obtain the status of a qualified certificate at Russian Federation.
* RFC-style description is available here: https://tools.ietf.org/html/draft-deremin-rfc4491-bis-04#section-5
* Russian Federal Law 63 "Digital Sign" is available here: http://www.consultant.ru/document/cons_doc_LAW_112701/
*/
ASN1_SEQUENCE(ISSUER_SIGN_TOOL) = {
ASN1_SIMPLE(ISSUER_SIGN_TOOL, signTool, ASN1_UTF8STRING),
ASN1_SIMPLE(ISSUER_SIGN_TOOL, cATool, ASN1_UTF8STRING),
ASN1_SIMPLE(ISSUER_SIGN_TOOL, signToolCert, ASN1_UTF8STRING),
ASN1_SIMPLE(ISSUER_SIGN_TOOL, cAToolCert, ASN1_UTF8STRING)
} ASN1_SEQUENCE_END(ISSUER_SIGN_TOOL)
IMPLEMENT_ASN1_FUNCTIONS(ISSUER_SIGN_TOOL)
static ISSUER_SIGN_TOOL *v2i_issuer_sign_tool(X509V3_EXT_METHOD *method, X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval)
{
ISSUER_SIGN_TOOL *ist = ISSUER_SIGN_TOOL_new();
int i;
if (ist == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(nval); ++i) {
CONF_VALUE *cnf = sk_CONF_VALUE_value(nval, i);
if (cnf == NULL) {
continue;
}
if (strcmp(cnf->name, "signTool") == 0) {
ist->signTool = ASN1_UTF8STRING_new();
if (ist->signTool == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
ISSUER_SIGN_TOOL_free(ist);
return NULL;
}
ASN1_STRING_set(ist->signTool, cnf->value, strlen(cnf->value));
} else if (strcmp(cnf->name, "cATool") == 0) {
ist->cATool = ASN1_UTF8STRING_new();
if (ist->cATool == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
ISSUER_SIGN_TOOL_free(ist);
return NULL;
}
ASN1_STRING_set(ist->cATool, cnf->value, strlen(cnf->value));
} else if (strcmp(cnf->name, "signToolCert") == 0) {
ist->signToolCert = ASN1_UTF8STRING_new();
if (ist->signToolCert == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
ISSUER_SIGN_TOOL_free(ist);
return NULL;
}
ASN1_STRING_set(ist->signToolCert, cnf->value, strlen(cnf->value));
} else if (strcmp(cnf->name, "cAToolCert") == 0) {
ist->cAToolCert = ASN1_UTF8STRING_new();
if (ist->cAToolCert == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
ISSUER_SIGN_TOOL_free(ist);
return NULL;
}
ASN1_STRING_set(ist->cAToolCert, cnf->value, strlen(cnf->value));
} else {
ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_INVALID_ARGUMENT);
ISSUER_SIGN_TOOL_free(ist);
return NULL;
}
}
return ist;
}
static int i2r_issuer_sign_tool(X509V3_EXT_METHOD *method,
ISSUER_SIGN_TOOL *ist, BIO *out,
int indent)
{
int new_line = 0;
if (ist == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
if (ist->signTool != NULL) {
if (new_line == 1) {
BIO_write(out, "\n", 1);
}
BIO_printf(out, "%*ssignTool : ", indent, "");
BIO_write(out, ist->signTool->data, ist->signTool->length);
new_line = 1;
}
if (ist->cATool != NULL) {
if (new_line == 1) {
BIO_write(out, "\n", 1);
}
BIO_printf(out, "%*scATool : ", indent, "");
BIO_write(out, ist->cATool->data, ist->cATool->length);
new_line = 1;
}
if (ist->signToolCert != NULL) {
if (new_line == 1) {
BIO_write(out, "\n", 1);
}
BIO_printf(out, "%*ssignToolCert: ", indent, "");
BIO_write(out, ist->signToolCert->data, ist->signToolCert->length);
new_line = 1;
}
if (ist->cAToolCert != NULL) {
if (new_line == 1) {
BIO_write(out, "\n", 1);
}
BIO_printf(out, "%*scAToolCert : ", indent, "");
BIO_write(out, ist->cAToolCert->data, ist->cAToolCert->length);
new_line = 1;
}
return 1;
}
const X509V3_EXT_METHOD ossl_v3_issuer_sign_tool = {
NID_issuerSignTool, /* nid */
X509V3_EXT_MULTILINE, /* flags */
ASN1_ITEM_ref(ISSUER_SIGN_TOOL), /* template */
0, 0, 0, 0, /* old functions, ignored */
0, /* i2s */
0, /* s2i */
0, /* i2v */
(X509V3_EXT_V2I)v2i_issuer_sign_tool, /* v2i */
(X509V3_EXT_I2R)i2r_issuer_sign_tool, /* i2r */
0, /* r2i */
NULL /* extension-specific data */
};
| 5,560 | 36.073333 | 115 |
c
|
openssl
|
openssl-master/crypto/x509/v3_lib.c
|
/*
* Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* X509 v3 extension utilities */
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
static STACK_OF(X509V3_EXT_METHOD) *ext_list = NULL;
static int ext_cmp(const X509V3_EXT_METHOD *const *a,
const X509V3_EXT_METHOD *const *b);
static void ext_list_free(X509V3_EXT_METHOD *ext);
int X509V3_EXT_add(X509V3_EXT_METHOD *ext)
{
if (ext_list == NULL
&& (ext_list = sk_X509V3_EXT_METHOD_new(ext_cmp)) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
return 0;
}
if (!sk_X509V3_EXT_METHOD_push(ext_list, ext)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
return 0;
}
return 1;
}
static int ext_cmp(const X509V3_EXT_METHOD *const *a,
const X509V3_EXT_METHOD *const *b)
{
return ((*a)->ext_nid - (*b)->ext_nid);
}
DECLARE_OBJ_BSEARCH_CMP_FN(const X509V3_EXT_METHOD *,
const X509V3_EXT_METHOD *, ext);
IMPLEMENT_OBJ_BSEARCH_CMP_FN(const X509V3_EXT_METHOD *,
const X509V3_EXT_METHOD *, ext);
#include "standard_exts.h"
const X509V3_EXT_METHOD *X509V3_EXT_get_nid(int nid)
{
X509V3_EXT_METHOD tmp;
const X509V3_EXT_METHOD *t = &tmp, *const *ret;
int idx;
if (nid < 0)
return NULL;
tmp.ext_nid = nid;
ret = OBJ_bsearch_ext(&t, standard_exts, STANDARD_EXTENSION_COUNT);
if (ret)
return *ret;
if (!ext_list)
return NULL;
/* Ideally, this would be done under a lock */
sk_X509V3_EXT_METHOD_sort(ext_list);
idx = sk_X509V3_EXT_METHOD_find(ext_list, &tmp);
/* A failure to locate the item is handled by the value method */
return sk_X509V3_EXT_METHOD_value(ext_list, idx);
}
const X509V3_EXT_METHOD *X509V3_EXT_get(X509_EXTENSION *ext)
{
int nid;
if ((nid = OBJ_obj2nid(X509_EXTENSION_get_object(ext))) == NID_undef)
return NULL;
return X509V3_EXT_get_nid(nid);
}
int X509V3_EXT_add_list(X509V3_EXT_METHOD *extlist)
{
for (; extlist->ext_nid != -1; extlist++)
if (!X509V3_EXT_add(extlist))
return 0;
return 1;
}
int X509V3_EXT_add_alias(int nid_to, int nid_from)
{
const X509V3_EXT_METHOD *ext;
X509V3_EXT_METHOD *tmpext;
if ((ext = X509V3_EXT_get_nid(nid_from)) == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_NOT_FOUND);
return 0;
}
if ((tmpext = OPENSSL_malloc(sizeof(*tmpext))) == NULL)
return 0;
*tmpext = *ext;
tmpext->ext_nid = nid_to;
tmpext->ext_flags |= X509V3_EXT_DYNAMIC;
return X509V3_EXT_add(tmpext);
}
void X509V3_EXT_cleanup(void)
{
sk_X509V3_EXT_METHOD_pop_free(ext_list, ext_list_free);
ext_list = NULL;
}
static void ext_list_free(X509V3_EXT_METHOD *ext)
{
if (ext->ext_flags & X509V3_EXT_DYNAMIC)
OPENSSL_free(ext);
}
/*
* Legacy function: we don't need to add standard extensions any more because
* they are now kept in ext_dat.h.
*/
int X509V3_add_standard_extensions(void)
{
return 1;
}
/* Return an extension internal structure */
void *X509V3_EXT_d2i(X509_EXTENSION *ext)
{
const X509V3_EXT_METHOD *method;
const unsigned char *p;
ASN1_STRING *extvalue;
int extlen;
if ((method = X509V3_EXT_get(ext)) == NULL)
return NULL;
extvalue = X509_EXTENSION_get_data(ext);
p = ASN1_STRING_get0_data(extvalue);
extlen = ASN1_STRING_length(extvalue);
if (method->it)
return ASN1_item_d2i(NULL, &p, extlen, ASN1_ITEM_ptr(method->it));
return method->d2i(NULL, &p, extlen);
}
/*-
* Get critical flag and decoded version of extension from a NID.
* The "idx" variable returns the last found extension and can
* be used to retrieve multiple extensions of the same NID.
* However multiple extensions with the same NID is usually
* due to a badly encoded certificate so if idx is NULL we
* choke if multiple extensions exist.
* The "crit" variable is set to the critical value.
* The return value is the decoded extension or NULL on
* error. The actual error can have several different causes,
* the value of *crit reflects the cause:
* >= 0, extension found but not decoded (reflects critical value).
* -1 extension not found.
* -2 extension occurs more than once.
*/
void *X509V3_get_d2i(const STACK_OF(X509_EXTENSION) *x, int nid, int *crit,
int *idx)
{
int lastpos, i;
X509_EXTENSION *ex, *found_ex = NULL;
if (!x) {
if (idx)
*idx = -1;
if (crit)
*crit = -1;
return NULL;
}
if (idx)
lastpos = *idx + 1;
else
lastpos = 0;
if (lastpos < 0)
lastpos = 0;
for (i = lastpos; i < sk_X509_EXTENSION_num(x); i++) {
ex = sk_X509_EXTENSION_value(x, i);
if (OBJ_obj2nid(X509_EXTENSION_get_object(ex)) == nid) {
if (idx) {
*idx = i;
found_ex = ex;
break;
} else if (found_ex) {
/* Found more than one */
if (crit)
*crit = -2;
return NULL;
}
found_ex = ex;
}
}
if (found_ex) {
/* Found it */
if (crit)
*crit = X509_EXTENSION_get_critical(found_ex);
return X509V3_EXT_d2i(found_ex);
}
/* Extension not found */
if (idx)
*idx = -1;
if (crit)
*crit = -1;
return NULL;
}
/*
* This function is a general extension append, replace and delete utility.
* The precise operation is governed by the 'flags' value. The 'crit' and
* 'value' arguments (if relevant) are the extensions internal structure.
*/
int X509V3_add1_i2d(STACK_OF(X509_EXTENSION) **x, int nid, void *value,
int crit, unsigned long flags)
{
int errcode, extidx = -1;
X509_EXTENSION *ext = NULL, *extmp;
STACK_OF(X509_EXTENSION) *ret = NULL;
unsigned long ext_op = flags & X509V3_ADD_OP_MASK;
/*
* If appending we don't care if it exists, otherwise look for existing
* extension.
*/
if (ext_op != X509V3_ADD_APPEND)
extidx = X509v3_get_ext_by_NID(*x, nid, -1);
/* See if extension exists */
if (extidx >= 0) {
/* If keep existing, nothing to do */
if (ext_op == X509V3_ADD_KEEP_EXISTING)
return 1;
/* If default then its an error */
if (ext_op == X509V3_ADD_DEFAULT) {
errcode = X509V3_R_EXTENSION_EXISTS;
goto err;
}
/* If delete, just delete it */
if (ext_op == X509V3_ADD_DELETE) {
extmp = sk_X509_EXTENSION_delete(*x, extidx);
if (extmp == NULL)
return -1;
X509_EXTENSION_free(extmp);
return 1;
}
} else {
/*
* If replace existing or delete, error since extension must exist
*/
if ((ext_op == X509V3_ADD_REPLACE_EXISTING) ||
(ext_op == X509V3_ADD_DELETE)) {
errcode = X509V3_R_EXTENSION_NOT_FOUND;
goto err;
}
}
/*
* If we get this far then we have to create an extension: could have
* some flags for alternative encoding schemes...
*/
ext = X509V3_EXT_i2d(nid, crit, value);
if (!ext) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_ERROR_CREATING_EXTENSION);
return 0;
}
/* If extension exists replace it.. */
if (extidx >= 0) {
extmp = sk_X509_EXTENSION_value(*x, extidx);
X509_EXTENSION_free(extmp);
if (!sk_X509_EXTENSION_set(*x, extidx, ext))
return -1;
return 1;
}
ret = *x;
if (*x == NULL
&& (ret = sk_X509_EXTENSION_new_null()) == NULL)
goto m_fail;
if (!sk_X509_EXTENSION_push(ret, ext))
goto m_fail;
*x = ret;
return 1;
m_fail:
/* ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB); */
if (ret != *x)
sk_X509_EXTENSION_free(ret);
X509_EXTENSION_free(ext);
return -1;
err:
if (!(flags & X509V3_ADD_SILENT))
ERR_raise(ERR_LIB_X509V3, errcode);
return 0;
}
| 8,502 | 26.787582 | 77 |
c
|
openssl
|
openssl-master/crypto/x509/v3_pci.c
|
/*
* Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This file is dual-licensed and is also available under the following
* terms:
*
* Copyright (c) 2004 Kungliga Tekniska Högskolan
* (Royal Institute of Technology, Stockholm, Sweden).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
static int i2r_pci(X509V3_EXT_METHOD *method, PROXY_CERT_INFO_EXTENSION *ext,
BIO *out, int indent);
static PROXY_CERT_INFO_EXTENSION *r2i_pci(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, char *str);
const X509V3_EXT_METHOD ossl_v3_pci =
{ NID_proxyCertInfo, 0, ASN1_ITEM_ref(PROXY_CERT_INFO_EXTENSION),
0, 0, 0, 0,
0, 0,
NULL, NULL,
(X509V3_EXT_I2R)i2r_pci,
(X509V3_EXT_R2I)r2i_pci,
NULL,
};
static int i2r_pci(X509V3_EXT_METHOD *method, PROXY_CERT_INFO_EXTENSION *pci,
BIO *out, int indent)
{
BIO_printf(out, "%*sPath Length Constraint: ", indent, "");
if (pci->pcPathLengthConstraint)
i2a_ASN1_INTEGER(out, pci->pcPathLengthConstraint);
else
BIO_printf(out, "infinite");
BIO_puts(out, "\n");
BIO_printf(out, "%*sPolicy Language: ", indent, "");
i2a_ASN1_OBJECT(out, pci->proxyPolicy->policyLanguage);
if (pci->proxyPolicy->policy && pci->proxyPolicy->policy->data)
BIO_printf(out, "\n%*sPolicy Text: %.*s", indent, "",
pci->proxyPolicy->policy->length,
pci->proxyPolicy->policy->data);
return 1;
}
static int process_pci_value(CONF_VALUE *val,
ASN1_OBJECT **language, ASN1_INTEGER **pathlen,
ASN1_OCTET_STRING **policy)
{
int free_policy = 0;
if (strcmp(val->name, "language") == 0) {
if (*language) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_POLICY_LANGUAGE_ALREADY_DEFINED);
X509V3_conf_err(val);
return 0;
}
if ((*language = OBJ_txt2obj(val->value, 0)) == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER);
X509V3_conf_err(val);
return 0;
}
} else if (strcmp(val->name, "pathlen") == 0) {
if (*pathlen) {
ERR_raise(ERR_LIB_X509V3,
X509V3_R_POLICY_PATH_LENGTH_ALREADY_DEFINED);
X509V3_conf_err(val);
return 0;
}
if (!X509V3_get_value_int(val, pathlen)) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_POLICY_PATH_LENGTH);
X509V3_conf_err(val);
return 0;
}
} else if (strcmp(val->name, "policy") == 0) {
char *valp = val->value;
unsigned char *tmp_data = NULL;
long val_len;
if (*policy == NULL) {
*policy = ASN1_OCTET_STRING_new();
if (*policy == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
X509V3_conf_err(val);
return 0;
}
free_policy = 1;
}
if (CHECK_AND_SKIP_PREFIX(valp, "hex:")) {
unsigned char *tmp_data2 =
OPENSSL_hexstr2buf(valp, &val_len);
if (!tmp_data2) {
X509V3_conf_err(val);
goto err;
}
tmp_data = OPENSSL_realloc((*policy)->data,
(*policy)->length + val_len + 1);
if (tmp_data) {
(*policy)->data = tmp_data;
memcpy(&(*policy)->data[(*policy)->length],
tmp_data2, val_len);
(*policy)->length += val_len;
(*policy)->data[(*policy)->length] = '\0';
} else {
OPENSSL_free(tmp_data2);
/*
* realloc failure implies the original data space is b0rked
* too!
*/
OPENSSL_free((*policy)->data);
(*policy)->data = NULL;
(*policy)->length = 0;
X509V3_conf_err(val);
goto err;
}
OPENSSL_free(tmp_data2);
} else if (CHECK_AND_SKIP_PREFIX(valp, "file:")) {
unsigned char buf[2048];
int n;
BIO *b = BIO_new_file(valp, "r");
if (!b) {
ERR_raise(ERR_LIB_X509V3, ERR_R_BIO_LIB);
X509V3_conf_err(val);
goto err;
}
while ((n = BIO_read(b, buf, sizeof(buf))) > 0
|| (n == 0 && BIO_should_retry(b))) {
if (!n)
continue;
tmp_data = OPENSSL_realloc((*policy)->data,
(*policy)->length + n + 1);
if (!tmp_data) {
OPENSSL_free((*policy)->data);
(*policy)->data = NULL;
(*policy)->length = 0;
X509V3_conf_err(val);
BIO_free_all(b);
goto err;
}
(*policy)->data = tmp_data;
memcpy(&(*policy)->data[(*policy)->length], buf, n);
(*policy)->length += n;
(*policy)->data[(*policy)->length] = '\0';
}
BIO_free_all(b);
if (n < 0) {
ERR_raise(ERR_LIB_X509V3, ERR_R_BIO_LIB);
X509V3_conf_err(val);
goto err;
}
} else if (CHECK_AND_SKIP_PREFIX(valp, "text:")) {
val_len = strlen(valp);
tmp_data = OPENSSL_realloc((*policy)->data,
(*policy)->length + val_len + 1);
if (tmp_data) {
(*policy)->data = tmp_data;
memcpy(&(*policy)->data[(*policy)->length],
val->value + 5, val_len);
(*policy)->length += val_len;
(*policy)->data[(*policy)->length] = '\0';
} else {
/*
* realloc failure implies the original data space is b0rked
* too!
*/
OPENSSL_free((*policy)->data);
(*policy)->data = NULL;
(*policy)->length = 0;
X509V3_conf_err(val);
goto err;
}
} else {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INCORRECT_POLICY_SYNTAX_TAG);
X509V3_conf_err(val);
goto err;
}
if (!tmp_data) {
X509V3_conf_err(val);
goto err;
}
}
return 1;
err:
if (free_policy) {
ASN1_OCTET_STRING_free(*policy);
*policy = NULL;
}
return 0;
}
static PROXY_CERT_INFO_EXTENSION *r2i_pci(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, char *value)
{
PROXY_CERT_INFO_EXTENSION *pci = NULL;
STACK_OF(CONF_VALUE) *vals;
ASN1_OBJECT *language = NULL;
ASN1_INTEGER *pathlen = NULL;
ASN1_OCTET_STRING *policy = NULL;
int i, j;
vals = X509V3_parse_list(value);
for (i = 0; i < sk_CONF_VALUE_num(vals); i++) {
CONF_VALUE *cnf = sk_CONF_VALUE_value(vals, i);
if (!cnf->name || (*cnf->name != '@' && !cnf->value)) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_PROXY_POLICY_SETTING);
X509V3_conf_err(cnf);
goto err;
}
if (*cnf->name == '@') {
STACK_OF(CONF_VALUE) *sect;
int success_p = 1;
sect = X509V3_get_section(ctx, cnf->name + 1);
if (!sect) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_SECTION);
X509V3_conf_err(cnf);
goto err;
}
for (j = 0; success_p && j < sk_CONF_VALUE_num(sect); j++) {
success_p =
process_pci_value(sk_CONF_VALUE_value(sect, j),
&language, &pathlen, &policy);
}
X509V3_section_free(ctx, sect);
if (!success_p)
goto err;
} else {
if (!process_pci_value(cnf, &language, &pathlen, &policy)) {
X509V3_conf_err(cnf);
goto err;
}
}
}
/* Language is mandatory */
if (!language) {
ERR_raise(ERR_LIB_X509V3,
X509V3_R_NO_PROXY_CERT_POLICY_LANGUAGE_DEFINED);
goto err;
}
i = OBJ_obj2nid(language);
if ((i == NID_Independent || i == NID_id_ppl_inheritAll) && policy) {
ERR_raise(ERR_LIB_X509V3,
X509V3_R_POLICY_WHEN_PROXY_LANGUAGE_REQUIRES_NO_POLICY);
goto err;
}
pci = PROXY_CERT_INFO_EXTENSION_new();
if (pci == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
pci->proxyPolicy->policyLanguage = language;
language = NULL;
pci->proxyPolicy->policy = policy;
policy = NULL;
pci->pcPathLengthConstraint = pathlen;
pathlen = NULL;
goto end;
err:
ASN1_OBJECT_free(language);
ASN1_INTEGER_free(pathlen);
pathlen = NULL;
ASN1_OCTET_STRING_free(policy);
policy = NULL;
PROXY_CERT_INFO_EXTENSION_free(pci);
pci = NULL;
end:
sk_CONF_VALUE_pop_free(vals, X509V3_conf_free);
return pci;
}
| 11,203 | 34.122257 | 80 |
c
|
openssl
|
openssl-master/crypto/x509/v3_pcia.c
|
/*
* Copyright 2004-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* This file is dual-licensed and is also available under the following
* terms:
*
* Copyright (c) 2004 Kungliga Tekniska Högskolan
* (Royal Institute of Technology, Stockholm, Sweden).
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
ASN1_SEQUENCE(PROXY_POLICY) = {
ASN1_SIMPLE(PROXY_POLICY, policyLanguage, ASN1_OBJECT),
ASN1_OPT(PROXY_POLICY, policy, ASN1_OCTET_STRING)
} ASN1_SEQUENCE_END(PROXY_POLICY)
IMPLEMENT_ASN1_FUNCTIONS(PROXY_POLICY)
ASN1_SEQUENCE(PROXY_CERT_INFO_EXTENSION) = {
ASN1_OPT(PROXY_CERT_INFO_EXTENSION, pcPathLengthConstraint, ASN1_INTEGER),
ASN1_SIMPLE(PROXY_CERT_INFO_EXTENSION, proxyPolicy, PROXY_POLICY)
} ASN1_SEQUENCE_END(PROXY_CERT_INFO_EXTENSION)
IMPLEMENT_ASN1_FUNCTIONS(PROXY_CERT_INFO_EXTENSION)
| 2,673 | 41.444444 | 82 |
c
|
openssl
|
openssl-master/crypto/x509/v3_pcons.c
|
/*
* Copyright 2003-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
static STACK_OF(CONF_VALUE) *i2v_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD
*method, void *bcons, STACK_OF(CONF_VALUE)
*extlist);
static void *v2i_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *values);
const X509V3_EXT_METHOD ossl_v3_policy_constraints = {
NID_policy_constraints, 0,
ASN1_ITEM_ref(POLICY_CONSTRAINTS),
0, 0, 0, 0,
0, 0,
i2v_POLICY_CONSTRAINTS,
v2i_POLICY_CONSTRAINTS,
NULL, NULL,
NULL
};
ASN1_SEQUENCE(POLICY_CONSTRAINTS) = {
ASN1_IMP_OPT(POLICY_CONSTRAINTS, requireExplicitPolicy, ASN1_INTEGER,0),
ASN1_IMP_OPT(POLICY_CONSTRAINTS, inhibitPolicyMapping, ASN1_INTEGER,1)
} ASN1_SEQUENCE_END(POLICY_CONSTRAINTS)
IMPLEMENT_ASN1_ALLOC_FUNCTIONS(POLICY_CONSTRAINTS)
static STACK_OF(CONF_VALUE) *i2v_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD
*method, void *a, STACK_OF(CONF_VALUE)
*extlist)
{
POLICY_CONSTRAINTS *pcons = a;
X509V3_add_value_int("Require Explicit Policy",
pcons->requireExplicitPolicy, &extlist);
X509V3_add_value_int("Inhibit Policy Mapping",
pcons->inhibitPolicyMapping, &extlist);
return extlist;
}
static void *v2i_POLICY_CONSTRAINTS(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *values)
{
POLICY_CONSTRAINTS *pcons = NULL;
CONF_VALUE *val;
int i;
if ((pcons = POLICY_CONSTRAINTS_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(values); i++) {
val = sk_CONF_VALUE_value(values, i);
if (strcmp(val->name, "requireExplicitPolicy") == 0) {
if (!X509V3_get_value_int(val, &pcons->requireExplicitPolicy))
goto err;
} else if (strcmp(val->name, "inhibitPolicyMapping") == 0) {
if (!X509V3_get_value_int(val, &pcons->inhibitPolicyMapping))
goto err;
} else {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_INVALID_NAME,
"%s", val->name);
goto err;
}
}
if (pcons->inhibitPolicyMapping == NULL
&& pcons->requireExplicitPolicy == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_ILLEGAL_EMPTY_EXTENSION);
goto err;
}
return pcons;
err:
POLICY_CONSTRAINTS_free(pcons);
return NULL;
}
| 3,254 | 34.380435 | 94 |
c
|
openssl
|
openssl-master/crypto/x509/v3_pku.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
static int i2r_PKEY_USAGE_PERIOD(X509V3_EXT_METHOD *method,
PKEY_USAGE_PERIOD *usage, BIO *out,
int indent);
const X509V3_EXT_METHOD ossl_v3_pkey_usage_period = {
NID_private_key_usage_period, 0, ASN1_ITEM_ref(PKEY_USAGE_PERIOD),
0, 0, 0, 0,
0, 0, 0, 0,
(X509V3_EXT_I2R)i2r_PKEY_USAGE_PERIOD, NULL,
NULL
};
ASN1_SEQUENCE(PKEY_USAGE_PERIOD) = {
ASN1_IMP_OPT(PKEY_USAGE_PERIOD, notBefore, ASN1_GENERALIZEDTIME, 0),
ASN1_IMP_OPT(PKEY_USAGE_PERIOD, notAfter, ASN1_GENERALIZEDTIME, 1)
} ASN1_SEQUENCE_END(PKEY_USAGE_PERIOD)
IMPLEMENT_ASN1_FUNCTIONS(PKEY_USAGE_PERIOD)
static int i2r_PKEY_USAGE_PERIOD(X509V3_EXT_METHOD *method,
PKEY_USAGE_PERIOD *usage, BIO *out,
int indent)
{
BIO_printf(out, "%*s", indent, "");
if (usage->notBefore) {
BIO_write(out, "Not Before: ", 12);
ASN1_GENERALIZEDTIME_print(out, usage->notBefore);
if (usage->notAfter)
BIO_write(out, ", ", 2);
}
if (usage->notAfter) {
BIO_write(out, "Not After: ", 11);
ASN1_GENERALIZEDTIME_print(out, usage->notAfter);
}
return 1;
}
| 1,728 | 31.622642 | 76 |
c
|
openssl
|
openssl-master/crypto/x509/v3_pmaps.c
|
/*
* Copyright 2003-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
static void *v2i_POLICY_MAPPINGS(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval);
static STACK_OF(CONF_VALUE) *i2v_POLICY_MAPPINGS(const X509V3_EXT_METHOD
*method, void *pmps, STACK_OF(CONF_VALUE)
*extlist);
const X509V3_EXT_METHOD ossl_v3_policy_mappings = {
NID_policy_mappings, 0,
ASN1_ITEM_ref(POLICY_MAPPINGS),
0, 0, 0, 0,
0, 0,
i2v_POLICY_MAPPINGS,
v2i_POLICY_MAPPINGS,
0, 0,
NULL
};
ASN1_SEQUENCE(POLICY_MAPPING) = {
ASN1_SIMPLE(POLICY_MAPPING, issuerDomainPolicy, ASN1_OBJECT),
ASN1_SIMPLE(POLICY_MAPPING, subjectDomainPolicy, ASN1_OBJECT)
} ASN1_SEQUENCE_END(POLICY_MAPPING)
ASN1_ITEM_TEMPLATE(POLICY_MAPPINGS) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, POLICY_MAPPINGS,
POLICY_MAPPING)
ASN1_ITEM_TEMPLATE_END(POLICY_MAPPINGS)
IMPLEMENT_ASN1_ALLOC_FUNCTIONS(POLICY_MAPPING)
static STACK_OF(CONF_VALUE) *i2v_POLICY_MAPPINGS(const X509V3_EXT_METHOD
*method, void *a, STACK_OF(CONF_VALUE)
*ext_list)
{
POLICY_MAPPINGS *pmaps = a;
POLICY_MAPPING *pmap;
int i;
char obj_tmp1[80];
char obj_tmp2[80];
for (i = 0; i < sk_POLICY_MAPPING_num(pmaps); i++) {
pmap = sk_POLICY_MAPPING_value(pmaps, i);
i2t_ASN1_OBJECT(obj_tmp1, 80, pmap->issuerDomainPolicy);
i2t_ASN1_OBJECT(obj_tmp2, 80, pmap->subjectDomainPolicy);
X509V3_add_value(obj_tmp1, obj_tmp2, &ext_list);
}
return ext_list;
}
static void *v2i_POLICY_MAPPINGS(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval)
{
POLICY_MAPPING *pmap = NULL;
ASN1_OBJECT *obj1 = NULL, *obj2 = NULL;
CONF_VALUE *val;
POLICY_MAPPINGS *pmaps;
const int num = sk_CONF_VALUE_num(nval);
int i;
if ((pmaps = sk_POLICY_MAPPING_new_reserve(NULL, num)) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
return NULL;
}
for (i = 0; i < num; i++) {
val = sk_CONF_VALUE_value(nval, i);
if (!val->value || !val->name) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER,
"%s", val->name);
goto err;
}
obj1 = OBJ_txt2obj(val->name, 0);
obj2 = OBJ_txt2obj(val->value, 0);
if (!obj1 || !obj2) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_INVALID_OBJECT_IDENTIFIER,
"%s", val->name);
goto err;
}
pmap = POLICY_MAPPING_new();
if (pmap == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
pmap->issuerDomainPolicy = obj1;
pmap->subjectDomainPolicy = obj2;
obj1 = obj2 = NULL;
sk_POLICY_MAPPING_push(pmaps, pmap); /* no failure as it was reserved */
}
return pmaps;
err:
ASN1_OBJECT_free(obj1);
ASN1_OBJECT_free(obj2);
sk_POLICY_MAPPING_pop_free(pmaps, POLICY_MAPPING_free);
return NULL;
}
| 3,763 | 32.90991 | 90 |
c
|
openssl
|
openssl-master/crypto/x509/v3_prn.c
|
/*
* Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* X509 v3 extension utilities */
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/x509v3.h>
/* Extension printing routines */
static int unknown_ext_print(BIO *out, const unsigned char *ext, int extlen,
unsigned long flag, int indent, int supported);
/* Print out a name+value stack */
void X509V3_EXT_val_prn(BIO *out, STACK_OF(CONF_VALUE) *val, int indent,
int ml)
{
int i;
CONF_VALUE *nval;
if (!val)
return;
if (!ml || !sk_CONF_VALUE_num(val)) {
BIO_printf(out, "%*s", indent, "");
if (!sk_CONF_VALUE_num(val))
BIO_puts(out, "<EMPTY>\n");
}
for (i = 0; i < sk_CONF_VALUE_num(val); i++) {
if (ml) {
if (i > 0)
BIO_printf(out, "\n");
BIO_printf(out, "%*s", indent, "");
}
else if (i > 0)
BIO_printf(out, ", ");
nval = sk_CONF_VALUE_value(val, i);
if (!nval->name)
BIO_puts(out, nval->value);
else if (!nval->value)
BIO_puts(out, nval->name);
#ifndef CHARSET_EBCDIC
else
BIO_printf(out, "%s:%s", nval->name, nval->value);
#else
else {
int len;
char *tmp;
len = strlen(nval->value) + 1;
tmp = OPENSSL_malloc(len);
if (tmp != NULL) {
ascii2ebcdic(tmp, nval->value, len);
BIO_printf(out, "%s:%s", nval->name, tmp);
OPENSSL_free(tmp);
}
}
#endif
}
}
/* Main routine: print out a general extension */
int X509V3_EXT_print(BIO *out, X509_EXTENSION *ext, unsigned long flag,
int indent)
{
void *ext_str = NULL;
char *value = NULL;
ASN1_OCTET_STRING *extoct;
const unsigned char *p;
int extlen;
const X509V3_EXT_METHOD *method;
STACK_OF(CONF_VALUE) *nval = NULL;
int ok = 1;
extoct = X509_EXTENSION_get_data(ext);
p = ASN1_STRING_get0_data(extoct);
extlen = ASN1_STRING_length(extoct);
if ((method = X509V3_EXT_get(ext)) == NULL)
return unknown_ext_print(out, p, extlen, flag, indent, 0);
if (method->it)
ext_str = ASN1_item_d2i(NULL, &p, extlen, ASN1_ITEM_ptr(method->it));
else
ext_str = method->d2i(NULL, &p, extlen);
if (!ext_str)
return unknown_ext_print(out, p, extlen, flag, indent, 1);
if (method->i2s) {
if ((value = method->i2s(method, ext_str)) == NULL) {
ok = 0;
goto err;
}
#ifndef CHARSET_EBCDIC
BIO_printf(out, "%*s%s", indent, "", value);
#else
{
int len;
char *tmp;
len = strlen(value) + 1;
tmp = OPENSSL_malloc(len);
if (tmp != NULL) {
ascii2ebcdic(tmp, value, len);
BIO_printf(out, "%*s%s", indent, "", tmp);
OPENSSL_free(tmp);
}
}
#endif
} else if (method->i2v) {
if ((nval = method->i2v(method, ext_str, NULL)) == NULL) {
ok = 0;
goto err;
}
X509V3_EXT_val_prn(out, nval, indent,
method->ext_flags & X509V3_EXT_MULTILINE);
} else if (method->i2r) {
if (!method->i2r(method, ext_str, out, indent))
ok = 0;
} else
ok = 0;
err:
sk_CONF_VALUE_pop_free(nval, X509V3_conf_free);
OPENSSL_free(value);
if (method->it)
ASN1_item_free(ext_str, ASN1_ITEM_ptr(method->it));
else
method->ext_free(ext_str);
return ok;
}
int X509V3_extensions_print(BIO *bp, const char *title,
const STACK_OF(X509_EXTENSION) *exts,
unsigned long flag, int indent)
{
int i, j;
if (sk_X509_EXTENSION_num(exts) <= 0)
return 1;
if (title) {
BIO_printf(bp, "%*s%s:\n", indent, "", title);
indent += 4;
}
for (i = 0; i < sk_X509_EXTENSION_num(exts); i++) {
ASN1_OBJECT *obj;
X509_EXTENSION *ex;
ex = sk_X509_EXTENSION_value(exts, i);
obj = X509_EXTENSION_get_object(ex);
if ((flag & X509_FLAG_EXTENSIONS_ONLY_KID) != 0
&& OBJ_obj2nid(obj) != NID_subject_key_identifier
&& OBJ_obj2nid(obj) != NID_authority_key_identifier)
continue;
if (indent && BIO_printf(bp, "%*s", indent, "") <= 0)
return 0;
i2a_ASN1_OBJECT(bp, obj);
j = X509_EXTENSION_get_critical(ex);
if (BIO_printf(bp, ": %s\n", j ? "critical" : "") <= 0)
return 0;
if (!X509V3_EXT_print(bp, ex, flag, indent + 4)) {
BIO_printf(bp, "%*s", indent + 4, "");
ASN1_STRING_print(bp, X509_EXTENSION_get_data(ex));
}
if (BIO_write(bp, "\n", 1) <= 0)
return 0;
}
return 1;
}
static int unknown_ext_print(BIO *out, const unsigned char *ext, int extlen,
unsigned long flag, int indent, int supported)
{
switch (flag & X509V3_EXT_UNKNOWN_MASK) {
case X509V3_EXT_DEFAULT:
return 0;
case X509V3_EXT_ERROR_UNKNOWN:
if (supported)
BIO_printf(out, "%*s<Parse Error>", indent, "");
else
BIO_printf(out, "%*s<Not Supported>", indent, "");
return 1;
case X509V3_EXT_PARSE_UNKNOWN:
return ASN1_parse_dump(out, ext, extlen, indent, -1);
case X509V3_EXT_DUMP_UNKNOWN:
return BIO_dump_indent(out, (const char *)ext, extlen, indent);
default:
return 1;
}
}
#ifndef OPENSSL_NO_STDIO
int X509V3_EXT_print_fp(FILE *fp, X509_EXTENSION *ext, int flag, int indent)
{
BIO *bio_tmp;
int ret;
if ((bio_tmp = BIO_new_fp(fp, BIO_NOCLOSE)) == NULL)
return 0;
ret = X509V3_EXT_print(bio_tmp, ext, flag, indent);
BIO_free(bio_tmp);
return ret;
}
#endif
| 6,285 | 27.967742 | 77 |
c
|
openssl
|
openssl-master/crypto/x509/v3_san.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include "crypto/x509.h"
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include <openssl/bio.h>
#include "ext_dat.h"
static GENERAL_NAMES *v2i_subject_alt(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval);
static GENERAL_NAMES *v2i_issuer_alt(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval);
static int copy_email(X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p);
static int copy_issuer(X509V3_CTX *ctx, GENERAL_NAMES *gens);
static int do_othername(GENERAL_NAME *gen, const char *value, X509V3_CTX *ctx);
static int do_dirname(GENERAL_NAME *gen, const char *value, X509V3_CTX *ctx);
const X509V3_EXT_METHOD ossl_v3_alt[3] = {
{NID_subject_alt_name, 0, ASN1_ITEM_ref(GENERAL_NAMES),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_GENERAL_NAMES,
(X509V3_EXT_V2I)v2i_subject_alt,
NULL, NULL, NULL},
{NID_issuer_alt_name, 0, ASN1_ITEM_ref(GENERAL_NAMES),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_GENERAL_NAMES,
(X509V3_EXT_V2I)v2i_issuer_alt,
NULL, NULL, NULL},
{NID_certificate_issuer, 0, ASN1_ITEM_ref(GENERAL_NAMES),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V) i2v_GENERAL_NAMES,
NULL, NULL, NULL, NULL},
};
STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES(X509V3_EXT_METHOD *method,
GENERAL_NAMES *gens,
STACK_OF(CONF_VALUE) *ret)
{
int i;
GENERAL_NAME *gen;
STACK_OF(CONF_VALUE) *tmpret = NULL, *origret = ret;
for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
gen = sk_GENERAL_NAME_value(gens, i);
/*
* i2v_GENERAL_NAME allocates ret if it is NULL. If something goes
* wrong we need to free the stack - but only if it was empty when we
* originally entered this function.
*/
tmpret = i2v_GENERAL_NAME(method, gen, ret);
if (tmpret == NULL) {
if (origret == NULL)
sk_CONF_VALUE_pop_free(ret, X509V3_conf_free);
return NULL;
}
ret = tmpret;
}
if (ret == NULL)
return sk_CONF_VALUE_new_null();
return ret;
}
STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(X509V3_EXT_METHOD *method,
GENERAL_NAME *gen,
STACK_OF(CONF_VALUE) *ret)
{
char othername[300];
char oline[256], *tmp;
switch (gen->type) {
case GEN_OTHERNAME:
switch (OBJ_obj2nid(gen->d.otherName->type_id)) {
case NID_id_on_SmtpUTF8Mailbox:
if (gen->d.otherName->value->type != V_ASN1_UTF8STRING
|| !x509v3_add_len_value_uchar("othername: SmtpUTF8Mailbox:",
gen->d.otherName->value->value.utf8string->data,
gen->d.otherName->value->value.utf8string->length,
&ret))
return NULL;
break;
case NID_XmppAddr:
if (gen->d.otherName->value->type != V_ASN1_UTF8STRING
|| !x509v3_add_len_value_uchar("othername: XmppAddr:",
gen->d.otherName->value->value.utf8string->data,
gen->d.otherName->value->value.utf8string->length,
&ret))
return NULL;
break;
case NID_SRVName:
if (gen->d.otherName->value->type != V_ASN1_IA5STRING
|| !x509v3_add_len_value_uchar("othername: SRVName:",
gen->d.otherName->value->value.ia5string->data,
gen->d.otherName->value->value.ia5string->length,
&ret))
return NULL;
break;
case NID_ms_upn:
if (gen->d.otherName->value->type != V_ASN1_UTF8STRING
|| !x509v3_add_len_value_uchar("othername: UPN:",
gen->d.otherName->value->value.utf8string->data,
gen->d.otherName->value->value.utf8string->length,
&ret))
return NULL;
break;
case NID_NAIRealm:
if (gen->d.otherName->value->type != V_ASN1_UTF8STRING
|| !x509v3_add_len_value_uchar("othername: NAIRealm:",
gen->d.otherName->value->value.utf8string->data,
gen->d.otherName->value->value.utf8string->length,
&ret))
return NULL;
break;
default:
if (OBJ_obj2txt(oline, sizeof(oline), gen->d.otherName->type_id, 0) > 0)
BIO_snprintf(othername, sizeof(othername), "othername: %s:",
oline);
else
OPENSSL_strlcpy(othername, "othername:", sizeof(othername));
/* check if the value is something printable */
if (gen->d.otherName->value->type == V_ASN1_IA5STRING) {
if (x509v3_add_len_value_uchar(othername,
gen->d.otherName->value->value.ia5string->data,
gen->d.otherName->value->value.ia5string->length,
&ret))
return ret;
}
if (gen->d.otherName->value->type == V_ASN1_UTF8STRING) {
if (x509v3_add_len_value_uchar(othername,
gen->d.otherName->value->value.utf8string->data,
gen->d.otherName->value->value.utf8string->length,
&ret))
return ret;
}
if (!X509V3_add_value(othername, "<unsupported>", &ret))
return NULL;
break;
}
break;
case GEN_X400:
if (!X509V3_add_value("X400Name", "<unsupported>", &ret))
return NULL;
break;
case GEN_EDIPARTY:
if (!X509V3_add_value("EdiPartyName", "<unsupported>", &ret))
return NULL;
break;
case GEN_EMAIL:
if (!x509v3_add_len_value_uchar("email", gen->d.ia5->data,
gen->d.ia5->length, &ret))
return NULL;
break;
case GEN_DNS:
if (!x509v3_add_len_value_uchar("DNS", gen->d.ia5->data,
gen->d.ia5->length, &ret))
return NULL;
break;
case GEN_URI:
if (!x509v3_add_len_value_uchar("URI", gen->d.ia5->data,
gen->d.ia5->length, &ret))
return NULL;
break;
case GEN_DIRNAME:
if (X509_NAME_oneline(gen->d.dirn, oline, sizeof(oline)) == NULL
|| !X509V3_add_value("DirName", oline, &ret))
return NULL;
break;
case GEN_IPADD:
tmp = ossl_ipaddr_to_asc(gen->d.ip->data, gen->d.ip->length);
if (tmp == NULL || !X509V3_add_value("IP Address", tmp, &ret))
ret = NULL;
OPENSSL_free(tmp);
break;
case GEN_RID:
i2t_ASN1_OBJECT(oline, 256, gen->d.rid);
if (!X509V3_add_value("Registered ID", oline, &ret))
return NULL;
break;
}
return ret;
}
int GENERAL_NAME_print(BIO *out, GENERAL_NAME *gen)
{
char *tmp;
int nid;
switch (gen->type) {
case GEN_OTHERNAME:
nid = OBJ_obj2nid(gen->d.otherName->type_id);
/* Validate the types are as we expect before we use them */
if ((nid == NID_SRVName
&& gen->d.otherName->value->type != V_ASN1_IA5STRING)
|| (nid != NID_SRVName
&& gen->d.otherName->value->type != V_ASN1_UTF8STRING)) {
BIO_printf(out, "othername:<unsupported>");
break;
}
switch (nid) {
case NID_id_on_SmtpUTF8Mailbox:
BIO_printf(out, "othername:SmtpUTF8Mailbox:%.*s",
gen->d.otherName->value->value.utf8string->length,
gen->d.otherName->value->value.utf8string->data);
break;
case NID_XmppAddr:
BIO_printf(out, "othername:XmppAddr:%.*s",
gen->d.otherName->value->value.utf8string->length,
gen->d.otherName->value->value.utf8string->data);
break;
case NID_SRVName:
BIO_printf(out, "othername:SRVName:%.*s",
gen->d.otherName->value->value.ia5string->length,
gen->d.otherName->value->value.ia5string->data);
break;
case NID_ms_upn:
BIO_printf(out, "othername:UPN:%.*s",
gen->d.otherName->value->value.utf8string->length,
gen->d.otherName->value->value.utf8string->data);
break;
case NID_NAIRealm:
BIO_printf(out, "othername:NAIRealm:%.*s",
gen->d.otherName->value->value.utf8string->length,
gen->d.otherName->value->value.utf8string->data);
break;
default:
BIO_printf(out, "othername:<unsupported>");
break;
}
break;
case GEN_X400:
BIO_printf(out, "X400Name:<unsupported>");
break;
case GEN_EDIPARTY:
/* Maybe fix this: it is supported now */
BIO_printf(out, "EdiPartyName:<unsupported>");
break;
case GEN_EMAIL:
BIO_printf(out, "email:");
ASN1_STRING_print(out, gen->d.ia5);
break;
case GEN_DNS:
BIO_printf(out, "DNS:");
ASN1_STRING_print(out, gen->d.ia5);
break;
case GEN_URI:
BIO_printf(out, "URI:");
ASN1_STRING_print(out, gen->d.ia5);
break;
case GEN_DIRNAME:
BIO_printf(out, "DirName:");
X509_NAME_print_ex(out, gen->d.dirn, 0, XN_FLAG_ONELINE);
break;
case GEN_IPADD:
tmp = ossl_ipaddr_to_asc(gen->d.ip->data, gen->d.ip->length);
if (tmp == NULL)
return 0;
BIO_printf(out, "IP Address:%s", tmp);
OPENSSL_free(tmp);
break;
case GEN_RID:
BIO_printf(out, "Registered ID:");
i2a_ASN1_OBJECT(out, gen->d.rid);
break;
}
return 1;
}
static GENERAL_NAMES *v2i_issuer_alt(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval)
{
const int num = sk_CONF_VALUE_num(nval);
GENERAL_NAMES *gens = sk_GENERAL_NAME_new_reserve(NULL, num);
int i;
if (gens == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
sk_GENERAL_NAME_free(gens);
return NULL;
}
for (i = 0; i < num; i++) {
CONF_VALUE *cnf = sk_CONF_VALUE_value(nval, i);
if (!ossl_v3_name_cmp(cnf->name, "issuer")
&& cnf->value && strcmp(cnf->value, "copy") == 0) {
if (!copy_issuer(ctx, gens))
goto err;
} else {
GENERAL_NAME *gen = v2i_GENERAL_NAME(method, ctx, cnf);
if (gen == NULL)
goto err;
sk_GENERAL_NAME_push(gens, gen); /* no failure as it was reserved */
}
}
return gens;
err:
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
return NULL;
}
/* Append subject altname of issuer to issuer alt name of subject */
static int copy_issuer(X509V3_CTX *ctx, GENERAL_NAMES *gens)
{
GENERAL_NAMES *ialt;
GENERAL_NAME *gen;
X509_EXTENSION *ext;
int i, num;
if (ctx != NULL && (ctx->flags & X509V3_CTX_TEST) != 0)
return 1;
if (!ctx || !ctx->issuer_cert) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_NO_ISSUER_DETAILS);
goto err;
}
i = X509_get_ext_by_NID(ctx->issuer_cert, NID_subject_alt_name, -1);
if (i < 0)
return 1;
if ((ext = X509_get_ext(ctx->issuer_cert, i)) == NULL
|| (ialt = X509V3_EXT_d2i(ext)) == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_ISSUER_DECODE_ERROR);
goto err;
}
num = sk_GENERAL_NAME_num(ialt);
if (!sk_GENERAL_NAME_reserve(gens, num)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
for (i = 0; i < num; i++) {
gen = sk_GENERAL_NAME_value(ialt, i);
sk_GENERAL_NAME_push(gens, gen); /* no failure as it was reserved */
}
sk_GENERAL_NAME_free(ialt);
return 1;
err:
return 0;
}
static GENERAL_NAMES *v2i_subject_alt(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval)
{
GENERAL_NAMES *gens;
CONF_VALUE *cnf;
const int num = sk_CONF_VALUE_num(nval);
int i;
gens = sk_GENERAL_NAME_new_reserve(NULL, num);
if (gens == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
sk_GENERAL_NAME_free(gens);
return NULL;
}
for (i = 0; i < num; i++) {
cnf = sk_CONF_VALUE_value(nval, i);
if (ossl_v3_name_cmp(cnf->name, "email") == 0
&& cnf->value && strcmp(cnf->value, "copy") == 0) {
if (!copy_email(ctx, gens, 0))
goto err;
} else if (ossl_v3_name_cmp(cnf->name, "email") == 0
&& cnf->value && strcmp(cnf->value, "move") == 0) {
if (!copy_email(ctx, gens, 1))
goto err;
} else {
GENERAL_NAME *gen;
if ((gen = v2i_GENERAL_NAME(method, ctx, cnf)) == NULL)
goto err;
sk_GENERAL_NAME_push(gens, gen); /* no failure as it was reserved */
}
}
return gens;
err:
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
return NULL;
}
/*
* Copy any email addresses in a certificate or request to GENERAL_NAMES
*/
static int copy_email(X509V3_CTX *ctx, GENERAL_NAMES *gens, int move_p)
{
X509_NAME *nm;
ASN1_IA5STRING *email = NULL;
X509_NAME_ENTRY *ne;
GENERAL_NAME *gen = NULL;
int i = -1;
if (ctx != NULL && (ctx->flags & X509V3_CTX_TEST) != 0)
return 1;
if (ctx == NULL
|| (ctx->subject_cert == NULL && ctx->subject_req == NULL)) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_NO_SUBJECT_DETAILS);
return 0;
}
/* Find the subject name */
nm = ctx->subject_cert != NULL ?
X509_get_subject_name(ctx->subject_cert) :
X509_REQ_get_subject_name(ctx->subject_req);
/* Now add any email address(es) to STACK */
while ((i = X509_NAME_get_index_by_NID(nm,
NID_pkcs9_emailAddress, i)) >= 0) {
ne = X509_NAME_get_entry(nm, i);
email = ASN1_STRING_dup(X509_NAME_ENTRY_get_data(ne));
if (move_p) {
X509_NAME_delete_entry(nm, i);
X509_NAME_ENTRY_free(ne);
i--;
}
if (email == NULL || (gen = GENERAL_NAME_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
gen->d.ia5 = email;
email = NULL;
gen->type = GEN_EMAIL;
if (!sk_GENERAL_NAME_push(gens, gen)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
gen = NULL;
}
return 1;
err:
GENERAL_NAME_free(gen);
ASN1_IA5STRING_free(email);
return 0;
}
GENERAL_NAMES *v2i_GENERAL_NAMES(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval)
{
GENERAL_NAME *gen;
GENERAL_NAMES *gens;
CONF_VALUE *cnf;
const int num = sk_CONF_VALUE_num(nval);
int i;
gens = sk_GENERAL_NAME_new_reserve(NULL, num);
if (gens == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
sk_GENERAL_NAME_free(gens);
return NULL;
}
for (i = 0; i < num; i++) {
cnf = sk_CONF_VALUE_value(nval, i);
if ((gen = v2i_GENERAL_NAME(method, ctx, cnf)) == NULL)
goto err;
sk_GENERAL_NAME_push(gens, gen); /* no failure as it was reserved */
}
return gens;
err:
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
return NULL;
}
GENERAL_NAME *v2i_GENERAL_NAME(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, CONF_VALUE *cnf)
{
return v2i_GENERAL_NAME_ex(NULL, method, ctx, cnf, 0);
}
GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out,
const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, int gen_type, const char *value,
int is_nc)
{
char is_string = 0;
GENERAL_NAME *gen = NULL;
if (!value) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_MISSING_VALUE);
return NULL;
}
if (out)
gen = out;
else {
gen = GENERAL_NAME_new();
if (gen == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
return NULL;
}
}
switch (gen_type) {
case GEN_URI:
case GEN_EMAIL:
case GEN_DNS:
is_string = 1;
break;
case GEN_RID:
{
ASN1_OBJECT *obj;
if ((obj = OBJ_txt2obj(value, 0)) == NULL) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_BAD_OBJECT,
"value=%s", value);
goto err;
}
gen->d.rid = obj;
}
break;
case GEN_IPADD:
if (is_nc)
gen->d.ip = a2i_IPADDRESS_NC(value);
else
gen->d.ip = a2i_IPADDRESS(value);
if (gen->d.ip == NULL) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_BAD_IP_ADDRESS,
"value=%s", value);
goto err;
}
break;
case GEN_DIRNAME:
if (!do_dirname(gen, value, ctx)) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_DIRNAME_ERROR);
goto err;
}
break;
case GEN_OTHERNAME:
if (!do_othername(gen, value, ctx)) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_OTHERNAME_ERROR);
goto err;
}
break;
default:
ERR_raise(ERR_LIB_X509V3, X509V3_R_UNSUPPORTED_TYPE);
goto err;
}
if (is_string) {
if ((gen->d.ia5 = ASN1_IA5STRING_new()) == NULL ||
!ASN1_STRING_set(gen->d.ia5, (unsigned char *)value,
strlen(value))) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
}
gen->type = gen_type;
return gen;
err:
if (!out)
GENERAL_NAME_free(gen);
return NULL;
}
GENERAL_NAME *v2i_GENERAL_NAME_ex(GENERAL_NAME *out,
const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, CONF_VALUE *cnf, int is_nc)
{
int type;
char *name, *value;
name = cnf->name;
value = cnf->value;
if (!value) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_MISSING_VALUE);
return NULL;
}
if (!ossl_v3_name_cmp(name, "email"))
type = GEN_EMAIL;
else if (!ossl_v3_name_cmp(name, "URI"))
type = GEN_URI;
else if (!ossl_v3_name_cmp(name, "DNS"))
type = GEN_DNS;
else if (!ossl_v3_name_cmp(name, "RID"))
type = GEN_RID;
else if (!ossl_v3_name_cmp(name, "IP"))
type = GEN_IPADD;
else if (!ossl_v3_name_cmp(name, "dirName"))
type = GEN_DIRNAME;
else if (!ossl_v3_name_cmp(name, "otherName"))
type = GEN_OTHERNAME;
else {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_UNSUPPORTED_OPTION,
"name=%s", name);
return NULL;
}
return a2i_GENERAL_NAME(out, method, ctx, type, value, is_nc);
}
static int do_othername(GENERAL_NAME *gen, const char *value, X509V3_CTX *ctx)
{
char *objtmp = NULL, *p;
int objlen;
if ((p = strchr(value, ';')) == NULL)
return 0;
if ((gen->d.otherName = OTHERNAME_new()) == NULL)
return 0;
/*
* Free this up because we will overwrite it. no need to free type_id
* because it is static
*/
ASN1_TYPE_free(gen->d.otherName->value);
if ((gen->d.otherName->value = ASN1_generate_v3(p + 1, ctx)) == NULL)
return 0;
objlen = p - value;
objtmp = OPENSSL_strndup(value, objlen);
if (objtmp == NULL)
return 0;
gen->d.otherName->type_id = OBJ_txt2obj(objtmp, 0);
OPENSSL_free(objtmp);
if (!gen->d.otherName->type_id)
return 0;
return 1;
}
static int do_dirname(GENERAL_NAME *gen, const char *value, X509V3_CTX *ctx)
{
int ret = 0;
STACK_OF(CONF_VALUE) *sk = NULL;
X509_NAME *nm;
if ((nm = X509_NAME_new()) == NULL)
goto err;
sk = X509V3_get_section(ctx, value);
if (!sk) {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_SECTION_NOT_FOUND,
"section=%s", value);
goto err;
}
/* FIXME: should allow other character types... */
ret = X509V3_NAME_from_section(nm, sk, MBSTRING_ASC);
if (!ret)
goto err;
gen->d.dirn = nm;
err:
if (ret == 0)
X509_NAME_free(nm);
X509V3_section_free(ctx, sk);
return ret;
}
| 21,737 | 30.413295 | 85 |
c
|
openssl
|
openssl-master/crypto/x509/v3_skid.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/x509v3.h>
#include "crypto/x509.h"
#include "ext_dat.h"
static ASN1_OCTET_STRING *s2i_skey_id(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, char *str);
const X509V3_EXT_METHOD ossl_v3_skey_id = {
NID_subject_key_identifier, 0, ASN1_ITEM_ref(ASN1_OCTET_STRING),
0, 0, 0, 0,
(X509V3_EXT_I2S)i2s_ASN1_OCTET_STRING,
(X509V3_EXT_S2I)s2i_skey_id,
0, 0, 0, 0,
NULL
};
char *i2s_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method,
const ASN1_OCTET_STRING *oct)
{
return OPENSSL_buf2hexstr(oct->data, oct->length);
}
ASN1_OCTET_STRING *s2i_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, const char *str)
{
ASN1_OCTET_STRING *oct;
long length;
if ((oct = ASN1_OCTET_STRING_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
return NULL;
}
if ((oct->data = OPENSSL_hexstr2buf(str, &length)) == NULL) {
ASN1_OCTET_STRING_free(oct);
return NULL;
}
oct->length = length;
return oct;
}
ASN1_OCTET_STRING *ossl_x509_pubkey_hash(X509_PUBKEY *pubkey)
{
ASN1_OCTET_STRING *oct;
const unsigned char *pk;
int pklen;
unsigned char pkey_dig[EVP_MAX_MD_SIZE];
unsigned int diglen;
const char *propq;
OSSL_LIB_CTX *libctx;
EVP_MD *md;
if (pubkey == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_NO_PUBLIC_KEY);
return NULL;
}
if (!ossl_x509_PUBKEY_get0_libctx(&libctx, &propq, pubkey))
return NULL;
if ((md = EVP_MD_fetch(libctx, SN_sha1, propq)) == NULL)
return NULL;
if ((oct = ASN1_OCTET_STRING_new()) == NULL) {
EVP_MD_free(md);
return NULL;
}
X509_PUBKEY_get0_param(NULL, &pk, &pklen, NULL, pubkey);
if (EVP_Digest(pk, pklen, pkey_dig, &diglen, md, NULL)
&& ASN1_OCTET_STRING_set(oct, pkey_dig, diglen)) {
EVP_MD_free(md);
return oct;
}
EVP_MD_free(md);
ASN1_OCTET_STRING_free(oct);
return NULL;
}
static ASN1_OCTET_STRING *s2i_skey_id(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, char *str)
{
if (strcmp(str, "none") == 0)
return ASN1_OCTET_STRING_new(); /* dummy */
if (strcmp(str, "hash") != 0)
return s2i_ASN1_OCTET_STRING(method, ctx /* not used */, str);
if (ctx != NULL && (ctx->flags & X509V3_CTX_TEST) != 0)
return ASN1_OCTET_STRING_new();
if (ctx == NULL
|| (ctx->subject_cert == NULL && ctx->subject_req == NULL)) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_NO_SUBJECT_DETAILS);
return NULL;
}
return ossl_x509_pubkey_hash(ctx->subject_cert != NULL ?
ctx->subject_cert->cert_info.key :
ctx->subject_req->req_info.pubkey);
}
| 3,272 | 28.223214 | 74 |
c
|
openssl
|
openssl-master/crypto/x509/v3_sxnet.c
|
/*
* Copyright 1999-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
/* Support for Thawte strong extranet extension */
#define SXNET_TEST
static int sxnet_i2r(X509V3_EXT_METHOD *method, SXNET *sx, BIO *out,
int indent);
#ifdef SXNET_TEST
static SXNET *sxnet_v2i(X509V3_EXT_METHOD *method, X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval);
#endif
const X509V3_EXT_METHOD ossl_v3_sxnet = {
NID_sxnet, X509V3_EXT_MULTILINE, ASN1_ITEM_ref(SXNET),
0, 0, 0, 0,
0, 0,
0,
#ifdef SXNET_TEST
(X509V3_EXT_V2I)sxnet_v2i,
#else
0,
#endif
(X509V3_EXT_I2R)sxnet_i2r,
0,
NULL
};
ASN1_SEQUENCE(SXNETID) = {
ASN1_SIMPLE(SXNETID, zone, ASN1_INTEGER),
ASN1_SIMPLE(SXNETID, user, ASN1_OCTET_STRING)
} ASN1_SEQUENCE_END(SXNETID)
IMPLEMENT_ASN1_FUNCTIONS(SXNETID)
ASN1_SEQUENCE(SXNET) = {
ASN1_SIMPLE(SXNET, version, ASN1_INTEGER),
ASN1_SEQUENCE_OF(SXNET, ids, SXNETID)
} ASN1_SEQUENCE_END(SXNET)
IMPLEMENT_ASN1_FUNCTIONS(SXNET)
static int sxnet_i2r(X509V3_EXT_METHOD *method, SXNET *sx, BIO *out,
int indent)
{
int64_t v;
char *tmp;
SXNETID *id;
int i;
/*
* Since we add 1 to the version number to display it, we don't support
* LONG_MAX since that would cause on overflow.
*/
if (!ASN1_INTEGER_get_int64(&v, sx->version)
|| v >= LONG_MAX
|| v < LONG_MIN) {
BIO_printf(out, "%*sVersion: <unsupported>", indent, "");
} else {
long vl = (long)v;
BIO_printf(out, "%*sVersion: %ld (0x%lX)", indent, "", vl + 1, vl);
}
for (i = 0; i < sk_SXNETID_num(sx->ids); i++) {
id = sk_SXNETID_value(sx->ids, i);
tmp = i2s_ASN1_INTEGER(NULL, id->zone);
if (tmp == NULL)
return 0;
BIO_printf(out, "\n%*sZone: %s, User: ", indent, "", tmp);
OPENSSL_free(tmp);
ASN1_STRING_print(out, id->user);
}
return 1;
}
#ifdef SXNET_TEST
/*
* NBB: this is used for testing only. It should *not* be used for anything
* else because it will just take static IDs from the configuration file and
* they should really be separate values for each user.
*/
static SXNET *sxnet_v2i(X509V3_EXT_METHOD *method, X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval)
{
CONF_VALUE *cnf;
SXNET *sx = NULL;
int i;
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
cnf = sk_CONF_VALUE_value(nval, i);
if (!SXNET_add_id_asc(&sx, cnf->name, cnf->value, -1))
return NULL;
}
return sx;
}
#endif
/* Strong Extranet utility functions */
/* Add an id given the zone as an ASCII number */
int SXNET_add_id_asc(SXNET **psx, const char *zone, const char *user, int userlen)
{
ASN1_INTEGER *izone;
if ((izone = s2i_ASN1_INTEGER(NULL, zone)) == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_ERROR_CONVERTING_ZONE);
return 0;
}
return SXNET_add_id_INTEGER(psx, izone, user, userlen);
}
/* Add an id given the zone as an unsigned long */
int SXNET_add_id_ulong(SXNET **psx, unsigned long lzone, const char *user,
int userlen)
{
ASN1_INTEGER *izone;
if ((izone = ASN1_INTEGER_new()) == NULL
|| !ASN1_INTEGER_set(izone, lzone)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
ASN1_INTEGER_free(izone);
return 0;
}
return SXNET_add_id_INTEGER(psx, izone, user, userlen);
}
/*
* Add an id given the zone as an ASN1_INTEGER. Note this version uses the
* passed integer and doesn't make a copy so don't free it up afterwards.
*/
int SXNET_add_id_INTEGER(SXNET **psx, ASN1_INTEGER *zone, const char *user,
int userlen)
{
SXNET *sx = NULL;
SXNETID *id = NULL;
if (psx == NULL || zone == NULL || user == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NULL_ARGUMENT);
return 0;
}
if (userlen == -1)
userlen = strlen(user);
if (userlen > 64) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_USER_TOO_LONG);
return 0;
}
if (*psx == NULL) {
if ((sx = SXNET_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
if (!ASN1_INTEGER_set(sx->version, 0)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
} else
sx = *psx;
if (SXNET_get_id_INTEGER(sx, zone)) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_DUPLICATE_ZONE_ID);
if (*psx == NULL)
SXNET_free(sx);
return 0;
}
if ((id = SXNETID_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
if (!ASN1_OCTET_STRING_set(id->user, (const unsigned char *)user, userlen)){
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
if (!sk_SXNETID_push(sx->ids, id)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
id->zone = zone;
*psx = sx;
return 1;
err:
SXNETID_free(id);
if (*psx == NULL)
SXNET_free(sx);
return 0;
}
ASN1_OCTET_STRING *SXNET_get_id_asc(SXNET *sx, const char *zone)
{
ASN1_INTEGER *izone;
ASN1_OCTET_STRING *oct;
if ((izone = s2i_ASN1_INTEGER(NULL, zone)) == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_ERROR_CONVERTING_ZONE);
return NULL;
}
oct = SXNET_get_id_INTEGER(sx, izone);
ASN1_INTEGER_free(izone);
return oct;
}
ASN1_OCTET_STRING *SXNET_get_id_ulong(SXNET *sx, unsigned long lzone)
{
ASN1_INTEGER *izone;
ASN1_OCTET_STRING *oct;
if ((izone = ASN1_INTEGER_new()) == NULL
|| !ASN1_INTEGER_set(izone, lzone)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
ASN1_INTEGER_free(izone);
return NULL;
}
oct = SXNET_get_id_INTEGER(sx, izone);
ASN1_INTEGER_free(izone);
return oct;
}
ASN1_OCTET_STRING *SXNET_get_id_INTEGER(SXNET *sx, ASN1_INTEGER *zone)
{
SXNETID *id;
int i;
for (i = 0; i < sk_SXNETID_num(sx->ids); i++) {
id = sk_SXNETID_value(sx->ids, i);
if (!ASN1_INTEGER_cmp(id->zone, zone))
return id->user;
}
return NULL;
}
| 6,667 | 25.672 | 82 |
c
|
openssl
|
openssl-master/crypto/x509/v3_tlsf.c
|
/*
* Copyright 2015-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/e_os.h"
#include "internal/cryptlib.h"
#include <stdio.h>
#include <openssl/asn1t.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
#include "x509_local.h"
static STACK_OF(CONF_VALUE) *i2v_TLS_FEATURE(const X509V3_EXT_METHOD *method,
TLS_FEATURE *tls_feature,
STACK_OF(CONF_VALUE) *ext_list);
static TLS_FEATURE *v2i_TLS_FEATURE(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx,
STACK_OF(CONF_VALUE) *nval);
ASN1_ITEM_TEMPLATE(TLS_FEATURE) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, TLS_FEATURE, ASN1_INTEGER)
static_ASN1_ITEM_TEMPLATE_END(TLS_FEATURE)
IMPLEMENT_ASN1_ALLOC_FUNCTIONS(TLS_FEATURE)
const X509V3_EXT_METHOD ossl_v3_tls_feature = {
NID_tlsfeature, 0,
ASN1_ITEM_ref(TLS_FEATURE),
0, 0, 0, 0,
0, 0,
(X509V3_EXT_I2V)i2v_TLS_FEATURE,
(X509V3_EXT_V2I)v2i_TLS_FEATURE,
0, 0,
NULL
};
typedef struct {
long num;
const char *name;
} TLS_FEATURE_NAME;
static TLS_FEATURE_NAME tls_feature_tbl[] = {
{ 5, "status_request" },
{ 17, "status_request_v2" }
};
/*
* i2v_TLS_FEATURE converts the TLS_FEATURE structure tls_feature into the
* STACK_OF(CONF_VALUE) structure ext_list. STACK_OF(CONF_VALUE) is the format
* used by the CONF library to represent a multi-valued extension. ext_list is
* returned.
*/
static STACK_OF(CONF_VALUE) *i2v_TLS_FEATURE(const X509V3_EXT_METHOD *method,
TLS_FEATURE *tls_feature,
STACK_OF(CONF_VALUE) *ext_list)
{
int i;
size_t j;
ASN1_INTEGER *ai;
long tlsextid;
for (i = 0; i < sk_ASN1_INTEGER_num(tls_feature); i++) {
ai = sk_ASN1_INTEGER_value(tls_feature, i);
tlsextid = ASN1_INTEGER_get(ai);
for (j = 0; j < OSSL_NELEM(tls_feature_tbl); j++)
if (tlsextid == tls_feature_tbl[j].num)
break;
if (j < OSSL_NELEM(tls_feature_tbl))
X509V3_add_value(NULL, tls_feature_tbl[j].name, &ext_list);
else
X509V3_add_value_int(NULL, ai, &ext_list);
}
return ext_list;
}
/*
* v2i_TLS_FEATURE converts the multi-valued extension nval into a TLS_FEATURE
* structure, which is returned if the conversion is successful. In case of
* error, NULL is returned.
*/
static TLS_FEATURE *v2i_TLS_FEATURE(const X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval)
{
TLS_FEATURE *tlsf;
char *extval, *endptr;
ASN1_INTEGER *ai = NULL;
CONF_VALUE *val;
int i;
size_t j;
long tlsextid;
if ((tlsf = sk_ASN1_INTEGER_new_null()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(nval); i++) {
val = sk_CONF_VALUE_value(nval, i);
if (val->value)
extval = val->value;
else
extval = val->name;
for (j = 0; j < OSSL_NELEM(tls_feature_tbl); j++)
if (OPENSSL_strcasecmp(extval, tls_feature_tbl[j].name) == 0)
break;
if (j < OSSL_NELEM(tls_feature_tbl))
tlsextid = tls_feature_tbl[j].num;
else {
tlsextid = strtol(extval, &endptr, 10);
if (((*endptr) != '\0') || (extval == endptr) || (tlsextid < 0) ||
(tlsextid > 65535)) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_SYNTAX);
X509V3_conf_add_error_name_value(val);
goto err;
}
}
if ((ai = ASN1_INTEGER_new()) == NULL
|| !ASN1_INTEGER_set(ai, tlsextid)
|| sk_ASN1_INTEGER_push(tlsf, ai) <= 0) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
/* So it doesn't get purged if an error occurs next time around */
ai = NULL;
}
return tlsf;
err:
sk_ASN1_INTEGER_pop_free(tlsf, ASN1_INTEGER_free);
ASN1_INTEGER_free(ai);
return NULL;
}
| 4,519 | 31.056738 | 82 |
c
|
openssl
|
openssl-master/crypto/x509/v3_utf8.c
|
/*
* Copyright 2020-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
#include "ext_dat.h"
/*
* Subject Sign Tool (1.2.643.100.111) The name of the tool used to signs the subject (UTF8String)
* This extension is required to obtain the status of a qualified certificate at Russian Federation.
* RFC-style description is available here: https://tools.ietf.org/html/draft-deremin-rfc4491-bis-04#section-5
* Russian Federal Law 63 "Digital Sign" is available here: http://www.consultant.ru/document/cons_doc_LAW_112701/
*/
const X509V3_EXT_METHOD ossl_v3_utf8_list[1] = {
EXT_UTF8STRING(NID_subjectSignTool),
};
char *i2s_ASN1_UTF8STRING(X509V3_EXT_METHOD *method,
ASN1_UTF8STRING *utf8)
{
char *tmp;
if (utf8 == NULL || utf8->length == 0) {
ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if ((tmp = OPENSSL_malloc(utf8->length + 1)) == NULL)
return NULL;
memcpy(tmp, utf8->data, utf8->length);
tmp[utf8->length] = 0;
return tmp;
}
ASN1_UTF8STRING *s2i_ASN1_UTF8STRING(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, const char *str)
{
ASN1_UTF8STRING *utf8;
if (str == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NULL_ARGUMENT);
return NULL;
}
if ((utf8 = ASN1_UTF8STRING_new()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
return NULL;
}
if (!ASN1_STRING_set((ASN1_STRING *)utf8, str, strlen(str))) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
ASN1_UTF8STRING_free(utf8);
return NULL;
}
#ifdef CHARSET_EBCDIC
ebcdic2ascii(utf8->data, utf8->data, utf8->length);
#endif /* CHARSET_EBCDIC */
return utf8;
}
| 2,183 | 31.597015 | 115 |
c
|
openssl
|
openssl-master/crypto/x509/v3err.c
|
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/err.h>
#include <openssl/x509v3err.h>
#include "crypto/x509v3err.h"
#ifndef OPENSSL_NO_ERR
static const ERR_STRING_DATA X509V3_str_reasons[] = {
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_BAD_IP_ADDRESS), "bad ip address"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_BAD_OBJECT), "bad object"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_BAD_OPTION), "bad option"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_BAD_VALUE), "bad value"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_BN_DEC2BN_ERROR), "bn dec2bn error"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_BN_TO_ASN1_INTEGER_ERROR),
"bn to asn1 integer error"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_DIRNAME_ERROR), "dirname error"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_DISTPOINT_ALREADY_SET),
"distpoint already set"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_DUPLICATE_ZONE_ID),
"duplicate zone id"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EMPTY_KEY_USAGE), "empty key usage"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_ERROR_CONVERTING_ZONE),
"error converting zone"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_ERROR_CREATING_EXTENSION),
"error creating extension"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_ERROR_IN_EXTENSION),
"error in extension"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EXPECTED_A_SECTION_NAME),
"expected a section name"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EXTENSION_EXISTS),
"extension exists"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EXTENSION_NAME_ERROR),
"extension name error"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EXTENSION_NOT_FOUND),
"extension not found"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EXTENSION_SETTING_NOT_SUPPORTED),
"extension setting not supported"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_EXTENSION_VALUE_ERROR),
"extension value error"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_ILLEGAL_EMPTY_EXTENSION),
"illegal empty extension"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INCORRECT_POLICY_SYNTAX_TAG),
"incorrect policy syntax tag"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_ASNUMBER),
"invalid asnumber"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_ASRANGE), "invalid asrange"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_BOOLEAN_STRING),
"invalid boolean string"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_CERTIFICATE),
"invalid certificate"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_EMPTY_NAME),
"invalid empty name"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_EXTENSION_STRING),
"invalid extension string"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_INHERITANCE),
"invalid inheritance"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_IPADDRESS),
"invalid ipaddress"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_MULTIPLE_RDNS),
"invalid multiple rdns"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_NAME), "invalid name"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_NULL_ARGUMENT),
"invalid null argument"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_NULL_VALUE),
"invalid null value"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_NUMBER), "invalid number"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_NUMBERS), "invalid numbers"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_OBJECT_IDENTIFIER),
"invalid object identifier"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_OPTION), "invalid option"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_POLICY_IDENTIFIER),
"invalid policy identifier"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_PROXY_POLICY_SETTING),
"invalid proxy policy setting"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_PURPOSE), "invalid purpose"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_SAFI), "invalid safi"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_SECTION), "invalid section"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_INVALID_SYNTAX), "invalid syntax"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_ISSUER_DECODE_ERROR),
"issuer decode error"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_MISSING_VALUE), "missing value"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NEED_ORGANIZATION_AND_NUMBERS),
"need organization and numbers"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NEGATIVE_PATHLEN),
"negative pathlen"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_CONFIG_DATABASE),
"no config database"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_ISSUER_CERTIFICATE),
"no issuer certificate"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_ISSUER_DETAILS),
"no issuer details"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_POLICY_IDENTIFIER),
"no policy identifier"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_PROXY_CERT_POLICY_LANGUAGE_DEFINED),
"no proxy cert policy language defined"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_PUBLIC_KEY), "no public key"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_NO_SUBJECT_DETAILS),
"no subject details"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_OPERATION_NOT_DEFINED),
"operation not defined"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_OTHERNAME_ERROR), "othername error"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_POLICY_LANGUAGE_ALREADY_DEFINED),
"policy language already defined"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_POLICY_PATH_LENGTH),
"policy path length"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_POLICY_PATH_LENGTH_ALREADY_DEFINED),
"policy path length already defined"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_POLICY_WHEN_PROXY_LANGUAGE_REQUIRES_NO_POLICY),
"policy when proxy language requires no policy"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_SECTION_NOT_FOUND),
"section not found"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS),
"unable to get issuer details"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNABLE_TO_GET_ISSUER_KEYID),
"unable to get issuer keyid"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNKNOWN_BIT_STRING_ARGUMENT),
"unknown bit string argument"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNKNOWN_EXTENSION),
"unknown extension"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNKNOWN_EXTENSION_NAME),
"unknown extension name"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNKNOWN_OPTION), "unknown option"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNKNOWN_VALUE), "unknown value"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNSUPPORTED_OPTION),
"unsupported option"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_UNSUPPORTED_TYPE),
"unsupported type"},
{ERR_PACK(ERR_LIB_X509V3, 0, X509V3_R_USER_TOO_LONG), "user too long"},
{0, NULL}
};
#endif
int ossl_err_load_X509V3_strings(void)
{
#ifndef OPENSSL_NO_ERR
if (ERR_reason_error_string(X509V3_str_reasons[0].error) == NULL)
ERR_load_strings_const(X509V3_str_reasons);
#endif
return 1;
}
| 7,297 | 47.331126 | 89 |
c
|
openssl
|
openssl-master/crypto/x509/x509_att.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/safestack.h>
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "crypto/x509.h"
#include "x509_local.h"
int X509at_get_attr_count(const STACK_OF(X509_ATTRIBUTE) *x)
{
return sk_X509_ATTRIBUTE_num(x);
}
int X509at_get_attr_by_NID(const STACK_OF(X509_ATTRIBUTE) *x, int nid,
int lastpos)
{
const ASN1_OBJECT *obj = OBJ_nid2obj(nid);
if (obj == NULL)
return -2;
return X509at_get_attr_by_OBJ(x, obj, lastpos);
}
int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk,
const ASN1_OBJECT *obj, int lastpos)
{
int n;
X509_ATTRIBUTE *ex;
if (sk == NULL)
return -1;
lastpos++;
if (lastpos < 0)
lastpos = 0;
n = sk_X509_ATTRIBUTE_num(sk);
for (; lastpos < n; lastpos++) {
ex = sk_X509_ATTRIBUTE_value(sk, lastpos);
if (OBJ_cmp(ex->object, obj) == 0)
return lastpos;
}
return -1;
}
X509_ATTRIBUTE *X509at_get_attr(const STACK_OF(X509_ATTRIBUTE) *x, int loc)
{
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (sk_X509_ATTRIBUTE_num(x) <= loc || loc < 0) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_INVALID_ARGUMENT);
return NULL;
}
return sk_X509_ATTRIBUTE_value(x, loc);
}
X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc)
{
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (sk_X509_ATTRIBUTE_num(x) <= loc || loc < 0) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_INVALID_ARGUMENT);
return NULL;
}
return sk_X509_ATTRIBUTE_delete(x, loc);
}
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x,
X509_ATTRIBUTE *attr)
{
X509_ATTRIBUTE *new_attr = NULL;
STACK_OF(X509_ATTRIBUTE) *sk = NULL;
if (x == NULL || attr == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (X509at_get_attr_by_OBJ(sk, attr->object, -1) != -1) {
ERR_raise(ERR_LIB_X509, X509_R_DUPLICATE_ATTRIBUTE);
return NULL;
}
if (*x == NULL) {
if ((sk = sk_X509_ATTRIBUTE_new_null()) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
}
} else {
sk = *x;
}
if ((new_attr = X509_ATTRIBUTE_dup(attr)) == NULL)
goto err;
if (!sk_X509_ATTRIBUTE_push(sk, new_attr)) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
}
if (*x == NULL)
*x = sk;
return sk;
err:
X509_ATTRIBUTE_free(new_attr);
if (*x == NULL)
sk_X509_ATTRIBUTE_free(sk);
return NULL;
}
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_OBJ(STACK_OF(X509_ATTRIBUTE)
**x, const ASN1_OBJECT *obj,
int type,
const unsigned char *bytes,
int len)
{
X509_ATTRIBUTE *attr;
STACK_OF(X509_ATTRIBUTE) *ret;
attr = X509_ATTRIBUTE_create_by_OBJ(NULL, obj, type, bytes, len);
if (attr == NULL)
return 0;
ret = X509at_add1_attr(x, attr);
X509_ATTRIBUTE_free(attr);
return ret;
}
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_NID(STACK_OF(X509_ATTRIBUTE)
**x, int nid, int type,
const unsigned char *bytes,
int len)
{
X509_ATTRIBUTE *attr;
STACK_OF(X509_ATTRIBUTE) *ret;
attr = X509_ATTRIBUTE_create_by_NID(NULL, nid, type, bytes, len);
if (attr == NULL)
return 0;
ret = X509at_add1_attr(x, attr);
X509_ATTRIBUTE_free(attr);
return ret;
}
STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_txt(STACK_OF(X509_ATTRIBUTE)
**x, const char *attrname,
int type,
const unsigned char *bytes,
int len)
{
X509_ATTRIBUTE *attr;
STACK_OF(X509_ATTRIBUTE) *ret;
attr = X509_ATTRIBUTE_create_by_txt(NULL, attrname, type, bytes, len);
if (attr == NULL)
return 0;
ret = X509at_add1_attr(x, attr);
X509_ATTRIBUTE_free(attr);
return ret;
}
void *X509at_get0_data_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *x,
const ASN1_OBJECT *obj, int lastpos, int type)
{
int i = X509at_get_attr_by_OBJ(x, obj, lastpos);
X509_ATTRIBUTE *at;
if (i == -1)
return NULL;
if (lastpos <= -2 && X509at_get_attr_by_OBJ(x, obj, i) != -1)
return NULL;
at = X509at_get_attr(x, i);
if (lastpos <= -3 && X509_ATTRIBUTE_count(at) != 1)
return NULL;
return X509_ATTRIBUTE_get0_data(at, 0, type, NULL);
}
STACK_OF(X509_ATTRIBUTE) *ossl_x509at_dup(const STACK_OF(X509_ATTRIBUTE) *x)
{
int i, n = sk_X509_ATTRIBUTE_num(x);
STACK_OF(X509_ATTRIBUTE) *sk = NULL;
for (i = 0; i < n; ++i) {
if (X509at_add1_attr(&sk, sk_X509_ATTRIBUTE_value(x, i)) == NULL) {
sk_X509_ATTRIBUTE_pop_free(sk, X509_ATTRIBUTE_free);
return NULL;
}
}
return sk;
}
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **attr, int nid,
int atrtype, const void *data,
int len)
{
ASN1_OBJECT *obj = OBJ_nid2obj(nid);
X509_ATTRIBUTE *ret;
if (obj == NULL) {
ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_NID);
return NULL;
}
ret = X509_ATTRIBUTE_create_by_OBJ(attr, obj, atrtype, data, len);
if (ret == NULL)
ASN1_OBJECT_free(obj);
return ret;
}
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr,
const ASN1_OBJECT *obj,
int atrtype, const void *data,
int len)
{
X509_ATTRIBUTE *ret;
if (attr == NULL || *attr == NULL) {
if ((ret = X509_ATTRIBUTE_new()) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
return NULL;
}
} else {
ret = *attr;
}
if (!X509_ATTRIBUTE_set1_object(ret, obj))
goto err;
if (!X509_ATTRIBUTE_set1_data(ret, atrtype, data, len))
goto err;
if (attr != NULL && *attr == NULL)
*attr = ret;
return ret;
err:
if (attr == NULL || ret != *attr)
X509_ATTRIBUTE_free(ret);
return NULL;
}
X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr,
const char *atrname, int type,
const unsigned char *bytes,
int len)
{
ASN1_OBJECT *obj = OBJ_txt2obj(atrname, 0);
X509_ATTRIBUTE *nattr;
if (obj == NULL) {
ERR_raise_data(ERR_LIB_X509, X509_R_INVALID_FIELD_NAME,
"name=%s", atrname);
return NULL;
}
nattr = X509_ATTRIBUTE_create_by_OBJ(attr, obj, type, bytes, len);
ASN1_OBJECT_free(obj);
return nattr;
}
int X509_ATTRIBUTE_set1_object(X509_ATTRIBUTE *attr, const ASN1_OBJECT *obj)
{
if (attr == NULL || obj == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
ASN1_OBJECT_free(attr->object);
attr->object = OBJ_dup(obj);
return attr->object != NULL;
}
int X509_ATTRIBUTE_set1_data(X509_ATTRIBUTE *attr, int attrtype,
const void *data, int len)
{
ASN1_TYPE *ttmp = NULL;
ASN1_STRING *stmp = NULL;
int atype = 0;
if (attr == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if ((attrtype & MBSTRING_FLAG) != 0) {
stmp = ASN1_STRING_set_by_NID(NULL, data, len, attrtype,
OBJ_obj2nid(attr->object));
if (stmp == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
return 0;
}
atype = stmp->type;
} else if (len != -1) {
if ((stmp = ASN1_STRING_type_new(attrtype)) == NULL
|| !ASN1_STRING_set(stmp, data, len)) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
goto err;
}
atype = attrtype;
}
/*
* This is a bit naughty because the attribute should really have at
* least one value but some types use and zero length SET and require
* this.
*/
if (attrtype == 0) {
ASN1_STRING_free(stmp);
return 1;
}
if ((ttmp = ASN1_TYPE_new()) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
goto err;
}
if (len == -1 && (attrtype & MBSTRING_FLAG) == 0) {
if (!ASN1_TYPE_set1(ttmp, attrtype, data)) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
goto err;
}
} else {
ASN1_TYPE_set(ttmp, atype, stmp);
stmp = NULL;
}
if (!sk_ASN1_TYPE_push(attr->set, ttmp)) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
}
return 1;
err:
ASN1_TYPE_free(ttmp);
ASN1_STRING_free(stmp);
return 0;
}
int X509_ATTRIBUTE_count(const X509_ATTRIBUTE *attr)
{
if (attr == NULL)
return 0;
return sk_ASN1_TYPE_num(attr->set);
}
ASN1_OBJECT *X509_ATTRIBUTE_get0_object(X509_ATTRIBUTE *attr)
{
if (attr == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
return attr->object;
}
void *X509_ATTRIBUTE_get0_data(X509_ATTRIBUTE *attr, int idx,
int atrtype, void *data)
{
ASN1_TYPE *ttmp = X509_ATTRIBUTE_get0_type(attr, idx);
if (ttmp == NULL)
return NULL;
if (atrtype == V_ASN1_BOOLEAN
|| atrtype == V_ASN1_NULL
|| atrtype != ASN1_TYPE_get(ttmp)) {
ERR_raise(ERR_LIB_X509, X509_R_WRONG_TYPE);
return NULL;
}
return ttmp->value.ptr;
}
ASN1_TYPE *X509_ATTRIBUTE_get0_type(X509_ATTRIBUTE *attr, int idx)
{
if (attr == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
return sk_ASN1_TYPE_value(attr->set, idx);
}
| 11,010 | 28.12963 | 78 |
c
|
openssl
|
openssl-master/crypto/x509/x509_cmp.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/core_names.h>
#include "crypto/x509.h"
int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b)
{
int i;
const X509_CINF *ai, *bi;
if (b == NULL)
return a != NULL;
if (a == NULL)
return -1;
ai = &a->cert_info;
bi = &b->cert_info;
i = ASN1_INTEGER_cmp(&ai->serialNumber, &bi->serialNumber);
if (i != 0)
return i < 0 ? -1 : 1;
return X509_NAME_cmp(ai->issuer, bi->issuer);
}
#ifndef OPENSSL_NO_MD5
unsigned long X509_issuer_and_serial_hash(X509 *a)
{
unsigned long ret = 0;
EVP_MD_CTX *ctx = EVP_MD_CTX_new();
unsigned char md[16];
char *f = NULL;
EVP_MD *digest = NULL;
if (ctx == NULL)
goto err;
f = X509_NAME_oneline(a->cert_info.issuer, NULL, 0);
if (f == NULL)
goto err;
digest = EVP_MD_fetch(a->libctx, SN_md5, a->propq);
if (digest == NULL)
goto err;
if (!EVP_DigestInit_ex(ctx, digest, NULL))
goto err;
if (!EVP_DigestUpdate(ctx, (unsigned char *)f, strlen(f)))
goto err;
if (!EVP_DigestUpdate
(ctx, (unsigned char *)a->cert_info.serialNumber.data,
(unsigned long)a->cert_info.serialNumber.length))
goto err;
if (!EVP_DigestFinal_ex(ctx, &(md[0]), NULL))
goto err;
ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) |
((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L)
) & 0xffffffffL;
err:
OPENSSL_free(f);
EVP_MD_free(digest);
EVP_MD_CTX_free(ctx);
return ret;
}
#endif
int X509_issuer_name_cmp(const X509 *a, const X509 *b)
{
return X509_NAME_cmp(a->cert_info.issuer, b->cert_info.issuer);
}
int X509_subject_name_cmp(const X509 *a, const X509 *b)
{
return X509_NAME_cmp(a->cert_info.subject, b->cert_info.subject);
}
int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b)
{
return X509_NAME_cmp(a->crl.issuer, b->crl.issuer);
}
int X509_CRL_match(const X509_CRL *a, const X509_CRL *b)
{
int rv;
if ((a->flags & EXFLAG_NO_FINGERPRINT) == 0
&& (b->flags & EXFLAG_NO_FINGERPRINT) == 0)
rv = memcmp(a->sha1_hash, b->sha1_hash, SHA_DIGEST_LENGTH);
else
return -2;
return rv < 0 ? -1 : rv > 0;
}
X509_NAME *X509_get_issuer_name(const X509 *a)
{
return a->cert_info.issuer;
}
unsigned long X509_issuer_name_hash(X509 *x)
{
return X509_NAME_hash_ex(x->cert_info.issuer, NULL, NULL, NULL);
}
#ifndef OPENSSL_NO_MD5
unsigned long X509_issuer_name_hash_old(X509 *x)
{
return X509_NAME_hash_old(x->cert_info.issuer);
}
#endif
X509_NAME *X509_get_subject_name(const X509 *a)
{
return a->cert_info.subject;
}
ASN1_INTEGER *X509_get_serialNumber(X509 *a)
{
return &a->cert_info.serialNumber;
}
const ASN1_INTEGER *X509_get0_serialNumber(const X509 *a)
{
return &a->cert_info.serialNumber;
}
unsigned long X509_subject_name_hash(X509 *x)
{
return X509_NAME_hash_ex(x->cert_info.subject, NULL, NULL, NULL);
}
#ifndef OPENSSL_NO_MD5
unsigned long X509_subject_name_hash_old(X509 *x)
{
return X509_NAME_hash_old(x->cert_info.subject);
}
#endif
/*
* Compare two certificates: they must be identical for this to work. NB:
* Although "cmp" operations are generally prototyped to take "const"
* arguments (eg. for use in STACKs), the way X509 handling is - these
* operations may involve ensuring the hashes are up-to-date and ensuring
* certain cert information is cached. So this is the point where the
* "depth-first" constification tree has to halt with an evil cast.
*/
int X509_cmp(const X509 *a, const X509 *b)
{
int rv = 0;
if (a == b) /* for efficiency */
return 0;
/* attempt to compute cert hash */
(void)X509_check_purpose((X509 *)a, -1, 0);
(void)X509_check_purpose((X509 *)b, -1, 0);
if ((a->ex_flags & EXFLAG_NO_FINGERPRINT) == 0
&& (b->ex_flags & EXFLAG_NO_FINGERPRINT) == 0)
rv = memcmp(a->sha1_hash, b->sha1_hash, SHA_DIGEST_LENGTH);
if (rv != 0)
return rv < 0 ? -1 : 1;
/* Check for match against stored encoding too */
if (!a->cert_info.enc.modified && !b->cert_info.enc.modified) {
if (a->cert_info.enc.len < b->cert_info.enc.len)
return -1;
if (a->cert_info.enc.len > b->cert_info.enc.len)
return 1;
rv = memcmp(a->cert_info.enc.enc,
b->cert_info.enc.enc, a->cert_info.enc.len);
}
return rv < 0 ? -1 : rv > 0;
}
int ossl_x509_add_cert_new(STACK_OF(X509) **p_sk, X509 *cert, int flags)
{
if (*p_sk == NULL && (*p_sk = sk_X509_new_null()) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
return 0;
}
return X509_add_cert(*p_sk, cert, flags);
}
int X509_add_cert(STACK_OF(X509) *sk, X509 *cert, int flags)
{
if (sk == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if ((flags & X509_ADD_FLAG_NO_DUP) != 0) {
/*
* not using sk_X509_set_cmp_func() and sk_X509_find()
* because this re-orders the certs on the stack
*/
int i;
for (i = 0; i < sk_X509_num(sk); i++) {
if (X509_cmp(sk_X509_value(sk, i), cert) == 0)
return 1;
}
}
if ((flags & X509_ADD_FLAG_NO_SS) != 0) {
int ret = X509_self_signed(cert, 0);
if (ret != 0)
return ret > 0 ? 1 : 0;
}
if (!sk_X509_insert(sk, cert,
(flags & X509_ADD_FLAG_PREPEND) != 0 ? 0 : -1)) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
return 0;
}
if ((flags & X509_ADD_FLAG_UP_REF) != 0)
(void)X509_up_ref(cert);
return 1;
}
int X509_add_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs, int flags)
/* compiler would allow 'const' for the certs, yet they may get up-ref'ed */
{
if (sk == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
return ossl_x509_add_certs_new(&sk, certs, flags);
}
int ossl_x509_add_certs_new(STACK_OF(X509) **p_sk, STACK_OF(X509) *certs,
int flags)
/* compiler would allow 'const' for the certs, yet they may get up-ref'ed */
{
int n = sk_X509_num(certs /* may be NULL */);
int i;
for (i = 0; i < n; i++) {
int j = (flags & X509_ADD_FLAG_PREPEND) == 0 ? i : n - 1 - i;
/* if prepend, add certs in reverse order to keep original order */
if (!ossl_x509_add_cert_new(p_sk, sk_X509_value(certs, j), flags))
return 0;
}
return 1;
}
int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b)
{
int ret;
if (b == NULL)
return a != NULL;
if (a == NULL)
return -1;
/* Ensure canonical encoding is present and up to date */
if (a->canon_enc == NULL || a->modified) {
ret = i2d_X509_NAME((X509_NAME *)a, NULL);
if (ret < 0)
return -2;
}
if (b->canon_enc == NULL || b->modified) {
ret = i2d_X509_NAME((X509_NAME *)b, NULL);
if (ret < 0)
return -2;
}
ret = a->canon_enclen - b->canon_enclen;
if (ret == 0 && a->canon_enclen == 0)
return 0;
if (ret == 0) {
if (a->canon_enc == NULL || b->canon_enc == NULL)
return -2;
ret = memcmp(a->canon_enc, b->canon_enc, a->canon_enclen);
}
return ret < 0 ? -1 : ret > 0;
}
unsigned long X509_NAME_hash_ex(const X509_NAME *x, OSSL_LIB_CTX *libctx,
const char *propq, int *ok)
{
unsigned long ret = 0;
unsigned char md[SHA_DIGEST_LENGTH];
EVP_MD *sha1 = EVP_MD_fetch(libctx, "SHA1", propq);
/* Make sure X509_NAME structure contains valid cached encoding */
i2d_X509_NAME(x, NULL);
if (ok != NULL)
*ok = 0;
if (sha1 != NULL
&& EVP_Digest(x->canon_enc, x->canon_enclen, md, NULL, sha1, NULL)) {
ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) |
((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L)
) & 0xffffffffL;
if (ok != NULL)
*ok = 1;
}
EVP_MD_free(sha1);
return ret;
}
#ifndef OPENSSL_NO_MD5
/*
* I now DER encode the name and hash it. Since I cache the DER encoding,
* this is reasonably efficient.
*/
unsigned long X509_NAME_hash_old(const X509_NAME *x)
{
EVP_MD *md5 = EVP_MD_fetch(NULL, OSSL_DIGEST_NAME_MD5, "-fips");
EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
unsigned long ret = 0;
unsigned char md[16];
if (md5 == NULL || md_ctx == NULL)
goto end;
/* Make sure X509_NAME structure contains valid cached encoding */
i2d_X509_NAME(x, NULL);
if (EVP_DigestInit_ex(md_ctx, md5, NULL)
&& EVP_DigestUpdate(md_ctx, x->bytes->data, x->bytes->length)
&& EVP_DigestFinal_ex(md_ctx, md, NULL))
ret = (((unsigned long)md[0]) | ((unsigned long)md[1] << 8L) |
((unsigned long)md[2] << 16L) | ((unsigned long)md[3] << 24L)
) & 0xffffffffL;
end:
EVP_MD_CTX_free(md_ctx);
EVP_MD_free(md5);
return ret;
}
#endif
/* Search a stack of X509 for a match */
X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, const X509_NAME *name,
const ASN1_INTEGER *serial)
{
int i;
X509 x, *x509 = NULL;
if (!sk)
return NULL;
x.cert_info.serialNumber = *serial;
x.cert_info.issuer = (X509_NAME *)name; /* won't modify it */
for (i = 0; i < sk_X509_num(sk); i++) {
x509 = sk_X509_value(sk, i);
if (X509_issuer_and_serial_cmp(x509, &x) == 0)
return x509;
}
return NULL;
}
X509 *X509_find_by_subject(STACK_OF(X509) *sk, const X509_NAME *name)
{
X509 *x509;
int i;
for (i = 0; i < sk_X509_num(sk); i++) {
x509 = sk_X509_value(sk, i);
if (X509_NAME_cmp(X509_get_subject_name(x509), name) == 0)
return x509;
}
return NULL;
}
EVP_PKEY *X509_get0_pubkey(const X509 *x)
{
if (x == NULL)
return NULL;
return X509_PUBKEY_get0(x->cert_info.key);
}
EVP_PKEY *X509_get_pubkey(X509 *x)
{
if (x == NULL)
return NULL;
return X509_PUBKEY_get(x->cert_info.key);
}
int X509_check_private_key(const X509 *cert, const EVP_PKEY *pkey)
{
const EVP_PKEY *xk = X509_get0_pubkey(cert);
if (xk == NULL) {
ERR_raise(ERR_LIB_X509, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY);
return 0;
}
return ossl_x509_check_private_key(xk, pkey);
}
int ossl_x509_check_private_key(const EVP_PKEY *x, const EVP_PKEY *pkey)
{
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
switch (EVP_PKEY_eq(x, pkey)) {
case 1:
return 1;
case 0:
ERR_raise(ERR_LIB_X509, X509_R_KEY_VALUES_MISMATCH);
return 0;
case -1:
ERR_raise(ERR_LIB_X509, X509_R_KEY_TYPE_MISMATCH);
return 0;
case -2:
ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_KEY_TYPE);
/* fall thru */
default:
return 0;
}
}
/*
* Check a suite B algorithm is permitted: pass in a public key and the NID
* of its signature (or 0 if no signature). The pflags is a pointer to a
* flags field which must contain the suite B verification flags.
*/
#ifndef OPENSSL_NO_EC
static int check_suite_b(EVP_PKEY *pkey, int sign_nid, unsigned long *pflags)
{
char curve_name[80];
size_t curve_name_len;
int curve_nid;
if (pkey == NULL || !EVP_PKEY_is_a(pkey, "EC"))
return X509_V_ERR_SUITE_B_INVALID_ALGORITHM;
if (!EVP_PKEY_get_group_name(pkey, curve_name, sizeof(curve_name),
&curve_name_len))
return X509_V_ERR_SUITE_B_INVALID_CURVE;
curve_nid = OBJ_txt2nid(curve_name);
/* Check curve is consistent with LOS */
if (curve_nid == NID_secp384r1) { /* P-384 */
/*
* Check signature algorithm is consistent with curve.
*/
if (sign_nid != -1 && sign_nid != NID_ecdsa_with_SHA384)
return X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM;
if (!(*pflags & X509_V_FLAG_SUITEB_192_LOS))
return X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED;
/* If we encounter P-384 we cannot use P-256 later */
*pflags &= ~X509_V_FLAG_SUITEB_128_LOS_ONLY;
} else if (curve_nid == NID_X9_62_prime256v1) { /* P-256 */
if (sign_nid != -1 && sign_nid != NID_ecdsa_with_SHA256)
return X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM;
if (!(*pflags & X509_V_FLAG_SUITEB_128_LOS_ONLY))
return X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED;
} else {
return X509_V_ERR_SUITE_B_INVALID_CURVE;
}
return X509_V_OK;
}
int X509_chain_check_suiteb(int *perror_depth, X509 *x, STACK_OF(X509) *chain,
unsigned long flags)
{
int rv, i, sign_nid;
EVP_PKEY *pk;
unsigned long tflags = flags;
if (!(flags & X509_V_FLAG_SUITEB_128_LOS))
return X509_V_OK;
/* If no EE certificate passed in must be first in chain */
if (x == NULL) {
x = sk_X509_value(chain, 0);
i = 1;
} else {
i = 0;
}
pk = X509_get0_pubkey(x);
/*
* With DANE-EE(3) success, or DANE-EE(3)/PKIX-EE(1) failure we don't build
* a chain all, just report trust success or failure, but must also report
* Suite-B errors if applicable. This is indicated via a NULL chain
* pointer. All we need to do is check the leaf key algorithm.
*/
if (chain == NULL)
return check_suite_b(pk, -1, &tflags);
if (X509_get_version(x) != X509_VERSION_3) {
rv = X509_V_ERR_SUITE_B_INVALID_VERSION;
/* Correct error depth */
i = 0;
goto end;
}
/* Check EE key only */
rv = check_suite_b(pk, -1, &tflags);
if (rv != X509_V_OK) {
/* Correct error depth */
i = 0;
goto end;
}
for (; i < sk_X509_num(chain); i++) {
sign_nid = X509_get_signature_nid(x);
x = sk_X509_value(chain, i);
if (X509_get_version(x) != X509_VERSION_3) {
rv = X509_V_ERR_SUITE_B_INVALID_VERSION;
goto end;
}
pk = X509_get0_pubkey(x);
rv = check_suite_b(pk, sign_nid, &tflags);
if (rv != X509_V_OK)
goto end;
}
/* Final check: root CA signature */
rv = check_suite_b(pk, X509_get_signature_nid(x), &tflags);
end:
if (rv != X509_V_OK) {
/* Invalid signature or LOS errors are for previous cert */
if ((rv == X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM
|| rv == X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED) && i)
i--;
/*
* If we have LOS error and flags changed then we are signing P-384
* with P-256. Use more meaningful error.
*/
if (rv == X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED && flags != tflags)
rv = X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256;
if (perror_depth)
*perror_depth = i;
}
return rv;
}
int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags)
{
int sign_nid;
if (!(flags & X509_V_FLAG_SUITEB_128_LOS))
return X509_V_OK;
sign_nid = OBJ_obj2nid(crl->crl.sig_alg.algorithm);
return check_suite_b(pk, sign_nid, &flags);
}
#else
int X509_chain_check_suiteb(int *perror_depth, X509 *x, STACK_OF(X509) *chain,
unsigned long flags)
{
return 0;
}
int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags)
{
return 0;
}
#endif
/*
* Not strictly speaking an "up_ref" as a STACK doesn't have a reference
* count but it has the same effect by duping the STACK and upping the ref of
* each X509 structure.
*/
STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain)
{
STACK_OF(X509) *ret = sk_X509_dup(chain);
int i;
if (ret == NULL)
return NULL;
for (i = 0; i < sk_X509_num(ret); i++) {
X509 *x = sk_X509_value(ret, i);
if (!X509_up_ref(x))
goto err;
}
return ret;
err:
while (i-- > 0)
X509_free(sk_X509_value(ret, i));
sk_X509_free(ret);
return NULL;
}
| 16,704 | 27.122896 | 79 |
c
|
openssl
|
openssl-master/crypto/x509/x509_d2.c
|
/*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/crypto.h>
#include <openssl/x509.h>
int X509_STORE_set_default_paths_ex(X509_STORE *ctx, OSSL_LIB_CTX *libctx,
const char *propq)
{
X509_LOOKUP *lookup;
lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_file());
if (lookup == NULL)
return 0;
X509_LOOKUP_load_file_ex(lookup, NULL, X509_FILETYPE_DEFAULT, libctx, propq);
lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_hash_dir());
if (lookup == NULL)
return 0;
X509_LOOKUP_add_dir(lookup, NULL, X509_FILETYPE_DEFAULT);
lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_store());
if (lookup == NULL)
return 0;
X509_LOOKUP_add_store_ex(lookup, NULL, libctx, propq);
/* clear any errors */
ERR_clear_error();
return 1;
}
int X509_STORE_set_default_paths(X509_STORE *ctx)
{
return X509_STORE_set_default_paths_ex(ctx, NULL, NULL);
}
int X509_STORE_load_file_ex(X509_STORE *ctx, const char *file,
OSSL_LIB_CTX *libctx, const char *propq)
{
X509_LOOKUP *lookup;
if (file == NULL
|| (lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_file())) == NULL
|| X509_LOOKUP_load_file_ex(lookup, file, X509_FILETYPE_PEM, libctx,
propq) <= 0)
return 0;
return 1;
}
int X509_STORE_load_file(X509_STORE *ctx, const char *file)
{
return X509_STORE_load_file_ex(ctx, file, NULL, NULL);
}
int X509_STORE_load_path(X509_STORE *ctx, const char *path)
{
X509_LOOKUP *lookup;
if (path == NULL
|| (lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_hash_dir())) == NULL
|| X509_LOOKUP_add_dir(lookup, path, X509_FILETYPE_PEM) <= 0)
return 0;
return 1;
}
int X509_STORE_load_store_ex(X509_STORE *ctx, const char *uri,
OSSL_LIB_CTX *libctx, const char *propq)
{
X509_LOOKUP *lookup;
if (uri == NULL
|| (lookup = X509_STORE_add_lookup(ctx, X509_LOOKUP_store())) == NULL
|| X509_LOOKUP_add_store_ex(lookup, uri, libctx, propq) == 0)
return 0;
return 1;
}
int X509_STORE_load_store(X509_STORE *ctx, const char *uri)
{
return X509_STORE_load_store_ex(ctx, uri, NULL, NULL);
}
int X509_STORE_load_locations_ex(X509_STORE *ctx, const char *file,
const char *path, OSSL_LIB_CTX *libctx,
const char *propq)
{
if (file == NULL && path == NULL)
return 0;
if (file != NULL && !X509_STORE_load_file_ex(ctx, file, libctx, propq))
return 0;
if (path != NULL && !X509_STORE_load_path(ctx, path))
return 0;
return 1;
}
int X509_STORE_load_locations(X509_STORE *ctx, const char *file,
const char *path)
{
return X509_STORE_load_locations_ex(ctx, file, path, NULL, NULL);
}
| 3,257 | 28.089286 | 81 |
c
|
openssl
|
openssl-master/crypto/x509/x509_err.c
|
/*
* Generated by util/mkerr.pl DO NOT EDIT
* Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <openssl/err.h>
#include <openssl/x509err.h>
#include "crypto/x509err.h"
#ifndef OPENSSL_NO_ERR
static const ERR_STRING_DATA X509_str_reasons[] = {
{ERR_PACK(ERR_LIB_X509, 0, X509_R_AKID_MISMATCH), "akid mismatch"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_BAD_SELECTOR), "bad selector"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_BAD_X509_FILETYPE), "bad x509 filetype"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_BASE64_DECODE_ERROR),
"base64 decode error"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_CANT_CHECK_DH_KEY), "can't check dh key"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_CERTIFICATE_VERIFICATION_FAILED),
"certificate verification failed"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_CERT_ALREADY_IN_HASH_TABLE),
"cert already in hash table"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_CRL_ALREADY_DELTA), "crl already delta"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_CRL_VERIFY_FAILURE),
"crl verify failure"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_DUPLICATE_ATTRIBUTE),
"duplicate attribute"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_ERROR_GETTING_MD_BY_NID),
"error getting md by nid"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_ERROR_USING_SIGINF_SET),
"error using siginf set"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_IDP_MISMATCH), "idp mismatch"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_ATTRIBUTES),
"invalid attributes"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_DIRECTORY), "invalid directory"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_DISTPOINT), "invalid distpoint"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_FIELD_NAME),
"invalid field name"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_INVALID_TRUST), "invalid trust"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_ISSUER_MISMATCH), "issuer mismatch"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_KEY_TYPE_MISMATCH), "key type mismatch"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_KEY_VALUES_MISMATCH),
"key values mismatch"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_LOADING_CERT_DIR), "loading cert dir"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_LOADING_DEFAULTS), "loading defaults"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_METHOD_NOT_SUPPORTED),
"method not supported"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_NAME_TOO_LONG), "name too long"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_NEWER_CRL_NOT_NEWER),
"newer crl not newer"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CERTIFICATE_FOUND),
"no certificate found"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CERTIFICATE_OR_CRL_FOUND),
"no certificate or crl found"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CERT_SET_FOR_US_TO_VERIFY),
"no cert set for us to verify"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CRL_FOUND), "no crl found"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_NO_CRL_NUMBER), "no crl number"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_PUBLIC_KEY_DECODE_ERROR),
"public key decode error"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_PUBLIC_KEY_ENCODE_ERROR),
"public key encode error"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_SHOULD_RETRY), "should retry"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN),
"unable to find parameters in chain"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY),
"unable to get certs public key"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_KEY_TYPE), "unknown key type"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_NID), "unknown nid"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_PURPOSE_ID),
"unknown purpose id"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_SIGID_ALGS),
"unknown sigid algs"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_UNKNOWN_TRUST_ID), "unknown trust id"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_UNSUPPORTED_ALGORITHM),
"unsupported algorithm"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_WRONG_LOOKUP_TYPE), "wrong lookup type"},
{ERR_PACK(ERR_LIB_X509, 0, X509_R_WRONG_TYPE), "wrong type"},
{0, NULL}
};
#endif
int ossl_err_load_X509_strings(void)
{
#ifndef OPENSSL_NO_ERR
if (ERR_reason_error_string(X509_str_reasons[0].error) == NULL)
ERR_load_strings_const(X509_str_reasons);
#endif
return 1;
}
| 4,506 | 45.463918 | 80 |
c
|
openssl
|
openssl-master/crypto/x509/x509_ext.c
|
/*
* Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
#include <openssl/x509v3.h>
int X509_CRL_get_ext_count(const X509_CRL *x)
{
return X509v3_get_ext_count(x->crl.extensions);
}
int X509_CRL_get_ext_by_NID(const X509_CRL *x, int nid, int lastpos)
{
return X509v3_get_ext_by_NID(x->crl.extensions, nid, lastpos);
}
int X509_CRL_get_ext_by_OBJ(const X509_CRL *x, const ASN1_OBJECT *obj,
int lastpos)
{
return X509v3_get_ext_by_OBJ(x->crl.extensions, obj, lastpos);
}
int X509_CRL_get_ext_by_critical(const X509_CRL *x, int crit, int lastpos)
{
return X509v3_get_ext_by_critical(x->crl.extensions, crit, lastpos);
}
X509_EXTENSION *X509_CRL_get_ext(const X509_CRL *x, int loc)
{
return X509v3_get_ext(x->crl.extensions, loc);
}
X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc)
{
return X509v3_delete_ext(x->crl.extensions, loc);
}
void *X509_CRL_get_ext_d2i(const X509_CRL *x, int nid, int *crit, int *idx)
{
return X509V3_get_d2i(x->crl.extensions, nid, crit, idx);
}
int X509_CRL_add1_ext_i2d(X509_CRL *x, int nid, void *value, int crit,
unsigned long flags)
{
return X509V3_add1_i2d(&x->crl.extensions, nid, value, crit, flags);
}
int X509_CRL_add_ext(X509_CRL *x, X509_EXTENSION *ex, int loc)
{
return (X509v3_add_ext(&(x->crl.extensions), ex, loc) != NULL);
}
int X509_get_ext_count(const X509 *x)
{
return X509v3_get_ext_count(x->cert_info.extensions);
}
int X509_get_ext_by_NID(const X509 *x, int nid, int lastpos)
{
return X509v3_get_ext_by_NID(x->cert_info.extensions, nid, lastpos);
}
int X509_get_ext_by_OBJ(const X509 *x, const ASN1_OBJECT *obj, int lastpos)
{
return X509v3_get_ext_by_OBJ(x->cert_info.extensions, obj, lastpos);
}
int X509_get_ext_by_critical(const X509 *x, int crit, int lastpos)
{
return (X509v3_get_ext_by_critical
(x->cert_info.extensions, crit, lastpos));
}
X509_EXTENSION *X509_get_ext(const X509 *x, int loc)
{
return X509v3_get_ext(x->cert_info.extensions, loc);
}
X509_EXTENSION *X509_delete_ext(X509 *x, int loc)
{
return X509v3_delete_ext(x->cert_info.extensions, loc);
}
int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc)
{
return (X509v3_add_ext(&(x->cert_info.extensions), ex, loc) != NULL);
}
void *X509_get_ext_d2i(const X509 *x, int nid, int *crit, int *idx)
{
return X509V3_get_d2i(x->cert_info.extensions, nid, crit, idx);
}
int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit,
unsigned long flags)
{
return X509V3_add1_i2d(&x->cert_info.extensions, nid, value, crit,
flags);
}
int X509_REVOKED_get_ext_count(const X509_REVOKED *x)
{
return X509v3_get_ext_count(x->extensions);
}
int X509_REVOKED_get_ext_by_NID(const X509_REVOKED *x, int nid, int lastpos)
{
return X509v3_get_ext_by_NID(x->extensions, nid, lastpos);
}
int X509_REVOKED_get_ext_by_OBJ(const X509_REVOKED *x, const ASN1_OBJECT *obj,
int lastpos)
{
return X509v3_get_ext_by_OBJ(x->extensions, obj, lastpos);
}
int X509_REVOKED_get_ext_by_critical(const X509_REVOKED *x, int crit, int lastpos)
{
return X509v3_get_ext_by_critical(x->extensions, crit, lastpos);
}
X509_EXTENSION *X509_REVOKED_get_ext(const X509_REVOKED *x, int loc)
{
return X509v3_get_ext(x->extensions, loc);
}
X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc)
{
return X509v3_delete_ext(x->extensions, loc);
}
int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc)
{
return (X509v3_add_ext(&(x->extensions), ex, loc) != NULL);
}
void *X509_REVOKED_get_ext_d2i(const X509_REVOKED *x, int nid, int *crit, int *idx)
{
return X509V3_get_d2i(x->extensions, nid, crit, idx);
}
int X509_REVOKED_add1_ext_i2d(X509_REVOKED *x, int nid, void *value, int crit,
unsigned long flags)
{
return X509V3_add1_i2d(&x->extensions, nid, value, crit, flags);
}
| 4,452 | 26.83125 | 83 |
c
|
openssl
|
openssl-master/crypto/x509/x509_local.h
|
/*
* Copyright 2014-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include "internal/refcount.h"
#define X509V3_conf_add_error_name_value(val) \
ERR_add_error_data(4, "name=", (val)->name, ", value=", (val)->value)
/*
* This structure holds all parameters associated with a verify operation by
* including an X509_VERIFY_PARAM structure in related structures the
* parameters used can be customized
*/
struct X509_VERIFY_PARAM_st {
char *name;
time_t check_time; /* Time to use */
uint32_t inh_flags; /* Inheritance flags */
unsigned long flags; /* Various verify flags */
int purpose; /* purpose to check untrusted certificates */
int trust; /* trust setting to check */
int depth; /* Verify depth */
int auth_level; /* Security level for chain verification */
STACK_OF(ASN1_OBJECT) *policies; /* Permissible policies */
/* Peer identity details */
STACK_OF(OPENSSL_STRING) *hosts; /* Set of acceptable names */
unsigned int hostflags; /* Flags to control matching features */
char *peername; /* Matching hostname in peer certificate */
char *email; /* If not NULL email address to match */
size_t emaillen;
unsigned char *ip; /* If not NULL IP address to match */
size_t iplen; /* Length of IP address */
};
/* No error callback if depth < 0 */
int ossl_x509_check_cert_time(X509_STORE_CTX *ctx, X509 *x, int depth);
/* a sequence of these are used */
struct x509_attributes_st {
ASN1_OBJECT *object;
STACK_OF(ASN1_TYPE) *set;
};
struct X509_extension_st {
ASN1_OBJECT *object;
ASN1_BOOLEAN critical;
ASN1_OCTET_STRING value;
};
/*
* Method to handle CRL access. In general a CRL could be very large (several
* Mb) and can consume large amounts of resources if stored in memory by
* multiple processes. This method allows general CRL operations to be
* redirected to more efficient callbacks: for example a CRL entry database.
*/
#define X509_CRL_METHOD_DYNAMIC 1
struct x509_crl_method_st {
int flags;
int (*crl_init) (X509_CRL *crl);
int (*crl_free) (X509_CRL *crl);
int (*crl_lookup) (X509_CRL *crl, X509_REVOKED **ret,
const ASN1_INTEGER *ser, const X509_NAME *issuer);
int (*crl_verify) (X509_CRL *crl, EVP_PKEY *pk);
};
struct x509_lookup_method_st {
char *name;
int (*new_item) (X509_LOOKUP *ctx);
void (*free) (X509_LOOKUP *ctx);
int (*init) (X509_LOOKUP *ctx);
int (*shutdown) (X509_LOOKUP *ctx);
int (*ctrl) (X509_LOOKUP *ctx, int cmd, const char *argc, long argl,
char **ret);
int (*get_by_subject) (X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const X509_NAME *name, X509_OBJECT *ret);
int (*get_by_issuer_serial) (X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const X509_NAME *name,
const ASN1_INTEGER *serial,
X509_OBJECT *ret);
int (*get_by_fingerprint) (X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const unsigned char *bytes, int len,
X509_OBJECT *ret);
int (*get_by_alias) (X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const char *str, int len, X509_OBJECT *ret);
int (*get_by_subject_ex) (X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
const X509_NAME *name, X509_OBJECT *ret,
OSSL_LIB_CTX *libctx, const char *propq);
int (*ctrl_ex) (X509_LOOKUP *ctx, int cmd, const char *argc, long argl,
char **ret, OSSL_LIB_CTX *libctx, const char *propq);
};
/* This is the functions plus an instance of the local variables. */
struct x509_lookup_st {
int init; /* have we been started */
int skip; /* don't use us. */
X509_LOOKUP_METHOD *method; /* the functions */
void *method_data; /* method data */
X509_STORE *store_ctx; /* who owns us */
};
/*
* This is used to hold everything. It is used for all certificate
* validation. Once we have a certificate chain, the 'verify' function is
* then called to actually check the cert chain.
*/
struct x509_store_st {
/* The following is a cache of trusted certs */
int cache; /* if true, stash any hits */
STACK_OF(X509_OBJECT) *objs; /* Cache of all objects */
/* These are external lookup methods */
STACK_OF(X509_LOOKUP) *get_cert_methods;
X509_VERIFY_PARAM *param;
/* Callbacks for various operations */
/* called to verify a certificate */
int (*verify) (X509_STORE_CTX *ctx);
/* error callback */
int (*verify_cb) (int ok, X509_STORE_CTX *ctx);
/* get issuers cert from ctx */
int (*get_issuer) (X509 **issuer, X509_STORE_CTX *ctx, X509 *x);
/* check issued */
int (*check_issued) (X509_STORE_CTX *ctx, X509 *x, X509 *issuer);
/* Check revocation status of chain */
int (*check_revocation) (X509_STORE_CTX *ctx);
/* retrieve CRL */
int (*get_crl) (X509_STORE_CTX *ctx, X509_CRL **crl, X509 *x);
/* Check CRL validity */
int (*check_crl) (X509_STORE_CTX *ctx, X509_CRL *crl);
/* Check certificate against CRL */
int (*cert_crl) (X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x);
/* Check policy status of the chain */
int (*check_policy) (X509_STORE_CTX *ctx);
STACK_OF(X509) *(*lookup_certs) (X509_STORE_CTX *ctx,
const X509_NAME *nm);
/* cannot constify 'ctx' param due to lookup_certs_sk() in x509_vfy.c */
STACK_OF(X509_CRL) *(*lookup_crls) (const X509_STORE_CTX *ctx,
const X509_NAME *nm);
int (*cleanup) (X509_STORE_CTX *ctx);
CRYPTO_EX_DATA ex_data;
CRYPTO_REF_COUNT references;
CRYPTO_RWLOCK *lock;
};
typedef struct lookup_dir_hashes_st BY_DIR_HASH;
typedef struct lookup_dir_entry_st BY_DIR_ENTRY;
DEFINE_STACK_OF(BY_DIR_HASH)
DEFINE_STACK_OF(BY_DIR_ENTRY)
typedef STACK_OF(X509_NAME_ENTRY) STACK_OF_X509_NAME_ENTRY;
DEFINE_STACK_OF(STACK_OF_X509_NAME_ENTRY)
int ossl_x509_likely_issued(X509 *issuer, X509 *subject);
int ossl_x509_signing_allowed(const X509 *issuer, const X509 *subject);
| 6,666 | 40.66875 | 77 |
h
|
openssl
|
openssl-master/crypto/x509/x509_meth.c
|
/*
* Copyright 2018-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <time.h>
#include <errno.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/x509.h>
#include <openssl/types.h>
#include "x509_local.h"
X509_LOOKUP_METHOD *X509_LOOKUP_meth_new(const char *name)
{
X509_LOOKUP_METHOD *method = OPENSSL_zalloc(sizeof(X509_LOOKUP_METHOD));
if (method != NULL) {
method->name = OPENSSL_strdup(name);
if (method->name == NULL)
goto err;
}
return method;
err:
OPENSSL_free(method);
return NULL;
}
void X509_LOOKUP_meth_free(X509_LOOKUP_METHOD *method)
{
if (method != NULL)
OPENSSL_free(method->name);
OPENSSL_free(method);
}
int X509_LOOKUP_meth_set_new_item(X509_LOOKUP_METHOD *method,
int (*new_item) (X509_LOOKUP *ctx))
{
method->new_item = new_item;
return 1;
}
int (*X509_LOOKUP_meth_get_new_item(const X509_LOOKUP_METHOD* method))
(X509_LOOKUP *ctx)
{
return method->new_item;
}
int X509_LOOKUP_meth_set_free(
X509_LOOKUP_METHOD *method,
void (*free_fn) (X509_LOOKUP *ctx))
{
method->free = free_fn;
return 1;
}
void (*X509_LOOKUP_meth_get_free(const X509_LOOKUP_METHOD* method))
(X509_LOOKUP *ctx)
{
return method->free;
}
int X509_LOOKUP_meth_set_init(X509_LOOKUP_METHOD *method,
int (*init) (X509_LOOKUP *ctx))
{
method->init = init;
return 1;
}
int (*X509_LOOKUP_meth_get_init(const X509_LOOKUP_METHOD* method))
(X509_LOOKUP *ctx)
{
return method->init;
}
int X509_LOOKUP_meth_set_shutdown(
X509_LOOKUP_METHOD *method,
int (*shutdown) (X509_LOOKUP *ctx))
{
method->shutdown = shutdown;
return 1;
}
int (*X509_LOOKUP_meth_get_shutdown(const X509_LOOKUP_METHOD* method))
(X509_LOOKUP *ctx)
{
return method->shutdown;
}
int X509_LOOKUP_meth_set_ctrl(
X509_LOOKUP_METHOD *method,
X509_LOOKUP_ctrl_fn ctrl)
{
method->ctrl = ctrl;
return 1;
}
X509_LOOKUP_ctrl_fn X509_LOOKUP_meth_get_ctrl(const X509_LOOKUP_METHOD *method)
{
return method->ctrl;
}
int X509_LOOKUP_meth_set_get_by_subject(X509_LOOKUP_METHOD *method,
X509_LOOKUP_get_by_subject_fn get_by_subject)
{
method->get_by_subject = get_by_subject;
return 1;
}
X509_LOOKUP_get_by_subject_fn X509_LOOKUP_meth_get_get_by_subject(
const X509_LOOKUP_METHOD *method)
{
return method->get_by_subject;
}
int X509_LOOKUP_meth_set_get_by_issuer_serial(X509_LOOKUP_METHOD *method,
X509_LOOKUP_get_by_issuer_serial_fn get_by_issuer_serial)
{
method->get_by_issuer_serial = get_by_issuer_serial;
return 1;
}
X509_LOOKUP_get_by_issuer_serial_fn
X509_LOOKUP_meth_get_get_by_issuer_serial(const X509_LOOKUP_METHOD *method)
{
return method->get_by_issuer_serial;
}
int X509_LOOKUP_meth_set_get_by_fingerprint(X509_LOOKUP_METHOD *method,
X509_LOOKUP_get_by_fingerprint_fn get_by_fingerprint)
{
method->get_by_fingerprint = get_by_fingerprint;
return 1;
}
X509_LOOKUP_get_by_fingerprint_fn X509_LOOKUP_meth_get_get_by_fingerprint(
const X509_LOOKUP_METHOD *method)
{
return method->get_by_fingerprint;
}
int X509_LOOKUP_meth_set_get_by_alias(X509_LOOKUP_METHOD *method,
X509_LOOKUP_get_by_alias_fn get_by_alias)
{
method->get_by_alias = get_by_alias;
return 1;
}
X509_LOOKUP_get_by_alias_fn X509_LOOKUP_meth_get_get_by_alias(
const X509_LOOKUP_METHOD *method)
{
return method->get_by_alias;
}
| 3,827 | 22.2 | 79 |
c
|
openssl
|
openssl-master/crypto/x509/x509_obj.c
|
/*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/objects.h>
#include <openssl/x509.h>
#include <openssl/buffer.h>
#include "crypto/x509.h"
#include "crypto/ctype.h"
/*
* Limit to ensure we don't overflow: much greater than
* anything encountered in practice.
*/
#define NAME_ONELINE_MAX (1024 * 1024)
char *X509_NAME_oneline(const X509_NAME *a, char *buf, int len)
{
const X509_NAME_ENTRY *ne;
int i;
int n, lold, l, l1, l2, num, j, type;
int prev_set = -1;
const char *s;
char *p;
unsigned char *q;
BUF_MEM *b = NULL;
static const char hex[17] = "0123456789ABCDEF";
int gs_doit[4];
char tmp_buf[80];
#ifdef CHARSET_EBCDIC
unsigned char ebcdic_buf[1024];
#endif
if (buf == NULL) {
if ((b = BUF_MEM_new()) == NULL)
goto buferr;
if (!BUF_MEM_grow(b, 200))
goto buferr;
b->data[0] = '\0';
len = 200;
} else if (len == 0) {
return NULL;
}
if (a == NULL) {
if (b) {
buf = b->data;
OPENSSL_free(b);
}
strncpy(buf, "NO X509_NAME", len);
buf[len - 1] = '\0';
return buf;
}
len--; /* space for '\0' */
l = 0;
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
ne = sk_X509_NAME_ENTRY_value(a->entries, i);
n = OBJ_obj2nid(ne->object);
if ((n == NID_undef) || ((s = OBJ_nid2sn(n)) == NULL)) {
i2t_ASN1_OBJECT(tmp_buf, sizeof(tmp_buf), ne->object);
s = tmp_buf;
}
l1 = strlen(s);
type = ne->value->type;
num = ne->value->length;
if (num > NAME_ONELINE_MAX) {
ERR_raise(ERR_LIB_X509, X509_R_NAME_TOO_LONG);
goto end;
}
q = ne->value->data;
#ifdef CHARSET_EBCDIC
if (type == V_ASN1_GENERALSTRING ||
type == V_ASN1_VISIBLESTRING ||
type == V_ASN1_PRINTABLESTRING ||
type == V_ASN1_TELETEXSTRING ||
type == V_ASN1_IA5STRING) {
if (num > (int)sizeof(ebcdic_buf))
num = sizeof(ebcdic_buf);
ascii2ebcdic(ebcdic_buf, q, num);
q = ebcdic_buf;
}
#endif
if ((type == V_ASN1_GENERALSTRING) && ((num % 4) == 0)) {
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 0;
for (j = 0; j < num; j++)
if (q[j] != 0)
gs_doit[j & 3] = 1;
if (gs_doit[0] | gs_doit[1] | gs_doit[2])
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1;
else {
gs_doit[0] = gs_doit[1] = gs_doit[2] = 0;
gs_doit[3] = 1;
}
} else
gs_doit[0] = gs_doit[1] = gs_doit[2] = gs_doit[3] = 1;
for (l2 = j = 0; j < num; j++) {
if (!gs_doit[j & 3])
continue;
l2++;
if (q[j] == '/' || q[j] == '+')
l2++; /* char needs to be escaped */
else if ((ossl_toascii(q[j]) < ossl_toascii(' ')) ||
(ossl_toascii(q[j]) > ossl_toascii('~')))
l2 += 3;
}
lold = l;
l += 1 + l1 + 1 + l2;
if (l > NAME_ONELINE_MAX) {
ERR_raise(ERR_LIB_X509, X509_R_NAME_TOO_LONG);
goto end;
}
if (b != NULL) {
if (!BUF_MEM_grow(b, l + 1))
goto buferr;
p = &(b->data[lold]);
} else if (l > len) {
break;
} else
p = &(buf[lold]);
*(p++) = prev_set == ne->set ? '+' : '/';
memcpy(p, s, (unsigned int)l1);
p += l1;
*(p++) = '=';
#ifndef CHARSET_EBCDIC /* q was assigned above already. */
q = ne->value->data;
#endif
for (j = 0; j < num; j++) {
if (!gs_doit[j & 3])
continue;
#ifndef CHARSET_EBCDIC
n = q[j];
if ((n < ' ') || (n > '~')) {
*(p++) = '\\';
*(p++) = 'x';
*(p++) = hex[(n >> 4) & 0x0f];
*(p++) = hex[n & 0x0f];
} else {
if (n == '/' || n == '+')
*(p++) = '\\';
*(p++) = n;
}
#else
n = os_toascii[q[j]];
if ((n < os_toascii[' ']) || (n > os_toascii['~'])) {
*(p++) = '\\';
*(p++) = 'x';
*(p++) = hex[(n >> 4) & 0x0f];
*(p++) = hex[n & 0x0f];
} else {
if (n == os_toascii['/'] || n == os_toascii['+'])
*(p++) = '\\';
*(p++) = q[j];
}
#endif
}
*p = '\0';
prev_set = ne->set;
}
if (b != NULL) {
p = b->data;
OPENSSL_free(b);
} else
p = buf;
if (i == 0)
*p = '\0';
return p;
buferr:
ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
end:
BUF_MEM_free(b);
return NULL;
}
| 5,372 | 27.579787 | 74 |
c
|
openssl
|
openssl-master/crypto/x509/x509_r2x.c
|
/*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/asn1.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
#include <openssl/objects.h>
#include <openssl/buffer.h>
X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey)
{
X509 *ret = NULL;
X509_CINF *xi = NULL;
const X509_NAME *xn;
EVP_PKEY *pubkey = NULL;
if ((ret = X509_new()) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
return NULL;
}
/* duplicate the request */
xi = &ret->cert_info;
if (sk_X509_ATTRIBUTE_num(r->req_info.attributes) != 0) {
if ((xi->version = ASN1_INTEGER_new()) == NULL)
goto err;
if (!ASN1_INTEGER_set(xi->version, 2))
goto err;
/*- xi->extensions=ri->attributes; <- bad, should not ever be done
ri->attributes=NULL; */
}
xn = X509_REQ_get_subject_name(r);
if (X509_set_subject_name(ret, xn) == 0)
goto err;
if (X509_set_issuer_name(ret, xn) == 0)
goto err;
if (X509_gmtime_adj(xi->validity.notBefore, 0) == NULL)
goto err;
if (X509_gmtime_adj(xi->validity.notAfter, (long)60 * 60 * 24 * days) ==
NULL)
goto err;
pubkey = X509_REQ_get0_pubkey(r);
if (pubkey == NULL || !X509_set_pubkey(ret, pubkey))
goto err;
if (!X509_sign(ret, pkey, EVP_md5()))
goto err;
return ret;
err:
X509_free(ret);
return NULL;
}
| 1,820 | 25.779412 | 76 |
c
|
openssl
|
openssl-master/crypto/x509/x509_req.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
#include <openssl/objects.h>
#include <openssl/buffer.h>
#include <openssl/pem.h>
X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md)
{
X509_REQ *ret;
X509_REQ_INFO *ri;
int i;
EVP_PKEY *pktmp;
ret = X509_REQ_new_ex(x->libctx, x->propq);
if (ret == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
goto err;
}
ri = &ret->req_info;
ri->version->length = 1;
ri->version->data = OPENSSL_malloc(1);
if (ri->version->data == NULL)
goto err;
ri->version->data[0] = 0; /* version == 0 */
if (!X509_REQ_set_subject_name(ret, X509_get_subject_name(x)))
goto err;
pktmp = X509_get0_pubkey(x);
if (pktmp == NULL)
goto err;
i = X509_REQ_set_pubkey(ret, pktmp);
if (!i)
goto err;
if (pkey != NULL) {
if (!X509_REQ_sign(ret, pkey, md))
goto err;
}
return ret;
err:
X509_REQ_free(ret);
return NULL;
}
EVP_PKEY *X509_REQ_get_pubkey(X509_REQ *req)
{
if (req == NULL)
return NULL;
return X509_PUBKEY_get(req->req_info.pubkey);
}
EVP_PKEY *X509_REQ_get0_pubkey(const X509_REQ *req)
{
if (req == NULL)
return NULL;
return X509_PUBKEY_get0(req->req_info.pubkey);
}
X509_PUBKEY *X509_REQ_get_X509_PUBKEY(X509_REQ *req)
{
return req->req_info.pubkey;
}
int X509_REQ_check_private_key(const X509_REQ *req, EVP_PKEY *pkey)
{
return ossl_x509_check_private_key(X509_REQ_get0_pubkey(req), pkey);
}
/*
* It seems several organisations had the same idea of including a list of
* extensions in a certificate request. There are at least two OIDs that are
* used and there may be more: so the list is configurable.
*/
static int ext_nid_list[] = { NID_ext_req, NID_ms_ext_req, NID_undef };
static int *ext_nids = ext_nid_list;
int X509_REQ_extension_nid(int req_nid)
{
int i, nid;
for (i = 0;; i++) {
nid = ext_nids[i];
if (nid == NID_undef)
return 0;
else if (req_nid == nid)
return 1;
}
}
int *X509_REQ_get_extension_nids(void)
{
return ext_nids;
}
void X509_REQ_set_extension_nids(int *nids)
{
ext_nids = nids;
}
STACK_OF(X509_EXTENSION) *X509_REQ_get_extensions(X509_REQ *req)
{
X509_ATTRIBUTE *attr;
ASN1_TYPE *ext = NULL;
int idx, *pnid;
const unsigned char *p;
if (req == NULL || !ext_nids)
return NULL;
for (pnid = ext_nids; *pnid != NID_undef; pnid++) {
idx = X509_REQ_get_attr_by_NID(req, *pnid, -1);
if (idx < 0)
continue;
attr = X509_REQ_get_attr(req, idx);
ext = X509_ATTRIBUTE_get0_type(attr, 0);
break;
}
if (ext == NULL) /* no extensions is not an error */
return sk_X509_EXTENSION_new_null();
if (ext->type != V_ASN1_SEQUENCE) {
ERR_raise(ERR_LIB_X509, X509_R_WRONG_TYPE);
return NULL;
}
p = ext->value.sequence->data;
return (STACK_OF(X509_EXTENSION) *)
ASN1_item_d2i(NULL, &p, ext->value.sequence->length,
ASN1_ITEM_rptr(X509_EXTENSIONS));
}
/*
* Add a STACK_OF extensions to a certificate request: allow alternative OIDs
* in case we want to create a non standard one.
*/
int X509_REQ_add_extensions_nid(X509_REQ *req,
const STACK_OF(X509_EXTENSION) *exts, int nid)
{
int extlen;
int rv = 0;
unsigned char *ext = NULL;
/* Generate encoding of extensions */
extlen = ASN1_item_i2d((const ASN1_VALUE *)exts, &ext,
ASN1_ITEM_rptr(X509_EXTENSIONS));
if (extlen <= 0)
return 0;
rv = X509_REQ_add1_attr_by_NID(req, nid, V_ASN1_SEQUENCE, ext, extlen);
OPENSSL_free(ext);
return rv;
}
/* This is the normal usage: use the "official" OID */
int X509_REQ_add_extensions(X509_REQ *req, const STACK_OF(X509_EXTENSION) *exts)
{
return X509_REQ_add_extensions_nid(req, exts, NID_ext_req);
}
/* Request attribute functions */
int X509_REQ_get_attr_count(const X509_REQ *req)
{
return X509at_get_attr_count(req->req_info.attributes);
}
int X509_REQ_get_attr_by_NID(const X509_REQ *req, int nid, int lastpos)
{
return X509at_get_attr_by_NID(req->req_info.attributes, nid, lastpos);
}
int X509_REQ_get_attr_by_OBJ(const X509_REQ *req, const ASN1_OBJECT *obj,
int lastpos)
{
return X509at_get_attr_by_OBJ(req->req_info.attributes, obj, lastpos);
}
X509_ATTRIBUTE *X509_REQ_get_attr(const X509_REQ *req, int loc)
{
return X509at_get_attr(req->req_info.attributes, loc);
}
X509_ATTRIBUTE *X509_REQ_delete_attr(X509_REQ *req, int loc)
{
X509_ATTRIBUTE *attr;
if (req == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
attr = X509at_delete_attr(req->req_info.attributes, loc);
if (attr != NULL)
req->req_info.enc.modified = 1;
return attr;
}
int X509_REQ_add1_attr(X509_REQ *req, X509_ATTRIBUTE *attr)
{
if (req == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (!X509at_add1_attr(&req->req_info.attributes, attr))
return 0;
req->req_info.enc.modified = 1;
return 1;
}
int X509_REQ_add1_attr_by_OBJ(X509_REQ *req,
const ASN1_OBJECT *obj, int type,
const unsigned char *bytes, int len)
{
if (req == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (!X509at_add1_attr_by_OBJ(&req->req_info.attributes, obj,
type, bytes, len))
return 0;
req->req_info.enc.modified = 1;
return 1;
}
int X509_REQ_add1_attr_by_NID(X509_REQ *req,
int nid, int type,
const unsigned char *bytes, int len)
{
if (req == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (!X509at_add1_attr_by_NID(&req->req_info.attributes, nid,
type, bytes, len))
return 0;
req->req_info.enc.modified = 1;
return 1;
}
int X509_REQ_add1_attr_by_txt(X509_REQ *req,
const char *attrname, int type,
const unsigned char *bytes, int len)
{
if (req == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (!X509at_add1_attr_by_txt(&req->req_info.attributes, attrname,
type, bytes, len))
return 0;
req->req_info.enc.modified = 1;
return 1;
}
long X509_REQ_get_version(const X509_REQ *req)
{
return ASN1_INTEGER_get(req->req_info.version);
}
X509_NAME *X509_REQ_get_subject_name(const X509_REQ *req)
{
return req->req_info.subject;
}
void X509_REQ_get0_signature(const X509_REQ *req, const ASN1_BIT_STRING **psig,
const X509_ALGOR **palg)
{
if (psig != NULL)
*psig = req->signature;
if (palg != NULL)
*palg = &req->sig_alg;
}
void X509_REQ_set0_signature(X509_REQ *req, ASN1_BIT_STRING *psig)
{
if (req->signature)
ASN1_BIT_STRING_free(req->signature);
req->signature = psig;
}
int X509_REQ_set1_signature_algo(X509_REQ *req, X509_ALGOR *palg)
{
return X509_ALGOR_copy(&req->sig_alg, palg);
}
int X509_REQ_get_signature_nid(const X509_REQ *req)
{
return OBJ_obj2nid(req->sig_alg.algorithm);
}
int i2d_re_X509_REQ_tbs(X509_REQ *req, unsigned char **pp)
{
if (req == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
req->req_info.enc.modified = 1;
return i2d_X509_REQ_INFO(&req->req_info, pp);
}
| 8,272 | 25.263492 | 80 |
c
|
openssl
|
openssl-master/crypto/x509/x509_set.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include "internal/refcount.h"
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "crypto/asn1.h"
#include "crypto/x509.h"
#include "x509_local.h"
int X509_set_version(X509 *x, long version)
{
if (x == NULL)
return 0;
if (version == X509_get_version(x))
return 1; /* avoid needless modification even re-allocation */
if (version == X509_VERSION_1) {
ASN1_INTEGER_free(x->cert_info.version);
x->cert_info.version = NULL;
x->cert_info.enc.modified = 1;
return 1;
}
if (x->cert_info.version == NULL) {
if ((x->cert_info.version = ASN1_INTEGER_new()) == NULL)
return 0;
}
if (!ASN1_INTEGER_set(x->cert_info.version, version))
return 0;
x->cert_info.enc.modified = 1;
return 1;
}
int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial)
{
ASN1_INTEGER *in;
if (x == NULL)
return 0;
in = &x->cert_info.serialNumber;
if (in != serial)
return ASN1_STRING_copy(in, serial);
x->cert_info.enc.modified = 1;
return 1;
}
int X509_set_issuer_name(X509 *x, const X509_NAME *name)
{
if (x == NULL || !X509_NAME_set(&x->cert_info.issuer, name))
return 0;
x->cert_info.enc.modified = 1;
return 1;
}
int X509_set_subject_name(X509 *x, const X509_NAME *name)
{
if (x == NULL || !X509_NAME_set(&x->cert_info.subject, name))
return 0;
x->cert_info.enc.modified = 1;
return 1;
}
int ossl_x509_set1_time(int *modified, ASN1_TIME **ptm, const ASN1_TIME *tm)
{
ASN1_TIME *new;
if (*ptm == tm)
return 1;
new = ASN1_STRING_dup(tm);
if (tm != NULL && new == NULL)
return 0;
ASN1_TIME_free(*ptm);
*ptm = new;
if (modified != NULL)
*modified = 1;
return 1;
}
int X509_set1_notBefore(X509 *x, const ASN1_TIME *tm)
{
if (x == NULL || tm == NULL)
return 0;
return ossl_x509_set1_time(&x->cert_info.enc.modified,
&x->cert_info.validity.notBefore, tm);
}
int X509_set1_notAfter(X509 *x, const ASN1_TIME *tm)
{
if (x == NULL || tm == NULL)
return 0;
return ossl_x509_set1_time(&x->cert_info.enc.modified,
&x->cert_info.validity.notAfter, tm);
}
int X509_set_pubkey(X509 *x, EVP_PKEY *pkey)
{
if (x == NULL)
return 0;
if (!X509_PUBKEY_set(&(x->cert_info.key), pkey))
return 0;
x->cert_info.enc.modified = 1;
return 1;
}
int X509_up_ref(X509 *x)
{
int i;
if (CRYPTO_UP_REF(&x->references, &i) <= 0)
return 0;
REF_PRINT_COUNT("X509", x);
REF_ASSERT_ISNT(i < 2);
return i > 1;
}
long X509_get_version(const X509 *x)
{
return ASN1_INTEGER_get(x->cert_info.version);
}
const ASN1_TIME *X509_get0_notBefore(const X509 *x)
{
return x->cert_info.validity.notBefore;
}
const ASN1_TIME *X509_get0_notAfter(const X509 *x)
{
return x->cert_info.validity.notAfter;
}
ASN1_TIME *X509_getm_notBefore(const X509 *x)
{
return x->cert_info.validity.notBefore;
}
ASN1_TIME *X509_getm_notAfter(const X509 *x)
{
return x->cert_info.validity.notAfter;
}
int X509_get_signature_type(const X509 *x)
{
return EVP_PKEY_type(OBJ_obj2nid(x->sig_alg.algorithm));
}
X509_PUBKEY *X509_get_X509_PUBKEY(const X509 *x)
{
return x->cert_info.key;
}
const STACK_OF(X509_EXTENSION) *X509_get0_extensions(const X509 *x)
{
return x->cert_info.extensions;
}
void X509_get0_uids(const X509 *x, const ASN1_BIT_STRING **piuid,
const ASN1_BIT_STRING **psuid)
{
if (piuid != NULL)
*piuid = x->cert_info.issuerUID;
if (psuid != NULL)
*psuid = x->cert_info.subjectUID;
}
const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x)
{
return &x->cert_info.signature;
}
int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid,
int *secbits, uint32_t *flags)
{
if (mdnid != NULL)
*mdnid = siginf->mdnid;
if (pknid != NULL)
*pknid = siginf->pknid;
if (secbits != NULL)
*secbits = siginf->secbits;
if (flags != NULL)
*flags = siginf->flags;
return (siginf->flags & X509_SIG_INFO_VALID) != 0;
}
void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid,
int secbits, uint32_t flags)
{
siginf->mdnid = mdnid;
siginf->pknid = pknid;
siginf->secbits = secbits;
siginf->flags = flags;
}
int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits,
uint32_t *flags)
{
X509_check_purpose(x, -1, -1);
return X509_SIG_INFO_get(&x->siginf, mdnid, pknid, secbits, flags);
}
/* Modify *siginf according to alg and sig. Return 1 on success, else 0. */
static int x509_sig_info_init(X509_SIG_INFO *siginf, const X509_ALGOR *alg,
const ASN1_STRING *sig, const EVP_PKEY *pubkey)
{
int pknid, mdnid;
const EVP_MD *md;
const EVP_PKEY_ASN1_METHOD *ameth;
siginf->mdnid = NID_undef;
siginf->pknid = NID_undef;
siginf->secbits = -1;
siginf->flags = 0;
if (!OBJ_find_sigid_algs(OBJ_obj2nid(alg->algorithm), &mdnid, &pknid)
|| pknid == NID_undef) {
ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_SIGID_ALGS);
return 0;
}
siginf->mdnid = mdnid;
siginf->pknid = pknid;
switch (mdnid) {
case NID_undef:
/* If we have one, use a custom handler for this algorithm */
ameth = EVP_PKEY_asn1_find(NULL, pknid);
if (ameth != NULL && ameth->siginf_set != NULL
&& ameth->siginf_set(siginf, alg, sig))
break;
if (pubkey != NULL) {
int secbits;
secbits = EVP_PKEY_get_security_bits(pubkey);
if (secbits != 0) {
siginf->secbits = secbits;
break;
}
}
ERR_raise(ERR_LIB_X509, X509_R_ERROR_USING_SIGINF_SET);
return 0;
/*
* SHA1 and MD5 are known to be broken. Reduce security bits so that
* they're no longer accepted at security level 1.
* The real values don't really matter as long as they're lower than 80,
* which is our security level 1.
*/
case NID_sha1:
/*
* https://eprint.iacr.org/2020/014 puts a chosen-prefix attack
* for SHA1 at2^63.4
*/
siginf->secbits = 63;
break;
case NID_md5:
/*
* https://documents.epfl.ch/users/l/le/lenstra/public/papers/lat.pdf
* puts a chosen-prefix attack for MD5 at 2^39.
*/
siginf->secbits = 39;
break;
case NID_id_GostR3411_94:
/*
* There is a collision attack on GOST R 34.11-94 at 2^105, see
* https://link.springer.com/chapter/10.1007%2F978-3-540-85174-5_10
*/
siginf->secbits = 105;
break;
default:
/* Security bits: half number of bits in digest */
if ((md = EVP_get_digestbynid(mdnid)) == NULL) {
ERR_raise(ERR_LIB_X509, X509_R_ERROR_GETTING_MD_BY_NID);
return 0;
}
siginf->secbits = EVP_MD_get_size(md) * 4;
break;
}
switch (mdnid) {
case NID_sha1:
case NID_sha256:
case NID_sha384:
case NID_sha512:
siginf->flags |= X509_SIG_INFO_TLS;
}
siginf->flags |= X509_SIG_INFO_VALID;
return 1;
}
/* Returns 1 on success, 0 on failure */
int ossl_x509_init_sig_info(X509 *x)
{
return x509_sig_info_init(&x->siginf, &x->sig_alg, &x->signature,
X509_PUBKEY_get0(x->cert_info.key));
}
| 8,098 | 25.817881 | 80 |
c
|
openssl
|
openssl-master/crypto/x509/x509_trust.c
|
/*
* Copyright 1999-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/x509v3.h>
#include "crypto/x509.h"
static int tr_cmp(const X509_TRUST *const *a, const X509_TRUST *const *b);
static void trtable_free(X509_TRUST *p);
static int trust_1oidany(X509_TRUST *trust, X509 *x, int flags);
static int trust_1oid(X509_TRUST *trust, X509 *x, int flags);
static int trust_compat(X509_TRUST *trust, X509 *x, int flags);
static int obj_trust(int id, X509 *x, int flags);
static int (*default_trust) (int id, X509 *x, int flags) = obj_trust;
/*
* WARNING: the following table should be kept in order of trust and without
* any gaps so we can just subtract the minimum trust value to get an index
* into the table
*/
static X509_TRUST trstandard[] = {
{X509_TRUST_COMPAT, 0, trust_compat, "compatible", 0, NULL},
{X509_TRUST_SSL_CLIENT, 0, trust_1oidany, "SSL Client", NID_client_auth,
NULL},
{X509_TRUST_SSL_SERVER, 0, trust_1oidany, "SSL Server", NID_server_auth,
NULL},
{X509_TRUST_EMAIL, 0, trust_1oidany, "S/MIME email", NID_email_protect,
NULL},
{X509_TRUST_OBJECT_SIGN, 0, trust_1oidany, "Object Signer", NID_code_sign,
NULL},
{X509_TRUST_OCSP_SIGN, 0, trust_1oid, "OCSP responder", NID_OCSP_sign,
NULL},
{X509_TRUST_OCSP_REQUEST, 0, trust_1oid, "OCSP request", NID_ad_OCSP,
NULL},
{X509_TRUST_TSA, 0, trust_1oidany, "TSA server", NID_time_stamp, NULL}
};
#define X509_TRUST_COUNT OSSL_NELEM(trstandard)
static STACK_OF(X509_TRUST) *trtable = NULL;
static int tr_cmp(const X509_TRUST *const *a, const X509_TRUST *const *b)
{
return (*a)->trust - (*b)->trust;
}
int (*X509_TRUST_set_default(int (*trust) (int, X509 *, int))) (int, X509 *,
int) {
int (*oldtrust) (int, X509 *, int);
oldtrust = default_trust;
default_trust = trust;
return oldtrust;
}
/* Returns X509_TRUST_TRUSTED, X509_TRUST_REJECTED, or X509_TRUST_UNTRUSTED */
int X509_check_trust(X509 *x, int id, int flags)
{
X509_TRUST *pt;
int idx;
/* We get this as a default value */
if (id == X509_TRUST_DEFAULT)
return obj_trust(NID_anyExtendedKeyUsage, x,
flags | X509_TRUST_DO_SS_COMPAT);
idx = X509_TRUST_get_by_id(id);
if (idx < 0)
return default_trust(id, x, flags);
pt = X509_TRUST_get0(idx);
return pt->check_trust(pt, x, flags);
}
int X509_TRUST_get_count(void)
{
if (!trtable)
return X509_TRUST_COUNT;
return sk_X509_TRUST_num(trtable) + X509_TRUST_COUNT;
}
X509_TRUST *X509_TRUST_get0(int idx)
{
if (idx < 0)
return NULL;
if (idx < (int)X509_TRUST_COUNT)
return trstandard + idx;
return sk_X509_TRUST_value(trtable, idx - X509_TRUST_COUNT);
}
int X509_TRUST_get_by_id(int id)
{
X509_TRUST tmp;
int idx;
if ((id >= X509_TRUST_MIN) && (id <= X509_TRUST_MAX))
return id - X509_TRUST_MIN;
if (trtable == NULL)
return -1;
tmp.trust = id;
/* Ideally, this would be done under lock */
sk_X509_TRUST_sort(trtable);
idx = sk_X509_TRUST_find(trtable, &tmp);
if (idx < 0)
return -1;
return idx + X509_TRUST_COUNT;
}
int X509_TRUST_set(int *t, int trust)
{
if (X509_TRUST_get_by_id(trust) < 0) {
ERR_raise(ERR_LIB_X509, X509_R_INVALID_TRUST);
return 0;
}
*t = trust;
return 1;
}
int X509_TRUST_add(int id, int flags, int (*ck) (X509_TRUST *, X509 *, int),
const char *name, int arg1, void *arg2)
{
int idx;
X509_TRUST *trtmp;
/*
* This is set according to what we change: application can't set it
*/
flags &= ~X509_TRUST_DYNAMIC;
/* This will always be set for application modified trust entries */
flags |= X509_TRUST_DYNAMIC_NAME;
/* Get existing entry if any */
idx = X509_TRUST_get_by_id(id);
/* Need a new entry */
if (idx < 0) {
if ((trtmp = OPENSSL_malloc(sizeof(*trtmp))) == NULL)
return 0;
trtmp->flags = X509_TRUST_DYNAMIC;
} else
trtmp = X509_TRUST_get0(idx);
/* OPENSSL_free existing name if dynamic */
if (trtmp->flags & X509_TRUST_DYNAMIC_NAME)
OPENSSL_free(trtmp->name);
/* dup supplied name */
if ((trtmp->name = OPENSSL_strdup(name)) == NULL)
goto err;
/* Keep the dynamic flag of existing entry */
trtmp->flags &= X509_TRUST_DYNAMIC;
/* Set all other flags */
trtmp->flags |= flags;
trtmp->trust = id;
trtmp->check_trust = ck;
trtmp->arg1 = arg1;
trtmp->arg2 = arg2;
/* If its a new entry manage the dynamic table */
if (idx < 0) {
if (trtable == NULL
&& (trtable = sk_X509_TRUST_new(tr_cmp)) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
}
if (!sk_X509_TRUST_push(trtable, trtmp)) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
}
}
return 1;
err:
if (idx < 0) {
OPENSSL_free(trtmp->name);
OPENSSL_free(trtmp);
}
return 0;
}
static void trtable_free(X509_TRUST *p)
{
if (p == NULL)
return;
if (p->flags & X509_TRUST_DYNAMIC) {
if (p->flags & X509_TRUST_DYNAMIC_NAME)
OPENSSL_free(p->name);
OPENSSL_free(p);
}
}
void X509_TRUST_cleanup(void)
{
sk_X509_TRUST_pop_free(trtable, trtable_free);
trtable = NULL;
}
int X509_TRUST_get_flags(const X509_TRUST *xp)
{
return xp->flags;
}
char *X509_TRUST_get0_name(const X509_TRUST *xp)
{
return xp->name;
}
int X509_TRUST_get_trust(const X509_TRUST *xp)
{
return xp->trust;
}
static int trust_1oidany(X509_TRUST *trust, X509 *x, int flags)
{
/*
* Declare the chain verified if the desired trust OID is not rejected in
* any auxiliary trust info for this certificate, and the OID is either
* expressly trusted, or else either "anyEKU" is trusted, or the
* certificate is self-signed and X509_TRUST_NO_SS_COMPAT is not set.
*/
flags |= X509_TRUST_DO_SS_COMPAT | X509_TRUST_OK_ANY_EKU;
return obj_trust(trust->arg1, x, flags);
}
static int trust_1oid(X509_TRUST *trust, X509 *x, int flags)
{
/*
* Declare the chain verified only if the desired trust OID is not
* rejected and is expressly trusted. Neither "anyEKU" nor "compat"
* trust in self-signed certificates apply.
*/
flags &= ~(X509_TRUST_DO_SS_COMPAT | X509_TRUST_OK_ANY_EKU);
return obj_trust(trust->arg1, x, flags);
}
static int trust_compat(X509_TRUST *trust, X509 *x, int flags)
{
/* Call for side-effect of setting EXFLAG_SS for self-signed-certs */
if (X509_check_purpose(x, -1, 0) != 1)
return X509_TRUST_UNTRUSTED;
if ((flags & X509_TRUST_NO_SS_COMPAT) == 0 && (x->ex_flags & EXFLAG_SS))
return X509_TRUST_TRUSTED;
else
return X509_TRUST_UNTRUSTED;
}
static int obj_trust(int id, X509 *x, int flags)
{
X509_CERT_AUX *ax = x->aux;
int i;
if (ax != NULL && ax->reject != NULL) {
for (i = 0; i < sk_ASN1_OBJECT_num(ax->reject); i++) {
ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(ax->reject, i);
int nid = OBJ_obj2nid(obj);
if (nid == id || (nid == NID_anyExtendedKeyUsage &&
(flags & X509_TRUST_OK_ANY_EKU)))
return X509_TRUST_REJECTED;
}
}
if (ax != NULL && ax->trust != NULL) {
for (i = 0; i < sk_ASN1_OBJECT_num(ax->trust); i++) {
ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(ax->trust, i);
int nid = OBJ_obj2nid(obj);
if (nid == id || (nid == NID_anyExtendedKeyUsage &&
(flags & X509_TRUST_OK_ANY_EKU)))
return X509_TRUST_TRUSTED;
}
/*
* Reject when explicit trust EKU are set and none match.
*
* Returning untrusted is enough for for full chains that end in
* self-signed roots, because when explicit trust is specified it
* suppresses the default blanket trust of self-signed objects.
*
* But for partial chains, this is not enough, because absent a similar
* trust-self-signed policy, non matching EKUs are indistinguishable
* from lack of EKU constraints.
*
* Therefore, failure to match any trusted purpose must trigger an
* explicit reject.
*/
return X509_TRUST_REJECTED;
}
if ((flags & X509_TRUST_DO_SS_COMPAT) == 0)
return X509_TRUST_UNTRUSTED;
/*
* Not rejected, and there is no list of accepted uses, try compat.
*/
return trust_compat(NULL, x, flags);
}
| 9,040 | 29.136667 | 79 |
c
|
openssl
|
openssl-master/crypto/x509/x509_txt.c
|
/*
* Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <time.h>
#include <errno.h>
#include "internal/cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/evp.h>
#include <openssl/asn1.h>
#include <openssl/x509.h>
#include <openssl/objects.h>
const char *X509_verify_cert_error_string(long n)
{
switch ((int)n) {
case X509_V_OK:
return "ok";
case X509_V_ERR_UNSPECIFIED:
return "unspecified certificate verification error";
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
return "unable to get issuer certificate";
case X509_V_ERR_UNABLE_TO_GET_CRL:
return "unable to get certificate CRL";
case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
return "unable to decrypt certificate's signature";
case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
return "unable to decrypt CRL's signature";
case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
return "unable to decode issuer public key";
case X509_V_ERR_CERT_SIGNATURE_FAILURE:
return "certificate signature failure";
case X509_V_ERR_CRL_SIGNATURE_FAILURE:
return "CRL signature failure";
case X509_V_ERR_CERT_NOT_YET_VALID:
return "certificate is not yet valid";
case X509_V_ERR_CERT_HAS_EXPIRED:
return "certificate has expired";
case X509_V_ERR_CRL_NOT_YET_VALID:
return "CRL is not yet valid";
case X509_V_ERR_CRL_HAS_EXPIRED:
return "CRL has expired";
case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
return "format error in certificate's notBefore field";
case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
return "format error in certificate's notAfter field";
case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
return "format error in CRL's lastUpdate field";
case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
return "format error in CRL's nextUpdate field";
case X509_V_ERR_OUT_OF_MEM:
return "out of memory";
case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
return "self-signed certificate";
case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
return "self-signed certificate in certificate chain";
case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
return "unable to get local issuer certificate";
case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
return "unable to verify the first certificate";
case X509_V_ERR_CERT_CHAIN_TOO_LONG:
return "certificate chain too long";
case X509_V_ERR_CERT_REVOKED:
return "certificate revoked";
case X509_V_ERR_NO_ISSUER_PUBLIC_KEY:
return "issuer certificate doesn't have a public key";
case X509_V_ERR_PATH_LENGTH_EXCEEDED:
return "path length constraint exceeded";
case X509_V_ERR_INVALID_PURPOSE:
return "unsuitable certificate purpose";
case X509_V_ERR_CERT_UNTRUSTED:
return "certificate not trusted";
case X509_V_ERR_CERT_REJECTED:
return "certificate rejected";
case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
return "subject issuer mismatch";
case X509_V_ERR_AKID_SKID_MISMATCH:
return "authority and subject key identifier mismatch";
case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH:
return "authority and issuer serial number mismatch";
case X509_V_ERR_KEYUSAGE_NO_CERTSIGN:
return "key usage does not include certificate signing";
case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
return "unable to get CRL issuer certificate";
case X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION:
return "unhandled critical extension";
case X509_V_ERR_KEYUSAGE_NO_CRL_SIGN:
return "key usage does not include CRL signing";
case X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION:
return "unhandled critical CRL extension";
case X509_V_ERR_INVALID_NON_CA:
return "invalid non-CA certificate (has CA markings)";
case X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED:
return "proxy path length constraint exceeded";
case X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE:
return "key usage does not include digital signature";
case X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED:
return
"proxy certificates not allowed, please set the appropriate flag";
case X509_V_ERR_INVALID_EXTENSION:
return "invalid or inconsistent certificate extension";
case X509_V_ERR_INVALID_POLICY_EXTENSION:
return "invalid or inconsistent certificate policy extension";
case X509_V_ERR_NO_EXPLICIT_POLICY:
return "no explicit policy";
case X509_V_ERR_DIFFERENT_CRL_SCOPE:
return "different CRL scope";
case X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE:
return "unsupported extension feature";
case X509_V_ERR_UNNESTED_RESOURCE:
return "RFC 3779 resource not subset of parent's resources";
case X509_V_ERR_PERMITTED_VIOLATION:
return "permitted subtree violation";
case X509_V_ERR_EXCLUDED_VIOLATION:
return "excluded subtree violation";
case X509_V_ERR_SUBTREE_MINMAX:
return "name constraints minimum and maximum not supported";
case X509_V_ERR_APPLICATION_VERIFICATION:
return "application verification failure";
case X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE:
return "unsupported name constraint type";
case X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX:
return "unsupported or invalid name constraint syntax";
case X509_V_ERR_UNSUPPORTED_NAME_SYNTAX:
return "unsupported or invalid name syntax";
case X509_V_ERR_CRL_PATH_VALIDATION_ERROR:
return "CRL path validation error";
case X509_V_ERR_PATH_LOOP:
return "path loop";
case X509_V_ERR_SUITE_B_INVALID_VERSION:
return "Suite B: certificate version invalid";
case X509_V_ERR_SUITE_B_INVALID_ALGORITHM:
return "Suite B: invalid public key algorithm";
case X509_V_ERR_SUITE_B_INVALID_CURVE:
return "Suite B: invalid ECC curve";
case X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM:
return "Suite B: invalid signature algorithm";
case X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED:
return "Suite B: curve not allowed for this LOS";
case X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256:
return "Suite B: cannot sign P-384 with P-256";
case X509_V_ERR_HOSTNAME_MISMATCH:
return "hostname mismatch";
case X509_V_ERR_EMAIL_MISMATCH:
return "email address mismatch";
case X509_V_ERR_IP_ADDRESS_MISMATCH:
return "IP address mismatch";
case X509_V_ERR_DANE_NO_MATCH:
return "no matching DANE TLSA records";
case X509_V_ERR_EE_KEY_TOO_SMALL:
return "EE certificate key too weak";
case X509_V_ERR_CA_KEY_TOO_SMALL:
return "CA certificate key too weak";
case X509_V_ERR_CA_MD_TOO_WEAK:
return "CA signature digest algorithm too weak";
case X509_V_ERR_INVALID_CALL:
return "invalid certificate verification context";
case X509_V_ERR_STORE_LOOKUP:
return "issuer certificate lookup error";
case X509_V_ERR_NO_VALID_SCTS:
return "Certificate Transparency required, but no valid SCTs found";
case X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION:
return "proxy subject name violation";
case X509_V_ERR_OCSP_VERIFY_NEEDED:
return "OCSP verification needed";
case X509_V_ERR_OCSP_VERIFY_FAILED:
return "OCSP verification failed";
case X509_V_ERR_OCSP_CERT_UNKNOWN:
return "OCSP unknown cert";
case X509_V_ERR_UNSUPPORTED_SIGNATURE_ALGORITHM:
return "Cannot find certificate signature algorithm";
case X509_V_ERR_SIGNATURE_ALGORITHM_MISMATCH:
return "subject signature algorithm and issuer public key algorithm mismatch";
case X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY:
return "cert info signature and signature algorithm mismatch";
case X509_V_ERR_INVALID_CA:
return "invalid CA certificate";
case X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA:
return "Path length invalid for non-CA cert";
case X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN:
return "Path length given without key usage keyCertSign";
case X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA:
return "Key usage keyCertSign invalid for non-CA cert";
case X509_V_ERR_ISSUER_NAME_EMPTY:
return "Issuer name empty";
case X509_V_ERR_SUBJECT_NAME_EMPTY:
return "Subject name empty";
case X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER:
return "Missing Authority Key Identifier";
case X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER:
return "Missing Subject Key Identifier";
case X509_V_ERR_EMPTY_SUBJECT_ALT_NAME:
return "Empty Subject Alternative Name extension";
case X509_V_ERR_CA_BCONS_NOT_CRITICAL:
return "Basic Constraints of CA cert not marked critical";
case X509_V_ERR_EMPTY_SUBJECT_SAN_NOT_CRITICAL:
return "Subject empty and Subject Alt Name extension not critical";
case X509_V_ERR_AUTHORITY_KEY_IDENTIFIER_CRITICAL:
return "Authority Key Identifier marked critical";
case X509_V_ERR_SUBJECT_KEY_IDENTIFIER_CRITICAL:
return "Subject Key Identifier marked critical";
case X509_V_ERR_CA_CERT_MISSING_KEY_USAGE:
return "CA cert does not include key usage extension";
case X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3:
return "Using cert extension requires at least X509v3";
case X509_V_ERR_EC_KEY_EXPLICIT_PARAMS:
return "Certificate public key has explicit ECC parameters";
case X509_V_ERR_RPK_UNTRUSTED:
return "Raw public key untrusted, no trusted keys configured";
/*
* Entries must be kept consistent with include/openssl/x509_vfy.h.in
* and with doc/man3/X509_STORE_CTX_get_error.pod
*/
default:
/* Printing an error number into a static buffer is not thread-safe */
return "unknown certificate verification error";
}
}
| 10,295 | 44.157895 | 86 |
c
|
openssl
|
openssl-master/crypto/x509/x509_v3.c
|
/*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/safestack.h>
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "x509_local.h"
int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x)
{
int ret;
if (x == NULL)
return 0;
ret = sk_X509_EXTENSION_num(x);
return ret > 0 ? ret : 0;
}
int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x, int nid,
int lastpos)
{
ASN1_OBJECT *obj;
obj = OBJ_nid2obj(nid);
if (obj == NULL)
return -2;
return X509v3_get_ext_by_OBJ(x, obj, lastpos);
}
int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *sk,
const ASN1_OBJECT *obj, int lastpos)
{
int n;
X509_EXTENSION *ex;
if (sk == NULL)
return -1;
lastpos++;
if (lastpos < 0)
lastpos = 0;
n = sk_X509_EXTENSION_num(sk);
for (; lastpos < n; lastpos++) {
ex = sk_X509_EXTENSION_value(sk, lastpos);
if (OBJ_cmp(ex->object, obj) == 0)
return lastpos;
}
return -1;
}
int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *sk, int crit,
int lastpos)
{
int n;
X509_EXTENSION *ex;
if (sk == NULL)
return -1;
lastpos++;
if (lastpos < 0)
lastpos = 0;
n = sk_X509_EXTENSION_num(sk);
for (; lastpos < n; lastpos++) {
ex = sk_X509_EXTENSION_value(sk, lastpos);
if (((ex->critical > 0) && crit) || ((ex->critical <= 0) && !crit))
return lastpos;
}
return -1;
}
X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc)
{
if (x == NULL || sk_X509_EXTENSION_num(x) <= loc || loc < 0)
return NULL;
else
return sk_X509_EXTENSION_value(x, loc);
}
X509_EXTENSION *X509v3_delete_ext(STACK_OF(X509_EXTENSION) *x, int loc)
{
X509_EXTENSION *ret;
if (x == NULL || sk_X509_EXTENSION_num(x) <= loc || loc < 0)
return NULL;
ret = sk_X509_EXTENSION_delete(x, loc);
return ret;
}
STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x,
X509_EXTENSION *ex, int loc)
{
X509_EXTENSION *new_ex = NULL;
int n;
STACK_OF(X509_EXTENSION) *sk = NULL;
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
goto err;
}
if (*x == NULL) {
if ((sk = sk_X509_EXTENSION_new_null()) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
}
} else
sk = *x;
n = sk_X509_EXTENSION_num(sk);
if (loc > n)
loc = n;
else if (loc < 0)
loc = n;
if ((new_ex = X509_EXTENSION_dup(ex)) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
goto err;
}
if (!sk_X509_EXTENSION_insert(sk, new_ex, loc)) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
}
if (*x == NULL)
*x = sk;
return sk;
err:
X509_EXTENSION_free(new_ex);
if (x != NULL && *x == NULL)
sk_X509_EXTENSION_free(sk);
return NULL;
}
X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex, int nid,
int crit,
ASN1_OCTET_STRING *data)
{
ASN1_OBJECT *obj;
X509_EXTENSION *ret;
obj = OBJ_nid2obj(nid);
if (obj == NULL) {
ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_NID);
return NULL;
}
ret = X509_EXTENSION_create_by_OBJ(ex, obj, crit, data);
if (ret == NULL)
ASN1_OBJECT_free(obj);
return ret;
}
X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex,
const ASN1_OBJECT *obj, int crit,
ASN1_OCTET_STRING *data)
{
X509_EXTENSION *ret;
if ((ex == NULL) || (*ex == NULL)) {
if ((ret = X509_EXTENSION_new()) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
return NULL;
}
} else
ret = *ex;
if (!X509_EXTENSION_set_object(ret, obj))
goto err;
if (!X509_EXTENSION_set_critical(ret, crit))
goto err;
if (!X509_EXTENSION_set_data(ret, data))
goto err;
if ((ex != NULL) && (*ex == NULL))
*ex = ret;
return ret;
err:
if ((ex == NULL) || (ret != *ex))
X509_EXTENSION_free(ret);
return NULL;
}
int X509_EXTENSION_set_object(X509_EXTENSION *ex, const ASN1_OBJECT *obj)
{
if ((ex == NULL) || (obj == NULL))
return 0;
ASN1_OBJECT_free(ex->object);
ex->object = OBJ_dup(obj);
return ex->object != NULL;
}
int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit)
{
if (ex == NULL)
return 0;
ex->critical = (crit) ? 0xFF : -1;
return 1;
}
int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data)
{
int i;
if (ex == NULL)
return 0;
i = ASN1_OCTET_STRING_set(&ex->value, data->data, data->length);
if (!i)
return 0;
return 1;
}
ASN1_OBJECT *X509_EXTENSION_get_object(X509_EXTENSION *ex)
{
if (ex == NULL)
return NULL;
return ex->object;
}
ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ex)
{
if (ex == NULL)
return NULL;
return &ex->value;
}
int X509_EXTENSION_get_critical(const X509_EXTENSION *ex)
{
if (ex == NULL)
return 0;
if (ex->critical > 0)
return 1;
return 0;
}
| 5,934 | 23.524793 | 78 |
c
|
openssl
|
openssl-master/crypto/x509/x509_vpm.c
|
/*
* Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/crypto.h>
#include <openssl/buffer.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "crypto/x509.h"
#include "x509_local.h"
/* X509_VERIFY_PARAM functions */
#define SET_HOST 0
#define ADD_HOST 1
static char *str_copy(const char *s)
{
return OPENSSL_strdup(s);
}
static void str_free(char *s)
{
OPENSSL_free(s);
}
static int int_x509_param_set_hosts(X509_VERIFY_PARAM *vpm, int mode,
const char *name, size_t namelen)
{
char *copy;
/*
* Refuse names with embedded NUL bytes, except perhaps as final byte.
* XXX: Do we need to push an error onto the error stack?
*/
if (namelen == 0 || name == NULL)
namelen = name ? strlen(name) : 0;
else if (name != NULL
&& memchr(name, '\0', namelen > 1 ? namelen - 1 : namelen) != NULL)
return 0;
if (namelen > 0 && name[namelen - 1] == '\0')
--namelen;
if (mode == SET_HOST) {
sk_OPENSSL_STRING_pop_free(vpm->hosts, str_free);
vpm->hosts = NULL;
}
if (name == NULL || namelen == 0)
return 1;
copy = OPENSSL_strndup(name, namelen);
if (copy == NULL)
return 0;
if (vpm->hosts == NULL &&
(vpm->hosts = sk_OPENSSL_STRING_new_null()) == NULL) {
OPENSSL_free(copy);
return 0;
}
if (!sk_OPENSSL_STRING_push(vpm->hosts, copy)) {
OPENSSL_free(copy);
if (sk_OPENSSL_STRING_num(vpm->hosts) == 0) {
sk_OPENSSL_STRING_free(vpm->hosts);
vpm->hosts = NULL;
}
return 0;
}
return 1;
}
X509_VERIFY_PARAM *X509_VERIFY_PARAM_new(void)
{
X509_VERIFY_PARAM *param;
param = OPENSSL_zalloc(sizeof(*param));
if (param == NULL)
return NULL;
param->trust = X509_TRUST_DEFAULT;
/* param->inh_flags = X509_VP_FLAG_DEFAULT; */
param->depth = -1;
param->auth_level = -1; /* -1 means unset, 0 is explicit */
return param;
}
void X509_VERIFY_PARAM_free(X509_VERIFY_PARAM *param)
{
if (param == NULL)
return;
sk_ASN1_OBJECT_pop_free(param->policies, ASN1_OBJECT_free);
sk_OPENSSL_STRING_pop_free(param->hosts, str_free);
OPENSSL_free(param->peername);
OPENSSL_free(param->email);
OPENSSL_free(param->ip);
OPENSSL_free(param);
}
/*-
* This function determines how parameters are "inherited" from one structure
* to another. There are several different ways this can happen.
*
* 1. If a child structure needs to have its values initialized from a parent
* they are simply copied across. For example SSL_CTX copied to SSL.
* 2. If the structure should take on values only if they are currently unset.
* For example the values in an SSL structure will take appropriate value
* for SSL servers or clients but only if the application has not set new
* ones.
*
* The "inh_flags" field determines how this function behaves.
*
* Normally any values which are set in the default are not copied from the
* destination and verify flags are ORed together.
*
* If X509_VP_FLAG_DEFAULT is set then anything set in the source is copied
* to the destination. Effectively the values in "to" become default values
* which will be used only if nothing new is set in "from".
*
* If X509_VP_FLAG_OVERWRITE is set then all value are copied across whether
* they are set or not. Flags is still Ored though.
*
* If X509_VP_FLAG_RESET_FLAGS is set then the flags value is copied instead
* of ORed.
*
* If X509_VP_FLAG_LOCKED is set then no values are copied.
*
* If X509_VP_FLAG_ONCE is set then the current inh_flags setting is zeroed
* after the next call.
*/
/* Macro to test if a field should be copied from src to dest */
#define test_x509_verify_param_copy(field, def) \
(to_overwrite || (src->field != def && (to_default || dest->field == def)))
/* Macro to test and copy a field if necessary */
#define x509_verify_param_copy(field, def) \
if (test_x509_verify_param_copy(field, def)) \
dest->field = src->field;
int X509_VERIFY_PARAM_inherit(X509_VERIFY_PARAM *dest,
const X509_VERIFY_PARAM *src)
{
unsigned long inh_flags;
int to_default, to_overwrite;
if (src == NULL)
return 1;
inh_flags = dest->inh_flags | src->inh_flags;
if ((inh_flags & X509_VP_FLAG_ONCE) != 0)
dest->inh_flags = 0;
if ((inh_flags & X509_VP_FLAG_LOCKED) != 0)
return 1;
to_default = (inh_flags & X509_VP_FLAG_DEFAULT) != 0;
to_overwrite = (inh_flags & X509_VP_FLAG_OVERWRITE) != 0;
x509_verify_param_copy(purpose, 0);
x509_verify_param_copy(trust, X509_TRUST_DEFAULT);
x509_verify_param_copy(depth, -1);
x509_verify_param_copy(auth_level, -1);
/* If overwrite or check time not set, copy across */
if (to_overwrite || (dest->flags & X509_V_FLAG_USE_CHECK_TIME) == 0) {
dest->check_time = src->check_time;
dest->flags &= ~X509_V_FLAG_USE_CHECK_TIME;
/* Don't need to copy flag: that is done below */
}
if ((inh_flags & X509_VP_FLAG_RESET_FLAGS) != 0)
dest->flags = 0;
dest->flags |= src->flags;
if (test_x509_verify_param_copy(policies, NULL)) {
if (!X509_VERIFY_PARAM_set1_policies(dest, src->policies))
return 0;
}
x509_verify_param_copy(hostflags, 0);
if (test_x509_verify_param_copy(hosts, NULL)) {
sk_OPENSSL_STRING_pop_free(dest->hosts, str_free);
dest->hosts = NULL;
if (src->hosts != NULL) {
dest->hosts =
sk_OPENSSL_STRING_deep_copy(src->hosts, str_copy, str_free);
if (dest->hosts == NULL)
return 0;
}
}
if (test_x509_verify_param_copy(email, NULL)) {
if (!X509_VERIFY_PARAM_set1_email(dest, src->email, src->emaillen))
return 0;
}
if (test_x509_verify_param_copy(ip, NULL)) {
if (!X509_VERIFY_PARAM_set1_ip(dest, src->ip, src->iplen))
return 0;
}
return 1;
}
int X509_VERIFY_PARAM_set1(X509_VERIFY_PARAM *to,
const X509_VERIFY_PARAM *from)
{
unsigned long save_flags;
int ret;
if (to == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
save_flags = to->inh_flags;
to->inh_flags |= X509_VP_FLAG_DEFAULT;
ret = X509_VERIFY_PARAM_inherit(to, from);
to->inh_flags = save_flags;
return ret;
}
static int int_x509_param_set1(char **pdest, size_t *pdestlen,
const char *src, size_t srclen)
{
char *tmp;
if (src != NULL) {
if (srclen == 0)
srclen = strlen(src);
tmp = OPENSSL_malloc(srclen + 1);
if (tmp == NULL)
return 0;
memcpy(tmp, src, srclen);
tmp[srclen] = '\0'; /* enforce NUL termination */
} else {
tmp = NULL;
srclen = 0;
}
OPENSSL_free(*pdest);
*pdest = tmp;
if (pdestlen != NULL)
*pdestlen = srclen;
return 1;
}
int X509_VERIFY_PARAM_set1_name(X509_VERIFY_PARAM *param, const char *name)
{
OPENSSL_free(param->name);
param->name = OPENSSL_strdup(name);
return param->name != NULL;
}
int X509_VERIFY_PARAM_set_flags(X509_VERIFY_PARAM *param, unsigned long flags)
{
param->flags |= flags;
if ((flags & X509_V_FLAG_POLICY_MASK) != 0)
param->flags |= X509_V_FLAG_POLICY_CHECK;
return 1;
}
int X509_VERIFY_PARAM_clear_flags(X509_VERIFY_PARAM *param,
unsigned long flags)
{
param->flags &= ~flags;
return 1;
}
unsigned long X509_VERIFY_PARAM_get_flags(const X509_VERIFY_PARAM *param)
{
return param->flags;
}
uint32_t X509_VERIFY_PARAM_get_inh_flags(const X509_VERIFY_PARAM *param)
{
return param->inh_flags;
}
int X509_VERIFY_PARAM_set_inh_flags(X509_VERIFY_PARAM *param, uint32_t flags)
{
param->inh_flags = flags;
return 1;
}
int X509_VERIFY_PARAM_set_purpose(X509_VERIFY_PARAM *param, int purpose)
{
return X509_PURPOSE_set(¶m->purpose, purpose);
}
int X509_VERIFY_PARAM_set_trust(X509_VERIFY_PARAM *param, int trust)
{
return X509_TRUST_set(¶m->trust, trust);
}
void X509_VERIFY_PARAM_set_depth(X509_VERIFY_PARAM *param, int depth)
{
param->depth = depth;
}
void X509_VERIFY_PARAM_set_auth_level(X509_VERIFY_PARAM *param, int auth_level)
{
param->auth_level = auth_level;
}
time_t X509_VERIFY_PARAM_get_time(const X509_VERIFY_PARAM *param)
{
return param->check_time;
}
void X509_VERIFY_PARAM_set_time(X509_VERIFY_PARAM *param, time_t t)
{
param->check_time = t;
param->flags |= X509_V_FLAG_USE_CHECK_TIME;
}
int X509_VERIFY_PARAM_add0_policy(X509_VERIFY_PARAM *param,
ASN1_OBJECT *policy)
{
if (param->policies == NULL) {
param->policies = sk_ASN1_OBJECT_new_null();
if (param->policies == NULL)
return 0;
}
return sk_ASN1_OBJECT_push(param->policies, policy);
}
int X509_VERIFY_PARAM_set1_policies(X509_VERIFY_PARAM *param,
STACK_OF(ASN1_OBJECT) *policies)
{
int i;
ASN1_OBJECT *oid, *doid;
if (param == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
sk_ASN1_OBJECT_pop_free(param->policies, ASN1_OBJECT_free);
if (policies == NULL) {
param->policies = NULL;
return 1;
}
param->policies = sk_ASN1_OBJECT_new_null();
if (param->policies == NULL)
return 0;
for (i = 0; i < sk_ASN1_OBJECT_num(policies); i++) {
oid = sk_ASN1_OBJECT_value(policies, i);
doid = OBJ_dup(oid);
if (doid == NULL)
return 0;
if (!sk_ASN1_OBJECT_push(param->policies, doid)) {
ASN1_OBJECT_free(doid);
return 0;
}
}
param->flags |= X509_V_FLAG_POLICY_CHECK;
return 1;
}
char *X509_VERIFY_PARAM_get0_host(X509_VERIFY_PARAM *param, int idx)
{
return sk_OPENSSL_STRING_value(param->hosts, idx);
}
int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param,
const char *name, size_t namelen)
{
return int_x509_param_set_hosts(param, SET_HOST, name, namelen);
}
int X509_VERIFY_PARAM_add1_host(X509_VERIFY_PARAM *param,
const char *name, size_t namelen)
{
return int_x509_param_set_hosts(param, ADD_HOST, name, namelen);
}
void X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param,
unsigned int flags)
{
param->hostflags = flags;
}
unsigned int X509_VERIFY_PARAM_get_hostflags(const X509_VERIFY_PARAM *param)
{
return param->hostflags;
}
char *X509_VERIFY_PARAM_get0_peername(const X509_VERIFY_PARAM *param)
{
return param->peername;
}
/*
* Move peername from one param structure to another, freeing any name present
* at the target. If the source is a NULL parameter structure, free and zero
* the target peername.
*/
void X509_VERIFY_PARAM_move_peername(X509_VERIFY_PARAM *to,
X509_VERIFY_PARAM *from)
{
char *peername = (from != NULL) ? from->peername : NULL;
if (to->peername != peername) {
OPENSSL_free(to->peername);
to->peername = peername;
}
if (from != NULL)
from->peername = NULL;
}
char *X509_VERIFY_PARAM_get0_email(X509_VERIFY_PARAM *param)
{
return param->email;
}
int X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *param,
const char *email, size_t emaillen)
{
return int_x509_param_set1(¶m->email, ¶m->emaillen,
email, emaillen);
}
static unsigned char
*int_X509_VERIFY_PARAM_get0_ip(X509_VERIFY_PARAM *param, size_t *plen)
{
if (param == NULL || param->ip == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (plen != NULL)
*plen = param->iplen;
return param->ip;
}
char *X509_VERIFY_PARAM_get1_ip_asc(X509_VERIFY_PARAM *param)
{
size_t iplen;
unsigned char *ip = int_X509_VERIFY_PARAM_get0_ip(param, &iplen);
return ip == NULL ? NULL : ossl_ipaddr_to_asc(ip, iplen);
}
int X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param,
const unsigned char *ip, size_t iplen)
{
if (iplen != 0 && iplen != 4 && iplen != 16) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_INVALID_ARGUMENT);
return 0;
}
return int_x509_param_set1((char **)¶m->ip, ¶m->iplen,
(char *)ip, iplen);
}
int X509_VERIFY_PARAM_set1_ip_asc(X509_VERIFY_PARAM *param, const char *ipasc)
{
unsigned char ipout[16];
size_t iplen = (size_t)ossl_a2i_ipadd(ipout, ipasc);
if (iplen == 0)
return 0;
return X509_VERIFY_PARAM_set1_ip(param, ipout, iplen);
}
int X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *param)
{
return param->depth;
}
int X509_VERIFY_PARAM_get_auth_level(const X509_VERIFY_PARAM *param)
{
return param->auth_level;
}
const char *X509_VERIFY_PARAM_get0_name(const X509_VERIFY_PARAM *param)
{
return param->name;
}
#define vpm_empty_id NULL, 0U, NULL, NULL, 0, NULL, 0
/*
* Default verify parameters: these are used for various applications and can
* be overridden by the user specified table. NB: the 'name' field *must* be
* in alphabetical order because it will be searched using OBJ_search.
*/
static const X509_VERIFY_PARAM default_table[] = {
{
"code_sign", /* Code sign parameters */
0, /* check time to use */
0, /* inheritance flags */
0, /* flags */
X509_PURPOSE_CODE_SIGN, /* purpose */
X509_TRUST_OBJECT_SIGN, /* trust */
-1, /* depth */
-1, /* auth_level */
NULL, /* policies */
vpm_empty_id
},
{
"default", /* X509 default parameters */
0, /* check time to use */
0, /* inheritance flags */
X509_V_FLAG_TRUSTED_FIRST, /* flags */
0, /* purpose */
0, /* trust */
100, /* depth */
-1, /* auth_level */
NULL, /* policies */
vpm_empty_id
},
{
"pkcs7", /* S/MIME sign parameters */
0, /* check time to use */
0, /* inheritance flags */
0, /* flags */
X509_PURPOSE_SMIME_SIGN, /* purpose */
X509_TRUST_EMAIL, /* trust */
-1, /* depth */
-1, /* auth_level */
NULL, /* policies */
vpm_empty_id
},
{
"smime_sign", /* S/MIME sign parameters */
0, /* check time to use */
0, /* inheritance flags */
0, /* flags */
X509_PURPOSE_SMIME_SIGN, /* purpose */
X509_TRUST_EMAIL, /* trust */
-1, /* depth */
-1, /* auth_level */
NULL, /* policies */
vpm_empty_id
},
{
"ssl_client", /* SSL/TLS client parameters */
0, /* check time to use */
0, /* inheritance flags */
0, /* flags */
X509_PURPOSE_SSL_CLIENT, /* purpose */
X509_TRUST_SSL_CLIENT, /* trust */
-1, /* depth */
-1, /* auth_level */
NULL, /* policies */
vpm_empty_id
},
{
"ssl_server", /* SSL/TLS server parameters */
0, /* check time to use */
0, /* inheritance flags */
0, /* flags */
X509_PURPOSE_SSL_SERVER, /* purpose */
X509_TRUST_SSL_SERVER, /* trust */
-1, /* depth */
-1, /* auth_level */
NULL, /* policies */
vpm_empty_id
}
};
static STACK_OF(X509_VERIFY_PARAM) *param_table = NULL;
static int table_cmp(const X509_VERIFY_PARAM *a, const X509_VERIFY_PARAM *b)
{
return strcmp(a->name, b->name);
}
DECLARE_OBJ_BSEARCH_CMP_FN(X509_VERIFY_PARAM, X509_VERIFY_PARAM, table);
IMPLEMENT_OBJ_BSEARCH_CMP_FN(X509_VERIFY_PARAM, X509_VERIFY_PARAM, table);
static int param_cmp(const X509_VERIFY_PARAM *const *a,
const X509_VERIFY_PARAM *const *b)
{
return strcmp((*a)->name, (*b)->name);
}
int X509_VERIFY_PARAM_add0_table(X509_VERIFY_PARAM *param)
{
int idx;
X509_VERIFY_PARAM *ptmp;
if (param_table == NULL) {
param_table = sk_X509_VERIFY_PARAM_new(param_cmp);
if (param_table == NULL)
return 0;
} else {
idx = sk_X509_VERIFY_PARAM_find(param_table, param);
if (idx >= 0) {
ptmp = sk_X509_VERIFY_PARAM_delete(param_table, idx);
X509_VERIFY_PARAM_free(ptmp);
}
}
return sk_X509_VERIFY_PARAM_push(param_table, param);
}
int X509_VERIFY_PARAM_get_count(void)
{
int num = OSSL_NELEM(default_table);
if (param_table != NULL)
num += sk_X509_VERIFY_PARAM_num(param_table);
return num;
}
const X509_VERIFY_PARAM *X509_VERIFY_PARAM_get0(int id)
{
int num = OSSL_NELEM(default_table);
if (id < num)
return default_table + id;
return sk_X509_VERIFY_PARAM_value(param_table, id - num);
}
const X509_VERIFY_PARAM *X509_VERIFY_PARAM_lookup(const char *name)
{
int idx;
X509_VERIFY_PARAM pm;
pm.name = (char *)name;
if (param_table != NULL) {
/* Ideally, this would be done under a lock */
sk_X509_VERIFY_PARAM_sort(param_table);
idx = sk_X509_VERIFY_PARAM_find(param_table, &pm);
if (idx >= 0)
return sk_X509_VERIFY_PARAM_value(param_table, idx);
}
return OBJ_bsearch_table(&pm, default_table, OSSL_NELEM(default_table));
}
void X509_VERIFY_PARAM_table_cleanup(void)
{
sk_X509_VERIFY_PARAM_pop_free(param_table, X509_VERIFY_PARAM_free);
param_table = NULL;
}
| 18,862 | 27.930982 | 80 |
c
|
openssl
|
openssl-master/crypto/x509/x509cset.c
|
/*
* Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include "internal/refcount.h"
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
int X509_CRL_set_version(X509_CRL *x, long version)
{
if (x == NULL)
return 0;
if (x->crl.version == NULL) {
if ((x->crl.version = ASN1_INTEGER_new()) == NULL)
return 0;
}
if (!ASN1_INTEGER_set(x->crl.version, version))
return 0;
x->crl.enc.modified = 1;
return 1;
}
int X509_CRL_set_issuer_name(X509_CRL *x, const X509_NAME *name)
{
if (x == NULL)
return 0;
if (!X509_NAME_set(&x->crl.issuer, name))
return 0;
x->crl.enc.modified = 1;
return 1;
}
int X509_CRL_set1_lastUpdate(X509_CRL *x, const ASN1_TIME *tm)
{
if (x == NULL || tm == NULL)
return 0;
return ossl_x509_set1_time(&x->crl.enc.modified, &x->crl.lastUpdate, tm);
}
int X509_CRL_set1_nextUpdate(X509_CRL *x, const ASN1_TIME *tm)
{
if (x == NULL)
return 0;
return ossl_x509_set1_time(&x->crl.enc.modified, &x->crl.nextUpdate, tm);
}
int X509_CRL_sort(X509_CRL *c)
{
int i;
X509_REVOKED *r;
/*
* sort the data so it will be written in serial number order
*/
sk_X509_REVOKED_sort(c->crl.revoked);
for (i = 0; i < sk_X509_REVOKED_num(c->crl.revoked); i++) {
r = sk_X509_REVOKED_value(c->crl.revoked, i);
r->sequence = i;
}
c->crl.enc.modified = 1;
return 1;
}
int X509_CRL_up_ref(X509_CRL *crl)
{
int i;
if (CRYPTO_UP_REF(&crl->references, &i) <= 0)
return 0;
REF_PRINT_COUNT("X509_CRL", crl);
REF_ASSERT_ISNT(i < 2);
return i > 1;
}
long X509_CRL_get_version(const X509_CRL *crl)
{
return ASN1_INTEGER_get(crl->crl.version);
}
const ASN1_TIME *X509_CRL_get0_lastUpdate(const X509_CRL *crl)
{
return crl->crl.lastUpdate;
}
const ASN1_TIME *X509_CRL_get0_nextUpdate(const X509_CRL *crl)
{
return crl->crl.nextUpdate;
}
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
ASN1_TIME *X509_CRL_get_lastUpdate(X509_CRL *crl)
{
return crl->crl.lastUpdate;
}
ASN1_TIME *X509_CRL_get_nextUpdate(X509_CRL *crl)
{
return crl->crl.nextUpdate;
}
#endif
X509_NAME *X509_CRL_get_issuer(const X509_CRL *crl)
{
return crl->crl.issuer;
}
const STACK_OF(X509_EXTENSION) *X509_CRL_get0_extensions(const X509_CRL *crl)
{
return crl->crl.extensions;
}
STACK_OF(X509_REVOKED) *X509_CRL_get_REVOKED(X509_CRL *crl)
{
return crl->crl.revoked;
}
void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig,
const X509_ALGOR **palg)
{
if (psig != NULL)
*psig = &crl->signature;
if (palg != NULL)
*palg = &crl->sig_alg;
}
int X509_CRL_get_signature_nid(const X509_CRL *crl)
{
return OBJ_obj2nid(crl->sig_alg.algorithm);
}
const ASN1_TIME *X509_REVOKED_get0_revocationDate(const X509_REVOKED *x)
{
return x->revocationDate;
}
int X509_REVOKED_set_revocationDate(X509_REVOKED *x, ASN1_TIME *tm)
{
if (x == NULL || tm == NULL)
return 0;
return ossl_x509_set1_time(NULL, &x->revocationDate, tm);
}
const ASN1_INTEGER *X509_REVOKED_get0_serialNumber(const X509_REVOKED *x)
{
return &x->serialNumber;
}
int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial)
{
ASN1_INTEGER *in;
if (x == NULL)
return 0;
in = &x->serialNumber;
if (in != serial)
return ASN1_STRING_copy(in, serial);
return 1;
}
const STACK_OF(X509_EXTENSION) *X509_REVOKED_get0_extensions(const
X509_REVOKED *r)
{
return r->extensions;
}
int i2d_re_X509_CRL_tbs(X509_CRL *crl, unsigned char **pp)
{
crl->crl.enc.modified = 1;
return i2d_X509_CRL_INFO(&crl->crl, pp);
}
| 4,186 | 22.005495 | 79 |
c
|
openssl
|
openssl-master/crypto/x509/x509name.c
|
/*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/safestack.h>
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
int X509_NAME_get_text_by_NID(const X509_NAME *name, int nid,
char *buf, int len)
{
ASN1_OBJECT *obj;
obj = OBJ_nid2obj(nid);
if (obj == NULL)
return -1;
return X509_NAME_get_text_by_OBJ(name, obj, buf, len);
}
int X509_NAME_get_text_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
char *buf, int len)
{
int i;
const ASN1_STRING *data;
i = X509_NAME_get_index_by_OBJ(name, obj, -1);
if (i < 0)
return -1;
data = X509_NAME_ENTRY_get_data(X509_NAME_get_entry(name, i));
if (buf == NULL)
return data->length;
if (len <= 0)
return 0;
i = (data->length > (len - 1)) ? (len - 1) : data->length;
memcpy(buf, data->data, i);
buf[i] = '\0';
return i;
}
int X509_NAME_entry_count(const X509_NAME *name)
{
int ret;
if (name == NULL)
return 0;
ret = sk_X509_NAME_ENTRY_num(name->entries);
return ret > 0 ? ret : 0;
}
int X509_NAME_get_index_by_NID(const X509_NAME *name, int nid, int lastpos)
{
ASN1_OBJECT *obj;
obj = OBJ_nid2obj(nid);
if (obj == NULL)
return -2;
return X509_NAME_get_index_by_OBJ(name, obj, lastpos);
}
/* NOTE: you should be passing -1, not 0 as lastpos */
int X509_NAME_get_index_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
int lastpos)
{
int n;
X509_NAME_ENTRY *ne;
STACK_OF(X509_NAME_ENTRY) *sk;
if (name == NULL)
return -1;
if (lastpos < 0)
lastpos = -1;
sk = name->entries;
n = sk_X509_NAME_ENTRY_num(sk);
for (lastpos++; lastpos < n; lastpos++) {
ne = sk_X509_NAME_ENTRY_value(sk, lastpos);
if (OBJ_cmp(ne->object, obj) == 0)
return lastpos;
}
return -1;
}
X509_NAME_ENTRY *X509_NAME_get_entry(const X509_NAME *name, int loc)
{
if (name == NULL || sk_X509_NAME_ENTRY_num(name->entries) <= loc
|| loc < 0)
return NULL;
return sk_X509_NAME_ENTRY_value(name->entries, loc);
}
X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc)
{
X509_NAME_ENTRY *ret;
int i, n, set_prev, set_next;
STACK_OF(X509_NAME_ENTRY) *sk;
if (name == NULL || sk_X509_NAME_ENTRY_num(name->entries) <= loc
|| loc < 0)
return NULL;
sk = name->entries;
ret = sk_X509_NAME_ENTRY_delete(sk, loc);
n = sk_X509_NAME_ENTRY_num(sk);
name->modified = 1;
if (loc == n)
return ret;
/* else we need to fixup the set field */
if (loc != 0)
set_prev = (sk_X509_NAME_ENTRY_value(sk, loc - 1))->set;
else
set_prev = ret->set - 1;
set_next = sk_X509_NAME_ENTRY_value(sk, loc)->set;
/*-
* set_prev is the previous set
* set is the current set
* set_next is the following
* prev 1 1 1 1 1 1 1 1
* set 1 1 2 2
* next 1 1 2 2 2 2 3 2
* so basically only if prev and next differ by 2, then
* re-number down by 1
*/
if (set_prev + 1 < set_next)
for (i = loc; i < n; i++)
sk_X509_NAME_ENTRY_value(sk, i)->set--;
return ret;
}
int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type,
const unsigned char *bytes, int len, int loc,
int set)
{
X509_NAME_ENTRY *ne;
int ret;
ne = X509_NAME_ENTRY_create_by_OBJ(NULL, obj, type, bytes, len);
if (!ne)
return 0;
ret = X509_NAME_add_entry(name, ne, loc, set);
X509_NAME_ENTRY_free(ne);
return ret;
}
int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type,
const unsigned char *bytes, int len, int loc,
int set)
{
X509_NAME_ENTRY *ne;
int ret;
ne = X509_NAME_ENTRY_create_by_NID(NULL, nid, type, bytes, len);
if (!ne)
return 0;
ret = X509_NAME_add_entry(name, ne, loc, set);
X509_NAME_ENTRY_free(ne);
return ret;
}
int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type,
const unsigned char *bytes, int len, int loc,
int set)
{
X509_NAME_ENTRY *ne;
int ret;
ne = X509_NAME_ENTRY_create_by_txt(NULL, field, type, bytes, len);
if (!ne)
return 0;
ret = X509_NAME_add_entry(name, ne, loc, set);
X509_NAME_ENTRY_free(ne);
return ret;
}
/*
* if set is -1, append to previous set, 0 'a new one', and 1, prepend to the
* guy we are about to stomp on.
*/
int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne, int loc,
int set)
{
X509_NAME_ENTRY *new_name = NULL;
int n, i, inc;
STACK_OF(X509_NAME_ENTRY) *sk;
if (name == NULL)
return 0;
sk = name->entries;
n = sk_X509_NAME_ENTRY_num(sk);
if (loc > n)
loc = n;
else if (loc < 0)
loc = n;
inc = (set == 0);
name->modified = 1;
if (set == -1) {
if (loc == 0) {
set = 0;
inc = 1;
} else {
set = sk_X509_NAME_ENTRY_value(sk, loc - 1)->set;
}
} else { /* if (set >= 0) */
if (loc >= n) {
if (loc != 0)
set = sk_X509_NAME_ENTRY_value(sk, loc - 1)->set + 1;
else
set = 0;
} else
set = sk_X509_NAME_ENTRY_value(sk, loc)->set;
}
if ((new_name = X509_NAME_ENTRY_dup(ne)) == NULL)
goto err;
new_name->set = set;
if (!sk_X509_NAME_ENTRY_insert(sk, new_name, loc)) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
}
if (inc) {
n = sk_X509_NAME_ENTRY_num(sk);
for (i = loc + 1; i < n; i++)
sk_X509_NAME_ENTRY_value(sk, i)->set += 1;
}
return 1;
err:
X509_NAME_ENTRY_free(new_name);
return 0;
}
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne,
const char *field, int type,
const unsigned char *bytes,
int len)
{
ASN1_OBJECT *obj;
X509_NAME_ENTRY *nentry;
obj = OBJ_txt2obj(field, 0);
if (obj == NULL) {
ERR_raise_data(ERR_LIB_X509, X509_R_INVALID_FIELD_NAME,
"name=%s", field);
return NULL;
}
nentry = X509_NAME_ENTRY_create_by_OBJ(ne, obj, type, bytes, len);
ASN1_OBJECT_free(obj);
return nentry;
}
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid,
int type,
const unsigned char *bytes,
int len)
{
ASN1_OBJECT *obj;
X509_NAME_ENTRY *nentry;
obj = OBJ_nid2obj(nid);
if (obj == NULL) {
ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_NID);
return NULL;
}
nentry = X509_NAME_ENTRY_create_by_OBJ(ne, obj, type, bytes, len);
ASN1_OBJECT_free(obj);
return nentry;
}
X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne,
const ASN1_OBJECT *obj, int type,
const unsigned char *bytes,
int len)
{
X509_NAME_ENTRY *ret;
if ((ne == NULL) || (*ne == NULL)) {
if ((ret = X509_NAME_ENTRY_new()) == NULL)
return NULL;
} else
ret = *ne;
if (!X509_NAME_ENTRY_set_object(ret, obj))
goto err;
if (!X509_NAME_ENTRY_set_data(ret, type, bytes, len))
goto err;
if ((ne != NULL) && (*ne == NULL))
*ne = ret;
return ret;
err:
if ((ne == NULL) || (ret != *ne))
X509_NAME_ENTRY_free(ret);
return NULL;
}
int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj)
{
if ((ne == NULL) || (obj == NULL)) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
ASN1_OBJECT_free(ne->object);
ne->object = OBJ_dup(obj);
return ((ne->object == NULL) ? 0 : 1);
}
int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type,
const unsigned char *bytes, int len)
{
int i;
if ((ne == NULL) || ((bytes == NULL) && (len != 0)))
return 0;
if ((type > 0) && (type & MBSTRING_FLAG))
return ASN1_STRING_set_by_NID(&ne->value, bytes,
len, type,
OBJ_obj2nid(ne->object)) ? 1 : 0;
if (len < 0)
len = strlen((const char *)bytes);
i = ASN1_STRING_set(ne->value, bytes, len);
if (!i)
return 0;
if (type != V_ASN1_UNDEF) {
if (type == V_ASN1_APP_CHOOSE)
ne->value->type = ASN1_PRINTABLE_type(bytes, len);
else
ne->value->type = type;
}
return 1;
}
ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne)
{
if (ne == NULL)
return NULL;
return ne->object;
}
ASN1_STRING *X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne)
{
if (ne == NULL)
return NULL;
return ne->value;
}
int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
{
return ne->set;
}
| 9,929 | 26.583333 | 81 |
c
|
openssl
|
openssl-master/crypto/x509/x509rset.c
|
/*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1.h>
#include <openssl/objects.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
int X509_REQ_set_version(X509_REQ *x, long version)
{
if (x == NULL)
return 0;
x->req_info.enc.modified = 1;
return ASN1_INTEGER_set(x->req_info.version, version);
}
int X509_REQ_set_subject_name(X509_REQ *x, const X509_NAME *name)
{
if (x == NULL)
return 0;
x->req_info.enc.modified = 1;
return X509_NAME_set(&x->req_info.subject, name);
}
int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey)
{
if (x == NULL)
return 0;
x->req_info.enc.modified = 1;
return X509_PUBKEY_set(&x->req_info.pubkey, pkey);
}
| 1,085 | 25.487805 | 74 |
c
|
openssl
|
openssl-master/crypto/x509/x509spki.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/x509.h>
int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey)
{
if ((x == NULL) || (x->spkac == NULL))
return 0;
return X509_PUBKEY_set(&(x->spkac->pubkey), pkey);
}
EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x)
{
if ((x == NULL) || (x->spkac == NULL))
return NULL;
return X509_PUBKEY_get(x->spkac->pubkey);
}
/* Load a Netscape SPKI from a base64 encoded string */
NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, int len)
{
unsigned char *spki_der;
const unsigned char *p;
int spki_len;
NETSCAPE_SPKI *spki;
if (len <= 0)
len = strlen(str);
if ((spki_der = OPENSSL_malloc(len + 1)) == NULL)
return NULL;
spki_len = EVP_DecodeBlock(spki_der, (const unsigned char *)str, len);
if (spki_len < 0) {
ERR_raise(ERR_LIB_X509, X509_R_BASE64_DECODE_ERROR);
OPENSSL_free(spki_der);
return NULL;
}
p = spki_der;
spki = d2i_NETSCAPE_SPKI(NULL, &p, spki_len);
OPENSSL_free(spki_der);
return spki;
}
/* Generate a base64 encoded string from an SPKI */
char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *spki)
{
unsigned char *der_spki, *p;
char *b64_str;
int der_len;
der_len = i2d_NETSCAPE_SPKI(spki, NULL);
if (der_len <= 0)
return NULL;
der_spki = OPENSSL_malloc(der_len);
b64_str = OPENSSL_malloc(der_len * 2);
if (der_spki == NULL || b64_str == NULL) {
OPENSSL_free(der_spki);
OPENSSL_free(b64_str);
return NULL;
}
p = der_spki;
i2d_NETSCAPE_SPKI(spki, &p);
EVP_EncodeBlock((unsigned char *)b64_str, der_spki, der_len);
OPENSSL_free(der_spki);
return b64_str;
}
| 2,098 | 26.618421 | 74 |
c
|
openssl
|
openssl-master/crypto/x509/x509type.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
int X509_certificate_type(const X509 *x, const EVP_PKEY *pkey)
{
const EVP_PKEY *pk;
int ret = 0, i;
if (x == NULL)
return 0;
if (pkey == NULL)
pk = X509_get0_pubkey(x);
else
pk = pkey;
if (pk == NULL)
return 0;
switch (EVP_PKEY_get_id(pk)) {
case EVP_PKEY_RSA:
ret = EVP_PK_RSA | EVP_PKT_SIGN;
/* if (!sign only extension) */
ret |= EVP_PKT_ENC;
break;
case EVP_PKEY_RSA_PSS:
ret = EVP_PK_RSA | EVP_PKT_SIGN;
break;
case EVP_PKEY_DSA:
ret = EVP_PK_DSA | EVP_PKT_SIGN;
break;
case EVP_PKEY_EC:
ret = EVP_PK_EC | EVP_PKT_SIGN | EVP_PKT_EXCH;
break;
case EVP_PKEY_ED448:
case EVP_PKEY_ED25519:
ret = EVP_PKT_SIGN;
break;
case EVP_PKEY_DH:
ret = EVP_PK_DH | EVP_PKT_EXCH;
break;
case NID_id_GostR3410_2001:
case NID_id_GostR3410_2012_256:
case NID_id_GostR3410_2012_512:
ret = EVP_PKT_EXCH | EVP_PKT_SIGN;
break;
default:
break;
}
i = X509_get_signature_nid(x);
if (i && OBJ_find_sigid_algs(i, NULL, &i)) {
switch (i) {
case NID_rsaEncryption:
case NID_rsa:
ret |= EVP_PKS_RSA;
break;
case NID_dsa:
case NID_dsa_2:
ret |= EVP_PKS_DSA;
break;
case NID_X9_62_id_ecPublicKey:
ret |= EVP_PKS_EC;
break;
default:
break;
}
}
return ret;
}
| 2,018 | 22.752941 | 74 |
c
|
openssl
|
openssl-master/crypto/x509/x_all.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Low level APIs are deprecated for public use, but still ok for
* internal use.
*/
#include "internal/deprecated.h"
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/buffer.h>
#include <openssl/asn1.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/http.h>
#include <openssl/rsa.h>
#include <openssl/dsa.h>
#include <openssl/x509v3.h>
#include "internal/asn1.h"
#include "crypto/pkcs7.h"
#include "crypto/x509.h"
#include "crypto/rsa.h"
int X509_verify(X509 *a, EVP_PKEY *r)
{
if (X509_ALGOR_cmp(&a->sig_alg, &a->cert_info.signature) != 0)
return 0;
return ASN1_item_verify_ex(ASN1_ITEM_rptr(X509_CINF), &a->sig_alg,
&a->signature, &a->cert_info,
a->distinguishing_id, r, a->libctx, a->propq);
}
int X509_REQ_verify_ex(X509_REQ *a, EVP_PKEY *r, OSSL_LIB_CTX *libctx,
const char *propq)
{
return ASN1_item_verify_ex(ASN1_ITEM_rptr(X509_REQ_INFO), &a->sig_alg,
a->signature, &a->req_info, a->distinguishing_id,
r, libctx, propq);
}
int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r)
{
return X509_REQ_verify_ex(a, r, NULL, NULL);
}
int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r)
{
return ASN1_item_verify(ASN1_ITEM_rptr(NETSCAPE_SPKAC),
&a->sig_algor, a->signature, a->spkac, r);
}
int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md)
{
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (sk_X509_EXTENSION_num(X509_get0_extensions(x)) > 0
&& !X509_set_version(x, X509_VERSION_3))
return 0;
/*
* Setting the modified flag before signing it. This makes the cached
* encoding to be ignored, so even if the certificate fields have changed,
* they are signed correctly.
* The X509_sign_ctx, X509_REQ_sign{,_ctx}, X509_CRL_sign{,_ctx} functions
* which exist below are the same.
*/
x->cert_info.enc.modified = 1;
return ASN1_item_sign_ex(ASN1_ITEM_rptr(X509_CINF), &x->cert_info.signature,
&x->sig_alg, &x->signature, &x->cert_info, NULL,
pkey, md, x->libctx, x->propq);
}
int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx)
{
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (sk_X509_EXTENSION_num(X509_get0_extensions(x)) > 0
&& !X509_set_version(x, X509_VERSION_3))
return 0;
x->cert_info.enc.modified = 1;
return ASN1_item_sign_ctx(ASN1_ITEM_rptr(X509_CINF),
&x->cert_info.signature,
&x->sig_alg, &x->signature, &x->cert_info, ctx);
}
static ASN1_VALUE *simple_get_asn1(const char *url, BIO *bio, BIO *rbio,
int timeout, const ASN1_ITEM *it)
{
#ifndef OPENSSL_NO_HTTP
BIO *mem = OSSL_HTTP_get(url, NULL /* proxy */, NULL /* no_proxy */,
bio, rbio, NULL /* cb */, NULL /* arg */,
1024 /* buf_size */, NULL /* headers */,
NULL /* expected_ct */, 1 /* expect_asn1 */,
OSSL_HTTP_DEFAULT_MAX_RESP_LEN, timeout);
ASN1_VALUE *res = ASN1_item_d2i_bio(it, mem, NULL);
BIO_free(mem);
return res;
#else
return 0;
#endif
}
X509 *X509_load_http(const char *url, BIO *bio, BIO *rbio, int timeout)
{
return (X509 *)simple_get_asn1(url, bio, rbio, timeout,
ASN1_ITEM_rptr(X509));
}
int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md)
{
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
x->req_info.enc.modified = 1;
return ASN1_item_sign_ex(ASN1_ITEM_rptr(X509_REQ_INFO), &x->sig_alg, NULL,
x->signature, &x->req_info, NULL,
pkey, md, x->libctx, x->propq);
}
int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx)
{
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
x->req_info.enc.modified = 1;
return ASN1_item_sign_ctx(ASN1_ITEM_rptr(X509_REQ_INFO),
&x->sig_alg, NULL, x->signature, &x->req_info,
ctx);
}
int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md)
{
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
x->crl.enc.modified = 1;
return ASN1_item_sign_ex(ASN1_ITEM_rptr(X509_CRL_INFO), &x->crl.sig_alg,
&x->sig_alg, &x->signature, &x->crl, NULL,
pkey, md, x->libctx, x->propq);
}
int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx)
{
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
x->crl.enc.modified = 1;
return ASN1_item_sign_ctx(ASN1_ITEM_rptr(X509_CRL_INFO),
&x->crl.sig_alg, &x->sig_alg, &x->signature,
&x->crl, ctx);
}
X509_CRL *X509_CRL_load_http(const char *url, BIO *bio, BIO *rbio, int timeout)
{
return (X509_CRL *)simple_get_asn1(url, bio, rbio, timeout,
ASN1_ITEM_rptr(X509_CRL));
}
int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md)
{
return
ASN1_item_sign_ex(ASN1_ITEM_rptr(NETSCAPE_SPKAC), &x->sig_algor, NULL,
x->signature, x->spkac, NULL, pkey, md, NULL, NULL);
}
#ifndef OPENSSL_NO_STDIO
X509 *d2i_X509_fp(FILE *fp, X509 **x509)
{
return ASN1_item_d2i_fp(ASN1_ITEM_rptr(X509), fp, x509);
}
int i2d_X509_fp(FILE *fp, const X509 *x509)
{
return ASN1_item_i2d_fp(ASN1_ITEM_rptr(X509), fp, x509);
}
#endif
X509 *d2i_X509_bio(BIO *bp, X509 **x509)
{
return ASN1_item_d2i_bio(ASN1_ITEM_rptr(X509), bp, x509);
}
int i2d_X509_bio(BIO *bp, const X509 *x509)
{
return ASN1_item_i2d_bio(ASN1_ITEM_rptr(X509), bp, x509);
}
#ifndef OPENSSL_NO_STDIO
X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **crl)
{
return ASN1_item_d2i_fp(ASN1_ITEM_rptr(X509_CRL), fp, crl);
}
int i2d_X509_CRL_fp(FILE *fp, const X509_CRL *crl)
{
return ASN1_item_i2d_fp(ASN1_ITEM_rptr(X509_CRL), fp, crl);
}
#endif
X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **crl)
{
return ASN1_item_d2i_bio(ASN1_ITEM_rptr(X509_CRL), bp, crl);
}
int i2d_X509_CRL_bio(BIO *bp, const X509_CRL *crl)
{
return ASN1_item_i2d_bio(ASN1_ITEM_rptr(X509_CRL), bp, crl);
}
#ifndef OPENSSL_NO_STDIO
PKCS7 *d2i_PKCS7_fp(FILE *fp, PKCS7 **p7)
{
PKCS7 *ret;
OSSL_LIB_CTX *libctx = NULL;
const char *propq = NULL;
if (p7 != NULL && *p7 != NULL) {
libctx = (*p7)->ctx.libctx;
propq = (*p7)->ctx.propq;
}
ret = ASN1_item_d2i_fp_ex(ASN1_ITEM_rptr(PKCS7), fp, p7, libctx, propq);
if (ret != NULL)
ossl_pkcs7_resolve_libctx(ret);
return ret;
}
int i2d_PKCS7_fp(FILE *fp, const PKCS7 *p7)
{
return ASN1_item_i2d_fp(ASN1_ITEM_rptr(PKCS7), fp, p7);
}
#endif
PKCS7 *d2i_PKCS7_bio(BIO *bp, PKCS7 **p7)
{
PKCS7 *ret;
OSSL_LIB_CTX *libctx = NULL;
const char *propq = NULL;
if (p7 != NULL && *p7 != NULL) {
libctx = (*p7)->ctx.libctx;
propq = (*p7)->ctx.propq;
}
ret = ASN1_item_d2i_bio_ex(ASN1_ITEM_rptr(PKCS7), bp, p7, libctx, propq);
if (ret != NULL)
ossl_pkcs7_resolve_libctx(ret);
return ret;
}
int i2d_PKCS7_bio(BIO *bp, const PKCS7 *p7)
{
return ASN1_item_i2d_bio(ASN1_ITEM_rptr(PKCS7), bp, p7);
}
#ifndef OPENSSL_NO_STDIO
X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **req)
{
return ASN1_item_d2i_fp(ASN1_ITEM_rptr(X509_REQ), fp, req);
}
int i2d_X509_REQ_fp(FILE *fp, const X509_REQ *req)
{
return ASN1_item_i2d_fp(ASN1_ITEM_rptr(X509_REQ), fp, req);
}
#endif
X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **req)
{
OSSL_LIB_CTX *libctx = NULL;
const char *propq = NULL;
if (req != NULL && *req != NULL) {
libctx = (*req)->libctx;
propq = (*req)->propq;
}
return
ASN1_item_d2i_bio_ex(ASN1_ITEM_rptr(X509_REQ), bp, req, libctx, propq);
}
int i2d_X509_REQ_bio(BIO *bp, const X509_REQ *req)
{
return ASN1_item_i2d_bio(ASN1_ITEM_rptr(X509_REQ), bp, req);
}
#ifndef OPENSSL_NO_STDIO
RSA *d2i_RSAPrivateKey_fp(FILE *fp, RSA **rsa)
{
return ASN1_item_d2i_fp(ASN1_ITEM_rptr(RSAPrivateKey), fp, rsa);
}
int i2d_RSAPrivateKey_fp(FILE *fp, const RSA *rsa)
{
return ASN1_item_i2d_fp(ASN1_ITEM_rptr(RSAPrivateKey), fp, rsa);
}
RSA *d2i_RSAPublicKey_fp(FILE *fp, RSA **rsa)
{
return ASN1_item_d2i_fp(ASN1_ITEM_rptr(RSAPublicKey), fp, rsa);
}
RSA *d2i_RSA_PUBKEY_fp(FILE *fp, RSA **rsa)
{
return ASN1_d2i_fp((void *(*)(void))
RSA_new, (D2I_OF(void)) d2i_RSA_PUBKEY, fp,
(void **)rsa);
}
int i2d_RSAPublicKey_fp(FILE *fp, const RSA *rsa)
{
return ASN1_item_i2d_fp(ASN1_ITEM_rptr(RSAPublicKey), fp, rsa);
}
int i2d_RSA_PUBKEY_fp(FILE *fp, const RSA *rsa)
{
return ASN1_i2d_fp((I2D_OF(void))i2d_RSA_PUBKEY, fp, rsa);
}
#endif
RSA *d2i_RSAPrivateKey_bio(BIO *bp, RSA **rsa)
{
return ASN1_item_d2i_bio(ASN1_ITEM_rptr(RSAPrivateKey), bp, rsa);
}
int i2d_RSAPrivateKey_bio(BIO *bp, const RSA *rsa)
{
return ASN1_item_i2d_bio(ASN1_ITEM_rptr(RSAPrivateKey), bp, rsa);
}
RSA *d2i_RSAPublicKey_bio(BIO *bp, RSA **rsa)
{
return ASN1_item_d2i_bio(ASN1_ITEM_rptr(RSAPublicKey), bp, rsa);
}
RSA *d2i_RSA_PUBKEY_bio(BIO *bp, RSA **rsa)
{
return ASN1_d2i_bio_of(RSA, RSA_new, d2i_RSA_PUBKEY, bp, rsa);
}
int i2d_RSAPublicKey_bio(BIO *bp, const RSA *rsa)
{
return ASN1_item_i2d_bio(ASN1_ITEM_rptr(RSAPublicKey), bp, rsa);
}
int i2d_RSA_PUBKEY_bio(BIO *bp, const RSA *rsa)
{
return ASN1_i2d_bio_of(RSA, i2d_RSA_PUBKEY, bp, rsa);
}
#ifndef OPENSSL_NO_DSA
# ifndef OPENSSL_NO_STDIO
DSA *d2i_DSAPrivateKey_fp(FILE *fp, DSA **dsa)
{
return ASN1_d2i_fp_of(DSA, DSA_new, d2i_DSAPrivateKey, fp, dsa);
}
int i2d_DSAPrivateKey_fp(FILE *fp, const DSA *dsa)
{
return ASN1_i2d_fp_of(DSA, i2d_DSAPrivateKey, fp, dsa);
}
DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa)
{
return ASN1_d2i_fp_of(DSA, DSA_new, d2i_DSA_PUBKEY, fp, dsa);
}
int i2d_DSA_PUBKEY_fp(FILE *fp, const DSA *dsa)
{
return ASN1_i2d_fp_of(DSA, i2d_DSA_PUBKEY, fp, dsa);
}
# endif
DSA *d2i_DSAPrivateKey_bio(BIO *bp, DSA **dsa)
{
return ASN1_d2i_bio_of(DSA, DSA_new, d2i_DSAPrivateKey, bp, dsa);
}
int i2d_DSAPrivateKey_bio(BIO *bp, const DSA *dsa)
{
return ASN1_i2d_bio_of(DSA, i2d_DSAPrivateKey, bp, dsa);
}
DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa)
{
return ASN1_d2i_bio_of(DSA, DSA_new, d2i_DSA_PUBKEY, bp, dsa);
}
int i2d_DSA_PUBKEY_bio(BIO *bp, const DSA *dsa)
{
return ASN1_i2d_bio_of(DSA, i2d_DSA_PUBKEY, bp, dsa);
}
#endif
#ifndef OPENSSL_NO_EC
# ifndef OPENSSL_NO_STDIO
EC_KEY *d2i_EC_PUBKEY_fp(FILE *fp, EC_KEY **eckey)
{
return ASN1_d2i_fp_of(EC_KEY, EC_KEY_new, d2i_EC_PUBKEY, fp, eckey);
}
int i2d_EC_PUBKEY_fp(FILE *fp, const EC_KEY *eckey)
{
return ASN1_i2d_fp_of(EC_KEY, i2d_EC_PUBKEY, fp, eckey);
}
EC_KEY *d2i_ECPrivateKey_fp(FILE *fp, EC_KEY **eckey)
{
return ASN1_d2i_fp_of(EC_KEY, EC_KEY_new, d2i_ECPrivateKey, fp, eckey);
}
int i2d_ECPrivateKey_fp(FILE *fp, const EC_KEY *eckey)
{
return ASN1_i2d_fp_of(EC_KEY, i2d_ECPrivateKey, fp, eckey);
}
# endif
EC_KEY *d2i_EC_PUBKEY_bio(BIO *bp, EC_KEY **eckey)
{
return ASN1_d2i_bio_of(EC_KEY, EC_KEY_new, d2i_EC_PUBKEY, bp, eckey);
}
int i2d_EC_PUBKEY_bio(BIO *bp, const EC_KEY *ecdsa)
{
return ASN1_i2d_bio_of(EC_KEY, i2d_EC_PUBKEY, bp, ecdsa);
}
EC_KEY *d2i_ECPrivateKey_bio(BIO *bp, EC_KEY **eckey)
{
return ASN1_d2i_bio_of(EC_KEY, EC_KEY_new, d2i_ECPrivateKey, bp, eckey);
}
int i2d_ECPrivateKey_bio(BIO *bp, const EC_KEY *eckey)
{
return ASN1_i2d_bio_of(EC_KEY, i2d_ECPrivateKey, bp, eckey);
}
#endif
int X509_pubkey_digest(const X509 *data, const EVP_MD *type,
unsigned char *md, unsigned int *len)
{
ASN1_BIT_STRING *key = X509_get0_pubkey_bitstr(data);
if (key == NULL)
return 0;
return EVP_Digest(key->data, key->length, md, len, type, NULL);
}
int X509_digest(const X509 *cert, const EVP_MD *md, unsigned char *data,
unsigned int *len)
{
if (EVP_MD_is_a(md, SN_sha1) && (cert->ex_flags & EXFLAG_SET) != 0
&& (cert->ex_flags & EXFLAG_NO_FINGERPRINT) == 0) {
/* Asking for SHA1 and we already computed it. */
if (len != NULL)
*len = sizeof(cert->sha1_hash);
memcpy(data, cert->sha1_hash, sizeof(cert->sha1_hash));
return 1;
}
return ossl_asn1_item_digest_ex(ASN1_ITEM_rptr(X509), md, (char *)cert,
data, len, cert->libctx, cert->propq);
}
/* calculate cert digest using the same hash algorithm as in its signature */
ASN1_OCTET_STRING *X509_digest_sig(const X509 *cert,
EVP_MD **md_used, int *md_is_fallback)
{
unsigned int len;
unsigned char hash[EVP_MAX_MD_SIZE];
int mdnid, pknid;
EVP_MD *md = NULL;
const char *md_name;
ASN1_OCTET_STRING *new;
if (md_used != NULL)
*md_used = NULL;
if (md_is_fallback != NULL)
*md_is_fallback = 0;
if (cert == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (!OBJ_find_sigid_algs(X509_get_signature_nid(cert), &mdnid, &pknid)) {
ERR_raise(ERR_LIB_X509, X509_R_UNKNOWN_SIGID_ALGS);
return NULL;
}
if (mdnid == NID_undef) {
if (pknid == EVP_PKEY_RSA_PSS) {
RSA_PSS_PARAMS *pss = ossl_rsa_pss_decode(&cert->sig_alg);
const EVP_MD *mgf1md, *mmd = NULL;
int saltlen, trailerfield;
if (pss == NULL
|| !ossl_rsa_pss_get_param_unverified(pss, &mmd, &mgf1md,
&saltlen,
&trailerfield)
|| mmd == NULL) {
RSA_PSS_PARAMS_free(pss);
ERR_raise(ERR_LIB_X509, X509_R_UNSUPPORTED_ALGORITHM);
return NULL;
}
RSA_PSS_PARAMS_free(pss);
/* Fetch explicitly and do not fallback */
if ((md = EVP_MD_fetch(cert->libctx, EVP_MD_get0_name(mmd),
cert->propq)) == NULL)
/* Error code from fetch is sufficient */
return NULL;
} else if (pknid != NID_undef) {
/* A known algorithm, but without a digest */
switch (pknid) {
case NID_ED25519: /* Follow CMS default given in RFC8419 */
md_name = "SHA512";
break;
case NID_ED448: /* Follow CMS default given in RFC8419 */
md_name = "SHAKE256";
break;
default: /* Fall back to SHA-256 */
md_name = "SHA256";
break;
}
if ((md = EVP_MD_fetch(cert->libctx, md_name,
cert->propq)) == NULL)
return NULL;
if (md_is_fallback != NULL)
*md_is_fallback = 1;
} else {
/* A completely unknown algorithm */
ERR_raise(ERR_LIB_X509, X509_R_UNSUPPORTED_ALGORITHM);
return NULL;
}
} else if ((md = EVP_MD_fetch(cert->libctx, OBJ_nid2sn(mdnid),
cert->propq)) == NULL
&& (md = (EVP_MD *)EVP_get_digestbynid(mdnid)) == NULL) {
ERR_raise(ERR_LIB_X509, X509_R_UNSUPPORTED_ALGORITHM);
return NULL;
}
if (!X509_digest(cert, md, hash, &len)
|| (new = ASN1_OCTET_STRING_new()) == NULL)
goto err;
if (ASN1_OCTET_STRING_set(new, hash, len)) {
if (md_used != NULL)
*md_used = md;
else
EVP_MD_free(md);
return new;
}
ASN1_OCTET_STRING_free(new);
err:
EVP_MD_free(md);
return NULL;
}
int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type,
unsigned char *md, unsigned int *len)
{
if (type == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (EVP_MD_is_a(type, SN_sha1)
&& (data->flags & EXFLAG_SET) != 0
&& (data->flags & EXFLAG_NO_FINGERPRINT) == 0) {
/* Asking for SHA1; always computed in CRL d2i. */
if (len != NULL)
*len = sizeof(data->sha1_hash);
memcpy(md, data->sha1_hash, sizeof(data->sha1_hash));
return 1;
}
return
ossl_asn1_item_digest_ex(ASN1_ITEM_rptr(X509_CRL), type, (char *)data,
md, len, data->libctx, data->propq);
}
int X509_REQ_digest(const X509_REQ *data, const EVP_MD *type,
unsigned char *md, unsigned int *len)
{
return
ossl_asn1_item_digest_ex(ASN1_ITEM_rptr(X509_REQ), type, (char *)data,
md, len, data->libctx, data->propq);
}
int X509_NAME_digest(const X509_NAME *data, const EVP_MD *type,
unsigned char *md, unsigned int *len)
{
return ASN1_item_digest(ASN1_ITEM_rptr(X509_NAME), type, (char *)data,
md, len);
}
int PKCS7_ISSUER_AND_SERIAL_digest(PKCS7_ISSUER_AND_SERIAL *data,
const EVP_MD *type, unsigned char *md,
unsigned int *len)
{
return ASN1_item_digest(ASN1_ITEM_rptr(PKCS7_ISSUER_AND_SERIAL), type,
(char *)data, md, len);
}
#ifndef OPENSSL_NO_STDIO
X509_SIG *d2i_PKCS8_fp(FILE *fp, X509_SIG **p8)
{
return ASN1_d2i_fp_of(X509_SIG, X509_SIG_new, d2i_X509_SIG, fp, p8);
}
int i2d_PKCS8_fp(FILE *fp, const X509_SIG *p8)
{
return ASN1_i2d_fp_of(X509_SIG, i2d_X509_SIG, fp, p8);
}
#endif
X509_SIG *d2i_PKCS8_bio(BIO *bp, X509_SIG **p8)
{
return ASN1_d2i_bio_of(X509_SIG, X509_SIG_new, d2i_X509_SIG, bp, p8);
}
int i2d_PKCS8_bio(BIO *bp, const X509_SIG *p8)
{
return ASN1_i2d_bio_of(X509_SIG, i2d_X509_SIG, bp, p8);
}
#ifndef OPENSSL_NO_STDIO
X509_PUBKEY *d2i_X509_PUBKEY_fp(FILE *fp, X509_PUBKEY **xpk)
{
return ASN1_d2i_fp_of(X509_PUBKEY, X509_PUBKEY_new, d2i_X509_PUBKEY,
fp, xpk);
}
int i2d_X509_PUBKEY_fp(FILE *fp, const X509_PUBKEY *xpk)
{
return ASN1_i2d_fp_of(X509_PUBKEY, i2d_X509_PUBKEY, fp, xpk);
}
#endif
X509_PUBKEY *d2i_X509_PUBKEY_bio(BIO *bp, X509_PUBKEY **xpk)
{
return ASN1_d2i_bio_of(X509_PUBKEY, X509_PUBKEY_new, d2i_X509_PUBKEY,
bp, xpk);
}
int i2d_X509_PUBKEY_bio(BIO *bp, const X509_PUBKEY *xpk)
{
return ASN1_i2d_bio_of(X509_PUBKEY, i2d_X509_PUBKEY, bp, xpk);
}
#ifndef OPENSSL_NO_STDIO
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_fp(FILE *fp,
PKCS8_PRIV_KEY_INFO **p8inf)
{
return ASN1_d2i_fp_of(PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_new,
d2i_PKCS8_PRIV_KEY_INFO, fp, p8inf);
}
int i2d_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, const PKCS8_PRIV_KEY_INFO *p8inf)
{
return ASN1_i2d_fp_of(PKCS8_PRIV_KEY_INFO, i2d_PKCS8_PRIV_KEY_INFO, fp,
p8inf);
}
int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, const EVP_PKEY *key)
{
PKCS8_PRIV_KEY_INFO *p8inf;
int ret;
p8inf = EVP_PKEY2PKCS8(key);
if (p8inf == NULL)
return 0;
ret = i2d_PKCS8_PRIV_KEY_INFO_fp(fp, p8inf);
PKCS8_PRIV_KEY_INFO_free(p8inf);
return ret;
}
int i2d_PrivateKey_fp(FILE *fp, const EVP_PKEY *pkey)
{
return ASN1_i2d_fp_of(EVP_PKEY, i2d_PrivateKey, fp, pkey);
}
EVP_PKEY *d2i_PrivateKey_fp(FILE *fp, EVP_PKEY **a)
{
return ASN1_d2i_fp_of(EVP_PKEY, EVP_PKEY_new, d2i_AutoPrivateKey, fp, a);
}
EVP_PKEY *d2i_PrivateKey_ex_fp(FILE *fp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
const char *propq)
{
BIO *b;
void *ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
return NULL;
}
BIO_set_fp(b, fp, BIO_NOCLOSE);
ret = d2i_PrivateKey_ex_bio(b, a, libctx, propq);
BIO_free(b);
return ret;
}
int i2d_PUBKEY_fp(FILE *fp, const EVP_PKEY *pkey)
{
return ASN1_i2d_fp_of(EVP_PKEY, i2d_PUBKEY, fp, pkey);
}
EVP_PKEY *d2i_PUBKEY_ex_fp(FILE *fp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
const char *propq)
{
BIO *b;
void *ret;
if ((b = BIO_new(BIO_s_file())) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
return NULL;
}
BIO_set_fp(b, fp, BIO_NOCLOSE);
ret = d2i_PUBKEY_ex_bio(b, a, libctx, propq);
BIO_free(b);
return ret;
}
EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a)
{
return ASN1_d2i_fp_of(EVP_PKEY, EVP_PKEY_new, d2i_PUBKEY, fp, a);
}
#endif
PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp,
PKCS8_PRIV_KEY_INFO **p8inf)
{
return ASN1_d2i_bio_of(PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO_new,
d2i_PKCS8_PRIV_KEY_INFO, bp, p8inf);
}
int i2d_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, const PKCS8_PRIV_KEY_INFO *p8inf)
{
return ASN1_i2d_bio_of(PKCS8_PRIV_KEY_INFO, i2d_PKCS8_PRIV_KEY_INFO, bp,
p8inf);
}
int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, const EVP_PKEY *key)
{
PKCS8_PRIV_KEY_INFO *p8inf;
int ret;
p8inf = EVP_PKEY2PKCS8(key);
if (p8inf == NULL)
return 0;
ret = i2d_PKCS8_PRIV_KEY_INFO_bio(bp, p8inf);
PKCS8_PRIV_KEY_INFO_free(p8inf);
return ret;
}
int i2d_PrivateKey_bio(BIO *bp, const EVP_PKEY *pkey)
{
return ASN1_i2d_bio_of(EVP_PKEY, i2d_PrivateKey, bp, pkey);
}
EVP_PKEY *d2i_PrivateKey_bio(BIO *bp, EVP_PKEY **a)
{
return ASN1_d2i_bio_of(EVP_PKEY, EVP_PKEY_new, d2i_AutoPrivateKey, bp, a);
}
EVP_PKEY *d2i_PrivateKey_ex_bio(BIO *bp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
const char *propq)
{
BUF_MEM *b = NULL;
const unsigned char *p;
void *ret = NULL;
int len;
len = asn1_d2i_read_bio(bp, &b);
if (len < 0)
goto err;
p = (unsigned char *)b->data;
ret = d2i_AutoPrivateKey_ex(a, &p, len, libctx, propq);
err:
BUF_MEM_free(b);
return ret;
}
int i2d_PUBKEY_bio(BIO *bp, const EVP_PKEY *pkey)
{
return ASN1_i2d_bio_of(EVP_PKEY, i2d_PUBKEY, bp, pkey);
}
EVP_PKEY *d2i_PUBKEY_ex_bio(BIO *bp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
const char *propq)
{
BUF_MEM *b = NULL;
const unsigned char *p;
void *ret = NULL;
int len;
len = asn1_d2i_read_bio(bp, &b);
if (len < 0)
goto err;
p = (unsigned char *)b->data;
ret = d2i_PUBKEY_ex(a, &p, len, libctx, propq);
err:
BUF_MEM_free(b);
return ret;
}
EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a)
{
return ASN1_d2i_bio_of(EVP_PKEY, EVP_PKEY_new, d2i_PUBKEY, bp, a);
}
| 23,534 | 27.458283 | 80 |
c
|
openssl
|
openssl-master/crypto/x509/x_attrib.c
|
/*
* Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/objects.h>
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include "x509_local.h"
/*-
* X509_ATTRIBUTE: this has the following form:
*
* typedef struct x509_attributes_st
* {
* ASN1_OBJECT *object;
* STACK_OF(ASN1_TYPE) *set;
* } X509_ATTRIBUTE;
*
*/
ASN1_SEQUENCE(X509_ATTRIBUTE) = {
ASN1_SIMPLE(X509_ATTRIBUTE, object, ASN1_OBJECT),
ASN1_SET_OF(X509_ATTRIBUTE, set, ASN1_ANY)
} ASN1_SEQUENCE_END(X509_ATTRIBUTE)
IMPLEMENT_ASN1_FUNCTIONS(X509_ATTRIBUTE)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_ATTRIBUTE)
X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value)
{
X509_ATTRIBUTE *ret = NULL;
ASN1_TYPE *val = NULL;
ASN1_OBJECT *oid;
if ((oid = OBJ_nid2obj(nid)) == NULL)
return NULL;
if ((ret = X509_ATTRIBUTE_new()) == NULL)
return NULL;
ret->object = oid;
if ((val = ASN1_TYPE_new()) == NULL)
goto err;
if (!sk_ASN1_TYPE_push(ret->set, val))
goto err;
ASN1_TYPE_set(val, atrtype, value);
return ret;
err:
X509_ATTRIBUTE_free(ret);
ASN1_TYPE_free(val);
return NULL;
}
| 1,526 | 24.881356 | 74 |
c
|
openssl
|
openssl-master/crypto/x509/x_crl.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
#include <openssl/x509v3.h>
#include "x509_local.h"
static int X509_REVOKED_cmp(const X509_REVOKED *const *a,
const X509_REVOKED *const *b);
static int setup_idp(X509_CRL *crl, ISSUING_DIST_POINT *idp);
ASN1_SEQUENCE(X509_REVOKED) = {
ASN1_EMBED(X509_REVOKED, serialNumber, ASN1_INTEGER),
ASN1_SIMPLE(X509_REVOKED, revocationDate, ASN1_TIME),
ASN1_SEQUENCE_OF_OPT(X509_REVOKED, extensions, X509_EXTENSION)
} ASN1_SEQUENCE_END(X509_REVOKED)
static int def_crl_verify(X509_CRL *crl, EVP_PKEY *r);
static int def_crl_lookup(X509_CRL *crl,
X509_REVOKED **ret, const ASN1_INTEGER *serial,
const X509_NAME *issuer);
static X509_CRL_METHOD int_crl_meth = {
0,
0, 0,
def_crl_lookup,
def_crl_verify
};
static const X509_CRL_METHOD *default_crl_method = &int_crl_meth;
/*
* The X509_CRL_INFO structure needs a bit of customisation. Since we cache
* the original encoding the signature won't be affected by reordering of the
* revoked field.
*/
static int crl_inf_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
void *exarg)
{
X509_CRL_INFO *a = (X509_CRL_INFO *)*pval;
if (!a || !a->revoked)
return 1;
switch (operation) {
/*
* Just set cmp function here. We don't sort because that would
* affect the output of X509_CRL_print().
*/
case ASN1_OP_D2I_POST:
(void)sk_X509_REVOKED_set_cmp_func(a->revoked, X509_REVOKED_cmp);
break;
}
return 1;
}
ASN1_SEQUENCE_enc(X509_CRL_INFO, enc, crl_inf_cb) = {
ASN1_OPT(X509_CRL_INFO, version, ASN1_INTEGER),
ASN1_EMBED(X509_CRL_INFO, sig_alg, X509_ALGOR),
ASN1_SIMPLE(X509_CRL_INFO, issuer, X509_NAME),
ASN1_SIMPLE(X509_CRL_INFO, lastUpdate, ASN1_TIME),
ASN1_OPT(X509_CRL_INFO, nextUpdate, ASN1_TIME),
ASN1_SEQUENCE_OF_OPT(X509_CRL_INFO, revoked, X509_REVOKED),
ASN1_EXP_SEQUENCE_OF_OPT(X509_CRL_INFO, extensions, X509_EXTENSION, 0)
} ASN1_SEQUENCE_END_enc(X509_CRL_INFO, X509_CRL_INFO)
/*
* Set CRL entry issuer according to CRL certificate issuer extension. Check
* for unhandled critical CRL entry extensions.
*/
static int crl_set_issuers(X509_CRL *crl)
{
int i, j;
GENERAL_NAMES *gens, *gtmp;
STACK_OF(X509_REVOKED) *revoked;
revoked = X509_CRL_get_REVOKED(crl);
gens = NULL;
for (i = 0; i < sk_X509_REVOKED_num(revoked); i++) {
X509_REVOKED *rev = sk_X509_REVOKED_value(revoked, i);
STACK_OF(X509_EXTENSION) *exts;
ASN1_ENUMERATED *reason;
X509_EXTENSION *ext;
gtmp = X509_REVOKED_get_ext_d2i(rev,
NID_certificate_issuer, &j, NULL);
if (gtmp == NULL && j != -1) {
crl->flags |= EXFLAG_INVALID;
return 1;
}
if (gtmp != NULL) {
if (crl->issuers == NULL) {
crl->issuers = sk_GENERAL_NAMES_new_null();
if (crl->issuers == NULL) {
GENERAL_NAMES_free(gtmp);
return 0;
}
}
if (!sk_GENERAL_NAMES_push(crl->issuers, gtmp)) {
GENERAL_NAMES_free(gtmp);
return 0;
}
gens = gtmp;
}
rev->issuer = gens;
reason = X509_REVOKED_get_ext_d2i(rev, NID_crl_reason, &j, NULL);
if (reason == NULL && j != -1) {
crl->flags |= EXFLAG_INVALID;
return 1;
}
if (reason != NULL) {
rev->reason = ASN1_ENUMERATED_get(reason);
ASN1_ENUMERATED_free(reason);
} else
rev->reason = CRL_REASON_NONE;
/* Check for critical CRL entry extensions */
exts = rev->extensions;
for (j = 0; j < sk_X509_EXTENSION_num(exts); j++) {
ext = sk_X509_EXTENSION_value(exts, j);
if (X509_EXTENSION_get_critical(ext)) {
if (OBJ_obj2nid(X509_EXTENSION_get_object(ext))
== NID_certificate_issuer)
continue;
crl->flags |= EXFLAG_CRITICAL;
break;
}
}
}
return 1;
}
/*
* The X509_CRL structure needs a bit of customisation. Cache some extensions
* and hash of the whole CRL or set EXFLAG_NO_FINGERPRINT if this fails.
*/
static int crl_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
void *exarg)
{
X509_CRL *crl = (X509_CRL *)*pval;
STACK_OF(X509_EXTENSION) *exts;
X509_EXTENSION *ext;
int idx, i;
switch (operation) {
case ASN1_OP_D2I_PRE:
if (crl->meth->crl_free) {
if (!crl->meth->crl_free(crl))
return 0;
}
AUTHORITY_KEYID_free(crl->akid);
ISSUING_DIST_POINT_free(crl->idp);
ASN1_INTEGER_free(crl->crl_number);
ASN1_INTEGER_free(crl->base_crl_number);
sk_GENERAL_NAMES_pop_free(crl->issuers, GENERAL_NAMES_free);
/* fall through */
case ASN1_OP_NEW_POST:
crl->idp = NULL;
crl->akid = NULL;
crl->flags = 0;
crl->idp_flags = 0;
crl->idp_reasons = CRLDP_ALL_REASONS;
crl->meth = default_crl_method;
crl->meth_data = NULL;
crl->issuers = NULL;
crl->crl_number = NULL;
crl->base_crl_number = NULL;
break;
case ASN1_OP_D2I_POST:
if (!X509_CRL_digest(crl, EVP_sha1(), crl->sha1_hash, NULL))
crl->flags |= EXFLAG_NO_FINGERPRINT;
crl->idp = X509_CRL_get_ext_d2i(crl,
NID_issuing_distribution_point, &i,
NULL);
if (crl->idp != NULL) {
if (!setup_idp(crl, crl->idp))
crl->flags |= EXFLAG_INVALID;
}
else if (i != -1) {
crl->flags |= EXFLAG_INVALID;
}
crl->akid = X509_CRL_get_ext_d2i(crl,
NID_authority_key_identifier, &i,
NULL);
if (crl->akid == NULL && i != -1)
crl->flags |= EXFLAG_INVALID;
crl->crl_number = X509_CRL_get_ext_d2i(crl,
NID_crl_number, &i, NULL);
if (crl->crl_number == NULL && i != -1)
crl->flags |= EXFLAG_INVALID;
crl->base_crl_number = X509_CRL_get_ext_d2i(crl,
NID_delta_crl, &i,
NULL);
if (crl->base_crl_number == NULL && i != -1)
crl->flags |= EXFLAG_INVALID;
/* Delta CRLs must have CRL number */
if (crl->base_crl_number && !crl->crl_number)
crl->flags |= EXFLAG_INVALID;
/*
* See if we have any unhandled critical CRL extensions and indicate
* this in a flag. We only currently handle IDP so anything else
* critical sets the flag. This code accesses the X509_CRL structure
* directly: applications shouldn't do this.
*/
exts = crl->crl.extensions;
for (idx = 0; idx < sk_X509_EXTENSION_num(exts); idx++) {
int nid;
ext = sk_X509_EXTENSION_value(exts, idx);
nid = OBJ_obj2nid(X509_EXTENSION_get_object(ext));
if (nid == NID_freshest_crl)
crl->flags |= EXFLAG_FRESHEST;
if (X509_EXTENSION_get_critical(ext)) {
/* We handle IDP and deltas */
if ((nid == NID_issuing_distribution_point)
|| (nid == NID_authority_key_identifier)
|| (nid == NID_delta_crl))
continue;
crl->flags |= EXFLAG_CRITICAL;
break;
}
}
if (!crl_set_issuers(crl))
return 0;
if (crl->meth->crl_init) {
if (crl->meth->crl_init(crl) == 0)
return 0;
}
crl->flags |= EXFLAG_SET;
break;
case ASN1_OP_FREE_POST:
if (crl->meth != NULL && crl->meth->crl_free != NULL) {
if (!crl->meth->crl_free(crl))
return 0;
}
AUTHORITY_KEYID_free(crl->akid);
ISSUING_DIST_POINT_free(crl->idp);
ASN1_INTEGER_free(crl->crl_number);
ASN1_INTEGER_free(crl->base_crl_number);
sk_GENERAL_NAMES_pop_free(crl->issuers, GENERAL_NAMES_free);
OPENSSL_free(crl->propq);
break;
case ASN1_OP_DUP_POST:
{
X509_CRL *old = exarg;
if (!ossl_x509_crl_set0_libctx(crl, old->libctx, old->propq))
return 0;
}
break;
}
return 1;
}
/* Convert IDP into a more convenient form */
static int setup_idp(X509_CRL *crl, ISSUING_DIST_POINT *idp)
{
int idp_only = 0;
/* Set various flags according to IDP */
crl->idp_flags |= IDP_PRESENT;
if (idp->onlyuser > 0) {
idp_only++;
crl->idp_flags |= IDP_ONLYUSER;
}
if (idp->onlyCA > 0) {
idp_only++;
crl->idp_flags |= IDP_ONLYCA;
}
if (idp->onlyattr > 0) {
idp_only++;
crl->idp_flags |= IDP_ONLYATTR;
}
if (idp_only > 1)
crl->idp_flags |= IDP_INVALID;
if (idp->indirectCRL > 0)
crl->idp_flags |= IDP_INDIRECT;
if (idp->onlysomereasons) {
crl->idp_flags |= IDP_REASONS;
if (idp->onlysomereasons->length > 0)
crl->idp_reasons = idp->onlysomereasons->data[0];
if (idp->onlysomereasons->length > 1)
crl->idp_reasons |= (idp->onlysomereasons->data[1] << 8);
crl->idp_reasons &= CRLDP_ALL_REASONS;
}
return DIST_POINT_set_dpname(idp->distpoint, X509_CRL_get_issuer(crl));
}
ASN1_SEQUENCE_ref(X509_CRL, crl_cb) = {
ASN1_EMBED(X509_CRL, crl, X509_CRL_INFO),
ASN1_EMBED(X509_CRL, sig_alg, X509_ALGOR),
ASN1_EMBED(X509_CRL, signature, ASN1_BIT_STRING)
} ASN1_SEQUENCE_END_ref(X509_CRL, X509_CRL)
IMPLEMENT_ASN1_FUNCTIONS(X509_REVOKED)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_REVOKED)
IMPLEMENT_ASN1_FUNCTIONS(X509_CRL_INFO)
IMPLEMENT_ASN1_FUNCTIONS(X509_CRL)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_CRL)
static int X509_REVOKED_cmp(const X509_REVOKED *const *a,
const X509_REVOKED *const *b)
{
return (ASN1_STRING_cmp((ASN1_STRING *)&(*a)->serialNumber,
(ASN1_STRING *)&(*b)->serialNumber));
}
X509_CRL *X509_CRL_new_ex(OSSL_LIB_CTX *libctx, const char *propq)
{
X509_CRL *crl = NULL;
crl = (X509_CRL *)ASN1_item_new((X509_CRL_it()));
if (!ossl_x509_crl_set0_libctx(crl, libctx, propq)) {
X509_CRL_free(crl);
crl = NULL;
}
return crl;
}
int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev)
{
X509_CRL_INFO *inf;
inf = &crl->crl;
if (inf->revoked == NULL)
inf->revoked = sk_X509_REVOKED_new(X509_REVOKED_cmp);
if (inf->revoked == NULL || !sk_X509_REVOKED_push(inf->revoked, rev)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_CRYPTO_LIB);
return 0;
}
inf->enc.modified = 1;
return 1;
}
int X509_CRL_verify(X509_CRL *crl, EVP_PKEY *r)
{
if (crl->meth->crl_verify)
return crl->meth->crl_verify(crl, r);
return 0;
}
int X509_CRL_get0_by_serial(X509_CRL *crl,
X509_REVOKED **ret, const ASN1_INTEGER *serial)
{
if (crl->meth->crl_lookup)
return crl->meth->crl_lookup(crl, ret, serial, NULL);
return 0;
}
int X509_CRL_get0_by_cert(X509_CRL *crl, X509_REVOKED **ret, X509 *x)
{
if (crl->meth->crl_lookup)
return crl->meth->crl_lookup(crl, ret,
X509_get0_serialNumber(x),
X509_get_issuer_name(x));
return 0;
}
static int def_crl_verify(X509_CRL *crl, EVP_PKEY *r)
{
return ASN1_item_verify_ex(ASN1_ITEM_rptr(X509_CRL_INFO),
&crl->sig_alg, &crl->signature, &crl->crl, NULL,
r, crl->libctx, crl->propq);
}
static int crl_revoked_issuer_match(X509_CRL *crl, const X509_NAME *nm,
X509_REVOKED *rev)
{
int i;
if (!rev->issuer) {
if (!nm)
return 1;
if (!X509_NAME_cmp(nm, X509_CRL_get_issuer(crl)))
return 1;
return 0;
}
if (!nm)
nm = X509_CRL_get_issuer(crl);
for (i = 0; i < sk_GENERAL_NAME_num(rev->issuer); i++) {
GENERAL_NAME *gen = sk_GENERAL_NAME_value(rev->issuer, i);
if (gen->type != GEN_DIRNAME)
continue;
if (!X509_NAME_cmp(nm, gen->d.directoryName))
return 1;
}
return 0;
}
static int def_crl_lookup(X509_CRL *crl,
X509_REVOKED **ret, const ASN1_INTEGER *serial,
const X509_NAME *issuer)
{
X509_REVOKED rtmp, *rev;
int idx, num;
if (crl->crl.revoked == NULL)
return 0;
/*
* Sort revoked into serial number order if not already sorted. Do this
* under a lock to avoid race condition.
*/
if (!sk_X509_REVOKED_is_sorted(crl->crl.revoked)) {
if (!CRYPTO_THREAD_write_lock(crl->lock))
return 0;
sk_X509_REVOKED_sort(crl->crl.revoked);
CRYPTO_THREAD_unlock(crl->lock);
}
rtmp.serialNumber = *serial;
idx = sk_X509_REVOKED_find(crl->crl.revoked, &rtmp);
if (idx < 0)
return 0;
/* Need to look for matching name */
for (num = sk_X509_REVOKED_num(crl->crl.revoked); idx < num; idx++) {
rev = sk_X509_REVOKED_value(crl->crl.revoked, idx);
if (ASN1_INTEGER_cmp(&rev->serialNumber, serial))
return 0;
if (crl_revoked_issuer_match(crl, issuer, rev)) {
if (ret)
*ret = rev;
if (rev->reason == CRL_REASON_REMOVE_FROM_CRL)
return 2;
return 1;
}
}
return 0;
}
void X509_CRL_set_default_method(const X509_CRL_METHOD *meth)
{
if (meth == NULL)
default_crl_method = &int_crl_meth;
else
default_crl_method = meth;
}
X509_CRL_METHOD *X509_CRL_METHOD_new(int (*crl_init) (X509_CRL *crl),
int (*crl_free) (X509_CRL *crl),
int (*crl_lookup) (X509_CRL *crl,
X509_REVOKED **ret,
const ASN1_INTEGER *ser,
const X509_NAME *issuer),
int (*crl_verify) (X509_CRL *crl,
EVP_PKEY *pk))
{
X509_CRL_METHOD *m = OPENSSL_malloc(sizeof(*m));
if (m == NULL)
return NULL;
m->crl_init = crl_init;
m->crl_free = crl_free;
m->crl_lookup = crl_lookup;
m->crl_verify = crl_verify;
m->flags = X509_CRL_METHOD_DYNAMIC;
return m;
}
void X509_CRL_METHOD_free(X509_CRL_METHOD *m)
{
if (m == NULL || !(m->flags & X509_CRL_METHOD_DYNAMIC))
return;
OPENSSL_free(m);
}
void X509_CRL_set_meth_data(X509_CRL *crl, void *dat)
{
crl->meth_data = dat;
}
void *X509_CRL_get_meth_data(X509_CRL *crl)
{
return crl->meth_data;
}
int ossl_x509_crl_set0_libctx(X509_CRL *x, OSSL_LIB_CTX *libctx,
const char *propq)
{
if (x != NULL) {
x->libctx = libctx;
OPENSSL_free(x->propq);
x->propq = NULL;
if (propq != NULL) {
x->propq = OPENSSL_strdup(propq);
if (x->propq == NULL)
return 0;
}
}
return 1;
}
| 16,280 | 29.431776 | 81 |
c
|
openssl
|
openssl-master/crypto/x509/x_exten.c
|
/*
* Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stddef.h>
#include <openssl/x509.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include "x509_local.h"
ASN1_SEQUENCE(X509_EXTENSION) = {
ASN1_SIMPLE(X509_EXTENSION, object, ASN1_OBJECT),
ASN1_OPT(X509_EXTENSION, critical, ASN1_BOOLEAN),
ASN1_EMBED(X509_EXTENSION, value, ASN1_OCTET_STRING)
} ASN1_SEQUENCE_END(X509_EXTENSION)
ASN1_ITEM_TEMPLATE(X509_EXTENSIONS) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, Extension, X509_EXTENSION)
ASN1_ITEM_TEMPLATE_END(X509_EXTENSIONS)
IMPLEMENT_ASN1_FUNCTIONS(X509_EXTENSION)
IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(X509_EXTENSIONS, X509_EXTENSIONS, X509_EXTENSIONS)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_EXTENSION)
| 1,045 | 35.068966 | 88 |
c
|
openssl
|
openssl-master/crypto/x509/x_name.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "crypto/ctype.h"
#include "internal/cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
#include "crypto/asn1.h"
#include "x509_local.h"
/*
* Maximum length of X509_NAME: much larger than anything we should
* ever see in practice.
*/
#define X509_NAME_MAX (1024 * 1024)
static int x509_name_ex_d2i(ASN1_VALUE **val,
const unsigned char **in, long len,
const ASN1_ITEM *it,
int tag, int aclass, char opt, ASN1_TLC *ctx);
static int x509_name_ex_i2d(const ASN1_VALUE **val, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass);
static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it);
static void x509_name_ex_free(ASN1_VALUE **val, const ASN1_ITEM *it);
static int x509_name_encode(X509_NAME *a);
static int x509_name_canon(X509_NAME *a);
static int asn1_string_canon(ASN1_STRING *out, const ASN1_STRING *in);
static int i2d_name_canon(const STACK_OF(STACK_OF_X509_NAME_ENTRY) * intname,
unsigned char **in);
static int x509_name_ex_print(BIO *out, const ASN1_VALUE **pval,
int indent,
const char *fname, const ASN1_PCTX *pctx);
ASN1_SEQUENCE(X509_NAME_ENTRY) = {
ASN1_SIMPLE(X509_NAME_ENTRY, object, ASN1_OBJECT),
ASN1_SIMPLE(X509_NAME_ENTRY, value, ASN1_PRINTABLE)
} ASN1_SEQUENCE_END(X509_NAME_ENTRY)
IMPLEMENT_ASN1_FUNCTIONS(X509_NAME_ENTRY)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)
/*
* For the "Name" type we need a SEQUENCE OF { SET OF X509_NAME_ENTRY } so
* declare two template wrappers for this
*/
ASN1_ITEM_TEMPLATE(X509_NAME_ENTRIES) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_OF, 0, RDNS, X509_NAME_ENTRY)
static_ASN1_ITEM_TEMPLATE_END(X509_NAME_ENTRIES)
ASN1_ITEM_TEMPLATE(X509_NAME_INTERNAL) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, Name, X509_NAME_ENTRIES)
static_ASN1_ITEM_TEMPLATE_END(X509_NAME_INTERNAL)
/*
* Normally that's where it would end: we'd have two nested STACK structures
* representing the ASN1. Unfortunately X509_NAME uses a completely different
* form and caches encodings so we have to process the internal form and
* convert to the external form.
*/
static const ASN1_EXTERN_FUNCS x509_name_ff = {
NULL,
x509_name_ex_new,
x509_name_ex_free,
0, /* Default clear behaviour is OK */
x509_name_ex_d2i,
x509_name_ex_i2d,
x509_name_ex_print
};
IMPLEMENT_EXTERN_ASN1(X509_NAME, V_ASN1_SEQUENCE, x509_name_ff)
IMPLEMENT_ASN1_FUNCTIONS(X509_NAME)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_NAME)
static int x509_name_ex_new(ASN1_VALUE **val, const ASN1_ITEM *it)
{
X509_NAME *ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL)
return 0;
if ((ret->entries = sk_X509_NAME_ENTRY_new_null()) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_CRYPTO_LIB);
goto err;
}
if ((ret->bytes = BUF_MEM_new()) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
goto err;
}
ret->modified = 1;
*val = (ASN1_VALUE *)ret;
return 1;
err:
if (ret) {
sk_X509_NAME_ENTRY_free(ret->entries);
OPENSSL_free(ret);
}
return 0;
}
static void x509_name_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
X509_NAME *a;
if (pval == NULL || *pval == NULL)
return;
a = (X509_NAME *)*pval;
BUF_MEM_free(a->bytes);
sk_X509_NAME_ENTRY_pop_free(a->entries, X509_NAME_ENTRY_free);
OPENSSL_free(a->canon_enc);
OPENSSL_free(a);
*pval = NULL;
}
static void local_sk_X509_NAME_ENTRY_free(STACK_OF(X509_NAME_ENTRY) *ne)
{
sk_X509_NAME_ENTRY_free(ne);
}
static void local_sk_X509_NAME_ENTRY_pop_free(STACK_OF(X509_NAME_ENTRY) *ne)
{
sk_X509_NAME_ENTRY_pop_free(ne, X509_NAME_ENTRY_free);
}
static int x509_name_ex_d2i(ASN1_VALUE **val,
const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass,
char opt, ASN1_TLC *ctx)
{
const unsigned char *p = *in, *q;
union {
STACK_OF(STACK_OF_X509_NAME_ENTRY) *s;
ASN1_VALUE *a;
} intname = {
NULL
};
union {
X509_NAME *x;
ASN1_VALUE *a;
} nm = {
NULL
};
int i, j, ret;
STACK_OF(X509_NAME_ENTRY) *entries;
X509_NAME_ENTRY *entry;
if (len > X509_NAME_MAX)
len = X509_NAME_MAX;
q = p;
/* Get internal representation of Name */
ret = ASN1_item_ex_d2i(&intname.a,
&p, len, ASN1_ITEM_rptr(X509_NAME_INTERNAL),
tag, aclass, opt, ctx);
if (ret <= 0)
return ret;
if (*val)
x509_name_ex_free(val, NULL);
if (!x509_name_ex_new(&nm.a, NULL))
goto err;
/* We've decoded it: now cache encoding */
if (!BUF_MEM_grow(nm.x->bytes, p - q))
goto err;
memcpy(nm.x->bytes->data, q, p - q);
/* Convert internal representation to X509_NAME structure */
for (i = 0; i < sk_STACK_OF_X509_NAME_ENTRY_num(intname.s); i++) {
entries = sk_STACK_OF_X509_NAME_ENTRY_value(intname.s, i);
for (j = 0; j < sk_X509_NAME_ENTRY_num(entries); j++) {
entry = sk_X509_NAME_ENTRY_value(entries, j);
entry->set = i;
if (!sk_X509_NAME_ENTRY_push(nm.x->entries, entry))
goto err;
(void)sk_X509_NAME_ENTRY_set(entries, j, NULL);
}
}
ret = x509_name_canon(nm.x);
if (!ret)
goto err;
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
local_sk_X509_NAME_ENTRY_free);
nm.x->modified = 0;
*val = nm.a;
*in = p;
return ret;
err:
if (nm.x != NULL)
X509_NAME_free(nm.x);
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
local_sk_X509_NAME_ENTRY_pop_free);
ERR_raise(ERR_LIB_ASN1, ERR_R_NESTED_ASN1_ERROR);
return 0;
}
static int x509_name_ex_i2d(const ASN1_VALUE **val, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass)
{
int ret;
X509_NAME *a = (X509_NAME *)*val;
if (a->modified) {
ret = x509_name_encode(a);
if (ret < 0)
return ret;
ret = x509_name_canon(a);
if (!ret)
return -1;
}
ret = a->bytes->length;
if (out != NULL) {
memcpy(*out, a->bytes->data, ret);
*out += ret;
}
return ret;
}
static int x509_name_encode(X509_NAME *a)
{
union {
STACK_OF(STACK_OF_X509_NAME_ENTRY) *s;
const ASN1_VALUE *a;
} intname = {
NULL
};
int len;
unsigned char *p;
STACK_OF(X509_NAME_ENTRY) *entries = NULL;
X509_NAME_ENTRY *entry;
int i, set = -1;
intname.s = sk_STACK_OF_X509_NAME_ENTRY_new_null();
if (!intname.s)
goto cerr;
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
entry = sk_X509_NAME_ENTRY_value(a->entries, i);
if (entry->set != set) {
entries = sk_X509_NAME_ENTRY_new_null();
if (!entries)
goto cerr;
if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname.s, entries)) {
sk_X509_NAME_ENTRY_free(entries);
goto cerr;
}
set = entry->set;
}
if (!sk_X509_NAME_ENTRY_push(entries, entry))
goto cerr;
}
len = ASN1_item_ex_i2d(&intname.a, NULL,
ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
if (!BUF_MEM_grow(a->bytes, len)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_BUF_LIB);
goto err;
}
p = (unsigned char *)a->bytes->data;
ASN1_item_ex_i2d(&intname.a,
&p, ASN1_ITEM_rptr(X509_NAME_INTERNAL), -1, -1);
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
local_sk_X509_NAME_ENTRY_free);
a->modified = 0;
return len;
cerr:
ERR_raise(ERR_LIB_ASN1, ERR_R_CRYPTO_LIB);
err:
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname.s,
local_sk_X509_NAME_ENTRY_free);
return -1;
}
static int x509_name_ex_print(BIO *out, const ASN1_VALUE **pval,
int indent,
const char *fname, const ASN1_PCTX *pctx)
{
if (X509_NAME_print_ex(out, (const X509_NAME *)*pval,
indent, pctx->nm_flags) <= 0)
return 0;
return 2;
}
/*
* This function generates the canonical encoding of the Name structure. In
* it all strings are converted to UTF8, leading, trailing and multiple
* spaces collapsed, converted to lower case and the leading SEQUENCE header
* removed. In future we could also normalize the UTF8 too. By doing this
* comparison of Name structures can be rapidly performed by just using
* memcmp() of the canonical encoding. By omitting the leading SEQUENCE name
* constraints of type dirName can also be checked with a simple memcmp().
* NOTE: For empty X509_NAME (NULL-DN), canon_enclen == 0 && canon_enc == NULL
*/
static int x509_name_canon(X509_NAME *a)
{
unsigned char *p;
STACK_OF(STACK_OF_X509_NAME_ENTRY) *intname;
STACK_OF(X509_NAME_ENTRY) *entries = NULL;
X509_NAME_ENTRY *entry, *tmpentry = NULL;
int i, set = -1, ret = 0, len;
OPENSSL_free(a->canon_enc);
a->canon_enc = NULL;
/* Special case: empty X509_NAME => null encoding */
if (sk_X509_NAME_ENTRY_num(a->entries) == 0) {
a->canon_enclen = 0;
return 1;
}
intname = sk_STACK_OF_X509_NAME_ENTRY_new_null();
if (intname == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
}
for (i = 0; i < sk_X509_NAME_ENTRY_num(a->entries); i++) {
entry = sk_X509_NAME_ENTRY_value(a->entries, i);
if (entry->set != set) {
entries = sk_X509_NAME_ENTRY_new_null();
if (entries == NULL)
goto err;
if (!sk_STACK_OF_X509_NAME_ENTRY_push(intname, entries)) {
sk_X509_NAME_ENTRY_free(entries);
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
}
set = entry->set;
}
tmpentry = X509_NAME_ENTRY_new();
if (tmpentry == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
goto err;
}
tmpentry->object = OBJ_dup(entry->object);
if (tmpentry->object == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_OBJ_LIB);
goto err;
}
if (!asn1_string_canon(tmpentry->value, entry->value))
goto err;
if (!sk_X509_NAME_ENTRY_push(entries, tmpentry)) {
ERR_raise(ERR_LIB_X509, ERR_R_CRYPTO_LIB);
goto err;
}
tmpentry = NULL;
}
/* Finally generate encoding */
len = i2d_name_canon(intname, NULL);
if (len < 0)
goto err;
a->canon_enclen = len;
p = OPENSSL_malloc(a->canon_enclen);
if (p == NULL)
goto err;
a->canon_enc = p;
i2d_name_canon(intname, &p);
ret = 1;
err:
X509_NAME_ENTRY_free(tmpentry);
sk_STACK_OF_X509_NAME_ENTRY_pop_free(intname,
local_sk_X509_NAME_ENTRY_pop_free);
return ret;
}
/* Bitmap of all the types of string that will be canonicalized. */
#define ASN1_MASK_CANON \
(B_ASN1_UTF8STRING | B_ASN1_BMPSTRING | B_ASN1_UNIVERSALSTRING \
| B_ASN1_PRINTABLESTRING | B_ASN1_T61STRING | B_ASN1_IA5STRING \
| B_ASN1_VISIBLESTRING)
static int asn1_string_canon(ASN1_STRING *out, const ASN1_STRING *in)
{
unsigned char *to, *from;
int len, i;
/* If type not in bitmask just copy string across */
if (!(ASN1_tag2bit(in->type) & ASN1_MASK_CANON)) {
if (!ASN1_STRING_copy(out, in))
return 0;
return 1;
}
out->type = V_ASN1_UTF8STRING;
out->length = ASN1_STRING_to_UTF8(&out->data, in);
if (out->length == -1)
return 0;
to = out->data;
from = to;
len = out->length;
/*
* Convert string in place to canonical form. Ultimately we may need to
* handle a wider range of characters but for now ignore anything with
* MSB set and rely on the ossl_isspace() to fail on bad characters without
* needing isascii or range checks as well.
*/
/* Ignore leading spaces */
while (len > 0 && ossl_isspace(*from)) {
from++;
len--;
}
to = from + len;
/* Ignore trailing spaces */
while (len > 0 && ossl_isspace(to[-1])) {
to--;
len--;
}
to = out->data;
i = 0;
while (i < len) {
/* If not ASCII set just copy across */
if (!ossl_isascii(*from)) {
*to++ = *from++;
i++;
}
/* Collapse multiple spaces */
else if (ossl_isspace(*from)) {
/* Copy one space across */
*to++ = ' ';
/*
* Ignore subsequent spaces. Note: don't need to check len here
* because we know the last character is a non-space so we can't
* overflow.
*/
do {
from++;
i++;
}
while (ossl_isspace(*from));
} else {
*to++ = ossl_tolower(*from);
from++;
i++;
}
}
out->length = to - out->data;
return 1;
}
static int i2d_name_canon(const STACK_OF(STACK_OF_X509_NAME_ENTRY) * _intname,
unsigned char **in)
{
int i, len, ltmp;
const ASN1_VALUE *v;
STACK_OF(ASN1_VALUE) *intname = (STACK_OF(ASN1_VALUE) *)_intname;
len = 0;
for (i = 0; i < sk_ASN1_VALUE_num(intname); i++) {
v = sk_ASN1_VALUE_value(intname, i);
ltmp = ASN1_item_ex_i2d(&v, in,
ASN1_ITEM_rptr(X509_NAME_ENTRIES), -1, -1);
if (ltmp < 0)
return ltmp;
len += ltmp;
}
return len;
}
int X509_NAME_set(X509_NAME **xn, const X509_NAME *name)
{
X509_NAME *name_copy;
if (*xn == name)
return *xn != NULL;
if ((name_copy = X509_NAME_dup(name)) == NULL)
return 0;
X509_NAME_free(*xn);
*xn = name_copy;
return 1;
}
int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase)
{
char *s, *c, *b;
int i;
b = X509_NAME_oneline(name, NULL, 0);
if (b == NULL)
return 0;
if (*b == '\0') {
OPENSSL_free(b);
return 1;
}
s = b + 1; /* skip the first slash */
c = s;
for (;;) {
if (((*s == '/') &&
(ossl_isupper(s[1]) && ((s[2] == '=') ||
(ossl_isupper(s[2]) && (s[3] == '='))
))) || (*s == '\0'))
{
i = s - c;
if (BIO_write(bp, c, i) != i)
goto err;
c = s + 1; /* skip following slash */
if (*s != '\0') {
if (BIO_write(bp, ", ", 2) != 2)
goto err;
}
}
if (*s == '\0')
break;
s++;
}
OPENSSL_free(b);
return 1;
err:
ERR_raise(ERR_LIB_X509, ERR_R_BUF_LIB);
OPENSSL_free(b);
return 0;
}
int X509_NAME_get0_der(const X509_NAME *nm, const unsigned char **pder,
size_t *pderlen)
{
/* Make sure encoding is valid */
if (i2d_X509_NAME(nm, NULL) <= 0)
return 0;
if (pder != NULL)
*pder = (unsigned char *)nm->bytes->data;
if (pderlen != NULL)
*pderlen = nm->bytes->length;
return 1;
}
| 16,162 | 27.96595 | 80 |
c
|
openssl
|
openssl-master/crypto/x509/x_req.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
/*-
* X509_REQ_INFO is handled in an unusual way to get round
* invalid encodings. Some broken certificate requests don't
* encode the attributes field if it is empty. This is in
* violation of PKCS#10 but we need to tolerate it. We do
* this by making the attributes field OPTIONAL then using
* the callback to initialise it to an empty STACK.
*
* This means that the field will be correctly encoded unless
* we NULL out the field.
*
* As a result we no longer need the req_kludge field because
* the information is now contained in the attributes field:
* 1. If it is NULL then it's the invalid omission.
* 2. If it is empty it is the correct encoding.
* 3. If it is not empty then some attributes are present.
*
*/
static int rinf_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
void *exarg)
{
X509_REQ_INFO *rinf = (X509_REQ_INFO *)*pval;
if (operation == ASN1_OP_NEW_POST) {
rinf->attributes = sk_X509_ATTRIBUTE_new_null();
if (!rinf->attributes)
return 0;
}
return 1;
}
static int req_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
void *exarg)
{
X509_REQ *ret = (X509_REQ *)*pval;
switch (operation) {
case ASN1_OP_D2I_PRE:
ASN1_OCTET_STRING_free(ret->distinguishing_id);
/* fall through */
case ASN1_OP_NEW_POST:
ret->distinguishing_id = NULL;
break;
case ASN1_OP_FREE_POST:
ASN1_OCTET_STRING_free(ret->distinguishing_id);
OPENSSL_free(ret->propq);
break;
case ASN1_OP_DUP_POST:
{
X509_REQ *old = exarg;
if (!ossl_x509_req_set0_libctx(ret, old->libctx, old->propq))
return 0;
if (old->req_info.pubkey != NULL) {
EVP_PKEY *pkey = X509_PUBKEY_get0(old->req_info.pubkey);
if (pkey != NULL) {
pkey = EVP_PKEY_dup(pkey);
if (pkey == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_EVP_LIB);
return 0;
}
if (!X509_PUBKEY_set(&ret->req_info.pubkey, pkey)) {
EVP_PKEY_free(pkey);
ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
return 0;
}
EVP_PKEY_free(pkey);
}
}
}
break;
case ASN1_OP_GET0_LIBCTX:
{
OSSL_LIB_CTX **libctx = exarg;
*libctx = ret->libctx;
}
break;
case ASN1_OP_GET0_PROPQ:
{
const char **propq = exarg;
*propq = ret->propq;
}
break;
}
return 1;
}
ASN1_SEQUENCE_enc(X509_REQ_INFO, enc, rinf_cb) = {
ASN1_SIMPLE(X509_REQ_INFO, version, ASN1_INTEGER),
ASN1_SIMPLE(X509_REQ_INFO, subject, X509_NAME),
ASN1_SIMPLE(X509_REQ_INFO, pubkey, X509_PUBKEY),
/* This isn't really OPTIONAL but it gets round invalid
* encodings
*/
ASN1_IMP_SET_OF_OPT(X509_REQ_INFO, attributes, X509_ATTRIBUTE, 0)
} ASN1_SEQUENCE_END_enc(X509_REQ_INFO, X509_REQ_INFO)
IMPLEMENT_ASN1_FUNCTIONS(X509_REQ_INFO)
ASN1_SEQUENCE_ref(X509_REQ, req_cb) = {
ASN1_EMBED(X509_REQ, req_info, X509_REQ_INFO),
ASN1_EMBED(X509_REQ, sig_alg, X509_ALGOR),
ASN1_SIMPLE(X509_REQ, signature, ASN1_BIT_STRING)
} ASN1_SEQUENCE_END_ref(X509_REQ, X509_REQ)
IMPLEMENT_ASN1_FUNCTIONS(X509_REQ)
IMPLEMENT_ASN1_DUP_FUNCTION(X509_REQ)
void X509_REQ_set0_distinguishing_id(X509_REQ *x, ASN1_OCTET_STRING *d_id)
{
ASN1_OCTET_STRING_free(x->distinguishing_id);
x->distinguishing_id = d_id;
}
ASN1_OCTET_STRING *X509_REQ_get0_distinguishing_id(X509_REQ *x)
{
return x->distinguishing_id;
}
/*
* This should only be used if the X509_REQ object was embedded inside another
* asn1 object and it needs a libctx to operate.
* Use X509_REQ_new_ex() instead if possible.
*/
int ossl_x509_req_set0_libctx(X509_REQ *x, OSSL_LIB_CTX *libctx,
const char *propq)
{
if (x != NULL) {
x->libctx = libctx;
OPENSSL_free(x->propq);
x->propq = NULL;
if (propq != NULL) {
x->propq = OPENSSL_strdup(propq);
if (x->propq == NULL)
return 0;
}
}
return 1;
}
X509_REQ *X509_REQ_new_ex(OSSL_LIB_CTX *libctx, const char *propq)
{
X509_REQ *req = NULL;
req = (X509_REQ *)ASN1_item_new((X509_REQ_it()));
if (!ossl_x509_req_set0_libctx(req, libctx, propq)) {
X509_REQ_free(req);
req = NULL;
}
return req;
}
| 5,147 | 28.586207 | 78 |
c
|
openssl
|
openssl-master/crypto/x509/x_x509.c
|
/*
* Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/evp.h>
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include "crypto/x509.h"
ASN1_SEQUENCE_enc(X509_CINF, enc, 0) = {
ASN1_EXP_OPT(X509_CINF, version, ASN1_INTEGER, 0),
ASN1_EMBED(X509_CINF, serialNumber, ASN1_INTEGER),
ASN1_EMBED(X509_CINF, signature, X509_ALGOR),
ASN1_SIMPLE(X509_CINF, issuer, X509_NAME),
ASN1_EMBED(X509_CINF, validity, X509_VAL),
ASN1_SIMPLE(X509_CINF, subject, X509_NAME),
ASN1_SIMPLE(X509_CINF, key, X509_PUBKEY),
ASN1_IMP_OPT(X509_CINF, issuerUID, ASN1_BIT_STRING, 1),
ASN1_IMP_OPT(X509_CINF, subjectUID, ASN1_BIT_STRING, 2),
ASN1_EXP_SEQUENCE_OF_OPT(X509_CINF, extensions, X509_EXTENSION, 3)
} ASN1_SEQUENCE_END_enc(X509_CINF, X509_CINF)
IMPLEMENT_ASN1_FUNCTIONS(X509_CINF)
/* X509 top level structure needs a bit of customisation */
extern void ossl_policy_cache_free(X509_POLICY_CACHE *cache);
static int x509_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it,
void *exarg)
{
X509 *ret = (X509 *)*pval;
switch (operation) {
case ASN1_OP_D2I_PRE:
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509, ret, &ret->ex_data);
X509_CERT_AUX_free(ret->aux);
ASN1_OCTET_STRING_free(ret->skid);
AUTHORITY_KEYID_free(ret->akid);
CRL_DIST_POINTS_free(ret->crldp);
ossl_policy_cache_free(ret->policy_cache);
GENERAL_NAMES_free(ret->altname);
NAME_CONSTRAINTS_free(ret->nc);
#ifndef OPENSSL_NO_RFC3779
sk_IPAddressFamily_pop_free(ret->rfc3779_addr, IPAddressFamily_free);
ASIdentifiers_free(ret->rfc3779_asid);
#endif
ASN1_OCTET_STRING_free(ret->distinguishing_id);
/* fall through */
case ASN1_OP_NEW_POST:
ret->ex_cached = 0;
ret->ex_kusage = 0;
ret->ex_xkusage = 0;
ret->ex_nscert = 0;
ret->ex_flags = 0;
ret->ex_pathlen = -1;
ret->ex_pcpathlen = -1;
ret->skid = NULL;
ret->akid = NULL;
ret->policy_cache = NULL;
ret->altname = NULL;
ret->nc = NULL;
#ifndef OPENSSL_NO_RFC3779
ret->rfc3779_addr = NULL;
ret->rfc3779_asid = NULL;
#endif
ret->distinguishing_id = NULL;
ret->aux = NULL;
ret->crldp = NULL;
if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_X509, ret, &ret->ex_data))
return 0;
break;
case ASN1_OP_FREE_POST:
CRYPTO_free_ex_data(CRYPTO_EX_INDEX_X509, ret, &ret->ex_data);
X509_CERT_AUX_free(ret->aux);
ASN1_OCTET_STRING_free(ret->skid);
AUTHORITY_KEYID_free(ret->akid);
CRL_DIST_POINTS_free(ret->crldp);
ossl_policy_cache_free(ret->policy_cache);
GENERAL_NAMES_free(ret->altname);
NAME_CONSTRAINTS_free(ret->nc);
#ifndef OPENSSL_NO_RFC3779
sk_IPAddressFamily_pop_free(ret->rfc3779_addr, IPAddressFamily_free);
ASIdentifiers_free(ret->rfc3779_asid);
#endif
ASN1_OCTET_STRING_free(ret->distinguishing_id);
OPENSSL_free(ret->propq);
break;
case ASN1_OP_DUP_POST:
{
X509 *old = exarg;
if (!ossl_x509_set0_libctx(ret, old->libctx, old->propq))
return 0;
}
break;
case ASN1_OP_GET0_LIBCTX:
{
OSSL_LIB_CTX **libctx = exarg;
*libctx = ret->libctx;
}
break;
case ASN1_OP_GET0_PROPQ:
{
const char **propq = exarg;
*propq = ret->propq;
}
break;
default:
break;
}
return 1;
}
ASN1_SEQUENCE_ref(X509, x509_cb) = {
ASN1_EMBED(X509, cert_info, X509_CINF),
ASN1_EMBED(X509, sig_alg, X509_ALGOR),
ASN1_EMBED(X509, signature, ASN1_BIT_STRING)
} ASN1_SEQUENCE_END_ref(X509, X509)
IMPLEMENT_ASN1_FUNCTIONS(X509)
IMPLEMENT_ASN1_DUP_FUNCTION(X509)
/*
* This should only be used if the X509 object was embedded inside another
* asn1 object and it needs a libctx to operate.
* Use X509_new_ex() instead if possible.
*/
int ossl_x509_set0_libctx(X509 *x, OSSL_LIB_CTX *libctx, const char *propq)
{
if (x != NULL) {
x->libctx = libctx;
OPENSSL_free(x->propq);
x->propq = NULL;
if (propq != NULL) {
x->propq = OPENSSL_strdup(propq);
if (x->propq == NULL)
return 0;
}
}
return 1;
}
X509 *X509_new_ex(OSSL_LIB_CTX *libctx, const char *propq)
{
X509 *cert = NULL;
cert = (X509 *)ASN1_item_new_ex(X509_it(), libctx, propq);
if (!ossl_x509_set0_libctx(cert, libctx, propq)) {
X509_free(cert);
cert = NULL;
}
return cert;
}
int X509_set_ex_data(X509 *r, int idx, void *arg)
{
return CRYPTO_set_ex_data(&r->ex_data, idx, arg);
}
void *X509_get_ex_data(const X509 *r, int idx)
{
return CRYPTO_get_ex_data(&r->ex_data, idx);
}
/*
* X509_AUX ASN1 routines. X509_AUX is the name given to a certificate with
* extra info tagged on the end. Since these functions set how a certificate
* is trusted they should only be used when the certificate comes from a
* reliable source such as local storage.
*/
X509 *d2i_X509_AUX(X509 **a, const unsigned char **pp, long length)
{
const unsigned char *q;
X509 *ret;
int freeret = 0;
/* Save start position */
q = *pp;
if (a == NULL || *a == NULL)
freeret = 1;
ret = d2i_X509(a, &q, length);
/* If certificate unreadable then forget it */
if (ret == NULL)
return NULL;
/* update length */
length -= q - *pp;
if (length > 0 && !d2i_X509_CERT_AUX(&ret->aux, &q, length))
goto err;
*pp = q;
return ret;
err:
if (freeret) {
X509_free(ret);
if (a)
*a = NULL;
}
return NULL;
}
/*
* Serialize trusted certificate to *pp or just return the required buffer
* length if pp == NULL. We ultimately want to avoid modifying *pp in the
* error path, but that depends on similar hygiene in lower-level functions.
* Here we avoid compounding the problem.
*/
static int i2d_x509_aux_internal(const X509 *a, unsigned char **pp)
{
int length, tmplen;
unsigned char *start = pp != NULL ? *pp : NULL;
/*
* This might perturb *pp on error, but fixing that belongs in i2d_X509()
* not here. It should be that if a == NULL length is zero, but we check
* both just in case.
*/
length = i2d_X509(a, pp);
if (length <= 0 || a == NULL)
return length;
tmplen = i2d_X509_CERT_AUX(a->aux, pp);
if (tmplen < 0) {
if (start != NULL)
*pp = start;
return tmplen;
}
length += tmplen;
return length;
}
/*
* Serialize trusted certificate to *pp, or just return the required buffer
* length if pp == NULL.
*
* When pp is not NULL, but *pp == NULL, we allocate the buffer, but since
* we're writing two ASN.1 objects back to back, we can't have i2d_X509() do
* the allocation, nor can we allow i2d_X509_CERT_AUX() to increment the
* allocated buffer.
*/
int i2d_X509_AUX(const X509 *a, unsigned char **pp)
{
int length;
unsigned char *tmp;
/* Buffer provided by caller */
if (pp == NULL || *pp != NULL)
return i2d_x509_aux_internal(a, pp);
/* Obtain the combined length */
if ((length = i2d_x509_aux_internal(a, NULL)) <= 0)
return length;
/* Allocate requisite combined storage */
*pp = tmp = OPENSSL_malloc(length);
if (tmp == NULL)
return -1;
/* Encode, but keep *pp at the originally malloced pointer */
length = i2d_x509_aux_internal(a, &tmp);
if (length <= 0) {
OPENSSL_free(*pp);
*pp = NULL;
}
return length;
}
int i2d_re_X509_tbs(X509 *x, unsigned char **pp)
{
x->cert_info.enc.modified = 1;
return i2d_X509_CINF(&x->cert_info, pp);
}
void X509_get0_signature(const ASN1_BIT_STRING **psig,
const X509_ALGOR **palg, const X509 *x)
{
if (psig)
*psig = &x->signature;
if (palg)
*palg = &x->sig_alg;
}
int X509_get_signature_nid(const X509 *x)
{
return OBJ_obj2nid(x->sig_alg.algorithm);
}
void X509_set0_distinguishing_id(X509 *x, ASN1_OCTET_STRING *d_id)
{
ASN1_OCTET_STRING_free(x->distinguishing_id);
x->distinguishing_id = d_id;
}
ASN1_OCTET_STRING *X509_get0_distinguishing_id(X509 *x)
{
return x->distinguishing_id;
}
| 8,829 | 26.85489 | 77 |
c
|
openssl
|
openssl-master/crypto/x509/x_x509a.c
|
/*
* Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/evp.h>
#include <openssl/asn1t.h>
#include <openssl/x509.h>
#include "crypto/x509.h"
/*
* X509_CERT_AUX routines. These are used to encode additional user
* modifiable data about a certificate. This data is appended to the X509
* encoding when the *_X509_AUX routines are used. This means that the
* "traditional" X509 routines will simply ignore the extra data.
*/
static X509_CERT_AUX *aux_get(X509 *x);
ASN1_SEQUENCE(X509_CERT_AUX) = {
ASN1_SEQUENCE_OF_OPT(X509_CERT_AUX, trust, ASN1_OBJECT),
ASN1_IMP_SEQUENCE_OF_OPT(X509_CERT_AUX, reject, ASN1_OBJECT, 0),
ASN1_OPT(X509_CERT_AUX, alias, ASN1_UTF8STRING),
ASN1_OPT(X509_CERT_AUX, keyid, ASN1_OCTET_STRING),
ASN1_IMP_SEQUENCE_OF_OPT(X509_CERT_AUX, other, X509_ALGOR, 1)
} ASN1_SEQUENCE_END(X509_CERT_AUX)
IMPLEMENT_ASN1_FUNCTIONS(X509_CERT_AUX)
int X509_trusted(const X509 *x)
{
return x->aux ? 1 : 0;
}
static X509_CERT_AUX *aux_get(X509 *x)
{
if (x == NULL)
return NULL;
if (x->aux == NULL && (x->aux = X509_CERT_AUX_new()) == NULL)
return NULL;
return x->aux;
}
int X509_alias_set1(X509 *x, const unsigned char *name, int len)
{
X509_CERT_AUX *aux;
if (!name) {
if (!x || !x->aux || !x->aux->alias)
return 1;
ASN1_UTF8STRING_free(x->aux->alias);
x->aux->alias = NULL;
return 1;
}
if ((aux = aux_get(x)) == NULL)
return 0;
if (aux->alias == NULL && (aux->alias = ASN1_UTF8STRING_new()) == NULL)
return 0;
return ASN1_STRING_set(aux->alias, name, len);
}
int X509_keyid_set1(X509 *x, const unsigned char *id, int len)
{
X509_CERT_AUX *aux;
if (!id) {
if (!x || !x->aux || !x->aux->keyid)
return 1;
ASN1_OCTET_STRING_free(x->aux->keyid);
x->aux->keyid = NULL;
return 1;
}
if ((aux = aux_get(x)) == NULL)
return 0;
if (aux->keyid == NULL
&& (aux->keyid = ASN1_OCTET_STRING_new()) == NULL)
return 0;
return ASN1_STRING_set(aux->keyid, id, len);
}
unsigned char *X509_alias_get0(X509 *x, int *len)
{
if (!x->aux || !x->aux->alias)
return NULL;
if (len)
*len = x->aux->alias->length;
return x->aux->alias->data;
}
unsigned char *X509_keyid_get0(X509 *x, int *len)
{
if (!x->aux || !x->aux->keyid)
return NULL;
if (len)
*len = x->aux->keyid->length;
return x->aux->keyid->data;
}
int X509_add1_trust_object(X509 *x, const ASN1_OBJECT *obj)
{
X509_CERT_AUX *aux;
ASN1_OBJECT *objtmp = NULL;
if (obj) {
objtmp = OBJ_dup(obj);
if (!objtmp)
return 0;
}
if ((aux = aux_get(x)) == NULL)
goto err;
if (aux->trust == NULL
&& (aux->trust = sk_ASN1_OBJECT_new_null()) == NULL)
goto err;
if (!objtmp || sk_ASN1_OBJECT_push(aux->trust, objtmp))
return 1;
err:
ASN1_OBJECT_free(objtmp);
return 0;
}
int X509_add1_reject_object(X509 *x, const ASN1_OBJECT *obj)
{
X509_CERT_AUX *aux;
ASN1_OBJECT *objtmp;
int res = 0;
if ((objtmp = OBJ_dup(obj)) == NULL)
return 0;
if ((aux = aux_get(x)) == NULL)
goto err;
if (aux->reject == NULL
&& (aux->reject = sk_ASN1_OBJECT_new_null()) == NULL)
goto err;
if (sk_ASN1_OBJECT_push(aux->reject, objtmp) > 0)
res = 1;
err:
if (!res)
ASN1_OBJECT_free(objtmp);
return res;
}
void X509_trust_clear(X509 *x)
{
if (x->aux) {
sk_ASN1_OBJECT_pop_free(x->aux->trust, ASN1_OBJECT_free);
x->aux->trust = NULL;
}
}
void X509_reject_clear(X509 *x)
{
if (x->aux) {
sk_ASN1_OBJECT_pop_free(x->aux->reject, ASN1_OBJECT_free);
x->aux->reject = NULL;
}
}
STACK_OF(ASN1_OBJECT) *X509_get0_trust_objects(X509 *x)
{
if (x->aux != NULL)
return x->aux->trust;
return NULL;
}
STACK_OF(ASN1_OBJECT) *X509_get0_reject_objects(X509 *x)
{
if (x->aux != NULL)
return x->aux->reject;
return NULL;
}
| 4,433 | 24.337143 | 75 |
c
|
openssl
|
openssl-master/demos/bio/client-arg.c
|
/*
* Copyright 2013-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
int main(int argc, char **argv)
{
BIO *sbio = NULL, *out = NULL;
int len;
char tmpbuf[1024];
SSL_CTX *ctx;
SSL_CONF_CTX *cctx;
SSL *ssl;
char **args = argv + 1;
const char *connect_str = "localhost:4433";
int nargs = argc - 1;
int ret = EXIT_FAILURE;
ctx = SSL_CTX_new(TLS_client_method());
cctx = SSL_CONF_CTX_new();
SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT);
SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
while (*args && **args == '-') {
int rv;
/* Parse standard arguments */
rv = SSL_CONF_cmd_argv(cctx, &nargs, &args);
if (rv == -3) {
fprintf(stderr, "Missing argument for %s\n", *args);
goto end;
}
if (rv < 0) {
fprintf(stderr, "Error in command %s\n", *args);
ERR_print_errors_fp(stderr);
goto end;
}
/* If rv > 0 we processed something so proceed to next arg */
if (rv > 0)
continue;
/* Otherwise application specific argument processing */
if (strcmp(*args, "-connect") == 0) {
connect_str = args[1];
if (connect_str == NULL) {
fprintf(stderr, "Missing -connect argument\n");
goto end;
}
args += 2;
nargs -= 2;
continue;
} else {
fprintf(stderr, "Unknown argument %s\n", *args);
goto end;
}
}
if (!SSL_CONF_CTX_finish(cctx)) {
fprintf(stderr, "Finish error\n");
ERR_print_errors_fp(stderr);
goto end;
}
/*
* We'd normally set some stuff like the verify paths and * mode here
* because as things stand this will connect to * any server whose
* certificate is signed by any CA.
*/
sbio = BIO_new_ssl_connect(ctx);
BIO_get_ssl(sbio, &ssl);
if (!ssl) {
fprintf(stderr, "Can't locate SSL pointer\n");
goto end;
}
/* We might want to do other things with ssl here */
BIO_set_conn_hostname(sbio, connect_str);
out = BIO_new_fp(stdout, BIO_NOCLOSE);
if (BIO_do_connect(sbio) <= 0) {
fprintf(stderr, "Error connecting to server\n");
ERR_print_errors_fp(stderr);
goto end;
}
/* Could examine ssl here to get connection info */
BIO_puts(sbio, "GET / HTTP/1.0\n\n");
for (;;) {
len = BIO_read(sbio, tmpbuf, 1024);
if (len <= 0)
break;
BIO_write(out, tmpbuf, len);
}
ret = EXIT_SUCCESS;
end:
SSL_CONF_CTX_free(cctx);
BIO_free_all(sbio);
BIO_free(out);
return ret;
}
| 3,055 | 26.531532 | 74 |
c
|
openssl
|
openssl-master/demos/bio/client-conf.c
|
/*
* Copyright 2013-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/conf.h>
int main(int argc, char **argv)
{
BIO *sbio = NULL, *out = NULL;
int i, len, rv;
char tmpbuf[1024];
SSL_CTX *ctx = NULL;
SSL_CONF_CTX *cctx = NULL;
SSL *ssl = NULL;
CONF *conf = NULL;
STACK_OF(CONF_VALUE) *sect = NULL;
CONF_VALUE *cnf;
const char *connect_str = "localhost:4433";
long errline = -1;
int ret = EXIT_FAILURE;
conf = NCONF_new(NULL);
if (NCONF_load(conf, "connect.cnf", &errline) <= 0) {
if (errline <= 0)
fprintf(stderr, "Error processing config file\n");
else
fprintf(stderr, "Error on line %ld\n", errline);
goto end;
}
sect = NCONF_get_section(conf, "default");
if (sect == NULL) {
fprintf(stderr, "Error retrieving default section\n");
goto end;
}
ctx = SSL_CTX_new(TLS_client_method());
cctx = SSL_CONF_CTX_new();
SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CLIENT);
SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE);
SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
for (i = 0; i < sk_CONF_VALUE_num(sect); i++) {
cnf = sk_CONF_VALUE_value(sect, i);
rv = SSL_CONF_cmd(cctx, cnf->name, cnf->value);
if (rv > 0)
continue;
if (rv != -2) {
fprintf(stderr, "Error processing %s = %s\n",
cnf->name, cnf->value);
ERR_print_errors_fp(stderr);
goto end;
}
if (strcmp(cnf->name, "Connect") == 0) {
connect_str = cnf->value;
} else {
fprintf(stderr, "Unknown configuration option %s\n", cnf->name);
goto end;
}
}
if (!SSL_CONF_CTX_finish(cctx)) {
fprintf(stderr, "Finish error\n");
ERR_print_errors_fp(stderr);
goto end;
}
/*
* We'd normally set some stuff like the verify paths and * mode here
* because as things stand this will connect to * any server whose
* certificate is signed by any CA.
*/
sbio = BIO_new_ssl_connect(ctx);
BIO_get_ssl(sbio, &ssl);
if (!ssl) {
fprintf(stderr, "Can't locate SSL pointer\n");
goto end;
}
/* We might want to do other things with ssl here */
BIO_set_conn_hostname(sbio, connect_str);
out = BIO_new_fp(stdout, BIO_NOCLOSE);
if (BIO_do_connect(sbio) <= 0) {
fprintf(stderr, "Error connecting to server\n");
ERR_print_errors_fp(stderr);
goto end;
}
/* Could examine ssl here to get connection info */
BIO_puts(sbio, "GET / HTTP/1.0\n\n");
for (;;) {
len = BIO_read(sbio, tmpbuf, 1024);
if (len <= 0)
break;
BIO_write(out, tmpbuf, len);
}
ret = EXIT_SUCCESS;
end:
SSL_CONF_CTX_free(cctx);
BIO_free_all(sbio);
BIO_free(out);
NCONF_free(conf);
return ret;
}
| 3,277 | 26.090909 | 76 |
c
|
openssl
|
openssl-master/demos/bio/saccept.c
|
/*
* Copyright 1998-2017 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*-
* A minimal program to serve an SSL connection.
* It uses blocking.
* saccept host:port
* host is the interface IP to use. If any interface, use *:port
* The default it *:4433
*
* cc -I../../include saccept.c -L../.. -lssl -lcrypto -ldl
*/
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#define CERT_FILE "server.pem"
static volatile int done = 0;
void interrupt(int sig)
{
done = 1;
}
void sigsetup(void)
{
struct sigaction sa;
/*
* Catch at most once, and don't restart the accept system call.
*/
sa.sa_flags = SA_RESETHAND;
sa.sa_handler = interrupt;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
}
int main(int argc, char *argv[])
{
char *port = NULL;
BIO *in = NULL;
BIO *ssl_bio, *tmp;
SSL_CTX *ctx;
char buf[512];
int ret = EXIT_FAILURE, i;
if (argc <= 1)
port = "*:4433";
else
port = argv[1];
ctx = SSL_CTX_new(TLS_server_method());
if (!SSL_CTX_use_certificate_chain_file(ctx, CERT_FILE))
goto err;
if (!SSL_CTX_use_PrivateKey_file(ctx, CERT_FILE, SSL_FILETYPE_PEM))
goto err;
if (!SSL_CTX_check_private_key(ctx))
goto err;
/* Setup server side SSL bio */
ssl_bio = BIO_new_ssl(ctx, 0);
if ((in = BIO_new_accept(port)) == NULL)
goto err;
/*
* This means that when a new connection is accepted on 'in', The ssl_bio
* will be 'duplicated' and have the new socket BIO push into it.
* Basically it means the SSL BIO will be automatically setup
*/
BIO_set_accept_bios(in, ssl_bio);
/* Arrange to leave server loop on interrupt */
sigsetup();
again:
/*
* The first call will setup the accept socket, and the second will get a
* socket. In this loop, the first actual accept will occur in the
* BIO_read() function.
*/
if (BIO_do_accept(in) <= 0)
goto err;
while (!done) {
i = BIO_read(in, buf, 512);
if (i == 0) {
/*
* If we have finished, remove the underlying BIO stack so the
* next time we call any function for this BIO, it will attempt
* to do an accept
*/
printf("Done\n");
tmp = BIO_pop(in);
BIO_free_all(tmp);
goto again;
}
if (i < 0)
goto err;
fwrite(buf, 1, i, stdout);
fflush(stdout);
}
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS)
ERR_print_errors_fp(stderr);
BIO_free(in);
return ret;
}
| 2,979 | 23.42623 | 77 |
c
|
openssl
|
openssl-master/demos/bio/sconnect.c
|
/*
* Copyright 1998-2020 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*-
* A minimal program to do SSL to a passed host and port.
* It is actually using non-blocking IO but in a very simple manner
* sconnect host:port - it does a 'GET / HTTP/1.0'
*
* cc -I../../include sconnect.c -L../.. -lssl -lcrypto
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#define HOSTPORT "localhost:4433"
#define CAFILE "root.pem"
int main(int argc, char *argv[])
{
const char *hostport = HOSTPORT;
const char *CAfile = CAFILE;
const char *hostname;
char *cp;
BIO *out = NULL;
char buf[1024 * 10], *p;
SSL_CTX *ssl_ctx = NULL;
SSL *ssl;
BIO *ssl_bio;
int i, len, off, ret = EXIT_FAILURE;
if (argc > 1)
hostport = argv[1];
if (argc > 2)
CAfile = argv[2];
#ifdef WATT32
dbug_init();
sock_init();
#endif
ssl_ctx = SSL_CTX_new(TLS_client_method());
/* Enable trust chain verification */
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
SSL_CTX_load_verify_locations(ssl_ctx, CAfile, NULL);
/* Lets make a SSL structure */
ssl = SSL_new(ssl_ctx);
SSL_set_connect_state(ssl);
/* Use it inside an SSL BIO */
ssl_bio = BIO_new(BIO_f_ssl());
BIO_set_ssl(ssl_bio, ssl, BIO_CLOSE);
/* Lets use a connect BIO under the SSL BIO */
out = BIO_new(BIO_s_connect());
BIO_set_conn_hostname(out, hostport);
/* The BIO has parsed the host:port and even IPv6 literals in [] */
hostname = BIO_get_conn_hostname(out);
if (!hostname || SSL_set1_host(ssl, hostname) <= 0)
goto err;
BIO_set_nbio(out, 1);
out = BIO_push(ssl_bio, out);
p = "GET / HTTP/1.0\r\n\r\n";
len = strlen(p);
off = 0;
for (;;) {
i = BIO_write(out, &(p[off]), len);
if (i <= 0) {
if (BIO_should_retry(out)) {
fprintf(stderr, "write DELAY\n");
sleep(1);
continue;
} else {
goto err;
}
}
off += i;
len -= i;
if (len <= 0)
break;
}
for (;;) {
i = BIO_read(out, buf, sizeof(buf));
if (i == 0)
break;
if (i < 0) {
if (BIO_should_retry(out)) {
fprintf(stderr, "read DELAY\n");
sleep(1);
continue;
}
goto err;
}
fwrite(buf, 1, i, stdout);
}
ret = EXIT_SUCCESS;
goto done;
err:
if (ERR_peek_error() == 0) { /* system call error */
fprintf(stderr, "errno=%d ", errno);
perror("error");
} else {
ERR_print_errors_fp(stderr);
}
done:
BIO_free_all(out);
SSL_CTX_free(ssl_ctx);
return ret;
}
| 3,137 | 23.325581 | 74 |
c
|
openssl
|
openssl-master/demos/bio/server-arg.c
|
/*
* Copyright 2013-2017 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* A minimal program to serve an SSL connection. It uses blocking. It use the
* SSL_CONF API with the command line. cc -I../../include server-arg.c
* -L../.. -lssl -lcrypto -ldl
*/
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
int main(int argc, char *argv[])
{
char *port = "*:4433";
BIO *ssl_bio, *tmp;
SSL_CTX *ctx;
SSL_CONF_CTX *cctx;
char buf[512];
BIO *in = NULL;
int ret = EXIT_FAILURE, i;
char **args = argv + 1;
int nargs = argc - 1;
ctx = SSL_CTX_new(TLS_server_method());
cctx = SSL_CONF_CTX_new();
SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER);
SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CERTIFICATE);
SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
while (*args && **args == '-') {
int rv;
/* Parse standard arguments */
rv = SSL_CONF_cmd_argv(cctx, &nargs, &args);
if (rv == -3) {
fprintf(stderr, "Missing argument for %s\n", *args);
goto err;
}
if (rv < 0) {
fprintf(stderr, "Error in command %s\n", *args);
ERR_print_errors_fp(stderr);
goto err;
}
/* If rv > 0 we processed something so proceed to next arg */
if (rv > 0)
continue;
/* Otherwise application specific argument processing */
if (strcmp(*args, "-port") == 0) {
port = args[1];
if (port == NULL) {
fprintf(stderr, "Missing -port argument\n");
goto err;
}
args += 2;
nargs -= 2;
continue;
} else {
fprintf(stderr, "Unknown argument %s\n", *args);
goto err;
}
}
if (!SSL_CONF_CTX_finish(cctx)) {
fprintf(stderr, "Finish error\n");
ERR_print_errors_fp(stderr);
goto err;
}
#ifdef ITERATE_CERTS
/*
* Demo of how to iterate over all certificates in an SSL_CTX structure.
*/
{
X509 *x;
int rv;
rv = SSL_CTX_set_current_cert(ctx, SSL_CERT_SET_FIRST);
while (rv) {
X509 *x = SSL_CTX_get0_certificate(ctx);
X509_NAME_print_ex_fp(stdout, X509_get_subject_name(x), 0,
XN_FLAG_ONELINE);
printf("\n");
rv = SSL_CTX_set_current_cert(ctx, SSL_CERT_SET_NEXT);
}
fflush(stdout);
}
#endif
/* Setup server side SSL bio */
ssl_bio = BIO_new_ssl(ctx, 0);
if ((in = BIO_new_accept(port)) == NULL)
goto err;
/*
* This means that when a new connection is accepted on 'in', The ssl_bio
* will be 'duplicated' and have the new socket BIO push into it.
* Basically it means the SSL BIO will be automatically setup
*/
BIO_set_accept_bios(in, ssl_bio);
again:
/*
* The first call will setup the accept socket, and the second will get a
* socket. In this loop, the first actual accept will occur in the
* BIO_read() function.
*/
if (BIO_do_accept(in) <= 0)
goto err;
for (;;) {
i = BIO_read(in, buf, 512);
if (i == 0) {
/*
* If we have finished, remove the underlying BIO stack so the
* next time we call any function for this BIO, it will attempt
* to do an accept
*/
printf("Done\n");
tmp = BIO_pop(in);
BIO_free_all(tmp);
goto again;
}
if (i < 0)
goto err;
fwrite(buf, 1, i, stdout);
fflush(stdout);
}
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS)
ERR_print_errors_fp(stderr);
BIO_free(in);
return ret;
}
| 4,134 | 27.517241 | 77 |
c
|
openssl
|
openssl-master/demos/bio/server-cmod.c
|
/*
* Copyright 2015-2017 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* A minimal TLS server it ses SSL_CTX_config and a configuration file to
* set most server parameters.
*/
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/conf.h>
int main(int argc, char *argv[])
{
unsigned char buf[512];
char *port = "*:4433";
BIO *in = NULL;
BIO *ssl_bio, *tmp;
SSL_CTX *ctx;
int ret = EXIT_FAILURE, i;
ctx = SSL_CTX_new(TLS_server_method());
if (CONF_modules_load_file("cmod.cnf", "testapp", 0) <= 0) {
fprintf(stderr, "Error processing config file\n");
goto err;
}
if (SSL_CTX_config(ctx, "server") == 0) {
fprintf(stderr, "Error configuring server.\n");
goto err;
}
/* Setup server side SSL bio */
ssl_bio = BIO_new_ssl(ctx, 0);
if ((in = BIO_new_accept(port)) == NULL)
goto err;
/*
* This means that when a new connection is accepted on 'in', The ssl_bio
* will be 'duplicated' and have the new socket BIO push into it.
* Basically it means the SSL BIO will be automatically setup
*/
BIO_set_accept_bios(in, ssl_bio);
again:
/*
* The first call will setup the accept socket, and the second will get a
* socket. In this loop, the first actual accept will occur in the
* BIO_read() function.
*/
if (BIO_do_accept(in) <= 0)
goto err;
for (;;) {
i = BIO_read(in, buf, sizeof(buf));
if (i == 0) {
/*
* If we have finished, remove the underlying BIO stack so the
* next time we call any function for this BIO, it will attempt
* to do an accept
*/
printf("Done\n");
tmp = BIO_pop(in);
BIO_free_all(tmp);
goto again;
}
if (i < 0) {
if (BIO_should_retry(in))
continue;
goto err;
}
fwrite(buf, 1, i, stdout);
fflush(stdout);
}
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS)
ERR_print_errors_fp(stderr);
BIO_free(in);
return ret;
}
| 2,483 | 25.147368 | 77 |
c
|
openssl
|
openssl-master/demos/bio/server-conf.c
|
/*
* Copyright 2013-2017 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* A minimal program to serve an SSL connection. It uses blocking. It uses
* the SSL_CONF API with a configuration file. cc -I../../include saccept.c
* -L../.. -lssl -lcrypto -ldl
*/
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <openssl/conf.h>
int main(int argc, char *argv[])
{
char *port = "*:4433";
BIO *in = NULL;
BIO *ssl_bio, *tmp;
SSL_CTX *ctx;
SSL_CONF_CTX *cctx = NULL;
CONF *conf = NULL;
STACK_OF(CONF_VALUE) *sect = NULL;
CONF_VALUE *cnf;
long errline = -1;
char buf[512];
int ret = EXIT_FAILURE, i;
ctx = SSL_CTX_new(TLS_server_method());
conf = NCONF_new(NULL);
if (NCONF_load(conf, "accept.cnf", &errline) <= 0) {
if (errline <= 0)
fprintf(stderr, "Error processing config file\n");
else
fprintf(stderr, "Error on line %ld\n", errline);
goto err;
}
sect = NCONF_get_section(conf, "default");
if (sect == NULL) {
fprintf(stderr, "Error retrieving default section\n");
goto err;
}
cctx = SSL_CONF_CTX_new();
SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_SERVER);
SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_CERTIFICATE);
SSL_CONF_CTX_set_flags(cctx, SSL_CONF_FLAG_FILE);
SSL_CONF_CTX_set_ssl_ctx(cctx, ctx);
for (i = 0; i < sk_CONF_VALUE_num(sect); i++) {
int rv;
cnf = sk_CONF_VALUE_value(sect, i);
rv = SSL_CONF_cmd(cctx, cnf->name, cnf->value);
if (rv > 0)
continue;
if (rv != -2) {
fprintf(stderr, "Error processing %s = %s\n",
cnf->name, cnf->value);
ERR_print_errors_fp(stderr);
goto err;
}
if (strcmp(cnf->name, "Port") == 0) {
port = cnf->value;
} else {
fprintf(stderr, "Unknown configuration option %s\n", cnf->name);
goto err;
}
}
if (!SSL_CONF_CTX_finish(cctx)) {
fprintf(stderr, "Finish error\n");
ERR_print_errors_fp(stderr);
goto err;
}
/* Setup server side SSL bio */
ssl_bio = BIO_new_ssl(ctx, 0);
if ((in = BIO_new_accept(port)) == NULL)
goto err;
/*
* This means that when a new connection is accepted on 'in', The ssl_bio
* will be 'duplicated' and have the new socket BIO push into it.
* Basically it means the SSL BIO will be automatically setup
*/
BIO_set_accept_bios(in, ssl_bio);
again:
/*
* The first call will setup the accept socket, and the second will get a
* socket. In this loop, the first actual accept will occur in the
* BIO_read() function.
*/
if (BIO_do_accept(in) <= 0)
goto err;
for (;;) {
i = BIO_read(in, buf, 512);
if (i == 0) {
/*
* If we have finished, remove the underlying BIO stack so the
* next time we call any function for this BIO, it will attempt
* to do an accept
*/
printf("Done\n");
tmp = BIO_pop(in);
BIO_free_all(tmp);
goto again;
}
if (i < 0) {
if (BIO_should_retry(in))
continue;
goto err;
}
fwrite(buf, 1, i, stdout);
fflush(stdout);
}
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS)
ERR_print_errors_fp(stderr);
BIO_free(in);
return ret;
}
| 3,863 | 26.6 | 77 |
c
|
openssl
|
openssl-master/demos/cipher/aesccm.c
|
/*
* Copyright 2013-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Simple AES CCM authenticated encryption with additional data (AEAD)
* demonstration program.
*/
#include <stdio.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/core_names.h>
/* AES-CCM test data obtained from NIST public test vectors */
/* AES key */
static const unsigned char ccm_key[] = {
0xce, 0xb0, 0x09, 0xae, 0xa4, 0x45, 0x44, 0x51, 0xfe, 0xad, 0xf0, 0xe6,
0xb3, 0x6f, 0x45, 0x55, 0x5d, 0xd0, 0x47, 0x23, 0xba, 0xa4, 0x48, 0xe8
};
/* Unique nonce to be used for this message */
static const unsigned char ccm_nonce[] = {
0x76, 0x40, 0x43, 0xc4, 0x94, 0x60, 0xb7
};
/*
* Example of Additional Authenticated Data (AAD), i.e. unencrypted data
* which can be authenticated using the generated Tag value.
*/
static const unsigned char ccm_adata[] = {
0x6e, 0x80, 0xdd, 0x7f, 0x1b, 0xad, 0xf3, 0xa1, 0xc9, 0xab, 0x25, 0xc7,
0x5f, 0x10, 0xbd, 0xe7, 0x8c, 0x23, 0xfa, 0x0e, 0xb8, 0xf9, 0xaa, 0xa5,
0x3a, 0xde, 0xfb, 0xf4, 0xcb, 0xf7, 0x8f, 0xe4
};
/* Example plaintext to encrypt */
static const unsigned char ccm_pt[] = {
0xc8, 0xd2, 0x75, 0xf9, 0x19, 0xe1, 0x7d, 0x7f, 0xe6, 0x9c, 0x2a, 0x1f,
0x58, 0x93, 0x9d, 0xfe, 0x4d, 0x40, 0x37, 0x91, 0xb5, 0xdf, 0x13, 0x10
};
/* Expected ciphertext value */
static const unsigned char ccm_ct[] = {
0x8a, 0x0f, 0x3d, 0x82, 0x29, 0xe4, 0x8e, 0x74, 0x87, 0xfd, 0x95, 0xa2,
0x8a, 0xd3, 0x92, 0xc8, 0x0b, 0x36, 0x81, 0xd4, 0xfb, 0xc7, 0xbb, 0xfd
};
/* Expected AEAD Tag value */
static const unsigned char ccm_tag[] = {
0x2d, 0xd6, 0xef, 0x1c, 0x45, 0xd4, 0xcc, 0xb7, 0x23, 0xdc, 0x07, 0x44,
0x14, 0xdb, 0x50, 0x6d
};
/*
* A library context and property query can be used to select & filter
* algorithm implementations. If they are NULL then the default library
* context and properties are used.
*/
OSSL_LIB_CTX *libctx = NULL;
const char *propq = NULL;
int aes_ccm_encrypt(void)
{
int ret = 0;
EVP_CIPHER_CTX *ctx;
EVP_CIPHER *cipher = NULL;
int outlen, tmplen;
size_t ccm_nonce_len = sizeof(ccm_nonce);
size_t ccm_tag_len = sizeof(ccm_tag);
unsigned char outbuf[1024];
unsigned char outtag[16];
OSSL_PARAM params[3] = {
OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END
};
printf("AES CCM Encrypt:\n");
printf("Plaintext:\n");
BIO_dump_fp(stdout, ccm_pt, sizeof(ccm_pt));
/* Create a context for the encrypt operation */
if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
/* Fetch the cipher implementation */
if ((cipher = EVP_CIPHER_fetch(libctx, "AES-192-CCM", propq)) == NULL)
goto err;
/* Set nonce length if default 96 bits is not appropriate */
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_IVLEN,
&ccm_nonce_len);
/* Set tag length */
params[1] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG,
NULL, ccm_tag_len);
/*
* Initialise encrypt operation with the cipher & mode,
* nonce length and tag length parameters.
*/
if (!EVP_EncryptInit_ex2(ctx, cipher, NULL, NULL, params))
goto err;
/* Initialise key and nonce */
if (!EVP_EncryptInit_ex(ctx, NULL, NULL, ccm_key, ccm_nonce))
goto err;
/* Set plaintext length: only needed if AAD is used */
if (!EVP_EncryptUpdate(ctx, NULL, &outlen, NULL, sizeof(ccm_pt)))
goto err;
/* Zero or one call to specify any AAD */
if (!EVP_EncryptUpdate(ctx, NULL, &outlen, ccm_adata, sizeof(ccm_adata)))
goto err;
/* Encrypt plaintext: can only be called once */
if (!EVP_EncryptUpdate(ctx, outbuf, &outlen, ccm_pt, sizeof(ccm_pt)))
goto err;
/* Output encrypted block */
printf("Ciphertext:\n");
BIO_dump_fp(stdout, outbuf, outlen);
/* Finalise: note get no output for CCM */
if (!EVP_EncryptFinal_ex(ctx, NULL, &tmplen))
goto err;
/* Get tag */
params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG,
outtag, ccm_tag_len);
params[1] = OSSL_PARAM_construct_end();
if (!EVP_CIPHER_CTX_get_params(ctx, params))
goto err;
/* Output tag */
printf("Tag:\n");
BIO_dump_fp(stdout, outtag, ccm_tag_len);
ret = 1;
err:
if (!ret)
ERR_print_errors_fp(stderr);
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
int aes_ccm_decrypt(void)
{
int ret = 0;
EVP_CIPHER_CTX *ctx;
EVP_CIPHER *cipher = NULL;
int outlen, rv;
unsigned char outbuf[1024];
size_t ccm_nonce_len = sizeof(ccm_nonce);
OSSL_PARAM params[3] = {
OSSL_PARAM_END, OSSL_PARAM_END, OSSL_PARAM_END
};
printf("AES CCM Decrypt:\n");
printf("Ciphertext:\n");
BIO_dump_fp(stdout, ccm_ct, sizeof(ccm_ct));
if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
/* Fetch the cipher implementation */
if ((cipher = EVP_CIPHER_fetch(libctx, "AES-192-CCM", propq)) == NULL)
goto err;
/* Set nonce length if default 96 bits is not appropriate */
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_IVLEN,
&ccm_nonce_len);
/* Set tag length */
params[1] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG,
(unsigned char *)ccm_tag,
sizeof(ccm_tag));
/*
* Initialise decrypt operation with the cipher & mode,
* nonce length and expected tag parameters.
*/
if (!EVP_DecryptInit_ex2(ctx, cipher, NULL, NULL, params))
goto err;
/* Specify key and IV */
if (!EVP_DecryptInit_ex(ctx, NULL, NULL, ccm_key, ccm_nonce))
goto err;
/* Set ciphertext length: only needed if we have AAD */
if (!EVP_DecryptUpdate(ctx, NULL, &outlen, NULL, sizeof(ccm_ct)))
goto err;
/* Zero or one call to specify any AAD */
if (!EVP_DecryptUpdate(ctx, NULL, &outlen, ccm_adata, sizeof(ccm_adata)))
goto err;
/* Decrypt plaintext, verify tag: can only be called once */
rv = EVP_DecryptUpdate(ctx, outbuf, &outlen, ccm_ct, sizeof(ccm_ct));
/* Output decrypted block: if tag verify failed we get nothing */
if (rv > 0) {
printf("Tag verify successful!\nPlaintext:\n");
BIO_dump_fp(stdout, outbuf, outlen);
} else {
printf("Tag verify failed!\nPlaintext not available\n");
goto err;
}
ret = 1;
err:
if (!ret)
ERR_print_errors_fp(stderr);
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
int main(int argc, char **argv)
{
if (!aes_ccm_encrypt())
return EXIT_FAILURE;
if (!aes_ccm_decrypt())
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
| 7,280 | 29.464435 | 77 |
c
|
openssl
|
openssl-master/demos/cipher/aesgcm.c
|
/*
* Copyright 2012-2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Simple AES GCM authenticated encryption with additional data (AEAD)
* demonstration program.
*/
#include <stdio.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/core_names.h>
/* AES-GCM test data obtained from NIST public test vectors */
/* AES key */
static const unsigned char gcm_key[] = {
0xee, 0xbc, 0x1f, 0x57, 0x48, 0x7f, 0x51, 0x92, 0x1c, 0x04, 0x65, 0x66,
0x5f, 0x8a, 0xe6, 0xd1, 0x65, 0x8b, 0xb2, 0x6d, 0xe6, 0xf8, 0xa0, 0x69,
0xa3, 0x52, 0x02, 0x93, 0xa5, 0x72, 0x07, 0x8f
};
/* Unique initialisation vector */
static const unsigned char gcm_iv[] = {
0x99, 0xaa, 0x3e, 0x68, 0xed, 0x81, 0x73, 0xa0, 0xee, 0xd0, 0x66, 0x84
};
/* Example plaintext to encrypt */
static const unsigned char gcm_pt[] = {
0xf5, 0x6e, 0x87, 0x05, 0x5b, 0xc3, 0x2d, 0x0e, 0xeb, 0x31, 0xb2, 0xea,
0xcc, 0x2b, 0xf2, 0xa5
};
/*
* Example of Additional Authenticated Data (AAD), i.e. unencrypted data
* which can be authenticated using the generated Tag value.
*/
static const unsigned char gcm_aad[] = {
0x4d, 0x23, 0xc3, 0xce, 0xc3, 0x34, 0xb4, 0x9b, 0xdb, 0x37, 0x0c, 0x43,
0x7f, 0xec, 0x78, 0xde
};
/* Expected ciphertext value */
static const unsigned char gcm_ct[] = {
0xf7, 0x26, 0x44, 0x13, 0xa8, 0x4c, 0x0e, 0x7c, 0xd5, 0x36, 0x86, 0x7e,
0xb9, 0xf2, 0x17, 0x36
};
/* Expected AEAD Tag value */
static const unsigned char gcm_tag[] = {
0x67, 0xba, 0x05, 0x10, 0x26, 0x2a, 0xe4, 0x87, 0xd7, 0x37, 0xee, 0x62,
0x98, 0xf7, 0x7e, 0x0c
};
/*
* A library context and property query can be used to select & filter
* algorithm implementations. If they are NULL then the default library
* context and properties are used.
*/
OSSL_LIB_CTX *libctx = NULL;
const char *propq = NULL;
int aes_gcm_encrypt(void)
{
int ret = 0;
EVP_CIPHER_CTX *ctx;
EVP_CIPHER *cipher = NULL;
int outlen, tmplen;
size_t gcm_ivlen = sizeof(gcm_iv);
unsigned char outbuf[1024];
unsigned char outtag[16];
OSSL_PARAM params[2] = {
OSSL_PARAM_END, OSSL_PARAM_END
};
printf("AES GCM Encrypt:\n");
printf("Plaintext:\n");
BIO_dump_fp(stdout, gcm_pt, sizeof(gcm_pt));
/* Create a context for the encrypt operation */
if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
/* Fetch the cipher implementation */
if ((cipher = EVP_CIPHER_fetch(libctx, "AES-256-GCM", propq)) == NULL)
goto err;
/* Set IV length if default 96 bits is not appropriate */
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_IVLEN,
&gcm_ivlen);
/*
* Initialise an encrypt operation with the cipher/mode, key, IV and
* IV length parameter.
* For demonstration purposes the IV is being set here. In a compliant
* application the IV would be generated internally so the iv passed in
* would be NULL.
*/
if (!EVP_EncryptInit_ex2(ctx, cipher, gcm_key, gcm_iv, params))
goto err;
/* Zero or more calls to specify any AAD */
if (!EVP_EncryptUpdate(ctx, NULL, &outlen, gcm_aad, sizeof(gcm_aad)))
goto err;
/* Encrypt plaintext */
if (!EVP_EncryptUpdate(ctx, outbuf, &outlen, gcm_pt, sizeof(gcm_pt)))
goto err;
/* Output encrypted block */
printf("Ciphertext:\n");
BIO_dump_fp(stdout, outbuf, outlen);
/* Finalise: note get no output for GCM */
if (!EVP_EncryptFinal_ex(ctx, outbuf, &tmplen))
goto err;
/* Get tag */
params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG,
outtag, 16);
if (!EVP_CIPHER_CTX_get_params(ctx, params))
goto err;
/* Output tag */
printf("Tag:\n");
BIO_dump_fp(stdout, outtag, 16);
ret = 1;
err:
if (!ret)
ERR_print_errors_fp(stderr);
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
int aes_gcm_decrypt(void)
{
int ret = 0;
EVP_CIPHER_CTX *ctx;
EVP_CIPHER *cipher = NULL;
int outlen, rv;
size_t gcm_ivlen = sizeof(gcm_iv);
unsigned char outbuf[1024];
OSSL_PARAM params[2] = {
OSSL_PARAM_END, OSSL_PARAM_END
};
printf("AES GCM Decrypt:\n");
printf("Ciphertext:\n");
BIO_dump_fp(stdout, gcm_ct, sizeof(gcm_ct));
if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
/* Fetch the cipher implementation */
if ((cipher = EVP_CIPHER_fetch(libctx, "AES-256-GCM", propq)) == NULL)
goto err;
/* Set IV length if default 96 bits is not appropriate */
params[0] = OSSL_PARAM_construct_size_t(OSSL_CIPHER_PARAM_AEAD_IVLEN,
&gcm_ivlen);
/*
* Initialise an encrypt operation with the cipher/mode, key, IV and
* IV length parameter.
*/
if (!EVP_DecryptInit_ex2(ctx, cipher, gcm_key, gcm_iv, params))
goto err;
/* Zero or more calls to specify any AAD */
if (!EVP_DecryptUpdate(ctx, NULL, &outlen, gcm_aad, sizeof(gcm_aad)))
goto err;
/* Decrypt plaintext */
if (!EVP_DecryptUpdate(ctx, outbuf, &outlen, gcm_ct, sizeof(gcm_ct)))
goto err;
/* Output decrypted block */
printf("Plaintext:\n");
BIO_dump_fp(stdout, outbuf, outlen);
/* Set expected tag value. */
params[0] = OSSL_PARAM_construct_octet_string(OSSL_CIPHER_PARAM_AEAD_TAG,
(void*)gcm_tag, sizeof(gcm_tag));
if (!EVP_CIPHER_CTX_set_params(ctx, params))
goto err;
/* Finalise: note get no output for GCM */
rv = EVP_DecryptFinal_ex(ctx, outbuf, &outlen);
/*
* Print out return value. If this is not successful authentication
* failed and plaintext is not trustworthy.
*/
printf("Tag Verify %s\n", rv > 0 ? "Successful!" : "Failed!");
ret = 1;
err:
if (!ret)
ERR_print_errors_fp(stderr);
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
int main(int argc, char **argv)
{
if (!aes_gcm_encrypt())
return EXIT_FAILURE;
if (!aes_gcm_decrypt())
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
| 6,537 | 27.550218 | 83 |
c
|
openssl
|
openssl-master/demos/cipher/aeskeywrap.c
|
/*
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Simple aes wrap encryption demonstration program.
*/
#include <stdio.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/crypto.h>
#include <openssl/core_names.h>
/* aes key */
static const unsigned char wrap_key[] = {
0xee, 0xbc, 0x1f, 0x57, 0x48, 0x7f, 0x51, 0x92, 0x1c, 0x04, 0x65, 0x66,
0x5f, 0x8a, 0xe6, 0xd1, 0x65, 0x8b, 0xb2, 0x6d, 0xe6, 0xf8, 0xa0, 0x69,
0xa3, 0x52, 0x02, 0x93, 0xa5, 0x72, 0x07, 0x8f
};
/* Unique initialisation vector */
static const unsigned char wrap_iv[] = {
0x99, 0xaa, 0x3e, 0x68, 0xed, 0x81, 0x73, 0xa0, 0xee, 0xd0, 0x66, 0x84,
0x99, 0xaa, 0x3e, 0x68,
};
/* Example plaintext to encrypt */
static const unsigned char wrap_pt[] = {
0xad, 0x4f, 0xc9, 0xfc, 0x77, 0x69, 0xc9, 0xea, 0xfc, 0xdf, 0x00, 0xac,
0x34, 0xec, 0x40, 0xbc, 0x28, 0x3f, 0xa4, 0x5e, 0xd8, 0x99, 0xe4, 0x5d,
0x5e, 0x7a, 0xc4, 0xe6, 0xca, 0x7b, 0xa5, 0xb7,
};
/* Expected ciphertext value */
static const unsigned char wrap_ct[] = {
0x97, 0x99, 0x55, 0xca, 0xf6, 0x3e, 0x95, 0x54, 0x39, 0xd6, 0xaf, 0x63, 0xff, 0x2c, 0xe3, 0x96,
0xf7, 0x0d, 0x2c, 0x9c, 0xc7, 0x43, 0xc0, 0xb6, 0x31, 0x43, 0xb9, 0x20, 0xac, 0x6b, 0xd3, 0x67,
0xad, 0x01, 0xaf, 0xa7, 0x32, 0x74, 0x26, 0x92,
};
/*
* A library context and property query can be used to select & filter
* algorithm implementations. If they are NULL then the default library
* context and properties are used.
*/
OSSL_LIB_CTX *libctx = NULL;
const char *propq = NULL;
int aes_wrap_encrypt(void)
{
int ret = 0;
EVP_CIPHER_CTX *ctx;
EVP_CIPHER *cipher = NULL;
int outlen, tmplen;
unsigned char outbuf[1024];
printf("aes wrap Encrypt:\n");
printf("Plaintext:\n");
BIO_dump_fp(stdout, wrap_pt, sizeof(wrap_pt));
/* Create a context for the encrypt operation */
if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
/* Fetch the cipher implementation */
if ((cipher = EVP_CIPHER_fetch(libctx, "AES-256-WRAP", propq)) == NULL)
goto err;
/*
* Initialise an encrypt operation with the cipher/mode, key and IV.
* We are not setting any custom params so let params be just NULL.
*/
if (!EVP_EncryptInit_ex2(ctx, cipher, wrap_key, wrap_iv, /* params */ NULL))
goto err;
/* Encrypt plaintext */
if (!EVP_EncryptUpdate(ctx, outbuf, &outlen, wrap_pt, sizeof(wrap_pt)))
goto err;
/* Finalise: there can be some additional output from padding */
if (!EVP_EncryptFinal_ex(ctx, outbuf + outlen, &tmplen))
goto err;
outlen += tmplen;
/* Output encrypted block */
printf("Ciphertext (outlen:%d):\n", outlen);
BIO_dump_fp(stdout, outbuf, outlen);
if (sizeof(wrap_ct) == outlen && !CRYPTO_memcmp(outbuf, wrap_ct, outlen))
printf("Final ciphertext matches expected ciphertext\n");
else
printf("Final ciphertext differs from expected ciphertext\n");
ret = 1;
err:
if (!ret)
ERR_print_errors_fp(stderr);
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
int aes_wrap_decrypt(void)
{
int ret = 0;
EVP_CIPHER_CTX *ctx;
EVP_CIPHER *cipher = NULL;
int outlen, tmplen;
unsigned char outbuf[1024];
printf("aes wrap Decrypt:\n");
printf("Ciphertext:\n");
BIO_dump_fp(stdout, wrap_ct, sizeof(wrap_ct));
if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW);
/* Fetch the cipher implementation */
if ((cipher = EVP_CIPHER_fetch(libctx, "aes-256-wrap", propq)) == NULL)
goto err;
/*
* Initialise an encrypt operation with the cipher/mode, key and IV.
* We are not setting any custom params so let params be just NULL.
*/
if (!EVP_DecryptInit_ex2(ctx, cipher, wrap_key, wrap_iv, /* params */ NULL))
goto err;
/* Decrypt plaintext */
if (!EVP_DecryptUpdate(ctx, outbuf, &outlen, wrap_ct, sizeof(wrap_ct)))
goto err;
/* Finalise: there can be some additional output from padding */
if (!EVP_DecryptFinal_ex(ctx, outbuf + outlen, &tmplen))
goto err;
outlen += tmplen;
/* Output decrypted block */
printf("Plaintext (outlen:%d):\n", outlen);
BIO_dump_fp(stdout, outbuf, outlen);
if (sizeof(wrap_pt) == outlen && !CRYPTO_memcmp(outbuf, wrap_pt, outlen))
printf("Final plaintext matches original plaintext\n");
else
printf("Final plaintext differs from original plaintext\n");
ret = 1;
err:
if (!ret)
ERR_print_errors_fp(stderr);
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
int main(int argc, char **argv)
{
if (!aes_wrap_encrypt())
return EXIT_FAILURE;
if (!aes_wrap_decrypt())
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
| 5,269 | 28.116022 | 99 |
c
|
openssl
|
openssl-master/demos/cipher/ariacbc.c
|
/*
* Copyright 2012-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Simple ARIA CBC encryption demonstration program.
*/
#include <stdio.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#include <openssl/evp.h>
#include <openssl/crypto.h>
#include <openssl/core_names.h>
/* ARIA key */
static const unsigned char cbc_key[] = {
0xee, 0xbc, 0x1f, 0x57, 0x48, 0x7f, 0x51, 0x92, 0x1c, 0x04, 0x65, 0x66,
0x5f, 0x8a, 0xe6, 0xd1, 0x65, 0x8b, 0xb2, 0x6d, 0xe6, 0xf8, 0xa0, 0x69,
0xa3, 0x52, 0x02, 0x93, 0xa5, 0x72, 0x07, 0x8f
};
/* Unique initialisation vector */
static const unsigned char cbc_iv[] = {
0x99, 0xaa, 0x3e, 0x68, 0xed, 0x81, 0x73, 0xa0, 0xee, 0xd0, 0x66, 0x84,
0x99, 0xaa, 0x3e, 0x68,
};
/* Example plaintext to encrypt */
static const unsigned char cbc_pt[] = {
0xf5, 0x6e, 0x87, 0x05, 0x5b, 0xc3, 0x2d, 0x0e, 0xeb, 0x31, 0xb2, 0xea,
0xcc, 0x2b, 0xf2, 0xa5
};
/* Expected ciphertext value */
static const unsigned char cbc_ct[] = {
0x9a, 0x44, 0xe6, 0x85, 0x94, 0x26, 0xff, 0x30, 0x03, 0xd3, 0x7e, 0xc6,
0xb5, 0x4a, 0x09, 0x66, 0x39, 0x28, 0xf3, 0x67, 0x14, 0xbc, 0xe8, 0xe2,
0xcf, 0x31, 0xb8, 0x60, 0x42, 0x72, 0x6d, 0xc8
};
/*
* A library context and property query can be used to select & filter
* algorithm implementations. If they are NULL then the default library
* context and properties are used.
*/
OSSL_LIB_CTX *libctx = NULL;
const char *propq = NULL;
int aria_cbc_encrypt(void)
{
int ret = 0;
EVP_CIPHER_CTX *ctx;
EVP_CIPHER *cipher = NULL;
int outlen, tmplen;
size_t cbc_ivlen = sizeof(cbc_iv);
unsigned char outbuf[1024];
unsigned char outtag[16];
printf("ARIA CBC Encrypt:\n");
printf("Plaintext:\n");
BIO_dump_fp(stdout, cbc_pt, sizeof(cbc_pt));
/* Create a context for the encrypt operation */
if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
/* Fetch the cipher implementation */
if ((cipher = EVP_CIPHER_fetch(libctx, "ARIA-256-CBC", propq)) == NULL)
goto err;
/*
* Initialise an encrypt operation with the cipher/mode, key and IV.
* We are not setting any custom params so let params be just NULL.
*/
if (!EVP_EncryptInit_ex2(ctx, cipher, cbc_key, cbc_iv, /* params */ NULL))
goto err;
/* Encrypt plaintext */
if (!EVP_EncryptUpdate(ctx, outbuf, &outlen, cbc_pt, sizeof(cbc_pt)))
goto err;
/* Finalise: there can be some additional output from padding */
if (!EVP_EncryptFinal_ex(ctx, outbuf + outlen, &tmplen))
goto err;
outlen += tmplen;
/* Output encrypted block */
printf("Ciphertext (outlen:%d):\n", outlen);
BIO_dump_fp(stdout, outbuf, outlen);
if (sizeof(cbc_ct) == outlen && !CRYPTO_memcmp(outbuf, cbc_ct, outlen))
printf("Final ciphertext matches expected ciphertext\n");
else
printf("Final ciphertext differs from expected ciphertext\n");
ret = 1;
err:
if (!ret)
ERR_print_errors_fp(stderr);
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
int aria_cbc_decrypt(void)
{
int ret = 0;
EVP_CIPHER_CTX *ctx;
EVP_CIPHER *cipher = NULL;
int outlen, tmplen, rv;
size_t cbc_ivlen = sizeof(cbc_iv);
unsigned char outbuf[1024];
printf("ARIA CBC Decrypt:\n");
printf("Ciphertext:\n");
BIO_dump_fp(stdout, cbc_ct, sizeof(cbc_ct));
if ((ctx = EVP_CIPHER_CTX_new()) == NULL)
goto err;
/* Fetch the cipher implementation */
if ((cipher = EVP_CIPHER_fetch(libctx, "ARIA-256-CBC", propq)) == NULL)
goto err;
/*
* Initialise an encrypt operation with the cipher/mode, key and IV.
* We are not setting any custom params so let params be just NULL.
*/
if (!EVP_DecryptInit_ex2(ctx, cipher, cbc_key, cbc_iv, /* params */ NULL))
goto err;
/* Decrypt plaintext */
if (!EVP_DecryptUpdate(ctx, outbuf, &outlen, cbc_ct, sizeof(cbc_ct)))
goto err;
/* Finalise: there can be some additional output from padding */
if (!EVP_DecryptFinal_ex(ctx, outbuf + outlen, &tmplen))
goto err;
outlen += tmplen;
/* Output decrypted block */
printf("Plaintext (outlen:%d):\n", outlen);
BIO_dump_fp(stdout, outbuf, outlen);
if (sizeof(cbc_pt) == outlen && !CRYPTO_memcmp(outbuf, cbc_pt, outlen))
printf("Final plaintext matches original plaintext\n");
else
printf("Final plaintext differs from original plaintext\n");
ret = 1;
err:
if (!ret)
ERR_print_errors_fp(stderr);
EVP_CIPHER_free(cipher);
EVP_CIPHER_CTX_free(ctx);
return ret;
}
int main(int argc, char **argv)
{
if (!aria_cbc_encrypt())
return EXIT_FAILURE;
if (!aria_cbc_decrypt())
return EXIT_FAILURE;
return EXIT_SUCCESS;
}
| 5,082 | 27.396648 | 78 |
c
|
openssl
|
openssl-master/demos/cms/cms_comp.c
|
/*
* Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* Simple S/MIME compress example */
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>
int main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL;
CMS_ContentInfo *cms = NULL;
int ret = EXIT_FAILURE;
/*
* On OpenSSL 1.0.0+ only:
* for streaming set CMS_STREAM
*/
int flags = CMS_STREAM;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Open content being compressed */
in = BIO_new_file("comp.txt", "r");
if (!in)
goto err;
/* compress content */
cms = CMS_compress(in, NID_zlib_compression, flags);
if (!cms)
goto err;
out = BIO_new_file("smcomp.txt", "w");
if (!out)
goto err;
/* Write out S/MIME message */
if (!SMIME_write_CMS(out, cms, in, flags))
goto err;
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS) {
fprintf(stderr, "Error Compressing Data\n");
ERR_print_errors_fp(stderr);
}
CMS_ContentInfo_free(cms);
BIO_free(in);
BIO_free(out);
return ret;
}
| 1,411 | 20.723077 | 74 |
c
|
openssl
|
openssl-master/demos/cms/cms_ddec.c
|
/*
* Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* S/MIME detached data decrypt example: rarely done but should the need
* arise this is an example....
*/
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>
int main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL, *tbio = NULL, *dcont = NULL;
X509 *rcert = NULL;
EVP_PKEY *rkey = NULL;
CMS_ContentInfo *cms = NULL;
int ret = EXIT_FAILURE;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Read in recipient certificate and private key */
tbio = BIO_new_file("signer.pem", "r");
if (!tbio)
goto err;
rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
BIO_reset(tbio);
rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
if (!rcert || !rkey)
goto err;
/* Open PEM file containing enveloped data */
in = BIO_new_file("smencr.pem", "r");
if (!in)
goto err;
/* Parse PEM content */
cms = PEM_read_bio_CMS(in, NULL, 0, NULL);
if (!cms)
goto err;
/* Open file containing detached content */
dcont = BIO_new_file("smencr.out", "rb");
if (!in)
goto err;
out = BIO_new_file("encrout.txt", "w");
if (!out)
goto err;
/* Decrypt S/MIME message */
if (!CMS_decrypt(cms, rkey, rcert, dcont, out, 0))
goto err;
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS) {
fprintf(stderr, "Error Decrypting Data\n");
ERR_print_errors_fp(stderr);
}
CMS_ContentInfo_free(cms);
X509_free(rcert);
EVP_PKEY_free(rkey);
BIO_free(in);
BIO_free(out);
BIO_free(tbio);
BIO_free(dcont);
return ret;
}
| 1,991 | 21.382022 | 74 |
c
|
openssl
|
openssl-master/demos/cms/cms_dec.c
|
/*
* Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* Simple S/MIME decryption example */
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>
int main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL, *tbio = NULL;
X509 *rcert = NULL;
EVP_PKEY *rkey = NULL;
CMS_ContentInfo *cms = NULL;
int ret = EXIT_FAILURE;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Read in recipient certificate and private key */
tbio = BIO_new_file("signer.pem", "r");
if (!tbio)
goto err;
rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
BIO_reset(tbio);
rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
if (!rcert || !rkey)
goto err;
/* Open S/MIME message to decrypt */
in = BIO_new_file("smencr.txt", "r");
if (!in)
goto err;
/* Parse message */
cms = SMIME_read_CMS(in, NULL);
if (!cms)
goto err;
out = BIO_new_file("decout.txt", "w");
if (!out)
goto err;
/* Decrypt S/MIME message */
if (!CMS_decrypt(cms, rkey, rcert, NULL, out, 0))
goto err;
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS) {
fprintf(stderr, "Error Decrypting Data\n");
ERR_print_errors_fp(stderr);
}
CMS_ContentInfo_free(cms);
X509_free(rcert);
EVP_PKEY_free(rkey);
BIO_free(in);
BIO_free(out);
BIO_free(tbio);
return ret;
}
| 1,728 | 21.166667 | 74 |
c
|
openssl
|
openssl-master/demos/cms/cms_denc.c
|
/*
* Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* S/MIME detached data encrypt example: rarely done but should the need
* arise this is an example....
*/
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>
int main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL, *tbio = NULL, *dout = NULL;
X509 *rcert = NULL;
STACK_OF(X509) *recips = NULL;
CMS_ContentInfo *cms = NULL;
int ret = EXIT_FAILURE;
int flags = CMS_STREAM | CMS_DETACHED;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Read in recipient certificate */
tbio = BIO_new_file("signer.pem", "r");
if (!tbio)
goto err;
rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
if (!rcert)
goto err;
/* Create recipient STACK and add recipient cert to it */
recips = sk_X509_new_null();
if (!recips || !sk_X509_push(recips, rcert))
goto err;
/*
* OSSL_STACK_OF_X509_free() free up recipient STACK and its contents
* so set rcert to NULL so it isn't freed up twice.
*/
rcert = NULL;
/* Open content being encrypted */
in = BIO_new_file("encr.txt", "r");
dout = BIO_new_file("smencr.out", "wb");
if (!in)
goto err;
/* encrypt content */
cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
if (!cms)
goto err;
out = BIO_new_file("smencr.pem", "w");
if (!out)
goto err;
if (!CMS_final(cms, in, dout, flags))
goto err;
/* Write out CMS structure without content */
if (!PEM_write_bio_CMS(out, cms))
goto err;
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS) {
fprintf(stderr, "Error Encrypting Data\n");
ERR_print_errors_fp(stderr);
}
CMS_ContentInfo_free(cms);
X509_free(rcert);
OSSL_STACK_OF_X509_free(recips);
BIO_free(in);
BIO_free(out);
BIO_free(dout);
BIO_free(tbio);
return ret;
}
| 2,253 | 22.479167 | 74 |
c
|
openssl
|
openssl-master/demos/cms/cms_enc.c
|
/*
* Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* Simple S/MIME encrypt example */
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>
int main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL, *tbio = NULL;
X509 *rcert = NULL;
STACK_OF(X509) *recips = NULL;
CMS_ContentInfo *cms = NULL;
int ret = EXIT_FAILURE;
/*
* On OpenSSL 1.0.0 and later only:
* for streaming set CMS_STREAM
*/
int flags = CMS_STREAM;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Read in recipient certificate */
tbio = BIO_new_file("signer.pem", "r");
if (!tbio)
goto err;
rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
if (!rcert)
goto err;
/* Create recipient STACK and add recipient cert to it */
recips = sk_X509_new_null();
if (!recips || !sk_X509_push(recips, rcert))
goto err;
/*
* OSSL_STACK_OF_X509_free() will free up recipient STACK and its contents
* so set rcert to NULL so it isn't freed up twice.
*/
rcert = NULL;
/* Open content being encrypted */
in = BIO_new_file("encr.txt", "r");
if (!in)
goto err;
/* encrypt content */
cms = CMS_encrypt(recips, in, EVP_des_ede3_cbc(), flags);
if (!cms)
goto err;
out = BIO_new_file("smencr.txt", "w");
if (!out)
goto err;
/* Write out S/MIME message */
if (!SMIME_write_CMS(out, cms, in, flags))
goto err;
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS) {
fprintf(stderr, "Error Encrypting Data\n");
ERR_print_errors_fp(stderr);
}
CMS_ContentInfo_free(cms);
X509_free(rcert);
OSSL_STACK_OF_X509_free(recips);
BIO_free(in);
BIO_free(out);
BIO_free(tbio);
return ret;
}
| 2,111 | 22.208791 | 78 |
c
|
openssl
|
openssl-master/demos/cms/cms_sign.c
|
/*
* Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* Simple S/MIME signing example */
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>
int main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL, *tbio = NULL;
X509 *scert = NULL;
EVP_PKEY *skey = NULL;
CMS_ContentInfo *cms = NULL;
int ret = EXIT_FAILURE;
/*
* For simple S/MIME signing use CMS_DETACHED. On OpenSSL 1.0.0 only: for
* streaming detached set CMS_DETACHED|CMS_STREAM for streaming
* non-detached set CMS_STREAM
*/
int flags = CMS_DETACHED | CMS_STREAM;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Read in signer certificate and private key */
tbio = BIO_new_file("signer.pem", "r");
if (!tbio)
goto err;
scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
BIO_reset(tbio);
skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
if (!scert || !skey)
goto err;
/* Open content being signed */
in = BIO_new_file("sign.txt", "r");
if (!in)
goto err;
/* Sign content */
cms = CMS_sign(scert, skey, NULL, in, flags);
if (!cms)
goto err;
out = BIO_new_file("smout.txt", "w");
if (!out)
goto err;
if (!(flags & CMS_STREAM))
BIO_reset(in);
/* Write out S/MIME message */
if (!SMIME_write_CMS(out, cms, in, flags))
goto err;
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS) {
fprintf(stderr, "Error Signing Data\n");
ERR_print_errors_fp(stderr);
}
CMS_ContentInfo_free(cms);
X509_free(scert);
EVP_PKEY_free(skey);
BIO_free(in);
BIO_free(out);
BIO_free(tbio);
return ret;
}
| 2,013 | 22.149425 | 77 |
c
|
openssl
|
openssl-master/demos/cms/cms_sign2.c
|
/*
* Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* S/MIME signing example: 2 signers */
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>
int main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL, *tbio = NULL;
X509 *scert = NULL, *scert2 = NULL;
EVP_PKEY *skey = NULL, *skey2 = NULL;
CMS_ContentInfo *cms = NULL;
int ret = EXIT_FAILURE;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
tbio = BIO_new_file("signer.pem", "r");
if (!tbio)
goto err;
scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
BIO_reset(tbio);
skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
BIO_free(tbio);
tbio = BIO_new_file("signer2.pem", "r");
if (!tbio)
goto err;
scert2 = PEM_read_bio_X509(tbio, NULL, 0, NULL);
BIO_reset(tbio);
skey2 = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);
if (!scert2 || !skey2)
goto err;
in = BIO_new_file("sign.txt", "r");
if (!in)
goto err;
cms = CMS_sign(NULL, NULL, NULL, in, CMS_STREAM | CMS_PARTIAL);
if (!cms)
goto err;
/* Add each signer in turn */
if (!CMS_add1_signer(cms, scert, skey, NULL, 0))
goto err;
if (!CMS_add1_signer(cms, scert2, skey2, NULL, 0))
goto err;
out = BIO_new_file("smout.txt", "w");
if (!out)
goto err;
/* NB: content included and finalized by SMIME_write_CMS */
if (!SMIME_write_CMS(out, cms, in, CMS_STREAM))
goto err;
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS) {
fprintf(stderr, "Error Signing Data\n");
ERR_print_errors_fp(stderr);
}
CMS_ContentInfo_free(cms);
X509_free(scert);
EVP_PKEY_free(skey);
X509_free(scert2);
EVP_PKEY_free(skey2);
BIO_free(in);
BIO_free(out);
BIO_free(tbio);
return ret;
}
| 2,161 | 21.28866 | 74 |
c
|
openssl
|
openssl-master/demos/cms/cms_uncomp.c
|
/*
* Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* Simple S/MIME uncompression example */
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>
int main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL;
CMS_ContentInfo *cms = NULL;
int ret = EXIT_FAILURE;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Open compressed content */
in = BIO_new_file("smcomp.txt", "r");
if (!in)
goto err;
/* Sign content */
cms = SMIME_read_CMS(in, NULL);
if (!cms)
goto err;
out = BIO_new_file("smuncomp.txt", "w");
if (!out)
goto err;
/* Uncompress S/MIME message */
if (!CMS_uncompress(cms, out, NULL, 0))
goto err;
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS) {
fprintf(stderr, "Error Uncompressing Data\n");
ERR_print_errors_fp(stderr);
}
CMS_ContentInfo_free(cms);
BIO_free(in);
BIO_free(out);
return ret;
}
| 1,276 | 21.403509 | 74 |
c
|
openssl
|
openssl-master/demos/cms/cms_ver.c
|
/*
* Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* Simple S/MIME verification example */
#include <openssl/pem.h>
#include <openssl/cms.h>
#include <openssl/err.h>
int main(int argc, char **argv)
{
BIO *in = NULL, *out = NULL, *tbio = NULL, *cont = NULL;
X509_STORE *st = NULL;
X509 *cacert = NULL;
CMS_ContentInfo *cms = NULL;
int ret = EXIT_FAILURE;
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
/* Set up trusted CA certificate store */
st = X509_STORE_new();
if (st == NULL)
goto err;
/* Read in CA certificate */
tbio = BIO_new_file("cacert.pem", "r");
if (tbio == NULL)
goto err;
cacert = PEM_read_bio_X509(tbio, NULL, 0, NULL);
if (cacert == NULL)
goto err;
if (!X509_STORE_add_cert(st, cacert))
goto err;
/* Open message being verified */
in = BIO_new_file("smout.txt", "r");
if (in == NULL)
goto err;
/* parse message */
cms = SMIME_read_CMS(in, &cont);
if (cms == NULL)
goto err;
/* File to output verified content to */
out = BIO_new_file("smver.txt", "w");
if (out == NULL)
goto err;
if (!CMS_verify(cms, NULL, st, cont, out, 0)) {
fprintf(stderr, "Verification Failure\n");
goto err;
}
fprintf(stderr, "Verification Successful\n");
ret = EXIT_SUCCESS;
err:
if (ret != EXIT_SUCCESS) {
fprintf(stderr, "Error Verifying Data\n");
ERR_print_errors_fp(stderr);
}
X509_STORE_free(st);
CMS_ContentInfo_free(cms);
X509_free(cacert);
BIO_free(in);
BIO_free(out);
BIO_free(tbio);
return ret;
}
| 1,957 | 21.767442 | 74 |
c
|
openssl
|
openssl-master/demos/digest/EVP_MD_demo.c
|
/*-
* Copyright 2021-2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* Example of using EVP_MD_fetch and EVP_Digest* methods to calculate
* a digest of static buffers
*/
#include <string.h>
#include <stdio.h>
#include <openssl/err.h>
#include <openssl/evp.h>
/*-
* This demonstration will show how to digest data using
* the soliloqy from Hamlet scene 1 act 3
* The soliloqy is split into two parts to demonstrate using EVP_DigestUpdate
* more than once.
*/
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 ſ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"
;
const char * hamlet_2 =
"The insolence of Office, and the spurns\n"
"That patient merit of the'unworthy takes,\n"
"When he himself might his Quietas make\n"
"With a bare bodkin? Who would fardels bear,\n"
"To grunt and sweat under a weary life,\n"
"But that the dread of something after death,\n"
"The undiscovered country, from whose bourn\n"
"No traveller returns, puzzles the will,\n"
"And makes us rather bear those ills we have,\n"
"Then fly to others we know not of?\n"
"Thus conscience does make cowards of us all,\n"
"And thus the native hue of Resolution\n"
"Is sickled o'er with the pale cast of Thought,\n"
"And enterprises of great pith and moment,\n"
"With this regard their currents turn awry,\n"
"And lose the name of Action. Soft you now,\n"
"The fair Ophelia? Nymph in thy Orisons\n"
"Be all my sins remember'd.\n"
;
/* The known value of the SHA3-512 digest of the above soliloqy */
const unsigned char known_answer[] = {
0xbb, 0x69, 0xf8, 0x09, 0x9c, 0x2e, 0x00, 0x3d,
0xa4, 0x29, 0x5f, 0x59, 0x4b, 0x89, 0xe4, 0xd9,
0xdb, 0xa2, 0xe5, 0xaf, 0xa5, 0x87, 0x73, 0x9d,
0x83, 0x72, 0xcf, 0xea, 0x84, 0x66, 0xc1, 0xf9,
0xc9, 0x78, 0xef, 0xba, 0x3d, 0xe9, 0xc1, 0xff,
0xa3, 0x75, 0xc7, 0x58, 0x74, 0x8e, 0x9c, 0x1d,
0x14, 0xd9, 0xdd, 0xd1, 0xfd, 0x24, 0x30, 0xd6,
0x81, 0xca, 0x8f, 0x78, 0x29, 0x19, 0x9a, 0xfe,
};
int demonstrate_digest(void)
{
OSSL_LIB_CTX *library_context;
int ret = 0;
const char *option_properties = NULL;
EVP_MD *message_digest = NULL;
EVP_MD_CTX *digest_context = NULL;
unsigned int digest_length;
unsigned char *digest_value = NULL;
int j;
library_context = OSSL_LIB_CTX_new();
if (library_context == NULL) {
fprintf(stderr, "OSSL_LIB_CTX_new() returned NULL\n");
goto cleanup;
}
/*
* Fetch a message digest by name
* The algorithm name is case insensitive.
* See providers(7) for details about algorithm fetching
*/
message_digest = EVP_MD_fetch(library_context,
"SHA3-512", option_properties);
if (message_digest == NULL) {
fprintf(stderr, "EVP_MD_fetch could not find SHA3-512.");
goto cleanup;
}
/* Determine the length of the fetched digest type */
digest_length = EVP_MD_get_size(message_digest);
if (digest_length <= 0) {
fprintf(stderr, "EVP_MD_get_size returned invalid size.\n");
goto cleanup;
}
digest_value = OPENSSL_malloc(digest_length);
if (digest_value == NULL) {
fprintf(stderr, "No memory.\n");
goto cleanup;
}
/*
* Make a message digest context to hold temporary state
* during digest creation
*/
digest_context = EVP_MD_CTX_new();
if (digest_context == NULL) {
fprintf(stderr, "EVP_MD_CTX_new failed.\n");
goto cleanup;
}
/*
* Initialize the message digest context to use the fetched
* digest provider
*/
if (EVP_DigestInit(digest_context, message_digest) != 1) {
fprintf(stderr, "EVP_DigestInit failed.\n");
goto cleanup;
}
/* Digest parts one and two of the soliloqy */
if (EVP_DigestUpdate(digest_context, hamlet_1, strlen(hamlet_1)) != 1) {
fprintf(stderr, "EVP_DigestUpdate(hamlet_1) failed.\n");
goto cleanup;
}
if (EVP_DigestUpdate(digest_context, hamlet_2, strlen(hamlet_2)) != 1) {
fprintf(stderr, "EVP_DigestUpdate(hamlet_2) failed.\n");
goto cleanup;
}
if (EVP_DigestFinal(digest_context, digest_value, &digest_length) != 1) {
fprintf(stderr, "EVP_DigestFinal() failed.\n");
goto cleanup;
}
for (j=0; j<digest_length; j++) {
fprintf(stdout, "%02x", digest_value[j]);
}
fprintf(stdout, "\n");
/* Check digest_value against the known answer */
if ((size_t)digest_length != sizeof(known_answer)) {
fprintf(stdout, "Digest length(%d) not equal to known answer length(%lu).\n",
digest_length, sizeof(known_answer));
} else if (memcmp(digest_value, known_answer, digest_length) != 0) {
for (j=0; j<sizeof(known_answer); j++) {
fprintf(stdout, "%02x", known_answer[j] );
}
fprintf(stdout, "\nDigest does not match known answer\n");
} else {
fprintf(stdout, "Digest computed properly.\n");
ret = 1;
}
cleanup:
if (ret != 1)
ERR_print_errors_fp(stderr);
/* OpenSSL free functions will ignore NULL arguments */
EVP_MD_CTX_free(digest_context);
OPENSSL_free(digest_value);
EVP_MD_free(message_digest);
OSSL_LIB_CTX_free(library_context);
return ret;
}
int main(void)
{
return demonstrate_digest() ? EXIT_SUCCESS : EXIT_FAILURE;
}
| 6,483 | 34.431694 | 85 |
c
|
openssl
|
openssl-master/demos/digest/EVP_MD_xof.c
|
/*-
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <string.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/core_names.h>
/*
* Example of using an extendable-output hash function (XOF). A XOF is a hash
* function with configurable output length and which can generate an
* arbitrarily large output.
*
* This example uses SHAKE256, an extendable output variant of SHA3 (Keccak).
*
* To generate different output lengths, you can pass a single integer argument
* on the command line, which is the output size in bytes. By default, a 20-byte
* output is generated and (for this length only) a known answer test is
* performed.
*/
/* Our input to the XOF hash function. */
const char message[] = "This is a test message.";
/* Expected output when an output length of 20 bytes is used. */
static const char known_answer[] = {
0x52, 0x97, 0x93, 0x78, 0x27, 0x58, 0x7d, 0x62,
0x8b, 0x00, 0x25, 0xb5, 0xec, 0x39, 0x5e, 0x2d,
0x7f, 0x3e, 0xd4, 0x19
};
/*
* A property query used for selecting the SHAKE256 implementation.
*/
static const char *propq = NULL;
int main(int argc, char **argv)
{
int ret = EXIT_FAILURE;
OSSL_LIB_CTX *libctx = NULL;
EVP_MD *md = NULL;
EVP_MD_CTX *ctx = NULL;
unsigned int digest_len = 20;
int digest_len_i;
unsigned char *digest = NULL;
/* Allow digest length to be changed for demonstration purposes. */
if (argc > 1) {
digest_len_i = atoi(argv[1]);
if (digest_len_i <= 0) {
fprintf(stderr, "Specify a non-negative digest length\n");
goto end;
}
digest_len = (unsigned int)digest_len_i;
}
/*
* Retrieve desired algorithm. This must be a hash algorithm which supports
* XOF.
*/
md = EVP_MD_fetch(libctx, "SHAKE256", propq);
if (md == NULL) {
fprintf(stderr, "Failed to retrieve SHAKE256 algorithm\n");
goto end;
}
/* Create context. */
ctx = EVP_MD_CTX_new();
if (ctx == NULL) {
fprintf(stderr, "Failed to create digest context\n");
goto end;
}
/* Initialize digest context. */
if (EVP_DigestInit(ctx, md) == 0) {
fprintf(stderr, "Failed to initialize digest\n");
goto end;
}
/*
* Feed our message into the digest function.
* This may be called multiple times.
*/
if (EVP_DigestUpdate(ctx, message, sizeof(message)) == 0) {
fprintf(stderr, "Failed to hash input message\n");
goto end;
}
/* Allocate enough memory for our digest length. */
digest = OPENSSL_malloc(digest_len);
if (digest == NULL) {
fprintf(stderr, "Failed to allocate memory for digest\n");
goto end;
}
/* Get computed digest. The digest will be of whatever length we specify. */
if (EVP_DigestFinalXOF(ctx, digest, digest_len) == 0) {
fprintf(stderr, "Failed to finalize hash\n");
goto end;
}
printf("Output digest:\n");
BIO_dump_indent_fp(stdout, digest, digest_len, 2);
/* If digest length is 20 bytes, check it matches our known answer. */
if (digest_len == 20) {
/*
* Always use a constant-time function such as CRYPTO_memcmp
* when comparing cryptographic values. Do not use memcmp(3).
*/
if (CRYPTO_memcmp(digest, known_answer, sizeof(known_answer)) != 0) {
fprintf(stderr, "Output does not match expected result\n");
goto end;
}
}
ret = EXIT_SUCCESS;
end:
OPENSSL_free(digest);
EVP_MD_CTX_free(ctx);
EVP_MD_free(md);
OSSL_LIB_CTX_free(libctx);
return ret;
}
| 3,944 | 28.661654 | 80 |
c
|
openssl
|
openssl-master/demos/encode/ec_encode.c
|
/*-
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/decoder.h>
#include <openssl/encoder.h>
#include <openssl/evp.h>
/*
* Example showing the encoding and decoding of EC public and private keys. A
* PEM-encoded EC key is read in from stdin, decoded, and then re-encoded and
* output for demonstration purposes. Both public and private keys are accepted.
*
* This can be used to load EC keys from a file or save EC keys to a file.
*/
/* A property query used for selecting algorithm implementations. */
static const char *propq = NULL;
/*
* Load a PEM-encoded EC key from a file, optionally decrypting it with a
* supplied passphrase.
*/
static EVP_PKEY *load_key(OSSL_LIB_CTX *libctx, FILE *f, const char *passphrase)
{
int ret = 0;
EVP_PKEY *pkey = NULL;
OSSL_DECODER_CTX *dctx = NULL;
int selection = 0;
/*
* Create PEM decoder context expecting an EC key.
*
* For raw (non-PEM-encoded) keys, change "PEM" to "DER".
*
* The selection argument here specifies whether we are willing to accept a
* public key, private key, or either. If it is set to zero, either will be
* accepted. If set to EVP_PKEY_KEYPAIR, a private key will be required, and
* if set to EVP_PKEY_PUBLIC_KEY, a public key will be required.
*/
dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "PEM", NULL, "EC",
selection,
libctx, propq);
if (dctx == NULL) {
fprintf(stderr, "OSSL_DECODER_CTX_new_for_pkey() failed\n");
goto cleanup;
}
/*
* Set passphrase if provided; needed to decrypt encrypted PEM files.
* If the input is not encrypted, any passphrase provided is ignored.
*
* Alternative methods for specifying passphrases exist, such as a callback
* (see OSSL_DECODER_CTX_set_passphrase_cb(3)), which may be more useful for
* interactive applications which do not know if a passphrase should be
* prompted for in advance, or for GUI applications.
*/
if (passphrase != NULL) {
if (OSSL_DECODER_CTX_set_passphrase(dctx,
(const unsigned char *)passphrase,
strlen(passphrase)) == 0) {
fprintf(stderr, "OSSL_DECODER_CTX_set_passphrase() failed\n");
goto cleanup;
}
}
/* Do the decode, reading from file. */
if (OSSL_DECODER_from_fp(dctx, f) == 0) {
fprintf(stderr, "OSSL_DECODER_from_fp() failed\n");
goto cleanup;
}
ret = 1;
cleanup:
OSSL_DECODER_CTX_free(dctx);
/*
* pkey is created by OSSL_DECODER_CTX_new_for_pkey, but we
* might fail subsequently, so ensure it's properly freed
* in this case.
*/
if (ret == 0) {
EVP_PKEY_free(pkey);
pkey = NULL;
}
return pkey;
}
/*
* Store a EC public or private key to a file using PEM encoding.
*
* If a passphrase is supplied, the file is encrypted, otherwise
* it is unencrypted.
*/
static int store_key(EVP_PKEY *pkey, FILE *f, const char *passphrase)
{
int ret = 0;
int selection;
OSSL_ENCODER_CTX *ectx = NULL;
/*
* Create a PEM encoder context.
*
* For raw (non-PEM-encoded) output, change "PEM" to "DER".
*
* The selection argument controls whether the private key is exported
* (EVP_PKEY_KEYPAIR), or only the public key (EVP_PKEY_PUBLIC_KEY). The
* former will fail if we only have a public key.
*
* Note that unlike the decode API, you cannot specify zero here.
*
* Purely for the sake of demonstration, here we choose to export the whole
* key if a passphrase is provided and the public key otherwise.
*/
selection = (passphrase != NULL)
? EVP_PKEY_KEYPAIR
: EVP_PKEY_PUBLIC_KEY;
ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, "PEM", NULL, propq);
if (ectx == NULL) {
fprintf(stderr, "OSSL_ENCODER_CTX_new_for_pkey() failed\n");
goto cleanup;
}
/*
* Set passphrase if provided; the encoded output will then be encrypted
* using the passphrase.
*
* Alternative methods for specifying passphrases exist, such as a callback
* (see OSSL_ENCODER_CTX_set_passphrase_cb(3), just as for OSSL_DECODER_CTX;
* however you are less likely to need them as you presumably know whether
* encryption is desired in advance.
*
* Note that specifying a passphrase alone is not enough to cause the
* key to be encrypted. You must set both a cipher and a passphrase.
*/
if (passphrase != NULL) {
/*
* Set cipher. Let's use AES-256-CBC, because it is
* more quantum resistant.
*/
if (OSSL_ENCODER_CTX_set_cipher(ectx, "AES-256-CBC", propq) == 0) {
fprintf(stderr, "OSSL_ENCODER_CTX_set_cipher() failed\n");
goto cleanup;
}
/* Set passphrase. */
if (OSSL_ENCODER_CTX_set_passphrase(ectx,
(const unsigned char *)passphrase,
strlen(passphrase)) == 0) {
fprintf(stderr, "OSSL_ENCODER_CTX_set_passphrase() failed\n");
goto cleanup;
}
}
/* Do the encode, writing to the given file. */
if (OSSL_ENCODER_to_fp(ectx, f) == 0) {
fprintf(stderr, "OSSL_ENCODER_to_fp() failed\n");
goto cleanup;
}
ret = 1;
cleanup:
OSSL_ENCODER_CTX_free(ectx);
return ret;
}
int main(int argc, char **argv)
{
int ret = EXIT_FAILURE;
OSSL_LIB_CTX *libctx = NULL;
EVP_PKEY *pkey = NULL;
const char *passphrase_in = NULL, *passphrase_out = NULL;
/* usage: ec_encode <passphrase-in> <passphrase-out> */
if (argc > 1 && argv[1][0])
passphrase_in = argv[1];
if (argc > 2 && argv[2][0])
passphrase_out = argv[2];
/* Decode PEM key from stdin and then PEM encode it to stdout. */
pkey = load_key(libctx, stdin, passphrase_in);
if (pkey == NULL) {
fprintf(stderr, "Failed to decode key\n");
goto cleanup;
}
if (store_key(pkey, stdout, passphrase_out) == 0) {
fprintf(stderr, "Failed to encode key\n");
goto cleanup;
}
ret = EXIT_SUCCESS;
cleanup:
EVP_PKEY_free(pkey);
OSSL_LIB_CTX_free(libctx);
return ret;
}
| 6,734 | 31.694175 | 80 |
c
|
openssl
|
openssl-master/demos/encode/rsa_encode.c
|
/*-
* Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <string.h>
#include <openssl/decoder.h>
#include <openssl/encoder.h>
#include <openssl/evp.h>
/*
* Example showing the encoding and decoding of RSA public and private keys. A
* PEM-encoded RSA key is read in from stdin, decoded, and then re-encoded and
* output for demonstration purposes. Both public and private keys are accepted.
*
* This can be used to load RSA keys from a file or save RSA keys to a file.
*/
/* A property query used for selecting algorithm implementations. */
static const char *propq = NULL;
/*
* Load a PEM-encoded RSA key from a file, optionally decrypting it with a
* supplied passphrase.
*/
static EVP_PKEY *load_key(OSSL_LIB_CTX *libctx, FILE *f, const char *passphrase)
{
int ret = 0;
EVP_PKEY *pkey = NULL;
OSSL_DECODER_CTX *dctx = NULL;
int selection = 0;
/*
* Create PEM decoder context expecting an RSA key.
*
* For raw (non-PEM-encoded) keys, change "PEM" to "DER".
*
* The selection argument here specifies whether we are willing to accept a
* public key, private key, or either. If it is set to zero, either will be
* accepted. If set to EVP_PKEY_KEYPAIR, a private key will be required, and
* if set to EVP_PKEY_PUBLIC_KEY, a public key will be required.
*/
dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "PEM", NULL, "RSA",
selection,
libctx, propq);
if (dctx == NULL) {
fprintf(stderr, "OSSL_DECODER_CTX_new_for_pkey() failed\n");
goto cleanup;
}
/*
* Set passphrase if provided; needed to decrypt encrypted PEM files.
* If the input is not encrypted, any passphrase provided is ignored.
*
* Alternative methods for specifying passphrases exist, such as a callback
* (see OSSL_DECODER_CTX_set_passphrase_cb(3)), which may be more useful for
* interactive applications which do not know if a passphrase should be
* prompted for in advance, or for GUI applications.
*/
if (passphrase != NULL) {
if (OSSL_DECODER_CTX_set_passphrase(dctx,
(const unsigned char *)passphrase,
strlen(passphrase)) == 0) {
fprintf(stderr, "OSSL_DECODER_CTX_set_passphrase() failed\n");
goto cleanup;
}
}
/* Do the decode, reading from file. */
if (OSSL_DECODER_from_fp(dctx, f) == 0) {
fprintf(stderr, "OSSL_DECODER_from_fp() failed\n");
goto cleanup;
}
ret = 1;
cleanup:
OSSL_DECODER_CTX_free(dctx);
/*
* pkey is created by OSSL_DECODER_CTX_new_for_pkey, but we
* might fail subsequently, so ensure it's properly freed
* in this case.
*/
if (ret == 0) {
EVP_PKEY_free(pkey);
pkey = NULL;
}
return pkey;
}
/*
* Store an RSA public or private key to a file using PEM encoding.
*
* If a passphrase is supplied, the file is encrypted, otherwise
* it is unencrypted.
*/
static int store_key(EVP_PKEY *pkey, FILE *f, const char *passphrase)
{
int ret = 0;
int selection;
OSSL_ENCODER_CTX *ectx = NULL;
/*
* Create a PEM encoder context.
*
* For raw (non-PEM-encoded) output, change "PEM" to "DER".
*
* The selection argument controls whether the private key is exported
* (EVP_PKEY_KEYPAIR), or only the public key (EVP_PKEY_PUBLIC_KEY). The
* former will fail if we only have a public key.
*
* Note that unlike the decode API, you cannot specify zero here.
*
* Purely for the sake of demonstration, here we choose to export the whole
* key if a passphrase is provided and the public key otherwise.
*/
selection = (passphrase != NULL)
? EVP_PKEY_KEYPAIR
: EVP_PKEY_PUBLIC_KEY;
ectx = OSSL_ENCODER_CTX_new_for_pkey(pkey, selection, "PEM", NULL, propq);
if (ectx == NULL) {
fprintf(stderr, "OSSL_ENCODER_CTX_new_for_pkey() failed\n");
goto cleanup;
}
/*
* Set passphrase if provided; the encoded output will then be encrypted
* using the passphrase.
*
* Alternative methods for specifying passphrases exist, such as a callback
* (see OSSL_ENCODER_CTX_set_passphrase_cb(3), just as for OSSL_DECODER_CTX;
* however you are less likely to need them as you presumably know whether
* encryption is desired in advance.
*
* Note that specifying a passphrase alone is not enough to cause the
* key to be encrypted. You must set both a cipher and a passphrase.
*/
if (passphrase != NULL) {
/* Set cipher. AES-128-CBC is a reasonable default. */
if (OSSL_ENCODER_CTX_set_cipher(ectx, "AES-128-CBC", propq) == 0) {
fprintf(stderr, "OSSL_ENCODER_CTX_set_cipher() failed\n");
goto cleanup;
}
/* Set passphrase. */
if (OSSL_ENCODER_CTX_set_passphrase(ectx,
(const unsigned char *)passphrase,
strlen(passphrase)) == 0) {
fprintf(stderr, "OSSL_ENCODER_CTX_set_passphrase() failed\n");
goto cleanup;
}
}
/* Do the encode, writing to the given file. */
if (OSSL_ENCODER_to_fp(ectx, f) == 0) {
fprintf(stderr, "OSSL_ENCODER_to_fp() failed\n");
goto cleanup;
}
ret = 1;
cleanup:
OSSL_ENCODER_CTX_free(ectx);
return ret;
}
int main(int argc, char **argv)
{
int ret = EXIT_FAILURE;
OSSL_LIB_CTX *libctx = NULL;
EVP_PKEY *pkey = NULL;
const char *passphrase_in = NULL, *passphrase_out = NULL;
/* usage: rsa_encode <passphrase-in> <passphrase-out> */
if (argc > 1 && argv[1][0])
passphrase_in = argv[1];
if (argc > 2 && argv[2][0])
passphrase_out = argv[2];
/* Decode PEM key from stdin and then PEM encode it to stdout. */
pkey = load_key(libctx, stdin, passphrase_in);
if (pkey == NULL) {
fprintf(stderr, "Failed to decode key\n");
goto cleanup;
}
if (store_key(pkey, stdout, passphrase_out) == 0) {
fprintf(stderr, "Failed to encode key\n");
goto cleanup;
}
ret = EXIT_SUCCESS;
cleanup:
EVP_PKEY_free(pkey);
OSSL_LIB_CTX_free(libctx);
return ret;
}
| 6,689 | 31.955665 | 80 |
c
|
openssl
|
openssl-master/demos/encrypt/rsa_encrypt.c
|
/*-
* Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* An example that uses EVP_PKEY_encrypt and EVP_PKEY_decrypt methods
* to encrypt and decrypt data using an RSA keypair.
* RSA encryption produces different encrypted output each time it is run,
* hence this is not a known answer test.
*/
#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"
/* Input data to encrypt */
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";
/*
* For do_encrypt(), load an RSA public key from pub_key_der[].
* For do_decrypt(), load an RSA private key from priv_key_der[].
*/
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;
}
/* Set optional parameters for RSA OAEP Padding */
static void set_optional_params(OSSL_PARAM *p, const char *propq)
{
static unsigned char label[] = "label";
/* "pkcs1" is used by default if the padding mode is not set */
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_PAD_MODE,
OSSL_PKEY_RSA_PAD_MODE_OAEP, 0);
/* No oaep_label is used if this is not set */
*p++ = OSSL_PARAM_construct_octet_string(OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL,
label, sizeof(label));
/* "SHA1" is used if this is not set */
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST,
"SHA256", 0);
/*
* If a non default property query needs to be specified when fetching the
* OAEP digest then it needs to be specified here.
*/
if (propq != NULL)
*p++ = OSSL_PARAM_construct_utf8_string(OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST_PROPS,
(char *)propq, 0);
/*
* OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST and
* OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST_PROPS can also be optionally added
* here if the MGF1 digest differs from the OAEP digest.
*/
*p = OSSL_PARAM_construct_end();
}
/*
* The length of the input data that can be encrypted is limited by the
* RSA key length minus some additional bytes that depends on the padding mode.
*
*/
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];
/* Get public key */
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 no optional parameters are required then NULL can be passed */
if (EVP_PKEY_encrypt_init_ex(ctx, params) <= 0) {
fprintf(stderr, "EVP_PKEY_encrypt_init_ex() failed.\n");
goto cleanup;
}
/* Calculate the size required to hold the encrypted data */
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 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];
/* Get private key */
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;
}
/* The parameters used for encryption must also be used for decryption */
set_optional_params(params, propq);
/* If no optional parameters are required then NULL can be passed */
if (EVP_PKEY_decrypt_init_ex(ctx, params) <= 0) {
fprintf(stderr, "EVP_PKEY_decrypt_init_ex() failed.\n");
goto cleanup;
}
/* Calculate the size required to hold the decrypted data */
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;
}
| 7,913 | 31.434426 | 89 |
c
|
openssl
|
openssl-master/demos/encrypt/rsa_encrypt.h
|
/*-
* Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* Private RSA key used for decryption */
static const unsigned char priv_key_der[] = {
0x30, 0x82, 0x04, 0xa4, 0x02, 0x01, 0x00, 0x02, 0x82, 0x01, 0x01, 0x00,
0xc2, 0x44, 0xbc, 0xcf, 0x5b, 0xca, 0xcd, 0x80, 0x77, 0xae, 0xf9, 0x7a,
0x34, 0xbb, 0x37, 0x6f, 0x5c, 0x76, 0x4c, 0xe4, 0xbb, 0x0c, 0x1d, 0xe7,
0xfe, 0x0f, 0xda, 0xcf, 0x8c, 0x56, 0x65, 0x72, 0x6e, 0x2c, 0xf9, 0xfd,
0x87, 0x43, 0xeb, 0x4c, 0x26, 0xb1, 0xd3, 0xf0, 0x87, 0xb1, 0x18, 0x68,
0x14, 0x7d, 0x3c, 0x2a, 0xfa, 0xc2, 0x5d, 0x70, 0x19, 0x11, 0x00, 0x2e,
0xb3, 0x9c, 0x8e, 0x38, 0x08, 0xbe, 0xe3, 0xeb, 0x7d, 0x6e, 0xc7, 0x19,
0xc6, 0x7f, 0x59, 0x48, 0x84, 0x1b, 0xe3, 0x27, 0x30, 0x46, 0x30, 0xd3,
0xfc, 0xfc, 0xb3, 0x35, 0x75, 0xc4, 0x31, 0x1a, 0xc0, 0xc2, 0x4c, 0x0b,
0xc7, 0x01, 0x95, 0xb2, 0xdc, 0x17, 0x77, 0x9b, 0x09, 0x15, 0x04, 0xbc,
0xdb, 0x57, 0x0b, 0x26, 0xda, 0x59, 0x54, 0x0d, 0x6e, 0xb7, 0x89, 0xbc,
0x53, 0x9d, 0x5f, 0x8c, 0xad, 0x86, 0x97, 0xd2, 0x48, 0x4f, 0x5c, 0x94,
0xdd, 0x30, 0x2f, 0xcf, 0xfc, 0xde, 0x20, 0x31, 0x25, 0x9d, 0x29, 0x25,
0x78, 0xb7, 0xd2, 0x5b, 0x5d, 0x99, 0x5b, 0x08, 0x12, 0x81, 0x79, 0x89,
0xa0, 0xcf, 0x8f, 0x40, 0xb1, 0x77, 0x72, 0x3b, 0x13, 0xfc, 0x55, 0x43,
0x70, 0x29, 0xd5, 0x41, 0xed, 0x31, 0x4b, 0x2d, 0x6c, 0x7d, 0xcf, 0x99,
0x5f, 0xd1, 0x72, 0x9f, 0x8b, 0x32, 0x96, 0xde, 0x5d, 0x8b, 0x19, 0x77,
0x75, 0xff, 0x09, 0xbf, 0x26, 0xe9, 0xd7, 0x3d, 0xc7, 0x1a, 0x81, 0xcf,
0x05, 0x1b, 0x89, 0xbf, 0x45, 0x32, 0xbf, 0x5e, 0xc9, 0xe3, 0x5c, 0x33,
0x4a, 0x72, 0x47, 0xf4, 0x24, 0xae, 0x9b, 0x38, 0x24, 0x76, 0x9a, 0xa2,
0x9a, 0x50, 0x50, 0x49, 0xf5, 0x26, 0xb9, 0x55, 0xa6, 0x47, 0xc9, 0x14,
0xa2, 0xca, 0xd4, 0xa8, 0x8a, 0x9f, 0xe9, 0x5a, 0x5a, 0x12, 0xaa, 0x30,
0xd5, 0x78, 0x8b, 0x39, 0x02, 0x03, 0x01, 0x00, 0x01, 0x02, 0x82, 0x01,
0x00, 0x22, 0x5d, 0xb9, 0x8e, 0xef, 0x1c, 0x91, 0xbd, 0x03, 0xaf, 0x1a,
0xe8, 0x00, 0xf3, 0x0b, 0x8b, 0xf2, 0x2d, 0xe5, 0x4d, 0x63, 0x3f, 0x71,
0xfc, 0xeb, 0xc7, 0x4f, 0x3c, 0x7f, 0x05, 0x7b, 0x9d, 0xc2, 0x1a, 0xc7,
0xc0, 0x8f, 0x50, 0xb7, 0x0b, 0xba, 0x1e, 0xa4, 0x30, 0xfd, 0x38, 0x19,
0x6a, 0xb4, 0x11, 0x31, 0x77, 0x22, 0xf4, 0x06, 0x46, 0x81, 0xd0, 0xad,
0x99, 0x15, 0x62, 0x01, 0x10, 0xad, 0x8f, 0x63, 0x4f, 0x71, 0xd9, 0x8a,
0x74, 0x27, 0x56, 0xb8, 0xeb, 0x28, 0x9f, 0xac, 0x4f, 0xee, 0xec, 0xc3,
0xcf, 0x84, 0x86, 0x09, 0x87, 0xd0, 0x04, 0xfc, 0x70, 0xd0, 0x9f, 0xae,
0x87, 0x38, 0xd5, 0xb1, 0x6f, 0x3a, 0x1b, 0x16, 0xa8, 0x00, 0xf3, 0xcc,
0x6a, 0x42, 0x5d, 0x04, 0x16, 0x83, 0xf2, 0xe0, 0x79, 0x1d, 0xd8, 0x6f,
0x0f, 0xb7, 0x34, 0xf4, 0x45, 0xb5, 0x1e, 0xc5, 0xb5, 0x78, 0xa7, 0xd3,
0xa3, 0x23, 0x35, 0xbc, 0x7b, 0x01, 0x59, 0x7d, 0xee, 0xb9, 0x4f, 0xda,
0x28, 0xad, 0x5d, 0x25, 0xab, 0x66, 0x6a, 0xb0, 0x61, 0xf6, 0x12, 0xa7,
0xee, 0xd1, 0xe7, 0xb1, 0x8b, 0x91, 0x29, 0xba, 0xb5, 0xf8, 0x78, 0xc8,
0x6b, 0x76, 0x67, 0x32, 0xe8, 0xf3, 0x4e, 0x59, 0xba, 0xc1, 0x44, 0xc0,
0xec, 0x8d, 0x7c, 0x63, 0xb2, 0x6e, 0x0c, 0xb9, 0x33, 0x42, 0x0c, 0x8d,
0xae, 0x4e, 0x54, 0xc8, 0x8a, 0xef, 0xf9, 0x47, 0xc8, 0x99, 0x84, 0xc8,
0x46, 0xf6, 0xa6, 0x53, 0x59, 0xf8, 0x60, 0xe3, 0xd7, 0x1d, 0x10, 0x95,
0xf5, 0x6d, 0xf4, 0xa3, 0x18, 0x40, 0xd7, 0x14, 0x04, 0xac, 0x8c, 0x69,
0xd6, 0x14, 0xdc, 0xd8, 0xcc, 0xbc, 0x1c, 0xac, 0xd7, 0x21, 0x2b, 0x7e,
0x29, 0x88, 0x06, 0xa0, 0xf4, 0x06, 0x08, 0x14, 0x04, 0x4d, 0x32, 0x33,
0x84, 0x9c, 0x20, 0x8e, 0xcf, 0x02, 0x81, 0x81, 0x00, 0xf3, 0xf9, 0xbd,
0xd5, 0x43, 0x6f, 0x27, 0x4a, 0x92, 0xd6, 0x18, 0x3d, 0x4b, 0xf1, 0x77,
0x7c, 0xaf, 0xce, 0x01, 0x17, 0x98, 0xcb, 0xbe, 0x06, 0x86, 0x3a, 0x13,
0x72, 0x4b, 0x7c, 0x81, 0x51, 0x24, 0x5d, 0xc3, 0xe9, 0xa2, 0x63, 0x1e,
0x4a, 0xeb, 0x66, 0xae, 0x01, 0x5e, 0xa4, 0xa4, 0x74, 0x9e, 0xee, 0x32,
0xe5, 0x59, 0x1b, 0x37, 0xef, 0x7d, 0xb3, 0x42, 0x8c, 0x93, 0x8b, 0xd3,
0x1e, 0x83, 0x43, 0xb5, 0x88, 0x3e, 0x24, 0xeb, 0xdc, 0x92, 0x2d, 0xcc,
0x9a, 0x9d, 0xf1, 0x7d, 0x16, 0x71, 0xcb, 0x25, 0x47, 0x36, 0xb0, 0xc4,
0x6b, 0xc8, 0x53, 0x4a, 0x25, 0x80, 0x47, 0x77, 0xdb, 0x97, 0x13, 0x15,
0x0f, 0x4a, 0xfa, 0x0c, 0x6c, 0x44, 0x13, 0x2f, 0xbc, 0x9a, 0x6b, 0x13,
0x57, 0xfc, 0x42, 0xb9, 0xe9, 0xd3, 0x2e, 0xd2, 0x11, 0xf4, 0xc5, 0x84,
0x55, 0xd2, 0xdf, 0x1d, 0xa7, 0x02, 0x81, 0x81, 0x00, 0xcb, 0xd7, 0xd6,
0x9d, 0x71, 0xb3, 0x86, 0xbe, 0x68, 0xed, 0x67, 0xe1, 0x51, 0x92, 0x17,
0x60, 0x58, 0xb3, 0x2a, 0x56, 0xfd, 0x18, 0xfb, 0x39, 0x4b, 0x14, 0xc6,
0xf6, 0x67, 0x0e, 0x31, 0xe3, 0xb3, 0x2f, 0x1f, 0xec, 0x16, 0x1c, 0x23,
0x2b, 0x60, 0x36, 0xd1, 0xcb, 0x4a, 0x03, 0x6a, 0x3a, 0x4c, 0x8c, 0xf2,
0x73, 0x08, 0x23, 0x29, 0xda, 0xcb, 0xf7, 0xb6, 0x18, 0x97, 0xc6, 0xfe,
0xd4, 0x40, 0x06, 0x87, 0x9d, 0x6e, 0xbb, 0x5d, 0x14, 0x44, 0xc8, 0x19,
0xfa, 0x7f, 0x0c, 0xc5, 0x02, 0x92, 0x00, 0xbb, 0x2e, 0x4f, 0x50, 0xb0,
0x71, 0x9f, 0xf3, 0x94, 0x12, 0xb8, 0x6c, 0x5f, 0xe1, 0x83, 0x7b, 0xbc,
0x8c, 0x0a, 0x6f, 0x09, 0x6a, 0x35, 0x4f, 0xf9, 0xa4, 0x92, 0x93, 0xe3,
0xad, 0x36, 0x25, 0x28, 0x90, 0x85, 0xd2, 0x9f, 0x86, 0xfd, 0xd9, 0xa8,
0x61, 0xe9, 0xb2, 0xec, 0x1f, 0x02, 0x81, 0x81, 0x00, 0xdd, 0x1c, 0x52,
0xda, 0x2b, 0xc2, 0x5a, 0x26, 0xb0, 0xcb, 0x0d, 0xae, 0xc7, 0xdb, 0xf0,
0x41, 0x75, 0x87, 0x4a, 0xe0, 0x1a, 0xdf, 0x53, 0xb9, 0xcf, 0xfe, 0x64,
0x4f, 0x6a, 0x70, 0x4d, 0x36, 0xbf, 0xb1, 0xa6, 0xf3, 0x5f, 0xf3, 0x5a,
0xa9, 0xe5, 0x8b, 0xea, 0x59, 0x5d, 0x6f, 0xf3, 0x87, 0xa9, 0xde, 0x11,
0x0c, 0x60, 0x64, 0x55, 0x9e, 0x5c, 0x1a, 0x91, 0x4e, 0x9c, 0x0d, 0xd5,
0xe9, 0x4a, 0x67, 0x9b, 0xe6, 0xfd, 0x03, 0x33, 0x2b, 0x74, 0xe3, 0xc3,
0x11, 0xc1, 0xe0, 0xf1, 0x4f, 0xdd, 0x13, 0x92, 0x16, 0x67, 0x4f, 0x6e,
0xc4, 0x8c, 0x0a, 0x48, 0x21, 0x92, 0x8f, 0xb2, 0xe5, 0xb5, 0x96, 0x5a,
0xb8, 0xc0, 0x67, 0xbb, 0xc8, 0x87, 0x2d, 0xa8, 0x4e, 0xd2, 0xd8, 0x05,
0xf0, 0xf0, 0xb3, 0x7c, 0x90, 0x98, 0x8f, 0x4f, 0x5d, 0x6c, 0xab, 0x71,
0x92, 0xe2, 0x88, 0xc8, 0xf3, 0x02, 0x81, 0x81, 0x00, 0x99, 0x27, 0x5a,
0x00, 0x81, 0x65, 0x39, 0x5f, 0xe6, 0xc6, 0x38, 0xbe, 0x79, 0xe3, 0x21,
0xdd, 0x29, 0xc7, 0xb3, 0x90, 0x18, 0x29, 0xa4, 0xd7, 0xaf, 0x29, 0xb5,
0x33, 0x7c, 0xca, 0x95, 0x81, 0x57, 0x27, 0x98, 0xfc, 0x70, 0xc0, 0x43,
0x4c, 0x5b, 0xc5, 0xd4, 0x6a, 0xc0, 0xf9, 0x3f, 0xde, 0xfd, 0x95, 0x08,
0xb4, 0x94, 0xf0, 0x96, 0x89, 0xe5, 0xa6, 0x00, 0x13, 0x0a, 0x36, 0x61,
0x50, 0x67, 0xaa, 0x80, 0x4a, 0x30, 0xe0, 0x65, 0x56, 0xcd, 0x36, 0xeb,
0x0d, 0xe2, 0x57, 0x5d, 0xce, 0x48, 0x94, 0x74, 0x0e, 0x9f, 0x59, 0x28,
0xb8, 0xb6, 0x4c, 0xf4, 0x7b, 0xfc, 0x44, 0xb0, 0xe5, 0x67, 0x3c, 0x98,
0xb5, 0x3f, 0x41, 0x9d, 0xf9, 0x46, 0x85, 0x08, 0x34, 0x36, 0x4d, 0x17,
0x4b, 0x14, 0xdb, 0x66, 0x56, 0xef, 0xb5, 0x08, 0x57, 0x0c, 0x73, 0x74,
0xa7, 0xdc, 0x46, 0xaa, 0x51, 0x02, 0x81, 0x80, 0x1e, 0x50, 0x4c, 0xde,
0x9c, 0x60, 0x6d, 0xd7, 0x31, 0xf6, 0xd8, 0x4f, 0xc2, 0x25, 0x7d, 0x83,
0xb3, 0xe7, 0xed, 0x92, 0xe7, 0x28, 0x1e, 0xb3, 0x9b, 0xcb, 0xf2, 0x86,
0xa4, 0x49, 0x45, 0x5e, 0xba, 0x1d, 0xdb, 0x21, 0x5d, 0xdf, 0xeb, 0x3c,
0x5e, 0x01, 0xc6, 0x68, 0x25, 0x28, 0xe6, 0x1a, 0xbf, 0xc1, 0xa1, 0xc5,
0x92, 0x0b, 0x08, 0x43, 0x0e, 0x5a, 0xa3, 0x85, 0x8a, 0x65, 0xb4, 0x54,
0xa1, 0x4c, 0x20, 0xa2, 0x5a, 0x08, 0xf6, 0x90, 0x0d, 0x9a, 0xd7, 0x20,
0xf1, 0x10, 0x66, 0x28, 0x4c, 0x22, 0x56, 0xa6, 0xb9, 0xff, 0xd0, 0x6a,
0x62, 0x8c, 0x9f, 0xf8, 0x7c, 0xf4, 0xad, 0xd7, 0xe8, 0xf9, 0x87, 0x43,
0xbf, 0x73, 0x5b, 0x04, 0xc7, 0xd0, 0x77, 0xcc, 0xe3, 0xbe, 0xda, 0xc2,
0x07, 0xed, 0x8d, 0x2a, 0x15, 0x77, 0x1d, 0x53, 0x47, 0xe0, 0xa2, 0x11,
0x41, 0x0d, 0xe2, 0xe7,
};
/* The matching public key used for encryption*/
static const unsigned char pub_key_der[] = {
0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xc2, 0x44, 0xbc,
0xcf, 0x5b, 0xca, 0xcd, 0x80, 0x77, 0xae, 0xf9, 0x7a, 0x34, 0xbb, 0x37,
0x6f, 0x5c, 0x76, 0x4c, 0xe4, 0xbb, 0x0c, 0x1d, 0xe7, 0xfe, 0x0f, 0xda,
0xcf, 0x8c, 0x56, 0x65, 0x72, 0x6e, 0x2c, 0xf9, 0xfd, 0x87, 0x43, 0xeb,
0x4c, 0x26, 0xb1, 0xd3, 0xf0, 0x87, 0xb1, 0x18, 0x68, 0x14, 0x7d, 0x3c,
0x2a, 0xfa, 0xc2, 0x5d, 0x70, 0x19, 0x11, 0x00, 0x2e, 0xb3, 0x9c, 0x8e,
0x38, 0x08, 0xbe, 0xe3, 0xeb, 0x7d, 0x6e, 0xc7, 0x19, 0xc6, 0x7f, 0x59,
0x48, 0x84, 0x1b, 0xe3, 0x27, 0x30, 0x46, 0x30, 0xd3, 0xfc, 0xfc, 0xb3,
0x35, 0x75, 0xc4, 0x31, 0x1a, 0xc0, 0xc2, 0x4c, 0x0b, 0xc7, 0x01, 0x95,
0xb2, 0xdc, 0x17, 0x77, 0x9b, 0x09, 0x15, 0x04, 0xbc, 0xdb, 0x57, 0x0b,
0x26, 0xda, 0x59, 0x54, 0x0d, 0x6e, 0xb7, 0x89, 0xbc, 0x53, 0x9d, 0x5f,
0x8c, 0xad, 0x86, 0x97, 0xd2, 0x48, 0x4f, 0x5c, 0x94, 0xdd, 0x30, 0x2f,
0xcf, 0xfc, 0xde, 0x20, 0x31, 0x25, 0x9d, 0x29, 0x25, 0x78, 0xb7, 0xd2,
0x5b, 0x5d, 0x99, 0x5b, 0x08, 0x12, 0x81, 0x79, 0x89, 0xa0, 0xcf, 0x8f,
0x40, 0xb1, 0x77, 0x72, 0x3b, 0x13, 0xfc, 0x55, 0x43, 0x70, 0x29, 0xd5,
0x41, 0xed, 0x31, 0x4b, 0x2d, 0x6c, 0x7d, 0xcf, 0x99, 0x5f, 0xd1, 0x72,
0x9f, 0x8b, 0x32, 0x96, 0xde, 0x5d, 0x8b, 0x19, 0x77, 0x75, 0xff, 0x09,
0xbf, 0x26, 0xe9, 0xd7, 0x3d, 0xc7, 0x1a, 0x81, 0xcf, 0x05, 0x1b, 0x89,
0xbf, 0x45, 0x32, 0xbf, 0x5e, 0xc9, 0xe3, 0x5c, 0x33, 0x4a, 0x72, 0x47,
0xf4, 0x24, 0xae, 0x9b, 0x38, 0x24, 0x76, 0x9a, 0xa2, 0x9a, 0x50, 0x50,
0x49, 0xf5, 0x26, 0xb9, 0x55, 0xa6, 0x47, 0xc9, 0x14, 0xa2, 0xca, 0xd4,
0xa8, 0x8a, 0x9f, 0xe9, 0x5a, 0x5a, 0x12, 0xaa, 0x30, 0xd5, 0x78, 0x8b,
0x39, 0x02, 0x03, 0x01, 0x00, 0x01,
};
| 9,938 | 68.992958 | 75 |
h
|
openssl
|
openssl-master/demos/guide/quic-client-block.c
|
/*
* Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* NB: Changes to this file should also be reflected in
* doc/man7/ossl-guide-quic-client-block.pod
*/
#include <string.h>
/* Include the appropriate header file for SOCK_DGRAM */
#ifdef _WIN32 /* Windows */
# include <winsock2.h>
#else /* Linux/Unix */
# include <sys/socket.h>
#endif
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
/* Helper function to create a BIO connected to the server */
static BIO *create_socket_bio(const char *hostname, const char *port,
BIO_ADDR **peer_addr)
{
int sock = -1;
BIO_ADDRINFO *res;
const BIO_ADDRINFO *ai = NULL;
BIO *bio;
/*
* Lookup IP address info for the server.
*/
if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, 0, SOCK_DGRAM, 0,
&res))
return NULL;
/*
* Loop through all the possible addresses for the server and find one
* we can connect to.
*/
for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
/*
* Create a TCP socket. We could equally use non-OpenSSL calls such
* as "socket" here for this and the subsequent connect and close
* functions. But for portability reasons and also so that we get
* errors on the OpenSSL stack in the event of a failure we use
* OpenSSL's versions of these functions.
*/
sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_DGRAM, 0, 0);
if (sock == -1)
continue;
/* Connect the socket to the server's address */
if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), 0)) {
BIO_closesocket(sock);
sock = -1;
continue;
}
/* Set to nonblocking mode */
if (!BIO_socket_nbio(sock, 1)) {
sock = -1;
continue;
}
break;
}
if (sock != -1) {
*peer_addr = BIO_ADDR_dup(BIO_ADDRINFO_address(ai));
if (*peer_addr == NULL) {
BIO_closesocket(sock);
return NULL;
}
}
/* Free the address information resources we allocated earlier */
BIO_ADDRINFO_free(res);
/* If sock is -1 then we've been unable to connect to the server */
if (sock == -1)
return NULL;
/* Create a BIO to wrap the socket*/
bio = BIO_new(BIO_s_datagram());
if (bio == NULL)
BIO_closesocket(sock);
/*
* Associate the newly created BIO with the underlying socket. By
* passing BIO_CLOSE here the socket will be automatically closed when
* the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which
* case you must close the socket explicitly when it is no longer
* needed.
*/
BIO_set_fd(bio, sock, BIO_CLOSE);
return bio;
}
/* Server hostname and port details. Must be in quotes */
#ifndef HOSTNAME
# define HOSTNAME "www.example.com"
#endif
#ifndef PORT
# define PORT "443"
#endif
/*
* Simple application to send a basic HTTP/1.0 request to a server and
* print the response on the screen. Note that HTTP/1.0 over QUIC is
* non-standard and will not typically be supported by real world servers. This
* is for demonstration purposes only.
*/
int main(void)
{
SSL_CTX *ctx = NULL;
SSL *ssl;
BIO *bio = NULL;
int res = EXIT_FAILURE;
int ret;
unsigned char alpn[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '0' };
const char *request =
"GET / HTTP/1.0\r\nConnection: close\r\nHost: "HOSTNAME"\r\n\r\n";
size_t written, readbytes;
char buf[160];
BIO_ADDR *peer_addr = NULL;
/*
* Create an SSL_CTX which we can use to create SSL objects from. We
* want an SSL_CTX for creating clients so we use
* OSSL_QUIC_client_method() here.
*/
ctx = SSL_CTX_new(OSSL_QUIC_client_method());
if (ctx == NULL) {
printf("Failed to create the SSL_CTX\n");
goto end;
}
/*
* Configure the client to abort the handshake if certificate
* verification fails. Virtually all clients should do this unless you
* really know what you are doing.
*/
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
/* Use the default trusted certificate store */
if (!SSL_CTX_set_default_verify_paths(ctx)) {
printf("Failed to set the default trusted certificate store\n");
goto end;
}
/* Create an SSL object to represent the TLS connection */
ssl = SSL_new(ctx);
if (ssl == NULL) {
printf("Failed to create the SSL object\n");
goto end;
}
/*
* Create the underlying transport socket/BIO and associate it with the
* connection.
*/
bio = create_socket_bio(HOSTNAME, PORT, &peer_addr);
if (bio == NULL) {
printf("Failed to crete the BIO\n");
goto end;
}
SSL_set_bio(ssl, bio, bio);
/*
* Tell the server during the handshake which hostname we are attempting
* to connect to in case the server supports multiple hosts.
*/
if (!SSL_set_tlsext_host_name(ssl, HOSTNAME)) {
printf("Failed to set the SNI hostname\n");
goto end;
}
/*
* Ensure we check during certificate verification that the server has
* supplied a certificate for the hostname that we were expecting.
* Virtually all clients should do this unless you really know what you
* are doing.
*/
if (!SSL_set1_host(ssl, HOSTNAME)) {
printf("Failed to set the certificate verification hostname");
goto end;
}
/* SSL_set_alpn_protos returns 0 for success! */
if (SSL_set_alpn_protos(ssl, alpn, sizeof(alpn)) != 0) {
printf("Failed to set the ALPN for the connection\n");
goto end;
}
if (!SSL_set_initial_peer_addr(ssl, peer_addr)) {
printf("Failed to set the initial peer address\n");
goto end;
}
if ((ret = SSL_connect(ssl)) < 1) {
/*
* If the failure is due to a verification error we can get more
* information about it from SSL_get_verify_result().
*/
if (SSL_get_verify_result(ssl) != X509_V_OK)
printf("Verify error: %s\n",
X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
goto end;
}
/* Write an HTTP GET request to the peer */
if (!SSL_write_ex(ssl, request, strlen(request), &written)) {
printf("Failed to write HTTP request\n");
goto end;
}
/*
* Get up to sizeof(buf) bytes of the response. We keep reading until the
* server closes the connection.
*/
while (SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
/*
* OpenSSL does not guarantee that the returned data is a string or
* that it is NUL terminated so we use fwrite() to write the exact
* number of bytes that we read. The data could be non-printable or
* have NUL characters in the middle of it. For this simple example
* we're going to print it to stdout anyway.
*/
fwrite(buf, 1, readbytes, stdout);
}
/* In case the response didn't finish with a newline we add one now */
printf("\n");
/*
* Check whether we finished the while loop above normally or as the
* result of an error. The 0 argument to SSL_get_error() is the return
* code we received from the SSL_read_ex() call. It must be 0 in order
* to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN.
*/
if (SSL_get_error(ssl, 0) != SSL_ERROR_ZERO_RETURN) {
/*
* Some error occurred other than a graceful close down by the
* peer.
*/
printf ("Failed reading remaining data\n");
goto end;
}
/*
* Repeatedly call SSL_shutdown() until the connection is fully
* closed.
*/
do {
ret = SSL_shutdown(ssl);
if (ret < 0) {
printf("Error shutting down: %d\n", ret);
goto end;
}
} while (ret != 1);
/* Success! */
res = EXIT_SUCCESS;
end:
/*
* If something bad happened then we will dump the contents of the
* OpenSSL error stack to stderr. There might be some useful diagnostic
* information there.
*/
if (res == EXIT_FAILURE)
ERR_print_errors_fp(stderr);
/*
* Free the resources we allocated. We do not free the BIO object here
* because ownership of it was immediately transferred to the SSL object
* via SSL_set_bio(). The BIO will be freed when we free the SSL object.
*/
SSL_free(ssl);
SSL_CTX_free(ctx);
BIO_ADDR_free(peer_addr);
return res;
}
| 8,963 | 29.69863 | 79 |
c
|
openssl
|
openssl-master/demos/guide/tls-client-block.c
|
/*
* Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*
* NB: Changes to this file should also be reflected in
* doc/man7/ossl-guide-tls-client-block.pod
*/
#include <string.h>
/* Include the appropriate header file for SOCK_STREAM */
#ifdef _WIN32 /* Windows */
# include <winsock2.h>
#else /* Linux/Unix */
# include <sys/socket.h>
#endif
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
/* Helper function to create a BIO connected to the server */
static BIO *create_socket_bio(const char *hostname, const char *port)
{
int sock = -1;
BIO_ADDRINFO *res;
const BIO_ADDRINFO *ai = NULL;
BIO *bio;
/*
* Lookup IP address info for the server.
*/
if (!BIO_lookup_ex(hostname, port, BIO_LOOKUP_CLIENT, 0, SOCK_STREAM, 0,
&res))
return NULL;
/*
* Loop through all the possible addresses for the server and find one
* we can connect to.
*/
for (ai = res; ai != NULL; ai = BIO_ADDRINFO_next(ai)) {
/*
* Create a TCP socket. We could equally use non-OpenSSL calls such
* as "socket" here for this and the subsequent connect and close
* functions. But for portability reasons and also so that we get
* errors on the OpenSSL stack in the event of a failure we use
* OpenSSL's versions of these functions.
*/
sock = BIO_socket(BIO_ADDRINFO_family(ai), SOCK_STREAM, 0, 0);
if (sock == -1)
continue;
/* Connect the socket to the server's address */
if (!BIO_connect(sock, BIO_ADDRINFO_address(ai), BIO_SOCK_NODELAY)) {
BIO_closesocket(sock);
sock = -1;
continue;
}
/* We have a connected socket so break out of the loop */
break;
}
/* Free the address information resources we allocated earlier */
BIO_ADDRINFO_free(res);
/* If sock is -1 then we've been unable to connect to the server */
if (sock == -1)
return NULL;
/* Create a BIO to wrap the socket*/
bio = BIO_new(BIO_s_socket());
if (bio == NULL)
BIO_closesocket(sock);
/*
* Associate the newly created BIO with the underlying socket. By
* passing BIO_CLOSE here the socket will be automatically closed when
* the BIO is freed. Alternatively you can use BIO_NOCLOSE, in which
* case you must close the socket explicitly when it is no longer
* needed.
*/
BIO_set_fd(bio, sock, BIO_CLOSE);
return bio;
}
/* Server hostname and port details. Must be in quotes */
#ifndef HOSTNAME
# define HOSTNAME "www.example.com"
#endif
#ifndef PORT
# define PORT "443"
#endif
/*
* Simple application to send a basic HTTP/1.0 request to a server and
* print the response on the screen.
*/
int main(void)
{
SSL_CTX *ctx = NULL;
SSL *ssl;
BIO *bio = NULL;
int res = EXIT_FAILURE;
int ret;
const char *request =
"GET / HTTP/1.0\r\nConnection: close\r\nHost: "HOSTNAME"\r\n\r\n";
size_t written, readbytes;
char buf[160];
/*
* Create an SSL_CTX which we can use to create SSL objects from. We
* want an SSL_CTX for creating clients so we use TLS_client_method()
* here.
*/
ctx = SSL_CTX_new(TLS_client_method());
if (ctx == NULL) {
printf("Failed to create the SSL_CTX\n");
goto end;
}
/*
* Configure the client to abort the handshake if certificate
* verification fails. Virtually all clients should do this unless you
* really know what you are doing.
*/
SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER, NULL);
/* Use the default trusted certificate store */
if (!SSL_CTX_set_default_verify_paths(ctx)) {
printf("Failed to set the default trusted certificate store\n");
goto end;
}
/*
* TLSv1.1 or earlier are deprecated by IETF and are generally to be
* avoided if possible. We require a minimum TLS version of TLSv1.2.
*/
if (!SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION)) {
printf("Failed to set the minimum TLS protocol version\n");
goto end;
}
/* Create an SSL object to represent the TLS connection */
ssl = SSL_new(ctx);
if (ssl == NULL) {
printf("Failed to create the SSL object\n");
goto end;
}
/*
* Create the underlying transport socket/BIO and associate it with the
* connection.
*/
bio = create_socket_bio(HOSTNAME, PORT);
if (bio == NULL) {
printf("Failed to crete the BIO\n");
goto end;
}
SSL_set_bio(ssl, bio, bio);
/*
* Tell the server during the handshake which hostname we are attempting
* to connect to in case the server supports multiple hosts.
*/
if (!SSL_set_tlsext_host_name(ssl, HOSTNAME)) {
printf("Failed to set the SNI hostname\n");
goto end;
}
/*
* Ensure we check during certificate verification that the server has
* supplied a certificate for the hostname that we were expecting.
* Virtually all clients should do this unless you really know what you
* are doing.
*/
if (!SSL_set1_host(ssl, HOSTNAME)) {
printf("Failed to set the certificate verification hostname");
goto end;
}
/* Do the handshake with the server */
if (SSL_connect(ssl) < 1) {
printf("Failed to connect to the server\n");
/*
* If the failure is due to a verification error we can get more
* information about it from SSL_get_verify_result().
*/
if (SSL_get_verify_result(ssl) != X509_V_OK)
printf("Verify error: %s\n",
X509_verify_cert_error_string(SSL_get_verify_result(ssl)));
goto end;
}
/* Write an HTTP GET request to the peer */
if (!SSL_write_ex(ssl, request, strlen(request), &written)) {
printf("Failed to write HTTP request\n");
goto end;
}
/*
* Get up to sizeof(buf) bytes of the response. We keep reading until the
* server closes the connection.
*/
while (SSL_read_ex(ssl, buf, sizeof(buf), &readbytes)) {
/*
* OpenSSL does not guarantee that the returned data is a string or
* that it is NUL terminated so we use fwrite() to write the exact
* number of bytes that we read. The data could be non-printable or
* have NUL characters in the middle of it. For this simple example
* we're going to print it to stdout anyway.
*/
fwrite(buf, 1, readbytes, stdout);
}
/* In case the response didn't finish with a newline we add one now */
printf("\n");
/*
* Check whether we finished the while loop above normally or as the
* result of an error. The 0 argument to SSL_get_error() is the return
* code we received from the SSL_read_ex() call. It must be 0 in order
* to get here. Normal completion is indicated by SSL_ERROR_ZERO_RETURN.
*/
if (SSL_get_error(ssl, 0) != SSL_ERROR_ZERO_RETURN) {
/*
* Some error occurred other than a graceful close down by the
* peer.
*/
printf ("Failed reading remaining data\n");
goto end;
}
/*
* The peer already shutdown gracefully (we know this because of the
* SSL_ERROR_ZERO_RETURN above). We should do the same back.
*/
ret = SSL_shutdown(ssl);
if (ret < 1) {
/*
* ret < 0 indicates an error. ret == 0 would be unexpected here
* because that means "we've sent a close_notify and we're waiting
* for one back". But we already know we got one from the peer
* because of the SSL_ERROR_ZERO_RETURN above.
*/
printf("Error shutting down\n");
goto end;
}
/* Success! */
res = EXIT_SUCCESS;
end:
/*
* If something bad happened then we will dump the contents of the
* OpenSSL error stack to stderr. There might be some useful diagnostic
* information there.
*/
if (res == EXIT_FAILURE)
ERR_print_errors_fp(stderr);
/*
* Free the resources we allocated. We do not free the BIO object here
* because ownership of it was immediately transferred to the SSL object
* via SSL_set_bio(). The BIO will be freed when we free the SSL object.
*/
SSL_free(ssl);
SSL_CTX_free(ctx);
return res;
}
| 8,705 | 30.543478 | 77 |
c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.