file_path
stringlengths 19
75
| code
stringlengths 279
1.37M
|
---|---|
./openssl/crypto/x509/v3_ind_iss.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
*/
#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_INDIRECT_ISSUER(X509V3_EXT_METHOD *method,
void *su, BIO *out,
int indent)
{
return 1;
}
static void *r2i_INDIRECT_ISSUER(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, const char *value)
{
return ASN1_NULL_new();
}
static char *i2s_INDIRECT_ISSUER(const X509V3_EXT_METHOD *method, void *val)
{
return OPENSSL_strdup("NULL");
}
static void *s2i_INDIRECT_ISSUER(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *str)
{
return ASN1_NULL_new();
}
/*
* The indirectIssuer X.509v3 extension is defined in ITU Recommendation X.509
* (2019), Section 17.5.2.5. See: https://www.itu.int/rec/T-REC-X.509-201910-I/en.
*/
const X509V3_EXT_METHOD ossl_v3_indirect_issuer = {
NID_indirect_issuer, 0, ASN1_ITEM_ref(ASN1_NULL),
0, 0, 0, 0,
(X509V3_EXT_I2S)i2s_INDIRECT_ISSUER,
(X509V3_EXT_S2I)s2i_INDIRECT_ISSUER,
0, 0,
(X509V3_EXT_I2R)i2r_INDIRECT_ISSUER,
(X509V3_EXT_R2I)r2i_INDIRECT_ISSUER,
NULL
};
|
./openssl/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);
|
./openssl/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;
}
|
./openssl/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;
}
|
./openssl/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";
}
}
|
./openssl/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;
}
|
./openssl/crypto/x509/pcy_tree.c | /*
* Copyright 2004-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 "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;
}
|
./openssl/crypto/x509/x_all.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
*/
/*
* 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);
}
|
./openssl/crypto/x509/x509_def.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 "internal/cryptlib.h"
#include <openssl/crypto.h>
#include <openssl/x509.h>
const char *X509_get_default_private_dir(void)
{
return X509_PRIVATE_DIR;
}
const char *X509_get_default_cert_area(void)
{
return X509_CERT_AREA;
}
const char *X509_get_default_cert_dir(void)
{
return X509_CERT_DIR;
}
const char *X509_get_default_cert_file(void)
{
return X509_CERT_FILE;
}
const char *X509_get_default_cert_dir_env(void)
{
return X509_CERT_DIR_EVP;
}
const char *X509_get_default_cert_file_env(void)
{
return X509_CERT_FILE_EVP;
}
|
./openssl/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)) {
SXNET_free(sx);
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;
}
if (!SXNET_add_id_INTEGER(psx, izone, user, userlen)) {
ASN1_INTEGER_free(izone);
return 0;
}
return 1;
}
/* 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;
}
if (!SXNET_add_id_INTEGER(psx, izone, user, userlen)) {
ASN1_INTEGER_free(izone);
return 0;
}
return 1;
}
/*
* 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;
}
ASN1_INTEGER_free(id->zone);
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;
}
|
./openssl/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;
}
|
./openssl/crypto/x509/v3_genn.c | /*
* Copyright 1999-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 "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;
}
|
./openssl/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;
}
|
./openssl/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
};
|
./openssl/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;
}
|
./openssl/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;
}
|
./openssl/crypto/x509/v3_purp.c | /*
* Copyright 1999-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 "internal/cryptlib.h"
#include "internal/numbers.h"
#include <openssl/x509v3.h>
#include <openssl/x509_vfy.h>
#include "crypto/x509.h"
#include "internal/tsan_assist.h"
#include "x509_local.h"
static int check_ssl_ca(const X509 *x);
static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
int non_leaf);
static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
int non_leaf);
static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
int non_leaf);
static int purpose_smime(const X509 *x, int non_leaf);
static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
int non_leaf);
static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
int non_leaf);
static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
int non_leaf);
static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
int non_leaf);
static int check_purpose_code_sign(const X509_PURPOSE *xp, const X509 *x,
int non_leaf);
static int no_check_purpose(const X509_PURPOSE *xp, const X509 *x,
int non_leaf);
static int check_purpose_ocsp_helper(const X509_PURPOSE *xp, const X509 *x,
int non_leaf);
static int xp_cmp(const X509_PURPOSE *const *a, const X509_PURPOSE *const *b);
static void xptable_free(X509_PURPOSE *p);
static X509_PURPOSE xstandard[] = {
{X509_PURPOSE_SSL_CLIENT, X509_TRUST_SSL_CLIENT, 0,
check_purpose_ssl_client, "SSL client", "sslclient", NULL},
{X509_PURPOSE_SSL_SERVER, X509_TRUST_SSL_SERVER, 0,
check_purpose_ssl_server, "SSL server", "sslserver", NULL},
{X509_PURPOSE_NS_SSL_SERVER, X509_TRUST_SSL_SERVER, 0,
check_purpose_ns_ssl_server, "Netscape SSL server", "nssslserver", NULL},
{X509_PURPOSE_SMIME_SIGN, X509_TRUST_EMAIL, 0, check_purpose_smime_sign,
"S/MIME signing", "smimesign", NULL},
{X509_PURPOSE_SMIME_ENCRYPT, X509_TRUST_EMAIL, 0,
check_purpose_smime_encrypt, "S/MIME encryption", "smimeencrypt", NULL},
{X509_PURPOSE_CRL_SIGN, X509_TRUST_COMPAT, 0, check_purpose_crl_sign,
"CRL signing", "crlsign", NULL},
{X509_PURPOSE_ANY, X509_TRUST_DEFAULT, 0, no_check_purpose,
"Any Purpose", "any",
NULL},
{X509_PURPOSE_OCSP_HELPER, X509_TRUST_COMPAT, 0, check_purpose_ocsp_helper,
"OCSP helper", "ocsphelper", NULL},
{X509_PURPOSE_TIMESTAMP_SIGN, X509_TRUST_TSA, 0,
check_purpose_timestamp_sign, "Time Stamp signing", "timestampsign",
NULL},
{X509_PURPOSE_CODE_SIGN, X509_TRUST_OBJECT_SIGN, 0,
check_purpose_code_sign, "Code signing", "codesign",
NULL},
};
#define X509_PURPOSE_COUNT OSSL_NELEM(xstandard)
static STACK_OF(X509_PURPOSE) *xptable = NULL;
static int xp_cmp(const X509_PURPOSE *const *a, const X509_PURPOSE *const *b)
{
return (*a)->purpose - (*b)->purpose;
}
/*
* As much as I'd like to make X509_check_purpose use a "const" X509* I really
* can't because it does recalculate hashes and do other non-const things.
* If id == -1 it just calls x509v3_cache_extensions() for its side-effect.
* Returns 1 on success, 0 if x does not allow purpose, -1 on (internal) error.
*/
int X509_check_purpose(X509 *x, int id, int non_leaf)
{
int idx;
const X509_PURPOSE *pt;
if (!ossl_x509v3_cache_extensions(x))
return -1;
if (id == -1)
return 1;
idx = X509_PURPOSE_get_by_id(id);
if (idx == -1)
return -1;
pt = X509_PURPOSE_get0(idx);
return pt->check_purpose(pt, x, non_leaf);
}
int X509_PURPOSE_set(int *p, int purpose)
{
if (X509_PURPOSE_get_by_id(purpose) == -1) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_PURPOSE);
return 0;
}
*p = purpose;
return 1;
}
int X509_PURPOSE_get_count(void)
{
if (!xptable)
return X509_PURPOSE_COUNT;
return sk_X509_PURPOSE_num(xptable) + X509_PURPOSE_COUNT;
}
X509_PURPOSE *X509_PURPOSE_get0(int idx)
{
if (idx < 0)
return NULL;
if (idx < (int)X509_PURPOSE_COUNT)
return xstandard + idx;
return sk_X509_PURPOSE_value(xptable, idx - X509_PURPOSE_COUNT);
}
int X509_PURPOSE_get_by_sname(const char *sname)
{
int i;
X509_PURPOSE *xptmp;
for (i = 0; i < X509_PURPOSE_get_count(); i++) {
xptmp = X509_PURPOSE_get0(i);
if (strcmp(xptmp->sname, sname) == 0)
return i;
}
return -1;
}
/* Returns -1 on error, else an index => 0 in standard/extended purpose table */
int X509_PURPOSE_get_by_id(int purpose)
{
X509_PURPOSE tmp;
int idx;
if (purpose >= X509_PURPOSE_MIN && purpose <= X509_PURPOSE_MAX)
return purpose - X509_PURPOSE_MIN;
if (xptable == NULL)
return -1;
tmp.purpose = purpose;
idx = sk_X509_PURPOSE_find(xptable, &tmp);
if (idx < 0)
return -1;
return idx + X509_PURPOSE_COUNT;
}
int X509_PURPOSE_add(int id, int trust, int flags,
int (*ck) (const X509_PURPOSE *, const X509 *, int),
const char *name, const char *sname, void *arg)
{
int idx;
X509_PURPOSE *ptmp;
/* This is set according to what we change: application can't set it */
flags &= ~X509_PURPOSE_DYNAMIC;
/* This will always be set for application modified trust entries */
flags |= X509_PURPOSE_DYNAMIC_NAME;
/* Get existing entry if any */
idx = X509_PURPOSE_get_by_id(id);
/* Need a new entry */
if (idx == -1) {
if ((ptmp = OPENSSL_malloc(sizeof(*ptmp))) == NULL)
return 0;
ptmp->flags = X509_PURPOSE_DYNAMIC;
} else {
ptmp = X509_PURPOSE_get0(idx);
}
/* OPENSSL_free existing name if dynamic */
if ((ptmp->flags & X509_PURPOSE_DYNAMIC_NAME) != 0) {
OPENSSL_free(ptmp->name);
OPENSSL_free(ptmp->sname);
}
/* Dup supplied name */
ptmp->name = OPENSSL_strdup(name);
ptmp->sname = OPENSSL_strdup(sname);
if (ptmp->name == NULL || ptmp->sname == NULL)
goto err;
/* Keep the dynamic flag of existing entry */
ptmp->flags &= X509_PURPOSE_DYNAMIC;
/* Set all other flags */
ptmp->flags |= flags;
ptmp->purpose = id;
ptmp->trust = trust;
ptmp->check_purpose = ck;
ptmp->usr_data = arg;
/* If its a new entry manage the dynamic table */
if (idx == -1) {
if (xptable == NULL
&& (xptable = sk_X509_PURPOSE_new(xp_cmp)) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
if (!sk_X509_PURPOSE_push(xptable, ptmp)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
}
return 1;
err:
if (idx == -1) {
OPENSSL_free(ptmp->name);
OPENSSL_free(ptmp->sname);
OPENSSL_free(ptmp);
}
return 0;
}
static void xptable_free(X509_PURPOSE *p)
{
if (p == NULL)
return;
if ((p->flags & X509_PURPOSE_DYNAMIC) != 0) {
if ((p->flags & X509_PURPOSE_DYNAMIC_NAME) != 0) {
OPENSSL_free(p->name);
OPENSSL_free(p->sname);
}
OPENSSL_free(p);
}
}
void X509_PURPOSE_cleanup(void)
{
sk_X509_PURPOSE_pop_free(xptable, xptable_free);
xptable = NULL;
}
int X509_PURPOSE_get_id(const X509_PURPOSE *xp)
{
return xp->purpose;
}
char *X509_PURPOSE_get0_name(const X509_PURPOSE *xp)
{
return xp->name;
}
char *X509_PURPOSE_get0_sname(const X509_PURPOSE *xp)
{
return xp->sname;
}
int X509_PURPOSE_get_trust(const X509_PURPOSE *xp)
{
return xp->trust;
}
static int nid_cmp(const int *a, const int *b)
{
return *a - *b;
}
DECLARE_OBJ_BSEARCH_CMP_FN(int, int, nid);
IMPLEMENT_OBJ_BSEARCH_CMP_FN(int, int, nid);
int X509_supported_extension(X509_EXTENSION *ex)
{
/*
* This table is a list of the NIDs of supported extensions: that is
* those which are used by the verify process. If an extension is
* critical and doesn't appear in this list then the verify process will
* normally reject the certificate. The list must be kept in numerical
* order because it will be searched using bsearch.
*/
static const int supported_nids[] = {
NID_netscape_cert_type, /* 71 */
NID_key_usage, /* 83 */
NID_subject_alt_name, /* 85 */
NID_basic_constraints, /* 87 */
NID_certificate_policies, /* 89 */
NID_crl_distribution_points, /* 103 */
NID_ext_key_usage, /* 126 */
#ifndef OPENSSL_NO_RFC3779
NID_sbgp_ipAddrBlock, /* 290 */
NID_sbgp_autonomousSysNum, /* 291 */
#endif
NID_id_pkix_OCSP_noCheck, /* 369 */
NID_policy_constraints, /* 401 */
NID_proxyCertInfo, /* 663 */
NID_name_constraints, /* 666 */
NID_policy_mappings, /* 747 */
NID_inhibit_any_policy /* 748 */
};
int ex_nid = OBJ_obj2nid(X509_EXTENSION_get_object(ex));
if (ex_nid == NID_undef)
return 0;
if (OBJ_bsearch_nid(&ex_nid, supported_nids, OSSL_NELEM(supported_nids)))
return 1;
return 0;
}
/* Returns 1 on success, 0 if x is invalid, -1 on (internal) error. */
static int setup_dp(const X509 *x, DIST_POINT *dp)
{
const X509_NAME *iname = NULL;
int i;
if (dp->distpoint == NULL && sk_GENERAL_NAME_num(dp->CRLissuer) <= 0) {
ERR_raise(ERR_LIB_X509, X509_R_INVALID_DISTPOINT);
return 0;
}
if (dp->reasons != NULL) {
if (dp->reasons->length > 0)
dp->dp_reasons = dp->reasons->data[0];
if (dp->reasons->length > 1)
dp->dp_reasons |= (dp->reasons->data[1] << 8);
dp->dp_reasons &= CRLDP_ALL_REASONS;
} else {
dp->dp_reasons = CRLDP_ALL_REASONS;
}
if (dp->distpoint == NULL || dp->distpoint->type != 1)
return 1;
/* Handle name fragment given by nameRelativeToCRLIssuer */
/*
* Note that the below way of determining iname is not really compliant
* with https://tools.ietf.org/html/rfc5280#section-4.2.1.13
* According to it, sk_GENERAL_NAME_num(dp->CRLissuer) MUST be <= 1
* and any CRLissuer could be of type different to GEN_DIRNAME.
*/
for (i = 0; i < sk_GENERAL_NAME_num(dp->CRLissuer); i++) {
GENERAL_NAME *gen = sk_GENERAL_NAME_value(dp->CRLissuer, i);
if (gen->type == GEN_DIRNAME) {
iname = gen->d.directoryName;
break;
}
}
if (iname == NULL)
iname = X509_get_issuer_name(x);
return DIST_POINT_set_dpname(dp->distpoint, iname) ? 1 : -1;
}
/* Return 1 on success, 0 if x is invalid, -1 on (internal) error. */
static int setup_crldp(X509 *x)
{
int i;
x->crldp = X509_get_ext_d2i(x, NID_crl_distribution_points, &i, NULL);
if (x->crldp == NULL && i != -1)
return 0;
for (i = 0; i < sk_DIST_POINT_num(x->crldp); i++) {
int res = setup_dp(x, sk_DIST_POINT_value(x->crldp, i));
if (res < 1)
return res;
}
return 1;
}
/* Check that issuer public key algorithm matches subject signature algorithm */
static int check_sig_alg_match(const EVP_PKEY *issuer_key, const X509 *subject)
{
int subj_sig_nid;
if (issuer_key == NULL)
return X509_V_ERR_NO_ISSUER_PUBLIC_KEY;
if (OBJ_find_sigid_algs(OBJ_obj2nid(subject->cert_info.signature.algorithm),
NULL, &subj_sig_nid) == 0)
return X509_V_ERR_UNSUPPORTED_SIGNATURE_ALGORITHM;
if (EVP_PKEY_is_a(issuer_key, OBJ_nid2sn(subj_sig_nid))
|| (EVP_PKEY_is_a(issuer_key, "RSA") && subj_sig_nid == NID_rsassaPss))
return X509_V_OK;
return X509_V_ERR_SIGNATURE_ALGORITHM_MISMATCH;
}
#define V1_ROOT (EXFLAG_V1 | EXFLAG_SS)
#define ku_reject(x, usage) \
(((x)->ex_flags & EXFLAG_KUSAGE) != 0 && ((x)->ex_kusage & (usage)) == 0)
#define xku_reject(x, usage) \
(((x)->ex_flags & EXFLAG_XKUSAGE) != 0 && ((x)->ex_xkusage & (usage)) == 0)
#define ns_reject(x, usage) \
(((x)->ex_flags & EXFLAG_NSCERT) != 0 && ((x)->ex_nscert & (usage)) == 0)
/*
* Cache info on various X.509v3 extensions and further derived information,
* e.g., if cert 'x' is self-issued, in x->ex_flags and other internal fields.
* x->sha1_hash is filled in, or else EXFLAG_NO_FINGERPRINT is set in x->flags.
* X509_SIG_INFO_VALID is set in x->flags if x->siginf was filled successfully.
* Set EXFLAG_INVALID and return 0 in case the certificate is invalid.
*/
int ossl_x509v3_cache_extensions(X509 *x)
{
BASIC_CONSTRAINTS *bs;
PROXY_CERT_INFO_EXTENSION *pci;
ASN1_BIT_STRING *usage;
ASN1_BIT_STRING *ns;
EXTENDED_KEY_USAGE *extusage;
int i;
int res;
#ifdef tsan_ld_acq
/* Fast lock-free check, see end of the function for details. */
if (tsan_ld_acq((TSAN_QUALIFIER int *)&x->ex_cached))
return (x->ex_flags & EXFLAG_INVALID) == 0;
#endif
if (!CRYPTO_THREAD_write_lock(x->lock))
return 0;
if ((x->ex_flags & EXFLAG_SET) != 0) { /* Cert has already been processed */
CRYPTO_THREAD_unlock(x->lock);
return (x->ex_flags & EXFLAG_INVALID) == 0;
}
ERR_set_mark();
/* Cache the SHA1 digest of the cert */
if (!X509_digest(x, EVP_sha1(), x->sha1_hash, NULL))
x->ex_flags |= EXFLAG_NO_FINGERPRINT;
/* V1 should mean no extensions ... */
if (X509_get_version(x) == X509_VERSION_1)
x->ex_flags |= EXFLAG_V1;
/* Handle basic constraints */
x->ex_pathlen = -1;
if ((bs = X509_get_ext_d2i(x, NID_basic_constraints, &i, NULL)) != NULL) {
if (bs->ca)
x->ex_flags |= EXFLAG_CA;
if (bs->pathlen != NULL) {
/*
* The error case !bs->ca is checked by check_chain()
* in case ctx->param->flags & X509_V_FLAG_X509_STRICT
*/
if (bs->pathlen->type == V_ASN1_NEG_INTEGER) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_NEGATIVE_PATHLEN);
x->ex_flags |= EXFLAG_INVALID;
} else {
x->ex_pathlen = ASN1_INTEGER_get(bs->pathlen);
}
}
BASIC_CONSTRAINTS_free(bs);
x->ex_flags |= EXFLAG_BCONS;
} else if (i != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
/* Handle proxy certificates */
if ((pci = X509_get_ext_d2i(x, NID_proxyCertInfo, &i, NULL)) != NULL) {
if ((x->ex_flags & EXFLAG_CA) != 0
|| X509_get_ext_by_NID(x, NID_subject_alt_name, -1) >= 0
|| X509_get_ext_by_NID(x, NID_issuer_alt_name, -1) >= 0) {
x->ex_flags |= EXFLAG_INVALID;
}
if (pci->pcPathLengthConstraint != NULL)
x->ex_pcpathlen = ASN1_INTEGER_get(pci->pcPathLengthConstraint);
else
x->ex_pcpathlen = -1;
PROXY_CERT_INFO_EXTENSION_free(pci);
x->ex_flags |= EXFLAG_PROXY;
} else if (i != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
/* Handle (basic) key usage */
if ((usage = X509_get_ext_d2i(x, NID_key_usage, &i, NULL)) != NULL) {
x->ex_kusage = 0;
if (usage->length > 0) {
x->ex_kusage = usage->data[0];
if (usage->length > 1)
x->ex_kusage |= usage->data[1] << 8;
}
x->ex_flags |= EXFLAG_KUSAGE;
ASN1_BIT_STRING_free(usage);
/* Check for empty key usage according to RFC 5280 section 4.2.1.3 */
if (x->ex_kusage == 0) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_EMPTY_KEY_USAGE);
x->ex_flags |= EXFLAG_INVALID;
}
} else if (i != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
/* Handle extended key usage */
x->ex_xkusage = 0;
if ((extusage = X509_get_ext_d2i(x, NID_ext_key_usage, &i, NULL)) != NULL) {
x->ex_flags |= EXFLAG_XKUSAGE;
for (i = 0; i < sk_ASN1_OBJECT_num(extusage); i++) {
switch (OBJ_obj2nid(sk_ASN1_OBJECT_value(extusage, i))) {
case NID_server_auth:
x->ex_xkusage |= XKU_SSL_SERVER;
break;
case NID_client_auth:
x->ex_xkusage |= XKU_SSL_CLIENT;
break;
case NID_email_protect:
x->ex_xkusage |= XKU_SMIME;
break;
case NID_code_sign:
x->ex_xkusage |= XKU_CODE_SIGN;
break;
case NID_ms_sgc:
case NID_ns_sgc:
x->ex_xkusage |= XKU_SGC;
break;
case NID_OCSP_sign:
x->ex_xkusage |= XKU_OCSP_SIGN;
break;
case NID_time_stamp:
x->ex_xkusage |= XKU_TIMESTAMP;
break;
case NID_dvcs:
x->ex_xkusage |= XKU_DVCS;
break;
case NID_anyExtendedKeyUsage:
x->ex_xkusage |= XKU_ANYEKU;
break;
default:
/* Ignore unknown extended key usage */
break;
}
}
sk_ASN1_OBJECT_pop_free(extusage, ASN1_OBJECT_free);
} else if (i != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
/* Handle legacy Netscape extension */
if ((ns = X509_get_ext_d2i(x, NID_netscape_cert_type, &i, NULL)) != NULL) {
if (ns->length > 0)
x->ex_nscert = ns->data[0];
else
x->ex_nscert = 0;
x->ex_flags |= EXFLAG_NSCERT;
ASN1_BIT_STRING_free(ns);
} else if (i != -1) {
x->ex_flags |= EXFLAG_INVALID;
}
/* Handle subject key identifier and issuer/authority key identifier */
x->skid = X509_get_ext_d2i(x, NID_subject_key_identifier, &i, NULL);
if (x->skid == NULL && i != -1)
x->ex_flags |= EXFLAG_INVALID;
x->akid = X509_get_ext_d2i(x, NID_authority_key_identifier, &i, NULL);
if (x->akid == NULL && i != -1)
x->ex_flags |= EXFLAG_INVALID;
/* Check if subject name matches issuer */
if (X509_NAME_cmp(X509_get_subject_name(x), X509_get_issuer_name(x)) == 0) {
x->ex_flags |= EXFLAG_SI; /* Cert is self-issued */
if (X509_check_akid(x, x->akid) == X509_V_OK /* SKID matches AKID */
/* .. and the signature alg matches the PUBKEY alg: */
&& check_sig_alg_match(X509_get0_pubkey(x), x) == X509_V_OK)
x->ex_flags |= EXFLAG_SS; /* indicate self-signed */
/* This is very related to ossl_x509_likely_issued(x, x) == X509_V_OK */
}
/* Handle subject alternative names and various other extensions */
x->altname = X509_get_ext_d2i(x, NID_subject_alt_name, &i, NULL);
if (x->altname == NULL && i != -1)
x->ex_flags |= EXFLAG_INVALID;
x->nc = X509_get_ext_d2i(x, NID_name_constraints, &i, NULL);
if (x->nc == NULL && i != -1)
x->ex_flags |= EXFLAG_INVALID;
/* Handle CRL distribution point entries */
res = setup_crldp(x);
if (res == 0)
x->ex_flags |= EXFLAG_INVALID;
#ifndef OPENSSL_NO_RFC3779
x->rfc3779_addr = X509_get_ext_d2i(x, NID_sbgp_ipAddrBlock, &i, NULL);
if (x->rfc3779_addr == NULL && i != -1)
x->ex_flags |= EXFLAG_INVALID;
x->rfc3779_asid = X509_get_ext_d2i(x, NID_sbgp_autonomousSysNum, &i, NULL);
if (x->rfc3779_asid == NULL && i != -1)
x->ex_flags |= EXFLAG_INVALID;
#endif
for (i = 0; i < X509_get_ext_count(x); i++) {
X509_EXTENSION *ex = X509_get_ext(x, i);
int nid = OBJ_obj2nid(X509_EXTENSION_get_object(ex));
if (nid == NID_freshest_crl)
x->ex_flags |= EXFLAG_FRESHEST;
if (!X509_EXTENSION_get_critical(ex))
continue;
if (!X509_supported_extension(ex)) {
x->ex_flags |= EXFLAG_CRITICAL;
break;
}
switch (nid) {
case NID_basic_constraints:
x->ex_flags |= EXFLAG_BCONS_CRITICAL;
break;
case NID_authority_key_identifier:
x->ex_flags |= EXFLAG_AKID_CRITICAL;
break;
case NID_subject_key_identifier:
x->ex_flags |= EXFLAG_SKID_CRITICAL;
break;
case NID_subject_alt_name:
x->ex_flags |= EXFLAG_SAN_CRITICAL;
break;
default:
break;
}
}
/* Set x->siginf, ignoring errors due to unsupported algos */
(void)ossl_x509_init_sig_info(x);
x->ex_flags |= EXFLAG_SET; /* Indicate that cert has been processed */
#ifdef tsan_st_rel
tsan_st_rel((TSAN_QUALIFIER int *)&x->ex_cached, 1);
/*
* Above store triggers fast lock-free check in the beginning of the
* function. But one has to ensure that the structure is "stable", i.e.
* all stores are visible on all processors. Hence the release fence.
*/
#endif
ERR_pop_to_mark();
if ((x->ex_flags & EXFLAG_INVALID) == 0) {
CRYPTO_THREAD_unlock(x->lock);
return 1;
}
CRYPTO_THREAD_unlock(x->lock);
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_CERTIFICATE);
return 0;
}
/*-
* CA checks common to all purposes
* return codes:
* 0 not a CA
* 1 is a CA
* 2 Only possible in older versions of openSSL when basicConstraints are absent
* new versions will not return this value. May be a CA
* 3 basicConstraints absent but self-signed V1.
* 4 basicConstraints absent but keyUsage present and keyCertSign asserted.
* 5 Netscape specific CA Flags present
*/
static int check_ca(const X509 *x)
{
/* keyUsage if present should allow cert signing */
if (ku_reject(x, KU_KEY_CERT_SIGN))
return 0;
if ((x->ex_flags & EXFLAG_BCONS) != 0) {
/* If basicConstraints says not a CA then say so */
return (x->ex_flags & EXFLAG_CA) != 0;
} else {
/* We support V1 roots for... uh, I don't really know why. */
if ((x->ex_flags & V1_ROOT) == V1_ROOT)
return 3;
/*
* If key usage present it must have certSign so tolerate it
*/
else if ((x->ex_flags & EXFLAG_KUSAGE) != 0)
return 4;
/* Older certificates could have Netscape-specific CA types */
else if ((x->ex_flags & EXFLAG_NSCERT) != 0
&& (x->ex_nscert & NS_ANY_CA) != 0)
return 5;
/* Can this still be regarded a CA certificate? I doubt it. */
return 0;
}
}
void X509_set_proxy_flag(X509 *x)
{
if (CRYPTO_THREAD_write_lock(x->lock)) {
x->ex_flags |= EXFLAG_PROXY;
CRYPTO_THREAD_unlock(x->lock);
}
}
void X509_set_proxy_pathlen(X509 *x, long l)
{
x->ex_pcpathlen = l;
}
int X509_check_ca(X509 *x)
{
/* Note 0 normally means "not a CA" - but in this case means error. */
if (!ossl_x509v3_cache_extensions(x))
return 0;
return check_ca(x);
}
/* Check SSL CA: common checks for SSL client and server. */
static int check_ssl_ca(const X509 *x)
{
int ca_ret = check_ca(x);
if (ca_ret == 0)
return 0;
/* Check nsCertType if present */
return ca_ret != 5 || (x->ex_nscert & NS_SSL_CA) != 0;
}
static int check_purpose_ssl_client(const X509_PURPOSE *xp, const X509 *x,
int non_leaf)
{
if (xku_reject(x, XKU_SSL_CLIENT))
return 0;
if (non_leaf)
return check_ssl_ca(x);
/* We need to do digital signatures or key agreement */
if (ku_reject(x, KU_DIGITAL_SIGNATURE | KU_KEY_AGREEMENT))
return 0;
/* nsCertType if present should allow SSL client use */
if (ns_reject(x, NS_SSL_CLIENT))
return 0;
return 1;
}
/*
* Key usage needed for TLS/SSL server: digital signature, encipherment or
* key agreement. The ssl code can check this more thoroughly for individual
* key types.
*/
#define KU_TLS \
KU_DIGITAL_SIGNATURE | KU_KEY_ENCIPHERMENT | KU_KEY_AGREEMENT
static int check_purpose_ssl_server(const X509_PURPOSE *xp, const X509 *x,
int non_leaf)
{
if (xku_reject(x, XKU_SSL_SERVER | XKU_SGC))
return 0;
if (non_leaf)
return check_ssl_ca(x);
if (ns_reject(x, NS_SSL_SERVER))
return 0;
if (ku_reject(x, KU_TLS))
return 0;
return 1;
}
static int check_purpose_ns_ssl_server(const X509_PURPOSE *xp, const X509 *x,
int non_leaf)
{
int ret = check_purpose_ssl_server(xp, x, non_leaf);
if (!ret || non_leaf)
return ret;
/* We need to encipher or Netscape complains */
return ku_reject(x, KU_KEY_ENCIPHERMENT) ? 0 : ret;
}
/* common S/MIME checks */
static int purpose_smime(const X509 *x, int non_leaf)
{
if (xku_reject(x, XKU_SMIME))
return 0;
if (non_leaf) {
int ca_ret = check_ca(x);
if (ca_ret == 0)
return 0;
/* Check nsCertType if present */
if (ca_ret != 5 || (x->ex_nscert & NS_SMIME_CA) != 0)
return ca_ret;
else
return 0;
}
if ((x->ex_flags & EXFLAG_NSCERT) != 0) {
if ((x->ex_nscert & NS_SMIME) != 0)
return 1;
/* Workaround for some buggy certificates */
return (x->ex_nscert & NS_SSL_CLIENT) != 0 ? 2 : 0;
}
return 1;
}
static int check_purpose_smime_sign(const X509_PURPOSE *xp, const X509 *x,
int non_leaf)
{
int ret = purpose_smime(x, non_leaf);
if (!ret || non_leaf)
return ret;
return ku_reject(x, KU_DIGITAL_SIGNATURE | KU_NON_REPUDIATION) ? 0 : ret;
}
static int check_purpose_smime_encrypt(const X509_PURPOSE *xp, const X509 *x,
int non_leaf)
{
int ret = purpose_smime(x, non_leaf);
if (!ret || non_leaf)
return ret;
return ku_reject(x, KU_KEY_ENCIPHERMENT) ? 0 : ret;
}
static int check_purpose_crl_sign(const X509_PURPOSE *xp, const X509 *x,
int non_leaf)
{
if (non_leaf) {
int ca_ret = check_ca(x);
return ca_ret == 2 ? 0 : ca_ret;
}
return !ku_reject(x, KU_CRL_SIGN);
}
/*
* OCSP helper: this is *not* a full OCSP check. It just checks that each CA
* is valid. Additional checks must be made on the chain.
*/
static int check_purpose_ocsp_helper(const X509_PURPOSE *xp, const X509 *x,
int non_leaf)
{
/*
* Must be a valid CA. Should we really support the "I don't know" value
* (2)?
*/
if (non_leaf)
return check_ca(x);
/* Leaf certificate is checked in OCSP_verify() */
return 1;
}
static int check_purpose_timestamp_sign(const X509_PURPOSE *xp, const X509 *x,
int non_leaf)
{
int i_ext;
/*
* If non_leaf is true we must check if this is a valid CA certificate.
* The extra requirements by the CA/Browser Forum are not checked.
*/
if (non_leaf)
return check_ca(x);
/*
* Key Usage is checked according to RFC 5280 and
* Extended Key Usage attributes is checked according to RFC 3161.
* The extra (and somewhat conflicting) CA/Browser Forum
* Baseline Requirements for the Issuance and Management of
* Publicly‐Trusted Code Signing Certificates, Version 3.0.0,
* Section 7.1.2.3: Code signing and Timestamp Certificate are not checked.
*/
/*
* Check the optional key usage field:
* if Key Usage is present, it must be one of digitalSignature
* and/or nonRepudiation (other values are not consistent and shall
* be rejected).
*/
if ((x->ex_flags & EXFLAG_KUSAGE) != 0
&& ((x->ex_kusage & ~(KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE)) ||
!(x->ex_kusage & (KU_NON_REPUDIATION | KU_DIGITAL_SIGNATURE))))
return 0;
/* Only timestamp key usage is permitted and it's required. */
if ((x->ex_flags & EXFLAG_XKUSAGE) == 0 || x->ex_xkusage != XKU_TIMESTAMP)
return 0;
/* Extended Key Usage MUST be critical */
i_ext = X509_get_ext_by_NID(x, NID_ext_key_usage, -1);
if (i_ext >= 0
&& !X509_EXTENSION_get_critical(X509_get_ext((X509 *)x, i_ext)))
return 0;
return 1;
}
static int check_purpose_code_sign(const X509_PURPOSE *xp, const X509 *x,
int non_leaf)
{
int i_ext;
/*
* If non_leaf is true we must check if this is a valid CA certificate.
* The extra requirements by the CA/Browser Forum are not checked.
*/
if (non_leaf)
return check_ca(x);
/*
* Check the key usage and extended key usage fields:
*
* Reference: CA/Browser Forum,
* Baseline Requirements for the Issuance and Management of
* Publicly‐Trusted Code Signing Certificates, Version 3.0.0,
* Section 7.1.2.3: Code signing and Timestamp Certificate
*
* Checking covers Key Usage and Extended Key Usage attributes.
* The certificatePolicies, cRLDistributionPoints (CDP), and
* authorityInformationAccess (AIA) extensions are so far not checked.
*/
/* Key Usage */
if ((x->ex_flags & EXFLAG_KUSAGE) == 0)
return 0;
if ((x->ex_kusage & KU_DIGITAL_SIGNATURE) == 0)
return 0;
if ((x->ex_kusage & (KU_KEY_CERT_SIGN | KU_CRL_SIGN)) != 0)
return 0;
/* Key Usage MUST be critical */
i_ext = X509_get_ext_by_NID(x, NID_key_usage, -1);
if (i_ext < 0)
return 0;
if (i_ext >= 0) {
X509_EXTENSION *ext = X509_get_ext((X509 *)x, i_ext);
if (!X509_EXTENSION_get_critical(ext))
return 0;
}
/* Extended Key Usage */
if ((x->ex_flags & EXFLAG_XKUSAGE) == 0)
return 0;
if ((x->ex_xkusage & XKU_CODE_SIGN) == 0)
return 0;
if ((x->ex_xkusage & (XKU_ANYEKU | XKU_SSL_SERVER)) != 0)
return 0;
return 1;
}
static int no_check_purpose(const X509_PURPOSE *xp, const X509 *x,
int non_leaf)
{
return 1;
}
/*-
* Various checks to see if one certificate potentially issued the second.
* This can be used to prune a set of possible issuer certificates which
* have been looked up using some simple method such as by subject name.
* These are:
* 1. issuer_name(subject) == subject_name(issuer)
* 2. If akid(subject) exists, it matches the respective issuer fields.
* 3. subject signature algorithm == issuer public key algorithm
* 4. If key_usage(issuer) exists, it allows for signing subject.
* Note that this does not include actually checking the signature.
* Returns 0 for OK, or positive for reason for mismatch
* where reason codes match those for X509_verify_cert().
*/
int X509_check_issued(X509 *issuer, X509 *subject)
{
int ret;
if ((ret = ossl_x509_likely_issued(issuer, subject)) != X509_V_OK)
return ret;
return ossl_x509_signing_allowed(issuer, subject);
}
/* do the checks 1., 2., and 3. as described above for X509_check_issued() */
int ossl_x509_likely_issued(X509 *issuer, X509 *subject)
{
int ret;
if (X509_NAME_cmp(X509_get_subject_name(issuer),
X509_get_issuer_name(subject)) != 0)
return X509_V_ERR_SUBJECT_ISSUER_MISMATCH;
/* set issuer->skid and subject->akid */
if (!ossl_x509v3_cache_extensions(issuer)
|| !ossl_x509v3_cache_extensions(subject))
return X509_V_ERR_UNSPECIFIED;
ret = X509_check_akid(issuer, subject->akid);
if (ret != X509_V_OK)
return ret;
/* Check if the subject signature alg matches the issuer's PUBKEY alg */
return check_sig_alg_match(X509_get0_pubkey(issuer), subject);
}
/*-
* Check if certificate I<issuer> is allowed to issue certificate I<subject>
* according to the B<keyUsage> field of I<issuer> if present
* depending on any proxyCertInfo extension of I<subject>.
* Returns 0 for OK, or positive for reason for rejection
* where reason codes match those for X509_verify_cert().
*/
int ossl_x509_signing_allowed(const X509 *issuer, const X509 *subject)
{
if ((subject->ex_flags & EXFLAG_PROXY) != 0) {
if (ku_reject(issuer, KU_DIGITAL_SIGNATURE))
return X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE;
} else if (ku_reject(issuer, KU_KEY_CERT_SIGN)) {
return X509_V_ERR_KEYUSAGE_NO_CERTSIGN;
}
return X509_V_OK;
}
int X509_check_akid(const X509 *issuer, const AUTHORITY_KEYID *akid)
{
if (akid == NULL)
return X509_V_OK;
/* Check key ids (if present) */
if (akid->keyid && issuer->skid &&
ASN1_OCTET_STRING_cmp(akid->keyid, issuer->skid))
return X509_V_ERR_AKID_SKID_MISMATCH;
/* Check serial number */
if (akid->serial &&
ASN1_INTEGER_cmp(X509_get0_serialNumber(issuer), akid->serial))
return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
/* Check issuer name */
if (akid->issuer) {
/*
* Ugh, for some peculiar reason AKID includes SEQUENCE OF
* GeneralName. So look for a DirName. There may be more than one but
* we only take any notice of the first.
*/
GENERAL_NAMES *gens = akid->issuer;
GENERAL_NAME *gen;
X509_NAME *nm = NULL;
int i;
for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
gen = sk_GENERAL_NAME_value(gens, i);
if (gen->type == GEN_DIRNAME) {
nm = gen->d.dirn;
break;
}
}
if (nm != NULL && X509_NAME_cmp(nm, X509_get_issuer_name(issuer)) != 0)
return X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH;
}
return X509_V_OK;
}
uint32_t X509_get_extension_flags(X509 *x)
{
/* Call for side-effect of computing hash and caching extensions */
X509_check_purpose(x, -1, 0);
return x->ex_flags;
}
uint32_t X509_get_key_usage(X509 *x)
{
/* Call for side-effect of computing hash and caching extensions */
if (X509_check_purpose(x, -1, 0) != 1)
return 0;
return (x->ex_flags & EXFLAG_KUSAGE) != 0 ? x->ex_kusage : UINT32_MAX;
}
uint32_t X509_get_extended_key_usage(X509 *x)
{
/* Call for side-effect of computing hash and caching extensions */
if (X509_check_purpose(x, -1, 0) != 1)
return 0;
return (x->ex_flags & EXFLAG_XKUSAGE) != 0 ? x->ex_xkusage : UINT32_MAX;
}
const ASN1_OCTET_STRING *X509_get0_subject_key_id(X509 *x)
{
/* Call for side-effect of computing hash and caching extensions */
if (X509_check_purpose(x, -1, 0) != 1)
return NULL;
return x->skid;
}
const ASN1_OCTET_STRING *X509_get0_authority_key_id(X509 *x)
{
/* Call for side-effect of computing hash and caching extensions */
if (X509_check_purpose(x, -1, 0) != 1)
return NULL;
return (x->akid != NULL ? x->akid->keyid : NULL);
}
const GENERAL_NAMES *X509_get0_authority_issuer(X509 *x)
{
/* Call for side-effect of computing hash and caching extensions */
if (X509_check_purpose(x, -1, 0) != 1)
return NULL;
return (x->akid != NULL ? x->akid->issuer : NULL);
}
const ASN1_INTEGER *X509_get0_authority_serial(X509 *x)
{
/* Call for side-effect of computing hash and caching extensions */
if (X509_check_purpose(x, -1, 0) != 1)
return NULL;
return (x->akid != NULL ? x->akid->serial : NULL);
}
long X509_get_pathlen(X509 *x)
{
/* Called for side effect of caching extensions */
if (X509_check_purpose(x, -1, 0) != 1
|| (x->ex_flags & EXFLAG_BCONS) == 0)
return -1;
return x->ex_pathlen;
}
long X509_get_proxy_pathlen(X509 *x)
{
/* Called for side effect of caching extensions */
if (X509_check_purpose(x, -1, 0) != 1
|| (x->ex_flags & EXFLAG_PROXY) == 0)
return -1;
return x->ex_pcpathlen;
}
|
./openssl/crypto/x509/by_file.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/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)
{
BIO *in = NULL;
int 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_BIO_LIB);
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();
if (count == 0) {
ERR_raise(ERR_LIB_X509, X509_R_NO_CERTIFICATE_FOUND);
} else {
ERR_raise(ERR_LIB_X509, ERR_R_PEM_LIB);
count = 0;
}
goto err;
}
}
ERR_clear_last_mark();
if (!X509_STORE_add_cert(ctx->store_ctx, x)) {
count = 0;
goto err;
}
/*
* X509_STORE_add_cert() added a reference rather than a copy,
* so we need a fresh X509 object.
*/
X509_free(x);
x = X509_new_ex(libctx, propq);
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
count = 0;
goto err;
}
count++;
}
} else if (type == X509_FILETYPE_ASN1) {
if (d2i_X509_bio(in, &x) == NULL) {
ERR_raise(ERR_LIB_X509, X509_R_NO_CERTIFICATE_FOUND);
goto err;
}
count = X509_STORE_add_cert(ctx->store_ctx, x);
} else {
ERR_raise(ERR_LIB_X509, X509_R_BAD_X509_FILETYPE);
goto err;
}
err:
X509_free(x);
BIO_free(in);
return count;
}
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)
{
BIO *in = NULL;
int 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_BIO_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 {
if (count == 0) {
ERR_raise(ERR_LIB_X509, X509_R_NO_CRL_FOUND);
} else {
ERR_raise(ERR_LIB_X509, ERR_R_PEM_LIB);
count = 0;
}
goto err;
}
}
if (!X509_STORE_add_crl(ctx->store_ctx, x)) {
count = 0;
goto err;
}
count++;
}
} else if (type == X509_FILETYPE_ASN1) {
x = d2i_X509_CRL_bio(in, NULL);
if (x == NULL) {
ERR_raise(ERR_LIB_X509, X509_R_NO_CRL_FOUND);
goto err;
}
count = X509_STORE_add_crl(ctx->store_ctx, x);
} else {
ERR_raise(ERR_LIB_X509, X509_R_BAD_X509_FILETYPE);
goto err;
}
err:
X509_CRL_free(x);
BIO_free(in);
return count;
}
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 = NULL;
X509_INFO *itmp = NULL;
BIO *in = NULL;
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 == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_BIO_LIB);
return 0;
}
inf = PEM_X509_INFO_read_bio_ex(in, NULL, NULL, "", libctx, propq);
BIO_free(in);
if (inf == NULL) {
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)) {
count = 0;
goto err;
}
count++;
}
if (itmp->crl) {
if (!X509_STORE_add_crl(ctx->store_ctx, itmp->crl)) {
count = 0;
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);
}
|
./openssl/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
|
./openssl/crypto/x509/v3_group_ac.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
*/
#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_GROUP_AC(X509V3_EXT_METHOD *method,
void *su, BIO *out,
int indent)
{
return 1;
}
static void *r2i_GROUP_AC(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, const char *value)
{
return ASN1_NULL_new();
}
static char *i2s_GROUP_AC(const X509V3_EXT_METHOD *method, void *val)
{
return OPENSSL_strdup("NULL");
}
static void *s2i_GROUP_AC(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *str)
{
return ASN1_NULL_new();
}
/*
* The groupAC X.509v3 extension is defined in ITU Recommendation X.509
* (2019), Section 17.1.2.6. See: https://www.itu.int/rec/T-REC-X.509-201910-I/en.
*/
const X509V3_EXT_METHOD ossl_v3_group_ac = {
NID_group_ac, 0, ASN1_ITEM_ref(ASN1_NULL),
0, 0, 0, 0,
(X509V3_EXT_I2S)i2s_GROUP_AC,
(X509V3_EXT_S2I)s2i_GROUP_AC,
0, 0,
(X509V3_EXT_I2R)i2r_GROUP_AC,
(X509V3_EXT_R2I)r2i_GROUP_AC,
NULL
};
|
./openssl/crypto/x509/v3_utl.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
*/
/* X509 v3 extension utilities */
#include "internal/e_os.h"
#include "internal/cryptlib.h"
#include <stdio.h>
#include <string.h>
#include "crypto/ctype.h"
#include <openssl/conf.h>
#include <openssl/crypto.h>
#include <openssl/x509v3.h>
#include "crypto/x509.h"
#include <openssl/bn.h>
#include "ext_dat.h"
#include "x509_local.h"
static char *strip_spaces(char *name);
static int sk_strcmp(const char *const *a, const char *const *b);
static STACK_OF(OPENSSL_STRING) *get_email(const X509_NAME *name,
GENERAL_NAMES *gens);
static void str_free(OPENSSL_STRING str);
static int append_ia5(STACK_OF(OPENSSL_STRING) **sk,
const ASN1_IA5STRING *email);
static int ipv4_from_asc(unsigned char *v4, const char *in);
static int ipv6_from_asc(unsigned char *v6, const char *in);
static int ipv6_cb(const char *elem, int len, void *usr);
static int ipv6_hex(unsigned char *out, const char *in, int inlen);
/* Add a CONF_VALUE name value pair to stack */
static int x509v3_add_len_value(const char *name, const char *value,
size_t vallen, STACK_OF(CONF_VALUE) **extlist)
{
CONF_VALUE *vtmp = NULL;
char *tname = NULL, *tvalue = NULL;
int sk_allocated = (*extlist == NULL);
if (name != NULL && (tname = OPENSSL_strdup(name)) == NULL)
goto err;
if (value != NULL) {
/* We don't allow embedded NUL characters */
if (memchr(value, 0, vallen) != NULL)
goto err;
tvalue = OPENSSL_strndup(value, vallen);
if (tvalue == NULL)
goto err;
}
if ((vtmp = OPENSSL_malloc(sizeof(*vtmp))) == NULL)
goto err;
if (sk_allocated && (*extlist = sk_CONF_VALUE_new_null()) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
goto err;
}
vtmp->section = NULL;
vtmp->name = tname;
vtmp->value = tvalue;
if (!sk_CONF_VALUE_push(*extlist, vtmp))
goto err;
return 1;
err:
if (sk_allocated) {
sk_CONF_VALUE_free(*extlist);
*extlist = NULL;
}
OPENSSL_free(vtmp);
OPENSSL_free(tname);
OPENSSL_free(tvalue);
return 0;
}
int X509V3_add_value(const char *name, const char *value,
STACK_OF(CONF_VALUE) **extlist)
{
return x509v3_add_len_value(name, value,
value != NULL ? strlen((const char *)value) : 0,
extlist);
}
int X509V3_add_value_uchar(const char *name, const unsigned char *value,
STACK_OF(CONF_VALUE) **extlist)
{
return x509v3_add_len_value(name, (const char *)value,
value != NULL ? strlen((const char *)value) : 0,
extlist);
}
int x509v3_add_len_value_uchar(const char *name, const unsigned char *value,
size_t vallen, STACK_OF(CONF_VALUE) **extlist)
{
return x509v3_add_len_value(name, (const char *)value, vallen, extlist);
}
/* Free function for STACK_OF(CONF_VALUE) */
void X509V3_conf_free(CONF_VALUE *conf)
{
if (!conf)
return;
OPENSSL_free(conf->name);
OPENSSL_free(conf->value);
OPENSSL_free(conf->section);
OPENSSL_free(conf);
}
int X509V3_add_value_bool(const char *name, int asn1_bool,
STACK_OF(CONF_VALUE) **extlist)
{
if (asn1_bool)
return X509V3_add_value(name, "TRUE", extlist);
return X509V3_add_value(name, "FALSE", extlist);
}
int X509V3_add_value_bool_nf(const char *name, int asn1_bool,
STACK_OF(CONF_VALUE) **extlist)
{
if (asn1_bool)
return X509V3_add_value(name, "TRUE", extlist);
return 1;
}
static char *bignum_to_string(const BIGNUM *bn)
{
char *tmp, *ret;
size_t len;
/*
* Display large numbers in hex and small numbers in decimal. Converting to
* decimal takes quadratic time and is no more useful than hex for large
* numbers.
*/
if (BN_num_bits(bn) < 128)
return BN_bn2dec(bn);
tmp = BN_bn2hex(bn);
if (tmp == NULL)
return NULL;
len = strlen(tmp) + 3;
ret = OPENSSL_malloc(len);
if (ret == NULL) {
OPENSSL_free(tmp);
return NULL;
}
/* Prepend "0x", but place it after the "-" if negative. */
if (tmp[0] == '-') {
OPENSSL_strlcpy(ret, "-0x", len);
OPENSSL_strlcat(ret, tmp + 1, len);
} else {
OPENSSL_strlcpy(ret, "0x", len);
OPENSSL_strlcat(ret, tmp, len);
}
OPENSSL_free(tmp);
return ret;
}
char *i2s_ASN1_ENUMERATED(X509V3_EXT_METHOD *method, const ASN1_ENUMERATED *a)
{
BIGNUM *bntmp = NULL;
char *strtmp = NULL;
if (!a)
return NULL;
if ((bntmp = ASN1_ENUMERATED_to_BN(a, NULL)) == NULL)
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
else if ((strtmp = bignum_to_string(bntmp)) == NULL)
ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB);
BN_free(bntmp);
return strtmp;
}
char *i2s_ASN1_INTEGER(X509V3_EXT_METHOD *method, const ASN1_INTEGER *a)
{
BIGNUM *bntmp = NULL;
char *strtmp = NULL;
if (!a)
return NULL;
if ((bntmp = ASN1_INTEGER_to_BN(a, NULL)) == NULL)
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
else if ((strtmp = bignum_to_string(bntmp)) == NULL)
ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB);
BN_free(bntmp);
return strtmp;
}
ASN1_INTEGER *s2i_ASN1_INTEGER(X509V3_EXT_METHOD *method, const char *value)
{
BIGNUM *bn = NULL;
ASN1_INTEGER *aint;
int isneg, ishex;
int ret;
if (value == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NULL_VALUE);
return NULL;
}
bn = BN_new();
if (bn == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_BN_LIB);
return NULL;
}
if (value[0] == '-') {
value++;
isneg = 1;
} else {
isneg = 0;
}
if (value[0] == '0' && ((value[1] == 'x') || (value[1] == 'X'))) {
value += 2;
ishex = 1;
} else {
ishex = 0;
}
if (ishex)
ret = BN_hex2bn(&bn, value);
else
ret = BN_dec2bn(&bn, value);
if (!ret || value[ret]) {
BN_free(bn);
ERR_raise(ERR_LIB_X509V3, X509V3_R_BN_DEC2BN_ERROR);
return NULL;
}
if (isneg && BN_is_zero(bn))
isneg = 0;
aint = BN_to_ASN1_INTEGER(bn, NULL);
BN_free(bn);
if (!aint) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_BN_TO_ASN1_INTEGER_ERROR);
return NULL;
}
if (isneg)
aint->type |= V_ASN1_NEG;
return aint;
}
int X509V3_add_value_int(const char *name, const ASN1_INTEGER *aint,
STACK_OF(CONF_VALUE) **extlist)
{
char *strtmp;
int ret;
if (!aint)
return 1;
if ((strtmp = i2s_ASN1_INTEGER(NULL, aint)) == NULL)
return 0;
ret = X509V3_add_value(name, strtmp, extlist);
OPENSSL_free(strtmp);
return ret;
}
int X509V3_get_value_bool(const CONF_VALUE *value, int *asn1_bool)
{
const char *btmp;
if ((btmp = value->value) == NULL)
goto err;
if (strcmp(btmp, "TRUE") == 0
|| strcmp(btmp, "true") == 0
|| strcmp(btmp, "Y") == 0
|| strcmp(btmp, "y") == 0
|| strcmp(btmp, "YES") == 0
|| strcmp(btmp, "yes") == 0) {
*asn1_bool = 0xff;
return 1;
}
if (strcmp(btmp, "FALSE") == 0
|| strcmp(btmp, "false") == 0
|| strcmp(btmp, "N") == 0
|| strcmp(btmp, "n") == 0
|| strcmp(btmp, "NO") == 0
|| strcmp(btmp, "no") == 0) {
*asn1_bool = 0;
return 1;
}
err:
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_BOOLEAN_STRING);
X509V3_conf_add_error_name_value(value);
return 0;
}
int X509V3_get_value_int(const CONF_VALUE *value, ASN1_INTEGER **aint)
{
ASN1_INTEGER *itmp;
if ((itmp = s2i_ASN1_INTEGER(NULL, value->value)) == NULL) {
X509V3_conf_add_error_name_value(value);
return 0;
}
*aint = itmp;
return 1;
}
#define HDR_NAME 1
#define HDR_VALUE 2
/*
* #define DEBUG
*/
STACK_OF(CONF_VALUE) *X509V3_parse_list(const char *line)
{
char *p, *q, c;
char *ntmp, *vtmp;
STACK_OF(CONF_VALUE) *values = NULL;
char *linebuf;
int state;
/* We are going to modify the line so copy it first */
linebuf = OPENSSL_strdup(line);
if (linebuf == NULL)
goto err;
state = HDR_NAME;
ntmp = NULL;
/* Go through all characters */
for (p = linebuf, q = linebuf; (c = *p) && (c != '\r') && (c != '\n');
p++) {
switch (state) {
case HDR_NAME:
if (c == ':') {
state = HDR_VALUE;
*p = 0;
ntmp = strip_spaces(q);
if (!ntmp) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_EMPTY_NAME);
goto err;
}
q = p + 1;
} else if (c == ',') {
*p = 0;
ntmp = strip_spaces(q);
q = p + 1;
if (!ntmp) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_EMPTY_NAME);
goto err;
}
if (!X509V3_add_value(ntmp, NULL, &values)) {
goto err;
}
}
break;
case HDR_VALUE:
if (c == ',') {
state = HDR_NAME;
*p = 0;
vtmp = strip_spaces(q);
if (!vtmp) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NULL_VALUE);
goto err;
}
if (!X509V3_add_value(ntmp, vtmp, &values)) {
goto err;
}
ntmp = NULL;
q = p + 1;
}
}
}
if (state == HDR_VALUE) {
vtmp = strip_spaces(q);
if (!vtmp) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_NULL_VALUE);
goto err;
}
if (!X509V3_add_value(ntmp, vtmp, &values)) {
goto err;
}
} else {
ntmp = strip_spaces(q);
if (!ntmp) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_EMPTY_NAME);
goto err;
}
if (!X509V3_add_value(ntmp, NULL, &values)) {
goto err;
}
}
OPENSSL_free(linebuf);
return values;
err:
OPENSSL_free(linebuf);
sk_CONF_VALUE_pop_free(values, X509V3_conf_free);
return NULL;
}
/* Delete leading and trailing spaces from a string */
static char *strip_spaces(char *name)
{
char *p, *q;
/* Skip over leading spaces */
p = name;
while (*p && ossl_isspace(*p))
p++;
if (*p == '\0')
return NULL;
q = p + strlen(p) - 1;
while ((q != p) && ossl_isspace(*q))
q--;
if (p != q)
q[1] = 0;
if (*p == '\0')
return NULL;
return p;
}
/*
* V2I name comparison function: returns zero if 'name' matches cmp or cmp.*
*/
int ossl_v3_name_cmp(const char *name, const char *cmp)
{
int len, ret;
char c;
len = strlen(cmp);
if ((ret = strncmp(name, cmp, len)))
return ret;
c = name[len];
if (!c || (c == '.'))
return 0;
return 1;
}
static int sk_strcmp(const char *const *a, const char *const *b)
{
return strcmp(*a, *b);
}
STACK_OF(OPENSSL_STRING) *X509_get1_email(X509 *x)
{
GENERAL_NAMES *gens;
STACK_OF(OPENSSL_STRING) *ret;
gens = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
ret = get_email(X509_get_subject_name(x), gens);
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
return ret;
}
STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(X509 *x)
{
AUTHORITY_INFO_ACCESS *info;
STACK_OF(OPENSSL_STRING) *ret = NULL;
int i;
info = X509_get_ext_d2i(x, NID_info_access, NULL, NULL);
if (!info)
return NULL;
for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
if (OBJ_obj2nid(ad->method) == NID_ad_OCSP) {
if (ad->location->type == GEN_URI) {
if (!append_ia5
(&ret, ad->location->d.uniformResourceIdentifier))
break;
}
}
}
AUTHORITY_INFO_ACCESS_free(info);
return ret;
}
STACK_OF(OPENSSL_STRING) *X509_REQ_get1_email(X509_REQ *x)
{
GENERAL_NAMES *gens;
STACK_OF(X509_EXTENSION) *exts;
STACK_OF(OPENSSL_STRING) *ret;
exts = X509_REQ_get_extensions(x);
gens = X509V3_get_d2i(exts, NID_subject_alt_name, NULL, NULL);
ret = get_email(X509_REQ_get_subject_name(x), gens);
sk_GENERAL_NAME_pop_free(gens, GENERAL_NAME_free);
sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
return ret;
}
static STACK_OF(OPENSSL_STRING) *get_email(const X509_NAME *name,
GENERAL_NAMES *gens)
{
STACK_OF(OPENSSL_STRING) *ret = NULL;
X509_NAME_ENTRY *ne;
const ASN1_IA5STRING *email;
GENERAL_NAME *gen;
int i = -1;
/* Now add any email address(es) to STACK */
/* First supplied X509_NAME */
while ((i = X509_NAME_get_index_by_NID(name,
NID_pkcs9_emailAddress, i)) >= 0) {
ne = X509_NAME_get_entry(name, i);
email = X509_NAME_ENTRY_get_data(ne);
if (!append_ia5(&ret, email))
return NULL;
}
for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
gen = sk_GENERAL_NAME_value(gens, i);
if (gen->type != GEN_EMAIL)
continue;
if (!append_ia5(&ret, gen->d.ia5))
return NULL;
}
return ret;
}
static void str_free(OPENSSL_STRING str)
{
OPENSSL_free(str);
}
static int append_ia5(STACK_OF(OPENSSL_STRING) **sk,
const ASN1_IA5STRING *email)
{
char *emtmp;
/* First some sanity checks */
if (email->type != V_ASN1_IA5STRING)
return 1;
if (email->data == NULL || email->length == 0)
return 1;
if (memchr(email->data, 0, email->length) != NULL)
return 1;
if (*sk == NULL)
*sk = sk_OPENSSL_STRING_new(sk_strcmp);
if (*sk == NULL)
return 0;
emtmp = OPENSSL_strndup((char *)email->data, email->length);
if (emtmp == NULL) {
X509_email_free(*sk);
*sk = NULL;
return 0;
}
/* Don't add duplicates */
if (sk_OPENSSL_STRING_find(*sk, emtmp) != -1) {
OPENSSL_free(emtmp);
return 1;
}
if (!sk_OPENSSL_STRING_push(*sk, emtmp)) {
OPENSSL_free(emtmp); /* free on push failure */
X509_email_free(*sk);
*sk = NULL;
return 0;
}
return 1;
}
void X509_email_free(STACK_OF(OPENSSL_STRING) *sk)
{
sk_OPENSSL_STRING_pop_free(sk, str_free);
}
typedef int (*equal_fn) (const unsigned char *pattern, size_t pattern_len,
const unsigned char *subject, size_t subject_len,
unsigned int flags);
/* Skip pattern prefix to match "wildcard" subject */
static void skip_prefix(const unsigned char **p, size_t *plen,
size_t subject_len,
unsigned int flags)
{
const unsigned char *pattern = *p;
size_t pattern_len = *plen;
/*
* If subject starts with a leading '.' followed by more octets, and
* pattern is longer, compare just an equal-length suffix with the
* full subject (starting at the '.'), provided the prefix contains
* no NULs.
*/
if ((flags & _X509_CHECK_FLAG_DOT_SUBDOMAINS) == 0)
return;
while (pattern_len > subject_len && *pattern) {
if ((flags & X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS) &&
*pattern == '.')
break;
++pattern;
--pattern_len;
}
/* Skip if entire prefix acceptable */
if (pattern_len == subject_len) {
*p = pattern;
*plen = pattern_len;
}
}
/* Compare while ASCII ignoring case. */
static int equal_nocase(const unsigned char *pattern, size_t pattern_len,
const unsigned char *subject, size_t subject_len,
unsigned int flags)
{
skip_prefix(&pattern, &pattern_len, subject_len, flags);
if (pattern_len != subject_len)
return 0;
while (pattern_len != 0) {
unsigned char l = *pattern;
unsigned char r = *subject;
/* The pattern must not contain NUL characters. */
if (l == 0)
return 0;
if (l != r) {
if ('A' <= l && l <= 'Z')
l = (l - 'A') + 'a';
if ('A' <= r && r <= 'Z')
r = (r - 'A') + 'a';
if (l != r)
return 0;
}
++pattern;
++subject;
--pattern_len;
}
return 1;
}
/* Compare using memcmp. */
static int equal_case(const unsigned char *pattern, size_t pattern_len,
const unsigned char *subject, size_t subject_len,
unsigned int flags)
{
skip_prefix(&pattern, &pattern_len, subject_len, flags);
if (pattern_len != subject_len)
return 0;
return !memcmp(pattern, subject, pattern_len);
}
/*
* RFC 5280, section 7.5, requires that only the domain is compared in a
* case-insensitive manner.
*/
static int equal_email(const unsigned char *a, size_t a_len,
const unsigned char *b, size_t b_len,
unsigned int unused_flags)
{
size_t i = a_len;
if (a_len != b_len)
return 0;
/*
* We search backwards for the '@' character, so that we do not have to
* deal with quoted local-parts. The domain part is compared in a
* case-insensitive manner.
*/
while (i > 0) {
--i;
if (a[i] == '@' || b[i] == '@') {
if (!equal_nocase(a + i, a_len - i, b + i, a_len - i, 0))
return 0;
break;
}
}
if (i == 0)
i = a_len;
return equal_case(a, i, b, i, 0);
}
/*
* Compare the prefix and suffix with the subject, and check that the
* characters in-between are valid.
*/
static int wildcard_match(const unsigned char *prefix, size_t prefix_len,
const unsigned char *suffix, size_t suffix_len,
const unsigned char *subject, size_t subject_len,
unsigned int flags)
{
const unsigned char *wildcard_start;
const unsigned char *wildcard_end;
const unsigned char *p;
int allow_multi = 0;
int allow_idna = 0;
if (subject_len < prefix_len + suffix_len)
return 0;
if (!equal_nocase(prefix, prefix_len, subject, prefix_len, flags))
return 0;
wildcard_start = subject + prefix_len;
wildcard_end = subject + (subject_len - suffix_len);
if (!equal_nocase(wildcard_end, suffix_len, suffix, suffix_len, flags))
return 0;
/*
* If the wildcard makes up the entire first label, it must match at
* least one character.
*/
if (prefix_len == 0 && *suffix == '.') {
if (wildcard_start == wildcard_end)
return 0;
allow_idna = 1;
if (flags & X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS)
allow_multi = 1;
}
/* IDNA labels cannot match partial wildcards */
if (!allow_idna &&
subject_len >= 4 && HAS_CASE_PREFIX((const char *)subject, "xn--"))
return 0;
/* The wildcard may match a literal '*' */
if (wildcard_end == wildcard_start + 1 && *wildcard_start == '*')
return 1;
/*
* Check that the part matched by the wildcard contains only
* permitted characters and only matches a single label unless
* allow_multi is set.
*/
for (p = wildcard_start; p != wildcard_end; ++p)
if (!(('0' <= *p && *p <= '9') ||
('A' <= *p && *p <= 'Z') ||
('a' <= *p && *p <= 'z') ||
*p == '-' || (allow_multi && *p == '.')))
return 0;
return 1;
}
#define LABEL_START (1 << 0)
#define LABEL_END (1 << 1)
#define LABEL_HYPHEN (1 << 2)
#define LABEL_IDNA (1 << 3)
static const unsigned char *valid_star(const unsigned char *p, size_t len,
unsigned int flags)
{
const unsigned char *star = 0;
size_t i;
int state = LABEL_START;
int dots = 0;
for (i = 0; i < len; ++i) {
/*
* Locate first and only legal wildcard, either at the start
* or end of a non-IDNA first and not final label.
*/
if (p[i] == '*') {
int atstart = (state & LABEL_START);
int atend = (i == len - 1 || p[i + 1] == '.');
/*-
* At most one wildcard per pattern.
* No wildcards in IDNA labels.
* No wildcards after the first label.
*/
if (star != NULL || (state & LABEL_IDNA) != 0 || dots)
return NULL;
/* Only full-label '*.example.com' wildcards? */
if ((flags & X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS)
&& (!atstart || !atend))
return NULL;
/* No 'foo*bar' wildcards */
if (!atstart && !atend)
return NULL;
star = &p[i];
state &= ~LABEL_START;
} else if (('a' <= p[i] && p[i] <= 'z')
|| ('A' <= p[i] && p[i] <= 'Z')
|| ('0' <= p[i] && p[i] <= '9')) {
if ((state & LABEL_START) != 0
&& len - i >= 4 && HAS_CASE_PREFIX((const char *)&p[i], "xn--"))
state |= LABEL_IDNA;
state &= ~(LABEL_HYPHEN | LABEL_START);
} else if (p[i] == '.') {
if ((state & (LABEL_HYPHEN | LABEL_START)) != 0)
return NULL;
state = LABEL_START;
++dots;
} else if (p[i] == '-') {
/* no domain/subdomain starts with '-' */
if ((state & LABEL_START) != 0)
return NULL;
state |= LABEL_HYPHEN;
} else {
return NULL;
}
}
/*
* The final label must not end in a hyphen or ".", and
* there must be at least two dots after the star.
*/
if ((state & (LABEL_START | LABEL_HYPHEN)) != 0 || dots < 2)
return NULL;
return star;
}
/* Compare using wildcards. */
static int equal_wildcard(const unsigned char *pattern, size_t pattern_len,
const unsigned char *subject, size_t subject_len,
unsigned int flags)
{
const unsigned char *star = NULL;
/*
* Subject names starting with '.' can only match a wildcard pattern
* via a subject sub-domain pattern suffix match.
*/
if (!(subject_len > 1 && subject[0] == '.'))
star = valid_star(pattern, pattern_len, flags);
if (star == NULL)
return equal_nocase(pattern, pattern_len,
subject, subject_len, flags);
return wildcard_match(pattern, star - pattern,
star + 1, (pattern + pattern_len) - star - 1,
subject, subject_len, flags);
}
/*
* Compare an ASN1_STRING to a supplied string. If they match return 1. If
* cmp_type > 0 only compare if string matches the type, otherwise convert it
* to UTF8.
*/
static int do_check_string(const ASN1_STRING *a, int cmp_type, equal_fn equal,
unsigned int flags, const char *b, size_t blen,
char **peername)
{
int rv = 0;
if (!a->data || !a->length)
return 0;
if (cmp_type > 0) {
if (cmp_type != a->type)
return 0;
if (cmp_type == V_ASN1_IA5STRING)
rv = equal(a->data, a->length, (unsigned char *)b, blen, flags);
else if (a->length == (int)blen && !memcmp(a->data, b, blen))
rv = 1;
if (rv > 0 && peername != NULL) {
*peername = OPENSSL_strndup((char *)a->data, a->length);
if (*peername == NULL)
return -1;
}
} else {
int astrlen;
unsigned char *astr;
astrlen = ASN1_STRING_to_UTF8(&astr, a);
if (astrlen < 0) {
/*
* -1 could be an internal malloc failure or a decoding error from
* malformed input; we can't distinguish.
*/
return -1;
}
rv = equal(astr, astrlen, (unsigned char *)b, blen, flags);
if (rv > 0 && peername != NULL) {
*peername = OPENSSL_strndup((char *)astr, astrlen);
if (*peername == NULL) {
OPENSSL_free(astr);
return -1;
}
}
OPENSSL_free(astr);
}
return rv;
}
static int do_x509_check(X509 *x, const char *chk, size_t chklen,
unsigned int flags, int check_type, char **peername)
{
GENERAL_NAMES *gens = NULL;
const X509_NAME *name = NULL;
int i;
int cnid = NID_undef;
int alt_type;
int san_present = 0;
int rv = 0;
equal_fn equal;
/* See below, this flag is internal-only */
flags &= ~_X509_CHECK_FLAG_DOT_SUBDOMAINS;
if (check_type == GEN_EMAIL) {
cnid = NID_pkcs9_emailAddress;
alt_type = V_ASN1_IA5STRING;
equal = equal_email;
} else if (check_type == GEN_DNS) {
cnid = NID_commonName;
/* Implicit client-side DNS sub-domain pattern */
if (chklen > 1 && chk[0] == '.')
flags |= _X509_CHECK_FLAG_DOT_SUBDOMAINS;
alt_type = V_ASN1_IA5STRING;
if (flags & X509_CHECK_FLAG_NO_WILDCARDS)
equal = equal_nocase;
else
equal = equal_wildcard;
} else {
alt_type = V_ASN1_OCTET_STRING;
equal = equal_case;
}
if (chklen == 0)
chklen = strlen(chk);
gens = X509_get_ext_d2i(x, NID_subject_alt_name, NULL, NULL);
if (gens) {
for (i = 0; i < sk_GENERAL_NAME_num(gens); i++) {
GENERAL_NAME *gen;
ASN1_STRING *cstr;
gen = sk_GENERAL_NAME_value(gens, i);
if ((gen->type == GEN_OTHERNAME) && (check_type == GEN_EMAIL)) {
if (OBJ_obj2nid(gen->d.otherName->type_id) ==
NID_id_on_SmtpUTF8Mailbox) {
san_present = 1;
/*
* If it is not a UTF8String then that is unexpected and we
* treat it as no match
*/
if (gen->d.otherName->value->type == V_ASN1_UTF8STRING) {
cstr = gen->d.otherName->value->value.utf8string;
/* Positive on success, negative on error! */
if ((rv = do_check_string(cstr, 0, equal, flags,
chk, chklen, peername)) != 0)
break;
}
} else
continue;
} else {
if ((gen->type != check_type) && (gen->type != GEN_OTHERNAME))
continue;
}
san_present = 1;
if (check_type == GEN_EMAIL)
cstr = gen->d.rfc822Name;
else if (check_type == GEN_DNS)
cstr = gen->d.dNSName;
else
cstr = gen->d.iPAddress;
/* Positive on success, negative on error! */
if ((rv = do_check_string(cstr, alt_type, equal, flags,
chk, chklen, peername)) != 0)
break;
}
GENERAL_NAMES_free(gens);
if (rv != 0)
return rv;
if (san_present && !(flags & X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT))
return 0;
}
/* We're done if CN-ID is not pertinent */
if (cnid == NID_undef || (flags & X509_CHECK_FLAG_NEVER_CHECK_SUBJECT))
return 0;
i = -1;
name = X509_get_subject_name(x);
while ((i = X509_NAME_get_index_by_NID(name, cnid, i)) >= 0) {
const X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, i);
const ASN1_STRING *str = X509_NAME_ENTRY_get_data(ne);
/* Positive on success, negative on error! */
if ((rv = do_check_string(str, -1, equal, flags,
chk, chklen, peername)) != 0)
return rv;
}
return 0;
}
int X509_check_host(X509 *x, const char *chk, size_t chklen,
unsigned int flags, char **peername)
{
if (chk == NULL)
return -2;
/*
* Embedded NULs are disallowed, except as the last character of a
* string of length 2 or more (tolerate caller including terminating
* NUL in string length).
*/
if (chklen == 0)
chklen = strlen(chk);
else if (memchr(chk, '\0', chklen > 1 ? chklen - 1 : chklen))
return -2;
if (chklen > 1 && chk[chklen - 1] == '\0')
--chklen;
return do_x509_check(x, chk, chklen, flags, GEN_DNS, peername);
}
int X509_check_email(X509 *x, const char *chk, size_t chklen,
unsigned int flags)
{
if (chk == NULL)
return -2;
/*
* Embedded NULs are disallowed, except as the last character of a
* string of length 2 or more (tolerate caller including terminating
* NUL in string length).
*/
if (chklen == 0)
chklen = strlen((char *)chk);
else if (memchr(chk, '\0', chklen > 1 ? chklen - 1 : chklen))
return -2;
if (chklen > 1 && chk[chklen - 1] == '\0')
--chklen;
return do_x509_check(x, chk, chklen, flags, GEN_EMAIL, NULL);
}
int X509_check_ip(X509 *x, const unsigned char *chk, size_t chklen,
unsigned int flags)
{
if (chk == NULL)
return -2;
return do_x509_check(x, (char *)chk, chklen, flags, GEN_IPADD, NULL);
}
int X509_check_ip_asc(X509 *x, const char *ipasc, unsigned int flags)
{
unsigned char ipout[16];
size_t iplen;
if (ipasc == NULL)
return -2;
iplen = (size_t)ossl_a2i_ipadd(ipout, ipasc);
if (iplen == 0)
return -2;
return do_x509_check(x, (char *)ipout, iplen, flags, GEN_IPADD, NULL);
}
char *ossl_ipaddr_to_asc(unsigned char *p, int len)
{
/*
* 40 is enough space for the longest IPv6 address + nul terminator byte
* XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX\0
*/
char buf[40], *out;
int i = 0, remain = 0, bytes = 0;
switch (len) {
case 4: /* IPv4 */
BIO_snprintf(buf, sizeof(buf), "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
break;
case 16: /* IPv6 */
for (out = buf, i = 8, remain = sizeof(buf);
i-- > 0 && bytes >= 0;
remain -= bytes, out += bytes) {
const char *template = (i > 0 ? "%X:" : "%X");
bytes = BIO_snprintf(out, remain, template, p[0] << 8 | p[1]);
p += 2;
}
break;
default:
BIO_snprintf(buf, sizeof(buf), "<invalid length=%d>", len);
break;
}
return OPENSSL_strdup(buf);
}
/*
* Convert IP addresses both IPv4 and IPv6 into an OCTET STRING compatible
* with RFC3280.
*/
ASN1_OCTET_STRING *a2i_IPADDRESS(const char *ipasc)
{
unsigned char ipout[16];
ASN1_OCTET_STRING *ret;
int iplen;
/* If string contains a ':' assume IPv6 */
iplen = ossl_a2i_ipadd(ipout, ipasc);
if (!iplen)
return NULL;
ret = ASN1_OCTET_STRING_new();
if (ret == NULL)
return NULL;
if (!ASN1_OCTET_STRING_set(ret, ipout, iplen)) {
ASN1_OCTET_STRING_free(ret);
return NULL;
}
return ret;
}
ASN1_OCTET_STRING *a2i_IPADDRESS_NC(const char *ipasc)
{
ASN1_OCTET_STRING *ret = NULL;
unsigned char ipout[32];
char *iptmp = NULL, *p;
int iplen1, iplen2;
p = strchr(ipasc, '/');
if (p == NULL)
return NULL;
iptmp = OPENSSL_strdup(ipasc);
if (iptmp == NULL)
return NULL;
p = iptmp + (p - ipasc);
*p++ = 0;
iplen1 = ossl_a2i_ipadd(ipout, iptmp);
if (!iplen1)
goto err;
iplen2 = ossl_a2i_ipadd(ipout + iplen1, p);
OPENSSL_free(iptmp);
iptmp = NULL;
if (!iplen2 || (iplen1 != iplen2))
goto err;
ret = ASN1_OCTET_STRING_new();
if (ret == NULL)
goto err;
if (!ASN1_OCTET_STRING_set(ret, ipout, iplen1 + iplen2))
goto err;
return ret;
err:
OPENSSL_free(iptmp);
ASN1_OCTET_STRING_free(ret);
return NULL;
}
int ossl_a2i_ipadd(unsigned char *ipout, const char *ipasc)
{
/* If string contains a ':' assume IPv6 */
if (strchr(ipasc, ':')) {
if (!ipv6_from_asc(ipout, ipasc))
return 0;
return 16;
} else {
if (!ipv4_from_asc(ipout, ipasc))
return 0;
return 4;
}
}
static int ipv4_from_asc(unsigned char *v4, const char *in)
{
const char *p;
int a0, a1, a2, a3, n;
if (sscanf(in, "%d.%d.%d.%d%n", &a0, &a1, &a2, &a3, &n) != 4)
return 0;
if ((a0 < 0) || (a0 > 255) || (a1 < 0) || (a1 > 255)
|| (a2 < 0) || (a2 > 255) || (a3 < 0) || (a3 > 255))
return 0;
p = in + n;
if (!(*p == '\0' || ossl_isspace(*p)))
return 0;
v4[0] = a0;
v4[1] = a1;
v4[2] = a2;
v4[3] = a3;
return 1;
}
typedef struct {
/* Temporary store for IPV6 output */
unsigned char tmp[16];
/* Total number of bytes in tmp */
int total;
/* The position of a zero (corresponding to '::') */
int zero_pos;
/* Number of zeroes */
int zero_cnt;
} IPV6_STAT;
static int ipv6_from_asc(unsigned char *v6, const char *in)
{
IPV6_STAT v6stat;
v6stat.total = 0;
v6stat.zero_pos = -1;
v6stat.zero_cnt = 0;
/*
* Treat the IPv6 representation as a list of values separated by ':'.
* The presence of a '::' will parse as one, two or three zero length
* elements.
*/
if (!CONF_parse_list(in, ':', 0, ipv6_cb, &v6stat))
return 0;
/* Now for some sanity checks */
if (v6stat.zero_pos == -1) {
/* If no '::' must have exactly 16 bytes */
if (v6stat.total != 16)
return 0;
} else {
/* If '::' must have less than 16 bytes */
if (v6stat.total == 16)
return 0;
/* More than three zeroes is an error */
if (v6stat.zero_cnt > 3) {
return 0;
/* Can only have three zeroes if nothing else present */
} else if (v6stat.zero_cnt == 3) {
if (v6stat.total > 0)
return 0;
} else if (v6stat.zero_cnt == 2) {
/* Can only have two zeroes if at start or end */
if ((v6stat.zero_pos != 0)
&& (v6stat.zero_pos != v6stat.total))
return 0;
} else {
/* Can only have one zero if *not* start or end */
if ((v6stat.zero_pos == 0)
|| (v6stat.zero_pos == v6stat.total))
return 0;
}
}
/* Format result */
if (v6stat.zero_pos >= 0) {
/* Copy initial part */
memcpy(v6, v6stat.tmp, v6stat.zero_pos);
/* Zero middle */
memset(v6 + v6stat.zero_pos, 0, 16 - v6stat.total);
/* Copy final part */
if (v6stat.total != v6stat.zero_pos)
memcpy(v6 + v6stat.zero_pos + 16 - v6stat.total,
v6stat.tmp + v6stat.zero_pos,
v6stat.total - v6stat.zero_pos);
} else {
memcpy(v6, v6stat.tmp, 16);
}
return 1;
}
static int ipv6_cb(const char *elem, int len, void *usr)
{
IPV6_STAT *s = usr;
/* Error if 16 bytes written */
if (s->total == 16)
return 0;
if (len == 0) {
/* Zero length element, corresponds to '::' */
if (s->zero_pos == -1)
s->zero_pos = s->total;
/* If we've already got a :: its an error */
else if (s->zero_pos != s->total)
return 0;
s->zero_cnt++;
} else {
/* If more than 4 characters could be final a.b.c.d form */
if (len > 4) {
/* Need at least 4 bytes left */
if (s->total > 12)
return 0;
/* Must be end of string */
if (elem[len])
return 0;
if (!ipv4_from_asc(s->tmp + s->total, elem))
return 0;
s->total += 4;
} else {
if (!ipv6_hex(s->tmp + s->total, elem, len))
return 0;
s->total += 2;
}
}
return 1;
}
/*
* Convert a string of up to 4 hex digits into the corresponding IPv6 form.
*/
static int ipv6_hex(unsigned char *out, const char *in, int inlen)
{
unsigned char c;
unsigned int num = 0;
int x;
if (inlen > 4)
return 0;
while (inlen--) {
c = *in++;
num <<= 4;
x = OPENSSL_hexchar2int(c);
if (x < 0)
return 0;
num |= (char)x;
}
out[0] = num >> 8;
out[1] = num & 0xff;
return 1;
}
int X509V3_NAME_from_section(X509_NAME *nm, STACK_OF(CONF_VALUE) *dn_sk,
unsigned long chtype)
{
CONF_VALUE *v;
int i, mval, spec_char, plus_char;
char *p, *type;
if (!nm)
return 0;
for (i = 0; i < sk_CONF_VALUE_num(dn_sk); i++) {
v = sk_CONF_VALUE_value(dn_sk, i);
type = v->name;
/*
* Skip past any leading X. X: X, etc to allow for multiple instances
*/
for (p = type; *p; p++) {
#ifndef CHARSET_EBCDIC
spec_char = ((*p == ':') || (*p == ',') || (*p == '.'));
#else
spec_char = ((*p == os_toascii[':']) || (*p == os_toascii[','])
|| (*p == os_toascii['.']));
#endif
if (spec_char) {
p++;
if (*p)
type = p;
break;
}
}
#ifndef CHARSET_EBCDIC
plus_char = (*type == '+');
#else
plus_char = (*type == os_toascii['+']);
#endif
if (plus_char) {
mval = -1;
type++;
} else {
mval = 0;
}
if (!X509_NAME_add_entry_by_txt(nm, type, chtype,
(unsigned char *)v->value, -1, -1,
mval))
return 0;
}
return 1;
}
|
./openssl/crypto/x509/x_pubkey.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
*/
/*
* DSA 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/asn1t.h>
#include <openssl/x509.h>
#include <openssl/engine.h>
#include "crypto/asn1.h"
#include "crypto/evp.h"
#include "crypto/x509.h"
#include <openssl/rsa.h>
#include <openssl/dsa.h>
#include <openssl/decoder.h>
#include <openssl/encoder.h>
#include "internal/provider.h"
#include "internal/sizes.h"
struct X509_pubkey_st {
X509_ALGOR *algor;
ASN1_BIT_STRING *public_key;
EVP_PKEY *pkey;
/* extra data for the callback, used by d2i_PUBKEY_ex */
OSSL_LIB_CTX *libctx;
char *propq;
/* Flag to force legacy keys */
unsigned int flag_force_legacy : 1;
};
static int x509_pubkey_decode(EVP_PKEY **pk, const X509_PUBKEY *key);
static int x509_pubkey_set0_libctx(X509_PUBKEY *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;
}
ASN1_SEQUENCE(X509_PUBKEY_INTERNAL) = {
ASN1_SIMPLE(X509_PUBKEY, algor, X509_ALGOR),
ASN1_SIMPLE(X509_PUBKEY, public_key, ASN1_BIT_STRING)
} static_ASN1_SEQUENCE_END_name(X509_PUBKEY, X509_PUBKEY_INTERNAL)
X509_PUBKEY *ossl_d2i_X509_PUBKEY_INTERNAL(const unsigned char **pp,
long len, OSSL_LIB_CTX *libctx,
const char *propq)
{
X509_PUBKEY *xpub = OPENSSL_zalloc(sizeof(*xpub));
if (xpub == NULL)
return NULL;
return (X509_PUBKEY *)ASN1_item_d2i_ex((ASN1_VALUE **)&xpub, pp, len,
ASN1_ITEM_rptr(X509_PUBKEY_INTERNAL),
libctx, propq);
}
void ossl_X509_PUBKEY_INTERNAL_free(X509_PUBKEY *xpub)
{
ASN1_item_free((ASN1_VALUE *)xpub, ASN1_ITEM_rptr(X509_PUBKEY_INTERNAL));
}
static void x509_pubkey_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
X509_PUBKEY *pubkey;
if (pval != NULL && (pubkey = (X509_PUBKEY *)*pval) != NULL) {
X509_ALGOR_free(pubkey->algor);
ASN1_BIT_STRING_free(pubkey->public_key);
EVP_PKEY_free(pubkey->pkey);
OPENSSL_free(pubkey->propq);
OPENSSL_free(pubkey);
*pval = NULL;
}
}
static int x509_pubkey_ex_populate(ASN1_VALUE **pval, const ASN1_ITEM *it)
{
X509_PUBKEY *pubkey = (X509_PUBKEY *)*pval;
return (pubkey->algor != NULL
|| (pubkey->algor = X509_ALGOR_new()) != NULL)
&& (pubkey->public_key != NULL
|| (pubkey->public_key = ASN1_BIT_STRING_new()) != NULL);
}
static int x509_pubkey_ex_new_ex(ASN1_VALUE **pval, const ASN1_ITEM *it,
OSSL_LIB_CTX *libctx, const char *propq)
{
X509_PUBKEY *ret;
if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL)
return 0;
if (!x509_pubkey_ex_populate((ASN1_VALUE **)&ret, NULL)
|| !x509_pubkey_set0_libctx(ret, libctx, propq)) {
x509_pubkey_ex_free((ASN1_VALUE **)&ret, NULL);
ret = NULL;
ERR_raise(ERR_LIB_ASN1, ERR_R_X509_LIB);
} else {
*pval = (ASN1_VALUE *)ret;
}
return ret != NULL;
}
static int x509_pubkey_ex_d2i_ex(ASN1_VALUE **pval,
const unsigned char **in, long len,
const ASN1_ITEM *it, int tag, int aclass,
char opt, ASN1_TLC *ctx, OSSL_LIB_CTX *libctx,
const char *propq)
{
const unsigned char *in_saved = *in;
size_t publen;
X509_PUBKEY *pubkey;
int ret;
OSSL_DECODER_CTX *dctx = NULL;
unsigned char *tmpbuf = NULL;
if (*pval == NULL && !x509_pubkey_ex_new_ex(pval, it, libctx, propq))
return 0;
if (!x509_pubkey_ex_populate(pval, NULL)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_X509_LIB);
return 0;
}
/* This ensures that |*in| advances properly no matter what */
if ((ret = ASN1_item_ex_d2i(pval, in, len,
ASN1_ITEM_rptr(X509_PUBKEY_INTERNAL),
tag, aclass, opt, ctx)) <= 0)
return ret;
publen = *in - in_saved;
if (!ossl_assert(publen > 0)) {
ERR_raise(ERR_LIB_ASN1, ERR_R_INTERNAL_ERROR);
return 0;
}
pubkey = (X509_PUBKEY *)*pval;
EVP_PKEY_free(pubkey->pkey);
pubkey->pkey = NULL;
/*
* Opportunistically decode the key but remove any non fatal errors
* from the queue. Subsequent explicit attempts to decode/use the key
* will return an appropriate error.
*/
ERR_set_mark();
/*
* Try to decode with legacy method first. This ensures that engines
* aren't overridden by providers.
*/
if ((ret = x509_pubkey_decode(&pubkey->pkey, pubkey)) == -1) {
/* -1 indicates a fatal error, like malloc failure */
ERR_clear_last_mark();
goto end;
}
/* Try to decode it into an EVP_PKEY with OSSL_DECODER */
if (ret <= 0 && !pubkey->flag_force_legacy) {
const unsigned char *p;
char txtoidname[OSSL_MAX_NAME_SIZE];
size_t slen = publen;
/*
* The decoders don't know how to handle anything other than Universal
* class so we modify the data accordingly.
*/
if (aclass != V_ASN1_UNIVERSAL) {
tmpbuf = OPENSSL_memdup(in_saved, publen);
if (tmpbuf == NULL)
return 0;
in_saved = tmpbuf;
*tmpbuf = V_ASN1_CONSTRUCTED | V_ASN1_SEQUENCE;
}
p = in_saved;
if (OBJ_obj2txt(txtoidname, sizeof(txtoidname),
pubkey->algor->algorithm, 0) <= 0) {
ERR_clear_last_mark();
goto end;
}
if ((dctx =
OSSL_DECODER_CTX_new_for_pkey(&pubkey->pkey,
"DER", "SubjectPublicKeyInfo",
txtoidname, EVP_PKEY_PUBLIC_KEY,
pubkey->libctx,
pubkey->propq)) != NULL)
/*
* As said higher up, we're being opportunistic. In other words,
* we don't care if we fail.
*/
if (OSSL_DECODER_from_data(dctx, &p, &slen)) {
if (slen != 0) {
/*
* If we successfully decoded then we *must* consume all the
* bytes.
*/
ERR_clear_last_mark();
ERR_raise(ERR_LIB_ASN1, EVP_R_DECODE_ERROR);
goto end;
}
}
}
ERR_pop_to_mark();
ret = 1;
end:
OSSL_DECODER_CTX_free(dctx);
OPENSSL_free(tmpbuf);
return ret;
}
static int x509_pubkey_ex_i2d(const ASN1_VALUE **pval, unsigned char **out,
const ASN1_ITEM *it, int tag, int aclass)
{
return ASN1_item_ex_i2d(pval, out, ASN1_ITEM_rptr(X509_PUBKEY_INTERNAL),
tag, aclass);
}
static int x509_pubkey_ex_print(BIO *out, const ASN1_VALUE **pval, int indent,
const char *fname, const ASN1_PCTX *pctx)
{
return ASN1_item_print(out, *pval, indent,
ASN1_ITEM_rptr(X509_PUBKEY_INTERNAL), pctx);
}
static const ASN1_EXTERN_FUNCS x509_pubkey_ff = {
NULL,
NULL,
x509_pubkey_ex_free,
0, /* Default clear behaviour is OK */
NULL,
x509_pubkey_ex_i2d,
x509_pubkey_ex_print,
x509_pubkey_ex_new_ex,
x509_pubkey_ex_d2i_ex,
};
IMPLEMENT_EXTERN_ASN1(X509_PUBKEY, V_ASN1_SEQUENCE, x509_pubkey_ff)
IMPLEMENT_ASN1_FUNCTIONS(X509_PUBKEY)
X509_PUBKEY *X509_PUBKEY_new_ex(OSSL_LIB_CTX *libctx, const char *propq)
{
X509_PUBKEY *pubkey = NULL;
pubkey = (X509_PUBKEY *)ASN1_item_new_ex(X509_PUBKEY_it(), libctx, propq);
if (!x509_pubkey_set0_libctx(pubkey, libctx, propq)) {
X509_PUBKEY_free(pubkey);
pubkey = NULL;
}
return pubkey;
}
/*
* X509_PUBKEY_dup() must be implemented manually, because there is no
* support for it in ASN1_EXTERN_FUNCS.
*/
X509_PUBKEY *X509_PUBKEY_dup(const X509_PUBKEY *a)
{
X509_PUBKEY *pubkey = OPENSSL_zalloc(sizeof(*pubkey));
if (pubkey == NULL)
return NULL;
if (!x509_pubkey_set0_libctx(pubkey, a->libctx, a->propq)) {
ERR_raise(ERR_LIB_X509, ERR_R_X509_LIB);
x509_pubkey_ex_free((ASN1_VALUE **)&pubkey,
ASN1_ITEM_rptr(X509_PUBKEY_INTERNAL));
return NULL;
}
if ((pubkey->algor = X509_ALGOR_dup(a->algor)) == NULL
|| (pubkey->public_key = ASN1_BIT_STRING_new()) == NULL
|| !ASN1_BIT_STRING_set(pubkey->public_key,
a->public_key->data,
a->public_key->length)) {
x509_pubkey_ex_free((ASN1_VALUE **)&pubkey,
ASN1_ITEM_rptr(X509_PUBKEY_INTERNAL));
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
return NULL;
}
if (a->pkey != NULL) {
ERR_set_mark();
pubkey->pkey = EVP_PKEY_dup(a->pkey);
if (pubkey->pkey == NULL) {
pubkey->flag_force_legacy = 1;
if (x509_pubkey_decode(&pubkey->pkey, pubkey) <= 0) {
x509_pubkey_ex_free((ASN1_VALUE **)&pubkey,
ASN1_ITEM_rptr(X509_PUBKEY_INTERNAL));
ERR_clear_last_mark();
return NULL;
}
}
ERR_pop_to_mark();
}
return pubkey;
}
int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey)
{
X509_PUBKEY *pk = NULL;
if (x == NULL || pkey == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return 0;
}
if (pkey->ameth != NULL) {
if ((pk = X509_PUBKEY_new()) == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_ASN1_LIB);
goto error;
}
if (pkey->ameth->pub_encode != NULL) {
if (!pkey->ameth->pub_encode(pk, pkey)) {
ERR_raise(ERR_LIB_X509, X509_R_PUBLIC_KEY_ENCODE_ERROR);
goto error;
}
} else {
ERR_raise(ERR_LIB_X509, X509_R_METHOD_NOT_SUPPORTED);
goto error;
}
} else if (evp_pkey_is_provided(pkey)) {
unsigned char *der = NULL;
size_t derlen = 0;
OSSL_ENCODER_CTX *ectx =
OSSL_ENCODER_CTX_new_for_pkey(pkey, EVP_PKEY_PUBLIC_KEY,
"DER", "SubjectPublicKeyInfo",
NULL);
if (OSSL_ENCODER_to_data(ectx, &der, &derlen)) {
const unsigned char *pder = der;
pk = d2i_X509_PUBKEY(NULL, &pder, (long)derlen);
}
OSSL_ENCODER_CTX_free(ectx);
OPENSSL_free(der);
}
if (pk == NULL) {
ERR_raise(ERR_LIB_X509, X509_R_UNSUPPORTED_ALGORITHM);
goto error;
}
X509_PUBKEY_free(*x);
if (!EVP_PKEY_up_ref(pkey)) {
ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
goto error;
}
*x = pk;
/*
* pk->pkey is NULL when using the legacy routine, but is non-NULL when
* going through the encoder, and for all intents and purposes, it's
* a perfect copy of the public key portions of |pkey|, just not the same
* instance. If that's all there was to pkey then we could simply return
* early, right here. However, some application might very well depend on
* the passed |pkey| being used and none other, so we spend a few more
* cycles throwing away the newly created |pk->pkey| and replace it with
* |pkey|.
*/
if (pk->pkey != NULL)
EVP_PKEY_free(pk->pkey);
pk->pkey = pkey;
return 1;
error:
X509_PUBKEY_free(pk);
return 0;
}
/*
* Attempt to decode a public key.
* Returns 1 on success, 0 for a decode failure and -1 for a fatal
* error e.g. malloc failure.
*
* This function is #legacy.
*/
static int x509_pubkey_decode(EVP_PKEY **ppkey, const X509_PUBKEY *key)
{
EVP_PKEY *pkey;
int nid;
nid = OBJ_obj2nid(key->algor->algorithm);
if (!key->flag_force_legacy) {
#ifndef OPENSSL_NO_ENGINE
ENGINE *e = NULL;
e = ENGINE_get_pkey_meth_engine(nid);
if (e == NULL)
return 0;
ENGINE_finish(e);
#else
return 0;
#endif
}
pkey = EVP_PKEY_new();
if (pkey == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_EVP_LIB);
return -1;
}
if (!EVP_PKEY_set_type(pkey, nid)) {
ERR_raise(ERR_LIB_X509, X509_R_UNSUPPORTED_ALGORITHM);
goto error;
}
if (pkey->ameth->pub_decode) {
/*
* Treat any failure of pub_decode as a decode error. In
* future we could have different return codes for decode
* errors and fatal errors such as malloc failure.
*/
if (!pkey->ameth->pub_decode(pkey, key))
goto error;
} else {
ERR_raise(ERR_LIB_X509, X509_R_METHOD_NOT_SUPPORTED);
goto error;
}
*ppkey = pkey;
return 1;
error:
EVP_PKEY_free(pkey);
return 0;
}
EVP_PKEY *X509_PUBKEY_get0(const X509_PUBKEY *key)
{
if (key == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (key->pkey == NULL) {
/* We failed to decode the key when we loaded it, or it was never set */
ERR_raise(ERR_LIB_EVP, EVP_R_DECODE_ERROR);
return NULL;
}
return key->pkey;
}
EVP_PKEY *X509_PUBKEY_get(const X509_PUBKEY *key)
{
EVP_PKEY *ret = X509_PUBKEY_get0(key);
if (ret != NULL && !EVP_PKEY_up_ref(ret)) {
ERR_raise(ERR_LIB_X509, ERR_R_INTERNAL_ERROR);
ret = NULL;
}
return ret;
}
/*
* Now three pseudo ASN1 routines that take an EVP_PKEY structure and encode
* or decode as X509_PUBKEY
*/
static EVP_PKEY *d2i_PUBKEY_int(EVP_PKEY **a,
const unsigned char **pp, long length,
OSSL_LIB_CTX *libctx, const char *propq,
unsigned int force_legacy,
X509_PUBKEY *
(*d2i_x509_pubkey)(X509_PUBKEY **a,
const unsigned char **in,
long len))
{
X509_PUBKEY *xpk, *xpk2 = NULL, **pxpk = NULL;
EVP_PKEY *pktmp = NULL;
const unsigned char *q;
q = *pp;
/*
* If libctx or propq are non-NULL, we take advantage of the reuse
* feature. It's not generally recommended, but is safe enough for
* newly created structures.
*/
if (libctx != NULL || propq != NULL || force_legacy) {
xpk2 = OPENSSL_zalloc(sizeof(*xpk2));
if (xpk2 == NULL)
return NULL;
if (!x509_pubkey_set0_libctx(xpk2, libctx, propq))
goto end;
xpk2->flag_force_legacy = !!force_legacy;
pxpk = &xpk2;
}
xpk = d2i_x509_pubkey(pxpk, &q, length);
if (xpk == NULL)
goto end;
pktmp = X509_PUBKEY_get(xpk);
X509_PUBKEY_free(xpk);
xpk2 = NULL; /* We know that xpk == xpk2 */
if (pktmp == NULL)
goto end;
*pp = q;
if (a != NULL) {
EVP_PKEY_free(*a);
*a = pktmp;
}
end:
X509_PUBKEY_free(xpk2);
return pktmp;
}
/* For the algorithm specific d2i functions further down */
EVP_PKEY *ossl_d2i_PUBKEY_legacy(EVP_PKEY **a, const unsigned char **pp,
long length)
{
return d2i_PUBKEY_int(a, pp, length, NULL, NULL, 1, d2i_X509_PUBKEY);
}
EVP_PKEY *d2i_PUBKEY_ex(EVP_PKEY **a, const unsigned char **pp, long length,
OSSL_LIB_CTX *libctx, const char *propq)
{
return d2i_PUBKEY_int(a, pp, length, libctx, propq, 0, d2i_X509_PUBKEY);
}
EVP_PKEY *d2i_PUBKEY(EVP_PKEY **a, const unsigned char **pp, long length)
{
return d2i_PUBKEY_ex(a, pp, length, NULL, NULL);
}
int i2d_PUBKEY(const EVP_PKEY *a, unsigned char **pp)
{
int ret = -1;
if (a == NULL)
return 0;
if (a->ameth != NULL) {
X509_PUBKEY *xpk = NULL;
if ((xpk = X509_PUBKEY_new()) == NULL)
return -1;
/* pub_encode() only encode parameters, not the key itself */
if (a->ameth->pub_encode != NULL && a->ameth->pub_encode(xpk, a)) {
xpk->pkey = (EVP_PKEY *)a;
ret = i2d_X509_PUBKEY(xpk, pp);
xpk->pkey = NULL;
}
X509_PUBKEY_free(xpk);
} else if (a->keymgmt != NULL) {
OSSL_ENCODER_CTX *ctx =
OSSL_ENCODER_CTX_new_for_pkey(a, EVP_PKEY_PUBLIC_KEY,
"DER", "SubjectPublicKeyInfo",
NULL);
BIO *out = BIO_new(BIO_s_mem());
BUF_MEM *buf = NULL;
if (OSSL_ENCODER_CTX_get_num_encoders(ctx) != 0
&& out != NULL
&& OSSL_ENCODER_to_bio(ctx, out)
&& BIO_get_mem_ptr(out, &buf) > 0) {
ret = buf->length;
if (pp != NULL) {
if (*pp == NULL) {
*pp = (unsigned char *)buf->data;
buf->length = 0;
buf->data = NULL;
} else {
memcpy(*pp, buf->data, ret);
*pp += ret;
}
}
}
BIO_free(out);
OSSL_ENCODER_CTX_free(ctx);
}
return ret;
}
/*
* The following are equivalents but which return RSA and DSA keys
*/
RSA *d2i_RSA_PUBKEY(RSA **a, const unsigned char **pp, long length)
{
EVP_PKEY *pkey;
RSA *key = NULL;
const unsigned char *q;
q = *pp;
pkey = ossl_d2i_PUBKEY_legacy(NULL, &q, length);
if (pkey == NULL)
return NULL;
key = EVP_PKEY_get1_RSA(pkey);
EVP_PKEY_free(pkey);
if (key == NULL)
return NULL;
*pp = q;
if (a != NULL) {
RSA_free(*a);
*a = key;
}
return key;
}
int i2d_RSA_PUBKEY(const RSA *a, unsigned char **pp)
{
EVP_PKEY *pktmp;
int ret;
if (!a)
return 0;
pktmp = EVP_PKEY_new();
if (pktmp == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
return -1;
}
(void)EVP_PKEY_assign_RSA(pktmp, (RSA *)a);
ret = i2d_PUBKEY(pktmp, pp);
pktmp->pkey.ptr = NULL;
EVP_PKEY_free(pktmp);
return ret;
}
#ifndef OPENSSL_NO_DH
DH *ossl_d2i_DH_PUBKEY(DH **a, const unsigned char **pp, long length)
{
EVP_PKEY *pkey;
DH *key = NULL;
const unsigned char *q;
q = *pp;
pkey = ossl_d2i_PUBKEY_legacy(NULL, &q, length);
if (pkey == NULL)
return NULL;
if (EVP_PKEY_get_id(pkey) == EVP_PKEY_DH)
key = EVP_PKEY_get1_DH(pkey);
EVP_PKEY_free(pkey);
if (key == NULL)
return NULL;
*pp = q;
if (a != NULL) {
DH_free(*a);
*a = key;
}
return key;
}
int ossl_i2d_DH_PUBKEY(const DH *a, unsigned char **pp)
{
EVP_PKEY *pktmp;
int ret;
if (!a)
return 0;
pktmp = EVP_PKEY_new();
if (pktmp == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
return -1;
}
(void)EVP_PKEY_assign_DH(pktmp, (DH *)a);
ret = i2d_PUBKEY(pktmp, pp);
pktmp->pkey.ptr = NULL;
EVP_PKEY_free(pktmp);
return ret;
}
DH *ossl_d2i_DHx_PUBKEY(DH **a, const unsigned char **pp, long length)
{
EVP_PKEY *pkey;
DH *key = NULL;
const unsigned char *q;
q = *pp;
pkey = ossl_d2i_PUBKEY_legacy(NULL, &q, length);
if (pkey == NULL)
return NULL;
if (EVP_PKEY_get_id(pkey) == EVP_PKEY_DHX)
key = EVP_PKEY_get1_DH(pkey);
EVP_PKEY_free(pkey);
if (key == NULL)
return NULL;
*pp = q;
if (a != NULL) {
DH_free(*a);
*a = key;
}
return key;
}
int ossl_i2d_DHx_PUBKEY(const DH *a, unsigned char **pp)
{
EVP_PKEY *pktmp;
int ret;
if (!a)
return 0;
pktmp = EVP_PKEY_new();
if (pktmp == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
return -1;
}
(void)EVP_PKEY_assign(pktmp, EVP_PKEY_DHX, (DH *)a);
ret = i2d_PUBKEY(pktmp, pp);
pktmp->pkey.ptr = NULL;
EVP_PKEY_free(pktmp);
return ret;
}
#endif
#ifndef OPENSSL_NO_DSA
DSA *d2i_DSA_PUBKEY(DSA **a, const unsigned char **pp, long length)
{
EVP_PKEY *pkey;
DSA *key = NULL;
const unsigned char *q;
q = *pp;
pkey = ossl_d2i_PUBKEY_legacy(NULL, &q, length);
if (pkey == NULL)
return NULL;
key = EVP_PKEY_get1_DSA(pkey);
EVP_PKEY_free(pkey);
if (key == NULL)
return NULL;
*pp = q;
if (a != NULL) {
DSA_free(*a);
*a = key;
}
return key;
}
/* Called from decoders; disallows provided DSA keys without parameters. */
DSA *ossl_d2i_DSA_PUBKEY(DSA **a, const unsigned char **pp, long length)
{
DSA *key = NULL;
const unsigned char *data;
const BIGNUM *p, *q, *g;
data = *pp;
key = d2i_DSA_PUBKEY(NULL, &data, length);
if (key == NULL)
return NULL;
DSA_get0_pqg(key, &p, &q, &g);
if (p == NULL || q == NULL || g == NULL) {
DSA_free(key);
return NULL;
}
*pp = data;
if (a != NULL) {
DSA_free(*a);
*a = key;
}
return key;
}
int i2d_DSA_PUBKEY(const DSA *a, unsigned char **pp)
{
EVP_PKEY *pktmp;
int ret;
if (!a)
return 0;
pktmp = EVP_PKEY_new();
if (pktmp == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
return -1;
}
(void)EVP_PKEY_assign_DSA(pktmp, (DSA *)a);
ret = i2d_PUBKEY(pktmp, pp);
pktmp->pkey.ptr = NULL;
EVP_PKEY_free(pktmp);
return ret;
}
#endif
#ifndef OPENSSL_NO_EC
EC_KEY *d2i_EC_PUBKEY(EC_KEY **a, const unsigned char **pp, long length)
{
EVP_PKEY *pkey;
EC_KEY *key = NULL;
const unsigned char *q;
int type;
q = *pp;
pkey = ossl_d2i_PUBKEY_legacy(NULL, &q, length);
if (pkey == NULL)
return NULL;
type = EVP_PKEY_get_id(pkey);
if (type == EVP_PKEY_EC || type == EVP_PKEY_SM2)
key = EVP_PKEY_get1_EC_KEY(pkey);
EVP_PKEY_free(pkey);
if (key == NULL)
return NULL;
*pp = q;
if (a != NULL) {
EC_KEY_free(*a);
*a = key;
}
return key;
}
int i2d_EC_PUBKEY(const EC_KEY *a, unsigned char **pp)
{
EVP_PKEY *pktmp;
int ret;
if (a == NULL)
return 0;
if ((pktmp = EVP_PKEY_new()) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
return -1;
}
(void)EVP_PKEY_assign_EC_KEY(pktmp, (EC_KEY *)a);
ret = i2d_PUBKEY(pktmp, pp);
pktmp->pkey.ptr = NULL;
EVP_PKEY_free(pktmp);
return ret;
}
# ifndef OPENSSL_NO_ECX
ECX_KEY *ossl_d2i_ED25519_PUBKEY(ECX_KEY **a,
const unsigned char **pp, long length)
{
EVP_PKEY *pkey;
ECX_KEY *key = NULL;
const unsigned char *q;
q = *pp;
pkey = ossl_d2i_PUBKEY_legacy(NULL, &q, length);
if (pkey == NULL)
return NULL;
key = ossl_evp_pkey_get1_ED25519(pkey);
EVP_PKEY_free(pkey);
if (key == NULL)
return NULL;
*pp = q;
if (a != NULL) {
ossl_ecx_key_free(*a);
*a = key;
}
return key;
}
int ossl_i2d_ED25519_PUBKEY(const ECX_KEY *a, unsigned char **pp)
{
EVP_PKEY *pktmp;
int ret;
if (a == NULL)
return 0;
if ((pktmp = EVP_PKEY_new()) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
return -1;
}
(void)EVP_PKEY_assign(pktmp, EVP_PKEY_ED25519, (ECX_KEY *)a);
ret = i2d_PUBKEY(pktmp, pp);
pktmp->pkey.ptr = NULL;
EVP_PKEY_free(pktmp);
return ret;
}
ECX_KEY *ossl_d2i_ED448_PUBKEY(ECX_KEY **a,
const unsigned char **pp, long length)
{
EVP_PKEY *pkey;
ECX_KEY *key = NULL;
const unsigned char *q;
q = *pp;
pkey = ossl_d2i_PUBKEY_legacy(NULL, &q, length);
if (pkey == NULL)
return NULL;
if (EVP_PKEY_get_id(pkey) == EVP_PKEY_ED448)
key = ossl_evp_pkey_get1_ED448(pkey);
EVP_PKEY_free(pkey);
if (key == NULL)
return NULL;
*pp = q;
if (a != NULL) {
ossl_ecx_key_free(*a);
*a = key;
}
return key;
}
int ossl_i2d_ED448_PUBKEY(const ECX_KEY *a, unsigned char **pp)
{
EVP_PKEY *pktmp;
int ret;
if (a == NULL)
return 0;
if ((pktmp = EVP_PKEY_new()) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
return -1;
}
(void)EVP_PKEY_assign(pktmp, EVP_PKEY_ED448, (ECX_KEY *)a);
ret = i2d_PUBKEY(pktmp, pp);
pktmp->pkey.ptr = NULL;
EVP_PKEY_free(pktmp);
return ret;
}
ECX_KEY *ossl_d2i_X25519_PUBKEY(ECX_KEY **a,
const unsigned char **pp, long length)
{
EVP_PKEY *pkey;
ECX_KEY *key = NULL;
const unsigned char *q;
q = *pp;
pkey = ossl_d2i_PUBKEY_legacy(NULL, &q, length);
if (pkey == NULL)
return NULL;
if (EVP_PKEY_get_id(pkey) == EVP_PKEY_X25519)
key = ossl_evp_pkey_get1_X25519(pkey);
EVP_PKEY_free(pkey);
if (key == NULL)
return NULL;
*pp = q;
if (a != NULL) {
ossl_ecx_key_free(*a);
*a = key;
}
return key;
}
int ossl_i2d_X25519_PUBKEY(const ECX_KEY *a, unsigned char **pp)
{
EVP_PKEY *pktmp;
int ret;
if (a == NULL)
return 0;
if ((pktmp = EVP_PKEY_new()) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
return -1;
}
(void)EVP_PKEY_assign(pktmp, EVP_PKEY_X25519, (ECX_KEY *)a);
ret = i2d_PUBKEY(pktmp, pp);
pktmp->pkey.ptr = NULL;
EVP_PKEY_free(pktmp);
return ret;
}
ECX_KEY *ossl_d2i_X448_PUBKEY(ECX_KEY **a,
const unsigned char **pp, long length)
{
EVP_PKEY *pkey;
ECX_KEY *key = NULL;
const unsigned char *q;
q = *pp;
pkey = ossl_d2i_PUBKEY_legacy(NULL, &q, length);
if (pkey == NULL)
return NULL;
if (EVP_PKEY_get_id(pkey) == EVP_PKEY_X448)
key = ossl_evp_pkey_get1_X448(pkey);
EVP_PKEY_free(pkey);
if (key == NULL)
return NULL;
*pp = q;
if (a != NULL) {
ossl_ecx_key_free(*a);
*a = key;
}
return key;
}
int ossl_i2d_X448_PUBKEY(const ECX_KEY *a, unsigned char **pp)
{
EVP_PKEY *pktmp;
int ret;
if (a == NULL)
return 0;
if ((pktmp = EVP_PKEY_new()) == NULL) {
ERR_raise(ERR_LIB_ASN1, ERR_R_EVP_LIB);
return -1;
}
(void)EVP_PKEY_assign(pktmp, EVP_PKEY_X448, (ECX_KEY *)a);
ret = i2d_PUBKEY(pktmp, pp);
pktmp->pkey.ptr = NULL;
EVP_PKEY_free(pktmp);
return ret;
}
# endif /* OPENSSL_NO_ECX */
#endif
void X509_PUBKEY_set0_public_key(X509_PUBKEY *pub,
unsigned char *penc, int penclen)
{
ASN1_STRING_set0(pub->public_key, penc, penclen);
ossl_asn1_string_set_bits_left(pub->public_key, 0);
}
int X509_PUBKEY_set0_param(X509_PUBKEY *pub, ASN1_OBJECT *aobj,
int ptype, void *pval,
unsigned char *penc, int penclen)
{
if (!X509_ALGOR_set0(pub->algor, aobj, ptype, pval))
return 0;
if (penc != NULL)
X509_PUBKEY_set0_public_key(pub, penc, penclen);
return 1;
}
int X509_PUBKEY_get0_param(ASN1_OBJECT **ppkalg,
const unsigned char **pk, int *ppklen,
X509_ALGOR **pa, const X509_PUBKEY *pub)
{
if (ppkalg)
*ppkalg = pub->algor->algorithm;
if (pk) {
*pk = pub->public_key->data;
*ppklen = pub->public_key->length;
}
if (pa)
*pa = pub->algor;
return 1;
}
ASN1_BIT_STRING *X509_get0_pubkey_bitstr(const X509 *x)
{
if (x == NULL)
return NULL;
return x->cert_info.key->public_key;
}
/* Returns 1 for equal, 0, for non-equal, < 0 on error */
int X509_PUBKEY_eq(const X509_PUBKEY *a, const X509_PUBKEY *b)
{
X509_ALGOR *algA, *algB;
EVP_PKEY *pA, *pB;
if (a == b)
return 1;
if (a == NULL || b == NULL)
return 0;
if (!X509_PUBKEY_get0_param(NULL, NULL, NULL, &algA, a) || algA == NULL
|| !X509_PUBKEY_get0_param(NULL, NULL, NULL, &algB, b) || algB == NULL)
return -2;
if (X509_ALGOR_cmp(algA, algB) != 0)
return 0;
if ((pA = X509_PUBKEY_get0(a)) == NULL
|| (pB = X509_PUBKEY_get0(b)) == NULL)
return -2;
return EVP_PKEY_eq(pA, pB);
}
int ossl_x509_PUBKEY_get0_libctx(OSSL_LIB_CTX **plibctx, const char **ppropq,
const X509_PUBKEY *key)
{
if (plibctx)
*plibctx = key->libctx;
if (ppropq)
*ppropq = key->propq;
return 1;
}
|
./openssl/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
|
./openssl/crypto/x509/x509_att.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 "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) *ossl_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 (*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(STACK_OF(X509_ATTRIBUTE) **x,
X509_ATTRIBUTE *attr)
{
if (x == NULL || attr == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (*x != NULL && X509at_get_attr_by_OBJ(*x, attr->object, -1) != -1) {
ERR_raise(ERR_LIB_X509, X509_R_DUPLICATE_ATTRIBUTE);
return NULL;
}
return ossl_x509at_add1_attr(x, attr);
}
STACK_OF(X509_ATTRIBUTE) *ossl_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 = ossl_x509at_add1_attr(x, attr);
X509_ATTRIBUTE_free(attr);
return ret;
}
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)
{
if (x == NULL || obj == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (*x != NULL && X509at_get_attr_by_OBJ(*x, obj, -1) != -1) {
ERR_raise(ERR_LIB_X509, X509_R_DUPLICATE_ATTRIBUTE);
return NULL;
}
return ossl_x509at_add1_attr_by_OBJ(x, obj, type, bytes, len);
}
STACK_OF(X509_ATTRIBUTE) *ossl_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 = ossl_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)
{
if (x == NULL) {
ERR_raise(ERR_LIB_X509, ERR_R_PASSED_NULL_PARAMETER);
return NULL;
}
if (*x != NULL && X509at_get_attr_by_NID(*x, nid, -1) != -1) {
ERR_raise(ERR_LIB_X509, X509_R_DUPLICATE_ATTRIBUTE);
return NULL;
}
return ossl_x509at_add1_attr_by_NID(x, nid, type, bytes, len);
}
STACK_OF(X509_ATTRIBUTE) *ossl_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 = ossl_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);
}
|
./openssl/crypto/x509/standard_exts.h | /*
* Copyright 1999-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
*/
/*
* 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,
&ossl_v3_no_rev_avail,
#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,
&ossl_v3_soa_identifier,
&ossl_v3_indirect_issuer,
&ossl_v3_no_assertion,
&ossl_v3_single_use,
&ossl_v3_group_ac
};
/* Number of standard extensions */
#define STANDARD_EXTENSION_COUNT OSSL_NELEM(standard_exts)
|
./openssl/crypto/x509/v3_soa_id.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
*/
#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_SOA_IDENTIFIER(X509V3_EXT_METHOD *method,
void *su, BIO *out,
int indent)
{
return 1;
}
static void *r2i_SOA_IDENTIFIER(X509V3_EXT_METHOD *method,
X509V3_CTX *ctx, const char *value)
{
return ASN1_NULL_new();
}
static char *i2s_SOA_IDENTIFIER(const X509V3_EXT_METHOD *method, void *val)
{
return OPENSSL_strdup("NULL");
}
static void *s2i_SOA_IDENTIFIER(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *str)
{
return ASN1_NULL_new();
}
/*
* The sOAIdentifier X.509v3 extension is defined in ITU Recommendation X.509
* (2019), Section 17.3.2.1.1. See: https://www.itu.int/rec/T-REC-X.509-201910-I/en.
*/
const X509V3_EXT_METHOD ossl_v3_soa_identifier = {
NID_soa_identifier, 0, ASN1_ITEM_ref(ASN1_NULL),
0, 0, 0, 0,
(X509V3_EXT_I2S)i2s_SOA_IDENTIFIER,
(X509V3_EXT_S2I)s2i_SOA_IDENTIFIER,
0, 0,
(X509V3_EXT_I2R)i2r_SOA_IDENTIFIER,
(X509V3_EXT_R2I)r2i_SOA_IDENTIFIER,
NULL
};
|
./openssl/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;
}
|
./openssl/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;
}
|
./openssl/crypto/x509/ext_dat.h | /*
* Copyright 1999-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
*/
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;
extern const X509V3_EXT_METHOD ossl_v3_group_ac;
extern const X509V3_EXT_METHOD ossl_v3_soa_identifier;
extern const X509V3_EXT_METHOD ossl_v3_no_assertion;
extern const X509V3_EXT_METHOD ossl_v3_no_rev_avail;
extern const X509V3_EXT_METHOD ossl_v3_single_use;
extern const X509V3_EXT_METHOD ossl_v3_indirect_issuer;
|
./openssl/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;
}
|
./openssl/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;
}
|
./openssl/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 == XN_FLAG_COMPAT)
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;
}
|
./openssl/crypto/x509/v3_admis.c | /*
* Copyright 2017-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 "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;
}
|
./openssl/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 NULL;
}
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);
}
|
./openssl/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);
}
|
./openssl/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;
}
|
./openssl/crypto/x509/v3_addr.c | /*
* Copyright 2006-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
*/
/*
* Implementation of RFC 3779 section 2.2.
*/
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <openssl/conf.h>
#include <openssl/asn1.h>
#include <openssl/asn1t.h>
#include <openssl/buffer.h>
#include <openssl/x509v3.h>
#include "internal/cryptlib.h"
#include "crypto/asn1.h"
#include "crypto/x509.h"
#include "ext_dat.h"
#include "x509_local.h"
#ifndef OPENSSL_NO_RFC3779
/*
* OpenSSL ASN.1 template translation of RFC 3779 2.2.3.
*/
ASN1_SEQUENCE(IPAddressRange) = {
ASN1_SIMPLE(IPAddressRange, min, ASN1_BIT_STRING),
ASN1_SIMPLE(IPAddressRange, max, ASN1_BIT_STRING)
} ASN1_SEQUENCE_END(IPAddressRange)
ASN1_CHOICE(IPAddressOrRange) = {
ASN1_SIMPLE(IPAddressOrRange, u.addressPrefix, ASN1_BIT_STRING),
ASN1_SIMPLE(IPAddressOrRange, u.addressRange, IPAddressRange)
} ASN1_CHOICE_END(IPAddressOrRange)
ASN1_CHOICE(IPAddressChoice) = {
ASN1_SIMPLE(IPAddressChoice, u.inherit, ASN1_NULL),
ASN1_SEQUENCE_OF(IPAddressChoice, u.addressesOrRanges, IPAddressOrRange)
} ASN1_CHOICE_END(IPAddressChoice)
ASN1_SEQUENCE(IPAddressFamily) = {
ASN1_SIMPLE(IPAddressFamily, addressFamily, ASN1_OCTET_STRING),
ASN1_SIMPLE(IPAddressFamily, ipAddressChoice, IPAddressChoice)
} ASN1_SEQUENCE_END(IPAddressFamily)
ASN1_ITEM_TEMPLATE(IPAddrBlocks) =
ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0,
IPAddrBlocks, IPAddressFamily)
static_ASN1_ITEM_TEMPLATE_END(IPAddrBlocks)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressRange)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressOrRange)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressChoice)
IMPLEMENT_ASN1_FUNCTIONS(IPAddressFamily)
/*
* How much buffer space do we need for a raw address?
*/
# define ADDR_RAW_BUF_LEN 16
/*
* What's the address length associated with this AFI?
*/
static int length_from_afi(const unsigned afi)
{
switch (afi) {
case IANA_AFI_IPV4:
return 4;
case IANA_AFI_IPV6:
return 16;
default:
return 0;
}
}
/*
* Extract the AFI from an IPAddressFamily.
*/
unsigned int X509v3_addr_get_afi(const IPAddressFamily *f)
{
if (f == NULL
|| f->addressFamily == NULL
|| f->addressFamily->data == NULL
|| f->addressFamily->length < 2)
return 0;
return (f->addressFamily->data[0] << 8) | f->addressFamily->data[1];
}
/*
* Expand the bitstring form of an address into a raw byte array.
* At the moment this is coded for simplicity, not speed.
*/
static int addr_expand(unsigned char *addr,
const ASN1_BIT_STRING *bs,
const int length, const unsigned char fill)
{
if (bs->length < 0 || bs->length > length)
return 0;
if (bs->length > 0) {
memcpy(addr, bs->data, bs->length);
if ((bs->flags & 7) != 0) {
unsigned char mask = 0xFF >> (8 - (bs->flags & 7));
if (fill == 0)
addr[bs->length - 1] &= ~mask;
else
addr[bs->length - 1] |= mask;
}
}
memset(addr + bs->length, fill, length - bs->length);
return 1;
}
/*
* Extract the prefix length from a bitstring.
*/
# define addr_prefixlen(bs) ((int)((bs)->length * 8 - ((bs)->flags & 7)))
/*
* i2r handler for one address bitstring.
*/
static int i2r_address(BIO *out,
const unsigned afi,
const unsigned char fill, const ASN1_BIT_STRING *bs)
{
unsigned char addr[ADDR_RAW_BUF_LEN];
int i, n;
if (bs->length < 0)
return 0;
switch (afi) {
case IANA_AFI_IPV4:
if (!addr_expand(addr, bs, 4, fill))
return 0;
BIO_printf(out, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]);
break;
case IANA_AFI_IPV6:
if (!addr_expand(addr, bs, 16, fill))
return 0;
for (n = 16; n > 1 && addr[n - 1] == 0x00 && addr[n - 2] == 0x00;
n -= 2) ;
for (i = 0; i < n; i += 2)
BIO_printf(out, "%x%s", (addr[i] << 8) | addr[i + 1],
(i < 14 ? ":" : ""));
if (i < 16)
BIO_puts(out, ":");
if (i == 0)
BIO_puts(out, ":");
break;
default:
for (i = 0; i < bs->length; i++)
BIO_printf(out, "%s%02x", (i > 0 ? ":" : ""), bs->data[i]);
BIO_printf(out, "[%d]", (int)(bs->flags & 7));
break;
}
return 1;
}
/*
* i2r handler for a sequence of addresses and ranges.
*/
static int i2r_IPAddressOrRanges(BIO *out,
const int indent,
const IPAddressOrRanges *aors,
const unsigned afi)
{
int i;
for (i = 0; i < sk_IPAddressOrRange_num(aors); i++) {
const IPAddressOrRange *aor = sk_IPAddressOrRange_value(aors, i);
BIO_printf(out, "%*s", indent, "");
switch (aor->type) {
case IPAddressOrRange_addressPrefix:
if (!i2r_address(out, afi, 0x00, aor->u.addressPrefix))
return 0;
BIO_printf(out, "/%d\n", addr_prefixlen(aor->u.addressPrefix));
continue;
case IPAddressOrRange_addressRange:
if (!i2r_address(out, afi, 0x00, aor->u.addressRange->min))
return 0;
BIO_puts(out, "-");
if (!i2r_address(out, afi, 0xFF, aor->u.addressRange->max))
return 0;
BIO_puts(out, "\n");
continue;
}
}
return 1;
}
/*
* i2r handler for an IPAddrBlocks extension.
*/
static int i2r_IPAddrBlocks(const X509V3_EXT_METHOD *method,
void *ext, BIO *out, int indent)
{
const IPAddrBlocks *addr = ext;
int i;
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
const unsigned int afi = X509v3_addr_get_afi(f);
switch (afi) {
case IANA_AFI_IPV4:
BIO_printf(out, "%*sIPv4", indent, "");
break;
case IANA_AFI_IPV6:
BIO_printf(out, "%*sIPv6", indent, "");
break;
default:
BIO_printf(out, "%*sUnknown AFI %u", indent, "", afi);
break;
}
if (f->addressFamily->length > 2) {
switch (f->addressFamily->data[2]) {
case 1:
BIO_puts(out, " (Unicast)");
break;
case 2:
BIO_puts(out, " (Multicast)");
break;
case 3:
BIO_puts(out, " (Unicast/Multicast)");
break;
case 4:
BIO_puts(out, " (MPLS)");
break;
case 64:
BIO_puts(out, " (Tunnel)");
break;
case 65:
BIO_puts(out, " (VPLS)");
break;
case 66:
BIO_puts(out, " (BGP MDT)");
break;
case 128:
BIO_puts(out, " (MPLS-labeled VPN)");
break;
default:
BIO_printf(out, " (Unknown SAFI %u)",
(unsigned)f->addressFamily->data[2]);
break;
}
}
switch (f->ipAddressChoice->type) {
case IPAddressChoice_inherit:
BIO_puts(out, ": inherit\n");
break;
case IPAddressChoice_addressesOrRanges:
BIO_puts(out, ":\n");
if (!i2r_IPAddressOrRanges(out,
indent + 2,
f->ipAddressChoice->
u.addressesOrRanges, afi))
return 0;
break;
}
}
return 1;
}
/*
* Sort comparison function for a sequence of IPAddressOrRange
* elements.
*
* There's no sane answer we can give if addr_expand() fails, and an
* assertion failure on externally supplied data is seriously uncool,
* so we just arbitrarily declare that if given invalid inputs this
* function returns -1. If this messes up your preferred sort order
* for garbage input, tough noogies.
*/
static int IPAddressOrRange_cmp(const IPAddressOrRange *a,
const IPAddressOrRange *b, const int length)
{
unsigned char addr_a[ADDR_RAW_BUF_LEN], addr_b[ADDR_RAW_BUF_LEN];
int prefixlen_a = 0, prefixlen_b = 0;
int r;
switch (a->type) {
case IPAddressOrRange_addressPrefix:
if (!addr_expand(addr_a, a->u.addressPrefix, length, 0x00))
return -1;
prefixlen_a = addr_prefixlen(a->u.addressPrefix);
break;
case IPAddressOrRange_addressRange:
if (!addr_expand(addr_a, a->u.addressRange->min, length, 0x00))
return -1;
prefixlen_a = length * 8;
break;
default:
return -1;
}
switch (b->type) {
case IPAddressOrRange_addressPrefix:
if (!addr_expand(addr_b, b->u.addressPrefix, length, 0x00))
return -1;
prefixlen_b = addr_prefixlen(b->u.addressPrefix);
break;
case IPAddressOrRange_addressRange:
if (!addr_expand(addr_b, b->u.addressRange->min, length, 0x00))
return -1;
prefixlen_b = length * 8;
break;
default:
return -1;
}
if ((r = memcmp(addr_a, addr_b, length)) != 0)
return r;
else
return prefixlen_a - prefixlen_b;
}
/*
* IPv4-specific closure over IPAddressOrRange_cmp, since sk_sort()
* comparison routines are only allowed two arguments.
*/
static int v4IPAddressOrRange_cmp(const IPAddressOrRange *const *a,
const IPAddressOrRange *const *b)
{
return IPAddressOrRange_cmp(*a, *b, 4);
}
/*
* IPv6-specific closure over IPAddressOrRange_cmp, since sk_sort()
* comparison routines are only allowed two arguments.
*/
static int v6IPAddressOrRange_cmp(const IPAddressOrRange *const *a,
const IPAddressOrRange *const *b)
{
return IPAddressOrRange_cmp(*a, *b, 16);
}
/*
* Calculate whether a range collapses to a prefix.
* See last paragraph of RFC 3779 2.2.3.7.
*/
static int range_should_be_prefix(const unsigned char *min,
const unsigned char *max, const int length)
{
unsigned char mask;
int i, j;
/*
* It is the responsibility of the caller to confirm min <= max. We don't
* use ossl_assert() here since we have no way of signalling an error from
* this function - so we just use a plain assert instead.
*/
assert(memcmp(min, max, length) <= 0);
for (i = 0; i < length && min[i] == max[i]; i++) ;
for (j = length - 1; j >= 0 && min[j] == 0x00 && max[j] == 0xFF; j--) ;
if (i < j)
return -1;
if (i > j)
return i * 8;
mask = min[i] ^ max[i];
switch (mask) {
case 0x01:
j = 7;
break;
case 0x03:
j = 6;
break;
case 0x07:
j = 5;
break;
case 0x0F:
j = 4;
break;
case 0x1F:
j = 3;
break;
case 0x3F:
j = 2;
break;
case 0x7F:
j = 1;
break;
default:
return -1;
}
if ((min[i] & mask) != 0 || (max[i] & mask) != mask)
return -1;
else
return i * 8 + j;
}
/*
* Construct a prefix.
*/
static int make_addressPrefix(IPAddressOrRange **result, unsigned char *addr,
const int prefixlen, const int afilen)
{
int bytelen = (prefixlen + 7) / 8, bitlen = prefixlen % 8;
IPAddressOrRange *aor = IPAddressOrRange_new();
if (prefixlen < 0 || prefixlen > (afilen * 8))
return 0;
if (aor == NULL)
return 0;
aor->type = IPAddressOrRange_addressPrefix;
if (aor->u.addressPrefix == NULL &&
(aor->u.addressPrefix = ASN1_BIT_STRING_new()) == NULL)
goto err;
if (!ASN1_BIT_STRING_set(aor->u.addressPrefix, addr, bytelen))
goto err;
if (bitlen > 0)
aor->u.addressPrefix->data[bytelen - 1] &= ~(0xFF >> bitlen);
ossl_asn1_string_set_bits_left(aor->u.addressPrefix, 8 - bitlen);
*result = aor;
return 1;
err:
IPAddressOrRange_free(aor);
return 0;
}
/*
* Construct a range. If it can be expressed as a prefix,
* return a prefix instead. Doing this here simplifies
* the rest of the code considerably.
*/
static int make_addressRange(IPAddressOrRange **result,
unsigned char *min,
unsigned char *max, const int length)
{
IPAddressOrRange *aor;
int i, prefixlen;
if (memcmp(min, max, length) > 0)
return 0;
if ((prefixlen = range_should_be_prefix(min, max, length)) >= 0)
return make_addressPrefix(result, min, prefixlen, length);
if ((aor = IPAddressOrRange_new()) == NULL)
return 0;
aor->type = IPAddressOrRange_addressRange;
if ((aor->u.addressRange = IPAddressRange_new()) == NULL)
goto err;
if (aor->u.addressRange->min == NULL &&
(aor->u.addressRange->min = ASN1_BIT_STRING_new()) == NULL)
goto err;
if (aor->u.addressRange->max == NULL &&
(aor->u.addressRange->max = ASN1_BIT_STRING_new()) == NULL)
goto err;
for (i = length; i > 0 && min[i - 1] == 0x00; --i) ;
if (!ASN1_BIT_STRING_set(aor->u.addressRange->min, min, i))
goto err;
ossl_asn1_string_set_bits_left(aor->u.addressRange->min, 0);
if (i > 0) {
unsigned char b = min[i - 1];
int j = 1;
while ((b & (0xFFU >> j)) != 0)
++j;
aor->u.addressRange->min->flags |= 8 - j;
}
for (i = length; i > 0 && max[i - 1] == 0xFF; --i) ;
if (!ASN1_BIT_STRING_set(aor->u.addressRange->max, max, i))
goto err;
ossl_asn1_string_set_bits_left(aor->u.addressRange->max, 0);
if (i > 0) {
unsigned char b = max[i - 1];
int j = 1;
while ((b & (0xFFU >> j)) != (0xFFU >> j))
++j;
aor->u.addressRange->max->flags |= 8 - j;
}
*result = aor;
return 1;
err:
IPAddressOrRange_free(aor);
return 0;
}
/*
* Construct a new address family or find an existing one.
*/
static IPAddressFamily *make_IPAddressFamily(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi)
{
IPAddressFamily *f;
unsigned char key[3];
int keylen;
int i;
key[0] = (afi >> 8) & 0xFF;
key[1] = afi & 0xFF;
if (safi != NULL) {
key[2] = *safi & 0xFF;
keylen = 3;
} else {
keylen = 2;
}
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
f = sk_IPAddressFamily_value(addr, i);
if (f->addressFamily->length == keylen &&
!memcmp(f->addressFamily->data, key, keylen))
return f;
}
if ((f = IPAddressFamily_new()) == NULL)
goto err;
if (f->ipAddressChoice == NULL &&
(f->ipAddressChoice = IPAddressChoice_new()) == NULL)
goto err;
if (f->addressFamily == NULL &&
(f->addressFamily = ASN1_OCTET_STRING_new()) == NULL)
goto err;
if (!ASN1_OCTET_STRING_set(f->addressFamily, key, keylen))
goto err;
if (!sk_IPAddressFamily_push(addr, f))
goto err;
return f;
err:
IPAddressFamily_free(f);
return NULL;
}
/*
* Add an inheritance element.
*/
int X509v3_addr_add_inherit(IPAddrBlocks *addr,
const unsigned afi, const unsigned *safi)
{
IPAddressFamily *f = make_IPAddressFamily(addr, afi, safi);
if (f == NULL ||
f->ipAddressChoice == NULL ||
(f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges &&
f->ipAddressChoice->u.addressesOrRanges != NULL))
return 0;
if (f->ipAddressChoice->type == IPAddressChoice_inherit &&
f->ipAddressChoice->u.inherit != NULL)
return 1;
if (f->ipAddressChoice->u.inherit == NULL &&
(f->ipAddressChoice->u.inherit = ASN1_NULL_new()) == NULL)
return 0;
f->ipAddressChoice->type = IPAddressChoice_inherit;
return 1;
}
/*
* Construct an IPAddressOrRange sequence, or return an existing one.
*/
static IPAddressOrRanges *make_prefix_or_range(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi)
{
IPAddressFamily *f = make_IPAddressFamily(addr, afi, safi);
IPAddressOrRanges *aors = NULL;
if (f == NULL ||
f->ipAddressChoice == NULL ||
(f->ipAddressChoice->type == IPAddressChoice_inherit &&
f->ipAddressChoice->u.inherit != NULL))
return NULL;
if (f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges)
aors = f->ipAddressChoice->u.addressesOrRanges;
if (aors != NULL)
return aors;
if ((aors = sk_IPAddressOrRange_new_null()) == NULL)
return NULL;
switch (afi) {
case IANA_AFI_IPV4:
(void)sk_IPAddressOrRange_set_cmp_func(aors, v4IPAddressOrRange_cmp);
break;
case IANA_AFI_IPV6:
(void)sk_IPAddressOrRange_set_cmp_func(aors, v6IPAddressOrRange_cmp);
break;
}
f->ipAddressChoice->type = IPAddressChoice_addressesOrRanges;
f->ipAddressChoice->u.addressesOrRanges = aors;
return aors;
}
/*
* Add a prefix.
*/
int X509v3_addr_add_prefix(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi,
unsigned char *a, const int prefixlen)
{
IPAddressOrRanges *aors = make_prefix_or_range(addr, afi, safi);
IPAddressOrRange *aor;
if (aors == NULL
|| !make_addressPrefix(&aor, a, prefixlen, length_from_afi(afi)))
return 0;
if (sk_IPAddressOrRange_push(aors, aor))
return 1;
IPAddressOrRange_free(aor);
return 0;
}
/*
* Add a range.
*/
int X509v3_addr_add_range(IPAddrBlocks *addr,
const unsigned afi,
const unsigned *safi,
unsigned char *min, unsigned char *max)
{
IPAddressOrRanges *aors = make_prefix_or_range(addr, afi, safi);
IPAddressOrRange *aor;
int length = length_from_afi(afi);
if (aors == NULL)
return 0;
if (!make_addressRange(&aor, min, max, length))
return 0;
if (sk_IPAddressOrRange_push(aors, aor))
return 1;
IPAddressOrRange_free(aor);
return 0;
}
/*
* Extract min and max values from an IPAddressOrRange.
*/
static int extract_min_max(IPAddressOrRange *aor,
unsigned char *min, unsigned char *max, int length)
{
if (aor == NULL || min == NULL || max == NULL)
return 0;
switch (aor->type) {
case IPAddressOrRange_addressPrefix:
return (addr_expand(min, aor->u.addressPrefix, length, 0x00) &&
addr_expand(max, aor->u.addressPrefix, length, 0xFF));
case IPAddressOrRange_addressRange:
return (addr_expand(min, aor->u.addressRange->min, length, 0x00) &&
addr_expand(max, aor->u.addressRange->max, length, 0xFF));
}
return 0;
}
/*
* Public wrapper for extract_min_max().
*/
int X509v3_addr_get_range(IPAddressOrRange *aor,
const unsigned afi,
unsigned char *min,
unsigned char *max, const int length)
{
int afi_length = length_from_afi(afi);
if (aor == NULL || min == NULL || max == NULL ||
afi_length == 0 || length < afi_length ||
(aor->type != IPAddressOrRange_addressPrefix &&
aor->type != IPAddressOrRange_addressRange) ||
!extract_min_max(aor, min, max, afi_length))
return 0;
return afi_length;
}
/*
* Sort comparison function for a sequence of IPAddressFamily.
*
* The last paragraph of RFC 3779 2.2.3.3 is slightly ambiguous about
* the ordering: I can read it as meaning that IPv6 without a SAFI
* comes before IPv4 with a SAFI, which seems pretty weird. The
* examples in appendix B suggest that the author intended the
* null-SAFI rule to apply only within a single AFI, which is what I
* would have expected and is what the following code implements.
*/
static int IPAddressFamily_cmp(const IPAddressFamily *const *a_,
const IPAddressFamily *const *b_)
{
const ASN1_OCTET_STRING *a = (*a_)->addressFamily;
const ASN1_OCTET_STRING *b = (*b_)->addressFamily;
int len = ((a->length <= b->length) ? a->length : b->length);
int cmp = memcmp(a->data, b->data, len);
return cmp ? cmp : a->length - b->length;
}
static int IPAddressFamily_check_len(const IPAddressFamily *f)
{
if (f->addressFamily->length < 2 || f->addressFamily->length > 3)
return 0;
else
return 1;
}
/*
* Check whether an IPAddrBLocks is in canonical form.
*/
int X509v3_addr_is_canonical(IPAddrBlocks *addr)
{
unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
unsigned char b_min[ADDR_RAW_BUF_LEN], b_max[ADDR_RAW_BUF_LEN];
IPAddressOrRanges *aors;
int i, j, k;
/*
* Empty extension is canonical.
*/
if (addr == NULL)
return 1;
/*
* Check whether the top-level list is in order.
*/
for (i = 0; i < sk_IPAddressFamily_num(addr) - 1; i++) {
const IPAddressFamily *a = sk_IPAddressFamily_value(addr, i);
const IPAddressFamily *b = sk_IPAddressFamily_value(addr, i + 1);
if (!IPAddressFamily_check_len(a) || !IPAddressFamily_check_len(b))
return 0;
if (IPAddressFamily_cmp(&a, &b) >= 0)
return 0;
}
/*
* Top level's ok, now check each address family.
*/
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
int length = length_from_afi(X509v3_addr_get_afi(f));
/*
* Inheritance is canonical. Anything other than inheritance or
* a SEQUENCE OF IPAddressOrRange is an ASN.1 error or something.
*/
if (f == NULL || f->ipAddressChoice == NULL)
return 0;
switch (f->ipAddressChoice->type) {
case IPAddressChoice_inherit:
continue;
case IPAddressChoice_addressesOrRanges:
break;
default:
return 0;
}
if (!IPAddressFamily_check_len(f))
return 0;
/*
* It's an IPAddressOrRanges sequence, check it.
*/
aors = f->ipAddressChoice->u.addressesOrRanges;
if (sk_IPAddressOrRange_num(aors) == 0)
return 0;
for (j = 0; j < sk_IPAddressOrRange_num(aors) - 1; j++) {
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j);
IPAddressOrRange *b = sk_IPAddressOrRange_value(aors, j + 1);
if (!extract_min_max(a, a_min, a_max, length) ||
!extract_min_max(b, b_min, b_max, length))
return 0;
/*
* Punt misordered list, overlapping start, or inverted range.
*/
if (memcmp(a_min, b_min, length) >= 0 ||
memcmp(a_min, a_max, length) > 0 ||
memcmp(b_min, b_max, length) > 0)
return 0;
/*
* Punt if adjacent or overlapping. Check for adjacency by
* subtracting one from b_min first.
*/
for (k = length - 1; k >= 0 && b_min[k]-- == 0x00; k--) ;
if (memcmp(a_max, b_min, length) >= 0)
return 0;
/*
* Check for range that should be expressed as a prefix.
*/
if (a->type == IPAddressOrRange_addressRange &&
range_should_be_prefix(a_min, a_max, length) >= 0)
return 0;
}
/*
* Check range to see if it's inverted or should be a
* prefix.
*/
j = sk_IPAddressOrRange_num(aors) - 1;
{
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j);
if (a != NULL && a->type == IPAddressOrRange_addressRange) {
if (!extract_min_max(a, a_min, a_max, length))
return 0;
if (memcmp(a_min, a_max, length) > 0 ||
range_should_be_prefix(a_min, a_max, length) >= 0)
return 0;
}
}
}
/*
* If we made it through all that, we're happy.
*/
return 1;
}
/*
* Whack an IPAddressOrRanges into canonical form.
*/
static int IPAddressOrRanges_canonize(IPAddressOrRanges *aors,
const unsigned afi)
{
int i, j, length = length_from_afi(afi);
/*
* Sort the IPAddressOrRanges sequence.
*/
sk_IPAddressOrRange_sort(aors);
/*
* Clean up representation issues, punt on duplicates or overlaps.
*/
for (i = 0; i < sk_IPAddressOrRange_num(aors) - 1; i++) {
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, i);
IPAddressOrRange *b = sk_IPAddressOrRange_value(aors, i + 1);
unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
unsigned char b_min[ADDR_RAW_BUF_LEN], b_max[ADDR_RAW_BUF_LEN];
if (!extract_min_max(a, a_min, a_max, length) ||
!extract_min_max(b, b_min, b_max, length))
return 0;
/*
* Punt inverted ranges.
*/
if (memcmp(a_min, a_max, length) > 0 ||
memcmp(b_min, b_max, length) > 0)
return 0;
/*
* Punt overlaps.
*/
if (memcmp(a_max, b_min, length) >= 0)
return 0;
/*
* Merge if a and b are adjacent. We check for
* adjacency by subtracting one from b_min first.
*/
for (j = length - 1; j >= 0 && b_min[j]-- == 0x00; j--) ;
if (memcmp(a_max, b_min, length) == 0) {
IPAddressOrRange *merged;
if (!make_addressRange(&merged, a_min, b_max, length))
return 0;
(void)sk_IPAddressOrRange_set(aors, i, merged);
(void)sk_IPAddressOrRange_delete(aors, i + 1);
IPAddressOrRange_free(a);
IPAddressOrRange_free(b);
--i;
continue;
}
}
/*
* Check for inverted final range.
*/
j = sk_IPAddressOrRange_num(aors) - 1;
{
IPAddressOrRange *a = sk_IPAddressOrRange_value(aors, j);
if (a != NULL && a->type == IPAddressOrRange_addressRange) {
unsigned char a_min[ADDR_RAW_BUF_LEN], a_max[ADDR_RAW_BUF_LEN];
if (!extract_min_max(a, a_min, a_max, length))
return 0;
if (memcmp(a_min, a_max, length) > 0)
return 0;
}
}
return 1;
}
/*
* Whack an IPAddrBlocks extension into canonical form.
*/
int X509v3_addr_canonize(IPAddrBlocks *addr)
{
int i;
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
if (!IPAddressFamily_check_len(f))
return 0;
if (f->ipAddressChoice->type == IPAddressChoice_addressesOrRanges &&
!IPAddressOrRanges_canonize(f->ipAddressChoice->
u.addressesOrRanges,
X509v3_addr_get_afi(f)))
return 0;
}
(void)sk_IPAddressFamily_set_cmp_func(addr, IPAddressFamily_cmp);
sk_IPAddressFamily_sort(addr);
if (!ossl_assert(X509v3_addr_is_canonical(addr)))
return 0;
return 1;
}
/*
* v2i handler for the IPAddrBlocks extension.
*/
static void *v2i_IPAddrBlocks(const struct v3_ext_method *method,
struct v3_ext_ctx *ctx,
STACK_OF(CONF_VALUE) *values)
{
static const char v4addr_chars[] = "0123456789.";
static const char v6addr_chars[] = "0123456789.:abcdefABCDEF";
IPAddrBlocks *addr = NULL;
char *s = NULL, *t;
int i;
if ((addr = sk_IPAddressFamily_new(IPAddressFamily_cmp)) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
return NULL;
}
for (i = 0; i < sk_CONF_VALUE_num(values); i++) {
CONF_VALUE *val = sk_CONF_VALUE_value(values, i);
unsigned char min[ADDR_RAW_BUF_LEN], max[ADDR_RAW_BUF_LEN];
unsigned afi, *safi = NULL, safi_;
const char *addr_chars = NULL;
int prefixlen, i1, i2, delim, length;
if (!ossl_v3_name_cmp(val->name, "IPv4")) {
afi = IANA_AFI_IPV4;
} else if (!ossl_v3_name_cmp(val->name, "IPv6")) {
afi = IANA_AFI_IPV6;
} else if (!ossl_v3_name_cmp(val->name, "IPv4-SAFI")) {
afi = IANA_AFI_IPV4;
safi = &safi_;
} else if (!ossl_v3_name_cmp(val->name, "IPv6-SAFI")) {
afi = IANA_AFI_IPV6;
safi = &safi_;
} else {
ERR_raise_data(ERR_LIB_X509V3, X509V3_R_EXTENSION_NAME_ERROR,
"%s", val->name);
goto err;
}
switch (afi) {
case IANA_AFI_IPV4:
addr_chars = v4addr_chars;
break;
case IANA_AFI_IPV6:
addr_chars = v6addr_chars;
break;
}
length = length_from_afi(afi);
/*
* Handle SAFI, if any, and OPENSSL_strdup() so we can null-terminate
* the other input values.
*/
if (safi != NULL) {
if (val->value == NULL) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_MISSING_VALUE);
goto err;
}
*safi = strtoul(val->value, &t, 0);
t += strspn(t, " \t");
if (*safi > 0xFF || *t++ != ':') {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_SAFI);
X509V3_conf_add_error_name_value(val);
goto err;
}
t += strspn(t, " \t");
s = OPENSSL_strdup(t);
} else {
s = OPENSSL_strdup(val->value);
}
if (s == NULL)
goto err;
/*
* Check for inheritance. Not worth additional complexity to
* optimize this (seldom-used) case.
*/
if (strcmp(s, "inherit") == 0) {
if (!X509v3_addr_add_inherit(addr, afi, safi)) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_INHERITANCE);
X509V3_conf_add_error_name_value(val);
goto err;
}
OPENSSL_free(s);
s = NULL;
continue;
}
i1 = strspn(s, addr_chars);
i2 = i1 + strspn(s + i1, " \t");
delim = s[i2++];
s[i1] = '\0';
if (ossl_a2i_ipadd(min, s) != length) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_IPADDRESS);
X509V3_conf_add_error_name_value(val);
goto err;
}
switch (delim) {
case '/':
prefixlen = (int)strtoul(s + i2, &t, 10);
if (t == s + i2
|| *t != '\0'
|| prefixlen > (length * 8)
|| prefixlen < 0) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_add_error_name_value(val);
goto err;
}
if (!X509v3_addr_add_prefix(addr, afi, safi, min, prefixlen)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB);
goto err;
}
break;
case '-':
i1 = i2 + strspn(s + i2, " \t");
i2 = i1 + strspn(s + i1, addr_chars);
if (i1 == i2 || s[i2] != '\0') {
ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_add_error_name_value(val);
goto err;
}
if (ossl_a2i_ipadd(max, s + i1) != length) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_INVALID_IPADDRESS);
X509V3_conf_add_error_name_value(val);
goto err;
}
if (memcmp(min, max, length_from_afi(afi)) > 0) {
ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_add_error_name_value(val);
goto err;
}
if (!X509v3_addr_add_range(addr, afi, safi, min, max)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB);
goto err;
}
break;
case '\0':
if (!X509v3_addr_add_prefix(addr, afi, safi, min, length * 8)) {
ERR_raise(ERR_LIB_X509V3, ERR_R_X509V3_LIB);
goto err;
}
break;
default:
ERR_raise(ERR_LIB_X509V3, X509V3_R_EXTENSION_VALUE_ERROR);
X509V3_conf_add_error_name_value(val);
goto err;
}
OPENSSL_free(s);
s = NULL;
}
/*
* Canonize the result, then we're done.
*/
if (!X509v3_addr_canonize(addr))
goto err;
return addr;
err:
OPENSSL_free(s);
sk_IPAddressFamily_pop_free(addr, IPAddressFamily_free);
return NULL;
}
/*
* OpenSSL dispatch
*/
const X509V3_EXT_METHOD ossl_v3_addr = {
NID_sbgp_ipAddrBlock, /* nid */
0, /* flags */
ASN1_ITEM_ref(IPAddrBlocks), /* template */
0, 0, 0, 0, /* old functions, ignored */
0, /* i2s */
0, /* s2i */
0, /* i2v */
v2i_IPAddrBlocks, /* v2i */
i2r_IPAddrBlocks, /* i2r */
0, /* r2i */
NULL /* extension-specific data */
};
/*
* Figure out whether extension sues inheritance.
*/
int X509v3_addr_inherits(IPAddrBlocks *addr)
{
int i;
if (addr == NULL)
return 0;
for (i = 0; i < sk_IPAddressFamily_num(addr); i++) {
IPAddressFamily *f = sk_IPAddressFamily_value(addr, i);
if (f->ipAddressChoice->type == IPAddressChoice_inherit)
return 1;
}
return 0;
}
/*
* Figure out whether parent contains child.
*/
static int addr_contains(IPAddressOrRanges *parent,
IPAddressOrRanges *child, int length)
{
unsigned char p_min[ADDR_RAW_BUF_LEN], p_max[ADDR_RAW_BUF_LEN];
unsigned char c_min[ADDR_RAW_BUF_LEN], c_max[ADDR_RAW_BUF_LEN];
int p, c;
if (child == NULL || parent == child)
return 1;
if (parent == NULL)
return 0;
p = 0;
for (c = 0; c < sk_IPAddressOrRange_num(child); c++) {
if (!extract_min_max(sk_IPAddressOrRange_value(child, c),
c_min, c_max, length))
return 0;
for (;; p++) {
if (p >= sk_IPAddressOrRange_num(parent))
return 0;
if (!extract_min_max(sk_IPAddressOrRange_value(parent, p),
p_min, p_max, length))
return 0;
if (memcmp(p_max, c_max, length) < 0)
continue;
if (memcmp(p_min, c_min, length) > 0)
return 0;
break;
}
}
return 1;
}
/*
* Test whether a is a subset of b.
*/
int X509v3_addr_subset(IPAddrBlocks *a, IPAddrBlocks *b)
{
int i;
if (a == NULL || a == b)
return 1;
if (b == NULL || X509v3_addr_inherits(a) || X509v3_addr_inherits(b))
return 0;
(void)sk_IPAddressFamily_set_cmp_func(b, IPAddressFamily_cmp);
sk_IPAddressFamily_sort(b);
/* Could sort a here too and get O(|a|) running time instead of O(|a| ln |b|) */
for (i = 0; i < sk_IPAddressFamily_num(a); i++) {
IPAddressFamily *fa = sk_IPAddressFamily_value(a, i);
int j = sk_IPAddressFamily_find(b, fa);
IPAddressFamily *fb = sk_IPAddressFamily_value(b, j);
if (fb == NULL)
return 0;
if (!IPAddressFamily_check_len(fa) || !IPAddressFamily_check_len(fb))
return 0;
if (!addr_contains(fb->ipAddressChoice->u.addressesOrRanges,
fa->ipAddressChoice->u.addressesOrRanges,
length_from_afi(X509v3_addr_get_afi(fb))))
return 0;
}
return 1;
}
/*
* Validation error handling via callback.
*/
# define validation_err(_err_) \
do { \
if (ctx != NULL) { \
ctx->error = _err_; \
ctx->error_depth = i; \
ctx->current_cert = x; \
rv = ctx->verify_cb(0, ctx); \
} else { \
rv = 0; \
} \
if (rv == 0) \
goto done; \
} while (0)
/*
* Core code for RFC 3779 2.3 path validation.
*
* Returns 1 for success, 0 on error.
*
* When returning 0, ctx->error MUST be set to an appropriate value other than
* X509_V_OK.
*/
static int addr_validate_path_internal(X509_STORE_CTX *ctx,
STACK_OF(X509) *chain,
IPAddrBlocks *ext)
{
IPAddrBlocks *child = NULL;
int i, j, ret = 0, rv;
X509 *x;
if (!ossl_assert(chain != NULL && sk_X509_num(chain) > 0)
|| !ossl_assert(ctx != NULL || ext != NULL)
|| !ossl_assert(ctx == NULL || ctx->verify_cb != NULL)) {
if (ctx != NULL)
ctx->error = X509_V_ERR_UNSPECIFIED;
return 0;
}
/*
* Figure out where to start. If we don't have an extension to
* check, we're done. Otherwise, check canonical form and
* set up for walking up the chain.
*/
if (ext != NULL) {
i = -1;
x = NULL;
} else {
i = 0;
x = sk_X509_value(chain, i);
if ((ext = x->rfc3779_addr) == NULL)
return 1; /* Return success */
}
if (!X509v3_addr_is_canonical(ext))
validation_err(X509_V_ERR_INVALID_EXTENSION);
(void)sk_IPAddressFamily_set_cmp_func(ext, IPAddressFamily_cmp);
if ((child = sk_IPAddressFamily_dup(ext)) == NULL) {
ERR_raise(ERR_LIB_X509V3, ERR_R_CRYPTO_LIB);
if (ctx != NULL)
ctx->error = X509_V_ERR_OUT_OF_MEM;
goto done;
}
sk_IPAddressFamily_sort(child);
/*
* Now walk up the chain. No cert may list resources that its
* parent doesn't list.
*/
for (i++; i < sk_X509_num(chain); i++) {
x = sk_X509_value(chain, i);
if (!X509v3_addr_is_canonical(x->rfc3779_addr))
validation_err(X509_V_ERR_INVALID_EXTENSION);
if (x->rfc3779_addr == NULL) {
for (j = 0; j < sk_IPAddressFamily_num(child); j++) {
IPAddressFamily *fc = sk_IPAddressFamily_value(child, j);
if (!IPAddressFamily_check_len(fc))
goto done;
if (fc->ipAddressChoice->type != IPAddressChoice_inherit) {
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
break;
}
}
continue;
}
(void)sk_IPAddressFamily_set_cmp_func(x->rfc3779_addr,
IPAddressFamily_cmp);
sk_IPAddressFamily_sort(x->rfc3779_addr);
for (j = 0; j < sk_IPAddressFamily_num(child); j++) {
IPAddressFamily *fc = sk_IPAddressFamily_value(child, j);
int k = sk_IPAddressFamily_find(x->rfc3779_addr, fc);
IPAddressFamily *fp =
sk_IPAddressFamily_value(x->rfc3779_addr, k);
if (fp == NULL) {
if (fc->ipAddressChoice->type ==
IPAddressChoice_addressesOrRanges) {
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
break;
}
continue;
}
if (!IPAddressFamily_check_len(fc) || !IPAddressFamily_check_len(fp))
goto done;
if (fp->ipAddressChoice->type ==
IPAddressChoice_addressesOrRanges) {
if (fc->ipAddressChoice->type == IPAddressChoice_inherit
|| addr_contains(fp->ipAddressChoice->u.addressesOrRanges,
fc->ipAddressChoice->u.addressesOrRanges,
length_from_afi(X509v3_addr_get_afi(fc))))
(void)sk_IPAddressFamily_set(child, j, fp);
else
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
}
}
}
/*
* Trust anchor can't inherit.
*/
if (x->rfc3779_addr != NULL) {
for (j = 0; j < sk_IPAddressFamily_num(x->rfc3779_addr); j++) {
IPAddressFamily *fp = sk_IPAddressFamily_value(x->rfc3779_addr, j);
if (!IPAddressFamily_check_len(fp))
goto done;
if (fp->ipAddressChoice->type == IPAddressChoice_inherit
&& sk_IPAddressFamily_find(child, fp) >= 0)
validation_err(X509_V_ERR_UNNESTED_RESOURCE);
}
}
ret = 1;
done:
sk_IPAddressFamily_free(child);
return ret;
}
# undef validation_err
/*
* RFC 3779 2.3 path validation -- called from X509_verify_cert().
*/
int X509v3_addr_validate_path(X509_STORE_CTX *ctx)
{
if (ctx->chain == NULL
|| sk_X509_num(ctx->chain) == 0
|| ctx->verify_cb == NULL) {
ctx->error = X509_V_ERR_UNSPECIFIED;
return 0;
}
return addr_validate_path_internal(ctx, ctx->chain, NULL);
}
/*
* RFC 3779 2.3 path validation of an extension.
* Test whether chain covers extension.
*/
int X509v3_addr_validate_resource_set(STACK_OF(X509) *chain,
IPAddrBlocks *ext, int allow_inheritance)
{
if (ext == NULL)
return 1;
if (chain == NULL || sk_X509_num(chain) == 0)
return 0;
if (!allow_inheritance && X509v3_addr_inherits(ext))
return 0;
return addr_validate_path_internal(NULL, chain, ext);
}
#endif /* OPENSSL_NO_RFC3779 */
|
./openssl/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;
}
|
./openssl/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;
}
|
./openssl/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;
}
|
./openssl/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;
}
|
./openssl/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;
}
|
./openssl/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)
|
./openssl/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);
}
|
./openssl/crypto/x509/pcy_cache.c | /*
* Copyright 2004-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 "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;
}
|
./openssl/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)
|
./openssl/crypto/x509/x509_vpm.c | /*
* Copyright 2004-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 "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;
}
if (sk_ASN1_OBJECT_push(param->policies, policy) <= 0)
return 0;
return 1;
}
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);
}
}
if (sk_X509_VERIFY_PARAM_push(param_table, param) <= 0)
return 0;
return 1;
}
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;
}
|
./openssl/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;
}
|
./openssl/crypto/x509/v3_ist.c | /*
* Copyright 2020-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 "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
|| cnf->value == NULL
|| !ASN1_STRING_set(ist->signTool, cnf->value, strlen(cnf->value))) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
} else if (strcmp(cnf->name, "cATool") == 0) {
ist->cATool = ASN1_UTF8STRING_new();
if (ist->cATool == NULL
|| cnf->value == NULL
|| !ASN1_STRING_set(ist->cATool, cnf->value, strlen(cnf->value))) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
} else if (strcmp(cnf->name, "signToolCert") == 0) {
ist->signToolCert = ASN1_UTF8STRING_new();
if (ist->signToolCert == NULL
|| cnf->value == NULL
|| !ASN1_STRING_set(ist->signToolCert, cnf->value, strlen(cnf->value))) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
} else if (strcmp(cnf->name, "cAToolCert") == 0) {
ist->cAToolCert = ASN1_UTF8STRING_new();
if (ist->cAToolCert == NULL
|| cnf->value == NULL
|| !ASN1_STRING_set(ist->cAToolCert, cnf->value, strlen(cnf->value))) {
ERR_raise(ERR_LIB_X509V3, ERR_R_ASN1_LIB);
goto err;
}
} else {
ERR_raise(ERR_LIB_X509V3, ERR_R_PASSED_INVALID_ARGUMENT);
goto err;
}
}
return ist;
err:
ISSUER_SIGN_TOOL_free(ist);
return NULL;
}
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) {
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 */
};
|
./openssl/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);
}
|
./openssl/crypto/sm4/sm4.c | /*
* Copyright 2017-2022 The OpenSSL Project Authors. All Rights Reserved.
* Copyright 2017 Ribose Inc. All Rights Reserved.
* Ported from Ribose contributions from Botan.
*
* 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/e_os2.h>
#include "crypto/sm4.h"
static const uint8_t SM4_S[256] = {
0xD6, 0x90, 0xE9, 0xFE, 0xCC, 0xE1, 0x3D, 0xB7, 0x16, 0xB6, 0x14, 0xC2,
0x28, 0xFB, 0x2C, 0x05, 0x2B, 0x67, 0x9A, 0x76, 0x2A, 0xBE, 0x04, 0xC3,
0xAA, 0x44, 0x13, 0x26, 0x49, 0x86, 0x06, 0x99, 0x9C, 0x42, 0x50, 0xF4,
0x91, 0xEF, 0x98, 0x7A, 0x33, 0x54, 0x0B, 0x43, 0xED, 0xCF, 0xAC, 0x62,
0xE4, 0xB3, 0x1C, 0xA9, 0xC9, 0x08, 0xE8, 0x95, 0x80, 0xDF, 0x94, 0xFA,
0x75, 0x8F, 0x3F, 0xA6, 0x47, 0x07, 0xA7, 0xFC, 0xF3, 0x73, 0x17, 0xBA,
0x83, 0x59, 0x3C, 0x19, 0xE6, 0x85, 0x4F, 0xA8, 0x68, 0x6B, 0x81, 0xB2,
0x71, 0x64, 0xDA, 0x8B, 0xF8, 0xEB, 0x0F, 0x4B, 0x70, 0x56, 0x9D, 0x35,
0x1E, 0x24, 0x0E, 0x5E, 0x63, 0x58, 0xD1, 0xA2, 0x25, 0x22, 0x7C, 0x3B,
0x01, 0x21, 0x78, 0x87, 0xD4, 0x00, 0x46, 0x57, 0x9F, 0xD3, 0x27, 0x52,
0x4C, 0x36, 0x02, 0xE7, 0xA0, 0xC4, 0xC8, 0x9E, 0xEA, 0xBF, 0x8A, 0xD2,
0x40, 0xC7, 0x38, 0xB5, 0xA3, 0xF7, 0xF2, 0xCE, 0xF9, 0x61, 0x15, 0xA1,
0xE0, 0xAE, 0x5D, 0xA4, 0x9B, 0x34, 0x1A, 0x55, 0xAD, 0x93, 0x32, 0x30,
0xF5, 0x8C, 0xB1, 0xE3, 0x1D, 0xF6, 0xE2, 0x2E, 0x82, 0x66, 0xCA, 0x60,
0xC0, 0x29, 0x23, 0xAB, 0x0D, 0x53, 0x4E, 0x6F, 0xD5, 0xDB, 0x37, 0x45,
0xDE, 0xFD, 0x8E, 0x2F, 0x03, 0xFF, 0x6A, 0x72, 0x6D, 0x6C, 0x5B, 0x51,
0x8D, 0x1B, 0xAF, 0x92, 0xBB, 0xDD, 0xBC, 0x7F, 0x11, 0xD9, 0x5C, 0x41,
0x1F, 0x10, 0x5A, 0xD8, 0x0A, 0xC1, 0x31, 0x88, 0xA5, 0xCD, 0x7B, 0xBD,
0x2D, 0x74, 0xD0, 0x12, 0xB8, 0xE5, 0xB4, 0xB0, 0x89, 0x69, 0x97, 0x4A,
0x0C, 0x96, 0x77, 0x7E, 0x65, 0xB9, 0xF1, 0x09, 0xC5, 0x6E, 0xC6, 0x84,
0x18, 0xF0, 0x7D, 0xEC, 0x3A, 0xDC, 0x4D, 0x20, 0x79, 0xEE, 0x5F, 0x3E,
0xD7, 0xCB, 0x39, 0x48
};
/*
* SM4_SBOX_T[j] == L(SM4_SBOX[j]).
*/
static const uint32_t SM4_SBOX_T0[256] = {
0x8ED55B5B, 0xD0924242, 0x4DEAA7A7, 0x06FDFBFB, 0xFCCF3333, 0x65E28787,
0xC93DF4F4, 0x6BB5DEDE, 0x4E165858, 0x6EB4DADA, 0x44145050, 0xCAC10B0B,
0x8828A0A0, 0x17F8EFEF, 0x9C2CB0B0, 0x11051414, 0x872BACAC, 0xFB669D9D,
0xF2986A6A, 0xAE77D9D9, 0x822AA8A8, 0x46BCFAFA, 0x14041010, 0xCFC00F0F,
0x02A8AAAA, 0x54451111, 0x5F134C4C, 0xBE269898, 0x6D482525, 0x9E841A1A,
0x1E061818, 0xFD9B6666, 0xEC9E7272, 0x4A430909, 0x10514141, 0x24F7D3D3,
0xD5934646, 0x53ECBFBF, 0xF89A6262, 0x927BE9E9, 0xFF33CCCC, 0x04555151,
0x270B2C2C, 0x4F420D0D, 0x59EEB7B7, 0xF3CC3F3F, 0x1CAEB2B2, 0xEA638989,
0x74E79393, 0x7FB1CECE, 0x6C1C7070, 0x0DABA6A6, 0xEDCA2727, 0x28082020,
0x48EBA3A3, 0xC1975656, 0x80820202, 0xA3DC7F7F, 0xC4965252, 0x12F9EBEB,
0xA174D5D5, 0xB38D3E3E, 0xC33FFCFC, 0x3EA49A9A, 0x5B461D1D, 0x1B071C1C,
0x3BA59E9E, 0x0CFFF3F3, 0x3FF0CFCF, 0xBF72CDCD, 0x4B175C5C, 0x52B8EAEA,
0x8F810E0E, 0x3D586565, 0xCC3CF0F0, 0x7D196464, 0x7EE59B9B, 0x91871616,
0x734E3D3D, 0x08AAA2A2, 0xC869A1A1, 0xC76AADAD, 0x85830606, 0x7AB0CACA,
0xB570C5C5, 0xF4659191, 0xB2D96B6B, 0xA7892E2E, 0x18FBE3E3, 0x47E8AFAF,
0x330F3C3C, 0x674A2D2D, 0xB071C1C1, 0x0E575959, 0xE99F7676, 0xE135D4D4,
0x661E7878, 0xB4249090, 0x360E3838, 0x265F7979, 0xEF628D8D, 0x38596161,
0x95D24747, 0x2AA08A8A, 0xB1259494, 0xAA228888, 0x8C7DF1F1, 0xD73BECEC,
0x05010404, 0xA5218484, 0x9879E1E1, 0x9B851E1E, 0x84D75353, 0x00000000,
0x5E471919, 0x0B565D5D, 0xE39D7E7E, 0x9FD04F4F, 0xBB279C9C, 0x1A534949,
0x7C4D3131, 0xEE36D8D8, 0x0A020808, 0x7BE49F9F, 0x20A28282, 0xD4C71313,
0xE8CB2323, 0xE69C7A7A, 0x42E9ABAB, 0x43BDFEFE, 0xA2882A2A, 0x9AD14B4B,
0x40410101, 0xDBC41F1F, 0xD838E0E0, 0x61B7D6D6, 0x2FA18E8E, 0x2BF4DFDF,
0x3AF1CBCB, 0xF6CD3B3B, 0x1DFAE7E7, 0xE5608585, 0x41155454, 0x25A38686,
0x60E38383, 0x16ACBABA, 0x295C7575, 0x34A69292, 0xF7996E6E, 0xE434D0D0,
0x721A6868, 0x01545555, 0x19AFB6B6, 0xDF914E4E, 0xFA32C8C8, 0xF030C0C0,
0x21F6D7D7, 0xBC8E3232, 0x75B3C6C6, 0x6FE08F8F, 0x691D7474, 0x2EF5DBDB,
0x6AE18B8B, 0x962EB8B8, 0x8A800A0A, 0xFE679999, 0xE2C92B2B, 0xE0618181,
0xC0C30303, 0x8D29A4A4, 0xAF238C8C, 0x07A9AEAE, 0x390D3434, 0x1F524D4D,
0x764F3939, 0xD36EBDBD, 0x81D65757, 0xB7D86F6F, 0xEB37DCDC, 0x51441515,
0xA6DD7B7B, 0x09FEF7F7, 0xB68C3A3A, 0x932FBCBC, 0x0F030C0C, 0x03FCFFFF,
0xC26BA9A9, 0xBA73C9C9, 0xD96CB5B5, 0xDC6DB1B1, 0x375A6D6D, 0x15504545,
0xB98F3636, 0x771B6C6C, 0x13ADBEBE, 0xDA904A4A, 0x57B9EEEE, 0xA9DE7777,
0x4CBEF2F2, 0x837EFDFD, 0x55114444, 0xBDDA6767, 0x2C5D7171, 0x45400505,
0x631F7C7C, 0x50104040, 0x325B6969, 0xB8DB6363, 0x220A2828, 0xC5C20707,
0xF531C4C4, 0xA88A2222, 0x31A79696, 0xF9CE3737, 0x977AEDED, 0x49BFF6F6,
0x992DB4B4, 0xA475D1D1, 0x90D34343, 0x5A124848, 0x58BAE2E2, 0x71E69797,
0x64B6D2D2, 0x70B2C2C2, 0xAD8B2626, 0xCD68A5A5, 0xCB955E5E, 0x624B2929,
0x3C0C3030, 0xCE945A5A, 0xAB76DDDD, 0x867FF9F9, 0xF1649595, 0x5DBBE6E6,
0x35F2C7C7, 0x2D092424, 0xD1C61717, 0xD66FB9B9, 0xDEC51B1B, 0x94861212,
0x78186060, 0x30F3C3C3, 0x897CF5F5, 0x5CEFB3B3, 0xD23AE8E8, 0xACDF7373,
0x794C3535, 0xA0208080, 0x9D78E5E5, 0x56EDBBBB, 0x235E7D7D, 0xC63EF8F8,
0x8BD45F5F, 0xE7C82F2F, 0xDD39E4E4, 0x68492121 };
static uint32_t SM4_SBOX_T1[256] = {
0x5B8ED55B, 0x42D09242, 0xA74DEAA7, 0xFB06FDFB, 0x33FCCF33, 0x8765E287,
0xF4C93DF4, 0xDE6BB5DE, 0x584E1658, 0xDA6EB4DA, 0x50441450, 0x0BCAC10B,
0xA08828A0, 0xEF17F8EF, 0xB09C2CB0, 0x14110514, 0xAC872BAC, 0x9DFB669D,
0x6AF2986A, 0xD9AE77D9, 0xA8822AA8, 0xFA46BCFA, 0x10140410, 0x0FCFC00F,
0xAA02A8AA, 0x11544511, 0x4C5F134C, 0x98BE2698, 0x256D4825, 0x1A9E841A,
0x181E0618, 0x66FD9B66, 0x72EC9E72, 0x094A4309, 0x41105141, 0xD324F7D3,
0x46D59346, 0xBF53ECBF, 0x62F89A62, 0xE9927BE9, 0xCCFF33CC, 0x51045551,
0x2C270B2C, 0x0D4F420D, 0xB759EEB7, 0x3FF3CC3F, 0xB21CAEB2, 0x89EA6389,
0x9374E793, 0xCE7FB1CE, 0x706C1C70, 0xA60DABA6, 0x27EDCA27, 0x20280820,
0xA348EBA3, 0x56C19756, 0x02808202, 0x7FA3DC7F, 0x52C49652, 0xEB12F9EB,
0xD5A174D5, 0x3EB38D3E, 0xFCC33FFC, 0x9A3EA49A, 0x1D5B461D, 0x1C1B071C,
0x9E3BA59E, 0xF30CFFF3, 0xCF3FF0CF, 0xCDBF72CD, 0x5C4B175C, 0xEA52B8EA,
0x0E8F810E, 0x653D5865, 0xF0CC3CF0, 0x647D1964, 0x9B7EE59B, 0x16918716,
0x3D734E3D, 0xA208AAA2, 0xA1C869A1, 0xADC76AAD, 0x06858306, 0xCA7AB0CA,
0xC5B570C5, 0x91F46591, 0x6BB2D96B, 0x2EA7892E, 0xE318FBE3, 0xAF47E8AF,
0x3C330F3C, 0x2D674A2D, 0xC1B071C1, 0x590E5759, 0x76E99F76, 0xD4E135D4,
0x78661E78, 0x90B42490, 0x38360E38, 0x79265F79, 0x8DEF628D, 0x61385961,
0x4795D247, 0x8A2AA08A, 0x94B12594, 0x88AA2288, 0xF18C7DF1, 0xECD73BEC,
0x04050104, 0x84A52184, 0xE19879E1, 0x1E9B851E, 0x5384D753, 0x00000000,
0x195E4719, 0x5D0B565D, 0x7EE39D7E, 0x4F9FD04F, 0x9CBB279C, 0x491A5349,
0x317C4D31, 0xD8EE36D8, 0x080A0208, 0x9F7BE49F, 0x8220A282, 0x13D4C713,
0x23E8CB23, 0x7AE69C7A, 0xAB42E9AB, 0xFE43BDFE, 0x2AA2882A, 0x4B9AD14B,
0x01404101, 0x1FDBC41F, 0xE0D838E0, 0xD661B7D6, 0x8E2FA18E, 0xDF2BF4DF,
0xCB3AF1CB, 0x3BF6CD3B, 0xE71DFAE7, 0x85E56085, 0x54411554, 0x8625A386,
0x8360E383, 0xBA16ACBA, 0x75295C75, 0x9234A692, 0x6EF7996E, 0xD0E434D0,
0x68721A68, 0x55015455, 0xB619AFB6, 0x4EDF914E, 0xC8FA32C8, 0xC0F030C0,
0xD721F6D7, 0x32BC8E32, 0xC675B3C6, 0x8F6FE08F, 0x74691D74, 0xDB2EF5DB,
0x8B6AE18B, 0xB8962EB8, 0x0A8A800A, 0x99FE6799, 0x2BE2C92B, 0x81E06181,
0x03C0C303, 0xA48D29A4, 0x8CAF238C, 0xAE07A9AE, 0x34390D34, 0x4D1F524D,
0x39764F39, 0xBDD36EBD, 0x5781D657, 0x6FB7D86F, 0xDCEB37DC, 0x15514415,
0x7BA6DD7B, 0xF709FEF7, 0x3AB68C3A, 0xBC932FBC, 0x0C0F030C, 0xFF03FCFF,
0xA9C26BA9, 0xC9BA73C9, 0xB5D96CB5, 0xB1DC6DB1, 0x6D375A6D, 0x45155045,
0x36B98F36, 0x6C771B6C, 0xBE13ADBE, 0x4ADA904A, 0xEE57B9EE, 0x77A9DE77,
0xF24CBEF2, 0xFD837EFD, 0x44551144, 0x67BDDA67, 0x712C5D71, 0x05454005,
0x7C631F7C, 0x40501040, 0x69325B69, 0x63B8DB63, 0x28220A28, 0x07C5C207,
0xC4F531C4, 0x22A88A22, 0x9631A796, 0x37F9CE37, 0xED977AED, 0xF649BFF6,
0xB4992DB4, 0xD1A475D1, 0x4390D343, 0x485A1248, 0xE258BAE2, 0x9771E697,
0xD264B6D2, 0xC270B2C2, 0x26AD8B26, 0xA5CD68A5, 0x5ECB955E, 0x29624B29,
0x303C0C30, 0x5ACE945A, 0xDDAB76DD, 0xF9867FF9, 0x95F16495, 0xE65DBBE6,
0xC735F2C7, 0x242D0924, 0x17D1C617, 0xB9D66FB9, 0x1BDEC51B, 0x12948612,
0x60781860, 0xC330F3C3, 0xF5897CF5, 0xB35CEFB3, 0xE8D23AE8, 0x73ACDF73,
0x35794C35, 0x80A02080, 0xE59D78E5, 0xBB56EDBB, 0x7D235E7D, 0xF8C63EF8,
0x5F8BD45F, 0x2FE7C82F, 0xE4DD39E4, 0x21684921};
static uint32_t SM4_SBOX_T2[256] = {
0x5B5B8ED5, 0x4242D092, 0xA7A74DEA, 0xFBFB06FD, 0x3333FCCF, 0x878765E2,
0xF4F4C93D, 0xDEDE6BB5, 0x58584E16, 0xDADA6EB4, 0x50504414, 0x0B0BCAC1,
0xA0A08828, 0xEFEF17F8, 0xB0B09C2C, 0x14141105, 0xACAC872B, 0x9D9DFB66,
0x6A6AF298, 0xD9D9AE77, 0xA8A8822A, 0xFAFA46BC, 0x10101404, 0x0F0FCFC0,
0xAAAA02A8, 0x11115445, 0x4C4C5F13, 0x9898BE26, 0x25256D48, 0x1A1A9E84,
0x18181E06, 0x6666FD9B, 0x7272EC9E, 0x09094A43, 0x41411051, 0xD3D324F7,
0x4646D593, 0xBFBF53EC, 0x6262F89A, 0xE9E9927B, 0xCCCCFF33, 0x51510455,
0x2C2C270B, 0x0D0D4F42, 0xB7B759EE, 0x3F3FF3CC, 0xB2B21CAE, 0x8989EA63,
0x939374E7, 0xCECE7FB1, 0x70706C1C, 0xA6A60DAB, 0x2727EDCA, 0x20202808,
0xA3A348EB, 0x5656C197, 0x02028082, 0x7F7FA3DC, 0x5252C496, 0xEBEB12F9,
0xD5D5A174, 0x3E3EB38D, 0xFCFCC33F, 0x9A9A3EA4, 0x1D1D5B46, 0x1C1C1B07,
0x9E9E3BA5, 0xF3F30CFF, 0xCFCF3FF0, 0xCDCDBF72, 0x5C5C4B17, 0xEAEA52B8,
0x0E0E8F81, 0x65653D58, 0xF0F0CC3C, 0x64647D19, 0x9B9B7EE5, 0x16169187,
0x3D3D734E, 0xA2A208AA, 0xA1A1C869, 0xADADC76A, 0x06068583, 0xCACA7AB0,
0xC5C5B570, 0x9191F465, 0x6B6BB2D9, 0x2E2EA789, 0xE3E318FB, 0xAFAF47E8,
0x3C3C330F, 0x2D2D674A, 0xC1C1B071, 0x59590E57, 0x7676E99F, 0xD4D4E135,
0x7878661E, 0x9090B424, 0x3838360E, 0x7979265F, 0x8D8DEF62, 0x61613859,
0x474795D2, 0x8A8A2AA0, 0x9494B125, 0x8888AA22, 0xF1F18C7D, 0xECECD73B,
0x04040501, 0x8484A521, 0xE1E19879, 0x1E1E9B85, 0x535384D7, 0x00000000,
0x19195E47, 0x5D5D0B56, 0x7E7EE39D, 0x4F4F9FD0, 0x9C9CBB27, 0x49491A53,
0x31317C4D, 0xD8D8EE36, 0x08080A02, 0x9F9F7BE4, 0x828220A2, 0x1313D4C7,
0x2323E8CB, 0x7A7AE69C, 0xABAB42E9, 0xFEFE43BD, 0x2A2AA288, 0x4B4B9AD1,
0x01014041, 0x1F1FDBC4, 0xE0E0D838, 0xD6D661B7, 0x8E8E2FA1, 0xDFDF2BF4,
0xCBCB3AF1, 0x3B3BF6CD, 0xE7E71DFA, 0x8585E560, 0x54544115, 0x868625A3,
0x838360E3, 0xBABA16AC, 0x7575295C, 0x929234A6, 0x6E6EF799, 0xD0D0E434,
0x6868721A, 0x55550154, 0xB6B619AF, 0x4E4EDF91, 0xC8C8FA32, 0xC0C0F030,
0xD7D721F6, 0x3232BC8E, 0xC6C675B3, 0x8F8F6FE0, 0x7474691D, 0xDBDB2EF5,
0x8B8B6AE1, 0xB8B8962E, 0x0A0A8A80, 0x9999FE67, 0x2B2BE2C9, 0x8181E061,
0x0303C0C3, 0xA4A48D29, 0x8C8CAF23, 0xAEAE07A9, 0x3434390D, 0x4D4D1F52,
0x3939764F, 0xBDBDD36E, 0x575781D6, 0x6F6FB7D8, 0xDCDCEB37, 0x15155144,
0x7B7BA6DD, 0xF7F709FE, 0x3A3AB68C, 0xBCBC932F, 0x0C0C0F03, 0xFFFF03FC,
0xA9A9C26B, 0xC9C9BA73, 0xB5B5D96C, 0xB1B1DC6D, 0x6D6D375A, 0x45451550,
0x3636B98F, 0x6C6C771B, 0xBEBE13AD, 0x4A4ADA90, 0xEEEE57B9, 0x7777A9DE,
0xF2F24CBE, 0xFDFD837E, 0x44445511, 0x6767BDDA, 0x71712C5D, 0x05054540,
0x7C7C631F, 0x40405010, 0x6969325B, 0x6363B8DB, 0x2828220A, 0x0707C5C2,
0xC4C4F531, 0x2222A88A, 0x969631A7, 0x3737F9CE, 0xEDED977A, 0xF6F649BF,
0xB4B4992D, 0xD1D1A475, 0x434390D3, 0x48485A12, 0xE2E258BA, 0x979771E6,
0xD2D264B6, 0xC2C270B2, 0x2626AD8B, 0xA5A5CD68, 0x5E5ECB95, 0x2929624B,
0x30303C0C, 0x5A5ACE94, 0xDDDDAB76, 0xF9F9867F, 0x9595F164, 0xE6E65DBB,
0xC7C735F2, 0x24242D09, 0x1717D1C6, 0xB9B9D66F, 0x1B1BDEC5, 0x12129486,
0x60607818, 0xC3C330F3, 0xF5F5897C, 0xB3B35CEF, 0xE8E8D23A, 0x7373ACDF,
0x3535794C, 0x8080A020, 0xE5E59D78, 0xBBBB56ED, 0x7D7D235E, 0xF8F8C63E,
0x5F5F8BD4, 0x2F2FE7C8, 0xE4E4DD39, 0x21216849};
static uint32_t SM4_SBOX_T3[256] = {
0xD55B5B8E, 0x924242D0, 0xEAA7A74D, 0xFDFBFB06, 0xCF3333FC, 0xE2878765,
0x3DF4F4C9, 0xB5DEDE6B, 0x1658584E, 0xB4DADA6E, 0x14505044, 0xC10B0BCA,
0x28A0A088, 0xF8EFEF17, 0x2CB0B09C, 0x05141411, 0x2BACAC87, 0x669D9DFB,
0x986A6AF2, 0x77D9D9AE, 0x2AA8A882, 0xBCFAFA46, 0x04101014, 0xC00F0FCF,
0xA8AAAA02, 0x45111154, 0x134C4C5F, 0x269898BE, 0x4825256D, 0x841A1A9E,
0x0618181E, 0x9B6666FD, 0x9E7272EC, 0x4309094A, 0x51414110, 0xF7D3D324,
0x934646D5, 0xECBFBF53, 0x9A6262F8, 0x7BE9E992, 0x33CCCCFF, 0x55515104,
0x0B2C2C27, 0x420D0D4F, 0xEEB7B759, 0xCC3F3FF3, 0xAEB2B21C, 0x638989EA,
0xE7939374, 0xB1CECE7F, 0x1C70706C, 0xABA6A60D, 0xCA2727ED, 0x08202028,
0xEBA3A348, 0x975656C1, 0x82020280, 0xDC7F7FA3, 0x965252C4, 0xF9EBEB12,
0x74D5D5A1, 0x8D3E3EB3, 0x3FFCFCC3, 0xA49A9A3E, 0x461D1D5B, 0x071C1C1B,
0xA59E9E3B, 0xFFF3F30C, 0xF0CFCF3F, 0x72CDCDBF, 0x175C5C4B, 0xB8EAEA52,
0x810E0E8F, 0x5865653D, 0x3CF0F0CC, 0x1964647D, 0xE59B9B7E, 0x87161691,
0x4E3D3D73, 0xAAA2A208, 0x69A1A1C8, 0x6AADADC7, 0x83060685, 0xB0CACA7A,
0x70C5C5B5, 0x659191F4, 0xD96B6BB2, 0x892E2EA7, 0xFBE3E318, 0xE8AFAF47,
0x0F3C3C33, 0x4A2D2D67, 0x71C1C1B0, 0x5759590E, 0x9F7676E9, 0x35D4D4E1,
0x1E787866, 0x249090B4, 0x0E383836, 0x5F797926, 0x628D8DEF, 0x59616138,
0xD2474795, 0xA08A8A2A, 0x259494B1, 0x228888AA, 0x7DF1F18C, 0x3BECECD7,
0x01040405, 0x218484A5, 0x79E1E198, 0x851E1E9B, 0xD7535384, 0x00000000,
0x4719195E, 0x565D5D0B, 0x9D7E7EE3, 0xD04F4F9F, 0x279C9CBB, 0x5349491A,
0x4D31317C, 0x36D8D8EE, 0x0208080A, 0xE49F9F7B, 0xA2828220, 0xC71313D4,
0xCB2323E8, 0x9C7A7AE6, 0xE9ABAB42, 0xBDFEFE43, 0x882A2AA2, 0xD14B4B9A,
0x41010140, 0xC41F1FDB, 0x38E0E0D8, 0xB7D6D661, 0xA18E8E2F, 0xF4DFDF2B,
0xF1CBCB3A, 0xCD3B3BF6, 0xFAE7E71D, 0x608585E5, 0x15545441, 0xA3868625,
0xE3838360, 0xACBABA16, 0x5C757529, 0xA6929234, 0x996E6EF7, 0x34D0D0E4,
0x1A686872, 0x54555501, 0xAFB6B619, 0x914E4EDF, 0x32C8C8FA, 0x30C0C0F0,
0xF6D7D721, 0x8E3232BC, 0xB3C6C675, 0xE08F8F6F, 0x1D747469, 0xF5DBDB2E,
0xE18B8B6A, 0x2EB8B896, 0x800A0A8A, 0x679999FE, 0xC92B2BE2, 0x618181E0,
0xC30303C0, 0x29A4A48D, 0x238C8CAF, 0xA9AEAE07, 0x0D343439, 0x524D4D1F,
0x4F393976, 0x6EBDBDD3, 0xD6575781, 0xD86F6FB7, 0x37DCDCEB, 0x44151551,
0xDD7B7BA6, 0xFEF7F709, 0x8C3A3AB6, 0x2FBCBC93, 0x030C0C0F, 0xFCFFFF03,
0x6BA9A9C2, 0x73C9C9BA, 0x6CB5B5D9, 0x6DB1B1DC, 0x5A6D6D37, 0x50454515,
0x8F3636B9, 0x1B6C6C77, 0xADBEBE13, 0x904A4ADA, 0xB9EEEE57, 0xDE7777A9,
0xBEF2F24C, 0x7EFDFD83, 0x11444455, 0xDA6767BD, 0x5D71712C, 0x40050545,
0x1F7C7C63, 0x10404050, 0x5B696932, 0xDB6363B8, 0x0A282822, 0xC20707C5,
0x31C4C4F5, 0x8A2222A8, 0xA7969631, 0xCE3737F9, 0x7AEDED97, 0xBFF6F649,
0x2DB4B499, 0x75D1D1A4, 0xD3434390, 0x1248485A, 0xBAE2E258, 0xE6979771,
0xB6D2D264, 0xB2C2C270, 0x8B2626AD, 0x68A5A5CD, 0x955E5ECB, 0x4B292962,
0x0C30303C, 0x945A5ACE, 0x76DDDDAB, 0x7FF9F986, 0x649595F1, 0xBBE6E65D,
0xF2C7C735, 0x0924242D, 0xC61717D1, 0x6FB9B9D6, 0xC51B1BDE, 0x86121294,
0x18606078, 0xF3C3C330, 0x7CF5F589, 0xEFB3B35C, 0x3AE8E8D2, 0xDF7373AC,
0x4C353579, 0x208080A0, 0x78E5E59D, 0xEDBBBB56, 0x5E7D7D23, 0x3EF8F8C6,
0xD45F5F8B, 0xC82F2FE7, 0x39E4E4DD, 0x49212168};
static ossl_inline uint32_t rotl(uint32_t a, uint8_t n)
{
return (a << n) | (a >> (32 - n));
}
static ossl_inline uint32_t load_u32_be(const uint8_t *b, uint32_t n)
{
return ((uint32_t)b[4 * n] << 24) |
((uint32_t)b[4 * n + 1] << 16) |
((uint32_t)b[4 * n + 2] << 8) |
((uint32_t)b[4 * n + 3]);
}
static ossl_inline void store_u32_be(uint32_t v, uint8_t *b)
{
b[0] = (uint8_t)(v >> 24);
b[1] = (uint8_t)(v >> 16);
b[2] = (uint8_t)(v >> 8);
b[3] = (uint8_t)(v);
}
static ossl_inline uint32_t SM4_T_non_lin_sub(uint32_t X)
{
uint32_t t = 0;
t |= ((uint32_t)SM4_S[(uint8_t)(X >> 24)]) << 24;
t |= ((uint32_t)SM4_S[(uint8_t)(X >> 16)]) << 16;
t |= ((uint32_t)SM4_S[(uint8_t)(X >> 8)]) << 8;
t |= SM4_S[(uint8_t)X];
return t;
}
static ossl_inline uint32_t SM4_T_slow(uint32_t X)
{
uint32_t t = SM4_T_non_lin_sub(X);
/*
* L linear transform
*/
return t ^ rotl(t, 2) ^ rotl(t, 10) ^ rotl(t, 18) ^ rotl(t, 24);
}
static ossl_inline uint32_t SM4_T(uint32_t X)
{
return SM4_SBOX_T0[(uint8_t)(X >> 24)] ^
SM4_SBOX_T1[(uint8_t)(X >> 16)] ^
SM4_SBOX_T2[(uint8_t)(X >> 8)] ^
SM4_SBOX_T3[(uint8_t)X];
}
static ossl_inline uint32_t SM4_key_sub(uint32_t X)
{
uint32_t t = SM4_T_non_lin_sub(X);
return t ^ rotl(t, 13) ^ rotl(t, 23);
}
int ossl_sm4_set_key(const uint8_t *key, SM4_KEY *ks)
{
/*
* Family Key
*/
static const uint32_t FK[4] =
{ 0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc };
/*
* Constant Key
*/
static const uint32_t CK[32] = {
0x00070E15, 0x1C232A31, 0x383F464D, 0x545B6269,
0x70777E85, 0x8C939AA1, 0xA8AFB6BD, 0xC4CBD2D9,
0xE0E7EEF5, 0xFC030A11, 0x181F262D, 0x343B4249,
0x50575E65, 0x6C737A81, 0x888F969D, 0xA4ABB2B9,
0xC0C7CED5, 0xDCE3EAF1, 0xF8FF060D, 0x141B2229,
0x30373E45, 0x4C535A61, 0x686F767D, 0x848B9299,
0xA0A7AEB5, 0xBCC3CAD1, 0xD8DFE6ED, 0xF4FB0209,
0x10171E25, 0x2C333A41, 0x484F565D, 0x646B7279
};
uint32_t K[4];
int i;
K[0] = load_u32_be(key, 0) ^ FK[0];
K[1] = load_u32_be(key, 1) ^ FK[1];
K[2] = load_u32_be(key, 2) ^ FK[2];
K[3] = load_u32_be(key, 3) ^ FK[3];
for (i = 0; i < SM4_KEY_SCHEDULE; i = i + 4) {
K[0] ^= SM4_key_sub(K[1] ^ K[2] ^ K[3] ^ CK[i]);
K[1] ^= SM4_key_sub(K[2] ^ K[3] ^ K[0] ^ CK[i + 1]);
K[2] ^= SM4_key_sub(K[3] ^ K[0] ^ K[1] ^ CK[i + 2]);
K[3] ^= SM4_key_sub(K[0] ^ K[1] ^ K[2] ^ CK[i + 3]);
ks->rk[i ] = K[0];
ks->rk[i + 1] = K[1];
ks->rk[i + 2] = K[2];
ks->rk[i + 3] = K[3];
}
return 1;
}
#define SM4_RNDS(k0, k1, k2, k3, F) \
do { \
B0 ^= F(B1 ^ B2 ^ B3 ^ ks->rk[k0]); \
B1 ^= F(B0 ^ B2 ^ B3 ^ ks->rk[k1]); \
B2 ^= F(B0 ^ B1 ^ B3 ^ ks->rk[k2]); \
B3 ^= F(B0 ^ B1 ^ B2 ^ ks->rk[k3]); \
} while(0)
void ossl_sm4_encrypt(const uint8_t *in, uint8_t *out, const SM4_KEY *ks)
{
uint32_t B0 = load_u32_be(in, 0);
uint32_t B1 = load_u32_be(in, 1);
uint32_t B2 = load_u32_be(in, 2);
uint32_t B3 = load_u32_be(in, 3);
/*
* Uses byte-wise sbox in the first and last rounds to provide some
* protection from cache based side channels.
*/
SM4_RNDS( 0, 1, 2, 3, SM4_T_slow);
SM4_RNDS( 4, 5, 6, 7, SM4_T);
SM4_RNDS( 8, 9, 10, 11, SM4_T);
SM4_RNDS(12, 13, 14, 15, SM4_T);
SM4_RNDS(16, 17, 18, 19, SM4_T);
SM4_RNDS(20, 21, 22, 23, SM4_T);
SM4_RNDS(24, 25, 26, 27, SM4_T);
SM4_RNDS(28, 29, 30, 31, SM4_T_slow);
store_u32_be(B3, out);
store_u32_be(B2, out + 4);
store_u32_be(B1, out + 8);
store_u32_be(B0, out + 12);
}
void ossl_sm4_decrypt(const uint8_t *in, uint8_t *out, const SM4_KEY *ks)
{
uint32_t B0 = load_u32_be(in, 0);
uint32_t B1 = load_u32_be(in, 1);
uint32_t B2 = load_u32_be(in, 2);
uint32_t B3 = load_u32_be(in, 3);
SM4_RNDS(31, 30, 29, 28, SM4_T_slow);
SM4_RNDS(27, 26, 25, 24, SM4_T);
SM4_RNDS(23, 22, 21, 20, SM4_T);
SM4_RNDS(19, 18, 17, 16, SM4_T);
SM4_RNDS(15, 14, 13, 12, SM4_T);
SM4_RNDS(11, 10, 9, 8, SM4_T);
SM4_RNDS( 7, 6, 5, 4, SM4_T);
SM4_RNDS( 3, 2, 1, 0, SM4_T_slow);
store_u32_be(B3, out);
store_u32_be(B2, out + 4);
store_u32_be(B1, out + 8);
store_u32_be(B0, out + 12);
}
|
./openssl/crypto/async/async_err.c | /*
* Generated by util/mkerr.pl DO NOT EDIT
* 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 <openssl/err.h>
#include <openssl/asyncerr.h>
#include "crypto/asyncerr.h"
#ifndef OPENSSL_NO_ERR
static const ERR_STRING_DATA ASYNC_str_reasons[] = {
{ERR_PACK(ERR_LIB_ASYNC, 0, ASYNC_R_FAILED_TO_SET_POOL),
"failed to set pool"},
{ERR_PACK(ERR_LIB_ASYNC, 0, ASYNC_R_FAILED_TO_SWAP_CONTEXT),
"failed to swap context"},
{ERR_PACK(ERR_LIB_ASYNC, 0, ASYNC_R_INIT_FAILED), "init failed"},
{ERR_PACK(ERR_LIB_ASYNC, 0, ASYNC_R_INVALID_POOL_SIZE),
"invalid pool size"},
{0, NULL}
};
#endif
int ossl_err_load_ASYNC_strings(void)
{
#ifndef OPENSSL_NO_ERR
if (ERR_reason_error_string(ASYNC_str_reasons[0].error) == NULL)
ERR_load_strings_const(ASYNC_str_reasons);
#endif
return 1;
}
|
./openssl/crypto/async/async.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
*/
/*
* Without this we start getting longjmp crashes because it thinks we're jumping
* up the stack when in fact we are jumping to an entirely different stack. The
* cost of this is not having certain buffer overrun/underrun checks etc for
* this source file :-(
*/
#undef _FORTIFY_SOURCE
/* This must be the first #include file */
#include "async_local.h"
#include <openssl/err.h>
#include "crypto/cryptlib.h"
#include <string.h>
#define ASYNC_JOB_RUNNING 0
#define ASYNC_JOB_PAUSING 1
#define ASYNC_JOB_PAUSED 2
#define ASYNC_JOB_STOPPING 3
static CRYPTO_THREAD_LOCAL ctxkey;
static CRYPTO_THREAD_LOCAL poolkey;
static void async_delete_thread_state(void *arg);
static async_ctx *async_ctx_new(void)
{
async_ctx *nctx;
if (!ossl_init_thread_start(NULL, NULL, async_delete_thread_state))
return NULL;
nctx = OPENSSL_malloc(sizeof(*nctx));
if (nctx == NULL)
goto err;
async_fibre_init_dispatcher(&nctx->dispatcher);
nctx->currjob = NULL;
nctx->blocked = 0;
if (!CRYPTO_THREAD_set_local(&ctxkey, nctx))
goto err;
return nctx;
err:
OPENSSL_free(nctx);
return NULL;
}
async_ctx *async_get_ctx(void)
{
return (async_ctx *)CRYPTO_THREAD_get_local(&ctxkey);
}
static int async_ctx_free(void)
{
async_ctx *ctx;
ctx = async_get_ctx();
if (!CRYPTO_THREAD_set_local(&ctxkey, NULL))
return 0;
OPENSSL_free(ctx);
return 1;
}
static ASYNC_JOB *async_job_new(void)
{
ASYNC_JOB *job = NULL;
job = OPENSSL_zalloc(sizeof(*job));
if (job == NULL)
return NULL;
job->status = ASYNC_JOB_RUNNING;
return job;
}
static void async_job_free(ASYNC_JOB *job)
{
if (job != NULL) {
OPENSSL_free(job->funcargs);
async_fibre_free(&job->fibrectx);
OPENSSL_free(job);
}
}
static ASYNC_JOB *async_get_pool_job(void) {
ASYNC_JOB *job;
async_pool *pool;
pool = (async_pool *)CRYPTO_THREAD_get_local(&poolkey);
if (pool == NULL) {
/*
* Pool has not been initialised, so init with the defaults, i.e.
* no max size and no pre-created jobs
*/
if (ASYNC_init_thread(0, 0) == 0)
return NULL;
pool = (async_pool *)CRYPTO_THREAD_get_local(&poolkey);
}
job = sk_ASYNC_JOB_pop(pool->jobs);
if (job == NULL) {
/* Pool is empty */
if ((pool->max_size != 0) && (pool->curr_size >= pool->max_size))
return NULL;
job = async_job_new();
if (job != NULL) {
if (! async_fibre_makecontext(&job->fibrectx)) {
async_job_free(job);
return NULL;
}
pool->curr_size++;
}
}
return job;
}
static void async_release_job(ASYNC_JOB *job) {
async_pool *pool;
pool = (async_pool *)CRYPTO_THREAD_get_local(&poolkey);
if (pool == NULL) {
ERR_raise(ERR_LIB_ASYNC, ERR_R_INTERNAL_ERROR);
return;
}
OPENSSL_free(job->funcargs);
job->funcargs = NULL;
sk_ASYNC_JOB_push(pool->jobs, job);
}
void async_start_func(void)
{
ASYNC_JOB *job;
async_ctx *ctx = async_get_ctx();
if (ctx == NULL) {
ERR_raise(ERR_LIB_ASYNC, ERR_R_INTERNAL_ERROR);
return;
}
while (1) {
/* Run the job */
job = ctx->currjob;
job->ret = job->func(job->funcargs);
/* Stop the job */
job->status = ASYNC_JOB_STOPPING;
if (!async_fibre_swapcontext(&job->fibrectx,
&ctx->dispatcher, 1)) {
/*
* Should not happen. Getting here will close the thread...can't do
* much about it
*/
ERR_raise(ERR_LIB_ASYNC, ASYNC_R_FAILED_TO_SWAP_CONTEXT);
}
}
}
int ASYNC_start_job(ASYNC_JOB **job, ASYNC_WAIT_CTX *wctx, int *ret,
int (*func)(void *), void *args, size_t size)
{
async_ctx *ctx;
OSSL_LIB_CTX *libctx;
if (!OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL))
return ASYNC_ERR;
ctx = async_get_ctx();
if (ctx == NULL)
ctx = async_ctx_new();
if (ctx == NULL)
return ASYNC_ERR;
if (*job != NULL)
ctx->currjob = *job;
for (;;) {
if (ctx->currjob != NULL) {
if (ctx->currjob->status == ASYNC_JOB_STOPPING) {
*ret = ctx->currjob->ret;
ctx->currjob->waitctx = NULL;
async_release_job(ctx->currjob);
ctx->currjob = NULL;
*job = NULL;
return ASYNC_FINISH;
}
if (ctx->currjob->status == ASYNC_JOB_PAUSING) {
*job = ctx->currjob;
ctx->currjob->status = ASYNC_JOB_PAUSED;
ctx->currjob = NULL;
return ASYNC_PAUSE;
}
if (ctx->currjob->status == ASYNC_JOB_PAUSED) {
if (*job == NULL)
return ASYNC_ERR;
ctx->currjob = *job;
/*
* Restore the default libctx to what it was the last time the
* fibre ran
*/
libctx = OSSL_LIB_CTX_set0_default(ctx->currjob->libctx);
if (libctx == NULL) {
/* Failed to set the default context */
ERR_raise(ERR_LIB_ASYNC, ERR_R_INTERNAL_ERROR);
goto err;
}
/* Resume previous job */
if (!async_fibre_swapcontext(&ctx->dispatcher,
&ctx->currjob->fibrectx, 1)) {
ctx->currjob->libctx = OSSL_LIB_CTX_set0_default(libctx);
ERR_raise(ERR_LIB_ASYNC, ASYNC_R_FAILED_TO_SWAP_CONTEXT);
goto err;
}
/*
* In case the fibre changed the default libctx we set it back
* again to what it was originally, and remember what it had
* been changed to.
*/
ctx->currjob->libctx = OSSL_LIB_CTX_set0_default(libctx);
continue;
}
/* Should not happen */
ERR_raise(ERR_LIB_ASYNC, ERR_R_INTERNAL_ERROR);
async_release_job(ctx->currjob);
ctx->currjob = NULL;
*job = NULL;
return ASYNC_ERR;
}
/* Start a new job */
if ((ctx->currjob = async_get_pool_job()) == NULL)
return ASYNC_NO_JOBS;
if (args != NULL) {
ctx->currjob->funcargs = OPENSSL_malloc(size);
if (ctx->currjob->funcargs == NULL) {
async_release_job(ctx->currjob);
ctx->currjob = NULL;
return ASYNC_ERR;
}
memcpy(ctx->currjob->funcargs, args, size);
} else {
ctx->currjob->funcargs = NULL;
}
ctx->currjob->func = func;
ctx->currjob->waitctx = wctx;
libctx = ossl_lib_ctx_get_concrete(NULL);
if (!async_fibre_swapcontext(&ctx->dispatcher,
&ctx->currjob->fibrectx, 1)) {
ERR_raise(ERR_LIB_ASYNC, ASYNC_R_FAILED_TO_SWAP_CONTEXT);
goto err;
}
/*
* In case the fibre changed the default libctx we set it back again
* to what it was, and remember what it had been changed to.
*/
ctx->currjob->libctx = OSSL_LIB_CTX_set0_default(libctx);
}
err:
async_release_job(ctx->currjob);
ctx->currjob = NULL;
*job = NULL;
return ASYNC_ERR;
}
int ASYNC_pause_job(void)
{
ASYNC_JOB *job;
async_ctx *ctx = async_get_ctx();
if (ctx == NULL
|| ctx->currjob == NULL
|| ctx->blocked) {
/*
* Could be we've deliberately not been started within a job so this is
* counted as success.
*/
return 1;
}
job = ctx->currjob;
job->status = ASYNC_JOB_PAUSING;
if (!async_fibre_swapcontext(&job->fibrectx,
&ctx->dispatcher, 1)) {
ERR_raise(ERR_LIB_ASYNC, ASYNC_R_FAILED_TO_SWAP_CONTEXT);
return 0;
}
/* Reset counts of added and deleted fds */
async_wait_ctx_reset_counts(job->waitctx);
return 1;
}
static void async_empty_pool(async_pool *pool)
{
ASYNC_JOB *job;
if (pool == NULL || pool->jobs == NULL)
return;
do {
job = sk_ASYNC_JOB_pop(pool->jobs);
async_job_free(job);
} while (job);
}
int async_init(void)
{
if (!CRYPTO_THREAD_init_local(&ctxkey, NULL))
return 0;
if (!CRYPTO_THREAD_init_local(&poolkey, NULL)) {
CRYPTO_THREAD_cleanup_local(&ctxkey);
return 0;
}
return async_local_init();
}
void async_deinit(void)
{
CRYPTO_THREAD_cleanup_local(&ctxkey);
CRYPTO_THREAD_cleanup_local(&poolkey);
async_local_deinit();
}
int ASYNC_init_thread(size_t max_size, size_t init_size)
{
async_pool *pool;
size_t curr_size = 0;
if (init_size > max_size) {
ERR_raise(ERR_LIB_ASYNC, ASYNC_R_INVALID_POOL_SIZE);
return 0;
}
if (!OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL))
return 0;
if (!ossl_init_thread_start(NULL, NULL, async_delete_thread_state))
return 0;
pool = OPENSSL_zalloc(sizeof(*pool));
if (pool == NULL)
return 0;
pool->jobs = sk_ASYNC_JOB_new_reserve(NULL, init_size);
if (pool->jobs == NULL) {
ERR_raise(ERR_LIB_ASYNC, ERR_R_CRYPTO_LIB);
OPENSSL_free(pool);
return 0;
}
pool->max_size = max_size;
/* Pre-create jobs as required */
while (init_size--) {
ASYNC_JOB *job;
job = async_job_new();
if (job == NULL || !async_fibre_makecontext(&job->fibrectx)) {
/*
* Not actually fatal because we already created the pool, just
* skip creation of any more jobs
*/
async_job_free(job);
break;
}
job->funcargs = NULL;
sk_ASYNC_JOB_push(pool->jobs, job); /* Cannot fail due to reserve */
curr_size++;
}
pool->curr_size = curr_size;
if (!CRYPTO_THREAD_set_local(&poolkey, pool)) {
ERR_raise(ERR_LIB_ASYNC, ASYNC_R_FAILED_TO_SET_POOL);
goto err;
}
return 1;
err:
async_empty_pool(pool);
sk_ASYNC_JOB_free(pool->jobs);
OPENSSL_free(pool);
return 0;
}
static void async_delete_thread_state(void *arg)
{
async_pool *pool = (async_pool *)CRYPTO_THREAD_get_local(&poolkey);
if (pool != NULL) {
async_empty_pool(pool);
sk_ASYNC_JOB_free(pool->jobs);
OPENSSL_free(pool);
CRYPTO_THREAD_set_local(&poolkey, NULL);
}
async_local_cleanup();
async_ctx_free();
}
void ASYNC_cleanup_thread(void)
{
if (!OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL))
return;
async_delete_thread_state(NULL);
}
ASYNC_JOB *ASYNC_get_current_job(void)
{
async_ctx *ctx;
if (!OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL))
return NULL;
ctx = async_get_ctx();
if (ctx == NULL)
return NULL;
return ctx->currjob;
}
ASYNC_WAIT_CTX *ASYNC_get_wait_ctx(ASYNC_JOB *job)
{
return job->waitctx;
}
void ASYNC_block_pause(void)
{
async_ctx *ctx;
if (!OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL))
return;
ctx = async_get_ctx();
if (ctx == NULL || ctx->currjob == NULL) {
/*
* We're not in a job anyway so ignore this
*/
return;
}
ctx->blocked++;
}
void ASYNC_unblock_pause(void)
{
async_ctx *ctx;
if (!OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL))
return;
ctx = async_get_ctx();
if (ctx == NULL || ctx->currjob == NULL) {
/*
* We're not in a job anyway so ignore this
*/
return;
}
if (ctx->blocked > 0)
ctx->blocked--;
}
|
./openssl/crypto/async/async_local.h | /*
* Copyright 2015-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
*/
/*
* Must do this before including any header files, because on MacOS/X <stlib.h>
* includes <signal.h> which includes <ucontext.h>
*/
#if defined(__APPLE__) && defined(__MACH__) && !defined(_XOPEN_SOURCE)
# define _XOPEN_SOURCE /* Otherwise incomplete ucontext_t structure */
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
#if defined(_WIN32)
# include <windows.h>
#endif
#include "crypto/async.h"
#include <openssl/crypto.h>
typedef struct async_ctx_st async_ctx;
typedef struct async_pool_st async_pool;
#include "arch/async_win.h"
#include "arch/async_posix.h"
#include "arch/async_null.h"
struct async_ctx_st {
async_fibre dispatcher;
ASYNC_JOB *currjob;
unsigned int blocked;
};
struct async_job_st {
async_fibre fibrectx;
int (*func) (void *);
void *funcargs;
int ret;
int status;
ASYNC_WAIT_CTX *waitctx;
OSSL_LIB_CTX *libctx;
};
struct fd_lookup_st {
const void *key;
OSSL_ASYNC_FD fd;
void *custom_data;
void (*cleanup)(ASYNC_WAIT_CTX *, const void *, OSSL_ASYNC_FD, void *);
int add;
int del;
struct fd_lookup_st *next;
};
struct async_wait_ctx_st {
struct fd_lookup_st *fds;
size_t numadd;
size_t numdel;
ASYNC_callback_fn callback;
void *callback_arg;
int status;
};
DEFINE_STACK_OF(ASYNC_JOB)
struct async_pool_st {
STACK_OF(ASYNC_JOB) *jobs;
size_t curr_size;
size_t max_size;
};
void async_local_cleanup(void);
void async_start_func(void);
async_ctx *async_get_ctx(void);
void async_wait_ctx_reset_counts(ASYNC_WAIT_CTX *ctx);
|
./openssl/crypto/async/async_wait.c | /*
* Copyright 2016-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
*/
/* This must be the first #include file */
#include "async_local.h"
#include <openssl/err.h>
ASYNC_WAIT_CTX *ASYNC_WAIT_CTX_new(void)
{
return OPENSSL_zalloc(sizeof(ASYNC_WAIT_CTX));
}
void ASYNC_WAIT_CTX_free(ASYNC_WAIT_CTX *ctx)
{
struct fd_lookup_st *curr;
struct fd_lookup_st *next;
if (ctx == NULL)
return;
curr = ctx->fds;
while (curr != NULL) {
if (!curr->del) {
/* Only try and cleanup if it hasn't been marked deleted */
if (curr->cleanup != NULL)
curr->cleanup(ctx, curr->key, curr->fd, curr->custom_data);
}
/* Always free the fd_lookup_st */
next = curr->next;
OPENSSL_free(curr);
curr = next;
}
OPENSSL_free(ctx);
}
int ASYNC_WAIT_CTX_set_wait_fd(ASYNC_WAIT_CTX *ctx, const void *key,
OSSL_ASYNC_FD fd, void *custom_data,
void (*cleanup)(ASYNC_WAIT_CTX *, const void *,
OSSL_ASYNC_FD, void *))
{
struct fd_lookup_st *fdlookup;
if ((fdlookup = OPENSSL_zalloc(sizeof(*fdlookup))) == NULL)
return 0;
fdlookup->key = key;
fdlookup->fd = fd;
fdlookup->custom_data = custom_data;
fdlookup->cleanup = cleanup;
fdlookup->add = 1;
fdlookup->next = ctx->fds;
ctx->fds = fdlookup;
ctx->numadd++;
return 1;
}
int ASYNC_WAIT_CTX_get_fd(ASYNC_WAIT_CTX *ctx, const void *key,
OSSL_ASYNC_FD *fd, void **custom_data)
{
struct fd_lookup_st *curr;
curr = ctx->fds;
while (curr != NULL) {
if (curr->del) {
/* This one has been marked deleted so do nothing */
curr = curr->next;
continue;
}
if (curr->key == key) {
*fd = curr->fd;
*custom_data = curr->custom_data;
return 1;
}
curr = curr->next;
}
return 0;
}
int ASYNC_WAIT_CTX_get_all_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *fd,
size_t *numfds)
{
struct fd_lookup_st *curr;
curr = ctx->fds;
*numfds = 0;
while (curr != NULL) {
if (curr->del) {
/* This one has been marked deleted so do nothing */
curr = curr->next;
continue;
}
if (fd != NULL) {
*fd = curr->fd;
fd++;
}
(*numfds)++;
curr = curr->next;
}
return 1;
}
int ASYNC_WAIT_CTX_get_changed_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *addfd,
size_t *numaddfds, OSSL_ASYNC_FD *delfd,
size_t *numdelfds)
{
struct fd_lookup_st *curr;
*numaddfds = ctx->numadd;
*numdelfds = ctx->numdel;
if (addfd == NULL && delfd == NULL)
return 1;
curr = ctx->fds;
while (curr != NULL) {
/* We ignore fds that have been marked as both added and deleted */
if (curr->del && !curr->add && (delfd != NULL)) {
*delfd = curr->fd;
delfd++;
}
if (curr->add && !curr->del && (addfd != NULL)) {
*addfd = curr->fd;
addfd++;
}
curr = curr->next;
}
return 1;
}
int ASYNC_WAIT_CTX_clear_fd(ASYNC_WAIT_CTX *ctx, const void *key)
{
struct fd_lookup_st *curr, *prev;
curr = ctx->fds;
prev = NULL;
while (curr != NULL) {
if (curr->del == 1) {
/* This one has been marked deleted already so do nothing */
prev = curr;
curr = curr->next;
continue;
}
if (curr->key == key) {
/* If fd has just been added, remove it from the list */
if (curr->add == 1) {
if (ctx->fds == curr) {
ctx->fds = curr->next;
} else {
prev->next = curr->next;
}
/* It is responsibility of the caller to cleanup before calling
* ASYNC_WAIT_CTX_clear_fd
*/
OPENSSL_free(curr);
ctx->numadd--;
return 1;
}
/*
* Mark it as deleted. We don't call cleanup if explicitly asked
* to clear an fd. We assume the caller is going to do that (if
* appropriate).
*/
curr->del = 1;
ctx->numdel++;
return 1;
}
prev = curr;
curr = curr->next;
}
return 0;
}
int ASYNC_WAIT_CTX_set_callback(ASYNC_WAIT_CTX *ctx,
ASYNC_callback_fn callback,
void *callback_arg)
{
if (ctx == NULL)
return 0;
ctx->callback = callback;
ctx->callback_arg = callback_arg;
return 1;
}
int ASYNC_WAIT_CTX_get_callback(ASYNC_WAIT_CTX *ctx,
ASYNC_callback_fn *callback,
void **callback_arg)
{
if (ctx->callback == NULL)
return 0;
*callback = ctx->callback;
*callback_arg = ctx->callback_arg;
return 1;
}
int ASYNC_WAIT_CTX_set_status(ASYNC_WAIT_CTX *ctx, int status)
{
ctx->status = status;
return 1;
}
int ASYNC_WAIT_CTX_get_status(ASYNC_WAIT_CTX *ctx)
{
return ctx->status;
}
void async_wait_ctx_reset_counts(ASYNC_WAIT_CTX *ctx)
{
struct fd_lookup_st *curr, *prev = NULL;
ctx->numadd = 0;
ctx->numdel = 0;
curr = ctx->fds;
while (curr != NULL) {
if (curr->del) {
if (prev == NULL)
ctx->fds = curr->next;
else
prev->next = curr->next;
OPENSSL_free(curr);
if (prev == NULL)
curr = ctx->fds;
else
curr = prev->next;
continue;
}
if (curr->add) {
curr->add = 0;
}
prev = curr;
curr = curr->next;
}
}
|
./openssl/crypto/async/arch/async_win.h | /*
* 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
*/
/*
* This is the same detection used in cryptlib to set up the thread local
* storage that we depend on, so just copy that
*/
#if defined(_WIN32) && !defined(OPENSSL_NO_ASYNC)
#include <openssl/async.h>
# define ASYNC_WIN
# define ASYNC_ARCH
# include <windows.h>
# include "internal/cryptlib.h"
typedef struct async_fibre_st {
LPVOID fibre;
int converted;
} async_fibre;
# define async_fibre_swapcontext(o,n,r) \
(SwitchToFiber((n)->fibre), 1)
# if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600
# define async_fibre_makecontext(c) \
((c)->fibre = CreateFiberEx(0, 0, FIBER_FLAG_FLOAT_SWITCH, \
async_start_func_win, 0))
# else
# define async_fibre_makecontext(c) \
((c)->fibre = CreateFiber(0, async_start_func_win, 0))
# endif
# define async_fibre_free(f) (DeleteFiber((f)->fibre))
# define async_local_init() 1
# define async_local_deinit()
int async_fibre_init_dispatcher(async_fibre *fibre);
VOID CALLBACK async_start_func_win(PVOID unused);
#endif
|
./openssl/crypto/async/arch/async_win.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
*/
/* This must be the first #include file */
#include "../async_local.h"
#ifdef ASYNC_WIN
# include <windows.h>
# include "internal/cryptlib.h"
int ASYNC_is_capable(void)
{
return 1;
}
int ASYNC_set_mem_functions(ASYNC_stack_alloc_fn alloc_fn,
ASYNC_stack_free_fn free_fn)
{
return 0;
}
void ASYNC_get_mem_functions(ASYNC_stack_alloc_fn *alloc_fn,
ASYNC_stack_free_fn *free_fn)
{
if (alloc_fn != NULL)
*alloc_fn = NULL;
if (free_fn != NULL)
*free_fn = NULL;
}
void async_local_cleanup(void)
{
async_ctx *ctx = async_get_ctx();
if (ctx != NULL) {
async_fibre *fibre = &ctx->dispatcher;
if (fibre != NULL && fibre->fibre != NULL && fibre->converted) {
ConvertFiberToThread();
fibre->fibre = NULL;
}
}
}
int async_fibre_init_dispatcher(async_fibre *fibre)
{
# if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x600
fibre->fibre = ConvertThreadToFiberEx(NULL, FIBER_FLAG_FLOAT_SWITCH);
# else
fibre->fibre = ConvertThreadToFiber(NULL);
# endif
if (fibre->fibre == NULL) {
fibre->converted = 0;
fibre->fibre = GetCurrentFiber();
if (fibre->fibre == NULL)
return 0;
} else {
fibre->converted = 1;
}
return 1;
}
VOID CALLBACK async_start_func_win(PVOID unused)
{
async_start_func();
}
#endif
|
./openssl/crypto/async/arch/async_posix.h | /*
* 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
*/
#ifndef OSSL_CRYPTO_ASYNC_POSIX_H
#define OSSL_CRYPTO_ASYNC_POSIX_H
#include <openssl/e_os2.h>
#if defined(OPENSSL_SYS_UNIX) \
&& defined(OPENSSL_THREADS) && !defined(OPENSSL_NO_ASYNC) \
&& !defined(__ANDROID__) && !defined(__OpenBSD__)
# include <unistd.h>
# if _POSIX_VERSION >= 200112L \
&& (_POSIX_VERSION < 200809L || defined(__GLIBC__))
# include <pthread.h>
# define ASYNC_POSIX
# define ASYNC_ARCH
# if defined(__CET__) || defined(__ia64__)
/*
* When Intel CET is enabled, makecontext will create a different
* shadow stack for each context. async_fibre_swapcontext cannot
* use _longjmp. It must call swapcontext to swap shadow stack as
* well as normal stack.
* On IA64 the register stack engine is not saved across setjmp/longjmp. Here
* swapcontext() performs correctly.
*/
# define USE_SWAPCONTEXT
# endif
# if defined(__aarch64__) && defined(__clang__) \
&& defined(__ARM_FEATURE_BTI_DEFAULT) && __ARM_FEATURE_BTI_DEFAULT == 1
/*
* setjmp/longjmp don't currently work with BTI on all libc implementations
* when compiled by clang. This is because clang doesn't put a BTI after the
* call to setjmp where it returns the second time. This then fails on libc
* implementations - notably glibc - which use an indirect jump to there.
* So use the swapcontext implementation, which does work.
* See https://github.com/llvm/llvm-project/issues/48888.
*/
# define USE_SWAPCONTEXT
# endif
# include <ucontext.h>
# ifndef USE_SWAPCONTEXT
# include <setjmp.h>
# endif
typedef struct async_fibre_st {
ucontext_t fibre;
# ifndef USE_SWAPCONTEXT
jmp_buf env;
int env_init;
# endif
} async_fibre;
int async_local_init(void);
void async_local_deinit(void);
static ossl_inline int async_fibre_swapcontext(async_fibre *o, async_fibre *n, int r)
{
# ifdef USE_SWAPCONTEXT
swapcontext(&o->fibre, &n->fibre);
# else
o->env_init = 1;
if (!r || !_setjmp(o->env)) {
if (n->env_init)
_longjmp(n->env, 1);
else
setcontext(&n->fibre);
}
# endif
return 1;
}
# define async_fibre_init_dispatcher(d)
int async_fibre_makecontext(async_fibre *fibre);
void async_fibre_free(async_fibre *fibre);
# endif
#endif
#endif /* OSSL_CRYPTO_ASYNC_POSIX_H */
|
./openssl/crypto/async/arch/async_posix.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
*/
/* This must be the first #include file */
#include "../async_local.h"
#ifdef ASYNC_POSIX
# include <stddef.h>
# include <unistd.h>
# include <openssl/err.h>
# include <openssl/crypto.h>
#define STACKSIZE 32768
static CRYPTO_RWLOCK *async_mem_lock;
static void *async_stack_alloc(size_t *num);
static void async_stack_free(void *addr);
int async_local_init(void)
{
async_mem_lock = CRYPTO_THREAD_lock_new();
return async_mem_lock != NULL;
}
void async_local_deinit(void)
{
CRYPTO_THREAD_lock_free(async_mem_lock);
}
static int allow_customize = 1;
static ASYNC_stack_alloc_fn stack_alloc_impl = async_stack_alloc;
static ASYNC_stack_free_fn stack_free_impl = async_stack_free;
int ASYNC_is_capable(void)
{
ucontext_t ctx;
/*
* Some platforms provide getcontext() but it does not work (notably
* MacOSX PPC64). Check for a working getcontext();
*/
return getcontext(&ctx) == 0;
}
int ASYNC_set_mem_functions(ASYNC_stack_alloc_fn alloc_fn,
ASYNC_stack_free_fn free_fn)
{
OPENSSL_init_crypto(OPENSSL_INIT_ASYNC, NULL);
if (!CRYPTO_THREAD_write_lock(async_mem_lock))
return 0;
if (!allow_customize) {
CRYPTO_THREAD_unlock(async_mem_lock);
return 0;
}
CRYPTO_THREAD_unlock(async_mem_lock);
if (alloc_fn != NULL)
stack_alloc_impl = alloc_fn;
if (free_fn != NULL)
stack_free_impl = free_fn;
return 1;
}
void ASYNC_get_mem_functions(ASYNC_stack_alloc_fn *alloc_fn,
ASYNC_stack_free_fn *free_fn)
{
if (alloc_fn != NULL)
*alloc_fn = stack_alloc_impl;
if (free_fn != NULL)
*free_fn = stack_free_impl;
}
static void *async_stack_alloc(size_t *num)
{
return OPENSSL_malloc(*num);
}
static void async_stack_free(void *addr)
{
OPENSSL_free(addr);
}
void async_local_cleanup(void)
{
}
int async_fibre_makecontext(async_fibre *fibre)
{
#ifndef USE_SWAPCONTEXT
fibre->env_init = 0;
#endif
if (getcontext(&fibre->fibre) == 0) {
size_t num = STACKSIZE;
/*
* Disallow customisation after the first
* stack is allocated.
*/
if (allow_customize) {
if (!CRYPTO_THREAD_write_lock(async_mem_lock))
return 0;
allow_customize = 0;
CRYPTO_THREAD_unlock(async_mem_lock);
}
fibre->fibre.uc_stack.ss_sp = stack_alloc_impl(&num);
if (fibre->fibre.uc_stack.ss_sp != NULL) {
fibre->fibre.uc_stack.ss_size = num;
fibre->fibre.uc_link = NULL;
makecontext(&fibre->fibre, async_start_func, 0);
return 1;
}
} else {
fibre->fibre.uc_stack.ss_sp = NULL;
}
return 0;
}
void async_fibre_free(async_fibre *fibre)
{
stack_free_impl(fibre->fibre.uc_stack.ss_sp);
fibre->fibre.uc_stack.ss_sp = NULL;
}
#endif
|
./openssl/crypto/async/arch/async_null.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
*/
/* This must be the first #include file */
#include "../async_local.h"
#ifdef ASYNC_NULL
int ASYNC_is_capable(void)
{
return 0;
}
int ASYNC_set_mem_functions(ASYNC_stack_alloc_fn alloc_fn,
ASYNC_stack_free_fn free_fn)
{
return 0;
}
void ASYNC_get_mem_functions(ASYNC_stack_alloc_fn *alloc_fn,
ASYNC_stack_free_fn *free_fn)
{
if (alloc_fn != NULL)
*alloc_fn = NULL;
if (free_fn != NULL)
*free_fn = NULL;
}
void async_local_cleanup(void)
{
}
#endif
|
./openssl/crypto/async/arch/async_null.h | /*
* 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 <openssl/async.h>
/*
* If we haven't managed to detect any other async architecture then we default
* to NULL.
*/
#ifndef ASYNC_ARCH
# define ASYNC_NULL
# define ASYNC_ARCH
typedef struct async_fibre_st {
int dummy;
} async_fibre;
# define async_fibre_swapcontext(o,n,r) 0
# define async_fibre_makecontext(c) 0
# define async_fibre_free(f)
# define async_fibre_init_dispatcher(f)
# define async_local_init() 1
# define async_local_deinit()
#endif
|
./openssl/crypto/err/err_blocks.c | /*
* Copyright 2019-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
*/
#define OSSL_FORCE_ERR_STATE
#include <string.h>
#include <openssl/err.h>
#include "err_local.h"
void ERR_new(void)
{
ERR_STATE *es;
es = ossl_err_get_state_int();
if (es == NULL)
return;
/* Allocate a slot */
err_get_slot(es);
err_clear(es, es->top, 0);
}
void ERR_set_debug(const char *file, int line, const char *func)
{
ERR_STATE *es;
es = ossl_err_get_state_int();
if (es == NULL)
return;
err_set_debug(es, es->top, file, line, func);
}
void ERR_set_error(int lib, int reason, const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
ERR_vset_error(lib, reason, fmt, args);
va_end(args);
}
void ERR_vset_error(int lib, int reason, const char *fmt, va_list args)
{
ERR_STATE *es;
char *buf = NULL;
size_t buf_size = 0;
unsigned long flags = 0;
size_t i;
es = ossl_err_get_state_int();
if (es == NULL)
return;
i = es->top;
if (fmt != NULL) {
int printed_len = 0;
char *rbuf = NULL;
buf = es->err_data[i];
buf_size = es->err_data_size[i];
/*
* To protect the string we just grabbed from tampering by other
* functions we may call, or to protect them from freeing a pointer
* that may no longer be valid at that point, we clear away the
* data pointer and the flags. We will set them again at the end
* of this function.
*/
es->err_data[i] = NULL;
es->err_data_flags[i] = 0;
/*
* Try to maximize the space available. If that fails, we use what
* we have.
*/
if (buf_size < ERR_MAX_DATA_SIZE
&& (rbuf = OPENSSL_realloc(buf, ERR_MAX_DATA_SIZE)) != NULL) {
buf = rbuf;
buf_size = ERR_MAX_DATA_SIZE;
}
if (buf != NULL) {
printed_len = BIO_vsnprintf(buf, buf_size, fmt, args);
}
if (printed_len < 0)
printed_len = 0;
if (buf != NULL)
buf[printed_len] = '\0';
/*
* Try to reduce the size, but only if we maximized above. If that
* fails, we keep what we have.
* (According to documentation, realloc leaves the old buffer untouched
* if it fails)
*/
if ((rbuf = OPENSSL_realloc(buf, printed_len + 1)) != NULL) {
buf = rbuf;
buf_size = printed_len + 1;
buf[printed_len] = '\0';
}
if (buf != NULL)
flags = ERR_TXT_MALLOCED | ERR_TXT_STRING;
}
err_clear_data(es, es->top, 0);
err_set_error(es, es->top, lib, reason);
if (fmt != NULL)
err_set_data(es, es->top, buf, buf_size, flags);
}
|
./openssl/crypto/err/err_all.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 <openssl/err.h>
#include "crypto/err.h"
#include "crypto/cryptoerr.h"
#include "crypto/asn1err.h"
#include "crypto/bnerr.h"
#include "crypto/ecerr.h"
#include "crypto/buffererr.h"
#include "crypto/bioerr.h"
#include "crypto/comperr.h"
#include "crypto/rsaerr.h"
#include "crypto/dherr.h"
#include "crypto/dsaerr.h"
#include "crypto/evperr.h"
#include "crypto/objectserr.h"
#include "crypto/pemerr.h"
#include "crypto/pkcs7err.h"
#include "crypto/x509err.h"
#include "crypto/x509v3err.h"
#include "crypto/conferr.h"
#include "crypto/pkcs12err.h"
#include "crypto/randerr.h"
#include "internal/dsoerr.h"
#include "crypto/engineerr.h"
#include "crypto/uierr.h"
#include "crypto/httperr.h"
#include "crypto/ocsperr.h"
#include "crypto/tserr.h"
#include "crypto/cmserr.h"
#include "crypto/crmferr.h"
#include "crypto/cmperr.h"
#include "crypto/cterr.h"
#include "crypto/asyncerr.h"
#include "crypto/storeerr.h"
#include "crypto/esserr.h"
#include "internal/propertyerr.h"
#include "prov/proverr.h"
int ossl_err_load_crypto_strings(void)
{
if (0
#ifndef OPENSSL_NO_ERR
|| ossl_err_load_ERR_strings() == 0 /* include error strings for SYSerr */
|| ossl_err_load_BN_strings() == 0
|| ossl_err_load_RSA_strings() == 0
# ifndef OPENSSL_NO_DH
|| ossl_err_load_DH_strings() == 0
# endif
|| ossl_err_load_EVP_strings() == 0
|| ossl_err_load_BUF_strings() == 0
|| ossl_err_load_OBJ_strings() == 0
|| ossl_err_load_PEM_strings() == 0
# ifndef OPENSSL_NO_DSA
|| ossl_err_load_DSA_strings() == 0
# endif
|| ossl_err_load_X509_strings() == 0
|| ossl_err_load_ASN1_strings() == 0
|| ossl_err_load_CONF_strings() == 0
|| ossl_err_load_CRYPTO_strings() == 0
# ifndef OPENSSL_NO_COMP
|| ossl_err_load_COMP_strings() == 0
# endif
# ifndef OPENSSL_NO_EC
|| ossl_err_load_EC_strings() == 0
# endif
/* skip ossl_err_load_SSL_strings() because it is not in this library */
|| ossl_err_load_BIO_strings() == 0
|| ossl_err_load_PKCS7_strings() == 0
|| ossl_err_load_X509V3_strings() == 0
|| ossl_err_load_PKCS12_strings() == 0
|| ossl_err_load_RAND_strings() == 0
|| ossl_err_load_DSO_strings() == 0
# ifndef OPENSSL_NO_TS
|| ossl_err_load_TS_strings() == 0
# endif
# ifndef OPENSSL_NO_ENGINE
|| ossl_err_load_ENGINE_strings() == 0
# endif
# ifndef OPENSSL_NO_HTTP
|| ossl_err_load_HTTP_strings() == 0
# endif
# ifndef OPENSSL_NO_OCSP
|| ossl_err_load_OCSP_strings() == 0
# endif
|| ossl_err_load_UI_strings() == 0
# ifndef OPENSSL_NO_CMS
|| ossl_err_load_CMS_strings() == 0
# endif
# ifndef OPENSSL_NO_CRMF
|| ossl_err_load_CRMF_strings() == 0
|| ossl_err_load_CMP_strings() == 0
# endif
# ifndef OPENSSL_NO_CT
|| ossl_err_load_CT_strings() == 0
# endif
|| ossl_err_load_ESS_strings() == 0
|| ossl_err_load_ASYNC_strings() == 0
|| ossl_err_load_OSSL_STORE_strings() == 0
|| ossl_err_load_PROP_strings() == 0
|| ossl_err_load_PROV_strings() == 0
#endif
)
return 0;
return 1;
}
|
./openssl/crypto/err/err_mark.c | /*
* Copyright 2003-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
*/
#define OSSL_FORCE_ERR_STATE
#include <openssl/err.h>
#include "err_local.h"
int ERR_set_mark(void)
{
ERR_STATE *es;
es = ossl_err_get_state_int();
if (es == NULL)
return 0;
if (es->bottom == es->top)
return 0;
es->err_marks[es->top]++;
return 1;
}
int ERR_pop(void)
{
ERR_STATE *es;
es = ossl_err_get_state_int();
if (es == NULL || es->bottom == es->top)
return 0;
err_clear(es, es->top, 0);
es->top = es->top > 0 ? es->top - 1 : ERR_NUM_ERRORS - 1;
return 1;
}
int ERR_pop_to_mark(void)
{
ERR_STATE *es;
es = ossl_err_get_state_int();
if (es == NULL)
return 0;
while (es->bottom != es->top
&& es->err_marks[es->top] == 0) {
err_clear(es, es->top, 0);
es->top = es->top > 0 ? es->top - 1 : ERR_NUM_ERRORS - 1;
}
if (es->bottom == es->top)
return 0;
es->err_marks[es->top]--;
return 1;
}
int ERR_count_to_mark(void)
{
ERR_STATE *es;
int count = 0, top;
es = ossl_err_get_state_int();
if (es == NULL)
return 0;
top = es->top;
while (es->bottom != top
&& es->err_marks[top] == 0) {
++count;
top = top > 0 ? top - 1 : ERR_NUM_ERRORS - 1;
}
return count;
}
int ERR_clear_last_mark(void)
{
ERR_STATE *es;
int top;
es = ossl_err_get_state_int();
if (es == NULL)
return 0;
top = es->top;
while (es->bottom != top
&& es->err_marks[top] == 0) {
top = top > 0 ? top - 1 : ERR_NUM_ERRORS - 1;
}
if (es->bottom == top)
return 0;
es->err_marks[top]--;
return 1;
}
|
./openssl/crypto/err/err_local.h | /*
* 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 <string.h>
#include <openssl/err.h>
#include <openssl/e_os2.h>
static ossl_inline void err_get_slot(ERR_STATE *es)
{
es->top = (es->top + 1) % ERR_NUM_ERRORS;
if (es->top == es->bottom)
es->bottom = (es->bottom + 1) % ERR_NUM_ERRORS;
}
static ossl_inline void err_clear_data(ERR_STATE *es, size_t i, int deall)
{
if (es->err_data_flags[i] & ERR_TXT_MALLOCED) {
if (deall) {
OPENSSL_free(es->err_data[i]);
es->err_data[i] = NULL;
es->err_data_size[i] = 0;
es->err_data_flags[i] = 0;
} else if (es->err_data[i] != NULL) {
es->err_data[i][0] = '\0';
es->err_data_flags[i] = ERR_TXT_MALLOCED;
}
} else {
es->err_data[i] = NULL;
es->err_data_size[i] = 0;
es->err_data_flags[i] = 0;
}
}
static ossl_inline void err_set_error(ERR_STATE *es, size_t i,
int lib, int reason)
{
es->err_buffer[i] =
lib == ERR_LIB_SYS
? (unsigned int)(ERR_SYSTEM_FLAG | reason)
: ERR_PACK(lib, 0, reason);
}
static ossl_inline void err_set_debug(ERR_STATE *es, size_t i,
const char *file, int line,
const char *fn)
{
/*
* We dup the file and fn strings because they may be provider owned. If the
* provider gets unloaded, they may not be valid anymore.
*/
OPENSSL_free(es->err_file[i]);
if (file == NULL || file[0] == '\0')
es->err_file[i] = NULL;
else if ((es->err_file[i] = CRYPTO_malloc(strlen(file) + 1,
NULL, 0)) != NULL)
/* We cannot use OPENSSL_strdup due to possible recursion */
strcpy(es->err_file[i], file);
es->err_line[i] = line;
OPENSSL_free(es->err_func[i]);
if (fn == NULL || fn[0] == '\0')
es->err_func[i] = NULL;
else if ((es->err_func[i] = CRYPTO_malloc(strlen(fn) + 1,
NULL, 0)) != NULL)
strcpy(es->err_func[i], fn);
}
static ossl_inline void err_set_data(ERR_STATE *es, size_t i,
void *data, size_t datasz, int flags)
{
if ((es->err_data_flags[i] & ERR_TXT_MALLOCED) != 0)
OPENSSL_free(es->err_data[i]);
es->err_data[i] = data;
es->err_data_size[i] = datasz;
es->err_data_flags[i] = flags;
}
static ossl_inline void err_clear(ERR_STATE *es, size_t i, int deall)
{
err_clear_data(es, i, (deall));
es->err_marks[i] = 0;
es->err_flags[i] = 0;
es->err_buffer[i] = 0;
es->err_line[i] = -1;
OPENSSL_free(es->err_file[i]);
es->err_file[i] = NULL;
OPENSSL_free(es->err_func[i]);
es->err_func[i] = NULL;
}
ERR_STATE *ossl_err_get_state_int(void);
void ossl_err_string_int(unsigned long e, const char *func,
char *buf, size_t len);
|
./openssl/crypto/err/err_all_legacy.c | /*
* Copyright 2020-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 is the C source file where we include this header directly */
#include <openssl/cryptoerr_legacy.h>
#ifndef OPENSSL_NO_DEPRECATED_3_0
# include "crypto/err.h"
# include "crypto/asn1err.h"
# include "crypto/asyncerr.h"
# include "crypto/bnerr.h"
# include "crypto/buffererr.h"
# include "crypto/bioerr.h"
# include "crypto/cmserr.h"
# include "crypto/comperr.h"
# include "crypto/conferr.h"
# include "crypto/cryptoerr.h"
# include "crypto/cterr.h"
# include "crypto/dherr.h"
# include "crypto/dsaerr.h"
# include "internal/dsoerr.h"
# include "crypto/ecerr.h"
# include "crypto/engineerr.h"
# include "crypto/evperr.h"
# include "crypto/httperr.h"
# include "crypto/objectserr.h"
# include "crypto/ocsperr.h"
# include "crypto/pemerr.h"
# include "crypto/pkcs12err.h"
# include "crypto/pkcs7err.h"
# include "crypto/randerr.h"
# include "crypto/rsaerr.h"
# include "crypto/storeerr.h"
# include "crypto/tserr.h"
# include "crypto/uierr.h"
# include "crypto/x509err.h"
# include "crypto/x509v3err.h"
# ifdef OPENSSL_NO_ERR
# define IMPLEMENT_LEGACY_ERR_LOAD(lib) \
int ERR_load_##lib##_strings(void) \
{ \
return 1; \
}
# else
# define IMPLEMENT_LEGACY_ERR_LOAD(lib) \
int ERR_load_##lib##_strings(void) \
{ \
return ossl_err_load_##lib##_strings(); \
}
# endif
IMPLEMENT_LEGACY_ERR_LOAD(ASN1)
IMPLEMENT_LEGACY_ERR_LOAD(ASYNC)
IMPLEMENT_LEGACY_ERR_LOAD(BIO)
IMPLEMENT_LEGACY_ERR_LOAD(BN)
IMPLEMENT_LEGACY_ERR_LOAD(BUF)
# ifndef OPENSSL_NO_CMS
IMPLEMENT_LEGACY_ERR_LOAD(CMS)
# endif
# ifndef OPENSSL_NO_COMP
IMPLEMENT_LEGACY_ERR_LOAD(COMP)
# endif
IMPLEMENT_LEGACY_ERR_LOAD(CONF)
IMPLEMENT_LEGACY_ERR_LOAD(CRYPTO)
# ifndef OPENSSL_NO_CT
IMPLEMENT_LEGACY_ERR_LOAD(CT)
# endif
# ifndef OPENSSL_NO_DH
IMPLEMENT_LEGACY_ERR_LOAD(DH)
# endif
# ifndef OPENSSL_NO_DSA
IMPLEMENT_LEGACY_ERR_LOAD(DSA)
# endif
# ifndef OPENSSL_NO_EC
IMPLEMENT_LEGACY_ERR_LOAD(EC)
# endif
# ifndef OPENSSL_NO_ENGINE
IMPLEMENT_LEGACY_ERR_LOAD(ENGINE)
# endif
IMPLEMENT_LEGACY_ERR_LOAD(ERR)
IMPLEMENT_LEGACY_ERR_LOAD(EVP)
IMPLEMENT_LEGACY_ERR_LOAD(OBJ)
# ifndef OPENSSL_NO_OCSP
IMPLEMENT_LEGACY_ERR_LOAD(OCSP)
# endif
IMPLEMENT_LEGACY_ERR_LOAD(PEM)
IMPLEMENT_LEGACY_ERR_LOAD(PKCS12)
IMPLEMENT_LEGACY_ERR_LOAD(PKCS7)
IMPLEMENT_LEGACY_ERR_LOAD(RAND)
IMPLEMENT_LEGACY_ERR_LOAD(RSA)
IMPLEMENT_LEGACY_ERR_LOAD(OSSL_STORE)
# ifndef OPENSSL_NO_TS
IMPLEMENT_LEGACY_ERR_LOAD(TS)
# endif
IMPLEMENT_LEGACY_ERR_LOAD(UI)
IMPLEMENT_LEGACY_ERR_LOAD(X509)
IMPLEMENT_LEGACY_ERR_LOAD(X509V3)
#endif /* OPENSSL_NO_DEPRECATED_3_0 */
|
./openssl/crypto/err/err_save.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
*/
#define OSSL_FORCE_ERR_STATE
#include <openssl/err.h>
#include "err_local.h"
/*
* Save and restore error state.
* We are using CRYPTO_zalloc(.., NULL, 0) instead of OPENSSL_malloc() in
* these functions to prevent mem alloc error loop.
*/
ERR_STATE *OSSL_ERR_STATE_new(void)
{
return CRYPTO_zalloc(sizeof(ERR_STATE), NULL, 0);
}
void OSSL_ERR_STATE_save(ERR_STATE *es)
{
size_t i;
ERR_STATE *thread_es;
if (es == NULL)
return;
for (i = 0; i < ERR_NUM_ERRORS; i++)
err_clear(es, i, 1);
thread_es = ossl_err_get_state_int();
if (thread_es == NULL)
return;
memcpy(es, thread_es, sizeof(*es));
/* Taking over the pointers, just clear the thread state. */
memset(thread_es, 0, sizeof(*thread_es));
}
void OSSL_ERR_STATE_save_to_mark(ERR_STATE *es)
{
size_t i, j, count;
int top;
ERR_STATE *thread_es;
if (es == NULL)
return;
thread_es = ossl_err_get_state_int();
if (thread_es == NULL) {
for (i = 0; i < ERR_NUM_ERRORS; ++i)
err_clear(es, i, 1);
es->top = es->bottom = 0;
return;
}
/* Determine number of errors we are going to move. */
for (count = 0, top = thread_es->top;
thread_es->bottom != top
&& thread_es->err_marks[top] == 0;
++count)
top = top > 0 ? top - 1 : ERR_NUM_ERRORS - 1;
/* Move the errors, preserving order. */
for (i = 0, j = top; i < count; ++i) {
j = (j + 1) % ERR_NUM_ERRORS;
err_clear(es, i, 1);
/* Move the error entry to the given ERR_STATE. */
es->err_flags[i] = thread_es->err_flags[j];
es->err_marks[i] = 0;
es->err_buffer[i] = thread_es->err_buffer[j];
es->err_data[i] = thread_es->err_data[j];
es->err_data_size[i] = thread_es->err_data_size[j];
es->err_data_flags[i] = thread_es->err_data_flags[j];
es->err_file[i] = thread_es->err_file[j];
es->err_line[i] = thread_es->err_line[j];
es->err_func[i] = thread_es->err_func[j];
thread_es->err_flags[j] = 0;
thread_es->err_buffer[j] = 0;
thread_es->err_data[j] = NULL;
thread_es->err_data_size[j] = 0;
thread_es->err_data_flags[j] = 0;
thread_es->err_file[j] = NULL;
thread_es->err_line[j] = 0;
thread_es->err_func[j] = NULL;
}
if (i > 0) {
thread_es->top = top;
/* If we moved anything, es's stack always starts at [0]. */
es->top = i - 1;
es->bottom = ERR_NUM_ERRORS - 1;
} else {
/* Didn't move anything - empty stack */
es->top = es->bottom = 0;
}
/* Erase extra space as a precaution. */
for (; i < ERR_NUM_ERRORS; ++i)
err_clear(es, i, 1);
}
void OSSL_ERR_STATE_restore(const ERR_STATE *es)
{
size_t i;
ERR_STATE *thread_es;
if (es == NULL || es->bottom == es->top)
return;
thread_es = ossl_err_get_state_int();
if (thread_es == NULL)
return;
for (i = (size_t)es->bottom; i != (size_t)es->top;) {
size_t top;
i = (i + 1) % ERR_NUM_ERRORS;
if ((es->err_flags[i] & ERR_FLAG_CLEAR) != 0)
continue;
err_get_slot(thread_es);
top = thread_es->top;
err_clear(thread_es, top, 0);
thread_es->err_flags[top] = es->err_flags[i];
thread_es->err_buffer[top] = es->err_buffer[i];
err_set_debug(thread_es, top, es->err_file[i], es->err_line[i],
es->err_func[i]);
if (es->err_data[i] != NULL && es->err_data_size[i] != 0) {
void *data;
size_t data_sz = es->err_data_size[i];
data = CRYPTO_malloc(data_sz, NULL, 0);
if (data != NULL) {
memcpy(data, es->err_data[i], data_sz);
err_set_data(thread_es, top, data, data_sz,
es->err_data_flags[i] | ERR_TXT_MALLOCED);
}
} else {
err_clear_data(thread_es, top, 0);
}
}
}
|
./openssl/crypto/err/err.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
*/
#define OSSL_FORCE_ERR_STATE
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include "crypto/cryptlib.h"
#include "internal/err.h"
#include "crypto/err.h"
#include <openssl/err.h>
#include <openssl/crypto.h>
#include <openssl/buffer.h>
#include <openssl/bio.h>
#include <openssl/opensslconf.h>
#include "internal/thread_once.h"
#include "crypto/ctype.h"
#include "internal/constant_time.h"
#include "internal/e_os.h"
#include "err_local.h"
/* Forward declaration in case it's not published because of configuration */
ERR_STATE *ERR_get_state(void);
#ifndef OPENSSL_NO_ERR
static int err_load_strings(const ERR_STRING_DATA *str);
#endif
#ifndef OPENSSL_NO_ERR
static ERR_STRING_DATA ERR_str_libraries[] = {
{ERR_PACK(ERR_LIB_NONE, 0, 0), "unknown library"},
{ERR_PACK(ERR_LIB_SYS, 0, 0), "system library"},
{ERR_PACK(ERR_LIB_BN, 0, 0), "bignum routines"},
{ERR_PACK(ERR_LIB_RSA, 0, 0), "rsa routines"},
{ERR_PACK(ERR_LIB_DH, 0, 0), "Diffie-Hellman routines"},
{ERR_PACK(ERR_LIB_EVP, 0, 0), "digital envelope routines"},
{ERR_PACK(ERR_LIB_BUF, 0, 0), "memory buffer routines"},
{ERR_PACK(ERR_LIB_OBJ, 0, 0), "object identifier routines"},
{ERR_PACK(ERR_LIB_PEM, 0, 0), "PEM routines"},
{ERR_PACK(ERR_LIB_DSA, 0, 0), "dsa routines"},
{ERR_PACK(ERR_LIB_X509, 0, 0), "x509 certificate routines"},
{ERR_PACK(ERR_LIB_ASN1, 0, 0), "asn1 encoding routines"},
{ERR_PACK(ERR_LIB_CONF, 0, 0), "configuration file routines"},
{ERR_PACK(ERR_LIB_CRYPTO, 0, 0), "common libcrypto routines"},
{ERR_PACK(ERR_LIB_EC, 0, 0), "elliptic curve routines"},
{ERR_PACK(ERR_LIB_ECDSA, 0, 0), "ECDSA routines"},
{ERR_PACK(ERR_LIB_ECDH, 0, 0), "ECDH routines"},
{ERR_PACK(ERR_LIB_SSL, 0, 0), "SSL routines"},
{ERR_PACK(ERR_LIB_BIO, 0, 0), "BIO routines"},
{ERR_PACK(ERR_LIB_PKCS7, 0, 0), "PKCS7 routines"},
{ERR_PACK(ERR_LIB_X509V3, 0, 0), "X509 V3 routines"},
{ERR_PACK(ERR_LIB_PKCS12, 0, 0), "PKCS12 routines"},
{ERR_PACK(ERR_LIB_RAND, 0, 0), "random number generator"},
{ERR_PACK(ERR_LIB_DSO, 0, 0), "DSO support routines"},
{ERR_PACK(ERR_LIB_TS, 0, 0), "time stamp routines"},
{ERR_PACK(ERR_LIB_ENGINE, 0, 0), "engine routines"},
{ERR_PACK(ERR_LIB_OCSP, 0, 0), "OCSP routines"},
{ERR_PACK(ERR_LIB_UI, 0, 0), "UI routines"},
{ERR_PACK(ERR_LIB_FIPS, 0, 0), "FIPS routines"},
{ERR_PACK(ERR_LIB_CMS, 0, 0), "CMS routines"},
{ERR_PACK(ERR_LIB_CRMF, 0, 0), "CRMF routines"},
{ERR_PACK(ERR_LIB_CMP, 0, 0), "CMP routines"},
{ERR_PACK(ERR_LIB_HMAC, 0, 0), "HMAC routines"},
{ERR_PACK(ERR_LIB_CT, 0, 0), "CT routines"},
{ERR_PACK(ERR_LIB_ASYNC, 0, 0), "ASYNC routines"},
{ERR_PACK(ERR_LIB_KDF, 0, 0), "KDF routines"},
{ERR_PACK(ERR_LIB_OSSL_STORE, 0, 0), "STORE routines"},
{ERR_PACK(ERR_LIB_SM2, 0, 0), "SM2 routines"},
{ERR_PACK(ERR_LIB_ESS, 0, 0), "ESS routines"},
{ERR_PACK(ERR_LIB_PROV, 0, 0), "Provider routines"},
{ERR_PACK(ERR_LIB_OSSL_ENCODER, 0, 0), "ENCODER routines"},
{ERR_PACK(ERR_LIB_OSSL_DECODER, 0, 0), "DECODER routines"},
{ERR_PACK(ERR_LIB_HTTP, 0, 0), "HTTP routines"},
{0, NULL},
};
/*
* Should make sure that all ERR_R_ reasons defined in include/openssl/err.h.in
* are listed. For maintainability, please keep all reasons in the same order.
*/
static ERR_STRING_DATA ERR_str_reasons[] = {
{ERR_R_SYS_LIB, "system lib"},
{ERR_R_BN_LIB, "BN lib"},
{ERR_R_RSA_LIB, "RSA lib"},
{ERR_R_DH_LIB, "DH lib"},
{ERR_R_EVP_LIB, "EVP lib"},
{ERR_R_BUF_LIB, "BUF lib"},
{ERR_R_OBJ_LIB, "OBJ lib"},
{ERR_R_PEM_LIB, "PEM lib"},
{ERR_R_DSA_LIB, "DSA lib"},
{ERR_R_X509_LIB, "X509 lib"},
{ERR_R_ASN1_LIB, "ASN1 lib"},
{ERR_R_CRYPTO_LIB, "CRYPTO lib"},
{ERR_R_EC_LIB, "EC lib"},
{ERR_R_BIO_LIB, "BIO lib"},
{ERR_R_PKCS7_LIB, "PKCS7 lib"},
{ERR_R_X509V3_LIB, "X509V3 lib"},
{ERR_R_ENGINE_LIB, "ENGINE lib"},
{ERR_R_UI_LIB, "UI lib"},
{ERR_R_ECDSA_LIB, "ECDSA lib"},
{ERR_R_OSSL_STORE_LIB, "OSSL_STORE lib"},
{ERR_R_OSSL_DECODER_LIB, "OSSL_DECODER lib"},
{ERR_R_FATAL, "fatal"},
{ERR_R_MALLOC_FAILURE, "malloc failure"},
{ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED,
"called a function you should not call"},
{ERR_R_PASSED_NULL_PARAMETER, "passed a null parameter"},
{ERR_R_INTERNAL_ERROR, "internal error"},
{ERR_R_DISABLED, "called a function that was disabled at compile-time"},
{ERR_R_INIT_FAIL, "init fail"},
{ERR_R_PASSED_INVALID_ARGUMENT, "passed invalid argument"},
{ERR_R_OPERATION_FAIL, "operation fail"},
{ERR_R_INVALID_PROVIDER_FUNCTIONS, "invalid provider functions"},
{ERR_R_INTERRUPTED_OR_CANCELLED, "interrupted or cancelled"},
{ERR_R_NESTED_ASN1_ERROR, "nested asn1 error"},
{ERR_R_MISSING_ASN1_EOS, "missing asn1 eos"},
/*
* Something is unsupported, exactly what is expressed with additional data
*/
{ERR_R_UNSUPPORTED, "unsupported"},
/*
* A fetch failed for other reasons than the name to be fetched being
* unsupported.
*/
{ERR_R_FETCH_FAILED, "fetch failed"},
{ERR_R_INVALID_PROPERTY_DEFINITION, "invalid property definition"},
{ERR_R_UNABLE_TO_GET_READ_LOCK, "unable to get read lock"},
{ERR_R_UNABLE_TO_GET_WRITE_LOCK, "unable to get write lock"},
{0, NULL},
};
#endif
static CRYPTO_ONCE err_init = CRYPTO_ONCE_STATIC_INIT;
static int set_err_thread_local;
static CRYPTO_THREAD_LOCAL err_thread_local;
static CRYPTO_ONCE err_string_init = CRYPTO_ONCE_STATIC_INIT;
static CRYPTO_RWLOCK *err_string_lock = NULL;
#ifndef OPENSSL_NO_ERR
static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *);
#endif
/*
* The internal state
*/
#ifndef OPENSSL_NO_ERR
static LHASH_OF(ERR_STRING_DATA) *int_error_hash = NULL;
#endif
static int int_err_library_number = ERR_LIB_USER;
typedef enum ERR_GET_ACTION_e {
EV_POP, EV_PEEK, EV_PEEK_LAST
} ERR_GET_ACTION;
static unsigned long get_error_values(ERR_GET_ACTION g,
const char **file, int *line,
const char **func, const char **data,
int *flags);
#ifndef OPENSSL_NO_ERR
static unsigned long err_string_data_hash(const ERR_STRING_DATA *a)
{
unsigned long ret, l;
l = a->error;
ret = l ^ ERR_GET_LIB(l);
return (ret ^ ret % 19 * 13);
}
static int err_string_data_cmp(const ERR_STRING_DATA *a,
const ERR_STRING_DATA *b)
{
if (a->error == b->error)
return 0;
return a->error > b->error ? 1 : -1;
}
static ERR_STRING_DATA *int_err_get_item(const ERR_STRING_DATA *d)
{
ERR_STRING_DATA *p = NULL;
if (!CRYPTO_THREAD_read_lock(err_string_lock))
return NULL;
p = lh_ERR_STRING_DATA_retrieve(int_error_hash, d);
CRYPTO_THREAD_unlock(err_string_lock);
return p;
}
#endif
void OSSL_ERR_STATE_free(ERR_STATE *state)
{
int i;
if (state == NULL)
return;
for (i = 0; i < ERR_NUM_ERRORS; i++) {
err_clear(state, i, 1);
}
CRYPTO_free(state, OPENSSL_FILE, OPENSSL_LINE);
}
DEFINE_RUN_ONCE_STATIC(do_err_strings_init)
{
if (!OPENSSL_init_crypto(OPENSSL_INIT_BASE_ONLY, NULL))
return 0;
err_string_lock = CRYPTO_THREAD_lock_new();
if (err_string_lock == NULL)
return 0;
#ifndef OPENSSL_NO_ERR
int_error_hash = lh_ERR_STRING_DATA_new(err_string_data_hash,
err_string_data_cmp);
if (int_error_hash == NULL) {
CRYPTO_THREAD_lock_free(err_string_lock);
err_string_lock = NULL;
return 0;
}
#endif
return 1;
}
void err_cleanup(void)
{
if (set_err_thread_local != 0)
CRYPTO_THREAD_cleanup_local(&err_thread_local);
CRYPTO_THREAD_lock_free(err_string_lock);
err_string_lock = NULL;
#ifndef OPENSSL_NO_ERR
lh_ERR_STRING_DATA_free(int_error_hash);
int_error_hash = NULL;
#endif
}
#ifndef OPENSSL_NO_ERR
/*
* Legacy; pack in the library.
*/
static void err_patch(int lib, ERR_STRING_DATA *str)
{
unsigned long plib = ERR_PACK(lib, 0, 0);
for (; str->error != 0; str++)
str->error |= plib;
}
/*
* Hash in |str| error strings. Assumes the RUN_ONCE was done.
*/
static int err_load_strings(const ERR_STRING_DATA *str)
{
if (!CRYPTO_THREAD_write_lock(err_string_lock))
return 0;
for (; str->error; str++)
(void)lh_ERR_STRING_DATA_insert(int_error_hash,
(ERR_STRING_DATA *)str);
CRYPTO_THREAD_unlock(err_string_lock);
return 1;
}
#endif
int ossl_err_load_ERR_strings(void)
{
#ifndef OPENSSL_NO_ERR
if (!RUN_ONCE(&err_string_init, do_err_strings_init))
return 0;
err_load_strings(ERR_str_libraries);
err_load_strings(ERR_str_reasons);
#endif
return 1;
}
int ERR_load_strings(int lib, ERR_STRING_DATA *str)
{
#ifndef OPENSSL_NO_ERR
if (ossl_err_load_ERR_strings() == 0)
return 0;
err_patch(lib, str);
err_load_strings(str);
#endif
return 1;
}
int ERR_load_strings_const(const ERR_STRING_DATA *str)
{
#ifndef OPENSSL_NO_ERR
if (ossl_err_load_ERR_strings() == 0)
return 0;
err_load_strings(str);
#endif
return 1;
}
int ERR_unload_strings(int lib, ERR_STRING_DATA *str)
{
#ifndef OPENSSL_NO_ERR
if (!RUN_ONCE(&err_string_init, do_err_strings_init))
return 0;
if (!CRYPTO_THREAD_write_lock(err_string_lock))
return 0;
/*
* We don't need to ERR_PACK the lib, since that was done (to
* the table) when it was loaded.
*/
for (; str->error; str++)
(void)lh_ERR_STRING_DATA_delete(int_error_hash, str);
CRYPTO_THREAD_unlock(err_string_lock);
#endif
return 1;
}
void err_free_strings_int(void)
{
/* obsolete */
}
/********************************************************/
void ERR_clear_error(void)
{
int i;
ERR_STATE *es;
es = ossl_err_get_state_int();
if (es == NULL)
return;
for (i = 0; i < ERR_NUM_ERRORS; i++) {
err_clear(es, i, 0);
}
es->top = es->bottom = 0;
}
unsigned long ERR_get_error(void)
{
return get_error_values(EV_POP, NULL, NULL, NULL, NULL, NULL);
}
unsigned long ERR_get_error_all(const char **file, int *line,
const char **func,
const char **data, int *flags)
{
return get_error_values(EV_POP, file, line, func, data, flags);
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
unsigned long ERR_get_error_line(const char **file, int *line)
{
return get_error_values(EV_POP, file, line, NULL, NULL, NULL);
}
unsigned long ERR_get_error_line_data(const char **file, int *line,
const char **data, int *flags)
{
return get_error_values(EV_POP, file, line, NULL, data, flags);
}
#endif
unsigned long ERR_peek_error(void)
{
return get_error_values(EV_PEEK, NULL, NULL, NULL, NULL, NULL);
}
unsigned long ERR_peek_error_line(const char **file, int *line)
{
return get_error_values(EV_PEEK, file, line, NULL, NULL, NULL);
}
unsigned long ERR_peek_error_func(const char **func)
{
return get_error_values(EV_PEEK, NULL, NULL, func, NULL, NULL);
}
unsigned long ERR_peek_error_data(const char **data, int *flags)
{
return get_error_values(EV_PEEK, NULL, NULL, NULL, data, flags);
}
unsigned long ERR_peek_error_all(const char **file, int *line,
const char **func,
const char **data, int *flags)
{
return get_error_values(EV_PEEK, file, line, func, data, flags);
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
unsigned long ERR_peek_error_line_data(const char **file, int *line,
const char **data, int *flags)
{
return get_error_values(EV_PEEK, file, line, NULL, data, flags);
}
#endif
unsigned long ERR_peek_last_error(void)
{
return get_error_values(EV_PEEK_LAST, NULL, NULL, NULL, NULL, NULL);
}
unsigned long ERR_peek_last_error_line(const char **file, int *line)
{
return get_error_values(EV_PEEK_LAST, file, line, NULL, NULL, NULL);
}
unsigned long ERR_peek_last_error_func(const char **func)
{
return get_error_values(EV_PEEK_LAST, NULL, NULL, func, NULL, NULL);
}
unsigned long ERR_peek_last_error_data(const char **data, int *flags)
{
return get_error_values(EV_PEEK_LAST, NULL, NULL, NULL, data, flags);
}
unsigned long ERR_peek_last_error_all(const char **file, int *line,
const char **func,
const char **data, int *flags)
{
return get_error_values(EV_PEEK_LAST, file, line, func, data, flags);
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
unsigned long ERR_peek_last_error_line_data(const char **file, int *line,
const char **data, int *flags)
{
return get_error_values(EV_PEEK_LAST, file, line, NULL, data, flags);
}
#endif
static unsigned long get_error_values(ERR_GET_ACTION g,
const char **file, int *line,
const char **func,
const char **data, int *flags)
{
int i = 0;
ERR_STATE *es;
unsigned long ret;
es = ossl_err_get_state_int();
if (es == NULL)
return 0;
/*
* Clear anything that should have been cleared earlier. We do this
* here because this doesn't have constant-time issues.
*/
while (es->bottom != es->top) {
if (es->err_flags[es->top] & ERR_FLAG_CLEAR) {
err_clear(es, es->top, 0);
es->top = es->top > 0 ? es->top - 1 : ERR_NUM_ERRORS - 1;
continue;
}
i = (es->bottom + 1) % ERR_NUM_ERRORS;
if (es->err_flags[i] & ERR_FLAG_CLEAR) {
es->bottom = i;
err_clear(es, es->bottom, 0);
continue;
}
break;
}
/* If everything has been cleared, the stack is empty. */
if (es->bottom == es->top)
return 0;
/* Which error, the top of stack (latest one) or the first one? */
if (g == EV_PEEK_LAST)
i = es->top;
else
i = (es->bottom + 1) % ERR_NUM_ERRORS;
ret = es->err_buffer[i];
if (g == EV_POP) {
es->bottom = i;
es->err_buffer[i] = 0;
}
if (file != NULL) {
*file = es->err_file[i];
if (*file == NULL)
*file = "";
}
if (line != NULL)
*line = es->err_line[i];
if (func != NULL) {
*func = es->err_func[i];
if (*func == NULL)
*func = "";
}
if (flags != NULL)
*flags = es->err_data_flags[i];
if (data == NULL) {
if (g == EV_POP) {
err_clear_data(es, i, 0);
}
} else {
*data = es->err_data[i];
if (*data == NULL) {
*data = "";
if (flags != NULL)
*flags = 0;
}
}
return ret;
}
void ossl_err_string_int(unsigned long e, const char *func,
char *buf, size_t len)
{
char lsbuf[64], rsbuf[256];
const char *ls, *rs = NULL;
unsigned long l, r;
if (len == 0)
return;
l = ERR_GET_LIB(e);
ls = ERR_lib_error_string(e);
if (ls == NULL) {
BIO_snprintf(lsbuf, sizeof(lsbuf), "lib(%lu)", l);
ls = lsbuf;
}
/*
* ERR_reason_error_string() can't safely return system error strings,
* since it would call openssl_strerror_r(), which needs a buffer for
* thread safety. So for system errors, we call openssl_strerror_r()
* directly instead.
*/
r = ERR_GET_REASON(e);
#ifndef OPENSSL_NO_ERR
if (ERR_SYSTEM_ERROR(e)) {
if (openssl_strerror_r(r, rsbuf, sizeof(rsbuf)))
rs = rsbuf;
} else {
rs = ERR_reason_error_string(e);
}
#endif
if (rs == NULL) {
BIO_snprintf(rsbuf, sizeof(rsbuf), "reason(%lu)",
r & ~(ERR_RFLAGS_MASK << ERR_RFLAGS_OFFSET));
rs = rsbuf;
}
BIO_snprintf(buf, len, "error:%08lX:%s:%s:%s", e, ls, func, rs);
if (strlen(buf) == len - 1) {
/* Didn't fit; use a minimal format. */
BIO_snprintf(buf, len, "err:%lx:%lx:%lx:%lx", e, l, 0L, r);
}
}
void ERR_error_string_n(unsigned long e, char *buf, size_t len)
{
ossl_err_string_int(e, "", buf, len);
}
/*
* ERR_error_string_n should be used instead for ret != NULL as
* ERR_error_string cannot know how large the buffer is
*/
char *ERR_error_string(unsigned long e, char *ret)
{
static char buf[256];
if (ret == NULL)
ret = buf;
ERR_error_string_n(e, ret, (int)sizeof(buf));
return ret;
}
const char *ERR_lib_error_string(unsigned long e)
{
#ifndef OPENSSL_NO_ERR
ERR_STRING_DATA d, *p;
unsigned long l;
if (!RUN_ONCE(&err_string_init, do_err_strings_init)) {
return NULL;
}
l = ERR_GET_LIB(e);
d.error = ERR_PACK(l, 0, 0);
p = int_err_get_item(&d);
return ((p == NULL) ? NULL : p->string);
#else
return NULL;
#endif
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
const char *ERR_func_error_string(unsigned long e)
{
return NULL;
}
#endif
const char *ERR_reason_error_string(unsigned long e)
{
#ifndef OPENSSL_NO_ERR
ERR_STRING_DATA d, *p = NULL;
unsigned long l, r;
if (!RUN_ONCE(&err_string_init, do_err_strings_init)) {
return NULL;
}
/*
* ERR_reason_error_string() can't safely return system error strings,
* since openssl_strerror_r() needs a buffer for thread safety, and we
* haven't got one that would serve any sensible purpose.
*/
if (ERR_SYSTEM_ERROR(e))
return NULL;
l = ERR_GET_LIB(e);
r = ERR_GET_REASON(e);
d.error = ERR_PACK(l, 0, r);
p = int_err_get_item(&d);
if (p == NULL) {
d.error = ERR_PACK(0, 0, r);
p = int_err_get_item(&d);
}
return ((p == NULL) ? NULL : p->string);
#else
return NULL;
#endif
}
static void err_delete_thread_state(void *unused)
{
ERR_STATE *state = CRYPTO_THREAD_get_local(&err_thread_local);
if (state == NULL)
return;
CRYPTO_THREAD_set_local(&err_thread_local, NULL);
OSSL_ERR_STATE_free(state);
}
#ifndef OPENSSL_NO_DEPRECATED_1_1_0
void ERR_remove_thread_state(void *dummy)
{
}
#endif
#ifndef OPENSSL_NO_DEPRECATED_1_0_0
void ERR_remove_state(unsigned long pid)
{
}
#endif
DEFINE_RUN_ONCE_STATIC(err_do_init)
{
set_err_thread_local = 1;
return CRYPTO_THREAD_init_local(&err_thread_local, NULL);
}
ERR_STATE *ossl_err_get_state_int(void)
{
ERR_STATE *state;
int saveerrno = get_last_sys_error();
if (!OPENSSL_init_crypto(OPENSSL_INIT_BASE_ONLY, NULL))
return NULL;
if (!RUN_ONCE(&err_init, err_do_init))
return NULL;
state = CRYPTO_THREAD_get_local(&err_thread_local);
if (state == (ERR_STATE*)-1)
return NULL;
if (state == NULL) {
if (!CRYPTO_THREAD_set_local(&err_thread_local, (ERR_STATE*)-1))
return NULL;
state = OSSL_ERR_STATE_new();
if (state == NULL) {
CRYPTO_THREAD_set_local(&err_thread_local, NULL);
return NULL;
}
if (!ossl_init_thread_start(NULL, NULL, err_delete_thread_state)
|| !CRYPTO_THREAD_set_local(&err_thread_local, state)) {
OSSL_ERR_STATE_free(state);
CRYPTO_THREAD_set_local(&err_thread_local, NULL);
return NULL;
}
/* Ignore failures from these */
OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
}
set_sys_error(saveerrno);
return state;
}
#ifndef OPENSSL_NO_DEPRECATED_3_0
ERR_STATE *ERR_get_state(void)
{
return ossl_err_get_state_int();
}
#endif
/*
* err_shelve_state returns the current thread local error state
* and freezes the error module until err_unshelve_state is called.
*/
int err_shelve_state(void **state)
{
int saveerrno = get_last_sys_error();
/*
* Note, at present our only caller is OPENSSL_init_crypto(), indirectly
* via ossl_init_load_crypto_nodelete(), by which point the requested
* "base" initialization has already been performed, so the below call is a
* NOOP, that re-enters OPENSSL_init_crypto() only to quickly return.
*
* If are no other valid callers of this function, the call below can be
* removed, avoiding the re-entry into OPENSSL_init_crypto(). If there are
* potential uses that are not from inside OPENSSL_init_crypto(), then this
* call is needed, but some care is required to make sure that the re-entry
* remains a NOOP.
*/
if (!OPENSSL_init_crypto(OPENSSL_INIT_BASE_ONLY, NULL))
return 0;
if (!RUN_ONCE(&err_init, err_do_init))
return 0;
*state = CRYPTO_THREAD_get_local(&err_thread_local);
if (!CRYPTO_THREAD_set_local(&err_thread_local, (ERR_STATE*)-1))
return 0;
set_sys_error(saveerrno);
return 1;
}
/*
* err_unshelve_state restores the error state that was returned
* by err_shelve_state previously.
*/
void err_unshelve_state(void* state)
{
if (state != (void*)-1)
CRYPTO_THREAD_set_local(&err_thread_local, (ERR_STATE*)state);
}
int ERR_get_next_error_library(void)
{
int ret;
if (!RUN_ONCE(&err_string_init, do_err_strings_init))
return 0;
if (!CRYPTO_THREAD_write_lock(err_string_lock))
return 0;
ret = int_err_library_number++;
CRYPTO_THREAD_unlock(err_string_lock);
return ret;
}
static int err_set_error_data_int(char *data, size_t size, int flags,
int deallocate)
{
ERR_STATE *es;
es = ossl_err_get_state_int();
if (es == NULL)
return 0;
err_clear_data(es, es->top, deallocate);
err_set_data(es, es->top, data, size, flags);
return 1;
}
void ERR_set_error_data(char *data, int flags)
{
/*
* This function is void so we cannot propagate the error return. Since it
* is also in the public API we can't change the return type.
*
* We estimate the size of the data. If it's not flagged as allocated,
* then this is safe, and if it is flagged as allocated, then our size
* may be smaller than the actual allocation, but that doesn't matter
* too much, the buffer will remain untouched or will eventually be
* reallocated to a new size.
*
* callers should be advised that this function takes over ownership of
* the allocated memory, i.e. they can't count on the pointer to remain
* valid.
*/
err_set_error_data_int(data, strlen(data) + 1, flags, 1);
}
void ERR_add_error_data(int num, ...)
{
va_list args;
va_start(args, num);
ERR_add_error_vdata(num, args);
va_end(args);
}
void ERR_add_error_vdata(int num, va_list args)
{
int i, len, size;
int flags = ERR_TXT_MALLOCED | ERR_TXT_STRING;
char *str, *arg;
ERR_STATE *es;
/* Get the current error data; if an allocated string get it. */
es = ossl_err_get_state_int();
if (es == NULL)
return;
i = es->top;
/*
* If err_data is allocated already, reuse the space.
* Otherwise, allocate a small new buffer.
*/
if ((es->err_data_flags[i] & flags) == flags
&& ossl_assert(es->err_data[i] != NULL)) {
str = es->err_data[i];
size = es->err_data_size[i];
/*
* To protect the string we just grabbed from tampering by other
* functions we may call, or to protect them from freeing a pointer
* that may no longer be valid at that point, we clear away the
* data pointer and the flags. We will set them again at the end
* of this function.
*/
es->err_data[i] = NULL;
es->err_data_flags[i] = 0;
} else if ((str = OPENSSL_malloc(size = 81)) == NULL) {
return;
} else {
str[0] = '\0';
}
len = strlen(str);
while (--num >= 0) {
arg = va_arg(args, char *);
if (arg == NULL)
arg = "<NULL>";
len += strlen(arg);
if (len >= size) {
char *p;
size = len + 20;
p = OPENSSL_realloc(str, size);
if (p == NULL) {
OPENSSL_free(str);
return;
}
str = p;
}
OPENSSL_strlcat(str, arg, (size_t)size);
}
if (!err_set_error_data_int(str, size, flags, 0))
OPENSSL_free(str);
}
void err_clear_last_constant_time(int clear)
{
ERR_STATE *es;
int top;
es = ossl_err_get_state_int();
if (es == NULL)
return;
top = es->top;
/*
* Flag error as cleared but remove it elsewhere to avoid two errors
* accessing the same error stack location, revealing timing information.
*/
clear = constant_time_select_int(constant_time_eq_int(clear, 0),
0, ERR_FLAG_CLEAR);
es->err_flags[top] |= clear;
}
|
./openssl/crypto/err/err_prn.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
*/
#define OSSL_FORCE_ERR_STATE
#include <stdio.h>
#include "internal/cryptlib.h"
#include <openssl/crypto.h>
#include <openssl/buffer.h>
#include <openssl/err.h>
#include "err_local.h"
#define ERR_PRINT_BUF_SIZE 4096
void ERR_print_errors_cb(int (*cb) (const char *str, size_t len, void *u),
void *u)
{
CRYPTO_THREAD_ID tid = CRYPTO_THREAD_get_current_id();
unsigned long l;
const char *file, *data, *func;
int line, flags;
while ((l = ERR_get_error_all(&file, &line, &func, &data, &flags)) != 0) {
char buf[ERR_PRINT_BUF_SIZE] = "";
char *hex = NULL;
int offset;
if ((flags & ERR_TXT_STRING) == 0)
data = "";
hex = ossl_buf2hexstr_sep((const unsigned char *)&tid, sizeof(tid), '\0');
BIO_snprintf(buf, sizeof(buf), "%s:", hex == NULL ? "<null>" : hex);
offset = strlen(buf);
ossl_err_string_int(l, func, buf + offset, sizeof(buf) - offset);
offset += strlen(buf + offset);
BIO_snprintf(buf + offset, sizeof(buf) - offset, ":%s:%d:%s\n",
file, line, data);
OPENSSL_free(hex);
if (cb(buf, strlen(buf), u) <= 0)
break; /* abort outputting the error report */
}
}
/* auxiliary function for incrementally reporting texts via the error queue */
static void put_error(int lib, const char *func, int reason,
const char *file, int line)
{
ERR_new();
ERR_set_debug(file, line, func);
ERR_set_error(lib, reason, NULL /* no data here, so fmt is NULL */);
}
#define TYPICAL_MAX_OUTPUT_BEFORE_DATA 100
#define MAX_DATA_LEN (ERR_PRINT_BUF_SIZE - TYPICAL_MAX_OUTPUT_BEFORE_DATA)
void ERR_add_error_txt(const char *separator, const char *txt)
{
const char *file = NULL;
int line;
const char *func = NULL;
const char *data = NULL;
int flags;
unsigned long err = ERR_peek_last_error();
if (separator == NULL)
separator = "";
if (err == 0)
put_error(ERR_LIB_NONE, NULL, 0, "", 0);
do {
size_t available_len, data_len;
const char *curr = txt, *next = txt;
const char *leading_separator = separator;
int trailing_separator = 0;
char *tmp;
ERR_peek_last_error_all(&file, &line, &func, &data, &flags);
if ((flags & ERR_TXT_STRING) == 0) {
data = "";
leading_separator = "";
}
data_len = strlen(data);
/* workaround for limit of ERR_print_errors_cb() */
if (data_len >= MAX_DATA_LEN
|| strlen(separator) >= (size_t)(MAX_DATA_LEN - data_len))
available_len = 0;
else
available_len = MAX_DATA_LEN - data_len - strlen(separator) - 1;
/* MAX_DATA_LEN > available_len >= 0 */
if (*separator == '\0') {
const size_t len_next = strlen(next);
if (len_next <= available_len) {
next += len_next;
curr = NULL; /* no need to split */
} else {
next += available_len;
curr = next; /* will split at this point */
}
} else {
while (*next != '\0' && (size_t)(next - txt) <= available_len) {
curr = next;
next = strstr(curr, separator);
if (next != NULL) {
next += strlen(separator);
trailing_separator = *next == '\0';
} else {
next = curr + strlen(curr);
}
}
if ((size_t)(next - txt) <= available_len)
curr = NULL; /* the above loop implies *next == '\0' */
}
if (curr != NULL) {
/* split error msg at curr since error data would get too long */
if (curr != txt) {
tmp = OPENSSL_strndup(txt, curr - txt);
if (tmp == NULL)
return;
ERR_add_error_data(2, separator, tmp);
OPENSSL_free(tmp);
}
put_error(ERR_GET_LIB(err), func, err, file, line);
txt = curr;
} else {
if (trailing_separator) {
tmp = OPENSSL_strndup(txt, next - strlen(separator) - txt);
if (tmp == NULL)
return;
/* output txt without the trailing separator */
ERR_add_error_data(2, leading_separator, tmp);
OPENSSL_free(tmp);
} else {
ERR_add_error_data(2, leading_separator, txt);
}
txt = next; /* finished */
}
} while (*txt != '\0');
}
void ERR_add_error_mem_bio(const char *separator, BIO *bio)
{
if (bio != NULL) {
char *str;
long len = BIO_get_mem_data(bio, &str);
if (len > 0) {
if (str[len - 1] != '\0') {
if (BIO_write(bio, "", 1) <= 0)
return;
len = BIO_get_mem_data(bio, &str);
}
if (len > 1)
ERR_add_error_txt(separator, str);
}
}
}
static int print_bio(const char *str, size_t len, void *bp)
{
return BIO_write((BIO *)bp, str, len);
}
void ERR_print_errors(BIO *bp)
{
ERR_print_errors_cb(print_bio, bp);
}
#ifndef OPENSSL_NO_STDIO
void ERR_print_errors_fp(FILE *fp)
{
BIO *bio = BIO_new_fp(fp, BIO_NOCLOSE);
if (bio == NULL)
return;
ERR_print_errors_cb(print_bio, bio);
BIO_free(bio);
}
#endif
|
./openssl/crypto/thread/arch.c | /*
* Copyright 2019-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 <openssl/configuration.h>
#include <internal/thread_arch.h>
CRYPTO_THREAD *ossl_crypto_thread_native_start(CRYPTO_THREAD_ROUTINE routine,
void *data, int joinable)
{
CRYPTO_THREAD *handle;
if (routine == NULL)
return NULL;
handle = OPENSSL_zalloc(sizeof(*handle));
if (handle == NULL)
return NULL;
if ((handle->lock = ossl_crypto_mutex_new()) == NULL)
goto fail;
if ((handle->statelock = ossl_crypto_mutex_new()) == NULL)
goto fail;
if ((handle->condvar = ossl_crypto_condvar_new()) == NULL)
goto fail;
handle->data = data;
handle->routine = routine;
handle->joinable = joinable;
if (ossl_crypto_thread_native_spawn(handle) == 1)
return handle;
fail:
ossl_crypto_condvar_free(&handle->condvar);
ossl_crypto_mutex_free(&handle->statelock);
ossl_crypto_mutex_free(&handle->lock);
OPENSSL_free(handle);
return NULL;
}
int ossl_crypto_thread_native_join(CRYPTO_THREAD *thread, CRYPTO_THREAD_RETVAL *retval)
{
uint64_t req_state_mask;
if (thread == NULL)
return 0;
ossl_crypto_mutex_lock(thread->statelock);
req_state_mask = CRYPTO_THREAD_FINISHED | CRYPTO_THREAD_JOINED;
while (!CRYPTO_THREAD_GET_STATE(thread, req_state_mask))
ossl_crypto_condvar_wait(thread->condvar, thread->statelock);
if (CRYPTO_THREAD_GET_STATE(thread, CRYPTO_THREAD_JOINED))
goto pass;
/* Await concurrent join completion, if any. */
while (CRYPTO_THREAD_GET_STATE(thread, CRYPTO_THREAD_JOIN_AWAIT)) {
if (!CRYPTO_THREAD_GET_STATE(thread, CRYPTO_THREAD_JOINED))
ossl_crypto_condvar_wait(thread->condvar, thread->statelock);
if (CRYPTO_THREAD_GET_STATE(thread, CRYPTO_THREAD_JOINED))
goto pass;
}
CRYPTO_THREAD_SET_STATE(thread, CRYPTO_THREAD_JOIN_AWAIT);
ossl_crypto_mutex_unlock(thread->statelock);
if (ossl_crypto_thread_native_perform_join(thread, retval) == 0)
goto fail;
ossl_crypto_mutex_lock(thread->statelock);
pass:
CRYPTO_THREAD_UNSET_ERROR(thread, CRYPTO_THREAD_JOINED);
CRYPTO_THREAD_SET_STATE(thread, CRYPTO_THREAD_JOINED);
/*
* Signal join completion. It is important to signal even if we haven't
* performed an actual join. Multiple threads could be awaiting the
* CRYPTO_THREAD_JOIN_AWAIT -> CRYPTO_THREAD_JOINED transition, but signal
* on actual join would wake only one. Signalling here will always wake one.
*/
ossl_crypto_condvar_signal(thread->condvar);
ossl_crypto_mutex_unlock(thread->statelock);
if (retval != NULL)
*retval = thread->retval;
return 1;
fail:
ossl_crypto_mutex_lock(thread->statelock);
CRYPTO_THREAD_SET_ERROR(thread, CRYPTO_THREAD_JOINED);
/* Have another thread that's awaiting join retry to avoid that
* thread deadlock. */
CRYPTO_THREAD_UNSET_STATE(thread, CRYPTO_THREAD_JOIN_AWAIT);
ossl_crypto_condvar_signal(thread->condvar);
ossl_crypto_mutex_unlock(thread->statelock);
return 0;
}
int ossl_crypto_thread_native_clean(CRYPTO_THREAD *handle)
{
uint64_t req_state_mask;
if (handle == NULL)
return 0;
req_state_mask = 0;
req_state_mask |= CRYPTO_THREAD_FINISHED;
req_state_mask |= CRYPTO_THREAD_JOINED;
ossl_crypto_mutex_lock(handle->statelock);
if (CRYPTO_THREAD_GET_STATE(handle, req_state_mask) == 0) {
ossl_crypto_mutex_unlock(handle->statelock);
return 0;
}
ossl_crypto_mutex_unlock(handle->statelock);
ossl_crypto_mutex_free(&handle->lock);
ossl_crypto_mutex_free(&handle->statelock);
ossl_crypto_condvar_free(&handle->condvar);
OPENSSL_free(handle->handle);
OPENSSL_free(handle);
return 1;
}
|
./openssl/crypto/thread/internal.c | /*
* Copyright 2019-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 <openssl/configuration.h>
#include <openssl/e_os2.h>
#include <openssl/types.h>
#include <openssl/crypto.h>
#include <internal/thread.h>
#include <internal/thread_arch.h>
#if !defined(OPENSSL_NO_DEFAULT_THREAD_POOL)
static ossl_inline uint64_t _ossl_get_avail_threads(OSSL_LIB_CTX_THREADS *tdata)
{
/* assumes that tdata->lock is taken */
return tdata->max_threads - tdata->active_threads;
}
uint64_t ossl_get_avail_threads(OSSL_LIB_CTX *ctx)
{
uint64_t retval = 0;
OSSL_LIB_CTX_THREADS *tdata = OSSL_LIB_CTX_GET_THREADS(ctx);
if (tdata == NULL)
return retval;
ossl_crypto_mutex_lock(tdata->lock);
retval = _ossl_get_avail_threads(tdata);
ossl_crypto_mutex_unlock(tdata->lock);
return retval;
}
void *ossl_crypto_thread_start(OSSL_LIB_CTX *ctx, CRYPTO_THREAD_ROUTINE start,
void *data)
{
CRYPTO_THREAD *thread;
OSSL_LIB_CTX_THREADS *tdata = OSSL_LIB_CTX_GET_THREADS(ctx);
if (tdata == NULL)
return NULL;
ossl_crypto_mutex_lock(tdata->lock);
if (tdata == NULL || tdata->max_threads == 0) {
ossl_crypto_mutex_unlock(tdata->lock);
return NULL;
}
while (_ossl_get_avail_threads(tdata) == 0)
ossl_crypto_condvar_wait(tdata->cond_finished, tdata->lock);
tdata->active_threads++;
ossl_crypto_mutex_unlock(tdata->lock);
thread = ossl_crypto_thread_native_start(start, data, 1);
if (thread == NULL) {
ossl_crypto_mutex_lock(tdata->lock);
tdata->active_threads--;
ossl_crypto_mutex_unlock(tdata->lock);
goto fail;
}
thread->ctx = ctx;
fail:
return (void *) thread;
}
int ossl_crypto_thread_join(void *vhandle, CRYPTO_THREAD_RETVAL *retval)
{
CRYPTO_THREAD *handle = vhandle;
OSSL_LIB_CTX_THREADS *tdata;
if (vhandle == NULL)
return 0;
tdata = OSSL_LIB_CTX_GET_THREADS(handle->ctx);
if (tdata == NULL)
return 0;
if (ossl_crypto_thread_native_join(handle, retval) == 0)
return 0;
ossl_crypto_mutex_lock(tdata->lock);
tdata->active_threads--;
ossl_crypto_condvar_signal(tdata->cond_finished);
ossl_crypto_mutex_unlock(tdata->lock);
return 1;
}
int ossl_crypto_thread_clean(void *vhandle)
{
CRYPTO_THREAD *handle = vhandle;
return ossl_crypto_thread_native_clean(handle);
}
#else
ossl_inline uint64_t ossl_get_avail_threads(OSSL_LIB_CTX *ctx)
{
return 0;
}
void *ossl_crypto_thread_start(OSSL_LIB_CTX *ctx, CRYPTO_THREAD_ROUTINE start,
void *data)
{
return NULL;
}
int ossl_crypto_thread_join(void *vhandle, CRYPTO_THREAD_RETVAL *retval)
{
return 0;
}
int ossl_crypto_thread_clean(void *vhandle)
{
return 0;
}
#endif
void *ossl_threads_ctx_new(OSSL_LIB_CTX *ctx)
{
struct openssl_threads_st *t = OPENSSL_zalloc(sizeof(*t));
if (t == NULL)
return NULL;
t->lock = ossl_crypto_mutex_new();
t->cond_finished = ossl_crypto_condvar_new();
if (t->lock == NULL || t->cond_finished == NULL)
goto fail;
return t;
fail:
ossl_threads_ctx_free((void *)t);
return NULL;
}
void ossl_threads_ctx_free(void *vdata)
{
OSSL_LIB_CTX_THREADS *t = (OSSL_LIB_CTX_THREADS *) vdata;
if (t == NULL)
return;
ossl_crypto_mutex_free(&t->lock);
ossl_crypto_condvar_free(&t->cond_finished);
OPENSSL_free(t);
}
|
./openssl/crypto/thread/api.c | /*
* Copyright 2019-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/configuration.h>
#include <openssl/thread.h>
#include <internal/thread.h>
uint32_t OSSL_get_thread_support_flags(void)
{
int support = 0;
#if !defined(OPENSSL_NO_THREAD_POOL)
support |= OSSL_THREAD_SUPPORT_FLAG_THREAD_POOL;
#endif
#if !defined(OPENSSL_NO_DEFAULT_THREAD_POOL)
support |= OSSL_THREAD_SUPPORT_FLAG_DEFAULT_SPAWN;
#endif
return support;
}
#if defined(OPENSSL_NO_THREAD_POOL) || defined(OPENSSL_NO_DEFAULT_THREAD_POOL)
int OSSL_set_max_threads(OSSL_LIB_CTX *ctx, uint64_t max_threads)
{
return 0;
}
uint64_t OSSL_get_max_threads(OSSL_LIB_CTX *ctx)
{
return 0;
}
#else
uint64_t OSSL_get_max_threads(OSSL_LIB_CTX *ctx)
{
uint64_t ret = 0;
OSSL_LIB_CTX_THREADS *tdata = OSSL_LIB_CTX_GET_THREADS(ctx);
if (tdata == NULL)
goto fail;
ossl_crypto_mutex_lock(tdata->lock);
ret = tdata->max_threads;
ossl_crypto_mutex_unlock(tdata->lock);
fail:
return ret;
}
int OSSL_set_max_threads(OSSL_LIB_CTX *ctx, uint64_t max_threads)
{
OSSL_LIB_CTX_THREADS *tdata;
tdata = OSSL_LIB_CTX_GET_THREADS(ctx);
if (tdata == NULL)
return 0;
ossl_crypto_mutex_lock(tdata->lock);
tdata->max_threads = max_threads;
ossl_crypto_mutex_unlock(tdata->lock);
return 1;
}
#endif
|
./openssl/crypto/thread/arch/thread_win.c | /*
* Copyright 2019-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 <internal/thread_arch.h>
#if defined(OPENSSL_THREADS_WINNT)
# include <process.h>
# include <windows.h>
static unsigned __stdcall thread_start_thunk(LPVOID vthread)
{
CRYPTO_THREAD *thread;
CRYPTO_THREAD_RETVAL ret;
thread = (CRYPTO_THREAD *)vthread;
thread->thread_id = GetCurrentThreadId();
ret = thread->routine(thread->data);
ossl_crypto_mutex_lock(thread->statelock);
CRYPTO_THREAD_SET_STATE(thread, CRYPTO_THREAD_FINISHED);
thread->retval = ret;
ossl_crypto_condvar_signal(thread->condvar);
ossl_crypto_mutex_unlock(thread->statelock);
return 0;
}
int ossl_crypto_thread_native_spawn(CRYPTO_THREAD *thread)
{
HANDLE *handle;
handle = OPENSSL_zalloc(sizeof(*handle));
if (handle == NULL)
goto fail;
*handle = (HANDLE)_beginthreadex(NULL, 0, &thread_start_thunk, thread, 0, NULL);
if (*handle == NULL)
goto fail;
thread->handle = handle;
return 1;
fail:
thread->handle = NULL;
OPENSSL_free(handle);
return 0;
}
int ossl_crypto_thread_native_perform_join(CRYPTO_THREAD *thread, CRYPTO_THREAD_RETVAL *retval)
{
DWORD thread_retval;
HANDLE *handle;
if (thread == NULL || thread->handle == NULL)
return 0;
handle = (HANDLE *) thread->handle;
if (WaitForSingleObject(*handle, INFINITE) != WAIT_OBJECT_0)
return 0;
if (GetExitCodeThread(*handle, &thread_retval) == 0)
return 0;
/*
* GetExitCodeThread call followed by this check is to make sure that
* the thread exited properly. In particular, thread_retval may be
* non-zero when exited via explicit ExitThread/TerminateThread or
* if the thread is still active (returns STILL_ACTIVE (259)).
*/
if (thread_retval != 0)
return 0;
if (CloseHandle(*handle) == 0)
return 0;
return 1;
}
int ossl_crypto_thread_native_exit(void)
{
_endthreadex(0);
return 1;
}
int ossl_crypto_thread_native_is_self(CRYPTO_THREAD *thread)
{
return thread->thread_id == GetCurrentThreadId();
}
CRYPTO_MUTEX *ossl_crypto_mutex_new(void)
{
CRITICAL_SECTION *mutex;
if ((mutex = OPENSSL_zalloc(sizeof(*mutex))) == NULL)
return NULL;
InitializeCriticalSection(mutex);
return (CRYPTO_MUTEX *)mutex;
}
void ossl_crypto_mutex_lock(CRYPTO_MUTEX *mutex)
{
CRITICAL_SECTION *mutex_p;
mutex_p = (CRITICAL_SECTION *)mutex;
EnterCriticalSection(mutex_p);
}
int ossl_crypto_mutex_try_lock(CRYPTO_MUTEX *mutex)
{
CRITICAL_SECTION *mutex_p;
mutex_p = (CRITICAL_SECTION *)mutex;
if (TryEnterCriticalSection(mutex_p))
return 1;
return 0;
}
void ossl_crypto_mutex_unlock(CRYPTO_MUTEX *mutex)
{
CRITICAL_SECTION *mutex_p;
mutex_p = (CRITICAL_SECTION *)mutex;
LeaveCriticalSection(mutex_p);
}
void ossl_crypto_mutex_free(CRYPTO_MUTEX **mutex)
{
CRITICAL_SECTION **mutex_p;
mutex_p = (CRITICAL_SECTION **)mutex;
if (*mutex_p != NULL)
DeleteCriticalSection(*mutex_p);
OPENSSL_free(*mutex_p);
*mutex = NULL;
}
static int determine_timeout(OSSL_TIME deadline, DWORD *w_timeout_p)
{
OSSL_TIME now, delta;
uint64_t ms;
if (ossl_time_is_infinite(deadline)) {
*w_timeout_p = INFINITE;
return 1;
}
now = ossl_time_now();
delta = ossl_time_subtract(deadline, now);
if (ossl_time_is_zero(delta))
return 0;
ms = ossl_time2ms(delta);
/*
* Amount of time we want to wait is too long for the 32-bit argument to
* the Win32 API, so just wait as long as possible.
*/
if (ms > (uint64_t)(INFINITE - 1))
*w_timeout_p = INFINITE - 1;
else
*w_timeout_p = (DWORD)ms;
return 1;
}
# if defined(OPENSSL_THREADS_WINNT_LEGACY)
# include <assert.h>
/*
* Win32, before Vista, did not have an OS-provided condition variable
* construct. This leads to the need to construct our own condition variable
* construct in order to support Windows XP.
*
* It is difficult to construct a condition variable construct using the
* OS-provided primitives in a way that is both correct (avoiding race
* conditions where broadcasts get lost) and fair.
*
* CORRECTNESS:
* A blocked thread is a thread which is calling wait(), between the
* precise instants at which the external mutex passed to wait() is
* unlocked and the instant at which it is relocked.
*
* a)
* - If broadcast() is called, ALL blocked threads MUST be unblocked.
* - If signal() is called, at least one blocked thread MUST be unblocked.
*
* (i.e.: a signal or broadcast must never get 'lost')
*
* b)
* - If broadcast() or signal() is called, this must not cause a thread
* which is not blocked to return immediately from a subsequent
* call to wait().
*
* FAIRNESS:
* If broadcast() is called at time T1, all blocked threads must be unblocked
* before any thread which subsequently calls wait() at time T2 > T1 is
* unblocked.
*
* An example of an implementation which lacks fairness is as follows:
*
* t1 enters wait()
* t2 enters wait()
*
* tZ calls broadcast()
*
* t1 exits wait()
* t1 enters wait()
*
* tZ calls broadcast()
*
* t1 exits wait()
*
* IMPLEMENTATION:
*
* The most suitable primitives available to us in Windows XP are semaphores,
* auto-reset events and manual-reset events. A solution based on semaphores
* is chosen.
*
* PROBLEM. Designing a solution based on semaphores is non-trivial because,
* while it is easy to track the number of waiters in an interlocked data
* structure and then add that number to the semaphore, this does not
* guarantee fairness or correctness. Consider the following situation:
*
* - t1 enters wait(), adding 1 to the wait counter & blocks on the semaphore
* - t2 enters wait(), adding 1 to the wait counter & blocks on the semaphore
* - tZ calls broadcast(), finds the wait counter is 2, adds 2 to the semaphore
*
* - t1 exits wait()
* - t1 immediately reenters wait() and blocks on the semaphore
* - The semaphore is still positive due to also having been signalled
* for t2, therefore it is decremented
* - t1 exits wait() immediately; t2 is never woken
*
* GENERATION COUNTERS. One naive solution to this is to use a generation
* counter. Each broadcast() invocation increments a generation counter. If
* the generation counter has not changed during a semaphore wait operation
* inside wait(), this indicates that no broadcast() call has been made in
* the meantime; therefore, the successful semaphore decrement must have
* 'stolen' a wakeup from another thread which was waiting to wakeup from the
* prior broadcast() call but which had not yet had a chance to do so. The
* semaphore can then be reincremented and the wait() operation repeated.
*
* However, this suffers from the obvious problem that without OS guarantees
* as to how semaphore readiness events are distributed amongst threads,
* there is no particular guarantee that the semaphore readiness event will
* not be immediately redistributed back to the same thread t1.
*
* SOLUTION. A solution is chosen as follows. In its initial state, a
* condition variable can accept waiters, who wait for the semaphore
* normally. However, once broadcast() is called, the condition
* variable becomes 'closed'. Any existing blocked threads are unblocked,
* but any new calls to wait() will instead enter a blocking pre-wait stage.
* Pre-wait threads are not considered to be waiting (and the external
* mutex remains held). A call to wait() in pre-wait cannot progress
* to waiting until all threads due to be unblocked by the prior broadcast()
* call have returned and had a chance to execute.
*
* This pre-wait does not affect a thread if it does not call wait()
* again until after all threads have had a chance to execute.
*
* RESOURCE USAGE. Aside from an allocation for the condition variable
* structure, this solution uses two Win32 semaphores.
*
* FUTURE OPTIMISATIONS:
*
* An optimised multi-generation implementation is possible at the cost of
* higher Win32 resource usage. Multiple 'buckets' could be defined, with
* usage rotating between buckets internally as buckets become closed.
* This would avoid the need for the prewait in more cases, depending
* on intensity of usage.
*
*/
typedef struct legacy_condvar_st {
CRYPTO_MUTEX *int_m; /* internal mutex */
HANDLE sema; /* main wait semaphore */
HANDLE prewait_sema; /* prewait semaphore */
/*
* All of the following fields are protected by int_m.
*
* num_wake only ever increases by virtue of a corresponding decrease in
* num_wait. num_wait can decrease for other reasons (for example due to a
* wait operation timing out).
*/
size_t num_wait; /* Num. threads currently blocked */
size_t num_wake; /* Num. threads due to wake up */
size_t num_prewait; /* Num. threads in prewait */
size_t gen; /* Prewait generation */
int closed; /* Is closed? */
} LEGACY_CONDVAR;
CRYPTO_CONDVAR *ossl_crypto_condvar_new(void)
{
LEGACY_CONDVAR *cv;
if ((cv = OPENSSL_malloc(sizeof(LEGACY_CONDVAR))) == NULL)
return NULL;
if ((cv->int_m = ossl_crypto_mutex_new()) == NULL) {
OPENSSL_free(cv);
return NULL;
}
if ((cv->sema = CreateSemaphoreA(NULL, 0, LONG_MAX, NULL)) == NULL) {
ossl_crypto_mutex_free(&cv->int_m);
OPENSSL_free(cv);
return NULL;
}
if ((cv->prewait_sema = CreateSemaphoreA(NULL, 0, LONG_MAX, NULL)) == NULL) {
CloseHandle(cv->sema);
ossl_crypto_mutex_free(&cv->int_m);
OPENSSL_free(cv);
return NULL;
}
cv->num_wait = 0;
cv->num_wake = 0;
cv->num_prewait = 0;
cv->closed = 0;
return (CRYPTO_CONDVAR *)cv;
}
void ossl_crypto_condvar_free(CRYPTO_CONDVAR **cv_p)
{
if (*cv_p != NULL) {
LEGACY_CONDVAR *cv = *(LEGACY_CONDVAR **)cv_p;
CloseHandle(cv->sema);
CloseHandle(cv->prewait_sema);
ossl_crypto_mutex_free(&cv->int_m);
OPENSSL_free(cv);
}
*cv_p = NULL;
}
static uint32_t obj_wait(HANDLE h, OSSL_TIME deadline)
{
DWORD timeout;
if (!determine_timeout(deadline, &timeout))
timeout = 1;
return WaitForSingleObject(h, timeout);
}
void ossl_crypto_condvar_wait_timeout(CRYPTO_CONDVAR *cv_, CRYPTO_MUTEX *ext_m,
OSSL_TIME deadline)
{
LEGACY_CONDVAR *cv = (LEGACY_CONDVAR *)cv_;
int closed, set_prewait = 0, have_orig_gen = 0;
uint32_t rc;
size_t orig_gen;
/* Admission control - prewait until we can enter our actual wait phase. */
do {
ossl_crypto_mutex_lock(cv->int_m);
closed = cv->closed;
/*
* Once prewait is over the prewait semaphore is signalled and
* num_prewait is set to 0. Use a generation counter to track if we need
* to remove a value we added to num_prewait when exiting (e.g. due to
* timeout or failure of WaitForSingleObject).
*/
if (!have_orig_gen) {
orig_gen = cv->gen;
have_orig_gen = 1;
} else if (cv->gen != orig_gen) {
set_prewait = 0;
orig_gen = cv->gen;
}
if (!closed) {
/* We can now be admitted. */
++cv->num_wait;
if (set_prewait) {
--cv->num_prewait;
set_prewait = 0;
}
} else if (!set_prewait) {
++cv->num_prewait;
set_prewait = 1;
}
ossl_crypto_mutex_unlock(cv->int_m);
if (closed)
if (obj_wait(cv->prewait_sema, deadline) != WAIT_OBJECT_0) {
/*
* If we got WAIT_OBJECT_0 we are safe - num_prewait has been
* set to 0 and the semaphore has been consumed. On the other
* hand if we timed out, there may be a residual posting that
* was made just after we timed out. However in the worst case
* this will just cause an internal spurious wakeup here in the
* future, so we do not care too much about this. We treat
* failure and timeout cases as the same, and simply exit in
* this case.
*/
ossl_crypto_mutex_lock(cv->int_m);
if (set_prewait && cv->gen == orig_gen)
--cv->num_prewait;
ossl_crypto_mutex_unlock(cv->int_m);
return;
}
} while (closed);
/*
* Unlock external mutex. Do not do this until we have been admitted, as we
* must guarantee we wake if broadcast is called at any time after ext_m is
* unlocked.
*/
ossl_crypto_mutex_unlock(ext_m);
for (;;) {
/* Wait. */
rc = obj_wait(cv->sema, deadline);
/* Reacquire internal mutex and probe state. */
ossl_crypto_mutex_lock(cv->int_m);
if (cv->num_wake > 0) {
/*
* A wake token is available, so we can wake up. Consume the token
* and get out of here. We don't care what WaitForSingleObject
* returned here (e.g. if it timed out coincidentally). In the
* latter case a signal might be left in the semaphore which causes
* a future WaitForSingleObject call to return immediately, but in
* this case we will just loop again.
*/
--cv->num_wake;
if (cv->num_wake == 0 && cv->closed) {
/*
* We consumed the last wake token, so we can now open the
* condition variable for new admissions.
*/
cv->closed = 0;
if (cv->num_prewait > 0) {
ReleaseSemaphore(cv->prewait_sema, (LONG)cv->num_prewait, NULL);
cv->num_prewait = 0;
++cv->gen;
}
}
} else if (rc == WAIT_OBJECT_0) {
/*
* We got a wakeup from the semaphore but we did not have any wake
* tokens. This ideally does not happen, but might if during a
* previous wait() call the semaphore is posted just after
* WaitForSingleObject returns due to a timeout (such that the
* num_wake > 0 case is taken above). Just spin again. (It is worth
* noting that repeated WaitForSingleObject calls is the only method
* documented for decrementing a Win32 semaphore, so this is
* basically the best possible strategy.)
*/
ossl_crypto_mutex_unlock(cv->int_m);
continue;
} else {
/*
* Assume we timed out. The WaitForSingleObject call may also have
* failed for some other reason, which we treat as a timeout.
*/
assert(cv->num_wait > 0);
--cv->num_wait;
}
break;
}
ossl_crypto_mutex_unlock(cv->int_m);
ossl_crypto_mutex_lock(ext_m);
}
void ossl_crypto_condvar_wait(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *ext_m)
{
ossl_crypto_condvar_wait_timeout(cv, ext_m, ossl_time_infinite());
}
void ossl_crypto_condvar_broadcast(CRYPTO_CONDVAR *cv_)
{
LEGACY_CONDVAR *cv = (LEGACY_CONDVAR *)cv_;
size_t num_wake;
ossl_crypto_mutex_lock(cv->int_m);
num_wake = cv->num_wait;
if (num_wake == 0) {
ossl_crypto_mutex_unlock(cv->int_m);
return;
}
cv->num_wake += num_wake;
cv->num_wait -= num_wake;
cv->closed = 1;
ossl_crypto_mutex_unlock(cv->int_m);
ReleaseSemaphore(cv->sema, num_wake, NULL);
}
void ossl_crypto_condvar_signal(CRYPTO_CONDVAR *cv_)
{
LEGACY_CONDVAR *cv = (LEGACY_CONDVAR *)cv_;
ossl_crypto_mutex_lock(cv->int_m);
if (cv->num_wait == 0) {
ossl_crypto_mutex_unlock(cv->int_m);
return;
}
/*
* We do not close the condition variable when merely signalling, as there
* are no guaranteed fairness semantics here, unlike for a broadcast.
*/
--cv->num_wait;
++cv->num_wake;
ossl_crypto_mutex_unlock(cv->int_m);
ReleaseSemaphore(cv->sema, 1, NULL);
}
# else
CRYPTO_CONDVAR *ossl_crypto_condvar_new(void)
{
CONDITION_VARIABLE *cv_p;
if ((cv_p = OPENSSL_zalloc(sizeof(*cv_p))) == NULL)
return NULL;
InitializeConditionVariable(cv_p);
return (CRYPTO_CONDVAR *)cv_p;
}
void ossl_crypto_condvar_wait(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex)
{
CONDITION_VARIABLE *cv_p;
CRITICAL_SECTION *mutex_p;
cv_p = (CONDITION_VARIABLE *)cv;
mutex_p = (CRITICAL_SECTION *)mutex;
SleepConditionVariableCS(cv_p, mutex_p, INFINITE);
}
void ossl_crypto_condvar_wait_timeout(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex,
OSSL_TIME deadline)
{
DWORD timeout;
CONDITION_VARIABLE *cv_p = (CONDITION_VARIABLE *)cv;
CRITICAL_SECTION *mutex_p = (CRITICAL_SECTION *)mutex;
if (!determine_timeout(deadline, &timeout))
timeout = 1;
SleepConditionVariableCS(cv_p, mutex_p, timeout);
}
void ossl_crypto_condvar_broadcast(CRYPTO_CONDVAR *cv)
{
CONDITION_VARIABLE *cv_p;
cv_p = (CONDITION_VARIABLE *)cv;
WakeAllConditionVariable(cv_p);
}
void ossl_crypto_condvar_signal(CRYPTO_CONDVAR *cv)
{
CONDITION_VARIABLE *cv_p;
cv_p = (CONDITION_VARIABLE *)cv;
WakeConditionVariable(cv_p);
}
void ossl_crypto_condvar_free(CRYPTO_CONDVAR **cv)
{
CONDITION_VARIABLE **cv_p;
cv_p = (CONDITION_VARIABLE **)cv;
OPENSSL_free(*cv_p);
*cv_p = NULL;
}
# endif
void ossl_crypto_mem_barrier(void)
{
MemoryBarrier();
}
#endif
|
./openssl/crypto/thread/arch/thread_none.c | /*
* Copyright 2019-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 <internal/thread_arch.h>
#if defined(OPENSSL_THREADS_NONE)
int ossl_crypto_thread_native_spawn(CRYPTO_THREAD *thread)
{
return 0;
}
int ossl_crypto_thread_native_perform_join(CRYPTO_THREAD *thread, CRYPTO_THREAD_RETVAL *retval)
{
return 0;
}
int ossl_crypto_thread_native_exit(void)
{
return 0;
}
int ossl_crypto_thread_native_is_self(CRYPTO_THREAD *thread)
{
return 0;
}
CRYPTO_MUTEX *ossl_crypto_mutex_new(void)
{
return NULL;
}
void ossl_crypto_mutex_lock(CRYPTO_MUTEX *mutex)
{
}
int ossl_crypto_mutex_try_lock(CRYPTO_MUTEX *mutex)
{
return 0;
}
void ossl_crypto_mutex_unlock(CRYPTO_MUTEX *mutex)
{
}
void ossl_crypto_mutex_free(CRYPTO_MUTEX **mutex)
{
}
CRYPTO_CONDVAR *ossl_crypto_condvar_new(void)
{
return NULL;
}
void ossl_crypto_condvar_wait(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex)
{
}
void ossl_crypto_condvar_wait_timeout(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex,
OSSL_TIME deadline)
{
}
void ossl_crypto_condvar_broadcast(CRYPTO_CONDVAR *cv)
{
}
void ossl_crypto_condvar_signal(CRYPTO_CONDVAR *cv)
{
}
void ossl_crypto_condvar_free(CRYPTO_CONDVAR **cv)
{
}
#endif
|
./openssl/crypto/thread/arch/thread_posix.c | /*
* Copyright 2019-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 <internal/thread_arch.h>
#if defined(OPENSSL_THREADS_POSIX)
# define _GNU_SOURCE
# include <errno.h>
# include <sys/types.h>
# include <unistd.h>
static void *thread_start_thunk(void *vthread)
{
CRYPTO_THREAD *thread;
CRYPTO_THREAD_RETVAL ret;
thread = (CRYPTO_THREAD *)vthread;
ret = thread->routine(thread->data);
ossl_crypto_mutex_lock(thread->statelock);
CRYPTO_THREAD_SET_STATE(thread, CRYPTO_THREAD_FINISHED);
thread->retval = ret;
ossl_crypto_condvar_broadcast(thread->condvar);
ossl_crypto_mutex_unlock(thread->statelock);
return NULL;
}
int ossl_crypto_thread_native_spawn(CRYPTO_THREAD *thread)
{
int ret;
pthread_attr_t attr;
pthread_t *handle;
handle = OPENSSL_zalloc(sizeof(*handle));
if (handle == NULL)
goto fail;
pthread_attr_init(&attr);
if (!thread->joinable)
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
ret = pthread_create(handle, &attr, thread_start_thunk, thread);
pthread_attr_destroy(&attr);
if (ret != 0)
goto fail;
thread->handle = handle;
return 1;
fail:
thread->handle = NULL;
OPENSSL_free(handle);
return 0;
}
int ossl_crypto_thread_native_perform_join(CRYPTO_THREAD *thread, CRYPTO_THREAD_RETVAL *retval)
{
void *thread_retval;
pthread_t *handle;
if (thread == NULL || thread->handle == NULL)
return 0;
handle = (pthread_t *) thread->handle;
if (pthread_join(*handle, &thread_retval) != 0)
return 0;
/*
* Join return value may be non-NULL when the thread has been cancelled,
* as indicated by thread_retval set to PTHREAD_CANCELLED.
*/
if (thread_retval != NULL)
return 0;
return 1;
}
int ossl_crypto_thread_native_exit(void)
{
pthread_exit(NULL);
return 1;
}
int ossl_crypto_thread_native_is_self(CRYPTO_THREAD *thread)
{
return pthread_equal(*(pthread_t *)thread->handle, pthread_self());
}
CRYPTO_MUTEX *ossl_crypto_mutex_new(void)
{
pthread_mutex_t *mutex;
if ((mutex = OPENSSL_zalloc(sizeof(*mutex))) == NULL)
return NULL;
if (pthread_mutex_init(mutex, NULL) != 0) {
OPENSSL_free(mutex);
return NULL;
}
return (CRYPTO_MUTEX *)mutex;
}
int ossl_crypto_mutex_try_lock(CRYPTO_MUTEX *mutex)
{
pthread_mutex_t *mutex_p;
mutex_p = (pthread_mutex_t *)mutex;
if (pthread_mutex_trylock(mutex_p) == EBUSY)
return 0;
return 1;
}
void ossl_crypto_mutex_lock(CRYPTO_MUTEX *mutex)
{
int rc;
pthread_mutex_t *mutex_p;
mutex_p = (pthread_mutex_t *)mutex;
rc = pthread_mutex_lock(mutex_p);
OPENSSL_assert(rc == 0);
}
void ossl_crypto_mutex_unlock(CRYPTO_MUTEX *mutex)
{
int rc;
pthread_mutex_t *mutex_p;
mutex_p = (pthread_mutex_t *)mutex;
rc = pthread_mutex_unlock(mutex_p);
OPENSSL_assert(rc == 0);
}
void ossl_crypto_mutex_free(CRYPTO_MUTEX **mutex)
{
pthread_mutex_t **mutex_p;
if (mutex == NULL)
return;
mutex_p = (pthread_mutex_t **)mutex;
if (*mutex_p != NULL)
pthread_mutex_destroy(*mutex_p);
OPENSSL_free(*mutex_p);
*mutex = NULL;
}
CRYPTO_CONDVAR *ossl_crypto_condvar_new(void)
{
pthread_cond_t *cv_p;
if ((cv_p = OPENSSL_zalloc(sizeof(*cv_p))) == NULL)
return NULL;
if (pthread_cond_init(cv_p, NULL) != 0) {
OPENSSL_free(cv_p);
return NULL;
}
return (CRYPTO_CONDVAR *) cv_p;
}
void ossl_crypto_condvar_wait(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex)
{
pthread_cond_t *cv_p;
pthread_mutex_t *mutex_p;
cv_p = (pthread_cond_t *)cv;
mutex_p = (pthread_mutex_t *)mutex;
pthread_cond_wait(cv_p, mutex_p);
}
void ossl_crypto_condvar_wait_timeout(CRYPTO_CONDVAR *cv, CRYPTO_MUTEX *mutex,
OSSL_TIME deadline)
{
pthread_cond_t *cv_p = (pthread_cond_t *)cv;
pthread_mutex_t *mutex_p = (pthread_mutex_t *)mutex;
if (ossl_time_is_infinite(deadline)) {
/*
* No deadline. Some pthread implementations allow
* pthread_cond_timedwait to work the same as pthread_cond_wait when
* abstime is NULL, but it is unclear whether this is POSIXly correct.
*/
pthread_cond_wait(cv_p, mutex_p);
} else {
struct timespec deadline_ts;
deadline_ts.tv_sec
= ossl_time2seconds(deadline);
deadline_ts.tv_nsec
= (ossl_time2ticks(deadline) % OSSL_TIME_SECOND) / OSSL_TIME_NS;
pthread_cond_timedwait(cv_p, mutex_p, &deadline_ts);
}
}
void ossl_crypto_condvar_broadcast(CRYPTO_CONDVAR *cv)
{
pthread_cond_t *cv_p;
cv_p = (pthread_cond_t *)cv;
pthread_cond_broadcast(cv_p);
}
void ossl_crypto_condvar_signal(CRYPTO_CONDVAR *cv)
{
pthread_cond_t *cv_p;
cv_p = (pthread_cond_t *)cv;
pthread_cond_signal(cv_p);
}
void ossl_crypto_condvar_free(CRYPTO_CONDVAR **cv)
{
pthread_cond_t **cv_p;
if (cv == NULL)
return;
cv_p = (pthread_cond_t **)cv;
if (*cv_p != NULL)
pthread_cond_destroy(*cv_p);
OPENSSL_free(*cv_p);
*cv_p = NULL;
}
#endif
|
./openssl/crypto/rc5/rc5ofb64.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
*/
/*
* RC5 low level APIs are deprecated for public use, but still ok for internal
* use.
*/
#include "internal/deprecated.h"
#include <openssl/rc5.h>
#include "rc5_local.h"
/*
* The input and output encrypted as though 64bit ofb mode is being used.
* The extra state information to record how much of the 64bit block we have
* used is contained in *num;
*/
void RC5_32_ofb64_encrypt(const unsigned char *in, unsigned char *out,
long length, RC5_32_KEY *schedule,
unsigned char *ivec, int *num)
{
register unsigned long v0, v1, t;
register int n = *num;
register long l = length;
unsigned char d[8];
register char *dp;
unsigned long ti[2];
unsigned char *iv;
int save = 0;
iv = (unsigned char *)ivec;
c2l(iv, v0);
c2l(iv, v1);
ti[0] = v0;
ti[1] = v1;
dp = (char *)d;
l2c(v0, dp);
l2c(v1, dp);
while (l--) {
if (n == 0) {
RC5_32_encrypt((unsigned long *)ti, schedule);
dp = (char *)d;
t = ti[0];
l2c(t, dp);
t = ti[1];
l2c(t, dp);
save++;
}
*(out++) = *(in++) ^ d[n];
n = (n + 1) & 0x07;
}
if (save) {
v0 = ti[0];
v1 = ti[1];
iv = (unsigned char *)ivec;
l2c(v0, iv);
l2c(v1, iv);
}
t = v0 = v1 = ti[0] = ti[1] = 0;
*num = n;
}
|
./openssl/crypto/rc5/rc5_skey.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
*/
/*
* RC5 low level APIs are deprecated for public use, but still ok for internal
* use.
*/
#include "internal/deprecated.h"
#include <openssl/rc5.h>
#include "rc5_local.h"
int RC5_32_set_key(RC5_32_KEY *key, int len, const unsigned char *data,
int rounds)
{
RC5_32_INT L[64], l, ll, A, B, *S, k;
int i, j, m, c, t, ii, jj;
if (len > 255)
return 0;
if ((rounds != RC5_16_ROUNDS) &&
(rounds != RC5_12_ROUNDS) && (rounds != RC5_8_ROUNDS))
rounds = RC5_16_ROUNDS;
key->rounds = rounds;
S = &(key->data[0]);
j = 0;
for (i = 0; i <= (len - 8); i += 8) {
c2l(data, l);
L[j++] = l;
c2l(data, l);
L[j++] = l;
}
ii = len - i;
if (ii) {
k = len & 0x07;
c2ln(data, l, ll, k);
L[j + 0] = l;
L[j + 1] = ll;
}
c = (len + 3) / 4;
t = (rounds + 1) * 2;
S[0] = RC5_32_P;
for (i = 1; i < t; i++)
S[i] = (S[i - 1] + RC5_32_Q) & RC5_32_MASK;
j = (t > c) ? t : c;
j *= 3;
ii = jj = 0;
A = B = 0;
for (i = 0; i < j; i++) {
k = (S[ii] + A + B) & RC5_32_MASK;
A = S[ii] = ROTATE_l32(k, 3);
m = (int)(A + B);
k = (L[jj] + A + B) & RC5_32_MASK;
B = L[jj] = ROTATE_l32(k, m);
if (++ii >= t)
ii = 0;
if (++jj >= c)
jj = 0;
}
return 1;
}
|
./openssl/crypto/rc5/rc5_ecb.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
*/
/*
* RC5 low level APIs are deprecated for public use, but still ok for internal
* use.
*/
#include "internal/deprecated.h"
#include <openssl/rc5.h>
#include "rc5_local.h"
#include <openssl/opensslv.h>
void RC5_32_ecb_encrypt(const unsigned char *in, unsigned char *out,
RC5_32_KEY *ks, int encrypt)
{
unsigned long l, d[2];
c2l(in, l);
d[0] = l;
c2l(in, l);
d[1] = l;
if (encrypt)
RC5_32_encrypt(d, ks);
else
RC5_32_decrypt(d, ks);
l = d[0];
l2c(l, out);
l = d[1];
l2c(l, out);
l = d[0] = d[1] = 0;
}
|
./openssl/crypto/rc5/rc5_enc.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
*/
/*
* RC5 low level APIs are deprecated for public use, but still ok for internal
* use.
*/
#include "internal/deprecated.h"
#include <stdio.h>
#include <openssl/rc5.h>
#include "rc5_local.h"
void RC5_32_cbc_encrypt(const unsigned char *in, unsigned char *out,
long length, RC5_32_KEY *ks, unsigned char *iv,
int encrypt)
{
register unsigned long tin0, tin1;
register unsigned long tout0, tout1, xor0, xor1;
register long l = length;
unsigned long tin[2];
if (encrypt) {
c2l(iv, tout0);
c2l(iv, tout1);
iv -= 8;
for (l -= 8; l >= 0; l -= 8) {
c2l(in, tin0);
c2l(in, tin1);
tin0 ^= tout0;
tin1 ^= tout1;
tin[0] = tin0;
tin[1] = tin1;
RC5_32_encrypt(tin, ks);
tout0 = tin[0];
l2c(tout0, out);
tout1 = tin[1];
l2c(tout1, out);
}
if (l != -8) {
c2ln(in, tin0, tin1, l + 8);
tin0 ^= tout0;
tin1 ^= tout1;
tin[0] = tin0;
tin[1] = tin1;
RC5_32_encrypt(tin, ks);
tout0 = tin[0];
l2c(tout0, out);
tout1 = tin[1];
l2c(tout1, out);
}
l2c(tout0, iv);
l2c(tout1, iv);
} else {
c2l(iv, xor0);
c2l(iv, xor1);
iv -= 8;
for (l -= 8; l >= 0; l -= 8) {
c2l(in, tin0);
tin[0] = tin0;
c2l(in, tin1);
tin[1] = tin1;
RC5_32_decrypt(tin, ks);
tout0 = tin[0] ^ xor0;
tout1 = tin[1] ^ xor1;
l2c(tout0, out);
l2c(tout1, out);
xor0 = tin0;
xor1 = tin1;
}
if (l != -8) {
c2l(in, tin0);
tin[0] = tin0;
c2l(in, tin1);
tin[1] = tin1;
RC5_32_decrypt(tin, ks);
tout0 = tin[0] ^ xor0;
tout1 = tin[1] ^ xor1;
l2cn(tout0, tout1, out, l + 8);
xor0 = tin0;
xor1 = tin1;
}
l2c(xor0, iv);
l2c(xor1, iv);
}
tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0;
tin[0] = tin[1] = 0;
}
void RC5_32_encrypt(unsigned long *d, RC5_32_KEY *key)
{
RC5_32_INT a, b, *s;
s = key->data;
a = d[0] + s[0];
b = d[1] + s[1];
E_RC5_32(a, b, s, 2);
E_RC5_32(a, b, s, 4);
E_RC5_32(a, b, s, 6);
E_RC5_32(a, b, s, 8);
E_RC5_32(a, b, s, 10);
E_RC5_32(a, b, s, 12);
E_RC5_32(a, b, s, 14);
E_RC5_32(a, b, s, 16);
if (key->rounds == 12) {
E_RC5_32(a, b, s, 18);
E_RC5_32(a, b, s, 20);
E_RC5_32(a, b, s, 22);
E_RC5_32(a, b, s, 24);
} else if (key->rounds == 16) {
/* Do a full expansion to avoid a jump */
E_RC5_32(a, b, s, 18);
E_RC5_32(a, b, s, 20);
E_RC5_32(a, b, s, 22);
E_RC5_32(a, b, s, 24);
E_RC5_32(a, b, s, 26);
E_RC5_32(a, b, s, 28);
E_RC5_32(a, b, s, 30);
E_RC5_32(a, b, s, 32);
}
d[0] = a;
d[1] = b;
}
void RC5_32_decrypt(unsigned long *d, RC5_32_KEY *key)
{
RC5_32_INT a, b, *s;
s = key->data;
a = d[0];
b = d[1];
if (key->rounds == 16) {
D_RC5_32(a, b, s, 32);
D_RC5_32(a, b, s, 30);
D_RC5_32(a, b, s, 28);
D_RC5_32(a, b, s, 26);
/* Do a full expansion to avoid a jump */
D_RC5_32(a, b, s, 24);
D_RC5_32(a, b, s, 22);
D_RC5_32(a, b, s, 20);
D_RC5_32(a, b, s, 18);
} else if (key->rounds == 12) {
D_RC5_32(a, b, s, 24);
D_RC5_32(a, b, s, 22);
D_RC5_32(a, b, s, 20);
D_RC5_32(a, b, s, 18);
}
D_RC5_32(a, b, s, 16);
D_RC5_32(a, b, s, 14);
D_RC5_32(a, b, s, 12);
D_RC5_32(a, b, s, 10);
D_RC5_32(a, b, s, 8);
D_RC5_32(a, b, s, 6);
D_RC5_32(a, b, s, 4);
D_RC5_32(a, b, s, 2);
d[0] = a - s[0];
d[1] = b - s[1];
}
|
./openssl/crypto/rc5/rc5cfb64.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
*/
/*
* RC5 low level APIs are deprecated for public use, but still ok for internal
* use.
*/
#include "internal/deprecated.h"
#include <openssl/rc5.h>
#include "rc5_local.h"
/*
* The input and output encrypted as though 64bit cfb mode is being used.
* The extra state information to record how much of the 64bit block we have
* used is contained in *num;
*/
void RC5_32_cfb64_encrypt(const unsigned char *in, unsigned char *out,
long length, RC5_32_KEY *schedule,
unsigned char *ivec, int *num, int encrypt)
{
register unsigned long v0, v1, t;
register int n = *num;
register long l = length;
unsigned long ti[2];
unsigned char *iv, c, cc;
iv = (unsigned char *)ivec;
if (encrypt) {
while (l--) {
if (n == 0) {
c2l(iv, v0);
ti[0] = v0;
c2l(iv, v1);
ti[1] = v1;
RC5_32_encrypt((unsigned long *)ti, schedule);
iv = (unsigned char *)ivec;
t = ti[0];
l2c(t, iv);
t = ti[1];
l2c(t, iv);
iv = (unsigned char *)ivec;
}
c = *(in++) ^ iv[n];
*(out++) = c;
iv[n] = c;
n = (n + 1) & 0x07;
}
} else {
while (l--) {
if (n == 0) {
c2l(iv, v0);
ti[0] = v0;
c2l(iv, v1);
ti[1] = v1;
RC5_32_encrypt((unsigned long *)ti, schedule);
iv = (unsigned char *)ivec;
t = ti[0];
l2c(t, iv);
t = ti[1];
l2c(t, iv);
iv = (unsigned char *)ivec;
}
cc = *(in++);
c = iv[n];
iv[n] = cc;
*(out++) = c ^ cc;
n = (n + 1) & 0x07;
}
}
v0 = v1 = ti[0] = ti[1] = t = c = cc = 0;
*num = n;
}
|
./openssl/crypto/rc5/rc5_local.h | /*
* 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 <stdlib.h>
#undef c2l
#define c2l(c,l) (l =((unsigned long)(*((c)++))) , \
l|=((unsigned long)(*((c)++)))<< 8L, \
l|=((unsigned long)(*((c)++)))<<16L, \
l|=((unsigned long)(*((c)++)))<<24L)
/* NOTE - c is not incremented as per c2l */
#undef c2ln
#define c2ln(c,l1,l2,n) { \
c+=n; \
l1=l2=0; \
switch (n) { \
case 8: l2 =((unsigned long)(*(--(c))))<<24L; \
/* fall through */ \
case 7: l2|=((unsigned long)(*(--(c))))<<16L; \
/* fall through */ \
case 6: l2|=((unsigned long)(*(--(c))))<< 8L; \
/* fall through */ \
case 5: l2|=((unsigned long)(*(--(c)))); \
/* fall through */ \
case 4: l1 =((unsigned long)(*(--(c))))<<24L; \
/* fall through */ \
case 3: l1|=((unsigned long)(*(--(c))))<<16L; \
/* fall through */ \
case 2: l1|=((unsigned long)(*(--(c))))<< 8L; \
/* fall through */ \
case 1: l1|=((unsigned long)(*(--(c)))); \
} \
}
#undef l2c
#define l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \
*((c)++)=(unsigned char)(((l)>> 8L)&0xff), \
*((c)++)=(unsigned char)(((l)>>16L)&0xff), \
*((c)++)=(unsigned char)(((l)>>24L)&0xff))
/* NOTE - c is not incremented as per l2c */
#undef l2cn
#define l2cn(l1,l2,c,n) { \
c+=n; \
switch (n) { \
case 8: *(--(c))=(unsigned char)(((l2)>>24L)&0xff); \
/* fall through */ \
case 7: *(--(c))=(unsigned char)(((l2)>>16L)&0xff); \
/* fall through */ \
case 6: *(--(c))=(unsigned char)(((l2)>> 8L)&0xff); \
/* fall through */ \
case 5: *(--(c))=(unsigned char)(((l2) )&0xff); \
/* fall through */ \
case 4: *(--(c))=(unsigned char)(((l1)>>24L)&0xff); \
/* fall through */ \
case 3: *(--(c))=(unsigned char)(((l1)>>16L)&0xff); \
/* fall through */ \
case 2: *(--(c))=(unsigned char)(((l1)>> 8L)&0xff); \
/* fall through */ \
case 1: *(--(c))=(unsigned char)(((l1) )&0xff); \
} \
}
#if (defined(OPENSSL_SYS_WIN32) && defined(_MSC_VER))
# define ROTATE_l32(a,n) _lrotl(a,n)
# define ROTATE_r32(a,n) _lrotr(a,n)
#elif defined(__ICC)
# define ROTATE_l32(a,n) _rotl(a,n)
# define ROTATE_r32(a,n) _rotr(a,n)
#elif defined(__GNUC__) && __GNUC__>=2 && !defined(__STRICT_ANSI__) && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) && !defined(PEDANTIC)
# if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)
# define ROTATE_l32(a,n) ({ register unsigned int ret; \
asm ("roll %%cl,%0" \
: "=r"(ret) \
: "c"(n),"0"((unsigned int)(a)) \
: "cc"); \
ret; \
})
# define ROTATE_r32(a,n) ({ register unsigned int ret; \
asm ("rorl %%cl,%0" \
: "=r"(ret) \
: "c"(n),"0"((unsigned int)(a)) \
: "cc"); \
ret; \
})
# endif
#endif
#ifndef ROTATE_l32
# define ROTATE_l32(a,n) (((a)<<(n&0x1f))|(((a)&0xffffffff)>>((32-n)&0x1f)))
#endif
#ifndef ROTATE_r32
# define ROTATE_r32(a,n) (((a)<<((32-n)&0x1f))|(((a)&0xffffffff)>>(n&0x1f)))
#endif
#define RC5_32_MASK 0xffffffffL
#define RC5_32_P 0xB7E15163L
#define RC5_32_Q 0x9E3779B9L
#define E_RC5_32(a,b,s,n) \
a^=b; \
a=ROTATE_l32(a,b); \
a+=s[n]; \
a&=RC5_32_MASK; \
b^=a; \
b=ROTATE_l32(b,a); \
b+=s[n+1]; \
b&=RC5_32_MASK;
#define D_RC5_32(a,b,s,n) \
b-=s[n+1]; \
b&=RC5_32_MASK; \
b=ROTATE_r32(b,a); \
b^=a; \
a-=s[n]; \
a&=RC5_32_MASK; \
a=ROTATE_r32(a,b); \
a^=b;
|
./openssl/crypto/aes/aes_local.h | /*
* Copyright 2002-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
*/
#ifndef OSSL_CRYPTO_AES_LOCAL_H
# define OSSL_CRYPTO_AES_LOCAL_H
# include <openssl/e_os2.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64))
# define SWAP(x) (_lrotl(x, 8) & 0x00ff00ff | _lrotr(x, 8) & 0xff00ff00)
# define GETU32(p) SWAP(*((u32 *)(p)))
# define PUTU32(ct, st) { *((u32 *)(ct)) = SWAP((st)); }
# else
# define GETU32(pt) (((u32)(pt)[0] << 24) ^ ((u32)(pt)[1] << 16) ^ ((u32)(pt)[2] << 8) ^ ((u32)(pt)[3]))
# define PUTU32(ct, st) { (ct)[0] = (u8)((st) >> 24); (ct)[1] = (u8)((st) >> 16); (ct)[2] = (u8)((st) >> 8); (ct)[3] = (u8)(st); }
# endif
typedef uint64_t u64;
# ifdef AES_LONG
typedef unsigned long u32;
# else
typedef unsigned int u32;
# endif
typedef unsigned short u16;
typedef unsigned char u8;
# define MAXKC (256/32)
# define MAXKB (256/8)
# define MAXNR 14
/* This controls loop-unrolling in aes_core.c */
# undef FULL_UNROLL
#endif /* !OSSL_CRYPTO_AES_LOCAL_H */
|
./openssl/crypto/aes/aes_ige.c | /*
* Copyright 2006-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
*/
/*
* AES_encrypt/AES_decrypt are deprecated - but we need to use them to implement
* these functions
*/
#include "internal/deprecated.h"
#include "internal/cryptlib.h"
#include <openssl/aes.h>
#include "aes_local.h"
/* XXX: probably some better way to do this */
#if defined(__i386__) || defined(__x86_64__)
# define UNALIGNED_MEMOPS_ARE_FAST 1
#else
# define UNALIGNED_MEMOPS_ARE_FAST 0
#endif
#define N_WORDS (AES_BLOCK_SIZE / sizeof(unsigned long))
typedef struct {
unsigned long data[N_WORDS];
#if defined(__GNUC__) && UNALIGNED_MEMOPS_ARE_FAST
} aes_block_t __attribute((__aligned__(1)));
#else
} aes_block_t;
#endif
#if UNALIGNED_MEMOPS_ARE_FAST
# define load_block(d, s) (d) = *(const aes_block_t *)(s)
# define store_block(d, s) *(aes_block_t *)(d) = (s)
#else
# define load_block(d, s) memcpy((d).data, (s), AES_BLOCK_SIZE)
# define store_block(d, s) memcpy((d), (s).data, AES_BLOCK_SIZE)
#endif
/* N.B. The IV for this mode is _twice_ the block size */
/* Use of this function is deprecated. */
void AES_ige_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, const int enc)
{
size_t n;
size_t len = length / AES_BLOCK_SIZE;
if (length == 0)
return;
OPENSSL_assert(in && out && key && ivec);
OPENSSL_assert((AES_ENCRYPT == enc) || (AES_DECRYPT == enc));
OPENSSL_assert((length % AES_BLOCK_SIZE) == 0);
if (AES_ENCRYPT == enc) {
if (in != out &&
(UNALIGNED_MEMOPS_ARE_FAST
|| ((size_t)in | (size_t)out | (size_t)ivec) % sizeof(long) ==
0)) {
aes_block_t *ivp = (aes_block_t *) ivec;
aes_block_t *iv2p = (aes_block_t *) (ivec + AES_BLOCK_SIZE);
while (len) {
aes_block_t *inp = (aes_block_t *) in;
aes_block_t *outp = (aes_block_t *) out;
for (n = 0; n < N_WORDS; ++n)
outp->data[n] = inp->data[n] ^ ivp->data[n];
AES_encrypt((unsigned char *)outp->data,
(unsigned char *)outp->data, key);
for (n = 0; n < N_WORDS; ++n)
outp->data[n] ^= iv2p->data[n];
ivp = outp;
iv2p = inp;
--len;
in += AES_BLOCK_SIZE;
out += AES_BLOCK_SIZE;
}
memcpy(ivec, ivp->data, AES_BLOCK_SIZE);
memcpy(ivec + AES_BLOCK_SIZE, iv2p->data, AES_BLOCK_SIZE);
} else {
aes_block_t tmp, tmp2;
aes_block_t iv;
aes_block_t iv2;
load_block(iv, ivec);
load_block(iv2, ivec + AES_BLOCK_SIZE);
while (len) {
load_block(tmp, in);
for (n = 0; n < N_WORDS; ++n)
tmp2.data[n] = tmp.data[n] ^ iv.data[n];
AES_encrypt((unsigned char *)tmp2.data,
(unsigned char *)tmp2.data, key);
for (n = 0; n < N_WORDS; ++n)
tmp2.data[n] ^= iv2.data[n];
store_block(out, tmp2);
iv = tmp2;
iv2 = tmp;
--len;
in += AES_BLOCK_SIZE;
out += AES_BLOCK_SIZE;
}
memcpy(ivec, iv.data, AES_BLOCK_SIZE);
memcpy(ivec + AES_BLOCK_SIZE, iv2.data, AES_BLOCK_SIZE);
}
} else {
if (in != out &&
(UNALIGNED_MEMOPS_ARE_FAST
|| ((size_t)in | (size_t)out | (size_t)ivec) % sizeof(long) ==
0)) {
aes_block_t *ivp = (aes_block_t *) ivec;
aes_block_t *iv2p = (aes_block_t *) (ivec + AES_BLOCK_SIZE);
while (len) {
aes_block_t tmp;
aes_block_t *inp = (aes_block_t *) in;
aes_block_t *outp = (aes_block_t *) out;
for (n = 0; n < N_WORDS; ++n)
tmp.data[n] = inp->data[n] ^ iv2p->data[n];
AES_decrypt((unsigned char *)tmp.data,
(unsigned char *)outp->data, key);
for (n = 0; n < N_WORDS; ++n)
outp->data[n] ^= ivp->data[n];
ivp = inp;
iv2p = outp;
--len;
in += AES_BLOCK_SIZE;
out += AES_BLOCK_SIZE;
}
memcpy(ivec, ivp->data, AES_BLOCK_SIZE);
memcpy(ivec + AES_BLOCK_SIZE, iv2p->data, AES_BLOCK_SIZE);
} else {
aes_block_t tmp, tmp2;
aes_block_t iv;
aes_block_t iv2;
load_block(iv, ivec);
load_block(iv2, ivec + AES_BLOCK_SIZE);
while (len) {
load_block(tmp, in);
tmp2 = tmp;
for (n = 0; n < N_WORDS; ++n)
tmp.data[n] ^= iv2.data[n];
AES_decrypt((unsigned char *)tmp.data,
(unsigned char *)tmp.data, key);
for (n = 0; n < N_WORDS; ++n)
tmp.data[n] ^= iv.data[n];
store_block(out, tmp);
iv = tmp2;
iv2 = tmp;
--len;
in += AES_BLOCK_SIZE;
out += AES_BLOCK_SIZE;
}
memcpy(ivec, iv.data, AES_BLOCK_SIZE);
memcpy(ivec + AES_BLOCK_SIZE, iv2.data, AES_BLOCK_SIZE);
}
}
}
/*
* Note that its effectively impossible to do biIGE in anything other
* than a single pass, so no provision is made for chaining.
*
* NB: The implementation of AES_bi_ige_encrypt has a bug. It is supposed to use
* 2 AES keys, but in fact only one is ever used. This bug has been present
* since this code was first implemented. It is believed to have minimal
* security impact in practice and has therefore not been fixed for backwards
* compatibility reasons.
*
* Use of this function is deprecated.
*/
/* N.B. The IV for this mode is _four times_ the block size */
void AES_bi_ige_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
const AES_KEY *key2, const unsigned char *ivec,
const int enc)
{
size_t n;
size_t len = length;
unsigned char tmp[AES_BLOCK_SIZE];
unsigned char tmp2[AES_BLOCK_SIZE];
unsigned char tmp3[AES_BLOCK_SIZE];
unsigned char prev[AES_BLOCK_SIZE];
const unsigned char *iv;
const unsigned char *iv2;
OPENSSL_assert(in && out && key && ivec);
OPENSSL_assert((AES_ENCRYPT == enc) || (AES_DECRYPT == enc));
OPENSSL_assert((length % AES_BLOCK_SIZE) == 0);
if (AES_ENCRYPT == enc) {
/*
* XXX: Do a separate case for when in != out (strictly should check
* for overlap, too)
*/
/* First the forward pass */
iv = ivec;
iv2 = ivec + AES_BLOCK_SIZE;
while (len >= AES_BLOCK_SIZE) {
for (n = 0; n < AES_BLOCK_SIZE; ++n)
out[n] = in[n] ^ iv[n];
AES_encrypt(out, out, key);
for (n = 0; n < AES_BLOCK_SIZE; ++n)
out[n] ^= iv2[n];
iv = out;
memcpy(prev, in, AES_BLOCK_SIZE);
iv2 = prev;
len -= AES_BLOCK_SIZE;
in += AES_BLOCK_SIZE;
out += AES_BLOCK_SIZE;
}
/* And now backwards */
iv = ivec + AES_BLOCK_SIZE * 2;
iv2 = ivec + AES_BLOCK_SIZE * 3;
len = length;
while (len >= AES_BLOCK_SIZE) {
out -= AES_BLOCK_SIZE;
/*
* XXX: reduce copies by alternating between buffers
*/
memcpy(tmp, out, AES_BLOCK_SIZE);
for (n = 0; n < AES_BLOCK_SIZE; ++n)
out[n] ^= iv[n];
/*
* hexdump(stdout, "out ^ iv", out, AES_BLOCK_SIZE);
*/
AES_encrypt(out, out, key);
/*
* hexdump(stdout,"enc", out, AES_BLOCK_SIZE);
*/
/*
* hexdump(stdout,"iv2", iv2, AES_BLOCK_SIZE);
*/
for (n = 0; n < AES_BLOCK_SIZE; ++n)
out[n] ^= iv2[n];
/*
* hexdump(stdout,"out", out, AES_BLOCK_SIZE);
*/
iv = out;
memcpy(prev, tmp, AES_BLOCK_SIZE);
iv2 = prev;
len -= AES_BLOCK_SIZE;
}
} else {
/* First backwards */
iv = ivec + AES_BLOCK_SIZE * 2;
iv2 = ivec + AES_BLOCK_SIZE * 3;
in += length;
out += length;
while (len >= AES_BLOCK_SIZE) {
in -= AES_BLOCK_SIZE;
out -= AES_BLOCK_SIZE;
memcpy(tmp, in, AES_BLOCK_SIZE);
memcpy(tmp2, in, AES_BLOCK_SIZE);
for (n = 0; n < AES_BLOCK_SIZE; ++n)
tmp[n] ^= iv2[n];
AES_decrypt(tmp, out, key);
for (n = 0; n < AES_BLOCK_SIZE; ++n)
out[n] ^= iv[n];
memcpy(tmp3, tmp2, AES_BLOCK_SIZE);
iv = tmp3;
iv2 = out;
len -= AES_BLOCK_SIZE;
}
/* And now forwards */
iv = ivec;
iv2 = ivec + AES_BLOCK_SIZE;
len = length;
while (len >= AES_BLOCK_SIZE) {
memcpy(tmp, out, AES_BLOCK_SIZE);
memcpy(tmp2, out, AES_BLOCK_SIZE);
for (n = 0; n < AES_BLOCK_SIZE; ++n)
tmp[n] ^= iv2[n];
AES_decrypt(tmp, out, key);
for (n = 0; n < AES_BLOCK_SIZE; ++n)
out[n] ^= iv[n];
memcpy(tmp3, tmp2, AES_BLOCK_SIZE);
iv = tmp3;
iv2 = out;
len -= AES_BLOCK_SIZE;
in += AES_BLOCK_SIZE;
out += AES_BLOCK_SIZE;
}
}
}
|
./openssl/crypto/aes/aes_ecb.c | /*
* Copyright 2002-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 <assert.h>
/*
* AES_encrypt/AES_decrypt are deprecated - but we need to use them to implement
* AES_ecb_encrypt
*/
#include "internal/deprecated.h"
#include <openssl/aes.h>
#include "aes_local.h"
void AES_ecb_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key, const int enc)
{
assert(in && out && key);
assert((AES_ENCRYPT == enc) || (AES_DECRYPT == enc));
if (AES_ENCRYPT == enc)
AES_encrypt(in, out, key);
else
AES_decrypt(in, out, key);
}
|
./openssl/crypto/aes/aes_cfb.c | /*
* Copyright 2002-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
*/
/*
* AES_encrypt is deprecated - but we need to use it to implement these other
* deprecated APIs.
*/
#include "internal/deprecated.h"
#include <openssl/aes.h>
#include <openssl/modes.h>
/*
* The input and output encrypted as though 128bit cfb mode is being used.
* The extra state information to record how much of the 128bit block we have
* used is contained in *num;
*/
void AES_cfb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num, const int enc)
{
CRYPTO_cfb128_encrypt(in, out, length, key, ivec, num, enc,
(block128_f) AES_encrypt);
}
/* N.B. This expects the input to be packed, MS bit first */
void AES_cfb1_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num, const int enc)
{
CRYPTO_cfb128_1_encrypt(in, out, length, key, ivec, num, enc,
(block128_f) AES_encrypt);
}
void AES_cfb8_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num, const int enc)
{
CRYPTO_cfb128_8_encrypt(in, out, length, key, ivec, num, enc,
(block128_f) AES_encrypt);
}
|
./openssl/crypto/aes/aes_misc.c | /*
* Copyright 2002-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 <openssl/opensslv.h>
#include <openssl/aes.h>
#include "aes_local.h"
#ifndef OPENSSL_NO_DEPRECATED_3_0
const char *AES_options(void)
{
# ifdef FULL_UNROLL
return "aes(full)";
# else
return "aes(partial)";
# endif
}
#endif
|
./openssl/crypto/aes/aes_wrap.c | /*
* Copyright 2008-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
*/
/*
* AES_encrypt/AES_decrypt are deprecated - but we need to use them to implement
* these functions
*/
#include "internal/deprecated.h"
#include "internal/cryptlib.h"
#include <openssl/aes.h>
#include <openssl/modes.h>
int AES_wrap_key(AES_KEY *key, const unsigned char *iv,
unsigned char *out,
const unsigned char *in, unsigned int inlen)
{
return CRYPTO_128_wrap(key, iv, out, in, inlen, (block128_f) AES_encrypt);
}
int AES_unwrap_key(AES_KEY *key, const unsigned char *iv,
unsigned char *out,
const unsigned char *in, unsigned int inlen)
{
return CRYPTO_128_unwrap(key, iv, out, in, inlen,
(block128_f) AES_decrypt);
}
|
./openssl/crypto/aes/aes_core.c | /*
* Copyright 2002-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
*/
/**
* rijndael-alg-fst.c
*
* @version 3.0 (December 2000)
*
* Optimised ANSI C code for the Rijndael cipher (now AES)
*
* @author Vincent Rijmen
* @author Antoon Bosselaers
* @author Paulo Barreto
*
* This code is hereby placed in the public domain.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''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 AUTHORS 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.
*/
/* Note: rewritten a little bit to provide error control and an OpenSSL-
compatible API */
/*
* AES low level APIs are deprecated for public use, but still ok for internal
* use where we're using them to implement the higher level EVP interface, as is
* the case here.
*/
#include "internal/deprecated.h"
#include <assert.h>
#include <stdlib.h>
#include <openssl/crypto.h>
#include <openssl/aes.h>
#include "aes_local.h"
#if defined(OPENSSL_AES_CONST_TIME) && !defined(AES_ASM)
# if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32__)
# define U64(C) C##UI64
# elif defined(__arch64__)
# define U64(C) C##UL
# else
# define U64(C) C##ULL
# endif
typedef union {
unsigned char b[8];
u32 w[2];
u64 d;
} uni;
/*
* Compute w := (w * x) mod (x^8 + x^4 + x^3 + x^1 + 1)
* Therefore the name "xtime".
*/
static void XtimeWord(u32 *w)
{
u32 a, b;
a = *w;
b = a & 0x80808080u;
a ^= b;
b -= b >> 7;
b &= 0x1B1B1B1Bu;
b ^= a << 1;
*w = b;
}
static void XtimeLong(u64 *w)
{
u64 a, b;
a = *w;
b = a & U64(0x8080808080808080);
a ^= b;
b -= b >> 7;
b &= U64(0x1B1B1B1B1B1B1B1B);
b ^= a << 1;
*w = b;
}
/*
* This computes w := S * w ^ -1 + c, where c = {01100011}.
* Instead of using GF(2^8) mod (x^8+x^4+x^3+x+1} we do the inversion
* in GF(GF(GF(2^2)^2)^2) mod (X^2+X+8)
* and GF(GF(2^2)^2) mod (X^2+X+2)
* and GF(2^2) mod (X^2+X+1)
* The first part of the algorithm below transfers the coordinates
* {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80} =>
* {1,Y,Y^2,Y^3,Y^4,Y^5,Y^6,Y^7} with Y=0x41:
* {0x01,0x41,0x66,0x6c,0x56,0x9a,0x58,0xc4}
* The last part undoes the coordinate transfer and the final affine
* transformation S:
* b[i] = b[i] + b[(i+4)%8] + b[(i+5)%8] + b[(i+6)%8] + b[(i+7)%8] + c[i]
* in one step.
* The multiplication in GF(2^2^2^2) is done in ordinary coords:
* A = (a0*1 + a1*x^4)
* B = (b0*1 + b1*x^4)
* AB = ((a0*b0 + 8*a1*b1)*1 + (a1*b0 + (a0+a1)*b1)*x^4)
* When A = (a0,a1) is given we want to solve AB = 1:
* (a) 1 = a0*b0 + 8*a1*b1
* (b) 0 = a1*b0 + (a0+a1)*b1
* => multiply (a) by a1 and (b) by a0
* (c) a1 = a1*a0*b0 + (8*a1*a1)*b1
* (d) 0 = a1*a0*b0 + (a0*a0+a1*a0)*b1
* => add (c) + (d)
* (e) a1 = (a0*a0 + a1*a0 + 8*a1*a1)*b1
* => therefore
* b1 = (a0*a0 + a1*a0 + 8*a1*a1)^-1 * a1
* => and adding (a1*b0) to (b) we get
* (f) a1*b0 = (a0+a1)*b1
* => therefore
* b0 = (a0*a0 + a1*a0 + 8*a1*a1)^-1 * (a0+a1)
* Note this formula also works for the case
* (a0+a1)*a0 + 8*a1*a1 = 0
* if the inverse element for 0^-1 is mapped to 0.
* Repeat the same for GF(2^2^2) and GF(2^2).
* We get the following algorithm:
* inv8(a0,a1):
* x0 = a0^a1
* [y0,y1] = mul4([x0,a1],[a0,a1]); (*)
* y1 = mul4(8,y1);
* t = inv4(y0^y1);
* [b0,b1] = mul4([x0,a1],[t,t]); (*)
* return [b0,b1];
* The non-linear multiplies (*) can be done in parallel at no extra cost.
*/
static void SubWord(u32 *w)
{
u32 x, y, a1, a2, a3, a4, a5, a6;
x = *w;
y = ((x & 0xFEFEFEFEu) >> 1) | ((x & 0x01010101u) << 7);
x &= 0xDDDDDDDDu;
x ^= y & 0x57575757u;
y = ((y & 0xFEFEFEFEu) >> 1) | ((y & 0x01010101u) << 7);
x ^= y & 0x1C1C1C1Cu;
y = ((y & 0xFEFEFEFEu) >> 1) | ((y & 0x01010101u) << 7);
x ^= y & 0x4A4A4A4Au;
y = ((y & 0xFEFEFEFEu) >> 1) | ((y & 0x01010101u) << 7);
x ^= y & 0x42424242u;
y = ((y & 0xFEFEFEFEu) >> 1) | ((y & 0x01010101u) << 7);
x ^= y & 0x64646464u;
y = ((y & 0xFEFEFEFEu) >> 1) | ((y & 0x01010101u) << 7);
x ^= y & 0xE0E0E0E0u;
a1 = x;
a1 ^= (x & 0xF0F0F0F0u) >> 4;
a2 = ((x & 0xCCCCCCCCu) >> 2) | ((x & 0x33333333u) << 2);
a3 = x & a1;
a3 ^= (a3 & 0xAAAAAAAAu) >> 1;
a3 ^= (((x << 1) & a1) ^ ((a1 << 1) & x)) & 0xAAAAAAAAu;
a4 = a2 & a1;
a4 ^= (a4 & 0xAAAAAAAAu) >> 1;
a4 ^= (((a2 << 1) & a1) ^ ((a1 << 1) & a2)) & 0xAAAAAAAAu;
a5 = (a3 & 0xCCCCCCCCu) >> 2;
a3 ^= ((a4 << 2) ^ a4) & 0xCCCCCCCCu;
a4 = a5 & 0x22222222u;
a4 |= a4 >> 1;
a4 ^= (a5 << 1) & 0x22222222u;
a3 ^= a4;
a5 = a3 & 0xA0A0A0A0u;
a5 |= a5 >> 1;
a5 ^= (a3 << 1) & 0xA0A0A0A0u;
a4 = a5 & 0xC0C0C0C0u;
a6 = a4 >> 2;
a4 ^= (a5 << 2) & 0xC0C0C0C0u;
a5 = a6 & 0x20202020u;
a5 |= a5 >> 1;
a5 ^= (a6 << 1) & 0x20202020u;
a4 |= a5;
a3 ^= a4 >> 4;
a3 &= 0x0F0F0F0Fu;
a2 = a3;
a2 ^= (a3 & 0x0C0C0C0Cu) >> 2;
a4 = a3 & a2;
a4 ^= (a4 & 0x0A0A0A0A0Au) >> 1;
a4 ^= (((a3 << 1) & a2) ^ ((a2 << 1) & a3)) & 0x0A0A0A0Au;
a5 = a4 & 0x08080808u;
a5 |= a5 >> 1;
a5 ^= (a4 << 1) & 0x08080808u;
a4 ^= a5 >> 2;
a4 &= 0x03030303u;
a4 ^= (a4 & 0x02020202u) >> 1;
a4 |= a4 << 2;
a3 = a2 & a4;
a3 ^= (a3 & 0x0A0A0A0Au) >> 1;
a3 ^= (((a2 << 1) & a4) ^ ((a4 << 1) & a2)) & 0x0A0A0A0Au;
a3 |= a3 << 4;
a2 = ((a1 & 0xCCCCCCCCu) >> 2) | ((a1 & 0x33333333u) << 2);
x = a1 & a3;
x ^= (x & 0xAAAAAAAAu) >> 1;
x ^= (((a1 << 1) & a3) ^ ((a3 << 1) & a1)) & 0xAAAAAAAAu;
a4 = a2 & a3;
a4 ^= (a4 & 0xAAAAAAAAu) >> 1;
a4 ^= (((a2 << 1) & a3) ^ ((a3 << 1) & a2)) & 0xAAAAAAAAu;
a5 = (x & 0xCCCCCCCCu) >> 2;
x ^= ((a4 << 2) ^ a4) & 0xCCCCCCCCu;
a4 = a5 & 0x22222222u;
a4 |= a4 >> 1;
a4 ^= (a5 << 1) & 0x22222222u;
x ^= a4;
y = ((x & 0xFEFEFEFEu) >> 1) | ((x & 0x01010101u) << 7);
x &= 0x39393939u;
x ^= y & 0x3F3F3F3Fu;
y = ((y & 0xFCFCFCFCu) >> 2) | ((y & 0x03030303u) << 6);
x ^= y & 0x97979797u;
y = ((y & 0xFEFEFEFEu) >> 1) | ((y & 0x01010101u) << 7);
x ^= y & 0x9B9B9B9Bu;
y = ((y & 0xFEFEFEFEu) >> 1) | ((y & 0x01010101u) << 7);
x ^= y & 0x3C3C3C3Cu;
y = ((y & 0xFEFEFEFEu) >> 1) | ((y & 0x01010101u) << 7);
x ^= y & 0xDDDDDDDDu;
y = ((y & 0xFEFEFEFEu) >> 1) | ((y & 0x01010101u) << 7);
x ^= y & 0x72727272u;
x ^= 0x63636363u;
*w = x;
}
static void SubLong(u64 *w)
{
u64 x, y, a1, a2, a3, a4, a5, a6;
x = *w;
y = ((x & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((x & U64(0x0101010101010101)) << 7);
x &= U64(0xDDDDDDDDDDDDDDDD);
x ^= y & U64(0x5757575757575757);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x1C1C1C1C1C1C1C1C);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x4A4A4A4A4A4A4A4A);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x4242424242424242);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x6464646464646464);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0xE0E0E0E0E0E0E0E0);
a1 = x;
a1 ^= (x & U64(0xF0F0F0F0F0F0F0F0)) >> 4;
a2 = ((x & U64(0xCCCCCCCCCCCCCCCC)) >> 2) | ((x & U64(0x3333333333333333)) << 2);
a3 = x & a1;
a3 ^= (a3 & U64(0xAAAAAAAAAAAAAAAA)) >> 1;
a3 ^= (((x << 1) & a1) ^ ((a1 << 1) & x)) & U64(0xAAAAAAAAAAAAAAAA);
a4 = a2 & a1;
a4 ^= (a4 & U64(0xAAAAAAAAAAAAAAAA)) >> 1;
a4 ^= (((a2 << 1) & a1) ^ ((a1 << 1) & a2)) & U64(0xAAAAAAAAAAAAAAAA);
a5 = (a3 & U64(0xCCCCCCCCCCCCCCCC)) >> 2;
a3 ^= ((a4 << 2) ^ a4) & U64(0xCCCCCCCCCCCCCCCC);
a4 = a5 & U64(0x2222222222222222);
a4 |= a4 >> 1;
a4 ^= (a5 << 1) & U64(0x2222222222222222);
a3 ^= a4;
a5 = a3 & U64(0xA0A0A0A0A0A0A0A0);
a5 |= a5 >> 1;
a5 ^= (a3 << 1) & U64(0xA0A0A0A0A0A0A0A0);
a4 = a5 & U64(0xC0C0C0C0C0C0C0C0);
a6 = a4 >> 2;
a4 ^= (a5 << 2) & U64(0xC0C0C0C0C0C0C0C0);
a5 = a6 & U64(0x2020202020202020);
a5 |= a5 >> 1;
a5 ^= (a6 << 1) & U64(0x2020202020202020);
a4 |= a5;
a3 ^= a4 >> 4;
a3 &= U64(0x0F0F0F0F0F0F0F0F);
a2 = a3;
a2 ^= (a3 & U64(0x0C0C0C0C0C0C0C0C)) >> 2;
a4 = a3 & a2;
a4 ^= (a4 & U64(0x0A0A0A0A0A0A0A0A)) >> 1;
a4 ^= (((a3 << 1) & a2) ^ ((a2 << 1) & a3)) & U64(0x0A0A0A0A0A0A0A0A);
a5 = a4 & U64(0x0808080808080808);
a5 |= a5 >> 1;
a5 ^= (a4 << 1) & U64(0x0808080808080808);
a4 ^= a5 >> 2;
a4 &= U64(0x0303030303030303);
a4 ^= (a4 & U64(0x0202020202020202)) >> 1;
a4 |= a4 << 2;
a3 = a2 & a4;
a3 ^= (a3 & U64(0x0A0A0A0A0A0A0A0A)) >> 1;
a3 ^= (((a2 << 1) & a4) ^ ((a4 << 1) & a2)) & U64(0x0A0A0A0A0A0A0A0A);
a3 |= a3 << 4;
a2 = ((a1 & U64(0xCCCCCCCCCCCCCCCC)) >> 2) | ((a1 & U64(0x3333333333333333)) << 2);
x = a1 & a3;
x ^= (x & U64(0xAAAAAAAAAAAAAAAA)) >> 1;
x ^= (((a1 << 1) & a3) ^ ((a3 << 1) & a1)) & U64(0xAAAAAAAAAAAAAAAA);
a4 = a2 & a3;
a4 ^= (a4 & U64(0xAAAAAAAAAAAAAAAA)) >> 1;
a4 ^= (((a2 << 1) & a3) ^ ((a3 << 1) & a2)) & U64(0xAAAAAAAAAAAAAAAA);
a5 = (x & U64(0xCCCCCCCCCCCCCCCC)) >> 2;
x ^= ((a4 << 2) ^ a4) & U64(0xCCCCCCCCCCCCCCCC);
a4 = a5 & U64(0x2222222222222222);
a4 |= a4 >> 1;
a4 ^= (a5 << 1) & U64(0x2222222222222222);
x ^= a4;
y = ((x & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((x & U64(0x0101010101010101)) << 7);
x &= U64(0x3939393939393939);
x ^= y & U64(0x3F3F3F3F3F3F3F3F);
y = ((y & U64(0xFCFCFCFCFCFCFCFC)) >> 2) | ((y & U64(0x0303030303030303)) << 6);
x ^= y & U64(0x9797979797979797);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x9B9B9B9B9B9B9B9B);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x3C3C3C3C3C3C3C3C);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0xDDDDDDDDDDDDDDDD);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x7272727272727272);
x ^= U64(0x6363636363636363);
*w = x;
}
/*
* This computes w := (S^-1 * (w + c))^-1
*/
static void InvSubLong(u64 *w)
{
u64 x, y, a1, a2, a3, a4, a5, a6;
x = *w;
x ^= U64(0x6363636363636363);
y = ((x & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((x & U64(0x0101010101010101)) << 7);
x &= U64(0xFDFDFDFDFDFDFDFD);
x ^= y & U64(0x5E5E5E5E5E5E5E5E);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0xF3F3F3F3F3F3F3F3);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0xF5F5F5F5F5F5F5F5);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x7878787878787878);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x7777777777777777);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x1515151515151515);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0xA5A5A5A5A5A5A5A5);
a1 = x;
a1 ^= (x & U64(0xF0F0F0F0F0F0F0F0)) >> 4;
a2 = ((x & U64(0xCCCCCCCCCCCCCCCC)) >> 2) | ((x & U64(0x3333333333333333)) << 2);
a3 = x & a1;
a3 ^= (a3 & U64(0xAAAAAAAAAAAAAAAA)) >> 1;
a3 ^= (((x << 1) & a1) ^ ((a1 << 1) & x)) & U64(0xAAAAAAAAAAAAAAAA);
a4 = a2 & a1;
a4 ^= (a4 & U64(0xAAAAAAAAAAAAAAAA)) >> 1;
a4 ^= (((a2 << 1) & a1) ^ ((a1 << 1) & a2)) & U64(0xAAAAAAAAAAAAAAAA);
a5 = (a3 & U64(0xCCCCCCCCCCCCCCCC)) >> 2;
a3 ^= ((a4 << 2) ^ a4) & U64(0xCCCCCCCCCCCCCCCC);
a4 = a5 & U64(0x2222222222222222);
a4 |= a4 >> 1;
a4 ^= (a5 << 1) & U64(0x2222222222222222);
a3 ^= a4;
a5 = a3 & U64(0xA0A0A0A0A0A0A0A0);
a5 |= a5 >> 1;
a5 ^= (a3 << 1) & U64(0xA0A0A0A0A0A0A0A0);
a4 = a5 & U64(0xC0C0C0C0C0C0C0C0);
a6 = a4 >> 2;
a4 ^= (a5 << 2) & U64(0xC0C0C0C0C0C0C0C0);
a5 = a6 & U64(0x2020202020202020);
a5 |= a5 >> 1;
a5 ^= (a6 << 1) & U64(0x2020202020202020);
a4 |= a5;
a3 ^= a4 >> 4;
a3 &= U64(0x0F0F0F0F0F0F0F0F);
a2 = a3;
a2 ^= (a3 & U64(0x0C0C0C0C0C0C0C0C)) >> 2;
a4 = a3 & a2;
a4 ^= (a4 & U64(0x0A0A0A0A0A0A0A0A)) >> 1;
a4 ^= (((a3 << 1) & a2) ^ ((a2 << 1) & a3)) & U64(0x0A0A0A0A0A0A0A0A);
a5 = a4 & U64(0x0808080808080808);
a5 |= a5 >> 1;
a5 ^= (a4 << 1) & U64(0x0808080808080808);
a4 ^= a5 >> 2;
a4 &= U64(0x0303030303030303);
a4 ^= (a4 & U64(0x0202020202020202)) >> 1;
a4 |= a4 << 2;
a3 = a2 & a4;
a3 ^= (a3 & U64(0x0A0A0A0A0A0A0A0A)) >> 1;
a3 ^= (((a2 << 1) & a4) ^ ((a4 << 1) & a2)) & U64(0x0A0A0A0A0A0A0A0A);
a3 |= a3 << 4;
a2 = ((a1 & U64(0xCCCCCCCCCCCCCCCC)) >> 2) | ((a1 & U64(0x3333333333333333)) << 2);
x = a1 & a3;
x ^= (x & U64(0xAAAAAAAAAAAAAAAA)) >> 1;
x ^= (((a1 << 1) & a3) ^ ((a3 << 1) & a1)) & U64(0xAAAAAAAAAAAAAAAA);
a4 = a2 & a3;
a4 ^= (a4 & U64(0xAAAAAAAAAAAAAAAA)) >> 1;
a4 ^= (((a2 << 1) & a3) ^ ((a3 << 1) & a2)) & U64(0xAAAAAAAAAAAAAAAA);
a5 = (x & U64(0xCCCCCCCCCCCCCCCC)) >> 2;
x ^= ((a4 << 2) ^ a4) & U64(0xCCCCCCCCCCCCCCCC);
a4 = a5 & U64(0x2222222222222222);
a4 |= a4 >> 1;
a4 ^= (a5 << 1) & U64(0x2222222222222222);
x ^= a4;
y = ((x & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((x & U64(0x0101010101010101)) << 7);
x &= U64(0xB5B5B5B5B5B5B5B5);
x ^= y & U64(0x4040404040404040);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x8080808080808080);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x1616161616161616);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0xEBEBEBEBEBEBEBEB);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x9797979797979797);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0xFBFBFBFBFBFBFBFB);
y = ((y & U64(0xFEFEFEFEFEFEFEFE)) >> 1) | ((y & U64(0x0101010101010101)) << 7);
x ^= y & U64(0x7D7D7D7D7D7D7D7D);
*w = x;
}
static void ShiftRows(u64 *state)
{
unsigned char s[4];
unsigned char *s0;
int r;
s0 = (unsigned char *)state;
for (r = 0; r < 4; r++) {
s[0] = s0[0*4 + r];
s[1] = s0[1*4 + r];
s[2] = s0[2*4 + r];
s[3] = s0[3*4 + r];
s0[0*4 + r] = s[(r+0) % 4];
s0[1*4 + r] = s[(r+1) % 4];
s0[2*4 + r] = s[(r+2) % 4];
s0[3*4 + r] = s[(r+3) % 4];
}
}
static void InvShiftRows(u64 *state)
{
unsigned char s[4];
unsigned char *s0;
int r;
s0 = (unsigned char *)state;
for (r = 0; r < 4; r++) {
s[0] = s0[0*4 + r];
s[1] = s0[1*4 + r];
s[2] = s0[2*4 + r];
s[3] = s0[3*4 + r];
s0[0*4 + r] = s[(4-r) % 4];
s0[1*4 + r] = s[(5-r) % 4];
s0[2*4 + r] = s[(6-r) % 4];
s0[3*4 + r] = s[(7-r) % 4];
}
}
static void MixColumns(u64 *state)
{
uni s1;
uni s;
int c;
for (c = 0; c < 2; c++) {
s1.d = state[c];
s.d = s1.d;
s.d ^= ((s.d & U64(0xFFFF0000FFFF0000)) >> 16)
| ((s.d & U64(0x0000FFFF0000FFFF)) << 16);
s.d ^= ((s.d & U64(0xFF00FF00FF00FF00)) >> 8)
| ((s.d & U64(0x00FF00FF00FF00FF)) << 8);
s.d ^= s1.d;
XtimeLong(&s1.d);
s.d ^= s1.d;
s.b[0] ^= s1.b[1];
s.b[1] ^= s1.b[2];
s.b[2] ^= s1.b[3];
s.b[3] ^= s1.b[0];
s.b[4] ^= s1.b[5];
s.b[5] ^= s1.b[6];
s.b[6] ^= s1.b[7];
s.b[7] ^= s1.b[4];
state[c] = s.d;
}
}
static void InvMixColumns(u64 *state)
{
uni s1;
uni s;
int c;
for (c = 0; c < 2; c++) {
s1.d = state[c];
s.d = s1.d;
s.d ^= ((s.d & U64(0xFFFF0000FFFF0000)) >> 16)
| ((s.d & U64(0x0000FFFF0000FFFF)) << 16);
s.d ^= ((s.d & U64(0xFF00FF00FF00FF00)) >> 8)
| ((s.d & U64(0x00FF00FF00FF00FF)) << 8);
s.d ^= s1.d;
XtimeLong(&s1.d);
s.d ^= s1.d;
s.b[0] ^= s1.b[1];
s.b[1] ^= s1.b[2];
s.b[2] ^= s1.b[3];
s.b[3] ^= s1.b[0];
s.b[4] ^= s1.b[5];
s.b[5] ^= s1.b[6];
s.b[6] ^= s1.b[7];
s.b[7] ^= s1.b[4];
XtimeLong(&s1.d);
s1.d ^= ((s1.d & U64(0xFFFF0000FFFF0000)) >> 16)
| ((s1.d & U64(0x0000FFFF0000FFFF)) << 16);
s.d ^= s1.d;
XtimeLong(&s1.d);
s1.d ^= ((s1.d & U64(0xFF00FF00FF00FF00)) >> 8)
| ((s1.d & U64(0x00FF00FF00FF00FF)) << 8);
s.d ^= s1.d;
state[c] = s.d;
}
}
static void AddRoundKey(u64 *state, const u64 *w)
{
state[0] ^= w[0];
state[1] ^= w[1];
}
static void Cipher(const unsigned char *in, unsigned char *out,
const u64 *w, int nr)
{
u64 state[2];
int i;
memcpy(state, in, 16);
AddRoundKey(state, w);
for (i = 1; i < nr; i++) {
SubLong(&state[0]);
SubLong(&state[1]);
ShiftRows(state);
MixColumns(state);
AddRoundKey(state, w + i*2);
}
SubLong(&state[0]);
SubLong(&state[1]);
ShiftRows(state);
AddRoundKey(state, w + nr*2);
memcpy(out, state, 16);
}
static void InvCipher(const unsigned char *in, unsigned char *out,
const u64 *w, int nr)
{
u64 state[2];
int i;
memcpy(state, in, 16);
AddRoundKey(state, w + nr*2);
for (i = nr - 1; i > 0; i--) {
InvShiftRows(state);
InvSubLong(&state[0]);
InvSubLong(&state[1]);
AddRoundKey(state, w + i*2);
InvMixColumns(state);
}
InvShiftRows(state);
InvSubLong(&state[0]);
InvSubLong(&state[1]);
AddRoundKey(state, w);
memcpy(out, state, 16);
}
static void RotWord(u32 *x)
{
unsigned char *w0;
unsigned char tmp;
w0 = (unsigned char *)x;
tmp = w0[0];
w0[0] = w0[1];
w0[1] = w0[2];
w0[2] = w0[3];
w0[3] = tmp;
}
static void KeyExpansion(const unsigned char *key, u64 *w,
int nr, int nk)
{
u32 rcon;
uni prev;
u32 temp;
int i, n;
memcpy(w, key, nk*4);
memcpy(&rcon, "\1\0\0\0", 4);
n = nk/2;
prev.d = w[n-1];
for (i = n; i < (nr+1)*2; i++) {
temp = prev.w[1];
if (i % n == 0) {
RotWord(&temp);
SubWord(&temp);
temp ^= rcon;
XtimeWord(&rcon);
} else if (nk > 6 && i % n == 2) {
SubWord(&temp);
}
prev.d = w[i-n];
prev.w[0] ^= temp;
prev.w[1] ^= prev.w[0];
w[i] = prev.d;
}
}
/**
* Expand the cipher key into the encryption key schedule.
*/
int AES_set_encrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key)
{
u64 *rk;
if (!userKey || !key)
return -1;
if (bits != 128 && bits != 192 && bits != 256)
return -2;
rk = (u64*)key->rd_key;
if (bits == 128)
key->rounds = 10;
else if (bits == 192)
key->rounds = 12;
else
key->rounds = 14;
KeyExpansion(userKey, rk, key->rounds, bits/32);
return 0;
}
/**
* Expand the cipher key into the decryption key schedule.
*/
int AES_set_decrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key)
{
return AES_set_encrypt_key(userKey, bits, key);
}
/*
* Encrypt a single block
* in and out can overlap
*/
void AES_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key)
{
const u64 *rk;
assert(in && out && key);
rk = (u64*)key->rd_key;
Cipher(in, out, rk, key->rounds);
}
/*
* Decrypt a single block
* in and out can overlap
*/
void AES_decrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key)
{
const u64 *rk;
assert(in && out && key);
rk = (u64*)key->rd_key;
InvCipher(in, out, rk, key->rounds);
}
#elif !defined(AES_ASM)
/*-
Te0[x] = S [x].[02, 01, 01, 03];
Te1[x] = S [x].[03, 02, 01, 01];
Te2[x] = S [x].[01, 03, 02, 01];
Te3[x] = S [x].[01, 01, 03, 02];
Td0[x] = Si[x].[0e, 09, 0d, 0b];
Td1[x] = Si[x].[0b, 0e, 09, 0d];
Td2[x] = Si[x].[0d, 0b, 0e, 09];
Td3[x] = Si[x].[09, 0d, 0b, 0e];
Td4[x] = Si[x].[01];
*/
static const u32 Te0[256] = {
0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU,
0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U,
0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU,
0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU,
0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U,
0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU,
0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU,
0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU,
0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU,
0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU,
0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U,
0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU,
0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU,
0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U,
0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU,
0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU,
0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU,
0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU,
0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU,
0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U,
0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU,
0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU,
0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU,
0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU,
0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U,
0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U,
0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U,
0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U,
0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU,
0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U,
0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U,
0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU,
0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU,
0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U,
0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U,
0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U,
0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU,
0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U,
0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU,
0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U,
0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU,
0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U,
0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U,
0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU,
0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U,
0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U,
0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U,
0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U,
0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U,
0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U,
0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U,
0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U,
0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU,
0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U,
0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U,
0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U,
0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U,
0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U,
0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U,
0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU,
0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U,
0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U,
0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U,
0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU,
};
static const u32 Te1[256] = {
0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU,
0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U,
0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU,
0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U,
0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU,
0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U,
0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU,
0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U,
0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U,
0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU,
0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U,
0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U,
0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U,
0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU,
0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U,
0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U,
0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU,
0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U,
0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U,
0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U,
0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU,
0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU,
0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U,
0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU,
0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU,
0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U,
0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU,
0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U,
0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU,
0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U,
0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U,
0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U,
0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU,
0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U,
0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU,
0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U,
0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU,
0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U,
0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U,
0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU,
0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU,
0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU,
0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U,
0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U,
0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU,
0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U,
0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU,
0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U,
0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU,
0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U,
0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU,
0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU,
0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U,
0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU,
0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U,
0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU,
0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U,
0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U,
0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U,
0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU,
0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU,
0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U,
0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU,
0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U,
};
static const u32 Te2[256] = {
0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU,
0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U,
0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU,
0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U,
0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU,
0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U,
0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU,
0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U,
0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U,
0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU,
0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U,
0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U,
0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U,
0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU,
0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U,
0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U,
0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU,
0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U,
0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U,
0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U,
0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU,
0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU,
0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U,
0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU,
0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU,
0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U,
0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU,
0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U,
0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU,
0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U,
0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U,
0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U,
0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU,
0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U,
0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU,
0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U,
0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU,
0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U,
0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U,
0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU,
0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU,
0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU,
0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U,
0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U,
0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU,
0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U,
0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU,
0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U,
0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU,
0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U,
0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU,
0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU,
0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U,
0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU,
0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U,
0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU,
0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U,
0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U,
0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U,
0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU,
0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU,
0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U,
0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU,
0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U,
};
static const u32 Te3[256] = {
0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U,
0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U,
0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U,
0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU,
0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU,
0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU,
0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U,
0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU,
0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU,
0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U,
0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U,
0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU,
0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU,
0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU,
0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU,
0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU,
0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U,
0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU,
0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU,
0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U,
0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U,
0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U,
0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U,
0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U,
0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU,
0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U,
0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU,
0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU,
0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U,
0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U,
0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U,
0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU,
0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U,
0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU,
0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU,
0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U,
0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U,
0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU,
0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U,
0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU,
0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U,
0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U,
0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U,
0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U,
0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU,
0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U,
0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU,
0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U,
0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU,
0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U,
0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU,
0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU,
0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU,
0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU,
0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U,
0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U,
0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U,
0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U,
0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U,
0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U,
0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU,
0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U,
0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU,
0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU,
};
static const u32 Td0[256] = {
0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U,
0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U,
0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U,
0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU,
0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U,
0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U,
0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU,
0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U,
0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU,
0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U,
0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U,
0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U,
0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U,
0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU,
0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U,
0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU,
0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U,
0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU,
0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U,
0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U,
0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U,
0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU,
0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U,
0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU,
0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U,
0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU,
0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U,
0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU,
0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU,
0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U,
0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU,
0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U,
0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU,
0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U,
0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U,
0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U,
0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU,
0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U,
0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U,
0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU,
0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U,
0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U,
0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U,
0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U,
0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U,
0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU,
0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U,
0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U,
0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U,
0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U,
0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U,
0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU,
0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU,
0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU,
0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU,
0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U,
0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U,
0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU,
0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU,
0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U,
0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU,
0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U,
0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U,
0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U,
};
static const u32 Td1[256] = {
0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU,
0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U,
0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU,
0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U,
0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U,
0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U,
0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U,
0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U,
0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U,
0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU,
0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU,
0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU,
0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U,
0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU,
0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U,
0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U,
0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U,
0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU,
0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU,
0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U,
0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU,
0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U,
0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU,
0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU,
0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U,
0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U,
0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U,
0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU,
0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U,
0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU,
0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U,
0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U,
0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U,
0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU,
0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U,
0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U,
0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U,
0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U,
0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U,
0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U,
0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU,
0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU,
0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U,
0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU,
0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U,
0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU,
0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU,
0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U,
0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU,
0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U,
0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U,
0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U,
0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U,
0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U,
0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U,
0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U,
0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU,
0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U,
0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U,
0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU,
0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U,
0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U,
0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U,
0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U,
};
static const u32 Td2[256] = {
0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U,
0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U,
0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U,
0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U,
0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU,
0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U,
0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U,
0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U,
0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U,
0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU,
0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U,
0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U,
0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU,
0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U,
0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U,
0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U,
0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U,
0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U,
0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U,
0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU,
0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U,
0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U,
0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U,
0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U,
0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U,
0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU,
0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU,
0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U,
0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU,
0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U,
0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU,
0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU,
0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU,
0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU,
0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U,
0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U,
0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U,
0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U,
0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U,
0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U,
0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U,
0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU,
0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU,
0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U,
0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U,
0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU,
0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU,
0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U,
0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U,
0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U,
0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U,
0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U,
0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U,
0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U,
0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU,
0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U,
0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U,
0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U,
0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U,
0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U,
0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U,
0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU,
0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U,
0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U,
};
static const u32 Td3[256] = {
0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU,
0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU,
0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U,
0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U,
0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU,
0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU,
0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U,
0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU,
0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U,
0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU,
0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U,
0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U,
0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U,
0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U,
0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U,
0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU,
0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU,
0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U,
0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U,
0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU,
0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU,
0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U,
0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U,
0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U,
0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U,
0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU,
0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U,
0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U,
0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU,
0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU,
0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U,
0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U,
0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U,
0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU,
0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U,
0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U,
0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U,
0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U,
0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U,
0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U,
0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U,
0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU,
0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U,
0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U,
0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU,
0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU,
0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U,
0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU,
0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U,
0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U,
0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U,
0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U,
0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U,
0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U,
0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU,
0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU,
0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU,
0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU,
0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U,
0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U,
0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U,
0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU,
0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U,
0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U,
};
static const u8 Td4[256] = {
0x52U, 0x09U, 0x6aU, 0xd5U, 0x30U, 0x36U, 0xa5U, 0x38U,
0xbfU, 0x40U, 0xa3U, 0x9eU, 0x81U, 0xf3U, 0xd7U, 0xfbU,
0x7cU, 0xe3U, 0x39U, 0x82U, 0x9bU, 0x2fU, 0xffU, 0x87U,
0x34U, 0x8eU, 0x43U, 0x44U, 0xc4U, 0xdeU, 0xe9U, 0xcbU,
0x54U, 0x7bU, 0x94U, 0x32U, 0xa6U, 0xc2U, 0x23U, 0x3dU,
0xeeU, 0x4cU, 0x95U, 0x0bU, 0x42U, 0xfaU, 0xc3U, 0x4eU,
0x08U, 0x2eU, 0xa1U, 0x66U, 0x28U, 0xd9U, 0x24U, 0xb2U,
0x76U, 0x5bU, 0xa2U, 0x49U, 0x6dU, 0x8bU, 0xd1U, 0x25U,
0x72U, 0xf8U, 0xf6U, 0x64U, 0x86U, 0x68U, 0x98U, 0x16U,
0xd4U, 0xa4U, 0x5cU, 0xccU, 0x5dU, 0x65U, 0xb6U, 0x92U,
0x6cU, 0x70U, 0x48U, 0x50U, 0xfdU, 0xedU, 0xb9U, 0xdaU,
0x5eU, 0x15U, 0x46U, 0x57U, 0xa7U, 0x8dU, 0x9dU, 0x84U,
0x90U, 0xd8U, 0xabU, 0x00U, 0x8cU, 0xbcU, 0xd3U, 0x0aU,
0xf7U, 0xe4U, 0x58U, 0x05U, 0xb8U, 0xb3U, 0x45U, 0x06U,
0xd0U, 0x2cU, 0x1eU, 0x8fU, 0xcaU, 0x3fU, 0x0fU, 0x02U,
0xc1U, 0xafU, 0xbdU, 0x03U, 0x01U, 0x13U, 0x8aU, 0x6bU,
0x3aU, 0x91U, 0x11U, 0x41U, 0x4fU, 0x67U, 0xdcU, 0xeaU,
0x97U, 0xf2U, 0xcfU, 0xceU, 0xf0U, 0xb4U, 0xe6U, 0x73U,
0x96U, 0xacU, 0x74U, 0x22U, 0xe7U, 0xadU, 0x35U, 0x85U,
0xe2U, 0xf9U, 0x37U, 0xe8U, 0x1cU, 0x75U, 0xdfU, 0x6eU,
0x47U, 0xf1U, 0x1aU, 0x71U, 0x1dU, 0x29U, 0xc5U, 0x89U,
0x6fU, 0xb7U, 0x62U, 0x0eU, 0xaaU, 0x18U, 0xbeU, 0x1bU,
0xfcU, 0x56U, 0x3eU, 0x4bU, 0xc6U, 0xd2U, 0x79U, 0x20U,
0x9aU, 0xdbU, 0xc0U, 0xfeU, 0x78U, 0xcdU, 0x5aU, 0xf4U,
0x1fU, 0xddU, 0xa8U, 0x33U, 0x88U, 0x07U, 0xc7U, 0x31U,
0xb1U, 0x12U, 0x10U, 0x59U, 0x27U, 0x80U, 0xecU, 0x5fU,
0x60U, 0x51U, 0x7fU, 0xa9U, 0x19U, 0xb5U, 0x4aU, 0x0dU,
0x2dU, 0xe5U, 0x7aU, 0x9fU, 0x93U, 0xc9U, 0x9cU, 0xefU,
0xa0U, 0xe0U, 0x3bU, 0x4dU, 0xaeU, 0x2aU, 0xf5U, 0xb0U,
0xc8U, 0xebU, 0xbbU, 0x3cU, 0x83U, 0x53U, 0x99U, 0x61U,
0x17U, 0x2bU, 0x04U, 0x7eU, 0xbaU, 0x77U, 0xd6U, 0x26U,
0xe1U, 0x69U, 0x14U, 0x63U, 0x55U, 0x21U, 0x0cU, 0x7dU,
};
static const u32 rcon[] = {
0x01000000, 0x02000000, 0x04000000, 0x08000000,
0x10000000, 0x20000000, 0x40000000, 0x80000000,
0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */
};
/**
* Expand the cipher key into the encryption key schedule.
*/
int AES_set_encrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key)
{
u32 *rk;
int i = 0;
u32 temp;
if (!userKey || !key)
return -1;
if (bits != 128 && bits != 192 && bits != 256)
return -2;
rk = key->rd_key;
if (bits == 128)
key->rounds = 10;
else if (bits == 192)
key->rounds = 12;
else
key->rounds = 14;
rk[0] = GETU32(userKey );
rk[1] = GETU32(userKey + 4);
rk[2] = GETU32(userKey + 8);
rk[3] = GETU32(userKey + 12);
if (bits == 128) {
while (1) {
temp = rk[3];
rk[4] = rk[0] ^
(Te2[(temp >> 16) & 0xff] & 0xff000000) ^
(Te3[(temp >> 8) & 0xff] & 0x00ff0000) ^
(Te0[(temp ) & 0xff] & 0x0000ff00) ^
(Te1[(temp >> 24) ] & 0x000000ff) ^
rcon[i];
rk[5] = rk[1] ^ rk[4];
rk[6] = rk[2] ^ rk[5];
rk[7] = rk[3] ^ rk[6];
if (++i == 10) {
return 0;
}
rk += 4;
}
}
rk[4] = GETU32(userKey + 16);
rk[5] = GETU32(userKey + 20);
if (bits == 192) {
while (1) {
temp = rk[ 5];
rk[ 6] = rk[ 0] ^
(Te2[(temp >> 16) & 0xff] & 0xff000000) ^
(Te3[(temp >> 8) & 0xff] & 0x00ff0000) ^
(Te0[(temp ) & 0xff] & 0x0000ff00) ^
(Te1[(temp >> 24) ] & 0x000000ff) ^
rcon[i];
rk[ 7] = rk[ 1] ^ rk[ 6];
rk[ 8] = rk[ 2] ^ rk[ 7];
rk[ 9] = rk[ 3] ^ rk[ 8];
if (++i == 8) {
return 0;
}
rk[10] = rk[ 4] ^ rk[ 9];
rk[11] = rk[ 5] ^ rk[10];
rk += 6;
}
}
rk[6] = GETU32(userKey + 24);
rk[7] = GETU32(userKey + 28);
if (bits == 256) {
while (1) {
temp = rk[ 7];
rk[ 8] = rk[ 0] ^
(Te2[(temp >> 16) & 0xff] & 0xff000000) ^
(Te3[(temp >> 8) & 0xff] & 0x00ff0000) ^
(Te0[(temp ) & 0xff] & 0x0000ff00) ^
(Te1[(temp >> 24) ] & 0x000000ff) ^
rcon[i];
rk[ 9] = rk[ 1] ^ rk[ 8];
rk[10] = rk[ 2] ^ rk[ 9];
rk[11] = rk[ 3] ^ rk[10];
if (++i == 7) {
return 0;
}
temp = rk[11];
rk[12] = rk[ 4] ^
(Te2[(temp >> 24) ] & 0xff000000) ^
(Te3[(temp >> 16) & 0xff] & 0x00ff0000) ^
(Te0[(temp >> 8) & 0xff] & 0x0000ff00) ^
(Te1[(temp ) & 0xff] & 0x000000ff);
rk[13] = rk[ 5] ^ rk[12];
rk[14] = rk[ 6] ^ rk[13];
rk[15] = rk[ 7] ^ rk[14];
rk += 8;
}
}
return 0;
}
/**
* Expand the cipher key into the decryption key schedule.
*/
int AES_set_decrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key)
{
u32 *rk;
int i, j, status;
u32 temp;
/* first, start with an encryption schedule */
status = AES_set_encrypt_key(userKey, bits, key);
if (status < 0)
return status;
rk = key->rd_key;
/* invert the order of the round keys: */
for (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) {
temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp;
temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp;
temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp;
temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;
}
/* apply the inverse MixColumn transform to all round keys but the first and the last: */
for (i = 1; i < (key->rounds); i++) {
rk += 4;
rk[0] =
Td0[Te1[(rk[0] >> 24) ] & 0xff] ^
Td1[Te1[(rk[0] >> 16) & 0xff] & 0xff] ^
Td2[Te1[(rk[0] >> 8) & 0xff] & 0xff] ^
Td3[Te1[(rk[0] ) & 0xff] & 0xff];
rk[1] =
Td0[Te1[(rk[1] >> 24) ] & 0xff] ^
Td1[Te1[(rk[1] >> 16) & 0xff] & 0xff] ^
Td2[Te1[(rk[1] >> 8) & 0xff] & 0xff] ^
Td3[Te1[(rk[1] ) & 0xff] & 0xff];
rk[2] =
Td0[Te1[(rk[2] >> 24) ] & 0xff] ^
Td1[Te1[(rk[2] >> 16) & 0xff] & 0xff] ^
Td2[Te1[(rk[2] >> 8) & 0xff] & 0xff] ^
Td3[Te1[(rk[2] ) & 0xff] & 0xff];
rk[3] =
Td0[Te1[(rk[3] >> 24) ] & 0xff] ^
Td1[Te1[(rk[3] >> 16) & 0xff] & 0xff] ^
Td2[Te1[(rk[3] >> 8) & 0xff] & 0xff] ^
Td3[Te1[(rk[3] ) & 0xff] & 0xff];
}
return 0;
}
/*
* Encrypt a single block
* in and out can overlap
*/
void AES_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key) {
const u32 *rk;
u32 s0, s1, s2, s3, t0, t1, t2, t3;
#ifndef FULL_UNROLL
int r;
#endif /* ?FULL_UNROLL */
assert(in && out && key);
rk = key->rd_key;
/*
* map byte array block to cipher state
* and add initial round key:
*/
s0 = GETU32(in ) ^ rk[0];
s1 = GETU32(in + 4) ^ rk[1];
s2 = GETU32(in + 8) ^ rk[2];
s3 = GETU32(in + 12) ^ rk[3];
#ifdef FULL_UNROLL
/* round 1: */
t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[ 4];
t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[ 5];
t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[ 6];
t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[ 7];
/* round 2: */
s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[ 8];
s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[ 9];
s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[10];
s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[11];
/* round 3: */
t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[12];
t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[13];
t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[14];
t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[15];
/* round 4: */
s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[16];
s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[17];
s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[18];
s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[19];
/* round 5: */
t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[20];
t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[21];
t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[22];
t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[23];
/* round 6: */
s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[24];
s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[25];
s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[26];
s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[27];
/* round 7: */
t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[28];
t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[29];
t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[30];
t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[31];
/* round 8: */
s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[32];
s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[33];
s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[34];
s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[35];
/* round 9: */
t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[36];
t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[37];
t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[38];
t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[39];
if (key->rounds > 10) {
/* round 10: */
s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[40];
s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[41];
s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[42];
s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[43];
/* round 11: */
t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[44];
t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[45];
t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[46];
t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[47];
if (key->rounds > 12) {
/* round 12: */
s0 = Te0[t0 >> 24] ^ Te1[(t1 >> 16) & 0xff] ^ Te2[(t2 >> 8) & 0xff] ^ Te3[t3 & 0xff] ^ rk[48];
s1 = Te0[t1 >> 24] ^ Te1[(t2 >> 16) & 0xff] ^ Te2[(t3 >> 8) & 0xff] ^ Te3[t0 & 0xff] ^ rk[49];
s2 = Te0[t2 >> 24] ^ Te1[(t3 >> 16) & 0xff] ^ Te2[(t0 >> 8) & 0xff] ^ Te3[t1 & 0xff] ^ rk[50];
s3 = Te0[t3 >> 24] ^ Te1[(t0 >> 16) & 0xff] ^ Te2[(t1 >> 8) & 0xff] ^ Te3[t2 & 0xff] ^ rk[51];
/* round 13: */
t0 = Te0[s0 >> 24] ^ Te1[(s1 >> 16) & 0xff] ^ Te2[(s2 >> 8) & 0xff] ^ Te3[s3 & 0xff] ^ rk[52];
t1 = Te0[s1 >> 24] ^ Te1[(s2 >> 16) & 0xff] ^ Te2[(s3 >> 8) & 0xff] ^ Te3[s0 & 0xff] ^ rk[53];
t2 = Te0[s2 >> 24] ^ Te1[(s3 >> 16) & 0xff] ^ Te2[(s0 >> 8) & 0xff] ^ Te3[s1 & 0xff] ^ rk[54];
t3 = Te0[s3 >> 24] ^ Te1[(s0 >> 16) & 0xff] ^ Te2[(s1 >> 8) & 0xff] ^ Te3[s2 & 0xff] ^ rk[55];
}
}
rk += key->rounds << 2;
#else /* !FULL_UNROLL */
/*
* Nr - 1 full rounds:
*/
r = key->rounds >> 1;
for (;;) {
t0 =
Te0[(s0 >> 24) ] ^
Te1[(s1 >> 16) & 0xff] ^
Te2[(s2 >> 8) & 0xff] ^
Te3[(s3 ) & 0xff] ^
rk[4];
t1 =
Te0[(s1 >> 24) ] ^
Te1[(s2 >> 16) & 0xff] ^
Te2[(s3 >> 8) & 0xff] ^
Te3[(s0 ) & 0xff] ^
rk[5];
t2 =
Te0[(s2 >> 24) ] ^
Te1[(s3 >> 16) & 0xff] ^
Te2[(s0 >> 8) & 0xff] ^
Te3[(s1 ) & 0xff] ^
rk[6];
t3 =
Te0[(s3 >> 24) ] ^
Te1[(s0 >> 16) & 0xff] ^
Te2[(s1 >> 8) & 0xff] ^
Te3[(s2 ) & 0xff] ^
rk[7];
rk += 8;
if (--r == 0) {
break;
}
s0 =
Te0[(t0 >> 24) ] ^
Te1[(t1 >> 16) & 0xff] ^
Te2[(t2 >> 8) & 0xff] ^
Te3[(t3 ) & 0xff] ^
rk[0];
s1 =
Te0[(t1 >> 24) ] ^
Te1[(t2 >> 16) & 0xff] ^
Te2[(t3 >> 8) & 0xff] ^
Te3[(t0 ) & 0xff] ^
rk[1];
s2 =
Te0[(t2 >> 24) ] ^
Te1[(t3 >> 16) & 0xff] ^
Te2[(t0 >> 8) & 0xff] ^
Te3[(t1 ) & 0xff] ^
rk[2];
s3 =
Te0[(t3 >> 24) ] ^
Te1[(t0 >> 16) & 0xff] ^
Te2[(t1 >> 8) & 0xff] ^
Te3[(t2 ) & 0xff] ^
rk[3];
}
#endif /* ?FULL_UNROLL */
/*
* apply last round and
* map cipher state to byte array block:
*/
s0 =
(Te2[(t0 >> 24) ] & 0xff000000) ^
(Te3[(t1 >> 16) & 0xff] & 0x00ff0000) ^
(Te0[(t2 >> 8) & 0xff] & 0x0000ff00) ^
(Te1[(t3 ) & 0xff] & 0x000000ff) ^
rk[0];
PUTU32(out , s0);
s1 =
(Te2[(t1 >> 24) ] & 0xff000000) ^
(Te3[(t2 >> 16) & 0xff] & 0x00ff0000) ^
(Te0[(t3 >> 8) & 0xff] & 0x0000ff00) ^
(Te1[(t0 ) & 0xff] & 0x000000ff) ^
rk[1];
PUTU32(out + 4, s1);
s2 =
(Te2[(t2 >> 24) ] & 0xff000000) ^
(Te3[(t3 >> 16) & 0xff] & 0x00ff0000) ^
(Te0[(t0 >> 8) & 0xff] & 0x0000ff00) ^
(Te1[(t1 ) & 0xff] & 0x000000ff) ^
rk[2];
PUTU32(out + 8, s2);
s3 =
(Te2[(t3 >> 24) ] & 0xff000000) ^
(Te3[(t0 >> 16) & 0xff] & 0x00ff0000) ^
(Te0[(t1 >> 8) & 0xff] & 0x0000ff00) ^
(Te1[(t2 ) & 0xff] & 0x000000ff) ^
rk[3];
PUTU32(out + 12, s3);
}
/*
* Decrypt a single block
* in and out can overlap
*/
void AES_decrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key)
{
const u32 *rk;
u32 s0, s1, s2, s3, t0, t1, t2, t3;
#ifndef FULL_UNROLL
int r;
#endif /* ?FULL_UNROLL */
assert(in && out && key);
rk = key->rd_key;
/*
* map byte array block to cipher state
* and add initial round key:
*/
s0 = GETU32(in ) ^ rk[0];
s1 = GETU32(in + 4) ^ rk[1];
s2 = GETU32(in + 8) ^ rk[2];
s3 = GETU32(in + 12) ^ rk[3];
#ifdef FULL_UNROLL
/* round 1: */
t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[ 4];
t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[ 5];
t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[ 6];
t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[ 7];
/* round 2: */
s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[ 8];
s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[ 9];
s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[10];
s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[11];
/* round 3: */
t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[12];
t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[13];
t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[14];
t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[15];
/* round 4: */
s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[16];
s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[17];
s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[18];
s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[19];
/* round 5: */
t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[20];
t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[21];
t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[22];
t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[23];
/* round 6: */
s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[24];
s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[25];
s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[26];
s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[27];
/* round 7: */
t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[28];
t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[29];
t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[30];
t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[31];
/* round 8: */
s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[32];
s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[33];
s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[34];
s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[35];
/* round 9: */
t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[36];
t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[37];
t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[38];
t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[39];
if (key->rounds > 10) {
/* round 10: */
s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[40];
s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[41];
s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[42];
s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[43];
/* round 11: */
t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[44];
t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[45];
t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[46];
t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[47];
if (key->rounds > 12) {
/* round 12: */
s0 = Td0[t0 >> 24] ^ Td1[(t3 >> 16) & 0xff] ^ Td2[(t2 >> 8) & 0xff] ^ Td3[t1 & 0xff] ^ rk[48];
s1 = Td0[t1 >> 24] ^ Td1[(t0 >> 16) & 0xff] ^ Td2[(t3 >> 8) & 0xff] ^ Td3[t2 & 0xff] ^ rk[49];
s2 = Td0[t2 >> 24] ^ Td1[(t1 >> 16) & 0xff] ^ Td2[(t0 >> 8) & 0xff] ^ Td3[t3 & 0xff] ^ rk[50];
s3 = Td0[t3 >> 24] ^ Td1[(t2 >> 16) & 0xff] ^ Td2[(t1 >> 8) & 0xff] ^ Td3[t0 & 0xff] ^ rk[51];
/* round 13: */
t0 = Td0[s0 >> 24] ^ Td1[(s3 >> 16) & 0xff] ^ Td2[(s2 >> 8) & 0xff] ^ Td3[s1 & 0xff] ^ rk[52];
t1 = Td0[s1 >> 24] ^ Td1[(s0 >> 16) & 0xff] ^ Td2[(s3 >> 8) & 0xff] ^ Td3[s2 & 0xff] ^ rk[53];
t2 = Td0[s2 >> 24] ^ Td1[(s1 >> 16) & 0xff] ^ Td2[(s0 >> 8) & 0xff] ^ Td3[s3 & 0xff] ^ rk[54];
t3 = Td0[s3 >> 24] ^ Td1[(s2 >> 16) & 0xff] ^ Td2[(s1 >> 8) & 0xff] ^ Td3[s0 & 0xff] ^ rk[55];
}
}
rk += key->rounds << 2;
#else /* !FULL_UNROLL */
/*
* Nr - 1 full rounds:
*/
r = key->rounds >> 1;
for (;;) {
t0 =
Td0[(s0 >> 24) ] ^
Td1[(s3 >> 16) & 0xff] ^
Td2[(s2 >> 8) & 0xff] ^
Td3[(s1 ) & 0xff] ^
rk[4];
t1 =
Td0[(s1 >> 24) ] ^
Td1[(s0 >> 16) & 0xff] ^
Td2[(s3 >> 8) & 0xff] ^
Td3[(s2 ) & 0xff] ^
rk[5];
t2 =
Td0[(s2 >> 24) ] ^
Td1[(s1 >> 16) & 0xff] ^
Td2[(s0 >> 8) & 0xff] ^
Td3[(s3 ) & 0xff] ^
rk[6];
t3 =
Td0[(s3 >> 24) ] ^
Td1[(s2 >> 16) & 0xff] ^
Td2[(s1 >> 8) & 0xff] ^
Td3[(s0 ) & 0xff] ^
rk[7];
rk += 8;
if (--r == 0) {
break;
}
s0 =
Td0[(t0 >> 24) ] ^
Td1[(t3 >> 16) & 0xff] ^
Td2[(t2 >> 8) & 0xff] ^
Td3[(t1 ) & 0xff] ^
rk[0];
s1 =
Td0[(t1 >> 24) ] ^
Td1[(t0 >> 16) & 0xff] ^
Td2[(t3 >> 8) & 0xff] ^
Td3[(t2 ) & 0xff] ^
rk[1];
s2 =
Td0[(t2 >> 24) ] ^
Td1[(t1 >> 16) & 0xff] ^
Td2[(t0 >> 8) & 0xff] ^
Td3[(t3 ) & 0xff] ^
rk[2];
s3 =
Td0[(t3 >> 24) ] ^
Td1[(t2 >> 16) & 0xff] ^
Td2[(t1 >> 8) & 0xff] ^
Td3[(t0 ) & 0xff] ^
rk[3];
}
#endif /* ?FULL_UNROLL */
/*
* apply last round and
* map cipher state to byte array block:
*/
s0 =
((u32)Td4[(t0 >> 24) ] << 24) ^
((u32)Td4[(t3 >> 16) & 0xff] << 16) ^
((u32)Td4[(t2 >> 8) & 0xff] << 8) ^
((u32)Td4[(t1 ) & 0xff]) ^
rk[0];
PUTU32(out , s0);
s1 =
((u32)Td4[(t1 >> 24) ] << 24) ^
((u32)Td4[(t0 >> 16) & 0xff] << 16) ^
((u32)Td4[(t3 >> 8) & 0xff] << 8) ^
((u32)Td4[(t2 ) & 0xff]) ^
rk[1];
PUTU32(out + 4, s1);
s2 =
((u32)Td4[(t2 >> 24) ] << 24) ^
((u32)Td4[(t1 >> 16) & 0xff] << 16) ^
((u32)Td4[(t0 >> 8) & 0xff] << 8) ^
((u32)Td4[(t3 ) & 0xff]) ^
rk[2];
PUTU32(out + 8, s2);
s3 =
((u32)Td4[(t3 >> 24) ] << 24) ^
((u32)Td4[(t2 >> 16) & 0xff] << 16) ^
((u32)Td4[(t1 >> 8) & 0xff] << 8) ^
((u32)Td4[(t0 ) & 0xff]) ^
rk[3];
PUTU32(out + 12, s3);
}
#else /* AES_ASM */
static const u8 Te4[256] = {
0x63U, 0x7cU, 0x77U, 0x7bU, 0xf2U, 0x6bU, 0x6fU, 0xc5U,
0x30U, 0x01U, 0x67U, 0x2bU, 0xfeU, 0xd7U, 0xabU, 0x76U,
0xcaU, 0x82U, 0xc9U, 0x7dU, 0xfaU, 0x59U, 0x47U, 0xf0U,
0xadU, 0xd4U, 0xa2U, 0xafU, 0x9cU, 0xa4U, 0x72U, 0xc0U,
0xb7U, 0xfdU, 0x93U, 0x26U, 0x36U, 0x3fU, 0xf7U, 0xccU,
0x34U, 0xa5U, 0xe5U, 0xf1U, 0x71U, 0xd8U, 0x31U, 0x15U,
0x04U, 0xc7U, 0x23U, 0xc3U, 0x18U, 0x96U, 0x05U, 0x9aU,
0x07U, 0x12U, 0x80U, 0xe2U, 0xebU, 0x27U, 0xb2U, 0x75U,
0x09U, 0x83U, 0x2cU, 0x1aU, 0x1bU, 0x6eU, 0x5aU, 0xa0U,
0x52U, 0x3bU, 0xd6U, 0xb3U, 0x29U, 0xe3U, 0x2fU, 0x84U,
0x53U, 0xd1U, 0x00U, 0xedU, 0x20U, 0xfcU, 0xb1U, 0x5bU,
0x6aU, 0xcbU, 0xbeU, 0x39U, 0x4aU, 0x4cU, 0x58U, 0xcfU,
0xd0U, 0xefU, 0xaaU, 0xfbU, 0x43U, 0x4dU, 0x33U, 0x85U,
0x45U, 0xf9U, 0x02U, 0x7fU, 0x50U, 0x3cU, 0x9fU, 0xa8U,
0x51U, 0xa3U, 0x40U, 0x8fU, 0x92U, 0x9dU, 0x38U, 0xf5U,
0xbcU, 0xb6U, 0xdaU, 0x21U, 0x10U, 0xffU, 0xf3U, 0xd2U,
0xcdU, 0x0cU, 0x13U, 0xecU, 0x5fU, 0x97U, 0x44U, 0x17U,
0xc4U, 0xa7U, 0x7eU, 0x3dU, 0x64U, 0x5dU, 0x19U, 0x73U,
0x60U, 0x81U, 0x4fU, 0xdcU, 0x22U, 0x2aU, 0x90U, 0x88U,
0x46U, 0xeeU, 0xb8U, 0x14U, 0xdeU, 0x5eU, 0x0bU, 0xdbU,
0xe0U, 0x32U, 0x3aU, 0x0aU, 0x49U, 0x06U, 0x24U, 0x5cU,
0xc2U, 0xd3U, 0xacU, 0x62U, 0x91U, 0x95U, 0xe4U, 0x79U,
0xe7U, 0xc8U, 0x37U, 0x6dU, 0x8dU, 0xd5U, 0x4eU, 0xa9U,
0x6cU, 0x56U, 0xf4U, 0xeaU, 0x65U, 0x7aU, 0xaeU, 0x08U,
0xbaU, 0x78U, 0x25U, 0x2eU, 0x1cU, 0xa6U, 0xb4U, 0xc6U,
0xe8U, 0xddU, 0x74U, 0x1fU, 0x4bU, 0xbdU, 0x8bU, 0x8aU,
0x70U, 0x3eU, 0xb5U, 0x66U, 0x48U, 0x03U, 0xf6U, 0x0eU,
0x61U, 0x35U, 0x57U, 0xb9U, 0x86U, 0xc1U, 0x1dU, 0x9eU,
0xe1U, 0xf8U, 0x98U, 0x11U, 0x69U, 0xd9U, 0x8eU, 0x94U,
0x9bU, 0x1eU, 0x87U, 0xe9U, 0xceU, 0x55U, 0x28U, 0xdfU,
0x8cU, 0xa1U, 0x89U, 0x0dU, 0xbfU, 0xe6U, 0x42U, 0x68U,
0x41U, 0x99U, 0x2dU, 0x0fU, 0xb0U, 0x54U, 0xbbU, 0x16U
};
static const u32 rcon[] = {
0x01000000, 0x02000000, 0x04000000, 0x08000000,
0x10000000, 0x20000000, 0x40000000, 0x80000000,
0x1B000000, 0x36000000, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */
};
/**
* Expand the cipher key into the encryption key schedule.
*/
int AES_set_encrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key)
{
u32 *rk;
int i = 0;
u32 temp;
if (!userKey || !key)
return -1;
if (bits != 128 && bits != 192 && bits != 256)
return -2;
rk = key->rd_key;
if (bits == 128)
key->rounds = 10;
else if (bits == 192)
key->rounds = 12;
else
key->rounds = 14;
rk[0] = GETU32(userKey );
rk[1] = GETU32(userKey + 4);
rk[2] = GETU32(userKey + 8);
rk[3] = GETU32(userKey + 12);
if (bits == 128) {
while (1) {
temp = rk[3];
rk[4] = rk[0] ^
((u32)Te4[(temp >> 16) & 0xff] << 24) ^
((u32)Te4[(temp >> 8) & 0xff] << 16) ^
((u32)Te4[(temp ) & 0xff] << 8) ^
((u32)Te4[(temp >> 24) ]) ^
rcon[i];
rk[5] = rk[1] ^ rk[4];
rk[6] = rk[2] ^ rk[5];
rk[7] = rk[3] ^ rk[6];
if (++i == 10) {
return 0;
}
rk += 4;
}
}
rk[4] = GETU32(userKey + 16);
rk[5] = GETU32(userKey + 20);
if (bits == 192) {
while (1) {
temp = rk[ 5];
rk[ 6] = rk[ 0] ^
((u32)Te4[(temp >> 16) & 0xff] << 24) ^
((u32)Te4[(temp >> 8) & 0xff] << 16) ^
((u32)Te4[(temp ) & 0xff] << 8) ^
((u32)Te4[(temp >> 24) ]) ^
rcon[i];
rk[ 7] = rk[ 1] ^ rk[ 6];
rk[ 8] = rk[ 2] ^ rk[ 7];
rk[ 9] = rk[ 3] ^ rk[ 8];
if (++i == 8) {
return 0;
}
rk[10] = rk[ 4] ^ rk[ 9];
rk[11] = rk[ 5] ^ rk[10];
rk += 6;
}
}
rk[6] = GETU32(userKey + 24);
rk[7] = GETU32(userKey + 28);
if (bits == 256) {
while (1) {
temp = rk[ 7];
rk[ 8] = rk[ 0] ^
((u32)Te4[(temp >> 16) & 0xff] << 24) ^
((u32)Te4[(temp >> 8) & 0xff] << 16) ^
((u32)Te4[(temp ) & 0xff] << 8) ^
((u32)Te4[(temp >> 24) ]) ^
rcon[i];
rk[ 9] = rk[ 1] ^ rk[ 8];
rk[10] = rk[ 2] ^ rk[ 9];
rk[11] = rk[ 3] ^ rk[10];
if (++i == 7) {
return 0;
}
temp = rk[11];
rk[12] = rk[ 4] ^
((u32)Te4[(temp >> 24) ] << 24) ^
((u32)Te4[(temp >> 16) & 0xff] << 16) ^
((u32)Te4[(temp >> 8) & 0xff] << 8) ^
((u32)Te4[(temp ) & 0xff]);
rk[13] = rk[ 5] ^ rk[12];
rk[14] = rk[ 6] ^ rk[13];
rk[15] = rk[ 7] ^ rk[14];
rk += 8;
}
}
return 0;
}
/**
* Expand the cipher key into the decryption key schedule.
*/
int AES_set_decrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key)
{
u32 *rk;
int i, j, status;
u32 temp;
/* first, start with an encryption schedule */
status = AES_set_encrypt_key(userKey, bits, key);
if (status < 0)
return status;
rk = key->rd_key;
/* invert the order of the round keys: */
for (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) {
temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp;
temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp;
temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp;
temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;
}
/* apply the inverse MixColumn transform to all round keys but the first and the last: */
for (i = 1; i < (key->rounds); i++) {
rk += 4;
for (j = 0; j < 4; j++) {
u32 tp1, tp2, tp4, tp8, tp9, tpb, tpd, tpe, m;
tp1 = rk[j];
m = tp1 & 0x80808080;
tp2 = ((tp1 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp2 & 0x80808080;
tp4 = ((tp2 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp4 & 0x80808080;
tp8 = ((tp4 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
tp9 = tp8 ^ tp1;
tpb = tp9 ^ tp2;
tpd = tp9 ^ tp4;
tpe = tp8 ^ tp4 ^ tp2;
#if defined(ROTATE)
rk[j] = tpe ^ ROTATE(tpd,16) ^
ROTATE(tp9,24) ^ ROTATE(tpb,8);
#else
rk[j] = tpe ^ (tpd >> 16) ^ (tpd << 16) ^
(tp9 >> 8) ^ (tp9 << 24) ^
(tpb >> 24) ^ (tpb << 8);
#endif
}
}
return 0;
}
#endif /* AES_ASM */
|
./openssl/crypto/aes/aes_ofb.c | /*
* Copyright 2002-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
*/
/*
* AES_encrypt is deprecated - but we need to use it to implement
* AES_ofb128_encrypt
*/
#include "internal/deprecated.h"
#include <openssl/aes.h>
#include <openssl/modes.h>
void AES_ofb128_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const AES_KEY *key,
unsigned char *ivec, int *num)
{
CRYPTO_ofb128_encrypt(in, out, length, key, ivec, num,
(block128_f) AES_encrypt);
}
|
./openssl/crypto/aes/aes_x86core.c | /*
* Copyright 2006-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 is experimental x86[_64] derivative. It assumes little-endian
* byte order and expects CPU to sustain unaligned memory references.
* It is used as playground for cache-time attack mitigations and
* serves as reference C implementation for x86[_64] as well as some
* other assembly modules.
*/
/**
* rijndael-alg-fst.c
*
* @version 3.0 (December 2000)
*
* Optimised ANSI C code for the Rijndael cipher (now AES)
*
* @author Vincent Rijmen
* @author Antoon Bosselaers
* @author Paulo Barreto
*
* This code is hereby placed in the public domain.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''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 AUTHORS 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 <assert.h>
#include <stdlib.h>
#include <openssl/aes.h>
#include "aes_local.h"
/*
* These two parameters control which table, 256-byte or 2KB, is
* referenced in outer and respectively inner rounds.
*/
#define AES_COMPACT_IN_OUTER_ROUNDS
#ifdef AES_COMPACT_IN_OUTER_ROUNDS
/* AES_COMPACT_IN_OUTER_ROUNDS costs ~30% in performance, while
* adding AES_COMPACT_IN_INNER_ROUNDS reduces benchmark *further*
* by factor of ~2. */
# undef AES_COMPACT_IN_INNER_ROUNDS
#endif
#if 1
static void prefetch256(const void *table)
{
volatile unsigned long *t = (void *)table, ret;
unsigned long sum;
int i;
/* 32 is common least cache-line size */
for (sum = 0, i = 0; i < 256/sizeof(t[0]); i += 32/sizeof(t[0]))
sum ^= t[i];
ret = sum;
}
#else
# define prefetch256(t)
#endif
#undef GETU32
#define GETU32(p) (*((u32*)(p)))
#if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32__)
#define U64(C) C##UI64
#elif defined(__arch64__)
#define U64(C) C##UL
#else
#define U64(C) C##ULL
#endif
#undef ROTATE
#if defined(_MSC_VER)
# define ROTATE(a,n) _lrotl(a,n)
#elif defined(__ICC)
# define ROTATE(a,n) _rotl(a,n)
#elif defined(__GNUC__) && __GNUC__>=2
# if defined(__i386) || defined(__i386__) || defined(__x86_64) || defined(__x86_64__)
# define ROTATE(a,n) ({ register unsigned int ret; \
asm ( \
"roll %1,%0" \
: "=r"(ret) \
: "I"(n), "0"(a) \
: "cc"); \
ret; \
})
# endif
#endif
/*-
Te [x] = S [x].[02, 01, 01, 03, 02, 01, 01, 03];
Te0[x] = S [x].[02, 01, 01, 03];
Te1[x] = S [x].[03, 02, 01, 01];
Te2[x] = S [x].[01, 03, 02, 01];
Te3[x] = S [x].[01, 01, 03, 02];
*/
#define Te0 (u32)((u64*)((u8*)Te+0))
#define Te1 (u32)((u64*)((u8*)Te+3))
#define Te2 (u32)((u64*)((u8*)Te+2))
#define Te3 (u32)((u64*)((u8*)Te+1))
/*-
Td [x] = Si[x].[0e, 09, 0d, 0b, 0e, 09, 0d, 0b];
Td0[x] = Si[x].[0e, 09, 0d, 0b];
Td1[x] = Si[x].[0b, 0e, 09, 0d];
Td2[x] = Si[x].[0d, 0b, 0e, 09];
Td3[x] = Si[x].[09, 0d, 0b, 0e];
Td4[x] = Si[x].[01];
*/
#define Td0 (u32)((u64*)((u8*)Td+0))
#define Td1 (u32)((u64*)((u8*)Td+3))
#define Td2 (u32)((u64*)((u8*)Td+2))
#define Td3 (u32)((u64*)((u8*)Td+1))
static const u64 Te[256] = {
U64(0xa56363c6a56363c6), U64(0x847c7cf8847c7cf8),
U64(0x997777ee997777ee), U64(0x8d7b7bf68d7b7bf6),
U64(0x0df2f2ff0df2f2ff), U64(0xbd6b6bd6bd6b6bd6),
U64(0xb16f6fdeb16f6fde), U64(0x54c5c59154c5c591),
U64(0x5030306050303060), U64(0x0301010203010102),
U64(0xa96767cea96767ce), U64(0x7d2b2b567d2b2b56),
U64(0x19fefee719fefee7), U64(0x62d7d7b562d7d7b5),
U64(0xe6abab4de6abab4d), U64(0x9a7676ec9a7676ec),
U64(0x45caca8f45caca8f), U64(0x9d82821f9d82821f),
U64(0x40c9c98940c9c989), U64(0x877d7dfa877d7dfa),
U64(0x15fafaef15fafaef), U64(0xeb5959b2eb5959b2),
U64(0xc947478ec947478e), U64(0x0bf0f0fb0bf0f0fb),
U64(0xecadad41ecadad41), U64(0x67d4d4b367d4d4b3),
U64(0xfda2a25ffda2a25f), U64(0xeaafaf45eaafaf45),
U64(0xbf9c9c23bf9c9c23), U64(0xf7a4a453f7a4a453),
U64(0x967272e4967272e4), U64(0x5bc0c09b5bc0c09b),
U64(0xc2b7b775c2b7b775), U64(0x1cfdfde11cfdfde1),
U64(0xae93933dae93933d), U64(0x6a26264c6a26264c),
U64(0x5a36366c5a36366c), U64(0x413f3f7e413f3f7e),
U64(0x02f7f7f502f7f7f5), U64(0x4fcccc834fcccc83),
U64(0x5c3434685c343468), U64(0xf4a5a551f4a5a551),
U64(0x34e5e5d134e5e5d1), U64(0x08f1f1f908f1f1f9),
U64(0x937171e2937171e2), U64(0x73d8d8ab73d8d8ab),
U64(0x5331316253313162), U64(0x3f15152a3f15152a),
U64(0x0c0404080c040408), U64(0x52c7c79552c7c795),
U64(0x6523234665232346), U64(0x5ec3c39d5ec3c39d),
U64(0x2818183028181830), U64(0xa1969637a1969637),
U64(0x0f05050a0f05050a), U64(0xb59a9a2fb59a9a2f),
U64(0x0907070e0907070e), U64(0x3612122436121224),
U64(0x9b80801b9b80801b), U64(0x3de2e2df3de2e2df),
U64(0x26ebebcd26ebebcd), U64(0x6927274e6927274e),
U64(0xcdb2b27fcdb2b27f), U64(0x9f7575ea9f7575ea),
U64(0x1b0909121b090912), U64(0x9e83831d9e83831d),
U64(0x742c2c58742c2c58), U64(0x2e1a1a342e1a1a34),
U64(0x2d1b1b362d1b1b36), U64(0xb26e6edcb26e6edc),
U64(0xee5a5ab4ee5a5ab4), U64(0xfba0a05bfba0a05b),
U64(0xf65252a4f65252a4), U64(0x4d3b3b764d3b3b76),
U64(0x61d6d6b761d6d6b7), U64(0xceb3b37dceb3b37d),
U64(0x7b2929527b292952), U64(0x3ee3e3dd3ee3e3dd),
U64(0x712f2f5e712f2f5e), U64(0x9784841397848413),
U64(0xf55353a6f55353a6), U64(0x68d1d1b968d1d1b9),
U64(0x0000000000000000), U64(0x2cededc12cededc1),
U64(0x6020204060202040), U64(0x1ffcfce31ffcfce3),
U64(0xc8b1b179c8b1b179), U64(0xed5b5bb6ed5b5bb6),
U64(0xbe6a6ad4be6a6ad4), U64(0x46cbcb8d46cbcb8d),
U64(0xd9bebe67d9bebe67), U64(0x4b3939724b393972),
U64(0xde4a4a94de4a4a94), U64(0xd44c4c98d44c4c98),
U64(0xe85858b0e85858b0), U64(0x4acfcf854acfcf85),
U64(0x6bd0d0bb6bd0d0bb), U64(0x2aefefc52aefefc5),
U64(0xe5aaaa4fe5aaaa4f), U64(0x16fbfbed16fbfbed),
U64(0xc5434386c5434386), U64(0xd74d4d9ad74d4d9a),
U64(0x5533336655333366), U64(0x9485851194858511),
U64(0xcf45458acf45458a), U64(0x10f9f9e910f9f9e9),
U64(0x0602020406020204), U64(0x817f7ffe817f7ffe),
U64(0xf05050a0f05050a0), U64(0x443c3c78443c3c78),
U64(0xba9f9f25ba9f9f25), U64(0xe3a8a84be3a8a84b),
U64(0xf35151a2f35151a2), U64(0xfea3a35dfea3a35d),
U64(0xc0404080c0404080), U64(0x8a8f8f058a8f8f05),
U64(0xad92923fad92923f), U64(0xbc9d9d21bc9d9d21),
U64(0x4838387048383870), U64(0x04f5f5f104f5f5f1),
U64(0xdfbcbc63dfbcbc63), U64(0xc1b6b677c1b6b677),
U64(0x75dadaaf75dadaaf), U64(0x6321214263212142),
U64(0x3010102030101020), U64(0x1affffe51affffe5),
U64(0x0ef3f3fd0ef3f3fd), U64(0x6dd2d2bf6dd2d2bf),
U64(0x4ccdcd814ccdcd81), U64(0x140c0c18140c0c18),
U64(0x3513132635131326), U64(0x2fececc32fececc3),
U64(0xe15f5fbee15f5fbe), U64(0xa2979735a2979735),
U64(0xcc444488cc444488), U64(0x3917172e3917172e),
U64(0x57c4c49357c4c493), U64(0xf2a7a755f2a7a755),
U64(0x827e7efc827e7efc), U64(0x473d3d7a473d3d7a),
U64(0xac6464c8ac6464c8), U64(0xe75d5dbae75d5dba),
U64(0x2b1919322b191932), U64(0x957373e6957373e6),
U64(0xa06060c0a06060c0), U64(0x9881811998818119),
U64(0xd14f4f9ed14f4f9e), U64(0x7fdcdca37fdcdca3),
U64(0x6622224466222244), U64(0x7e2a2a547e2a2a54),
U64(0xab90903bab90903b), U64(0x8388880b8388880b),
U64(0xca46468cca46468c), U64(0x29eeeec729eeeec7),
U64(0xd3b8b86bd3b8b86b), U64(0x3c1414283c141428),
U64(0x79dedea779dedea7), U64(0xe25e5ebce25e5ebc),
U64(0x1d0b0b161d0b0b16), U64(0x76dbdbad76dbdbad),
U64(0x3be0e0db3be0e0db), U64(0x5632326456323264),
U64(0x4e3a3a744e3a3a74), U64(0x1e0a0a141e0a0a14),
U64(0xdb494992db494992), U64(0x0a06060c0a06060c),
U64(0x6c2424486c242448), U64(0xe45c5cb8e45c5cb8),
U64(0x5dc2c29f5dc2c29f), U64(0x6ed3d3bd6ed3d3bd),
U64(0xefacac43efacac43), U64(0xa66262c4a66262c4),
U64(0xa8919139a8919139), U64(0xa4959531a4959531),
U64(0x37e4e4d337e4e4d3), U64(0x8b7979f28b7979f2),
U64(0x32e7e7d532e7e7d5), U64(0x43c8c88b43c8c88b),
U64(0x5937376e5937376e), U64(0xb76d6ddab76d6dda),
U64(0x8c8d8d018c8d8d01), U64(0x64d5d5b164d5d5b1),
U64(0xd24e4e9cd24e4e9c), U64(0xe0a9a949e0a9a949),
U64(0xb46c6cd8b46c6cd8), U64(0xfa5656acfa5656ac),
U64(0x07f4f4f307f4f4f3), U64(0x25eaeacf25eaeacf),
U64(0xaf6565caaf6565ca), U64(0x8e7a7af48e7a7af4),
U64(0xe9aeae47e9aeae47), U64(0x1808081018080810),
U64(0xd5baba6fd5baba6f), U64(0x887878f0887878f0),
U64(0x6f25254a6f25254a), U64(0x722e2e5c722e2e5c),
U64(0x241c1c38241c1c38), U64(0xf1a6a657f1a6a657),
U64(0xc7b4b473c7b4b473), U64(0x51c6c69751c6c697),
U64(0x23e8e8cb23e8e8cb), U64(0x7cdddda17cdddda1),
U64(0x9c7474e89c7474e8), U64(0x211f1f3e211f1f3e),
U64(0xdd4b4b96dd4b4b96), U64(0xdcbdbd61dcbdbd61),
U64(0x868b8b0d868b8b0d), U64(0x858a8a0f858a8a0f),
U64(0x907070e0907070e0), U64(0x423e3e7c423e3e7c),
U64(0xc4b5b571c4b5b571), U64(0xaa6666ccaa6666cc),
U64(0xd8484890d8484890), U64(0x0503030605030306),
U64(0x01f6f6f701f6f6f7), U64(0x120e0e1c120e0e1c),
U64(0xa36161c2a36161c2), U64(0x5f35356a5f35356a),
U64(0xf95757aef95757ae), U64(0xd0b9b969d0b9b969),
U64(0x9186861791868617), U64(0x58c1c19958c1c199),
U64(0x271d1d3a271d1d3a), U64(0xb99e9e27b99e9e27),
U64(0x38e1e1d938e1e1d9), U64(0x13f8f8eb13f8f8eb),
U64(0xb398982bb398982b), U64(0x3311112233111122),
U64(0xbb6969d2bb6969d2), U64(0x70d9d9a970d9d9a9),
U64(0x898e8e07898e8e07), U64(0xa7949433a7949433),
U64(0xb69b9b2db69b9b2d), U64(0x221e1e3c221e1e3c),
U64(0x9287871592878715), U64(0x20e9e9c920e9e9c9),
U64(0x49cece8749cece87), U64(0xff5555aaff5555aa),
U64(0x7828285078282850), U64(0x7adfdfa57adfdfa5),
U64(0x8f8c8c038f8c8c03), U64(0xf8a1a159f8a1a159),
U64(0x8089890980898909), U64(0x170d0d1a170d0d1a),
U64(0xdabfbf65dabfbf65), U64(0x31e6e6d731e6e6d7),
U64(0xc6424284c6424284), U64(0xb86868d0b86868d0),
U64(0xc3414182c3414182), U64(0xb0999929b0999929),
U64(0x772d2d5a772d2d5a), U64(0x110f0f1e110f0f1e),
U64(0xcbb0b07bcbb0b07b), U64(0xfc5454a8fc5454a8),
U64(0xd6bbbb6dd6bbbb6d), U64(0x3a16162c3a16162c)
};
static const u8 Te4[256] = {
0x63U, 0x7cU, 0x77U, 0x7bU, 0xf2U, 0x6bU, 0x6fU, 0xc5U,
0x30U, 0x01U, 0x67U, 0x2bU, 0xfeU, 0xd7U, 0xabU, 0x76U,
0xcaU, 0x82U, 0xc9U, 0x7dU, 0xfaU, 0x59U, 0x47U, 0xf0U,
0xadU, 0xd4U, 0xa2U, 0xafU, 0x9cU, 0xa4U, 0x72U, 0xc0U,
0xb7U, 0xfdU, 0x93U, 0x26U, 0x36U, 0x3fU, 0xf7U, 0xccU,
0x34U, 0xa5U, 0xe5U, 0xf1U, 0x71U, 0xd8U, 0x31U, 0x15U,
0x04U, 0xc7U, 0x23U, 0xc3U, 0x18U, 0x96U, 0x05U, 0x9aU,
0x07U, 0x12U, 0x80U, 0xe2U, 0xebU, 0x27U, 0xb2U, 0x75U,
0x09U, 0x83U, 0x2cU, 0x1aU, 0x1bU, 0x6eU, 0x5aU, 0xa0U,
0x52U, 0x3bU, 0xd6U, 0xb3U, 0x29U, 0xe3U, 0x2fU, 0x84U,
0x53U, 0xd1U, 0x00U, 0xedU, 0x20U, 0xfcU, 0xb1U, 0x5bU,
0x6aU, 0xcbU, 0xbeU, 0x39U, 0x4aU, 0x4cU, 0x58U, 0xcfU,
0xd0U, 0xefU, 0xaaU, 0xfbU, 0x43U, 0x4dU, 0x33U, 0x85U,
0x45U, 0xf9U, 0x02U, 0x7fU, 0x50U, 0x3cU, 0x9fU, 0xa8U,
0x51U, 0xa3U, 0x40U, 0x8fU, 0x92U, 0x9dU, 0x38U, 0xf5U,
0xbcU, 0xb6U, 0xdaU, 0x21U, 0x10U, 0xffU, 0xf3U, 0xd2U,
0xcdU, 0x0cU, 0x13U, 0xecU, 0x5fU, 0x97U, 0x44U, 0x17U,
0xc4U, 0xa7U, 0x7eU, 0x3dU, 0x64U, 0x5dU, 0x19U, 0x73U,
0x60U, 0x81U, 0x4fU, 0xdcU, 0x22U, 0x2aU, 0x90U, 0x88U,
0x46U, 0xeeU, 0xb8U, 0x14U, 0xdeU, 0x5eU, 0x0bU, 0xdbU,
0xe0U, 0x32U, 0x3aU, 0x0aU, 0x49U, 0x06U, 0x24U, 0x5cU,
0xc2U, 0xd3U, 0xacU, 0x62U, 0x91U, 0x95U, 0xe4U, 0x79U,
0xe7U, 0xc8U, 0x37U, 0x6dU, 0x8dU, 0xd5U, 0x4eU, 0xa9U,
0x6cU, 0x56U, 0xf4U, 0xeaU, 0x65U, 0x7aU, 0xaeU, 0x08U,
0xbaU, 0x78U, 0x25U, 0x2eU, 0x1cU, 0xa6U, 0xb4U, 0xc6U,
0xe8U, 0xddU, 0x74U, 0x1fU, 0x4bU, 0xbdU, 0x8bU, 0x8aU,
0x70U, 0x3eU, 0xb5U, 0x66U, 0x48U, 0x03U, 0xf6U, 0x0eU,
0x61U, 0x35U, 0x57U, 0xb9U, 0x86U, 0xc1U, 0x1dU, 0x9eU,
0xe1U, 0xf8U, 0x98U, 0x11U, 0x69U, 0xd9U, 0x8eU, 0x94U,
0x9bU, 0x1eU, 0x87U, 0xe9U, 0xceU, 0x55U, 0x28U, 0xdfU,
0x8cU, 0xa1U, 0x89U, 0x0dU, 0xbfU, 0xe6U, 0x42U, 0x68U,
0x41U, 0x99U, 0x2dU, 0x0fU, 0xb0U, 0x54U, 0xbbU, 0x16U
};
static const u64 Td[256] = {
U64(0x50a7f45150a7f451), U64(0x5365417e5365417e),
U64(0xc3a4171ac3a4171a), U64(0x965e273a965e273a),
U64(0xcb6bab3bcb6bab3b), U64(0xf1459d1ff1459d1f),
U64(0xab58faacab58faac), U64(0x9303e34b9303e34b),
U64(0x55fa302055fa3020), U64(0xf66d76adf66d76ad),
U64(0x9176cc889176cc88), U64(0x254c02f5254c02f5),
U64(0xfcd7e54ffcd7e54f), U64(0xd7cb2ac5d7cb2ac5),
U64(0x8044352680443526), U64(0x8fa362b58fa362b5),
U64(0x495ab1de495ab1de), U64(0x671bba25671bba25),
U64(0x980eea45980eea45), U64(0xe1c0fe5de1c0fe5d),
U64(0x02752fc302752fc3), U64(0x12f04c8112f04c81),
U64(0xa397468da397468d), U64(0xc6f9d36bc6f9d36b),
U64(0xe75f8f03e75f8f03), U64(0x959c9215959c9215),
U64(0xeb7a6dbfeb7a6dbf), U64(0xda595295da595295),
U64(0x2d83bed42d83bed4), U64(0xd3217458d3217458),
U64(0x2969e0492969e049), U64(0x44c8c98e44c8c98e),
U64(0x6a89c2756a89c275), U64(0x78798ef478798ef4),
U64(0x6b3e58996b3e5899), U64(0xdd71b927dd71b927),
U64(0xb64fe1beb64fe1be), U64(0x17ad88f017ad88f0),
U64(0x66ac20c966ac20c9), U64(0xb43ace7db43ace7d),
U64(0x184adf63184adf63), U64(0x82311ae582311ae5),
U64(0x6033519760335197), U64(0x457f5362457f5362),
U64(0xe07764b1e07764b1), U64(0x84ae6bbb84ae6bbb),
U64(0x1ca081fe1ca081fe), U64(0x942b08f9942b08f9),
U64(0x5868487058684870), U64(0x19fd458f19fd458f),
U64(0x876cde94876cde94), U64(0xb7f87b52b7f87b52),
U64(0x23d373ab23d373ab), U64(0xe2024b72e2024b72),
U64(0x578f1fe3578f1fe3), U64(0x2aab55662aab5566),
U64(0x0728ebb20728ebb2), U64(0x03c2b52f03c2b52f),
U64(0x9a7bc5869a7bc586), U64(0xa50837d3a50837d3),
U64(0xf2872830f2872830), U64(0xb2a5bf23b2a5bf23),
U64(0xba6a0302ba6a0302), U64(0x5c8216ed5c8216ed),
U64(0x2b1ccf8a2b1ccf8a), U64(0x92b479a792b479a7),
U64(0xf0f207f3f0f207f3), U64(0xa1e2694ea1e2694e),
U64(0xcdf4da65cdf4da65), U64(0xd5be0506d5be0506),
U64(0x1f6234d11f6234d1), U64(0x8afea6c48afea6c4),
U64(0x9d532e349d532e34), U64(0xa055f3a2a055f3a2),
U64(0x32e18a0532e18a05), U64(0x75ebf6a475ebf6a4),
U64(0x39ec830b39ec830b), U64(0xaaef6040aaef6040),
U64(0x069f715e069f715e), U64(0x51106ebd51106ebd),
U64(0xf98a213ef98a213e), U64(0x3d06dd963d06dd96),
U64(0xae053eddae053edd), U64(0x46bde64d46bde64d),
U64(0xb58d5491b58d5491), U64(0x055dc471055dc471),
U64(0x6fd406046fd40604), U64(0xff155060ff155060),
U64(0x24fb981924fb9819), U64(0x97e9bdd697e9bdd6),
U64(0xcc434089cc434089), U64(0x779ed967779ed967),
U64(0xbd42e8b0bd42e8b0), U64(0x888b8907888b8907),
U64(0x385b19e7385b19e7), U64(0xdbeec879dbeec879),
U64(0x470a7ca1470a7ca1), U64(0xe90f427ce90f427c),
U64(0xc91e84f8c91e84f8), U64(0x0000000000000000),
U64(0x8386800983868009), U64(0x48ed2b3248ed2b32),
U64(0xac70111eac70111e), U64(0x4e725a6c4e725a6c),
U64(0xfbff0efdfbff0efd), U64(0x5638850f5638850f),
U64(0x1ed5ae3d1ed5ae3d), U64(0x27392d3627392d36),
U64(0x64d90f0a64d90f0a), U64(0x21a65c6821a65c68),
U64(0xd1545b9bd1545b9b), U64(0x3a2e36243a2e3624),
U64(0xb1670a0cb1670a0c), U64(0x0fe757930fe75793),
U64(0xd296eeb4d296eeb4), U64(0x9e919b1b9e919b1b),
U64(0x4fc5c0804fc5c080), U64(0xa220dc61a220dc61),
U64(0x694b775a694b775a), U64(0x161a121c161a121c),
U64(0x0aba93e20aba93e2), U64(0xe52aa0c0e52aa0c0),
U64(0x43e0223c43e0223c), U64(0x1d171b121d171b12),
U64(0x0b0d090e0b0d090e), U64(0xadc78bf2adc78bf2),
U64(0xb9a8b62db9a8b62d), U64(0xc8a91e14c8a91e14),
U64(0x8519f1578519f157), U64(0x4c0775af4c0775af),
U64(0xbbdd99eebbdd99ee), U64(0xfd607fa3fd607fa3),
U64(0x9f2601f79f2601f7), U64(0xbcf5725cbcf5725c),
U64(0xc53b6644c53b6644), U64(0x347efb5b347efb5b),
U64(0x7629438b7629438b), U64(0xdcc623cbdcc623cb),
U64(0x68fcedb668fcedb6), U64(0x63f1e4b863f1e4b8),
U64(0xcadc31d7cadc31d7), U64(0x1085634210856342),
U64(0x4022971340229713), U64(0x2011c6842011c684),
U64(0x7d244a857d244a85), U64(0xf83dbbd2f83dbbd2),
U64(0x1132f9ae1132f9ae), U64(0x6da129c76da129c7),
U64(0x4b2f9e1d4b2f9e1d), U64(0xf330b2dcf330b2dc),
U64(0xec52860dec52860d), U64(0xd0e3c177d0e3c177),
U64(0x6c16b32b6c16b32b), U64(0x99b970a999b970a9),
U64(0xfa489411fa489411), U64(0x2264e9472264e947),
U64(0xc48cfca8c48cfca8), U64(0x1a3ff0a01a3ff0a0),
U64(0xd82c7d56d82c7d56), U64(0xef903322ef903322),
U64(0xc74e4987c74e4987), U64(0xc1d138d9c1d138d9),
U64(0xfea2ca8cfea2ca8c), U64(0x360bd498360bd498),
U64(0xcf81f5a6cf81f5a6), U64(0x28de7aa528de7aa5),
U64(0x268eb7da268eb7da), U64(0xa4bfad3fa4bfad3f),
U64(0xe49d3a2ce49d3a2c), U64(0x0d9278500d927850),
U64(0x9bcc5f6a9bcc5f6a), U64(0x62467e5462467e54),
U64(0xc2138df6c2138df6), U64(0xe8b8d890e8b8d890),
U64(0x5ef7392e5ef7392e), U64(0xf5afc382f5afc382),
U64(0xbe805d9fbe805d9f), U64(0x7c93d0697c93d069),
U64(0xa92dd56fa92dd56f), U64(0xb31225cfb31225cf),
U64(0x3b99acc83b99acc8), U64(0xa77d1810a77d1810),
U64(0x6e639ce86e639ce8), U64(0x7bbb3bdb7bbb3bdb),
U64(0x097826cd097826cd), U64(0xf418596ef418596e),
U64(0x01b79aec01b79aec), U64(0xa89a4f83a89a4f83),
U64(0x656e95e6656e95e6), U64(0x7ee6ffaa7ee6ffaa),
U64(0x08cfbc2108cfbc21), U64(0xe6e815efe6e815ef),
U64(0xd99be7bad99be7ba), U64(0xce366f4ace366f4a),
U64(0xd4099fead4099fea), U64(0xd67cb029d67cb029),
U64(0xafb2a431afb2a431), U64(0x31233f2a31233f2a),
U64(0x3094a5c63094a5c6), U64(0xc066a235c066a235),
U64(0x37bc4e7437bc4e74), U64(0xa6ca82fca6ca82fc),
U64(0xb0d090e0b0d090e0), U64(0x15d8a73315d8a733),
U64(0x4a9804f14a9804f1), U64(0xf7daec41f7daec41),
U64(0x0e50cd7f0e50cd7f), U64(0x2ff691172ff69117),
U64(0x8dd64d768dd64d76), U64(0x4db0ef434db0ef43),
U64(0x544daacc544daacc), U64(0xdf0496e4df0496e4),
U64(0xe3b5d19ee3b5d19e), U64(0x1b886a4c1b886a4c),
U64(0xb81f2cc1b81f2cc1), U64(0x7f5165467f516546),
U64(0x04ea5e9d04ea5e9d), U64(0x5d358c015d358c01),
U64(0x737487fa737487fa), U64(0x2e410bfb2e410bfb),
U64(0x5a1d67b35a1d67b3), U64(0x52d2db9252d2db92),
U64(0x335610e9335610e9), U64(0x1347d66d1347d66d),
U64(0x8c61d79a8c61d79a), U64(0x7a0ca1377a0ca137),
U64(0x8e14f8598e14f859), U64(0x893c13eb893c13eb),
U64(0xee27a9ceee27a9ce), U64(0x35c961b735c961b7),
U64(0xede51ce1ede51ce1), U64(0x3cb1477a3cb1477a),
U64(0x59dfd29c59dfd29c), U64(0x3f73f2553f73f255),
U64(0x79ce141879ce1418), U64(0xbf37c773bf37c773),
U64(0xeacdf753eacdf753), U64(0x5baafd5f5baafd5f),
U64(0x146f3ddf146f3ddf), U64(0x86db447886db4478),
U64(0x81f3afca81f3afca), U64(0x3ec468b93ec468b9),
U64(0x2c3424382c342438), U64(0x5f40a3c25f40a3c2),
U64(0x72c31d1672c31d16), U64(0x0c25e2bc0c25e2bc),
U64(0x8b493c288b493c28), U64(0x41950dff41950dff),
U64(0x7101a8397101a839), U64(0xdeb30c08deb30c08),
U64(0x9ce4b4d89ce4b4d8), U64(0x90c1566490c15664),
U64(0x6184cb7b6184cb7b), U64(0x70b632d570b632d5),
U64(0x745c6c48745c6c48), U64(0x4257b8d04257b8d0)
};
static const u8 Td4[256] = {
0x52U, 0x09U, 0x6aU, 0xd5U, 0x30U, 0x36U, 0xa5U, 0x38U,
0xbfU, 0x40U, 0xa3U, 0x9eU, 0x81U, 0xf3U, 0xd7U, 0xfbU,
0x7cU, 0xe3U, 0x39U, 0x82U, 0x9bU, 0x2fU, 0xffU, 0x87U,
0x34U, 0x8eU, 0x43U, 0x44U, 0xc4U, 0xdeU, 0xe9U, 0xcbU,
0x54U, 0x7bU, 0x94U, 0x32U, 0xa6U, 0xc2U, 0x23U, 0x3dU,
0xeeU, 0x4cU, 0x95U, 0x0bU, 0x42U, 0xfaU, 0xc3U, 0x4eU,
0x08U, 0x2eU, 0xa1U, 0x66U, 0x28U, 0xd9U, 0x24U, 0xb2U,
0x76U, 0x5bU, 0xa2U, 0x49U, 0x6dU, 0x8bU, 0xd1U, 0x25U,
0x72U, 0xf8U, 0xf6U, 0x64U, 0x86U, 0x68U, 0x98U, 0x16U,
0xd4U, 0xa4U, 0x5cU, 0xccU, 0x5dU, 0x65U, 0xb6U, 0x92U,
0x6cU, 0x70U, 0x48U, 0x50U, 0xfdU, 0xedU, 0xb9U, 0xdaU,
0x5eU, 0x15U, 0x46U, 0x57U, 0xa7U, 0x8dU, 0x9dU, 0x84U,
0x90U, 0xd8U, 0xabU, 0x00U, 0x8cU, 0xbcU, 0xd3U, 0x0aU,
0xf7U, 0xe4U, 0x58U, 0x05U, 0xb8U, 0xb3U, 0x45U, 0x06U,
0xd0U, 0x2cU, 0x1eU, 0x8fU, 0xcaU, 0x3fU, 0x0fU, 0x02U,
0xc1U, 0xafU, 0xbdU, 0x03U, 0x01U, 0x13U, 0x8aU, 0x6bU,
0x3aU, 0x91U, 0x11U, 0x41U, 0x4fU, 0x67U, 0xdcU, 0xeaU,
0x97U, 0xf2U, 0xcfU, 0xceU, 0xf0U, 0xb4U, 0xe6U, 0x73U,
0x96U, 0xacU, 0x74U, 0x22U, 0xe7U, 0xadU, 0x35U, 0x85U,
0xe2U, 0xf9U, 0x37U, 0xe8U, 0x1cU, 0x75U, 0xdfU, 0x6eU,
0x47U, 0xf1U, 0x1aU, 0x71U, 0x1dU, 0x29U, 0xc5U, 0x89U,
0x6fU, 0xb7U, 0x62U, 0x0eU, 0xaaU, 0x18U, 0xbeU, 0x1bU,
0xfcU, 0x56U, 0x3eU, 0x4bU, 0xc6U, 0xd2U, 0x79U, 0x20U,
0x9aU, 0xdbU, 0xc0U, 0xfeU, 0x78U, 0xcdU, 0x5aU, 0xf4U,
0x1fU, 0xddU, 0xa8U, 0x33U, 0x88U, 0x07U, 0xc7U, 0x31U,
0xb1U, 0x12U, 0x10U, 0x59U, 0x27U, 0x80U, 0xecU, 0x5fU,
0x60U, 0x51U, 0x7fU, 0xa9U, 0x19U, 0xb5U, 0x4aU, 0x0dU,
0x2dU, 0xe5U, 0x7aU, 0x9fU, 0x93U, 0xc9U, 0x9cU, 0xefU,
0xa0U, 0xe0U, 0x3bU, 0x4dU, 0xaeU, 0x2aU, 0xf5U, 0xb0U,
0xc8U, 0xebU, 0xbbU, 0x3cU, 0x83U, 0x53U, 0x99U, 0x61U,
0x17U, 0x2bU, 0x04U, 0x7eU, 0xbaU, 0x77U, 0xd6U, 0x26U,
0xe1U, 0x69U, 0x14U, 0x63U, 0x55U, 0x21U, 0x0cU, 0x7dU
};
static const u32 rcon[] = {
0x00000001U, 0x00000002U, 0x00000004U, 0x00000008U,
0x00000010U, 0x00000020U, 0x00000040U, 0x00000080U,
0x0000001bU, 0x00000036U, /* for 128-bit blocks, Rijndael never uses more than 10 rcon values */
};
/**
* Expand the cipher key into the encryption key schedule.
*/
int AES_set_encrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key)
{
u32 *rk;
int i = 0;
u32 temp;
if (!userKey || !key)
return -1;
if (bits != 128 && bits != 192 && bits != 256)
return -2;
rk = key->rd_key;
if (bits==128)
key->rounds = 10;
else if (bits==192)
key->rounds = 12;
else
key->rounds = 14;
rk[0] = GETU32(userKey );
rk[1] = GETU32(userKey + 4);
rk[2] = GETU32(userKey + 8);
rk[3] = GETU32(userKey + 12);
if (bits == 128) {
while (1) {
temp = rk[3];
rk[4] = rk[0] ^
((u32)Te4[(temp >> 8) & 0xff] ) ^
((u32)Te4[(temp >> 16) & 0xff] << 8) ^
((u32)Te4[(temp >> 24) ] << 16) ^
((u32)Te4[(temp ) & 0xff] << 24) ^
rcon[i];
rk[5] = rk[1] ^ rk[4];
rk[6] = rk[2] ^ rk[5];
rk[7] = rk[3] ^ rk[6];
if (++i == 10) {
return 0;
}
rk += 4;
}
}
rk[4] = GETU32(userKey + 16);
rk[5] = GETU32(userKey + 20);
if (bits == 192) {
while (1) {
temp = rk[ 5];
rk[ 6] = rk[ 0] ^
((u32)Te4[(temp >> 8) & 0xff] ) ^
((u32)Te4[(temp >> 16) & 0xff] << 8) ^
((u32)Te4[(temp >> 24) ] << 16) ^
((u32)Te4[(temp ) & 0xff] << 24) ^
rcon[i];
rk[ 7] = rk[ 1] ^ rk[ 6];
rk[ 8] = rk[ 2] ^ rk[ 7];
rk[ 9] = rk[ 3] ^ rk[ 8];
if (++i == 8) {
return 0;
}
rk[10] = rk[ 4] ^ rk[ 9];
rk[11] = rk[ 5] ^ rk[10];
rk += 6;
}
}
rk[6] = GETU32(userKey + 24);
rk[7] = GETU32(userKey + 28);
if (bits == 256) {
while (1) {
temp = rk[ 7];
rk[ 8] = rk[ 0] ^
((u32)Te4[(temp >> 8) & 0xff] ) ^
((u32)Te4[(temp >> 16) & 0xff] << 8) ^
((u32)Te4[(temp >> 24) ] << 16) ^
((u32)Te4[(temp ) & 0xff] << 24) ^
rcon[i];
rk[ 9] = rk[ 1] ^ rk[ 8];
rk[10] = rk[ 2] ^ rk[ 9];
rk[11] = rk[ 3] ^ rk[10];
if (++i == 7) {
return 0;
}
temp = rk[11];
rk[12] = rk[ 4] ^
((u32)Te4[(temp ) & 0xff] ) ^
((u32)Te4[(temp >> 8) & 0xff] << 8) ^
((u32)Te4[(temp >> 16) & 0xff] << 16) ^
((u32)Te4[(temp >> 24) ] << 24);
rk[13] = rk[ 5] ^ rk[12];
rk[14] = rk[ 6] ^ rk[13];
rk[15] = rk[ 7] ^ rk[14];
rk += 8;
}
}
return 0;
}
/**
* Expand the cipher key into the decryption key schedule.
*/
int AES_set_decrypt_key(const unsigned char *userKey, const int bits,
AES_KEY *key)
{
u32 *rk;
int i, j, status;
u32 temp;
/* first, start with an encryption schedule */
status = AES_set_encrypt_key(userKey, bits, key);
if (status < 0)
return status;
rk = key->rd_key;
/* invert the order of the round keys: */
for (i = 0, j = 4*(key->rounds); i < j; i += 4, j -= 4) {
temp = rk[i ]; rk[i ] = rk[j ]; rk[j ] = temp;
temp = rk[i + 1]; rk[i + 1] = rk[j + 1]; rk[j + 1] = temp;
temp = rk[i + 2]; rk[i + 2] = rk[j + 2]; rk[j + 2] = temp;
temp = rk[i + 3]; rk[i + 3] = rk[j + 3]; rk[j + 3] = temp;
}
/* apply the inverse MixColumn transform to all round keys but the first and the last: */
for (i = 1; i < (key->rounds); i++) {
rk += 4;
#if 1
for (j = 0; j < 4; j++) {
u32 tp1, tp2, tp4, tp8, tp9, tpb, tpd, tpe, m;
tp1 = rk[j];
m = tp1 & 0x80808080;
tp2 = ((tp1 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp2 & 0x80808080;
tp4 = ((tp2 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp4 & 0x80808080;
tp8 = ((tp4 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
tp9 = tp8 ^ tp1;
tpb = tp9 ^ tp2;
tpd = tp9 ^ tp4;
tpe = tp8 ^ tp4 ^ tp2;
#if defined(ROTATE)
rk[j] = tpe ^ ROTATE(tpd,16) ^
ROTATE(tp9,8) ^ ROTATE(tpb,24);
#else
rk[j] = tpe ^ (tpd >> 16) ^ (tpd << 16) ^
(tp9 >> 24) ^ (tp9 << 8) ^
(tpb >> 8) ^ (tpb << 24);
#endif
}
#else
rk[0] =
Td0[Te2[(rk[0] ) & 0xff] & 0xff] ^
Td1[Te2[(rk[0] >> 8) & 0xff] & 0xff] ^
Td2[Te2[(rk[0] >> 16) & 0xff] & 0xff] ^
Td3[Te2[(rk[0] >> 24) ] & 0xff];
rk[1] =
Td0[Te2[(rk[1] ) & 0xff] & 0xff] ^
Td1[Te2[(rk[1] >> 8) & 0xff] & 0xff] ^
Td2[Te2[(rk[1] >> 16) & 0xff] & 0xff] ^
Td3[Te2[(rk[1] >> 24) ] & 0xff];
rk[2] =
Td0[Te2[(rk[2] ) & 0xff] & 0xff] ^
Td1[Te2[(rk[2] >> 8) & 0xff] & 0xff] ^
Td2[Te2[(rk[2] >> 16) & 0xff] & 0xff] ^
Td3[Te2[(rk[2] >> 24) ] & 0xff];
rk[3] =
Td0[Te2[(rk[3] ) & 0xff] & 0xff] ^
Td1[Te2[(rk[3] >> 8) & 0xff] & 0xff] ^
Td2[Te2[(rk[3] >> 16) & 0xff] & 0xff] ^
Td3[Te2[(rk[3] >> 24) ] & 0xff];
#endif
}
return 0;
}
/*
* Encrypt a single block
* in and out can overlap
*/
void AES_encrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key)
{
const u32 *rk;
u32 s0, s1, s2, s3, t[4];
int r;
assert(in && out && key);
rk = key->rd_key;
/*
* map byte array block to cipher state
* and add initial round key:
*/
s0 = GETU32(in ) ^ rk[0];
s1 = GETU32(in + 4) ^ rk[1];
s2 = GETU32(in + 8) ^ rk[2];
s3 = GETU32(in + 12) ^ rk[3];
#if defined(AES_COMPACT_IN_OUTER_ROUNDS)
prefetch256(Te4);
t[0] = (u32)Te4[(s0 ) & 0xff] ^
(u32)Te4[(s1 >> 8) & 0xff] << 8 ^
(u32)Te4[(s2 >> 16) & 0xff] << 16 ^
(u32)Te4[(s3 >> 24) ] << 24;
t[1] = (u32)Te4[(s1 ) & 0xff] ^
(u32)Te4[(s2 >> 8) & 0xff] << 8 ^
(u32)Te4[(s3 >> 16) & 0xff] << 16 ^
(u32)Te4[(s0 >> 24) ] << 24;
t[2] = (u32)Te4[(s2 ) & 0xff] ^
(u32)Te4[(s3 >> 8) & 0xff] << 8 ^
(u32)Te4[(s0 >> 16) & 0xff] << 16 ^
(u32)Te4[(s1 >> 24) ] << 24;
t[3] = (u32)Te4[(s3 ) & 0xff] ^
(u32)Te4[(s0 >> 8) & 0xff] << 8 ^
(u32)Te4[(s1 >> 16) & 0xff] << 16 ^
(u32)Te4[(s2 >> 24) ] << 24;
/* now do the linear transform using words */
{ int i;
u32 r0, r1, r2;
for (i = 0; i < 4; i++) {
r0 = t[i];
r1 = r0 & 0x80808080;
r2 = ((r0 & 0x7f7f7f7f) << 1) ^
((r1 - (r1 >> 7)) & 0x1b1b1b1b);
#if defined(ROTATE)
t[i] = r2 ^ ROTATE(r2,24) ^ ROTATE(r0,24) ^
ROTATE(r0,16) ^ ROTATE(r0,8);
#else
t[i] = r2 ^ ((r2 ^ r0) << 24) ^ ((r2 ^ r0) >> 8) ^
(r0 << 16) ^ (r0 >> 16) ^
(r0 << 8) ^ (r0 >> 24);
#endif
t[i] ^= rk[4+i];
}
}
#else
t[0] = Te0[(s0 ) & 0xff] ^
Te1[(s1 >> 8) & 0xff] ^
Te2[(s2 >> 16) & 0xff] ^
Te3[(s3 >> 24) ] ^
rk[4];
t[1] = Te0[(s1 ) & 0xff] ^
Te1[(s2 >> 8) & 0xff] ^
Te2[(s3 >> 16) & 0xff] ^
Te3[(s0 >> 24) ] ^
rk[5];
t[2] = Te0[(s2 ) & 0xff] ^
Te1[(s3 >> 8) & 0xff] ^
Te2[(s0 >> 16) & 0xff] ^
Te3[(s1 >> 24) ] ^
rk[6];
t[3] = Te0[(s3 ) & 0xff] ^
Te1[(s0 >> 8) & 0xff] ^
Te2[(s1 >> 16) & 0xff] ^
Te3[(s2 >> 24) ] ^
rk[7];
#endif
s0 = t[0]; s1 = t[1]; s2 = t[2]; s3 = t[3];
/*
* Nr - 2 full rounds:
*/
for (rk+=8,r=key->rounds-2; r>0; rk+=4,r--) {
#if defined(AES_COMPACT_IN_INNER_ROUNDS)
t[0] = (u32)Te4[(s0 ) & 0xff] ^
(u32)Te4[(s1 >> 8) & 0xff] << 8 ^
(u32)Te4[(s2 >> 16) & 0xff] << 16 ^
(u32)Te4[(s3 >> 24) ] << 24;
t[1] = (u32)Te4[(s1 ) & 0xff] ^
(u32)Te4[(s2 >> 8) & 0xff] << 8 ^
(u32)Te4[(s3 >> 16) & 0xff] << 16 ^
(u32)Te4[(s0 >> 24) ] << 24;
t[2] = (u32)Te4[(s2 ) & 0xff] ^
(u32)Te4[(s3 >> 8) & 0xff] << 8 ^
(u32)Te4[(s0 >> 16) & 0xff] << 16 ^
(u32)Te4[(s1 >> 24) ] << 24;
t[3] = (u32)Te4[(s3 ) & 0xff] ^
(u32)Te4[(s0 >> 8) & 0xff] << 8 ^
(u32)Te4[(s1 >> 16) & 0xff] << 16 ^
(u32)Te4[(s2 >> 24) ] << 24;
/* now do the linear transform using words */
{
int i;
u32 r0, r1, r2;
for (i = 0; i < 4; i++) {
r0 = t[i];
r1 = r0 & 0x80808080;
r2 = ((r0 & 0x7f7f7f7f) << 1) ^
((r1 - (r1 >> 7)) & 0x1b1b1b1b);
#if defined(ROTATE)
t[i] = r2 ^ ROTATE(r2,24) ^ ROTATE(r0,24) ^
ROTATE(r0,16) ^ ROTATE(r0,8);
#else
t[i] = r2 ^ ((r2 ^ r0) << 24) ^ ((r2 ^ r0) >> 8) ^
(r0 << 16) ^ (r0 >> 16) ^
(r0 << 8) ^ (r0 >> 24);
#endif
t[i] ^= rk[i];
}
}
#else
t[0] = Te0[(s0 ) & 0xff] ^
Te1[(s1 >> 8) & 0xff] ^
Te2[(s2 >> 16) & 0xff] ^
Te3[(s3 >> 24) ] ^
rk[0];
t[1] = Te0[(s1 ) & 0xff] ^
Te1[(s2 >> 8) & 0xff] ^
Te2[(s3 >> 16) & 0xff] ^
Te3[(s0 >> 24) ] ^
rk[1];
t[2] = Te0[(s2 ) & 0xff] ^
Te1[(s3 >> 8) & 0xff] ^
Te2[(s0 >> 16) & 0xff] ^
Te3[(s1 >> 24) ] ^
rk[2];
t[3] = Te0[(s3 ) & 0xff] ^
Te1[(s0 >> 8) & 0xff] ^
Te2[(s1 >> 16) & 0xff] ^
Te3[(s2 >> 24) ] ^
rk[3];
#endif
s0 = t[0]; s1 = t[1]; s2 = t[2]; s3 = t[3];
}
/*
* apply last round and
* map cipher state to byte array block:
*/
#if defined(AES_COMPACT_IN_OUTER_ROUNDS)
prefetch256(Te4);
*(u32*)(out+0) =
(u32)Te4[(s0 ) & 0xff] ^
(u32)Te4[(s1 >> 8) & 0xff] << 8 ^
(u32)Te4[(s2 >> 16) & 0xff] << 16 ^
(u32)Te4[(s3 >> 24) ] << 24 ^
rk[0];
*(u32*)(out+4) =
(u32)Te4[(s1 ) & 0xff] ^
(u32)Te4[(s2 >> 8) & 0xff] << 8 ^
(u32)Te4[(s3 >> 16) & 0xff] << 16 ^
(u32)Te4[(s0 >> 24) ] << 24 ^
rk[1];
*(u32*)(out+8) =
(u32)Te4[(s2 ) & 0xff] ^
(u32)Te4[(s3 >> 8) & 0xff] << 8 ^
(u32)Te4[(s0 >> 16) & 0xff] << 16 ^
(u32)Te4[(s1 >> 24) ] << 24 ^
rk[2];
*(u32*)(out+12) =
(u32)Te4[(s3 ) & 0xff] ^
(u32)Te4[(s0 >> 8) & 0xff] << 8 ^
(u32)Te4[(s1 >> 16) & 0xff] << 16 ^
(u32)Te4[(s2 >> 24) ] << 24 ^
rk[3];
#else
*(u32*)(out+0) =
(Te2[(s0 ) & 0xff] & 0x000000ffU) ^
(Te3[(s1 >> 8) & 0xff] & 0x0000ff00U) ^
(Te0[(s2 >> 16) & 0xff] & 0x00ff0000U) ^
(Te1[(s3 >> 24) ] & 0xff000000U) ^
rk[0];
*(u32*)(out+4) =
(Te2[(s1 ) & 0xff] & 0x000000ffU) ^
(Te3[(s2 >> 8) & 0xff] & 0x0000ff00U) ^
(Te0[(s3 >> 16) & 0xff] & 0x00ff0000U) ^
(Te1[(s0 >> 24) ] & 0xff000000U) ^
rk[1];
*(u32*)(out+8) =
(Te2[(s2 ) & 0xff] & 0x000000ffU) ^
(Te3[(s3 >> 8) & 0xff] & 0x0000ff00U) ^
(Te0[(s0 >> 16) & 0xff] & 0x00ff0000U) ^
(Te1[(s1 >> 24) ] & 0xff000000U) ^
rk[2];
*(u32*)(out+12) =
(Te2[(s3 ) & 0xff] & 0x000000ffU) ^
(Te3[(s0 >> 8) & 0xff] & 0x0000ff00U) ^
(Te0[(s1 >> 16) & 0xff] & 0x00ff0000U) ^
(Te1[(s2 >> 24) ] & 0xff000000U) ^
rk[3];
#endif
}
/*
* Decrypt a single block
* in and out can overlap
*/
void AES_decrypt(const unsigned char *in, unsigned char *out,
const AES_KEY *key)
{
const u32 *rk;
u32 s0, s1, s2, s3, t[4];
int r;
assert(in && out && key);
rk = key->rd_key;
/*
* map byte array block to cipher state
* and add initial round key:
*/
s0 = GETU32(in ) ^ rk[0];
s1 = GETU32(in + 4) ^ rk[1];
s2 = GETU32(in + 8) ^ rk[2];
s3 = GETU32(in + 12) ^ rk[3];
#if defined(AES_COMPACT_IN_OUTER_ROUNDS)
prefetch256(Td4);
t[0] = (u32)Td4[(s0 ) & 0xff] ^
(u32)Td4[(s3 >> 8) & 0xff] << 8 ^
(u32)Td4[(s2 >> 16) & 0xff] << 16 ^
(u32)Td4[(s1 >> 24) ] << 24;
t[1] = (u32)Td4[(s1 ) & 0xff] ^
(u32)Td4[(s0 >> 8) & 0xff] << 8 ^
(u32)Td4[(s3 >> 16) & 0xff] << 16 ^
(u32)Td4[(s2 >> 24) ] << 24;
t[2] = (u32)Td4[(s2 ) & 0xff] ^
(u32)Td4[(s1 >> 8) & 0xff] << 8 ^
(u32)Td4[(s0 >> 16) & 0xff] << 16 ^
(u32)Td4[(s3 >> 24) ] << 24;
t[3] = (u32)Td4[(s3 ) & 0xff] ^
(u32)Td4[(s2 >> 8) & 0xff] << 8 ^
(u32)Td4[(s1 >> 16) & 0xff] << 16 ^
(u32)Td4[(s0 >> 24) ] << 24;
/* now do the linear transform using words */
{
int i;
u32 tp1, tp2, tp4, tp8, tp9, tpb, tpd, tpe, m;
for (i = 0; i < 4; i++) {
tp1 = t[i];
m = tp1 & 0x80808080;
tp2 = ((tp1 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp2 & 0x80808080;
tp4 = ((tp2 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp4 & 0x80808080;
tp8 = ((tp4 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
tp9 = tp8 ^ tp1;
tpb = tp9 ^ tp2;
tpd = tp9 ^ tp4;
tpe = tp8 ^ tp4 ^ tp2;
#if defined(ROTATE)
t[i] = tpe ^ ROTATE(tpd,16) ^
ROTATE(tp9,8) ^ ROTATE(tpb,24);
#else
t[i] = tpe ^ (tpd >> 16) ^ (tpd << 16) ^
(tp9 >> 24) ^ (tp9 << 8) ^
(tpb >> 8) ^ (tpb << 24);
#endif
t[i] ^= rk[4+i];
}
}
#else
t[0] = Td0[(s0 ) & 0xff] ^
Td1[(s3 >> 8) & 0xff] ^
Td2[(s2 >> 16) & 0xff] ^
Td3[(s1 >> 24) ] ^
rk[4];
t[1] = Td0[(s1 ) & 0xff] ^
Td1[(s0 >> 8) & 0xff] ^
Td2[(s3 >> 16) & 0xff] ^
Td3[(s2 >> 24) ] ^
rk[5];
t[2] = Td0[(s2 ) & 0xff] ^
Td1[(s1 >> 8) & 0xff] ^
Td2[(s0 >> 16) & 0xff] ^
Td3[(s3 >> 24) ] ^
rk[6];
t[3] = Td0[(s3 ) & 0xff] ^
Td1[(s2 >> 8) & 0xff] ^
Td2[(s1 >> 16) & 0xff] ^
Td3[(s0 >> 24) ] ^
rk[7];
#endif
s0 = t[0]; s1 = t[1]; s2 = t[2]; s3 = t[3];
/*
* Nr - 2 full rounds:
*/
for (rk+=8,r=key->rounds-2; r>0; rk+=4,r--) {
#if defined(AES_COMPACT_IN_INNER_ROUNDS)
t[0] = (u32)Td4[(s0 ) & 0xff] ^
(u32)Td4[(s3 >> 8) & 0xff] << 8 ^
(u32)Td4[(s2 >> 16) & 0xff] << 16 ^
(u32)Td4[(s1 >> 24) ] << 24;
t[1] = (u32)Td4[(s1 ) & 0xff] ^
(u32)Td4[(s0 >> 8) & 0xff] << 8 ^
(u32)Td4[(s3 >> 16) & 0xff] << 16 ^
(u32)Td4[(s2 >> 24) ] << 24;
t[2] = (u32)Td4[(s2 ) & 0xff] ^
(u32)Td4[(s1 >> 8) & 0xff] << 8 ^
(u32)Td4[(s0 >> 16) & 0xff] << 16 ^
(u32)Td4[(s3 >> 24) ] << 24;
t[3] = (u32)Td4[(s3 ) & 0xff] ^
(u32)Td4[(s2 >> 8) & 0xff] << 8 ^
(u32)Td4[(s1 >> 16) & 0xff] << 16 ^
(u32)Td4[(s0 >> 24) ] << 24;
/* now do the linear transform using words */
{
int i;
u32 tp1, tp2, tp4, tp8, tp9, tpb, tpd, tpe, m;
for (i = 0; i < 4; i++) {
tp1 = t[i];
m = tp1 & 0x80808080;
tp2 = ((tp1 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp2 & 0x80808080;
tp4 = ((tp2 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
m = tp4 & 0x80808080;
tp8 = ((tp4 & 0x7f7f7f7f) << 1) ^
((m - (m >> 7)) & 0x1b1b1b1b);
tp9 = tp8 ^ tp1;
tpb = tp9 ^ tp2;
tpd = tp9 ^ tp4;
tpe = tp8 ^ tp4 ^ tp2;
#if defined(ROTATE)
t[i] = tpe ^ ROTATE(tpd,16) ^
ROTATE(tp9,8) ^ ROTATE(tpb,24);
#else
t[i] = tpe ^ (tpd >> 16) ^ (tpd << 16) ^
(tp9 >> 24) ^ (tp9 << 8) ^
(tpb >> 8) ^ (tpb << 24);
#endif
t[i] ^= rk[i];
}
}
#else
t[0] = Td0[(s0 ) & 0xff] ^
Td1[(s3 >> 8) & 0xff] ^
Td2[(s2 >> 16) & 0xff] ^
Td3[(s1 >> 24) ] ^
rk[0];
t[1] = Td0[(s1 ) & 0xff] ^
Td1[(s0 >> 8) & 0xff] ^
Td2[(s3 >> 16) & 0xff] ^
Td3[(s2 >> 24) ] ^
rk[1];
t[2] = Td0[(s2 ) & 0xff] ^
Td1[(s1 >> 8) & 0xff] ^
Td2[(s0 >> 16) & 0xff] ^
Td3[(s3 >> 24) ] ^
rk[2];
t[3] = Td0[(s3 ) & 0xff] ^
Td1[(s2 >> 8) & 0xff] ^
Td2[(s1 >> 16) & 0xff] ^
Td3[(s0 >> 24) ] ^
rk[3];
#endif
s0 = t[0]; s1 = t[1]; s2 = t[2]; s3 = t[3];
}
/*
* apply last round and
* map cipher state to byte array block:
*/
prefetch256(Td4);
*(u32*)(out+0) =
((u32)Td4[(s0 ) & 0xff]) ^
((u32)Td4[(s3 >> 8) & 0xff] << 8) ^
((u32)Td4[(s2 >> 16) & 0xff] << 16) ^
((u32)Td4[(s1 >> 24) ] << 24) ^
rk[0];
*(u32*)(out+4) =
((u32)Td4[(s1 ) & 0xff]) ^
((u32)Td4[(s0 >> 8) & 0xff] << 8) ^
((u32)Td4[(s3 >> 16) & 0xff] << 16) ^
((u32)Td4[(s2 >> 24) ] << 24) ^
rk[1];
*(u32*)(out+8) =
((u32)Td4[(s2 ) & 0xff]) ^
((u32)Td4[(s1 >> 8) & 0xff] << 8) ^
((u32)Td4[(s0 >> 16) & 0xff] << 16) ^
((u32)Td4[(s3 >> 24) ] << 24) ^
rk[2];
*(u32*)(out+12) =
((u32)Td4[(s3 ) & 0xff]) ^
((u32)Td4[(s2 >> 8) & 0xff] << 8) ^
((u32)Td4[(s1 >> 16) & 0xff] << 16) ^
((u32)Td4[(s0 >> 24) ] << 24) ^
rk[3];
}
|
./openssl/crypto/aes/aes_cbc.c | /*
* Copyright 2002-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
*/
/*
* AES low level APIs are deprecated for public use, but still ok for internal
* use where we're using them to implement the higher level EVP interface, as is
* the case here.
*/
#include "internal/deprecated.h"
#include <openssl/aes.h>
#include <openssl/modes.h>
void AES_cbc_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const AES_KEY *key,
unsigned char *ivec, const int enc)
{
if (enc)
CRYPTO_cbc128_encrypt(in, out, len, key, ivec,
(block128_f) AES_encrypt);
else
CRYPTO_cbc128_decrypt(in, out, len, key, ivec,
(block128_f) AES_decrypt);
}
|
./openssl/crypto/modes/cfb128.c | /*
* Copyright 2008-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/crypto.h>
#include "crypto/modes.h"
#if defined(__GNUC__) && !defined(STRICT_ALIGNMENT)
typedef size_t size_t_aX __attribute((__aligned__(1)));
#else
typedef size_t size_t_aX;
#endif
/*
* The input and output encrypted as though 128bit cfb mode is being used.
* The extra state information to record how much of the 128bit block we have
* used is contained in *num;
*/
void CRYPTO_cfb128_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
unsigned char ivec[16], int *num,
int enc, block128_f block)
{
unsigned int n;
size_t l = 0;
if (*num < 0) {
/* There is no good way to signal an error return from here */
*num = -1;
return;
}
n = *num;
if (enc) {
#if !defined(OPENSSL_SMALL_FOOTPRINT)
if (16 % sizeof(size_t) == 0) { /* always true actually */
do {
while (n && len) {
*(out++) = ivec[n] ^= *(in++);
--len;
n = (n + 1) % 16;
}
# if defined(STRICT_ALIGNMENT)
if (((size_t)in | (size_t)out | (size_t)ivec) %
sizeof(size_t) != 0)
break;
# endif
while (len >= 16) {
(*block) (ivec, ivec, key);
for (; n < 16; n += sizeof(size_t)) {
*(size_t_aX *)(out + n) =
*(size_t_aX *)(ivec + n)
^= *(size_t_aX *)(in + n);
}
len -= 16;
out += 16;
in += 16;
n = 0;
}
if (len) {
(*block) (ivec, ivec, key);
while (len--) {
out[n] = ivec[n] ^= in[n];
++n;
}
}
*num = n;
return;
} while (0);
}
/* the rest would be commonly eliminated by x86* compiler */
#endif
while (l < len) {
if (n == 0) {
(*block) (ivec, ivec, key);
}
out[l] = ivec[n] ^= in[l];
++l;
n = (n + 1) % 16;
}
*num = n;
} else {
#if !defined(OPENSSL_SMALL_FOOTPRINT)
if (16 % sizeof(size_t) == 0) { /* always true actually */
do {
while (n && len) {
unsigned char c;
*(out++) = ivec[n] ^ (c = *(in++));
ivec[n] = c;
--len;
n = (n + 1) % 16;
}
# if defined(STRICT_ALIGNMENT)
if (((size_t)in | (size_t)out | (size_t)ivec) %
sizeof(size_t) != 0)
break;
# endif
while (len >= 16) {
(*block) (ivec, ivec, key);
for (; n < 16; n += sizeof(size_t)) {
size_t t = *(size_t_aX *)(in + n);
*(size_t_aX *)(out + n)
= *(size_t_aX *)(ivec + n) ^ t;
*(size_t_aX *)(ivec + n) = t;
}
len -= 16;
out += 16;
in += 16;
n = 0;
}
if (len) {
(*block) (ivec, ivec, key);
while (len--) {
unsigned char c;
out[n] = ivec[n] ^ (c = in[n]);
ivec[n] = c;
++n;
}
}
*num = n;
return;
} while (0);
}
/* the rest would be commonly eliminated by x86* compiler */
#endif
while (l < len) {
unsigned char c;
if (n == 0) {
(*block) (ivec, ivec, key);
}
out[l] = ivec[n] ^ (c = in[l]);
ivec[n] = c;
++l;
n = (n + 1) % 16;
}
*num = n;
}
}
/*
* This expects a single block of size nbits for both in and out. Note that
* it corrupts any extra bits in the last byte of out
*/
static void cfbr_encrypt_block(const unsigned char *in, unsigned char *out,
int nbits, const void *key,
unsigned char ivec[16], int enc,
block128_f block)
{
int n, rem, num;
unsigned char ovec[16 * 2 + 1]; /* +1 because we dereference (but don't
* use) one byte off the end */
if (nbits <= 0 || nbits > 128)
return;
/* fill in the first half of the new IV with the current IV */
memcpy(ovec, ivec, 16);
/* construct the new IV */
(*block) (ivec, ivec, key);
num = (nbits + 7) / 8;
if (enc) /* encrypt the input */
for (n = 0; n < num; ++n)
out[n] = (ovec[16 + n] = in[n] ^ ivec[n]);
else /* decrypt the input */
for (n = 0; n < num; ++n)
out[n] = (ovec[16 + n] = in[n]) ^ ivec[n];
/* shift ovec left... */
rem = nbits % 8;
num = nbits / 8;
if (rem == 0)
memcpy(ivec, ovec + num, 16);
else
for (n = 0; n < 16; ++n)
ivec[n] = ovec[n + num] << rem | ovec[n + num + 1] >> (8 - rem);
/* it is not necessary to cleanse ovec, since the IV is not secret */
}
/* N.B. This expects the input to be packed, MS bit first */
void CRYPTO_cfb128_1_encrypt(const unsigned char *in, unsigned char *out,
size_t bits, const void *key,
unsigned char ivec[16], int *num,
int enc, block128_f block)
{
size_t n;
unsigned char c[1], d[1];
for (n = 0; n < bits; ++n) {
c[0] = (in[n / 8] & (1 << (7 - n % 8))) ? 0x80 : 0;
cfbr_encrypt_block(c, d, 1, key, ivec, enc, block);
out[n / 8] = (out[n / 8] & ~(1 << (unsigned int)(7 - n % 8))) |
((d[0] & 0x80) >> (unsigned int)(n % 8));
}
}
void CRYPTO_cfb128_8_encrypt(const unsigned char *in, unsigned char *out,
size_t length, const void *key,
unsigned char ivec[16], int *num,
int enc, block128_f block)
{
size_t n;
for (n = 0; n < length; ++n)
cfbr_encrypt_block(&in[n], &out[n], 8, key, ivec, enc, block);
}
|
./openssl/crypto/modes/xts128.c | /*
* Copyright 2011-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 <string.h>
#include <openssl/crypto.h>
#include "internal/endian.h"
#include "crypto/modes.h"
#ifndef STRICT_ALIGNMENT
# ifdef __GNUC__
typedef u64 u64_a1 __attribute((__aligned__(1)));
# else
typedef u64 u64_a1;
# endif
#endif
int CRYPTO_xts128_encrypt(const XTS128_CONTEXT *ctx,
const unsigned char iv[16],
const unsigned char *inp, unsigned char *out,
size_t len, int enc)
{
DECLARE_IS_ENDIAN;
union {
u64 u[2];
u32 d[4];
u8 c[16];
} tweak, scratch;
unsigned int i;
if (len < 16)
return -1;
memcpy(tweak.c, iv, 16);
(*ctx->block2) (tweak.c, tweak.c, ctx->key2);
if (!enc && (len % 16))
len -= 16;
while (len >= 16) {
#if defined(STRICT_ALIGNMENT)
memcpy(scratch.c, inp, 16);
scratch.u[0] ^= tweak.u[0];
scratch.u[1] ^= tweak.u[1];
#else
scratch.u[0] = ((u64_a1 *)inp)[0] ^ tweak.u[0];
scratch.u[1] = ((u64_a1 *)inp)[1] ^ tweak.u[1];
#endif
(*ctx->block1) (scratch.c, scratch.c, ctx->key1);
#if defined(STRICT_ALIGNMENT)
scratch.u[0] ^= tweak.u[0];
scratch.u[1] ^= tweak.u[1];
memcpy(out, scratch.c, 16);
#else
((u64_a1 *)out)[0] = scratch.u[0] ^= tweak.u[0];
((u64_a1 *)out)[1] = scratch.u[1] ^= tweak.u[1];
#endif
inp += 16;
out += 16;
len -= 16;
if (len == 0)
return 0;
if (IS_LITTLE_ENDIAN) {
unsigned int carry, res;
res = 0x87 & (((int)tweak.d[3]) >> 31);
carry = (unsigned int)(tweak.u[0] >> 63);
tweak.u[0] = (tweak.u[0] << 1) ^ res;
tweak.u[1] = (tweak.u[1] << 1) | carry;
} else {
size_t c;
for (c = 0, i = 0; i < 16; ++i) {
/*
* + substitutes for |, because c is 1 bit
*/
c += ((size_t)tweak.c[i]) << 1;
tweak.c[i] = (u8)c;
c = c >> 8;
}
tweak.c[0] ^= (u8)(0x87 & (0 - c));
}
}
if (enc) {
for (i = 0; i < len; ++i) {
u8 c = inp[i];
out[i] = scratch.c[i];
scratch.c[i] = c;
}
scratch.u[0] ^= tweak.u[0];
scratch.u[1] ^= tweak.u[1];
(*ctx->block1) (scratch.c, scratch.c, ctx->key1);
scratch.u[0] ^= tweak.u[0];
scratch.u[1] ^= tweak.u[1];
memcpy(out - 16, scratch.c, 16);
} else {
union {
u64 u[2];
u8 c[16];
} tweak1;
if (IS_LITTLE_ENDIAN) {
unsigned int carry, res;
res = 0x87 & (((int)tweak.d[3]) >> 31);
carry = (unsigned int)(tweak.u[0] >> 63);
tweak1.u[0] = (tweak.u[0] << 1) ^ res;
tweak1.u[1] = (tweak.u[1] << 1) | carry;
} else {
size_t c;
for (c = 0, i = 0; i < 16; ++i) {
/*
* + substitutes for |, because c is 1 bit
*/
c += ((size_t)tweak.c[i]) << 1;
tweak1.c[i] = (u8)c;
c = c >> 8;
}
tweak1.c[0] ^= (u8)(0x87 & (0 - c));
}
#if defined(STRICT_ALIGNMENT)
memcpy(scratch.c, inp, 16);
scratch.u[0] ^= tweak1.u[0];
scratch.u[1] ^= tweak1.u[1];
#else
scratch.u[0] = ((u64_a1 *)inp)[0] ^ tweak1.u[0];
scratch.u[1] = ((u64_a1 *)inp)[1] ^ tweak1.u[1];
#endif
(*ctx->block1) (scratch.c, scratch.c, ctx->key1);
scratch.u[0] ^= tweak1.u[0];
scratch.u[1] ^= tweak1.u[1];
for (i = 0; i < len; ++i) {
u8 c = inp[16 + i];
out[16 + i] = scratch.c[i];
scratch.c[i] = c;
}
scratch.u[0] ^= tweak.u[0];
scratch.u[1] ^= tweak.u[1];
(*ctx->block1) (scratch.c, scratch.c, ctx->key1);
#if defined(STRICT_ALIGNMENT)
scratch.u[0] ^= tweak.u[0];
scratch.u[1] ^= tweak.u[1];
memcpy(out, scratch.c, 16);
#else
((u64_a1 *)out)[0] = scratch.u[0] ^ tweak.u[0];
((u64_a1 *)out)[1] = scratch.u[1] ^ tweak.u[1];
#endif
}
return 0;
}
|
./openssl/crypto/modes/ofb128.c | /*
* Copyright 2008-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/crypto.h>
#include "crypto/modes.h"
#if defined(__GNUC__) && !defined(STRICT_ALIGNMENT)
typedef size_t size_t_aX __attribute((__aligned__(1)));
#else
typedef size_t size_t_aX;
#endif
/*
* The input and output encrypted as though 128bit ofb mode is being used.
* The extra state information to record how much of the 128bit block we have
* used is contained in *num;
*/
void CRYPTO_ofb128_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
unsigned char ivec[16], int *num, block128_f block)
{
unsigned int n;
size_t l = 0;
if (*num < 0) {
/* There is no good way to signal an error return from here */
*num = -1;
return;
}
n = *num;
#if !defined(OPENSSL_SMALL_FOOTPRINT)
if (16 % sizeof(size_t) == 0) { /* always true actually */
do {
while (n && len) {
*(out++) = *(in++) ^ ivec[n];
--len;
n = (n + 1) % 16;
}
# if defined(STRICT_ALIGNMENT)
if (((size_t)in | (size_t)out | (size_t)ivec) % sizeof(size_t) !=
0)
break;
# endif
while (len >= 16) {
(*block) (ivec, ivec, key);
for (; n < 16; n += sizeof(size_t))
*(size_t_aX *)(out + n) =
*(size_t_aX *)(in + n)
^ *(size_t_aX *)(ivec + n);
len -= 16;
out += 16;
in += 16;
n = 0;
}
if (len) {
(*block) (ivec, ivec, key);
while (len--) {
out[n] = in[n] ^ ivec[n];
++n;
}
}
*num = n;
return;
} while (0);
}
/* the rest would be commonly eliminated by x86* compiler */
#endif
while (l < len) {
if (n == 0) {
(*block) (ivec, ivec, key);
}
out[l] = in[l] ^ ivec[n];
++l;
n = (n + 1) % 16;
}
*num = n;
}
|
./openssl/crypto/modes/cbc128.c | /*
* Copyright 2008-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/crypto.h>
#include "crypto/modes.h"
#if !defined(STRICT_ALIGNMENT) && !defined(PEDANTIC)
# define STRICT_ALIGNMENT 0
#endif
#if defined(__GNUC__) && !STRICT_ALIGNMENT
typedef size_t size_t_aX __attribute((__aligned__(1)));
#else
typedef size_t size_t_aX;
#endif
void CRYPTO_cbc128_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
unsigned char ivec[16], block128_f block)
{
size_t n;
const unsigned char *iv = ivec;
if (len == 0)
return;
#if !defined(OPENSSL_SMALL_FOOTPRINT)
if (STRICT_ALIGNMENT &&
((size_t)in | (size_t)out | (size_t)ivec) % sizeof(size_t) != 0) {
while (len >= 16) {
for (n = 0; n < 16; ++n)
out[n] = in[n] ^ iv[n];
(*block) (out, out, key);
iv = out;
len -= 16;
in += 16;
out += 16;
}
} else {
while (len >= 16) {
for (n = 0; n < 16; n += sizeof(size_t))
*(size_t_aX *)(out + n) =
*(size_t_aX *)(in + n) ^ *(size_t_aX *)(iv + n);
(*block) (out, out, key);
iv = out;
len -= 16;
in += 16;
out += 16;
}
}
#endif
while (len) {
for (n = 0; n < 16 && n < len; ++n)
out[n] = in[n] ^ iv[n];
for (; n < 16; ++n)
out[n] = iv[n];
(*block) (out, out, key);
iv = out;
if (len <= 16)
break;
len -= 16;
in += 16;
out += 16;
}
if (ivec != iv)
memcpy(ivec, iv, 16);
}
void CRYPTO_cbc128_decrypt(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
unsigned char ivec[16], block128_f block)
{
size_t n;
union {
size_t t[16 / sizeof(size_t)];
unsigned char c[16];
} tmp;
if (len == 0)
return;
#if !defined(OPENSSL_SMALL_FOOTPRINT)
if (in != out) {
const unsigned char *iv = ivec;
if (STRICT_ALIGNMENT &&
((size_t)in | (size_t)out | (size_t)ivec) % sizeof(size_t) != 0) {
while (len >= 16) {
(*block) (in, out, key);
for (n = 0; n < 16; ++n)
out[n] ^= iv[n];
iv = in;
len -= 16;
in += 16;
out += 16;
}
} else if (16 % sizeof(size_t) == 0) { /* always true */
while (len >= 16) {
size_t_aX *out_t = (size_t_aX *)out;
size_t_aX *iv_t = (size_t_aX *)iv;
(*block) (in, out, key);
for (n = 0; n < 16 / sizeof(size_t); n++)
out_t[n] ^= iv_t[n];
iv = in;
len -= 16;
in += 16;
out += 16;
}
}
if (ivec != iv)
memcpy(ivec, iv, 16);
} else {
if (STRICT_ALIGNMENT &&
((size_t)in | (size_t)out | (size_t)ivec) % sizeof(size_t) != 0) {
unsigned char c;
while (len >= 16) {
(*block) (in, tmp.c, key);
for (n = 0; n < 16; ++n) {
c = in[n];
out[n] = tmp.c[n] ^ ivec[n];
ivec[n] = c;
}
len -= 16;
in += 16;
out += 16;
}
} else if (16 % sizeof(size_t) == 0) { /* always true */
while (len >= 16) {
size_t c;
size_t_aX *out_t = (size_t_aX *)out;
size_t_aX *ivec_t = (size_t_aX *)ivec;
const size_t_aX *in_t = (const size_t_aX *)in;
(*block) (in, tmp.c, key);
for (n = 0; n < 16 / sizeof(size_t); n++) {
c = in_t[n];
out_t[n] = tmp.t[n] ^ ivec_t[n];
ivec_t[n] = c;
}
len -= 16;
in += 16;
out += 16;
}
}
}
#endif
while (len) {
unsigned char c;
(*block) (in, tmp.c, key);
for (n = 0; n < 16 && n < len; ++n) {
c = in[n];
out[n] = tmp.c[n] ^ ivec[n];
ivec[n] = c;
}
if (len <= 16) {
for (; n < 16; ++n)
ivec[n] = in[n];
break;
}
len -= 16;
in += 16;
out += 16;
}
}
|
./openssl/crypto/modes/ccm128.c | /*
* Copyright 2011-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 <string.h>
#include <openssl/crypto.h>
#include "crypto/modes.h"
#ifndef STRICT_ALIGNMENT
# ifdef __GNUC__
typedef u64 u64_a1 __attribute((__aligned__(1)));
# else
typedef u64 u64_a1;
# endif
#endif
/*
* First you setup M and L parameters and pass the key schedule. This is
* called once per session setup...
*/
void CRYPTO_ccm128_init(CCM128_CONTEXT *ctx,
unsigned int M, unsigned int L, void *key,
block128_f block)
{
memset(ctx->nonce.c, 0, sizeof(ctx->nonce.c));
ctx->nonce.c[0] = ((u8)(L - 1) & 7) | (u8)(((M - 2) / 2) & 7) << 3;
ctx->blocks = 0;
ctx->block = block;
ctx->key = key;
}
/* !!! Following interfaces are to be called *once* per packet !!! */
/* Then you setup per-message nonce and pass the length of the message */
int CRYPTO_ccm128_setiv(CCM128_CONTEXT *ctx,
const unsigned char *nonce, size_t nlen, size_t mlen)
{
unsigned int L = ctx->nonce.c[0] & 7; /* the L parameter */
if (nlen < (14 - L))
return -1; /* nonce is too short */
if (sizeof(mlen) == 8 && L >= 3) {
ctx->nonce.c[8] = (u8)(mlen >> (56 % (sizeof(mlen) * 8)));
ctx->nonce.c[9] = (u8)(mlen >> (48 % (sizeof(mlen) * 8)));
ctx->nonce.c[10] = (u8)(mlen >> (40 % (sizeof(mlen) * 8)));
ctx->nonce.c[11] = (u8)(mlen >> (32 % (sizeof(mlen) * 8)));
} else
ctx->nonce.u[1] = 0;
ctx->nonce.c[12] = (u8)(mlen >> 24);
ctx->nonce.c[13] = (u8)(mlen >> 16);
ctx->nonce.c[14] = (u8)(mlen >> 8);
ctx->nonce.c[15] = (u8)mlen;
ctx->nonce.c[0] &= ~0x40; /* clear Adata flag */
memcpy(&ctx->nonce.c[1], nonce, 14 - L);
return 0;
}
/* Then you pass additional authentication data, this is optional */
void CRYPTO_ccm128_aad(CCM128_CONTEXT *ctx,
const unsigned char *aad, size_t alen)
{
unsigned int i;
block128_f block = ctx->block;
if (alen == 0)
return;
ctx->nonce.c[0] |= 0x40; /* set Adata flag */
(*block) (ctx->nonce.c, ctx->cmac.c, ctx->key), ctx->blocks++;
if (alen < (0x10000 - 0x100)) {
ctx->cmac.c[0] ^= (u8)(alen >> 8);
ctx->cmac.c[1] ^= (u8)alen;
i = 2;
} else if (sizeof(alen) == 8
&& alen >= (size_t)1 << (32 % (sizeof(alen) * 8))) {
ctx->cmac.c[0] ^= 0xFF;
ctx->cmac.c[1] ^= 0xFF;
ctx->cmac.c[2] ^= (u8)(alen >> (56 % (sizeof(alen) * 8)));
ctx->cmac.c[3] ^= (u8)(alen >> (48 % (sizeof(alen) * 8)));
ctx->cmac.c[4] ^= (u8)(alen >> (40 % (sizeof(alen) * 8)));
ctx->cmac.c[5] ^= (u8)(alen >> (32 % (sizeof(alen) * 8)));
ctx->cmac.c[6] ^= (u8)(alen >> 24);
ctx->cmac.c[7] ^= (u8)(alen >> 16);
ctx->cmac.c[8] ^= (u8)(alen >> 8);
ctx->cmac.c[9] ^= (u8)alen;
i = 10;
} else {
ctx->cmac.c[0] ^= 0xFF;
ctx->cmac.c[1] ^= 0xFE;
ctx->cmac.c[2] ^= (u8)(alen >> 24);
ctx->cmac.c[3] ^= (u8)(alen >> 16);
ctx->cmac.c[4] ^= (u8)(alen >> 8);
ctx->cmac.c[5] ^= (u8)alen;
i = 6;
}
do {
for (; i < 16 && alen; ++i, ++aad, --alen)
ctx->cmac.c[i] ^= *aad;
(*block) (ctx->cmac.c, ctx->cmac.c, ctx->key), ctx->blocks++;
i = 0;
} while (alen);
}
/* Finally you encrypt or decrypt the message */
/*
* counter part of nonce may not be larger than L*8 bits, L is not larger
* than 8, therefore 64-bit counter...
*/
static void ctr64_inc(unsigned char *counter)
{
unsigned int n = 8;
u8 c;
counter += 8;
do {
--n;
c = counter[n];
++c;
counter[n] = c;
if (c)
return;
} while (n);
}
int CRYPTO_ccm128_encrypt(CCM128_CONTEXT *ctx,
const unsigned char *inp, unsigned char *out,
size_t len)
{
size_t n;
unsigned int i, L;
unsigned char flags0 = ctx->nonce.c[0];
block128_f block = ctx->block;
void *key = ctx->key;
union {
u64 u[2];
u8 c[16];
} scratch;
if (!(flags0 & 0x40))
(*block) (ctx->nonce.c, ctx->cmac.c, key), ctx->blocks++;
ctx->nonce.c[0] = L = flags0 & 7;
for (n = 0, i = 15 - L; i < 15; ++i) {
n |= ctx->nonce.c[i];
ctx->nonce.c[i] = 0;
n <<= 8;
}
n |= ctx->nonce.c[15]; /* reconstructed length */
ctx->nonce.c[15] = 1;
if (n != len)
return -1; /* length mismatch */
ctx->blocks += ((len + 15) >> 3) | 1;
if (ctx->blocks > (U64(1) << 61))
return -2; /* too much data */
while (len >= 16) {
#if defined(STRICT_ALIGNMENT)
union {
u64 u[2];
u8 c[16];
} temp;
memcpy(temp.c, inp, 16);
ctx->cmac.u[0] ^= temp.u[0];
ctx->cmac.u[1] ^= temp.u[1];
#else
ctx->cmac.u[0] ^= ((u64_a1 *)inp)[0];
ctx->cmac.u[1] ^= ((u64_a1 *)inp)[1];
#endif
(*block) (ctx->cmac.c, ctx->cmac.c, key);
(*block) (ctx->nonce.c, scratch.c, key);
ctr64_inc(ctx->nonce.c);
#if defined(STRICT_ALIGNMENT)
temp.u[0] ^= scratch.u[0];
temp.u[1] ^= scratch.u[1];
memcpy(out, temp.c, 16);
#else
((u64_a1 *)out)[0] = scratch.u[0] ^ ((u64_a1 *)inp)[0];
((u64_a1 *)out)[1] = scratch.u[1] ^ ((u64_a1 *)inp)[1];
#endif
inp += 16;
out += 16;
len -= 16;
}
if (len) {
for (i = 0; i < len; ++i)
ctx->cmac.c[i] ^= inp[i];
(*block) (ctx->cmac.c, ctx->cmac.c, key);
(*block) (ctx->nonce.c, scratch.c, key);
for (i = 0; i < len; ++i)
out[i] = scratch.c[i] ^ inp[i];
}
for (i = 15 - L; i < 16; ++i)
ctx->nonce.c[i] = 0;
(*block) (ctx->nonce.c, scratch.c, key);
ctx->cmac.u[0] ^= scratch.u[0];
ctx->cmac.u[1] ^= scratch.u[1];
ctx->nonce.c[0] = flags0;
return 0;
}
int CRYPTO_ccm128_decrypt(CCM128_CONTEXT *ctx,
const unsigned char *inp, unsigned char *out,
size_t len)
{
size_t n;
unsigned int i, L;
unsigned char flags0 = ctx->nonce.c[0];
block128_f block = ctx->block;
void *key = ctx->key;
union {
u64 u[2];
u8 c[16];
} scratch;
if (!(flags0 & 0x40))
(*block) (ctx->nonce.c, ctx->cmac.c, key);
ctx->nonce.c[0] = L = flags0 & 7;
for (n = 0, i = 15 - L; i < 15; ++i) {
n |= ctx->nonce.c[i];
ctx->nonce.c[i] = 0;
n <<= 8;
}
n |= ctx->nonce.c[15]; /* reconstructed length */
ctx->nonce.c[15] = 1;
if (n != len)
return -1;
while (len >= 16) {
#if defined(STRICT_ALIGNMENT)
union {
u64 u[2];
u8 c[16];
} temp;
#endif
(*block) (ctx->nonce.c, scratch.c, key);
ctr64_inc(ctx->nonce.c);
#if defined(STRICT_ALIGNMENT)
memcpy(temp.c, inp, 16);
ctx->cmac.u[0] ^= (scratch.u[0] ^= temp.u[0]);
ctx->cmac.u[1] ^= (scratch.u[1] ^= temp.u[1]);
memcpy(out, scratch.c, 16);
#else
ctx->cmac.u[0] ^= (((u64_a1 *)out)[0]
= scratch.u[0] ^ ((u64_a1 *)inp)[0]);
ctx->cmac.u[1] ^= (((u64_a1 *)out)[1]
= scratch.u[1] ^ ((u64_a1 *)inp)[1]);
#endif
(*block) (ctx->cmac.c, ctx->cmac.c, key);
inp += 16;
out += 16;
len -= 16;
}
if (len) {
(*block) (ctx->nonce.c, scratch.c, key);
for (i = 0; i < len; ++i)
ctx->cmac.c[i] ^= (out[i] = scratch.c[i] ^ inp[i]);
(*block) (ctx->cmac.c, ctx->cmac.c, key);
}
for (i = 15 - L; i < 16; ++i)
ctx->nonce.c[i] = 0;
(*block) (ctx->nonce.c, scratch.c, key);
ctx->cmac.u[0] ^= scratch.u[0];
ctx->cmac.u[1] ^= scratch.u[1];
ctx->nonce.c[0] = flags0;
return 0;
}
static void ctr64_add(unsigned char *counter, size_t inc)
{
size_t n = 8, val = 0;
counter += 8;
do {
--n;
val += counter[n] + (inc & 0xff);
counter[n] = (unsigned char)val;
val >>= 8; /* carry bit */
inc >>= 8;
} while (n && (inc || val));
}
int CRYPTO_ccm128_encrypt_ccm64(CCM128_CONTEXT *ctx,
const unsigned char *inp, unsigned char *out,
size_t len, ccm128_f stream)
{
size_t n;
unsigned int i, L;
unsigned char flags0 = ctx->nonce.c[0];
block128_f block = ctx->block;
void *key = ctx->key;
union {
u64 u[2];
u8 c[16];
} scratch;
if (!(flags0 & 0x40))
(*block) (ctx->nonce.c, ctx->cmac.c, key), ctx->blocks++;
ctx->nonce.c[0] = L = flags0 & 7;
for (n = 0, i = 15 - L; i < 15; ++i) {
n |= ctx->nonce.c[i];
ctx->nonce.c[i] = 0;
n <<= 8;
}
n |= ctx->nonce.c[15]; /* reconstructed length */
ctx->nonce.c[15] = 1;
if (n != len)
return -1; /* length mismatch */
ctx->blocks += ((len + 15) >> 3) | 1;
if (ctx->blocks > (U64(1) << 61))
return -2; /* too much data */
if ((n = len / 16)) {
(*stream) (inp, out, n, key, ctx->nonce.c, ctx->cmac.c);
n *= 16;
inp += n;
out += n;
len -= n;
if (len)
ctr64_add(ctx->nonce.c, n / 16);
}
if (len) {
for (i = 0; i < len; ++i)
ctx->cmac.c[i] ^= inp[i];
(*block) (ctx->cmac.c, ctx->cmac.c, key);
(*block) (ctx->nonce.c, scratch.c, key);
for (i = 0; i < len; ++i)
out[i] = scratch.c[i] ^ inp[i];
}
for (i = 15 - L; i < 16; ++i)
ctx->nonce.c[i] = 0;
(*block) (ctx->nonce.c, scratch.c, key);
ctx->cmac.u[0] ^= scratch.u[0];
ctx->cmac.u[1] ^= scratch.u[1];
ctx->nonce.c[0] = flags0;
return 0;
}
int CRYPTO_ccm128_decrypt_ccm64(CCM128_CONTEXT *ctx,
const unsigned char *inp, unsigned char *out,
size_t len, ccm128_f stream)
{
size_t n;
unsigned int i, L;
unsigned char flags0 = ctx->nonce.c[0];
block128_f block = ctx->block;
void *key = ctx->key;
union {
u64 u[2];
u8 c[16];
} scratch;
if (!(flags0 & 0x40))
(*block) (ctx->nonce.c, ctx->cmac.c, key);
ctx->nonce.c[0] = L = flags0 & 7;
for (n = 0, i = 15 - L; i < 15; ++i) {
n |= ctx->nonce.c[i];
ctx->nonce.c[i] = 0;
n <<= 8;
}
n |= ctx->nonce.c[15]; /* reconstructed length */
ctx->nonce.c[15] = 1;
if (n != len)
return -1;
if ((n = len / 16)) {
(*stream) (inp, out, n, key, ctx->nonce.c, ctx->cmac.c);
n *= 16;
inp += n;
out += n;
len -= n;
if (len)
ctr64_add(ctx->nonce.c, n / 16);
}
if (len) {
(*block) (ctx->nonce.c, scratch.c, key);
for (i = 0; i < len; ++i)
ctx->cmac.c[i] ^= (out[i] = scratch.c[i] ^ inp[i]);
(*block) (ctx->cmac.c, ctx->cmac.c, key);
}
for (i = 15 - L; i < 16; ++i)
ctx->nonce.c[i] = 0;
(*block) (ctx->nonce.c, scratch.c, key);
ctx->cmac.u[0] ^= scratch.u[0];
ctx->cmac.u[1] ^= scratch.u[1];
ctx->nonce.c[0] = flags0;
return 0;
}
size_t CRYPTO_ccm128_tag(CCM128_CONTEXT *ctx, unsigned char *tag, size_t len)
{
unsigned int M = (ctx->nonce.c[0] >> 3) & 7; /* the M parameter */
M *= 2;
M += 2;
if (len != M)
return 0;
memcpy(tag, ctx->cmac.c, M);
return M;
}
|
./openssl/crypto/modes/cts128.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
*/
#include <string.h>
#include <openssl/crypto.h>
#include "crypto/modes.h"
/*
* Trouble with Ciphertext Stealing, CTS, mode is that there is no
* common official specification, but couple of cipher/application
* specific ones: RFC2040 and RFC3962. Then there is 'Proposal to
* Extend CBC Mode By "Ciphertext Stealing"' at NIST site, which
* deviates from mentioned RFCs. Most notably it allows input to be
* of block length and it doesn't flip the order of the last two
* blocks. CTS is being discussed even in ECB context, but it's not
* adopted for any known application. This implementation provides
* two interfaces: one compliant with above mentioned RFCs and one
* compliant with the NIST proposal, both extending CBC mode.
*/
size_t CRYPTO_cts128_encrypt_block(const unsigned char *in,
unsigned char *out, size_t len,
const void *key, unsigned char ivec[16],
block128_f block)
{
size_t residue, n;
if (len <= 16)
return 0;
if ((residue = len % 16) == 0)
residue = 16;
len -= residue;
CRYPTO_cbc128_encrypt(in, out, len, key, ivec, block);
in += len;
out += len;
for (n = 0; n < residue; ++n)
ivec[n] ^= in[n];
(*block) (ivec, ivec, key);
memcpy(out, out - 16, residue);
memcpy(out - 16, ivec, 16);
return len + residue;
}
size_t CRYPTO_nistcts128_encrypt_block(const unsigned char *in,
unsigned char *out, size_t len,
const void *key,
unsigned char ivec[16],
block128_f block)
{
size_t residue, n;
if (len < 16)
return 0;
residue = len % 16;
len -= residue;
CRYPTO_cbc128_encrypt(in, out, len, key, ivec, block);
if (residue == 0)
return len;
in += len;
out += len;
for (n = 0; n < residue; ++n)
ivec[n] ^= in[n];
(*block) (ivec, ivec, key);
memcpy(out - 16 + residue, ivec, 16);
return len + residue;
}
size_t CRYPTO_cts128_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
unsigned char ivec[16], cbc128_f cbc)
{
size_t residue;
union {
size_t align;
unsigned char c[16];
} tmp;
if (len <= 16)
return 0;
if ((residue = len % 16) == 0)
residue = 16;
len -= residue;
(*cbc) (in, out, len, key, ivec, 1);
in += len;
out += len;
#if defined(CBC_HANDLES_TRUNCATED_IO)
memcpy(tmp.c, out - 16, 16);
(*cbc) (in, out - 16, residue, key, ivec, 1);
memcpy(out, tmp.c, residue);
#else
memset(tmp.c, 0, sizeof(tmp));
memcpy(tmp.c, in, residue);
memcpy(out, out - 16, residue);
(*cbc) (tmp.c, out - 16, 16, key, ivec, 1);
#endif
return len + residue;
}
size_t CRYPTO_nistcts128_encrypt(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
unsigned char ivec[16], cbc128_f cbc)
{
size_t residue;
union {
size_t align;
unsigned char c[16];
} tmp;
if (len < 16)
return 0;
residue = len % 16;
len -= residue;
(*cbc) (in, out, len, key, ivec, 1);
if (residue == 0)
return len;
in += len;
out += len;
#if defined(CBC_HANDLES_TRUNCATED_IO)
(*cbc) (in, out - 16 + residue, residue, key, ivec, 1);
#else
memset(tmp.c, 0, sizeof(tmp));
memcpy(tmp.c, in, residue);
(*cbc) (tmp.c, out - 16 + residue, 16, key, ivec, 1);
#endif
return len + residue;
}
size_t CRYPTO_cts128_decrypt_block(const unsigned char *in,
unsigned char *out, size_t len,
const void *key, unsigned char ivec[16],
block128_f block)
{
size_t residue, n;
union {
size_t align;
unsigned char c[32];
} tmp;
if (len <= 16)
return 0;
if ((residue = len % 16) == 0)
residue = 16;
len -= 16 + residue;
if (len) {
CRYPTO_cbc128_decrypt(in, out, len, key, ivec, block);
in += len;
out += len;
}
(*block) (in, tmp.c + 16, key);
memcpy(tmp.c, tmp.c + 16, 16);
memcpy(tmp.c, in + 16, residue);
(*block) (tmp.c, tmp.c, key);
for (n = 0; n < 16; ++n) {
unsigned char c = in[n];
out[n] = tmp.c[n] ^ ivec[n];
ivec[n] = c;
}
for (residue += 16; n < residue; ++n)
out[n] = tmp.c[n] ^ in[n];
return 16 + len + residue;
}
size_t CRYPTO_nistcts128_decrypt_block(const unsigned char *in,
unsigned char *out, size_t len,
const void *key,
unsigned char ivec[16],
block128_f block)
{
size_t residue, n;
union {
size_t align;
unsigned char c[32];
} tmp;
if (len < 16)
return 0;
residue = len % 16;
if (residue == 0) {
CRYPTO_cbc128_decrypt(in, out, len, key, ivec, block);
return len;
}
len -= 16 + residue;
if (len) {
CRYPTO_cbc128_decrypt(in, out, len, key, ivec, block);
in += len;
out += len;
}
(*block) (in + residue, tmp.c + 16, key);
memcpy(tmp.c, tmp.c + 16, 16);
memcpy(tmp.c, in, residue);
(*block) (tmp.c, tmp.c, key);
for (n = 0; n < 16; ++n) {
unsigned char c = in[n];
out[n] = tmp.c[n] ^ ivec[n];
ivec[n] = in[n + residue];
tmp.c[n] = c;
}
for (residue += 16; n < residue; ++n)
out[n] = tmp.c[n] ^ tmp.c[n - 16];
return 16 + len + residue;
}
size_t CRYPTO_cts128_decrypt(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
unsigned char ivec[16], cbc128_f cbc)
{
size_t residue;
union {
size_t align;
unsigned char c[32];
} tmp;
if (len <= 16)
return 0;
if ((residue = len % 16) == 0)
residue = 16;
len -= 16 + residue;
if (len) {
(*cbc) (in, out, len, key, ivec, 0);
in += len;
out += len;
}
memset(tmp.c, 0, sizeof(tmp));
/*
* this places in[16] at &tmp.c[16] and decrypted block at &tmp.c[0]
*/
(*cbc) (in, tmp.c, 16, key, tmp.c + 16, 0);
memcpy(tmp.c, in + 16, residue);
#if defined(CBC_HANDLES_TRUNCATED_IO)
(*cbc) (tmp.c, out, 16 + residue, key, ivec, 0);
#else
(*cbc) (tmp.c, tmp.c, 32, key, ivec, 0);
memcpy(out, tmp.c, 16 + residue);
#endif
return 16 + len + residue;
}
size_t CRYPTO_nistcts128_decrypt(const unsigned char *in, unsigned char *out,
size_t len, const void *key,
unsigned char ivec[16], cbc128_f cbc)
{
size_t residue;
union {
size_t align;
unsigned char c[32];
} tmp;
if (len < 16)
return 0;
residue = len % 16;
if (residue == 0) {
(*cbc) (in, out, len, key, ivec, 0);
return len;
}
len -= 16 + residue;
if (len) {
(*cbc) (in, out, len, key, ivec, 0);
in += len;
out += len;
}
memset(tmp.c, 0, sizeof(tmp));
/*
* this places in[16] at &tmp.c[16] and decrypted block at &tmp.c[0]
*/
(*cbc) (in + residue, tmp.c, 16, key, tmp.c + 16, 0);
memcpy(tmp.c, in, residue);
#if defined(CBC_HANDLES_TRUNCATED_IO)
(*cbc) (tmp.c, out, 16 + residue, key, ivec, 0);
#else
(*cbc) (tmp.c, tmp.c, 32, key, ivec, 0);
memcpy(out, tmp.c, 16 + residue);
#endif
return 16 + len + residue;
}
|
./openssl/crypto/modes/siv128.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 <string.h>
#include <stdlib.h>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/core_names.h>
#include <openssl/params.h>
#include "internal/endian.h"
#include "crypto/modes.h"
#include "crypto/siv.h"
#ifndef OPENSSL_NO_SIV
__owur static ossl_inline uint32_t rotl8(uint32_t x)
{
return (x << 8) | (x >> 24);
}
__owur static ossl_inline uint32_t rotr8(uint32_t x)
{
return (x >> 8) | (x << 24);
}
__owur static ossl_inline uint64_t byteswap8(uint64_t x)
{
uint32_t high = (uint32_t)(x >> 32);
uint32_t low = (uint32_t)x;
high = (rotl8(high) & 0x00ff00ff) | (rotr8(high) & 0xff00ff00);
low = (rotl8(low) & 0x00ff00ff) | (rotr8(low) & 0xff00ff00);
return ((uint64_t)low) << 32 | (uint64_t)high;
}
__owur static ossl_inline uint64_t siv128_getword(SIV_BLOCK const *b, size_t i)
{
DECLARE_IS_ENDIAN;
if (IS_LITTLE_ENDIAN)
return byteswap8(b->word[i]);
return b->word[i];
}
static ossl_inline void siv128_putword(SIV_BLOCK *b, size_t i, uint64_t x)
{
DECLARE_IS_ENDIAN;
if (IS_LITTLE_ENDIAN)
b->word[i] = byteswap8(x);
else
b->word[i] = x;
}
static ossl_inline void siv128_xorblock(SIV_BLOCK *x,
SIV_BLOCK const *y)
{
x->word[0] ^= y->word[0];
x->word[1] ^= y->word[1];
}
/*
* Doubles |b|, which is 16 bytes representing an element
* of GF(2**128) modulo the irreducible polynomial
* x**128 + x**7 + x**2 + x + 1.
* Assumes two's-complement arithmetic
*/
static ossl_inline void siv128_dbl(SIV_BLOCK *b)
{
uint64_t high = siv128_getword(b, 0);
uint64_t low = siv128_getword(b, 1);
uint64_t high_carry = high & (((uint64_t)1) << 63);
uint64_t low_carry = low & (((uint64_t)1) << 63);
int64_t low_mask = -((int64_t)(high_carry >> 63)) & 0x87;
uint64_t high_mask = low_carry >> 63;
high = (high << 1) | high_mask;
low = (low << 1) ^ (uint64_t)low_mask;
siv128_putword(b, 0, high);
siv128_putword(b, 1, low);
}
__owur static ossl_inline int siv128_do_s2v_p(SIV128_CONTEXT *ctx, SIV_BLOCK *out,
unsigned char const* in, size_t len)
{
SIV_BLOCK t;
size_t out_len = sizeof(out->byte);
EVP_MAC_CTX *mac_ctx;
int ret = 0;
mac_ctx = EVP_MAC_CTX_dup(ctx->mac_ctx_init);
if (mac_ctx == NULL)
return 0;
if (len >= SIV_LEN) {
if (!EVP_MAC_update(mac_ctx, in, len - SIV_LEN))
goto err;
memcpy(&t, in + (len-SIV_LEN), SIV_LEN);
siv128_xorblock(&t, &ctx->d);
if (!EVP_MAC_update(mac_ctx, t.byte, SIV_LEN))
goto err;
} else {
memset(&t, 0, sizeof(t));
memcpy(&t, in, len);
t.byte[len] = 0x80;
siv128_dbl(&ctx->d);
siv128_xorblock(&t, &ctx->d);
if (!EVP_MAC_update(mac_ctx, t.byte, SIV_LEN))
goto err;
}
if (!EVP_MAC_final(mac_ctx, out->byte, &out_len, sizeof(out->byte))
|| out_len != SIV_LEN)
goto err;
ret = 1;
err:
EVP_MAC_CTX_free(mac_ctx);
return ret;
}
__owur static ossl_inline int siv128_do_encrypt(EVP_CIPHER_CTX *ctx, unsigned char *out,
unsigned char const *in, size_t len,
SIV_BLOCK *icv)
{
int out_len = (int)len;
if (!EVP_CipherInit_ex(ctx, NULL, NULL, NULL, icv->byte, 1))
return 0;
return EVP_EncryptUpdate(ctx, out, &out_len, in, out_len);
}
/*
* Create a new SIV128_CONTEXT
*/
SIV128_CONTEXT *ossl_siv128_new(const unsigned char *key, int klen,
EVP_CIPHER *cbc, EVP_CIPHER *ctr,
OSSL_LIB_CTX *libctx, const char *propq)
{
SIV128_CONTEXT *ctx;
int ret;
if ((ctx = OPENSSL_malloc(sizeof(*ctx))) != NULL) {
ret = ossl_siv128_init(ctx, key, klen, cbc, ctr, libctx, propq);
if (ret)
return ctx;
OPENSSL_free(ctx);
}
return NULL;
}
/*
* Initialise an existing SIV128_CONTEXT
*/
int ossl_siv128_init(SIV128_CONTEXT *ctx, const unsigned char *key, int klen,
const EVP_CIPHER *cbc, const EVP_CIPHER *ctr,
OSSL_LIB_CTX *libctx, const char *propq)
{
static const unsigned char zero[SIV_LEN] = { 0 };
size_t out_len = SIV_LEN;
EVP_MAC_CTX *mac_ctx = NULL;
OSSL_PARAM params[3];
const char *cbc_name;
if (ctx == NULL)
return 0;
memset(&ctx->d, 0, sizeof(ctx->d));
EVP_CIPHER_CTX_free(ctx->cipher_ctx);
EVP_MAC_CTX_free(ctx->mac_ctx_init);
EVP_MAC_free(ctx->mac);
ctx->mac = NULL;
ctx->cipher_ctx = NULL;
ctx->mac_ctx_init = NULL;
if (key == NULL || cbc == NULL || ctr == NULL)
return 0;
cbc_name = EVP_CIPHER_get0_name(cbc);
params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_CIPHER,
(char *)cbc_name, 0);
params[1] = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
(void *)key, klen);
params[2] = OSSL_PARAM_construct_end();
if ((ctx->cipher_ctx = EVP_CIPHER_CTX_new()) == NULL
|| (ctx->mac =
EVP_MAC_fetch(libctx, OSSL_MAC_NAME_CMAC, propq)) == NULL
|| (ctx->mac_ctx_init = EVP_MAC_CTX_new(ctx->mac)) == NULL
|| !EVP_MAC_CTX_set_params(ctx->mac_ctx_init, params)
|| !EVP_EncryptInit_ex(ctx->cipher_ctx, ctr, NULL, key + klen, NULL)
|| (mac_ctx = EVP_MAC_CTX_dup(ctx->mac_ctx_init)) == NULL
|| !EVP_MAC_update(mac_ctx, zero, sizeof(zero))
|| !EVP_MAC_final(mac_ctx, ctx->d.byte, &out_len,
sizeof(ctx->d.byte))) {
EVP_CIPHER_CTX_free(ctx->cipher_ctx);
EVP_MAC_CTX_free(ctx->mac_ctx_init);
EVP_MAC_CTX_free(mac_ctx);
EVP_MAC_free(ctx->mac);
return 0;
}
EVP_MAC_CTX_free(mac_ctx);
ctx->final_ret = -1;
ctx->crypto_ok = 1;
return 1;
}
/*
* Copy an SIV128_CONTEXT object
*/
int ossl_siv128_copy_ctx(SIV128_CONTEXT *dest, SIV128_CONTEXT *src)
{
memcpy(&dest->d, &src->d, sizeof(src->d));
if (dest->cipher_ctx == NULL) {
dest->cipher_ctx = EVP_CIPHER_CTX_new();
if (dest->cipher_ctx == NULL)
return 0;
}
if (!EVP_CIPHER_CTX_copy(dest->cipher_ctx, src->cipher_ctx))
return 0;
EVP_MAC_CTX_free(dest->mac_ctx_init);
dest->mac_ctx_init = EVP_MAC_CTX_dup(src->mac_ctx_init);
if (dest->mac_ctx_init == NULL)
return 0;
dest->mac = src->mac;
if (dest->mac != NULL)
EVP_MAC_up_ref(dest->mac);
return 1;
}
/*
* Provide any AAD. This can be called multiple times.
* Per RFC5297, the last piece of associated data
* is the nonce, but it's not treated special
*/
int ossl_siv128_aad(SIV128_CONTEXT *ctx, const unsigned char *aad,
size_t len)
{
SIV_BLOCK mac_out;
size_t out_len = SIV_LEN;
EVP_MAC_CTX *mac_ctx;
siv128_dbl(&ctx->d);
if ((mac_ctx = EVP_MAC_CTX_dup(ctx->mac_ctx_init)) == NULL
|| !EVP_MAC_update(mac_ctx, aad, len)
|| !EVP_MAC_final(mac_ctx, mac_out.byte, &out_len,
sizeof(mac_out.byte))
|| out_len != SIV_LEN) {
EVP_MAC_CTX_free(mac_ctx);
return 0;
}
EVP_MAC_CTX_free(mac_ctx);
siv128_xorblock(&ctx->d, &mac_out);
return 1;
}
/*
* Provide any data to be encrypted. This can be called once.
*/
int ossl_siv128_encrypt(SIV128_CONTEXT *ctx,
const unsigned char *in, unsigned char *out,
size_t len)
{
SIV_BLOCK q;
/* can only do one crypto operation */
if (ctx->crypto_ok == 0)
return 0;
ctx->crypto_ok--;
if (!siv128_do_s2v_p(ctx, &q, in, len))
return 0;
memcpy(ctx->tag.byte, &q, SIV_LEN);
q.byte[8] &= 0x7f;
q.byte[12] &= 0x7f;
if (!siv128_do_encrypt(ctx->cipher_ctx, out, in, len, &q))
return 0;
ctx->final_ret = 0;
return len;
}
/*
* Provide any data to be decrypted. This can be called once.
*/
int ossl_siv128_decrypt(SIV128_CONTEXT *ctx,
const unsigned char *in, unsigned char *out,
size_t len)
{
unsigned char* p;
SIV_BLOCK t, q;
int i;
/* can only do one crypto operation */
if (ctx->crypto_ok == 0)
return 0;
ctx->crypto_ok--;
memcpy(&q, ctx->tag.byte, SIV_LEN);
q.byte[8] &= 0x7f;
q.byte[12] &= 0x7f;
if (!siv128_do_encrypt(ctx->cipher_ctx, out, in, len, &q)
|| !siv128_do_s2v_p(ctx, &t, out, len))
return 0;
p = ctx->tag.byte;
for (i = 0; i < SIV_LEN; i++)
t.byte[i] ^= p[i];
if ((t.word[0] | t.word[1]) != 0) {
OPENSSL_cleanse(out, len);
return 0;
}
ctx->final_ret = 0;
return len;
}
/*
* Return the already calculated final result.
*/
int ossl_siv128_finish(SIV128_CONTEXT *ctx)
{
return ctx->final_ret;
}
/*
* Set the tag
*/
int ossl_siv128_set_tag(SIV128_CONTEXT *ctx, const unsigned char *tag, size_t len)
{
if (len != SIV_LEN)
return 0;
/* Copy the tag from the supplied buffer */
memcpy(ctx->tag.byte, tag, len);
return 1;
}
/*
* Retrieve the calculated tag
*/
int ossl_siv128_get_tag(SIV128_CONTEXT *ctx, unsigned char *tag, size_t len)
{
if (len != SIV_LEN)
return 0;
/* Copy the tag into the supplied buffer */
memcpy(tag, ctx->tag.byte, len);
return 1;
}
/*
* Release all resources
*/
int ossl_siv128_cleanup(SIV128_CONTEXT *ctx)
{
if (ctx != NULL) {
EVP_CIPHER_CTX_free(ctx->cipher_ctx);
ctx->cipher_ctx = NULL;
EVP_MAC_CTX_free(ctx->mac_ctx_init);
ctx->mac_ctx_init = NULL;
EVP_MAC_free(ctx->mac);
ctx->mac = NULL;
OPENSSL_cleanse(&ctx->d, sizeof(ctx->d));
OPENSSL_cleanse(&ctx->tag, sizeof(ctx->tag));
ctx->final_ret = -1;
ctx->crypto_ok = 1;
}
return 1;
}
int ossl_siv128_speed(SIV128_CONTEXT *ctx, int arg)
{
ctx->crypto_ok = (arg == 1) ? -1 : 1;
return 1;
}
#endif /* OPENSSL_NO_SIV */
|
./openssl/crypto/modes/gcm128.c | /*
* Copyright 2010-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 <string.h>
#include <openssl/crypto.h>
#include "internal/cryptlib.h"
#include "internal/endian.h"
#include "crypto/modes.h"
#if defined(__GNUC__) && !defined(STRICT_ALIGNMENT)
typedef size_t size_t_aX __attribute((__aligned__(1)));
#else
typedef size_t size_t_aX;
#endif
#if defined(BSWAP4) && defined(STRICT_ALIGNMENT)
/* redefine, because alignment is ensured */
# undef GETU32
# define GETU32(p) BSWAP4(*(const u32 *)(p))
# undef PUTU32
# define PUTU32(p,v) *(u32 *)(p) = BSWAP4(v)
#endif
/* RISC-V uses C implementation as a fallback. */
#if defined(__riscv)
# define INCLUDE_C_GMULT_4BIT
# define INCLUDE_C_GHASH_4BIT
#endif
#define PACK(s) ((size_t)(s)<<(sizeof(size_t)*8-16))
#define REDUCE1BIT(V) do { \
if (sizeof(size_t)==8) { \
u64 T = U64(0xe100000000000000) & (0-(V.lo&1)); \
V.lo = (V.hi<<63)|(V.lo>>1); \
V.hi = (V.hi>>1 )^T; \
} \
else { \
u32 T = 0xe1000000U & (0-(u32)(V.lo&1)); \
V.lo = (V.hi<<63)|(V.lo>>1); \
V.hi = (V.hi>>1 )^((u64)T<<32); \
} \
} while(0)
/*-
*
* NOTE: TABLE_BITS and all non-4bit implementations have been removed in 3.1.
*
* Even though permitted values for TABLE_BITS are 8, 4 and 1, it should
* never be set to 8. 8 is effectively reserved for testing purposes.
* TABLE_BITS>1 are lookup-table-driven implementations referred to as
* "Shoup's" in GCM specification. In other words OpenSSL does not cover
* whole spectrum of possible table driven implementations. Why? In
* non-"Shoup's" case memory access pattern is segmented in such manner,
* that it's trivial to see that cache timing information can reveal
* fair portion of intermediate hash value. Given that ciphertext is
* always available to attacker, it's possible for him to attempt to
* deduce secret parameter H and if successful, tamper with messages
* [which is nothing but trivial in CTR mode]. In "Shoup's" case it's
* not as trivial, but there is no reason to believe that it's resistant
* to cache-timing attack. And the thing about "8-bit" implementation is
* that it consumes 16 (sixteen) times more memory, 4KB per individual
* key + 1KB shared. Well, on pros side it should be twice as fast as
* "4-bit" version. And for gcc-generated x86[_64] code, "8-bit" version
* was observed to run ~75% faster, closer to 100% for commercial
* compilers... Yet "4-bit" procedure is preferred, because it's
* believed to provide better security-performance balance and adequate
* all-round performance. "All-round" refers to things like:
*
* - shorter setup time effectively improves overall timing for
* handling short messages;
* - larger table allocation can become unbearable because of VM
* subsystem penalties (for example on Windows large enough free
* results in VM working set trimming, meaning that consequent
* malloc would immediately incur working set expansion);
* - larger table has larger cache footprint, which can affect
* performance of other code paths (not necessarily even from same
* thread in Hyper-Threading world);
*
* Value of 1 is not appropriate for performance reasons.
*/
static void gcm_init_4bit(u128 Htable[16], const u64 H[2])
{
u128 V;
# if defined(OPENSSL_SMALL_FOOTPRINT)
int i;
# endif
Htable[0].hi = 0;
Htable[0].lo = 0;
V.hi = H[0];
V.lo = H[1];
# if defined(OPENSSL_SMALL_FOOTPRINT)
for (Htable[8] = V, i = 4; i > 0; i >>= 1) {
REDUCE1BIT(V);
Htable[i] = V;
}
for (i = 2; i < 16; i <<= 1) {
u128 *Hi = Htable + i;
int j;
for (V = *Hi, j = 1; j < i; ++j) {
Hi[j].hi = V.hi ^ Htable[j].hi;
Hi[j].lo = V.lo ^ Htable[j].lo;
}
}
# else
Htable[8] = V;
REDUCE1BIT(V);
Htable[4] = V;
REDUCE1BIT(V);
Htable[2] = V;
REDUCE1BIT(V);
Htable[1] = V;
Htable[3].hi = V.hi ^ Htable[2].hi, Htable[3].lo = V.lo ^ Htable[2].lo;
V = Htable[4];
Htable[5].hi = V.hi ^ Htable[1].hi, Htable[5].lo = V.lo ^ Htable[1].lo;
Htable[6].hi = V.hi ^ Htable[2].hi, Htable[6].lo = V.lo ^ Htable[2].lo;
Htable[7].hi = V.hi ^ Htable[3].hi, Htable[7].lo = V.lo ^ Htable[3].lo;
V = Htable[8];
Htable[9].hi = V.hi ^ Htable[1].hi, Htable[9].lo = V.lo ^ Htable[1].lo;
Htable[10].hi = V.hi ^ Htable[2].hi, Htable[10].lo = V.lo ^ Htable[2].lo;
Htable[11].hi = V.hi ^ Htable[3].hi, Htable[11].lo = V.lo ^ Htable[3].lo;
Htable[12].hi = V.hi ^ Htable[4].hi, Htable[12].lo = V.lo ^ Htable[4].lo;
Htable[13].hi = V.hi ^ Htable[5].hi, Htable[13].lo = V.lo ^ Htable[5].lo;
Htable[14].hi = V.hi ^ Htable[6].hi, Htable[14].lo = V.lo ^ Htable[6].lo;
Htable[15].hi = V.hi ^ Htable[7].hi, Htable[15].lo = V.lo ^ Htable[7].lo;
# endif
# if defined(GHASH_ASM) && (defined(__arm__) || defined(__arm))
/*
* ARM assembler expects specific dword order in Htable.
*/
{
int j;
DECLARE_IS_ENDIAN;
if (IS_LITTLE_ENDIAN)
for (j = 0; j < 16; ++j) {
V = Htable[j];
Htable[j].hi = V.lo;
Htable[j].lo = V.hi;
} else
for (j = 0; j < 16; ++j) {
V = Htable[j];
Htable[j].hi = V.lo << 32 | V.lo >> 32;
Htable[j].lo = V.hi << 32 | V.hi >> 32;
}
}
# endif
}
# if !defined(GHASH_ASM) || defined(INCLUDE_C_GMULT_4BIT)
static const size_t rem_4bit[16] = {
PACK(0x0000), PACK(0x1C20), PACK(0x3840), PACK(0x2460),
PACK(0x7080), PACK(0x6CA0), PACK(0x48C0), PACK(0x54E0),
PACK(0xE100), PACK(0xFD20), PACK(0xD940), PACK(0xC560),
PACK(0x9180), PACK(0x8DA0), PACK(0xA9C0), PACK(0xB5E0)
};
static void gcm_gmult_4bit(u64 Xi[2], const u128 Htable[16])
{
u128 Z;
int cnt = 15;
size_t rem, nlo, nhi;
DECLARE_IS_ENDIAN;
nlo = ((const u8 *)Xi)[15];
nhi = nlo >> 4;
nlo &= 0xf;
Z.hi = Htable[nlo].hi;
Z.lo = Htable[nlo].lo;
while (1) {
rem = (size_t)Z.lo & 0xf;
Z.lo = (Z.hi << 60) | (Z.lo >> 4);
Z.hi = (Z.hi >> 4);
if (sizeof(size_t) == 8)
Z.hi ^= rem_4bit[rem];
else
Z.hi ^= (u64)rem_4bit[rem] << 32;
Z.hi ^= Htable[nhi].hi;
Z.lo ^= Htable[nhi].lo;
if (--cnt < 0)
break;
nlo = ((const u8 *)Xi)[cnt];
nhi = nlo >> 4;
nlo &= 0xf;
rem = (size_t)Z.lo & 0xf;
Z.lo = (Z.hi << 60) | (Z.lo >> 4);
Z.hi = (Z.hi >> 4);
if (sizeof(size_t) == 8)
Z.hi ^= rem_4bit[rem];
else
Z.hi ^= (u64)rem_4bit[rem] << 32;
Z.hi ^= Htable[nlo].hi;
Z.lo ^= Htable[nlo].lo;
}
if (IS_LITTLE_ENDIAN) {
# ifdef BSWAP8
Xi[0] = BSWAP8(Z.hi);
Xi[1] = BSWAP8(Z.lo);
# else
u8 *p = (u8 *)Xi;
u32 v;
v = (u32)(Z.hi >> 32);
PUTU32(p, v);
v = (u32)(Z.hi);
PUTU32(p + 4, v);
v = (u32)(Z.lo >> 32);
PUTU32(p + 8, v);
v = (u32)(Z.lo);
PUTU32(p + 12, v);
# endif
} else {
Xi[0] = Z.hi;
Xi[1] = Z.lo;
}
}
# endif
# if !defined(GHASH_ASM) || defined(INCLUDE_C_GHASH_4BIT)
# if !defined(OPENSSL_SMALL_FOOTPRINT)
/*
* Streamed gcm_mult_4bit, see CRYPTO_gcm128_[en|de]crypt for
* details... Compiler-generated code doesn't seem to give any
* performance improvement, at least not on x86[_64]. It's here
* mostly as reference and a placeholder for possible future
* non-trivial optimization[s]...
*/
static void gcm_ghash_4bit(u64 Xi[2], const u128 Htable[16],
const u8 *inp, size_t len)
{
u128 Z;
int cnt;
size_t rem, nlo, nhi;
DECLARE_IS_ENDIAN;
do {
cnt = 15;
nlo = ((const u8 *)Xi)[15];
nlo ^= inp[15];
nhi = nlo >> 4;
nlo &= 0xf;
Z.hi = Htable[nlo].hi;
Z.lo = Htable[nlo].lo;
while (1) {
rem = (size_t)Z.lo & 0xf;
Z.lo = (Z.hi << 60) | (Z.lo >> 4);
Z.hi = (Z.hi >> 4);
if (sizeof(size_t) == 8)
Z.hi ^= rem_4bit[rem];
else
Z.hi ^= (u64)rem_4bit[rem] << 32;
Z.hi ^= Htable[nhi].hi;
Z.lo ^= Htable[nhi].lo;
if (--cnt < 0)
break;
nlo = ((const u8 *)Xi)[cnt];
nlo ^= inp[cnt];
nhi = nlo >> 4;
nlo &= 0xf;
rem = (size_t)Z.lo & 0xf;
Z.lo = (Z.hi << 60) | (Z.lo >> 4);
Z.hi = (Z.hi >> 4);
if (sizeof(size_t) == 8)
Z.hi ^= rem_4bit[rem];
else
Z.hi ^= (u64)rem_4bit[rem] << 32;
Z.hi ^= Htable[nlo].hi;
Z.lo ^= Htable[nlo].lo;
}
if (IS_LITTLE_ENDIAN) {
# ifdef BSWAP8
Xi[0] = BSWAP8(Z.hi);
Xi[1] = BSWAP8(Z.lo);
# else
u8 *p = (u8 *)Xi;
u32 v;
v = (u32)(Z.hi >> 32);
PUTU32(p, v);
v = (u32)(Z.hi);
PUTU32(p + 4, v);
v = (u32)(Z.lo >> 32);
PUTU32(p + 8, v);
v = (u32)(Z.lo);
PUTU32(p + 12, v);
# endif
} else {
Xi[0] = Z.hi;
Xi[1] = Z.lo;
}
inp += 16;
/* Block size is 128 bits so len is a multiple of 16 */
len -= 16;
} while (len > 0);
}
# endif
# else
void gcm_gmult_4bit(u64 Xi[2], const u128 Htable[16]);
void gcm_ghash_4bit(u64 Xi[2], const u128 Htable[16], const u8 *inp,
size_t len);
# endif
# define GCM_MUL(ctx) ctx->funcs.gmult(ctx->Xi.u,ctx->Htable)
# if defined(GHASH_ASM) || !defined(OPENSSL_SMALL_FOOTPRINT)
# define GHASH(ctx,in,len) ctx->funcs.ghash((ctx)->Xi.u,(ctx)->Htable,in,len)
/*
* GHASH_CHUNK is "stride parameter" missioned to mitigate cache trashing
* effect. In other words idea is to hash data while it's still in L1 cache
* after encryption pass...
*/
# define GHASH_CHUNK (3*1024)
# endif
#if (defined(GHASH_ASM) || defined(OPENSSL_CPUID_OBJ))
# if !defined(I386_ONLY) && \
(defined(__i386) || defined(__i386__) || \
defined(__x86_64) || defined(__x86_64__) || \
defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64))
# define GHASH_ASM_X86_OR_64
void gcm_init_clmul(u128 Htable[16], const u64 Xi[2]);
void gcm_gmult_clmul(u64 Xi[2], const u128 Htable[16]);
void gcm_ghash_clmul(u64 Xi[2], const u128 Htable[16], const u8 *inp,
size_t len);
# if defined(__i386) || defined(__i386__) || defined(_M_IX86)
# define gcm_init_avx gcm_init_clmul
# define gcm_gmult_avx gcm_gmult_clmul
# define gcm_ghash_avx gcm_ghash_clmul
# else
void gcm_init_avx(u128 Htable[16], const u64 Xi[2]);
void gcm_gmult_avx(u64 Xi[2], const u128 Htable[16]);
void gcm_ghash_avx(u64 Xi[2], const u128 Htable[16], const u8 *inp,
size_t len);
# endif
# if defined(__i386) || defined(__i386__) || defined(_M_IX86)
# define GHASH_ASM_X86
void gcm_gmult_4bit_mmx(u64 Xi[2], const u128 Htable[16]);
void gcm_ghash_4bit_mmx(u64 Xi[2], const u128 Htable[16], const u8 *inp,
size_t len);
void gcm_gmult_4bit_x86(u64 Xi[2], const u128 Htable[16]);
void gcm_ghash_4bit_x86(u64 Xi[2], const u128 Htable[16], const u8 *inp,
size_t len);
# endif
# elif defined(__arm__) || defined(__arm) || defined(__aarch64__) || defined(_M_ARM64)
# include "arm_arch.h"
# if __ARM_MAX_ARCH__>=7
# define GHASH_ASM_ARM
# define PMULL_CAPABLE (OPENSSL_armcap_P & ARMV8_PMULL)
# if defined(__arm__) || defined(__arm)
# define NEON_CAPABLE (OPENSSL_armcap_P & ARMV7_NEON)
# endif
void gcm_init_neon(u128 Htable[16], const u64 Xi[2]);
void gcm_gmult_neon(u64 Xi[2], const u128 Htable[16]);
void gcm_ghash_neon(u64 Xi[2], const u128 Htable[16], const u8 *inp,
size_t len);
void gcm_init_v8(u128 Htable[16], const u64 Xi[2]);
void gcm_gmult_v8(u64 Xi[2], const u128 Htable[16]);
void gcm_ghash_v8(u64 Xi[2], const u128 Htable[16], const u8 *inp,
size_t len);
# endif
# elif defined(__sparc__) || defined(__sparc)
# include "crypto/sparc_arch.h"
# define GHASH_ASM_SPARC
void gcm_init_vis3(u128 Htable[16], const u64 Xi[2]);
void gcm_gmult_vis3(u64 Xi[2], const u128 Htable[16]);
void gcm_ghash_vis3(u64 Xi[2], const u128 Htable[16], const u8 *inp,
size_t len);
# elif defined(OPENSSL_CPUID_OBJ) && (defined(__powerpc__) || defined(__POWERPC__) || defined(_ARCH_PPC))
# include "crypto/ppc_arch.h"
# define GHASH_ASM_PPC
void gcm_init_p8(u128 Htable[16], const u64 Xi[2]);
void gcm_gmult_p8(u64 Xi[2], const u128 Htable[16]);
void gcm_ghash_p8(u64 Xi[2], const u128 Htable[16], const u8 *inp,
size_t len);
# elif defined(OPENSSL_CPUID_OBJ) && defined(__riscv) && __riscv_xlen == 64
# include "crypto/riscv_arch.h"
# define GHASH_ASM_RV64I
/* Zbc/Zbkc (scalar crypto with clmul) based routines. */
void gcm_init_rv64i_zbc(u128 Htable[16], const u64 Xi[2]);
void gcm_init_rv64i_zbc__zbb(u128 Htable[16], const u64 Xi[2]);
void gcm_init_rv64i_zbc__zbkb(u128 Htable[16], const u64 Xi[2]);
void gcm_gmult_rv64i_zbc(u64 Xi[2], const u128 Htable[16]);
void gcm_gmult_rv64i_zbc__zbkb(u64 Xi[2], const u128 Htable[16]);
void gcm_ghash_rv64i_zbc(u64 Xi[2], const u128 Htable[16],
const u8 *inp, size_t len);
void gcm_ghash_rv64i_zbc__zbkb(u64 Xi[2], const u128 Htable[16],
const u8 *inp, size_t len);
/* zvkb/Zvbc (vector crypto with vclmul) based routines. */
void gcm_init_rv64i_zvkb_zvbc(u128 Htable[16], const u64 Xi[2]);
void gcm_gmult_rv64i_zvkb_zvbc(u64 Xi[2], const u128 Htable[16]);
void gcm_ghash_rv64i_zvkb_zvbc(u64 Xi[2], const u128 Htable[16],
const u8 *inp, size_t len);
/* Zvkg (vector crypto with vgmul.vv and vghsh.vv). */
void gcm_init_rv64i_zvkg(u128 Htable[16], const u64 Xi[2]);
void gcm_init_rv64i_zvkg_zvkb(u128 Htable[16], const u64 Xi[2]);
void gcm_gmult_rv64i_zvkg(u64 Xi[2], const u128 Htable[16]);
void gcm_ghash_rv64i_zvkg(u64 Xi[2], const u128 Htable[16],
const u8 *inp, size_t len);
# endif
#endif
static void gcm_get_funcs(struct gcm_funcs_st *ctx)
{
/* set defaults -- overridden below as needed */
ctx->ginit = gcm_init_4bit;
#if !defined(GHASH_ASM)
ctx->gmult = gcm_gmult_4bit;
#else
ctx->gmult = NULL;
#endif
#if !defined(GHASH_ASM) && !defined(OPENSSL_SMALL_FOOTPRINT)
ctx->ghash = gcm_ghash_4bit;
#else
ctx->ghash = NULL;
#endif
#if defined(GHASH_ASM_X86_OR_64)
# if !defined(GHASH_ASM_X86) || defined(OPENSSL_IA32_SSE2)
/* x86_64 */
if (OPENSSL_ia32cap_P[1] & (1 << 1)) { /* check PCLMULQDQ bit */
if (((OPENSSL_ia32cap_P[1] >> 22) & 0x41) == 0x41) { /* AVX+MOVBE */
ctx->ginit = gcm_init_avx;
ctx->gmult = gcm_gmult_avx;
ctx->ghash = gcm_ghash_avx;
} else {
ctx->ginit = gcm_init_clmul;
ctx->gmult = gcm_gmult_clmul;
ctx->ghash = gcm_ghash_clmul;
}
return;
}
# endif
# if defined(GHASH_ASM_X86)
/* x86 only */
# if defined(OPENSSL_IA32_SSE2)
if (OPENSSL_ia32cap_P[0] & (1 << 25)) { /* check SSE bit */
ctx->gmult = gcm_gmult_4bit_mmx;
ctx->ghash = gcm_ghash_4bit_mmx;
return;
}
# else
if (OPENSSL_ia32cap_P[0] & (1 << 23)) { /* check MMX bit */
ctx->gmult = gcm_gmult_4bit_mmx;
ctx->ghash = gcm_ghash_4bit_mmx;
return;
}
# endif
ctx->gmult = gcm_gmult_4bit_x86;
ctx->ghash = gcm_ghash_4bit_x86;
return;
# else
/* x86_64 fallback defaults */
ctx->gmult = gcm_gmult_4bit;
ctx->ghash = gcm_ghash_4bit;
return;
# endif
#elif defined(GHASH_ASM_ARM)
/* ARM defaults */
ctx->gmult = gcm_gmult_4bit;
ctx->ghash = gcm_ghash_4bit;
# ifdef PMULL_CAPABLE
if (PMULL_CAPABLE) {
ctx->ginit = (gcm_init_fn)gcm_init_v8;
ctx->gmult = gcm_gmult_v8;
ctx->ghash = gcm_ghash_v8;
}
# elif defined(NEON_CAPABLE)
if (NEON_CAPABLE) {
ctx->ginit = gcm_init_neon;
ctx->gmult = gcm_gmult_neon;
ctx->ghash = gcm_ghash_neon;
}
# endif
return;
#elif defined(GHASH_ASM_SPARC)
/* SPARC defaults */
ctx->gmult = gcm_gmult_4bit;
ctx->ghash = gcm_ghash_4bit;
if (OPENSSL_sparcv9cap_P[0] & SPARCV9_VIS3) {
ctx->ginit = gcm_init_vis3;
ctx->gmult = gcm_gmult_vis3;
ctx->ghash = gcm_ghash_vis3;
}
return;
#elif defined(GHASH_ASM_PPC)
/* PowerPC does not define GHASH_ASM; defaults set above */
if (OPENSSL_ppccap_P & PPC_CRYPTO207) {
ctx->ginit = gcm_init_p8;
ctx->gmult = gcm_gmult_p8;
ctx->ghash = gcm_ghash_p8;
}
return;
#elif defined(GHASH_ASM_RV64I)
/* RISCV defaults */
ctx->gmult = gcm_gmult_4bit;
ctx->ghash = gcm_ghash_4bit;
if (RISCV_HAS_ZVKG() && riscv_vlen() >= 128) {
if (RISCV_HAS_ZVKB())
ctx->ginit = gcm_init_rv64i_zvkg_zvkb;
else
ctx->ginit = gcm_init_rv64i_zvkg;
ctx->gmult = gcm_gmult_rv64i_zvkg;
ctx->ghash = gcm_ghash_rv64i_zvkg;
} else if (RISCV_HAS_ZVKB() && RISCV_HAS_ZVBC() && riscv_vlen() >= 128) {
ctx->ginit = gcm_init_rv64i_zvkb_zvbc;
ctx->gmult = gcm_gmult_rv64i_zvkb_zvbc;
ctx->ghash = gcm_ghash_rv64i_zvkb_zvbc;
} else if (RISCV_HAS_ZBC()) {
if (RISCV_HAS_ZBKB()) {
ctx->ginit = gcm_init_rv64i_zbc__zbkb;
ctx->gmult = gcm_gmult_rv64i_zbc__zbkb;
ctx->ghash = gcm_ghash_rv64i_zbc__zbkb;
} else if (RISCV_HAS_ZBB()) {
ctx->ginit = gcm_init_rv64i_zbc__zbb;
ctx->gmult = gcm_gmult_rv64i_zbc;
ctx->ghash = gcm_ghash_rv64i_zbc;
} else {
ctx->ginit = gcm_init_rv64i_zbc;
ctx->gmult = gcm_gmult_rv64i_zbc;
ctx->ghash = gcm_ghash_rv64i_zbc;
}
}
return;
#elif defined(GHASH_ASM)
/* all other architectures use the generic names */
ctx->gmult = gcm_gmult_4bit;
ctx->ghash = gcm_ghash_4bit;
return;
#endif
}
void ossl_gcm_init_4bit(u128 Htable[16], const u64 H[2])
{
struct gcm_funcs_st funcs;
gcm_get_funcs(&funcs);
funcs.ginit(Htable, H);
}
void ossl_gcm_gmult_4bit(u64 Xi[2], const u128 Htable[16])
{
struct gcm_funcs_st funcs;
gcm_get_funcs(&funcs);
funcs.gmult(Xi, Htable);
}
void ossl_gcm_ghash_4bit(u64 Xi[2], const u128 Htable[16],
const u8 *inp, size_t len)
{
struct gcm_funcs_st funcs;
u64 tmp[2];
size_t i;
gcm_get_funcs(&funcs);
if (funcs.ghash != NULL) {
funcs.ghash(Xi, Htable, inp, len);
} else {
/* Emulate ghash if needed */
for (i = 0; i < len; i += 16) {
memcpy(tmp, &inp[i], sizeof(tmp));
Xi[0] ^= tmp[0];
Xi[1] ^= tmp[1];
funcs.gmult(Xi, Htable);
}
}
}
void CRYPTO_gcm128_init(GCM128_CONTEXT *ctx, void *key, block128_f block)
{
DECLARE_IS_ENDIAN;
memset(ctx, 0, sizeof(*ctx));
ctx->block = block;
ctx->key = key;
(*block) (ctx->H.c, ctx->H.c, key);
if (IS_LITTLE_ENDIAN) {
/* H is stored in host byte order */
#ifdef BSWAP8
ctx->H.u[0] = BSWAP8(ctx->H.u[0]);
ctx->H.u[1] = BSWAP8(ctx->H.u[1]);
#else
u8 *p = ctx->H.c;
u64 hi, lo;
hi = (u64)GETU32(p) << 32 | GETU32(p + 4);
lo = (u64)GETU32(p + 8) << 32 | GETU32(p + 12);
ctx->H.u[0] = hi;
ctx->H.u[1] = lo;
#endif
}
gcm_get_funcs(&ctx->funcs);
ctx->funcs.ginit(ctx->Htable, ctx->H.u);
}
void CRYPTO_gcm128_setiv(GCM128_CONTEXT *ctx, const unsigned char *iv,
size_t len)
{
DECLARE_IS_ENDIAN;
unsigned int ctr;
ctx->len.u[0] = 0; /* AAD length */
ctx->len.u[1] = 0; /* message length */
ctx->ares = 0;
ctx->mres = 0;
if (len == 12) {
memcpy(ctx->Yi.c, iv, 12);
ctx->Yi.c[12] = 0;
ctx->Yi.c[13] = 0;
ctx->Yi.c[14] = 0;
ctx->Yi.c[15] = 1;
ctr = 1;
} else {
size_t i;
u64 len0 = len;
/* Borrow ctx->Xi to calculate initial Yi */
ctx->Xi.u[0] = 0;
ctx->Xi.u[1] = 0;
while (len >= 16) {
for (i = 0; i < 16; ++i)
ctx->Xi.c[i] ^= iv[i];
GCM_MUL(ctx);
iv += 16;
len -= 16;
}
if (len) {
for (i = 0; i < len; ++i)
ctx->Xi.c[i] ^= iv[i];
GCM_MUL(ctx);
}
len0 <<= 3;
if (IS_LITTLE_ENDIAN) {
#ifdef BSWAP8
ctx->Xi.u[1] ^= BSWAP8(len0);
#else
ctx->Xi.c[8] ^= (u8)(len0 >> 56);
ctx->Xi.c[9] ^= (u8)(len0 >> 48);
ctx->Xi.c[10] ^= (u8)(len0 >> 40);
ctx->Xi.c[11] ^= (u8)(len0 >> 32);
ctx->Xi.c[12] ^= (u8)(len0 >> 24);
ctx->Xi.c[13] ^= (u8)(len0 >> 16);
ctx->Xi.c[14] ^= (u8)(len0 >> 8);
ctx->Xi.c[15] ^= (u8)(len0);
#endif
} else {
ctx->Xi.u[1] ^= len0;
}
GCM_MUL(ctx);
if (IS_LITTLE_ENDIAN)
#ifdef BSWAP4
ctr = BSWAP4(ctx->Xi.d[3]);
#else
ctr = GETU32(ctx->Xi.c + 12);
#endif
else
ctr = ctx->Xi.d[3];
/* Copy borrowed Xi to Yi */
ctx->Yi.u[0] = ctx->Xi.u[0];
ctx->Yi.u[1] = ctx->Xi.u[1];
}
ctx->Xi.u[0] = 0;
ctx->Xi.u[1] = 0;
(*ctx->block) (ctx->Yi.c, ctx->EK0.c, ctx->key);
++ctr;
if (IS_LITTLE_ENDIAN)
#ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
#else
PUTU32(ctx->Yi.c + 12, ctr);
#endif
else
ctx->Yi.d[3] = ctr;
}
int CRYPTO_gcm128_aad(GCM128_CONTEXT *ctx, const unsigned char *aad,
size_t len)
{
size_t i;
unsigned int n;
u64 alen = ctx->len.u[0];
if (ctx->len.u[1])
return -2;
alen += len;
if (alen > (U64(1) << 61) || (sizeof(len) == 8 && alen < len))
return -1;
ctx->len.u[0] = alen;
n = ctx->ares;
if (n) {
while (n && len) {
ctx->Xi.c[n] ^= *(aad++);
--len;
n = (n + 1) % 16;
}
if (n == 0)
GCM_MUL(ctx);
else {
ctx->ares = n;
return 0;
}
}
#ifdef GHASH
if ((i = (len & (size_t)-16))) {
GHASH(ctx, aad, i);
aad += i;
len -= i;
}
#else
while (len >= 16) {
for (i = 0; i < 16; ++i)
ctx->Xi.c[i] ^= aad[i];
GCM_MUL(ctx);
aad += 16;
len -= 16;
}
#endif
if (len) {
n = (unsigned int)len;
for (i = 0; i < len; ++i)
ctx->Xi.c[i] ^= aad[i];
}
ctx->ares = n;
return 0;
}
int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx,
const unsigned char *in, unsigned char *out,
size_t len)
{
DECLARE_IS_ENDIAN;
unsigned int n, ctr, mres;
size_t i;
u64 mlen = ctx->len.u[1];
block128_f block = ctx->block;
void *key = ctx->key;
mlen += len;
if (mlen > ((U64(1) << 36) - 32) || (sizeof(len) == 8 && mlen < len))
return -1;
ctx->len.u[1] = mlen;
mres = ctx->mres;
if (ctx->ares) {
/* First call to encrypt finalizes GHASH(AAD) */
#if defined(GHASH) && !defined(OPENSSL_SMALL_FOOTPRINT)
if (len == 0) {
GCM_MUL(ctx);
ctx->ares = 0;
return 0;
}
memcpy(ctx->Xn, ctx->Xi.c, sizeof(ctx->Xi));
ctx->Xi.u[0] = 0;
ctx->Xi.u[1] = 0;
mres = sizeof(ctx->Xi);
#else
GCM_MUL(ctx);
#endif
ctx->ares = 0;
}
if (IS_LITTLE_ENDIAN)
#ifdef BSWAP4
ctr = BSWAP4(ctx->Yi.d[3]);
#else
ctr = GETU32(ctx->Yi.c + 12);
#endif
else
ctr = ctx->Yi.d[3];
n = mres % 16;
#if !defined(OPENSSL_SMALL_FOOTPRINT)
if (16 % sizeof(size_t) == 0) { /* always true actually */
do {
if (n) {
# if defined(GHASH)
while (n && len) {
ctx->Xn[mres++] = *(out++) = *(in++) ^ ctx->EKi.c[n];
--len;
n = (n + 1) % 16;
}
if (n == 0) {
GHASH(ctx, ctx->Xn, mres);
mres = 0;
} else {
ctx->mres = mres;
return 0;
}
# else
while (n && len) {
ctx->Xi.c[n] ^= *(out++) = *(in++) ^ ctx->EKi.c[n];
--len;
n = (n + 1) % 16;
}
if (n == 0) {
GCM_MUL(ctx);
mres = 0;
} else {
ctx->mres = n;
return 0;
}
# endif
}
# if defined(STRICT_ALIGNMENT)
if (((size_t)in | (size_t)out) % sizeof(size_t) != 0)
break;
# endif
# if defined(GHASH)
if (len >= 16 && mres) {
GHASH(ctx, ctx->Xn, mres);
mres = 0;
}
# if defined(GHASH_CHUNK)
while (len >= GHASH_CHUNK) {
size_t j = GHASH_CHUNK;
while (j) {
size_t_aX *out_t = (size_t_aX *)out;
const size_t_aX *in_t = (const size_t_aX *)in;
(*block) (ctx->Yi.c, ctx->EKi.c, key);
++ctr;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
for (i = 0; i < 16 / sizeof(size_t); ++i)
out_t[i] = in_t[i] ^ ctx->EKi.t[i];
out += 16;
in += 16;
j -= 16;
}
GHASH(ctx, out - GHASH_CHUNK, GHASH_CHUNK);
len -= GHASH_CHUNK;
}
# endif
if ((i = (len & (size_t)-16))) {
size_t j = i;
while (len >= 16) {
size_t_aX *out_t = (size_t_aX *)out;
const size_t_aX *in_t = (const size_t_aX *)in;
(*block) (ctx->Yi.c, ctx->EKi.c, key);
++ctr;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
for (i = 0; i < 16 / sizeof(size_t); ++i)
out_t[i] = in_t[i] ^ ctx->EKi.t[i];
out += 16;
in += 16;
len -= 16;
}
GHASH(ctx, out - j, j);
}
# else
while (len >= 16) {
size_t *out_t = (size_t *)out;
const size_t *in_t = (const size_t *)in;
(*block) (ctx->Yi.c, ctx->EKi.c, key);
++ctr;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
for (i = 0; i < 16 / sizeof(size_t); ++i)
ctx->Xi.t[i] ^= out_t[i] = in_t[i] ^ ctx->EKi.t[i];
GCM_MUL(ctx);
out += 16;
in += 16;
len -= 16;
}
# endif
if (len) {
(*block) (ctx->Yi.c, ctx->EKi.c, key);
++ctr;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
# if defined(GHASH)
while (len--) {
ctx->Xn[mres++] = out[n] = in[n] ^ ctx->EKi.c[n];
++n;
}
# else
while (len--) {
ctx->Xi.c[n] ^= out[n] = in[n] ^ ctx->EKi.c[n];
++n;
}
mres = n;
# endif
}
ctx->mres = mres;
return 0;
} while (0);
}
#endif
for (i = 0; i < len; ++i) {
if (n == 0) {
(*block) (ctx->Yi.c, ctx->EKi.c, key);
++ctr;
if (IS_LITTLE_ENDIAN)
#ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
#else
PUTU32(ctx->Yi.c + 12, ctr);
#endif
else
ctx->Yi.d[3] = ctr;
}
#if defined(GHASH) && !defined(OPENSSL_SMALL_FOOTPRINT)
ctx->Xn[mres++] = out[i] = in[i] ^ ctx->EKi.c[n];
n = (n + 1) % 16;
if (mres == sizeof(ctx->Xn)) {
GHASH(ctx,ctx->Xn,sizeof(ctx->Xn));
mres = 0;
}
#else
ctx->Xi.c[n] ^= out[i] = in[i] ^ ctx->EKi.c[n];
mres = n = (n + 1) % 16;
if (n == 0)
GCM_MUL(ctx);
#endif
}
ctx->mres = mres;
return 0;
}
int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx,
const unsigned char *in, unsigned char *out,
size_t len)
{
DECLARE_IS_ENDIAN;
unsigned int n, ctr, mres;
size_t i;
u64 mlen = ctx->len.u[1];
block128_f block = ctx->block;
void *key = ctx->key;
mlen += len;
if (mlen > ((U64(1) << 36) - 32) || (sizeof(len) == 8 && mlen < len))
return -1;
ctx->len.u[1] = mlen;
mres = ctx->mres;
if (ctx->ares) {
/* First call to decrypt finalizes GHASH(AAD) */
#if defined(GHASH) && !defined(OPENSSL_SMALL_FOOTPRINT)
if (len == 0) {
GCM_MUL(ctx);
ctx->ares = 0;
return 0;
}
memcpy(ctx->Xn, ctx->Xi.c, sizeof(ctx->Xi));
ctx->Xi.u[0] = 0;
ctx->Xi.u[1] = 0;
mres = sizeof(ctx->Xi);
#else
GCM_MUL(ctx);
#endif
ctx->ares = 0;
}
if (IS_LITTLE_ENDIAN)
#ifdef BSWAP4
ctr = BSWAP4(ctx->Yi.d[3]);
#else
ctr = GETU32(ctx->Yi.c + 12);
#endif
else
ctr = ctx->Yi.d[3];
n = mres % 16;
#if !defined(OPENSSL_SMALL_FOOTPRINT)
if (16 % sizeof(size_t) == 0) { /* always true actually */
do {
if (n) {
# if defined(GHASH)
while (n && len) {
*(out++) = (ctx->Xn[mres++] = *(in++)) ^ ctx->EKi.c[n];
--len;
n = (n + 1) % 16;
}
if (n == 0) {
GHASH(ctx, ctx->Xn, mres);
mres = 0;
} else {
ctx->mres = mres;
return 0;
}
# else
while (n && len) {
u8 c = *(in++);
*(out++) = c ^ ctx->EKi.c[n];
ctx->Xi.c[n] ^= c;
--len;
n = (n + 1) % 16;
}
if (n == 0) {
GCM_MUL(ctx);
mres = 0;
} else {
ctx->mres = n;
return 0;
}
# endif
}
# if defined(STRICT_ALIGNMENT)
if (((size_t)in | (size_t)out) % sizeof(size_t) != 0)
break;
# endif
# if defined(GHASH)
if (len >= 16 && mres) {
GHASH(ctx, ctx->Xn, mres);
mres = 0;
}
# if defined(GHASH_CHUNK)
while (len >= GHASH_CHUNK) {
size_t j = GHASH_CHUNK;
GHASH(ctx, in, GHASH_CHUNK);
while (j) {
size_t_aX *out_t = (size_t_aX *)out;
const size_t_aX *in_t = (const size_t_aX *)in;
(*block) (ctx->Yi.c, ctx->EKi.c, key);
++ctr;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
for (i = 0; i < 16 / sizeof(size_t); ++i)
out_t[i] = in_t[i] ^ ctx->EKi.t[i];
out += 16;
in += 16;
j -= 16;
}
len -= GHASH_CHUNK;
}
# endif
if ((i = (len & (size_t)-16))) {
GHASH(ctx, in, i);
while (len >= 16) {
size_t_aX *out_t = (size_t_aX *)out;
const size_t_aX *in_t = (const size_t_aX *)in;
(*block) (ctx->Yi.c, ctx->EKi.c, key);
++ctr;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
for (i = 0; i < 16 / sizeof(size_t); ++i)
out_t[i] = in_t[i] ^ ctx->EKi.t[i];
out += 16;
in += 16;
len -= 16;
}
}
# else
while (len >= 16) {
size_t *out_t = (size_t *)out;
const size_t *in_t = (const size_t *)in;
(*block) (ctx->Yi.c, ctx->EKi.c, key);
++ctr;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
for (i = 0; i < 16 / sizeof(size_t); ++i) {
size_t c = in_t[i];
out_t[i] = c ^ ctx->EKi.t[i];
ctx->Xi.t[i] ^= c;
}
GCM_MUL(ctx);
out += 16;
in += 16;
len -= 16;
}
# endif
if (len) {
(*block) (ctx->Yi.c, ctx->EKi.c, key);
++ctr;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
# if defined(GHASH)
while (len--) {
out[n] = (ctx->Xn[mres++] = in[n]) ^ ctx->EKi.c[n];
++n;
}
# else
while (len--) {
u8 c = in[n];
ctx->Xi.c[n] ^= c;
out[n] = c ^ ctx->EKi.c[n];
++n;
}
mres = n;
# endif
}
ctx->mres = mres;
return 0;
} while (0);
}
#endif
for (i = 0; i < len; ++i) {
u8 c;
if (n == 0) {
(*block) (ctx->Yi.c, ctx->EKi.c, key);
++ctr;
if (IS_LITTLE_ENDIAN)
#ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
#else
PUTU32(ctx->Yi.c + 12, ctr);
#endif
else
ctx->Yi.d[3] = ctr;
}
#if defined(GHASH) && !defined(OPENSSL_SMALL_FOOTPRINT)
out[i] = (ctx->Xn[mres++] = c = in[i]) ^ ctx->EKi.c[n];
n = (n + 1) % 16;
if (mres == sizeof(ctx->Xn)) {
GHASH(ctx,ctx->Xn,sizeof(ctx->Xn));
mres = 0;
}
#else
c = in[i];
out[i] = c ^ ctx->EKi.c[n];
ctx->Xi.c[n] ^= c;
mres = n = (n + 1) % 16;
if (n == 0)
GCM_MUL(ctx);
#endif
}
ctx->mres = mres;
return 0;
}
int CRYPTO_gcm128_encrypt_ctr32(GCM128_CONTEXT *ctx,
const unsigned char *in, unsigned char *out,
size_t len, ctr128_f stream)
{
#if defined(OPENSSL_SMALL_FOOTPRINT)
return CRYPTO_gcm128_encrypt(ctx, in, out, len);
#else
DECLARE_IS_ENDIAN;
unsigned int n, ctr, mres;
size_t i;
u64 mlen = ctx->len.u[1];
void *key = ctx->key;
mlen += len;
if (mlen > ((U64(1) << 36) - 32) || (sizeof(len) == 8 && mlen < len))
return -1;
ctx->len.u[1] = mlen;
mres = ctx->mres;
if (ctx->ares) {
/* First call to encrypt finalizes GHASH(AAD) */
#if defined(GHASH)
if (len == 0) {
GCM_MUL(ctx);
ctx->ares = 0;
return 0;
}
memcpy(ctx->Xn, ctx->Xi.c, sizeof(ctx->Xi));
ctx->Xi.u[0] = 0;
ctx->Xi.u[1] = 0;
mres = sizeof(ctx->Xi);
#else
GCM_MUL(ctx);
#endif
ctx->ares = 0;
}
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctr = BSWAP4(ctx->Yi.d[3]);
# else
ctr = GETU32(ctx->Yi.c + 12);
# endif
else
ctr = ctx->Yi.d[3];
n = mres % 16;
if (n) {
# if defined(GHASH)
while (n && len) {
ctx->Xn[mres++] = *(out++) = *(in++) ^ ctx->EKi.c[n];
--len;
n = (n + 1) % 16;
}
if (n == 0) {
GHASH(ctx, ctx->Xn, mres);
mres = 0;
} else {
ctx->mres = mres;
return 0;
}
# else
while (n && len) {
ctx->Xi.c[n] ^= *(out++) = *(in++) ^ ctx->EKi.c[n];
--len;
n = (n + 1) % 16;
}
if (n == 0) {
GCM_MUL(ctx);
mres = 0;
} else {
ctx->mres = n;
return 0;
}
# endif
}
# if defined(GHASH)
if (len >= 16 && mres) {
GHASH(ctx, ctx->Xn, mres);
mres = 0;
}
# if defined(GHASH_CHUNK)
while (len >= GHASH_CHUNK) {
(*stream) (in, out, GHASH_CHUNK / 16, key, ctx->Yi.c);
ctr += GHASH_CHUNK / 16;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
GHASH(ctx, out, GHASH_CHUNK);
out += GHASH_CHUNK;
in += GHASH_CHUNK;
len -= GHASH_CHUNK;
}
# endif
# endif
if ((i = (len & (size_t)-16))) {
size_t j = i / 16;
(*stream) (in, out, j, key, ctx->Yi.c);
ctr += (unsigned int)j;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
in += i;
len -= i;
# if defined(GHASH)
GHASH(ctx, out, i);
out += i;
# else
while (j--) {
for (i = 0; i < 16; ++i)
ctx->Xi.c[i] ^= out[i];
GCM_MUL(ctx);
out += 16;
}
# endif
}
if (len) {
(*ctx->block) (ctx->Yi.c, ctx->EKi.c, key);
++ctr;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
while (len--) {
# if defined(GHASH)
ctx->Xn[mres++] = out[n] = in[n] ^ ctx->EKi.c[n];
# else
ctx->Xi.c[mres++] ^= out[n] = in[n] ^ ctx->EKi.c[n];
# endif
++n;
}
}
ctx->mres = mres;
return 0;
#endif
}
int CRYPTO_gcm128_decrypt_ctr32(GCM128_CONTEXT *ctx,
const unsigned char *in, unsigned char *out,
size_t len, ctr128_f stream)
{
#if defined(OPENSSL_SMALL_FOOTPRINT)
return CRYPTO_gcm128_decrypt(ctx, in, out, len);
#else
DECLARE_IS_ENDIAN;
unsigned int n, ctr, mres;
size_t i;
u64 mlen = ctx->len.u[1];
void *key = ctx->key;
mlen += len;
if (mlen > ((U64(1) << 36) - 32) || (sizeof(len) == 8 && mlen < len))
return -1;
ctx->len.u[1] = mlen;
mres = ctx->mres;
if (ctx->ares) {
/* First call to decrypt finalizes GHASH(AAD) */
# if defined(GHASH)
if (len == 0) {
GCM_MUL(ctx);
ctx->ares = 0;
return 0;
}
memcpy(ctx->Xn, ctx->Xi.c, sizeof(ctx->Xi));
ctx->Xi.u[0] = 0;
ctx->Xi.u[1] = 0;
mres = sizeof(ctx->Xi);
# else
GCM_MUL(ctx);
# endif
ctx->ares = 0;
}
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctr = BSWAP4(ctx->Yi.d[3]);
# else
ctr = GETU32(ctx->Yi.c + 12);
# endif
else
ctr = ctx->Yi.d[3];
n = mres % 16;
if (n) {
# if defined(GHASH)
while (n && len) {
*(out++) = (ctx->Xn[mres++] = *(in++)) ^ ctx->EKi.c[n];
--len;
n = (n + 1) % 16;
}
if (n == 0) {
GHASH(ctx, ctx->Xn, mres);
mres = 0;
} else {
ctx->mres = mres;
return 0;
}
# else
while (n && len) {
u8 c = *(in++);
*(out++) = c ^ ctx->EKi.c[n];
ctx->Xi.c[n] ^= c;
--len;
n = (n + 1) % 16;
}
if (n == 0) {
GCM_MUL(ctx);
mres = 0;
} else {
ctx->mres = n;
return 0;
}
# endif
}
# if defined(GHASH)
if (len >= 16 && mres) {
GHASH(ctx, ctx->Xn, mres);
mres = 0;
}
# if defined(GHASH_CHUNK)
while (len >= GHASH_CHUNK) {
GHASH(ctx, in, GHASH_CHUNK);
(*stream) (in, out, GHASH_CHUNK / 16, key, ctx->Yi.c);
ctr += GHASH_CHUNK / 16;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
out += GHASH_CHUNK;
in += GHASH_CHUNK;
len -= GHASH_CHUNK;
}
# endif
# endif
if ((i = (len & (size_t)-16))) {
size_t j = i / 16;
# if defined(GHASH)
GHASH(ctx, in, i);
# else
while (j--) {
size_t k;
for (k = 0; k < 16; ++k)
ctx->Xi.c[k] ^= in[k];
GCM_MUL(ctx);
in += 16;
}
j = i / 16;
in -= i;
# endif
(*stream) (in, out, j, key, ctx->Yi.c);
ctr += (unsigned int)j;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
out += i;
in += i;
len -= i;
}
if (len) {
(*ctx->block) (ctx->Yi.c, ctx->EKi.c, key);
++ctr;
if (IS_LITTLE_ENDIAN)
# ifdef BSWAP4
ctx->Yi.d[3] = BSWAP4(ctr);
# else
PUTU32(ctx->Yi.c + 12, ctr);
# endif
else
ctx->Yi.d[3] = ctr;
while (len--) {
# if defined(GHASH)
out[n] = (ctx->Xn[mres++] = in[n]) ^ ctx->EKi.c[n];
# else
u8 c = in[n];
ctx->Xi.c[mres++] ^= c;
out[n] = c ^ ctx->EKi.c[n];
# endif
++n;
}
}
ctx->mres = mres;
return 0;
#endif
}
int CRYPTO_gcm128_finish(GCM128_CONTEXT *ctx, const unsigned char *tag,
size_t len)
{
DECLARE_IS_ENDIAN;
u64 alen = ctx->len.u[0] << 3;
u64 clen = ctx->len.u[1] << 3;
#if defined(GHASH) && !defined(OPENSSL_SMALL_FOOTPRINT)
u128 bitlen;
unsigned int mres = ctx->mres;
if (mres) {
unsigned blocks = (mres + 15) & -16;
memset(ctx->Xn + mres, 0, blocks - mres);
mres = blocks;
if (mres == sizeof(ctx->Xn)) {
GHASH(ctx, ctx->Xn, mres);
mres = 0;
}
} else if (ctx->ares) {
GCM_MUL(ctx);
}
#else
if (ctx->mres || ctx->ares)
GCM_MUL(ctx);
#endif
if (IS_LITTLE_ENDIAN) {
#ifdef BSWAP8
alen = BSWAP8(alen);
clen = BSWAP8(clen);
#else
u8 *p = ctx->len.c;
ctx->len.u[0] = alen;
ctx->len.u[1] = clen;
alen = (u64)GETU32(p) << 32 | GETU32(p + 4);
clen = (u64)GETU32(p + 8) << 32 | GETU32(p + 12);
#endif
}
#if defined(GHASH) && !defined(OPENSSL_SMALL_FOOTPRINT)
bitlen.hi = alen;
bitlen.lo = clen;
memcpy(ctx->Xn + mres, &bitlen, sizeof(bitlen));
mres += sizeof(bitlen);
GHASH(ctx, ctx->Xn, mres);
#else
ctx->Xi.u[0] ^= alen;
ctx->Xi.u[1] ^= clen;
GCM_MUL(ctx);
#endif
ctx->Xi.u[0] ^= ctx->EK0.u[0];
ctx->Xi.u[1] ^= ctx->EK0.u[1];
if (tag && len <= sizeof(ctx->Xi))
return CRYPTO_memcmp(ctx->Xi.c, tag, len);
else
return -1;
}
void CRYPTO_gcm128_tag(GCM128_CONTEXT *ctx, unsigned char *tag, size_t len)
{
CRYPTO_gcm128_finish(ctx, NULL, 0);
memcpy(tag, ctx->Xi.c,
len <= sizeof(ctx->Xi.c) ? len : sizeof(ctx->Xi.c));
}
GCM128_CONTEXT *CRYPTO_gcm128_new(void *key, block128_f block)
{
GCM128_CONTEXT *ret;
if ((ret = OPENSSL_malloc(sizeof(*ret))) != NULL)
CRYPTO_gcm128_init(ret, key, block);
return ret;
}
void CRYPTO_gcm128_release(GCM128_CONTEXT *ctx)
{
OPENSSL_clear_free(ctx, sizeof(*ctx));
}
|
./openssl/crypto/modes/xts128gb.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/crypto.h>
#include "internal/endian.h"
#include "crypto/modes.h"
#ifndef STRICT_ALIGNMENT
# ifdef __GNUC__
typedef u64 u64_a1 __attribute((__aligned__(1)));
# else
typedef u64 u64_a1;
# endif
#endif
int ossl_crypto_xts128gb_encrypt(const XTS128_CONTEXT *ctx,
const unsigned char iv[16],
const unsigned char *inp, unsigned char *out,
size_t len, int enc)
{
DECLARE_IS_ENDIAN;
union {
u64 u[2];
u32 d[4];
u8 c[16];
} tweak, scratch;
unsigned int i;
if (len < 16)
return -1;
memcpy(tweak.c, iv, 16);
(*ctx->block2) (tweak.c, tweak.c, ctx->key2);
if (!enc && (len % 16))
len -= 16;
while (len >= 16) {
#if defined(STRICT_ALIGNMENT)
memcpy(scratch.c, inp, 16);
scratch.u[0] ^= tweak.u[0];
scratch.u[1] ^= tweak.u[1];
#else
scratch.u[0] = ((u64_a1 *)inp)[0] ^ tweak.u[0];
scratch.u[1] = ((u64_a1 *)inp)[1] ^ tweak.u[1];
#endif
(*ctx->block1) (scratch.c, scratch.c, ctx->key1);
#if defined(STRICT_ALIGNMENT)
scratch.u[0] ^= tweak.u[0];
scratch.u[1] ^= tweak.u[1];
memcpy(out, scratch.c, 16);
#else
((u64_a1 *)out)[0] = scratch.u[0] ^= tweak.u[0];
((u64_a1 *)out)[1] = scratch.u[1] ^= tweak.u[1];
#endif
inp += 16;
out += 16;
len -= 16;
if (len == 0)
return 0;
if (IS_LITTLE_ENDIAN) {
u8 res;
u64 hi, lo;
#ifdef BSWAP8
hi = BSWAP8(tweak.u[0]);
lo = BSWAP8(tweak.u[1]);
#else
u8 *p = tweak.c;
hi = (u64)GETU32(p) << 32 | GETU32(p + 4);
lo = (u64)GETU32(p + 8) << 32 | GETU32(p + 12);
#endif
res = (u8)lo & 1;
tweak.u[0] = (lo >> 1) | (hi << 63);
tweak.u[1] = hi >> 1;
if (res)
tweak.c[15] ^= 0xe1;
#ifdef BSWAP8
hi = BSWAP8(tweak.u[0]);
lo = BSWAP8(tweak.u[1]);
#else
p = tweak.c;
hi = (u64)GETU32(p) << 32 | GETU32(p + 4);
lo = (u64)GETU32(p + 8) << 32 | GETU32(p + 12);
#endif
tweak.u[0] = lo;
tweak.u[1] = hi;
} else {
u8 carry, res;
carry = 0;
for (i = 0; i < 16; ++i) {
res = (tweak.c[i] << 7) & 0x80;
tweak.c[i] = ((tweak.c[i] >> 1) + carry) & 0xff;
carry = res;
}
if (res)
tweak.c[0] ^= 0xe1;
}
}
if (enc) {
for (i = 0; i < len; ++i) {
u8 c = inp[i];
out[i] = scratch.c[i];
scratch.c[i] = c;
}
scratch.u[0] ^= tweak.u[0];
scratch.u[1] ^= tweak.u[1];
(*ctx->block1) (scratch.c, scratch.c, ctx->key1);
scratch.u[0] ^= tweak.u[0];
scratch.u[1] ^= tweak.u[1];
memcpy(out - 16, scratch.c, 16);
} else {
union {
u64 u[2];
u8 c[16];
} tweak1;
if (IS_LITTLE_ENDIAN) {
u8 res;
u64 hi, lo;
#ifdef BSWAP8
hi = BSWAP8(tweak.u[0]);
lo = BSWAP8(tweak.u[1]);
#else
u8 *p = tweak.c;
hi = (u64)GETU32(p) << 32 | GETU32(p + 4);
lo = (u64)GETU32(p + 8) << 32 | GETU32(p + 12);
#endif
res = (u8)lo & 1;
tweak1.u[0] = (lo >> 1) | (hi << 63);
tweak1.u[1] = hi >> 1;
if (res)
tweak1.c[15] ^= 0xe1;
#ifdef BSWAP8
hi = BSWAP8(tweak1.u[0]);
lo = BSWAP8(tweak1.u[1]);
#else
p = tweak1.c;
hi = (u64)GETU32(p) << 32 | GETU32(p + 4);
lo = (u64)GETU32(p + 8) << 32 | GETU32(p + 12);
#endif
tweak1.u[0] = lo;
tweak1.u[1] = hi;
} else {
u8 carry, res;
carry = 0;
for (i = 0; i < 16; ++i) {
res = (tweak.c[i] << 7) & 0x80;
tweak1.c[i] = ((tweak.c[i] >> 1) + carry) & 0xff;
carry = res;
}
if (res)
tweak1.c[0] ^= 0xe1;
}
#if defined(STRICT_ALIGNMENT)
memcpy(scratch.c, inp, 16);
scratch.u[0] ^= tweak1.u[0];
scratch.u[1] ^= tweak1.u[1];
#else
scratch.u[0] = ((u64_a1 *)inp)[0] ^ tweak1.u[0];
scratch.u[1] = ((u64_a1 *)inp)[1] ^ tweak1.u[1];
#endif
(*ctx->block1) (scratch.c, scratch.c, ctx->key1);
scratch.u[0] ^= tweak1.u[0];
scratch.u[1] ^= tweak1.u[1];
for (i = 0; i < len; ++i) {
u8 c = inp[16 + i];
out[16 + i] = scratch.c[i];
scratch.c[i] = c;
}
scratch.u[0] ^= tweak.u[0];
scratch.u[1] ^= tweak.u[1];
(*ctx->block1) (scratch.c, scratch.c, ctx->key1);
#if defined(STRICT_ALIGNMENT)
scratch.u[0] ^= tweak.u[0];
scratch.u[1] ^= tweak.u[1];
memcpy(out, scratch.c, 16);
#else
((u64_a1 *)out)[0] = scratch.u[0] ^ tweak.u[0];
((u64_a1 *)out)[1] = scratch.u[1] ^ tweak.u[1];
#endif
}
return 0;
}
|