repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
openssl
openssl-master/crypto/hmac/hmac_local.h
/* * 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 */ #ifndef OSSL_CRYPTO_HMAC_LOCAL_H # define OSSL_CRYPTO_HMAC_LOCAL_H /* The current largest case is for SHA3-224 */ #define HMAC_MAX_MD_CBLOCK_SIZE 144 struct hmac_ctx_st { const EVP_MD *md; EVP_MD_CTX *md_ctx; EVP_MD_CTX *i_ctx; EVP_MD_CTX *o_ctx; }; #endif
617
24.75
74
h
openssl
openssl-master/crypto/hpke/hpke_util.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/core_names.h> #include <openssl/kdf.h> #include <openssl/params.h> #include <openssl/err.h> #include <openssl/proverr.h> #include <openssl/hpke.h> #include <openssl/sha.h> #include <openssl/rand.h> #include "crypto/ecx.h" #include "internal/hpke_util.h" #include "internal/packet.h" #include "internal/nelem.h" /* * Delimiter used in OSSL_HPKE_str2suite */ #define OSSL_HPKE_STR_DELIMCHAR ',' /* * table with identifier and synonym strings * right now, there are 4 synonyms for each - a name, a hex string * a hex string with a leading zero and a decimal string - more * could be added but that seems like enough */ typedef struct { uint16_t id; char *synonyms[4]; } synonymttab_t; /* max length of string we'll try map to a suite */ #define OSSL_HPKE_MAX_SUITESTR 38 /* Define HPKE labels from RFC9180 in hex for EBCDIC compatibility */ /* ASCII: "HPKE-v1", in hex for EBCDIC compatibility */ static const char LABEL_HPKEV1[] = "\x48\x50\x4B\x45\x2D\x76\x31"; /* * Note that if additions are made to the set of IANA codepoints * and the tables below, corresponding additions should also be * made to the synonymtab tables a little further down so that * OSSL_HPKE_str2suite() continues to function correctly. * * The canonical place to check for IANA registered codepoints * is: https://www.iana.org/assignments/hpke/hpke.xhtml */ /* * @brief table of KEMs * See RFC9180 Section 7.1 "Table 2 KEM IDs" */ static const OSSL_HPKE_KEM_INFO hpke_kem_tab[] = { #ifndef OPENSSL_NO_EC { OSSL_HPKE_KEM_ID_P256, "EC", OSSL_HPKE_KEMSTR_P256, LN_sha256, SHA256_DIGEST_LENGTH, 65, 65, 32, 0xFF }, { OSSL_HPKE_KEM_ID_P384, "EC", OSSL_HPKE_KEMSTR_P384, LN_sha384, SHA384_DIGEST_LENGTH, 97, 97, 48, 0xFF }, { OSSL_HPKE_KEM_ID_P521, "EC", OSSL_HPKE_KEMSTR_P521, LN_sha512, SHA512_DIGEST_LENGTH, 133, 133, 66, 0x01 }, # ifndef OPENSSL_NO_ECX { OSSL_HPKE_KEM_ID_X25519, OSSL_HPKE_KEMSTR_X25519, NULL, LN_sha256, SHA256_DIGEST_LENGTH, X25519_KEYLEN, X25519_KEYLEN, X25519_KEYLEN, 0x00 }, { OSSL_HPKE_KEM_ID_X448, OSSL_HPKE_KEMSTR_X448, NULL, LN_sha512, SHA512_DIGEST_LENGTH, X448_KEYLEN, X448_KEYLEN, X448_KEYLEN, 0x00 } # endif #else { OSSL_HPKE_KEM_ID_RESERVED, NULL, NULL, NULL, 0, 0, 0, 0, 0x00 } #endif }; /* * @brief table of AEADs * See RFC9180 Section 7.2 "Table 3 KDF IDs" */ static const OSSL_HPKE_AEAD_INFO hpke_aead_tab[] = { { OSSL_HPKE_AEAD_ID_AES_GCM_128, LN_aes_128_gcm, 16, 16, OSSL_HPKE_MAX_NONCELEN }, { OSSL_HPKE_AEAD_ID_AES_GCM_256, LN_aes_256_gcm, 16, 32, OSSL_HPKE_MAX_NONCELEN }, #if !defined(OPENSSL_NO_CHACHA) && !defined(OPENSSL_NO_POLY1305) { OSSL_HPKE_AEAD_ID_CHACHA_POLY1305, LN_chacha20_poly1305, 16, 32, OSSL_HPKE_MAX_NONCELEN }, #endif { OSSL_HPKE_AEAD_ID_EXPORTONLY, NULL, 0, 0, 0 } }; /* * @brief table of KDFs * See RFC9180 Section 7.3 "Table 5 AEAD IDs" */ static const OSSL_HPKE_KDF_INFO hpke_kdf_tab[] = { { OSSL_HPKE_KDF_ID_HKDF_SHA256, LN_sha256, SHA256_DIGEST_LENGTH }, { OSSL_HPKE_KDF_ID_HKDF_SHA384, LN_sha384, SHA384_DIGEST_LENGTH }, { OSSL_HPKE_KDF_ID_HKDF_SHA512, LN_sha512, SHA512_DIGEST_LENGTH } }; /** * Synonym tables for KEMs, KDFs and AEADs: idea is to allow * mapping strings to suites with a little flexibility in terms * of allowing a name or a couple of forms of number (for * the IANA codepoint). If new IANA codepoints are allocated * then these tables should be updated at the same time as the * others above. * * The function to use these is ossl_hpke_str2suite() further down * this file and shouldn't need modification so long as the table * sizes (i.e. allow exactly 4 synonyms) don't change. */ static const synonymttab_t kemstrtab[] = { {OSSL_HPKE_KEM_ID_P256, {OSSL_HPKE_KEMSTR_P256, "0x10", "0x10", "16" }}, {OSSL_HPKE_KEM_ID_P384, {OSSL_HPKE_KEMSTR_P384, "0x11", "0x11", "17" }}, {OSSL_HPKE_KEM_ID_P521, {OSSL_HPKE_KEMSTR_P521, "0x12", "0x12", "18" }}, # ifndef OPENSSL_NO_ECX {OSSL_HPKE_KEM_ID_X25519, {OSSL_HPKE_KEMSTR_X25519, "0x20", "0x20", "32" }}, {OSSL_HPKE_KEM_ID_X448, {OSSL_HPKE_KEMSTR_X448, "0x21", "0x21", "33" }} # endif }; static const synonymttab_t kdfstrtab[] = { {OSSL_HPKE_KDF_ID_HKDF_SHA256, {OSSL_HPKE_KDFSTR_256, "0x1", "0x01", "1"}}, {OSSL_HPKE_KDF_ID_HKDF_SHA384, {OSSL_HPKE_KDFSTR_384, "0x2", "0x02", "2"}}, {OSSL_HPKE_KDF_ID_HKDF_SHA512, {OSSL_HPKE_KDFSTR_512, "0x3", "0x03", "3"}} }; static const synonymttab_t aeadstrtab[] = { {OSSL_HPKE_AEAD_ID_AES_GCM_128, {OSSL_HPKE_AEADSTR_AES128GCM, "0x1", "0x01", "1"}}, {OSSL_HPKE_AEAD_ID_AES_GCM_256, {OSSL_HPKE_AEADSTR_AES256GCM, "0x2", "0x02", "2"}}, {OSSL_HPKE_AEAD_ID_CHACHA_POLY1305, {OSSL_HPKE_AEADSTR_CP, "0x3", "0x03", "3"}}, {OSSL_HPKE_AEAD_ID_EXPORTONLY, {OSSL_HPKE_AEADSTR_EXP, "ff", "0xff", "255"}} }; /* Return an object containing KEM constants associated with a EC curve name */ const OSSL_HPKE_KEM_INFO *ossl_HPKE_KEM_INFO_find_curve(const char *curve) { int i, sz = OSSL_NELEM(hpke_kem_tab); for (i = 0; i < sz; ++i) { const char *group = hpke_kem_tab[i].groupname; if (group == NULL) group = hpke_kem_tab[i].keytype; if (OPENSSL_strcasecmp(curve, group) == 0) return &hpke_kem_tab[i]; } ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CURVE); return NULL; } const OSSL_HPKE_KEM_INFO *ossl_HPKE_KEM_INFO_find_id(uint16_t kemid) { int i, sz = OSSL_NELEM(hpke_kem_tab); /* * this check can happen if we're in a no-ec build and there are no * KEMS available */ if (kemid == OSSL_HPKE_KEM_ID_RESERVED) { ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CURVE); return NULL; } for (i = 0; i != sz; ++i) { if (hpke_kem_tab[i].kem_id == kemid) return &hpke_kem_tab[i]; } ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CURVE); return NULL; } const OSSL_HPKE_KEM_INFO *ossl_HPKE_KEM_INFO_find_random(OSSL_LIB_CTX *ctx) { unsigned char rval = 0; int sz = OSSL_NELEM(hpke_kem_tab); if (RAND_bytes_ex(ctx, &rval, sizeof(rval), 0) <= 0) return NULL; return &hpke_kem_tab[rval % sz]; } const OSSL_HPKE_KDF_INFO *ossl_HPKE_KDF_INFO_find_id(uint16_t kdfid) { int i, sz = OSSL_NELEM(hpke_kdf_tab); for (i = 0; i != sz; ++i) { if (hpke_kdf_tab[i].kdf_id == kdfid) return &hpke_kdf_tab[i]; } ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_KDF); return NULL; } const OSSL_HPKE_KDF_INFO *ossl_HPKE_KDF_INFO_find_random(OSSL_LIB_CTX *ctx) { unsigned char rval = 0; int sz = OSSL_NELEM(hpke_kdf_tab); if (RAND_bytes_ex(ctx, &rval, sizeof(rval), 0) <= 0) return NULL; return &hpke_kdf_tab[rval % sz]; } const OSSL_HPKE_AEAD_INFO *ossl_HPKE_AEAD_INFO_find_id(uint16_t aeadid) { int i, sz = OSSL_NELEM(hpke_aead_tab); for (i = 0; i != sz; ++i) { if (hpke_aead_tab[i].aead_id == aeadid) return &hpke_aead_tab[i]; } ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_AEAD); return NULL; } const OSSL_HPKE_AEAD_INFO *ossl_HPKE_AEAD_INFO_find_random(OSSL_LIB_CTX *ctx) { unsigned char rval = 0; /* the minus 1 below is so we don't pick the EXPORTONLY codepoint */ int sz = OSSL_NELEM(hpke_aead_tab) - 1; if (RAND_bytes_ex(ctx, &rval, sizeof(rval), 0) <= 0) return NULL; return &hpke_aead_tab[rval % sz]; } static int kdf_derive(EVP_KDF_CTX *kctx, unsigned char *out, size_t outlen, int mode, const unsigned char *salt, size_t saltlen, const unsigned char *ikm, size_t ikmlen, const unsigned char *info, size_t infolen) { int ret; OSSL_PARAM params[5], *p = params; *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode); if (salt != NULL) *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, (char *)salt, saltlen); if (ikm != NULL) *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY, (char *)ikm, ikmlen); if (info != NULL) *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_INFO, (char *)info, infolen); *p = OSSL_PARAM_construct_end(); ret = EVP_KDF_derive(kctx, out, outlen, params) > 0; if (!ret) ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_DURING_DERIVATION); return ret; } int ossl_hpke_kdf_extract(EVP_KDF_CTX *kctx, unsigned char *prk, size_t prklen, const unsigned char *salt, size_t saltlen, const unsigned char *ikm, size_t ikmlen) { return kdf_derive(kctx, prk, prklen, EVP_KDF_HKDF_MODE_EXTRACT_ONLY, salt, saltlen, ikm, ikmlen, NULL, 0); } /* Common code to perform a HKDF expand */ int ossl_hpke_kdf_expand(EVP_KDF_CTX *kctx, unsigned char *okm, size_t okmlen, const unsigned char *prk, size_t prklen, const unsigned char *info, size_t infolen) { return kdf_derive(kctx, okm, okmlen, EVP_KDF_HKDF_MODE_EXPAND_ONLY, NULL, 0, prk, prklen, info, infolen); } /* * See RFC 9180 Section 4 LabelExtract() */ int ossl_hpke_labeled_extract(EVP_KDF_CTX *kctx, unsigned char *prk, size_t prklen, const unsigned char *salt, size_t saltlen, const char *protocol_label, const unsigned char *suiteid, size_t suiteidlen, const char *label, const unsigned char *ikm, size_t ikmlen) { int ret = 0; size_t label_hpkev1len = 0; size_t protocol_labellen = 0; size_t labellen = 0; size_t labeled_ikmlen = 0; unsigned char *labeled_ikm = NULL; WPACKET pkt; label_hpkev1len = strlen(LABEL_HPKEV1); protocol_labellen = strlen(protocol_label); labellen = strlen(label); labeled_ikmlen = label_hpkev1len + protocol_labellen + suiteidlen + labellen + ikmlen; labeled_ikm = OPENSSL_malloc(labeled_ikmlen); if (labeled_ikm == NULL) return 0; /* labeled_ikm = concat("HPKE-v1", suiteid, label, ikm) */ if (!WPACKET_init_static_len(&pkt, labeled_ikm, labeled_ikmlen, 0) || !WPACKET_memcpy(&pkt, LABEL_HPKEV1, label_hpkev1len) || !WPACKET_memcpy(&pkt, protocol_label, protocol_labellen) || !WPACKET_memcpy(&pkt, suiteid, suiteidlen) || !WPACKET_memcpy(&pkt, label, labellen) || !WPACKET_memcpy(&pkt, ikm, ikmlen) || !WPACKET_get_total_written(&pkt, &labeled_ikmlen) || !WPACKET_finish(&pkt)) { ERR_raise(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL); goto end; } ret = ossl_hpke_kdf_extract(kctx, prk, prklen, salt, saltlen, labeled_ikm, labeled_ikmlen); end: WPACKET_cleanup(&pkt); OPENSSL_cleanse(labeled_ikm, labeled_ikmlen); OPENSSL_free(labeled_ikm); return ret; } /* * See RFC 9180 Section 4 LabelExpand() */ int ossl_hpke_labeled_expand(EVP_KDF_CTX *kctx, unsigned char *okm, size_t okmlen, const unsigned char *prk, size_t prklen, const char *protocol_label, const unsigned char *suiteid, size_t suiteidlen, const char *label, const unsigned char *info, size_t infolen) { int ret = 0; size_t label_hpkev1len = 0; size_t protocol_labellen = 0; size_t labellen = 0; size_t labeled_infolen = 0; unsigned char *labeled_info = NULL; WPACKET pkt; label_hpkev1len = strlen(LABEL_HPKEV1); protocol_labellen = strlen(protocol_label); labellen = strlen(label); labeled_infolen = 2 + okmlen + prklen + label_hpkev1len + protocol_labellen + suiteidlen + labellen + infolen; labeled_info = OPENSSL_malloc(labeled_infolen); if (labeled_info == NULL) return 0; /* labeled_info = concat(okmlen, "HPKE-v1", suiteid, label, info) */ if (!WPACKET_init_static_len(&pkt, labeled_info, labeled_infolen, 0) || !WPACKET_put_bytes_u16(&pkt, okmlen) || !WPACKET_memcpy(&pkt, LABEL_HPKEV1, label_hpkev1len) || !WPACKET_memcpy(&pkt, protocol_label, protocol_labellen) || !WPACKET_memcpy(&pkt, suiteid, suiteidlen) || !WPACKET_memcpy(&pkt, label, labellen) || !WPACKET_memcpy(&pkt, info, infolen) || !WPACKET_get_total_written(&pkt, &labeled_infolen) || !WPACKET_finish(&pkt)) { ERR_raise(ERR_LIB_PROV, PROV_R_OUTPUT_BUFFER_TOO_SMALL); goto end; } ret = ossl_hpke_kdf_expand(kctx, okm, okmlen, prk, prklen, labeled_info, labeled_infolen); end: WPACKET_cleanup(&pkt); OPENSSL_free(labeled_info); return ret; } /* Common code to create a HKDF ctx */ EVP_KDF_CTX *ossl_kdf_ctx_create(const char *kdfname, const char *mdname, OSSL_LIB_CTX *libctx, const char *propq) { EVP_KDF *kdf; EVP_KDF_CTX *kctx = NULL; kdf = EVP_KDF_fetch(libctx, kdfname, propq); if (kdf == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_FETCH_FAILED); return NULL; } kctx = EVP_KDF_CTX_new(kdf); EVP_KDF_free(kdf); if (kctx != NULL && mdname != NULL) { OSSL_PARAM params[3], *p = params; if (mdname != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, (char *)mdname, 0); if (propq != NULL) *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_PROPERTIES, (char *)propq, 0); *p = OSSL_PARAM_construct_end(); if (EVP_KDF_CTX_set_params(kctx, params) <= 0) { EVP_KDF_CTX_free(kctx); return NULL; } } return kctx; } /* * @brief look for a label into the synonym tables, and return its id * @param st is the string value * @param synp is the synonyms labels array * @param arrsize is the previous array size * @return 0 when not found, else the matching item id. */ static uint16_t synonyms_name2id(const char *st, const synonymttab_t *synp, size_t arrsize) { size_t i, j; for (i = 0; i < arrsize; ++i) { for (j = 0; j < OSSL_NELEM(synp[i].synonyms); ++j) { if (OPENSSL_strcasecmp(st, synp[i].synonyms[j]) == 0) return synp[i].id; } } return 0; } /* * @brief map a string to a HPKE suite based on synonym tables * @param str is the string value * @param suite is the resulting suite * @return 1 for success, otherwise failure */ int ossl_hpke_str2suite(const char *suitestr, OSSL_HPKE_SUITE *suite) { uint16_t kem = 0, kdf = 0, aead = 0; char *st = NULL, *instrcp = NULL; size_t inplen; int labels = 0, result = 0; int delim_count = 0; if (suitestr == NULL || suitestr[0] == 0x00 || suite == NULL) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_NULL_PARAMETER); return 0; } inplen = OPENSSL_strnlen(suitestr, OSSL_HPKE_MAX_SUITESTR); if (inplen >= OSSL_HPKE_MAX_SUITESTR) { ERR_raise(ERR_LIB_CRYPTO, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } /* * we don't want a delimiter at the end of the string; * strtok_r/s() doesn't care about that, so we should */ if (suitestr[inplen - 1] == OSSL_HPKE_STR_DELIMCHAR) return 0; /* We want exactly two delimiters in the input string */ for (st = (char *)suitestr; *st != '\0'; st++) { if (*st == OSSL_HPKE_STR_DELIMCHAR) delim_count++; } if (delim_count != 2) return 0; /* Duplicate `suitestr` to allow its parsing */ instrcp = OPENSSL_memdup(suitestr, inplen + 1); if (instrcp == NULL) goto fail; /* See if it contains a mix of our strings and numbers */ st = instrcp; while (st != NULL && labels < 3) { char *cp = strchr(st, OSSL_HPKE_STR_DELIMCHAR); /* add a NUL like strtok would if we're not at the end */ if (cp != NULL) *cp = '\0'; /* check if string is known or number and if so handle appropriately */ if (labels == 0 && (kem = synonyms_name2id(st, kemstrtab, OSSL_NELEM(kemstrtab))) == 0) goto fail; else if (labels == 1 && (kdf = synonyms_name2id(st, kdfstrtab, OSSL_NELEM(kdfstrtab))) == 0) goto fail; else if (labels == 2 && (aead = synonyms_name2id(st, aeadstrtab, OSSL_NELEM(aeadstrtab))) == 0) goto fail; if (cp == NULL) st = NULL; else st = cp + 1; ++labels; } if (st != NULL || labels != 3) goto fail; suite->kem_id = kem; suite->kdf_id = kdf; suite->aead_id = aead; result = 1; fail: OPENSSL_free(instrcp); return result; }
17,873
32.916509
79
c
openssl
openssl-master/crypto/http/http_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/httperr.h> #include "crypto/httperr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA HTTP_str_reasons[] = { {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_ASN1_LEN_EXCEEDS_MAX_RESP_LEN), "asn1 len exceeds max resp len"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_CONNECT_FAILURE), "connect failure"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_ERROR_PARSING_ASN1_LENGTH), "error parsing asn1 length"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_ERROR_PARSING_CONTENT_LENGTH), "error parsing content length"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_ERROR_PARSING_URL), "error parsing url"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_ERROR_RECEIVING), "error receiving"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_ERROR_SENDING), "error sending"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_FAILED_READING_DATA), "failed reading data"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_HEADER_PARSE_ERROR), "header parse error"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_INCONSISTENT_CONTENT_LENGTH), "inconsistent content length"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_INVALID_PORT_NUMBER), "invalid port number"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_INVALID_URL_PATH), "invalid url path"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_INVALID_URL_SCHEME), "invalid url scheme"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_MAX_RESP_LEN_EXCEEDED), "max resp len exceeded"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_MISSING_ASN1_ENCODING), "missing asn1 encoding"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_MISSING_CONTENT_TYPE), "missing content type"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_MISSING_REDIRECT_LOCATION), "missing redirect location"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_RECEIVED_ERROR), "received error"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_RECEIVED_WRONG_HTTP_VERSION), "received wrong http version"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP), "redirection from https to http"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_REDIRECTION_NOT_ENABLED), "redirection not enabled"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_RESPONSE_LINE_TOO_LONG), "response line too long"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_RESPONSE_PARSE_ERROR), "response parse error"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_RETRY_TIMEOUT), "retry timeout"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_SERVER_CANCELED_CONNECTION), "server canceled connection"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_SOCK_NOT_SUPPORTED), "sock not supported"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_STATUS_CODE_UNSUPPORTED), "status code unsupported"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_TLS_NOT_ENABLED), "tls not enabled"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_TOO_MANY_REDIRECTIONS), "too many redirections"}, {ERR_PACK(ERR_LIB_HTTP, 0, HTTP_R_UNEXPECTED_CONTENT_TYPE), "unexpected content type"}, {0, NULL} }; #endif int ossl_err_load_HTTP_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(HTTP_str_reasons[0].error) == NULL) ERR_load_strings_const(HTTP_str_reasons); #endif return 1; }
3,477
40.903614
79
c
openssl
openssl-master/crypto/http/http_lib.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> /* for sscanf() */ #include <string.h> #include <openssl/http.h> #include <openssl/httperr.h> #include <openssl/bio.h> /* for BIO_snprintf() */ #include <openssl/err.h> #include "internal/cryptlib.h" /* for ossl_assert() */ static void init_pstring(char **pstr) { if (pstr != NULL) { *pstr = NULL; } } static void init_pint(int *pint) { if (pint != NULL) { *pint = 0; } } static int copy_substring(char **dest, const char *start, const char *end) { return dest == NULL || (*dest = OPENSSL_strndup(start, end - start)) != NULL; } static void free_pstring(char **pstr) { if (pstr != NULL) { OPENSSL_free(*pstr); *pstr = NULL; } } int OSSL_parse_url(const char *url, char **pscheme, char **puser, char **phost, char **pport, int *pport_num, char **ppath, char **pquery, char **pfrag) { const char *p, *tmp; const char *scheme, *scheme_end; const char *user, *user_end; const char *host, *host_end; const char *port, *port_end; unsigned int portnum; const char *path, *path_end; const char *query, *query_end; const char *frag, *frag_end; init_pstring(pscheme); init_pstring(puser); init_pstring(phost); init_pstring(pport); init_pint(pport_num); init_pstring(ppath); init_pstring(pfrag); init_pstring(pquery); if (url == NULL) { ERR_raise(ERR_LIB_HTTP, ERR_R_PASSED_NULL_PARAMETER); return 0; } /* check for optional prefix "<scheme>://" */ scheme = scheme_end = url; p = strstr(url, "://"); if (p == NULL) { p = url; } else { scheme_end = p; if (scheme_end == scheme) goto parse_err; p += strlen("://"); } /* parse optional "userinfo@" */ user = user_end = host = p; host = strchr(p, '@'); if (host != NULL) user_end = host++; else host = p; /* parse hostname/address as far as needed here */ if (host[0] == '[') { /* IPv6 literal, which may include ':' */ host_end = strchr(host + 1, ']'); if (host_end == NULL) goto parse_err; p = ++host_end; } else { /* look for start of optional port, path, query, or fragment */ host_end = strchr(host, ':'); if (host_end == NULL) host_end = strchr(host, '/'); if (host_end == NULL) host_end = strchr(host, '?'); if (host_end == NULL) host_end = strchr(host, '#'); if (host_end == NULL) /* the remaining string is just the hostname */ host_end = host + strlen(host); p = host_end; } /* parse optional port specification starting with ':' */ port = "0"; /* default */ if (*p == ':') port = ++p; /* remaining port spec handling is also done for the default values */ /* make sure a decimal port number is given */ if (!sscanf(port, "%u", &portnum) || portnum > 65535) { ERR_raise_data(ERR_LIB_HTTP, HTTP_R_INVALID_PORT_NUMBER, "%s", port); goto err; } for (port_end = port; '0' <= *port_end && *port_end <= '9'; port_end++) ; if (port == p) /* port was given explicitly */ p += port_end - port; /* check for optional path starting with '/' or '?'. Else must start '#' */ path = p; if (*path != '\0' && *path != '/' && *path != '?' && *path != '#') { ERR_raise(ERR_LIB_HTTP, HTTP_R_INVALID_URL_PATH); goto parse_err; } path_end = query = query_end = frag = frag_end = path + strlen(path); /* parse optional "?query" */ tmp = strchr(p, '?'); if (tmp != NULL) { p = tmp; if (pquery != NULL) { path_end = p; query = p + 1; } } /* parse optional "#fragment" */ tmp = strchr(p, '#'); if (tmp != NULL) { if (query == path_end) /* we did not record a query component */ path_end = tmp; query_end = tmp; frag = tmp + 1; } if (!copy_substring(pscheme, scheme, scheme_end) || !copy_substring(phost, host, host_end) || !copy_substring(pport, port, port_end) || !copy_substring(puser, user, user_end) || !copy_substring(pquery, query, query_end) || !copy_substring(pfrag, frag, frag_end)) goto err; if (pport_num != NULL) *pport_num = (int)portnum; if (*path == '/') { if (!copy_substring(ppath, path, path_end)) goto err; } else if (ppath != NULL) { /* must prepend '/' */ size_t buflen = 1 + path_end - path + 1; if ((*ppath = OPENSSL_malloc(buflen)) == NULL) goto err; BIO_snprintf(*ppath, buflen, "/%s", path); } return 1; parse_err: ERR_raise(ERR_LIB_HTTP, HTTP_R_ERROR_PARSING_URL); err: free_pstring(pscheme); free_pstring(puser); free_pstring(phost); free_pstring(pport); free_pstring(ppath); free_pstring(pquery); free_pstring(pfrag); return 0; } int OSSL_HTTP_parse_url(const char *url, int *pssl, char **puser, char **phost, char **pport, int *pport_num, char **ppath, char **pquery, char **pfrag) { char *scheme, *port; int ssl = 0, portnum; init_pstring(pport); if (pssl != NULL) *pssl = 0; if (!OSSL_parse_url(url, &scheme, puser, phost, &port, pport_num, ppath, pquery, pfrag)) return 0; /* check for optional HTTP scheme "http[s]" */ if (strcmp(scheme, OSSL_HTTPS_NAME) == 0) { ssl = 1; if (pssl != NULL) *pssl = ssl; } else if (*scheme != '\0' && strcmp(scheme, OSSL_HTTP_NAME) != 0) { ERR_raise(ERR_LIB_HTTP, HTTP_R_INVALID_URL_SCHEME); OPENSSL_free(scheme); OPENSSL_free(port); goto err; } OPENSSL_free(scheme); if (strcmp(port, "0") == 0) { /* set default port */ OPENSSL_free(port); port = ssl ? OSSL_HTTPS_PORT : OSSL_HTTP_PORT; if (!ossl_assert(sscanf(port, "%d", &portnum) == 1)) goto err; if (pport_num != NULL) *pport_num = portnum; if (pport != NULL) { *pport = OPENSSL_strdup(port); if (*pport == NULL) goto err; } } else { if (pport != NULL) *pport = port; else OPENSSL_free(port); } return 1; err: free_pstring(puser); free_pstring(phost); free_pstring(ppath); free_pstring(pquery); free_pstring(pfrag); return 0; } /* Respect no_proxy, taking default value from environment variable(s) */ static int use_proxy(const char *no_proxy, const char *server) { size_t sl; const char *found = NULL; if (!ossl_assert(server != NULL)) return 0; sl = strlen(server); /* * using environment variable names, both lowercase and uppercase variants, * compatible with other HTTP client implementations like wget, curl and git */ if (no_proxy == NULL) no_proxy = ossl_safe_getenv("no_proxy"); if (no_proxy == NULL) no_proxy = ossl_safe_getenv(OPENSSL_NO_PROXY); if (no_proxy != NULL) found = strstr(no_proxy, server); while (found != NULL && ((found != no_proxy && found[-1] != ' ' && found[-1] != ',') || (found[sl] != '\0' && found[sl] != ' ' && found[sl] != ','))) found = strstr(found + 1, server); return found == NULL; } /* Take default value from environment variable(s), respect no_proxy */ const char *OSSL_HTTP_adapt_proxy(const char *proxy, const char *no_proxy, const char *server, int use_ssl) { /* * using environment variable names, both lowercase and uppercase variants, * compatible with other HTTP client implementations like wget, curl and git */ if (proxy == NULL) proxy = ossl_safe_getenv(use_ssl ? "https_proxy" : "http_proxy"); if (proxy == NULL) proxy = ossl_safe_getenv(use_ssl ? OPENSSL_HTTP_PROXY : OPENSSL_HTTPS_PROXY); if (proxy == NULL || *proxy == '\0' || !use_proxy(no_proxy, server)) return NULL; return proxy; }
8,664
28.472789
85
c
openssl
openssl-master/crypto/idea/i_cbc.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 */ /* * IDEA 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/idea.h> #include "idea_local.h" void IDEA_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, IDEA_KEY_SCHEDULE *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) { n2l(iv, tout0); n2l(iv, tout1); iv -= 8; for (l -= 8; l >= 0; l -= 8) { n2l(in, tin0); n2l(in, tin1); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; IDEA_encrypt(tin, ks); tout0 = tin[0]; l2n(tout0, out); tout1 = tin[1]; l2n(tout1, out); } if (l != -8) { n2ln(in, tin0, tin1, l + 8); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; IDEA_encrypt(tin, ks); tout0 = tin[0]; l2n(tout0, out); tout1 = tin[1]; l2n(tout1, out); } l2n(tout0, iv); l2n(tout1, iv); } else { n2l(iv, xor0); n2l(iv, xor1); iv -= 8; for (l -= 8; l >= 0; l -= 8) { n2l(in, tin0); tin[0] = tin0; n2l(in, tin1); tin[1] = tin1; IDEA_encrypt(tin, ks); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2n(tout0, out); l2n(tout1, out); xor0 = tin0; xor1 = tin1; } if (l != -8) { n2l(in, tin0); tin[0] = tin0; n2l(in, tin1); tin[1] = tin1; IDEA_encrypt(tin, ks); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2nn(tout0, tout1, out, l + 8); xor0 = tin0; xor1 = tin1; } l2n(xor0, iv); l2n(xor1, iv); } tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; tin[0] = tin[1] = 0; } void IDEA_encrypt(unsigned long *d, IDEA_KEY_SCHEDULE *key) { register IDEA_INT *p; register unsigned long x1, x2, x3, x4, t0, t1, ul; x2 = d[0]; x1 = (x2 >> 16); x4 = d[1]; x3 = (x4 >> 16); p = &(key->data[0][0]); E_IDEA(0); E_IDEA(1); E_IDEA(2); E_IDEA(3); E_IDEA(4); E_IDEA(5); E_IDEA(6); E_IDEA(7); x1 &= 0xffff; idea_mul(x1, x1, *p, ul); p++; t0 = x3 + *(p++); t1 = x2 + *(p++); x4 &= 0xffff; idea_mul(x4, x4, *p, ul); d[0] = (t0 & 0xffff) | ((x1 & 0xffff) << 16); d[1] = (x4 & 0xffff) | ((t1 & 0xffff) << 16); }
3,299
24.384615
80
c
openssl
openssl-master/crypto/idea/i_cfb64.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 */ /* * IDEA 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/idea.h> #include "idea_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 IDEA_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, IDEA_KEY_SCHEDULE *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; if (n < 0) { *num = -1; return; } iv = (unsigned char *)ivec; if (encrypt) { while (l--) { if (n == 0) { n2l(iv, v0); ti[0] = v0; n2l(iv, v1); ti[1] = v1; IDEA_encrypt((unsigned long *)ti, schedule); iv = (unsigned char *)ivec; t = ti[0]; l2n(t, iv); t = ti[1]; l2n(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) { n2l(iv, v0); ti[0] = v0; n2l(iv, v1); ti[1] = v1; IDEA_encrypt((unsigned long *)ti, schedule); iv = (unsigned char *)ivec; t = ti[0]; l2n(t, iv); t = ti[1]; l2n(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; }
2,484
27.563218
80
c
openssl
openssl-master/crypto/idea/i_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 */ /* * IDEA 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/idea.h> #include "idea_local.h" #include <openssl/opensslv.h> const char *IDEA_options(void) { return "idea(int)"; } void IDEA_ecb_encrypt(const unsigned char *in, unsigned char *out, IDEA_KEY_SCHEDULE *ks) { unsigned long l0, l1, d[2]; n2l(in, l0); d[0] = l0; n2l(in, l1); d[1] = l1; IDEA_encrypt(d, ks); l0 = d[0]; l2n(l0, out); l1 = d[1]; l2n(l1, out); l0 = l1 = d[0] = d[1] = 0; }
1,033
23.619048
80
c
openssl
openssl-master/crypto/idea/i_ofb64.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 */ /* * IDEA 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/idea.h> #include "idea_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 IDEA_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, IDEA_KEY_SCHEDULE *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; if (n < 0) { *num = -1; return; } iv = (unsigned char *)ivec; n2l(iv, v0); n2l(iv, v1); ti[0] = v0; ti[1] = v1; dp = (char *)d; l2n(v0, dp); l2n(v1, dp); while (l--) { if (n == 0) { IDEA_encrypt((unsigned long *)ti, schedule); dp = (char *)d; t = ti[0]; l2n(t, dp); t = ti[1]; l2n(t, dp); save++; } *(out++) = *(in++) ^ d[n]; n = (n + 1) & 0x07; } if (save) { v0 = ti[0]; v1 = ti[1]; iv = (unsigned char *)ivec; l2n(v0, iv); l2n(v1, iv); } t = v0 = v1 = ti[0] = ti[1] = 0; *num = n; }
1,919
24.945946
80
c
openssl
openssl-master/crypto/idea/i_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 */ /* * IDEA 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/idea.h> #include "idea_local.h" static IDEA_INT inverse(unsigned int xin); void IDEA_set_encrypt_key(const unsigned char *key, IDEA_KEY_SCHEDULE *ks) { int i; register IDEA_INT *kt, *kf, r0, r1, r2; kt = &(ks->data[0][0]); n2s(key, kt[0]); n2s(key, kt[1]); n2s(key, kt[2]); n2s(key, kt[3]); n2s(key, kt[4]); n2s(key, kt[5]); n2s(key, kt[6]); n2s(key, kt[7]); kf = kt; kt += 8; for (i = 0; i < 6; i++) { r2 = kf[1]; r1 = kf[2]; *(kt++) = ((r2 << 9) | (r1 >> 7)) & 0xffff; r0 = kf[3]; *(kt++) = ((r1 << 9) | (r0 >> 7)) & 0xffff; r1 = kf[4]; *(kt++) = ((r0 << 9) | (r1 >> 7)) & 0xffff; r0 = kf[5]; *(kt++) = ((r1 << 9) | (r0 >> 7)) & 0xffff; r1 = kf[6]; *(kt++) = ((r0 << 9) | (r1 >> 7)) & 0xffff; r0 = kf[7]; *(kt++) = ((r1 << 9) | (r0 >> 7)) & 0xffff; r1 = kf[0]; if (i >= 5) break; *(kt++) = ((r0 << 9) | (r1 >> 7)) & 0xffff; *(kt++) = ((r1 << 9) | (r2 >> 7)) & 0xffff; kf += 8; } } void IDEA_set_decrypt_key(IDEA_KEY_SCHEDULE *ek, IDEA_KEY_SCHEDULE *dk) { int r; register IDEA_INT *fp, *tp, t; tp = &(dk->data[0][0]); fp = &(ek->data[8][0]); for (r = 0; r < 9; r++) { *(tp++) = inverse(fp[0]); *(tp++) = ((int)(0x10000L - fp[2]) & 0xffff); *(tp++) = ((int)(0x10000L - fp[1]) & 0xffff); *(tp++) = inverse(fp[3]); if (r == 8) break; fp -= 6; *(tp++) = fp[4]; *(tp++) = fp[5]; } tp = &(dk->data[0][0]); t = tp[1]; tp[1] = tp[2]; tp[2] = t; t = tp[49]; tp[49] = tp[50]; tp[50] = t; } /* taken directly from the 'paper' I'll have a look at it later */ static IDEA_INT inverse(unsigned int xin) { long n1, n2, q, r, b1, b2, t; if (xin == 0) b2 = 0; else { n1 = 0x10001; n2 = xin; b2 = 1; b1 = 0; do { r = (n1 % n2); q = (n1 - r) / n2; if (r == 0) { if (b2 < 0) b2 = 0x10001 + b2; } else { n1 = n2; n2 = r; t = b2; b2 = b1 - q * b2; b1 = t; } } while (r != 0); } return (IDEA_INT)b2; }
2,961
23.683333
80
c
openssl
openssl-master/crypto/idea/idea_local.h
/* * Copyright 1995-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 */ #define idea_mul(r,a,b,ul) \ ul=(unsigned long)a*b; \ if (ul != 0) \ { \ r=(ul&0xffff)-(ul>>16); \ r-=((r)>>16); \ } \ else \ r=(-(int)a-b+1); /* assuming a or b is 0 and in range */ /* NOTE - c is not incremented as per n2l */ #define n2ln(c,l1,l2,n) { \ c+=n; \ l1=l2=0; \ switch (n) { \ case 8: l2 =((unsigned long)(*(--(c)))) ; \ /* fall through */ \ case 7: l2|=((unsigned long)(*(--(c))))<< 8; \ /* fall through */ \ case 6: l2|=((unsigned long)(*(--(c))))<<16; \ /* fall through */ \ case 5: l2|=((unsigned long)(*(--(c))))<<24; \ /* fall through */ \ case 4: l1 =((unsigned long)(*(--(c)))) ; \ /* fall through */ \ case 3: l1|=((unsigned long)(*(--(c))))<< 8; \ /* fall through */ \ case 2: l1|=((unsigned long)(*(--(c))))<<16; \ /* fall through */ \ case 1: l1|=((unsigned long)(*(--(c))))<<24; \ } \ } /* NOTE - c is not incremented as per l2n */ #define l2nn(l1,l2,c,n) { \ c+=n; \ switch (n) { \ case 8: *(--(c))=(unsigned char)(((l2) )&0xff); \ /* fall through */ \ case 7: *(--(c))=(unsigned char)(((l2)>> 8)&0xff); \ /* fall through */ \ case 6: *(--(c))=(unsigned char)(((l2)>>16)&0xff); \ /* fall through */ \ case 5: *(--(c))=(unsigned char)(((l2)>>24)&0xff); \ /* fall through */ \ case 4: *(--(c))=(unsigned char)(((l1) )&0xff); \ /* fall through */ \ case 3: *(--(c))=(unsigned char)(((l1)>> 8)&0xff); \ /* fall through */ \ case 2: *(--(c))=(unsigned char)(((l1)>>16)&0xff); \ /* fall through */ \ case 1: *(--(c))=(unsigned char)(((l1)>>24)&0xff); \ } \ } #undef n2l #define n2l(c,l) (l =((unsigned long)(*((c)++)))<<24L, \ l|=((unsigned long)(*((c)++)))<<16L, \ l|=((unsigned long)(*((c)++)))<< 8L, \ l|=((unsigned long)(*((c)++)))) #undef l2n #define l2n(l,c) (*((c)++)=(unsigned char)(((l)>>24L)&0xff), \ *((c)++)=(unsigned char)(((l)>>16L)&0xff), \ *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \ *((c)++)=(unsigned char)(((l) )&0xff)) #undef s2n #define s2n(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ *((c)++)=(unsigned char)(((l)>> 8L)&0xff)) #undef n2s #define n2s(c,l) (l =((IDEA_INT)(*((c)++)))<< 8L, \ l|=((IDEA_INT)(*((c)++))) ) #define E_IDEA(num) \ x1&=0xffff; \ idea_mul(x1,x1,*p,ul); p++; \ x2+= *(p++); \ x3+= *(p++); \ x4&=0xffff; \ idea_mul(x4,x4,*p,ul); p++; \ t0=(x1^x3)&0xffff; \ idea_mul(t0,t0,*p,ul); p++; \ t1=(t0+(x2^x4))&0xffff; \ idea_mul(t1,t1,*p,ul); p++; \ t0+=t1; \ x1^=t1; \ x4^=t0; \ ul=x2^t0; /* do the swap to x3 */ \ x2=x3^t1; \ x3=ul;
4,570
43.378641
79
h
openssl
openssl-master/crypto/kdf/kdf_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2019 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/kdferr.h> #ifndef OPENSSL_NO_DEPRECATED_3_0 int ERR_load_KDF_strings(void) { return 1; } #endif
523
25.2
74
c
openssl
openssl-master/crypto/lhash/lh_stats.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 */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <string.h> #include <stdlib.h> /* * If you wish to build this outside of OpenSSL, remove the following lines * and things should work as expected */ #include "internal/cryptlib.h" #include <openssl/bio.h> #include <openssl/lhash.h> #include "lhash_local.h" # ifndef OPENSSL_NO_STDIO # ifndef OPENSSL_NO_DEPRECATED_3_2 void OPENSSL_LH_stats(const OPENSSL_LHASH *lh, FILE *fp) { BIO *bp; bp = BIO_new(BIO_s_file()); if (bp == NULL) return; BIO_set_fp(bp, fp, BIO_NOCLOSE); OPENSSL_LH_stats_bio(lh, bp); BIO_free(bp); } void OPENSSL_LH_node_stats(const OPENSSL_LHASH *lh, FILE *fp) { BIO *bp; bp = BIO_new(BIO_s_file()); if (bp == NULL) return; BIO_set_fp(bp, fp, BIO_NOCLOSE); OPENSSL_LH_node_stats_bio(lh, bp); BIO_free(bp); } void OPENSSL_LH_node_usage_stats(const OPENSSL_LHASH *lh, FILE *fp) { BIO *bp; bp = BIO_new(BIO_s_file()); if (bp == NULL) return; BIO_set_fp(bp, fp, BIO_NOCLOSE); OPENSSL_LH_node_usage_stats_bio(lh, bp); BIO_free(bp); } # endif # endif # ifndef OPENSSL_NO_DEPRECATED_3_2 /* * These functions are implemented as separate static functions as they are * called from the stdio functions above and calling deprecated functions will * generate a warning. */ void OPENSSL_LH_stats_bio(const OPENSSL_LHASH *lh, BIO *out) { BIO_printf(out, "num_items = %lu\n", lh->num_items); BIO_printf(out, "num_nodes = %u\n", lh->num_nodes); BIO_printf(out, "num_alloc_nodes = %u\n", lh->num_alloc_nodes); BIO_printf(out, "num_expands = 0\n"); BIO_printf(out, "num_expand_reallocs = 0\n"); BIO_printf(out, "num_contracts = 0\n"); BIO_printf(out, "num_contract_reallocs = 0\n"); BIO_printf(out, "num_hash_calls = 0\n"); BIO_printf(out, "num_comp_calls = 0\n"); BIO_printf(out, "num_insert = 0\n"); BIO_printf(out, "num_replace = 0\n"); BIO_printf(out, "num_delete = 0\n"); BIO_printf(out, "num_no_delete = 0\n"); BIO_printf(out, "num_retrieve = 0\n"); BIO_printf(out, "num_retrieve_miss = 0\n"); BIO_printf(out, "num_hash_comps = 0\n"); } void OPENSSL_LH_node_stats_bio(const OPENSSL_LHASH *lh, BIO *out) { OPENSSL_LH_NODE *n; unsigned int i, num; for (i = 0; i < lh->num_nodes; i++) { for (n = lh->b[i], num = 0; n != NULL; n = n->next) num++; BIO_printf(out, "node %6u -> %3u\n", i, num); } } void OPENSSL_LH_node_usage_stats_bio(const OPENSSL_LHASH *lh, BIO *out) { OPENSSL_LH_NODE *n; unsigned long num; unsigned int i; unsigned long total = 0, n_used = 0; for (i = 0; i < lh->num_nodes; i++) { for (n = lh->b[i], num = 0; n != NULL; n = n->next) num++; if (num != 0) { n_used++; total += num; } } BIO_printf(out, "%lu nodes used out of %u\n", n_used, lh->num_nodes); BIO_printf(out, "%lu items\n", total); if (n_used == 0) return; BIO_printf(out, "load %d.%02d actual load %d.%02d\n", (int)(total / lh->num_nodes), (int)((total % lh->num_nodes) * 100 / lh->num_nodes), (int)(total / n_used), (int)((total % n_used) * 100 / n_used)); } # endif
3,759
28.375
78
c
openssl
openssl-master/crypto/lhash/lhash.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 <string.h> #include <stdlib.h> #include <openssl/crypto.h> #include <openssl/lhash.h> #include <openssl/err.h> #include "crypto/ctype.h" #include "crypto/lhash.h" #include "lhash_local.h" /* * A hashing implementation that appears to be based on the linear hashing * algorithm: * https://en.wikipedia.org/wiki/Linear_hashing * * Litwin, Witold (1980), "Linear hashing: A new tool for file and table * addressing", Proc. 6th Conference on Very Large Databases: 212-223 * https://hackthology.com/pdfs/Litwin-1980-Linear_Hashing.pdf * * From the Wikipedia article "Linear hashing is used in the BDB Berkeley * database system, which in turn is used by many software systems such as * OpenLDAP, using a C implementation derived from the CACM article and first * published on the Usenet in 1988 by Esmond Pitt." * * The CACM paper is available here: * https://pdfs.semanticscholar.org/ff4d/1c5deca6269cc316bfd952172284dbf610ee.pdf */ #undef MIN_NODES #define MIN_NODES 16 #define UP_LOAD (2*LH_LOAD_MULT) /* load times 256 (default 2) */ #define DOWN_LOAD (LH_LOAD_MULT) /* load times 256 (default 1) */ static int expand(OPENSSL_LHASH *lh); static void contract(OPENSSL_LHASH *lh); static OPENSSL_LH_NODE **getrn(OPENSSL_LHASH *lh, const void *data, unsigned long *rhash); OPENSSL_LHASH *OPENSSL_LH_new(OPENSSL_LH_HASHFUNC h, OPENSSL_LH_COMPFUNC c) { OPENSSL_LHASH *ret; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; if ((ret->b = OPENSSL_zalloc(sizeof(*ret->b) * MIN_NODES)) == NULL) goto err; ret->comp = ((c == NULL) ? (OPENSSL_LH_COMPFUNC)strcmp : c); ret->hash = ((h == NULL) ? (OPENSSL_LH_HASHFUNC)OPENSSL_LH_strhash : h); ret->num_nodes = MIN_NODES / 2; ret->num_alloc_nodes = MIN_NODES; ret->pmax = MIN_NODES / 2; ret->up_load = UP_LOAD; ret->down_load = DOWN_LOAD; return ret; err: OPENSSL_free(ret->b); OPENSSL_free(ret); return NULL; } void OPENSSL_LH_free(OPENSSL_LHASH *lh) { if (lh == NULL) return; OPENSSL_LH_flush(lh); OPENSSL_free(lh->b); OPENSSL_free(lh); } void OPENSSL_LH_flush(OPENSSL_LHASH *lh) { unsigned int i; OPENSSL_LH_NODE *n, *nn; if (lh == NULL) return; for (i = 0; i < lh->num_nodes; i++) { n = lh->b[i]; while (n != NULL) { nn = n->next; OPENSSL_free(n); n = nn; } lh->b[i] = NULL; } lh->num_items = 0; } void *OPENSSL_LH_insert(OPENSSL_LHASH *lh, void *data) { unsigned long hash; OPENSSL_LH_NODE *nn, **rn; void *ret; lh->error = 0; if ((lh->up_load <= (lh->num_items * LH_LOAD_MULT / lh->num_nodes)) && !expand(lh)) return NULL; /* 'lh->error++' already done in 'expand' */ rn = getrn(lh, data, &hash); if (*rn == NULL) { if ((nn = OPENSSL_malloc(sizeof(*nn))) == NULL) { lh->error++; return NULL; } nn->data = data; nn->next = NULL; nn->hash = hash; *rn = nn; ret = NULL; lh->num_items++; } else { /* replace same key */ ret = (*rn)->data; (*rn)->data = data; } return ret; } void *OPENSSL_LH_delete(OPENSSL_LHASH *lh, const void *data) { unsigned long hash; OPENSSL_LH_NODE *nn, **rn; void *ret; lh->error = 0; rn = getrn(lh, data, &hash); if (*rn == NULL) { return NULL; } else { nn = *rn; *rn = nn->next; ret = nn->data; OPENSSL_free(nn); } lh->num_items--; if ((lh->num_nodes > MIN_NODES) && (lh->down_load >= (lh->num_items * LH_LOAD_MULT / lh->num_nodes))) contract(lh); return ret; } void *OPENSSL_LH_retrieve(OPENSSL_LHASH *lh, const void *data) { unsigned long hash; OPENSSL_LH_NODE **rn; if (lh->error != 0) lh->error = 0; rn = getrn(lh, data, &hash); return *rn == NULL ? NULL : (*rn)->data; } static void doall_util_fn(OPENSSL_LHASH *lh, int use_arg, OPENSSL_LH_DOALL_FUNC func, OPENSSL_LH_DOALL_FUNCARG func_arg, void *arg) { int i; OPENSSL_LH_NODE *a, *n; if (lh == NULL) return; /* * reverse the order so we search from 'top to bottom' We were having * memory leaks otherwise */ for (i = lh->num_nodes - 1; i >= 0; i--) { a = lh->b[i]; while (a != NULL) { n = a->next; if (use_arg) func_arg(a->data, arg); else func(a->data); a = n; } } } void OPENSSL_LH_doall(OPENSSL_LHASH *lh, OPENSSL_LH_DOALL_FUNC func) { doall_util_fn(lh, 0, func, (OPENSSL_LH_DOALL_FUNCARG)0, NULL); } void OPENSSL_LH_doall_arg(OPENSSL_LHASH *lh, OPENSSL_LH_DOALL_FUNCARG func, void *arg) { doall_util_fn(lh, 1, (OPENSSL_LH_DOALL_FUNC)0, func, arg); } static int expand(OPENSSL_LHASH *lh) { OPENSSL_LH_NODE **n, **n1, **n2, *np; unsigned int p, pmax, nni, j; unsigned long hash; nni = lh->num_alloc_nodes; p = lh->p; pmax = lh->pmax; if (p + 1 >= pmax) { j = nni * 2; n = OPENSSL_realloc(lh->b, sizeof(OPENSSL_LH_NODE *) * j); if (n == NULL) { lh->error++; return 0; } lh->b = n; memset(n + nni, 0, sizeof(*n) * (j - nni)); lh->pmax = nni; lh->num_alloc_nodes = j; lh->p = 0; } else { lh->p++; } lh->num_nodes++; n1 = &(lh->b[p]); n2 = &(lh->b[p + pmax]); *n2 = NULL; for (np = *n1; np != NULL;) { hash = np->hash; if ((hash % nni) != p) { /* move it */ *n1 = (*n1)->next; np->next = *n2; *n2 = np; } else n1 = &((*n1)->next); np = *n1; } return 1; } static void contract(OPENSSL_LHASH *lh) { OPENSSL_LH_NODE **n, *n1, *np; np = lh->b[lh->p + lh->pmax - 1]; lh->b[lh->p + lh->pmax - 1] = NULL; /* 24/07-92 - eay - weird but :-( */ if (lh->p == 0) { n = OPENSSL_realloc(lh->b, (unsigned int)(sizeof(OPENSSL_LH_NODE *) * lh->pmax)); if (n == NULL) { /* fputs("realloc error in lhash", stderr); */ lh->error++; return; } lh->num_alloc_nodes /= 2; lh->pmax /= 2; lh->p = lh->pmax - 1; lh->b = n; } else lh->p--; lh->num_nodes--; n1 = lh->b[(int)lh->p]; if (n1 == NULL) lh->b[(int)lh->p] = np; else { while (n1->next != NULL) n1 = n1->next; n1->next = np; } } static OPENSSL_LH_NODE **getrn(OPENSSL_LHASH *lh, const void *data, unsigned long *rhash) { OPENSSL_LH_NODE **ret, *n1; unsigned long hash, nn; OPENSSL_LH_COMPFUNC cf; hash = (*(lh->hash)) (data); *rhash = hash; nn = hash % lh->pmax; if (nn < lh->p) nn = hash % lh->num_alloc_nodes; cf = lh->comp; ret = &(lh->b[(int)nn]); for (n1 = *ret; n1 != NULL; n1 = n1->next) { if (n1->hash != hash) { ret = &(n1->next); continue; } if (cf(n1->data, data) == 0) break; ret = &(n1->next); } return ret; } /* * The following hash seems to work very well on normal text strings no * collisions on /usr/dict/words and it distributes on %2^n quite well, not * as good as MD5, but still good. */ unsigned long OPENSSL_LH_strhash(const char *c) { unsigned long ret = 0; long n; unsigned long v; int r; if ((c == NULL) || (*c == '\0')) return ret; n = 0x100; while (*c) { v = n | (*c); n += 0x100; r = (int)((v >> 2) ^ v) & 0x0f; /* cast to uint64_t to avoid 32 bit shift of 32 bit value */ ret = (ret << r) | (unsigned long)((uint64_t)ret >> (32 - r)); ret &= 0xFFFFFFFFL; ret ^= v * v; c++; } return (ret >> 16) ^ ret; } /* * Case insensitive string hashing. * * The lower/upper case bit is masked out (forcing all letters to be capitals). * The major side effect on non-alpha characters is mapping the symbols and * digits into the control character range (which should be harmless). * The duplication (with respect to the hash value) of printable characters * are that '`', '{', '|', '}' and '~' map to '@', '[', '\', ']' and '^' * respectively (which seems tolerable). * * For EBCDIC, the alpha mapping is to lower case, most symbols go to control * characters. The only duplication is '0' mapping to '^', which is better * than for ASCII. */ unsigned long ossl_lh_strcasehash(const char *c) { unsigned long ret = 0; long n; unsigned long v; int r; #if defined(CHARSET_EBCDIC) && !defined(CHARSET_EBCDIC_TEST) const long int case_adjust = ~0x40; #else const long int case_adjust = ~0x20; #endif if (c == NULL || *c == '\0') return ret; for (n = 0x100; *c != '\0'; n += 0x100) { v = n | (case_adjust & *c); r = (int)((v >> 2) ^ v) & 0x0f; /* cast to uint64_t to avoid 32 bit shift of 32 bit value */ ret = (ret << r) | (unsigned long)((uint64_t)ret >> (32 - r)); ret &= 0xFFFFFFFFL; ret ^= v * v; c++; } return (ret >> 16) ^ ret; } unsigned long OPENSSL_LH_num_items(const OPENSSL_LHASH *lh) { return lh ? lh->num_items : 0; } unsigned long OPENSSL_LH_get_down_load(const OPENSSL_LHASH *lh) { return lh->down_load; } void OPENSSL_LH_set_down_load(OPENSSL_LHASH *lh, unsigned long down_load) { lh->down_load = down_load; } int OPENSSL_LH_error(OPENSSL_LHASH *lh) { return lh->error; }
10,182
24.394015
90
c
openssl
openssl-master/crypto/lhash/lhash_local.h
/* * 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/crypto.h> #include "internal/tsan_assist.h" struct lhash_node_st { void *data; struct lhash_node_st *next; unsigned long hash; }; struct lhash_st { OPENSSL_LH_NODE **b; OPENSSL_LH_COMPFUNC comp; OPENSSL_LH_HASHFUNC hash; unsigned int num_nodes; unsigned int num_alloc_nodes; unsigned int p; unsigned int pmax; unsigned long up_load; /* load times 256 */ unsigned long down_load; /* load times 256 */ unsigned long num_items; int error; };
860
25.90625
74
h
openssl
openssl-master/crypto/md2/md2_dgst.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 */ /* * MD2 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/md2.h> #include <openssl/opensslv.h> #include <openssl/crypto.h> /* * Implemented from RFC1319 The MD2 Message-Digest Algorithm */ #define UCHAR unsigned char static void md2_block(MD2_CTX *c, const unsigned char *d); /* * The magic S table - I have converted it to hex since it is basically just * a random byte string. */ static const MD2_INT S[256] = { 0x29, 0x2E, 0x43, 0xC9, 0xA2, 0xD8, 0x7C, 0x01, 0x3D, 0x36, 0x54, 0xA1, 0xEC, 0xF0, 0x06, 0x13, 0x62, 0xA7, 0x05, 0xF3, 0xC0, 0xC7, 0x73, 0x8C, 0x98, 0x93, 0x2B, 0xD9, 0xBC, 0x4C, 0x82, 0xCA, 0x1E, 0x9B, 0x57, 0x3C, 0xFD, 0xD4, 0xE0, 0x16, 0x67, 0x42, 0x6F, 0x18, 0x8A, 0x17, 0xE5, 0x12, 0xBE, 0x4E, 0xC4, 0xD6, 0xDA, 0x9E, 0xDE, 0x49, 0xA0, 0xFB, 0xF5, 0x8E, 0xBB, 0x2F, 0xEE, 0x7A, 0xA9, 0x68, 0x79, 0x91, 0x15, 0xB2, 0x07, 0x3F, 0x94, 0xC2, 0x10, 0x89, 0x0B, 0x22, 0x5F, 0x21, 0x80, 0x7F, 0x5D, 0x9A, 0x5A, 0x90, 0x32, 0x27, 0x35, 0x3E, 0xCC, 0xE7, 0xBF, 0xF7, 0x97, 0x03, 0xFF, 0x19, 0x30, 0xB3, 0x48, 0xA5, 0xB5, 0xD1, 0xD7, 0x5E, 0x92, 0x2A, 0xAC, 0x56, 0xAA, 0xC6, 0x4F, 0xB8, 0x38, 0xD2, 0x96, 0xA4, 0x7D, 0xB6, 0x76, 0xFC, 0x6B, 0xE2, 0x9C, 0x74, 0x04, 0xF1, 0x45, 0x9D, 0x70, 0x59, 0x64, 0x71, 0x87, 0x20, 0x86, 0x5B, 0xCF, 0x65, 0xE6, 0x2D, 0xA8, 0x02, 0x1B, 0x60, 0x25, 0xAD, 0xAE, 0xB0, 0xB9, 0xF6, 0x1C, 0x46, 0x61, 0x69, 0x34, 0x40, 0x7E, 0x0F, 0x55, 0x47, 0xA3, 0x23, 0xDD, 0x51, 0xAF, 0x3A, 0xC3, 0x5C, 0xF9, 0xCE, 0xBA, 0xC5, 0xEA, 0x26, 0x2C, 0x53, 0x0D, 0x6E, 0x85, 0x28, 0x84, 0x09, 0xD3, 0xDF, 0xCD, 0xF4, 0x41, 0x81, 0x4D, 0x52, 0x6A, 0xDC, 0x37, 0xC8, 0x6C, 0xC1, 0xAB, 0xFA, 0x24, 0xE1, 0x7B, 0x08, 0x0C, 0xBD, 0xB1, 0x4A, 0x78, 0x88, 0x95, 0x8B, 0xE3, 0x63, 0xE8, 0x6D, 0xE9, 0xCB, 0xD5, 0xFE, 0x3B, 0x00, 0x1D, 0x39, 0xF2, 0xEF, 0xB7, 0x0E, 0x66, 0x58, 0xD0, 0xE4, 0xA6, 0x77, 0x72, 0xF8, 0xEB, 0x75, 0x4B, 0x0A, 0x31, 0x44, 0x50, 0xB4, 0x8F, 0xED, 0x1F, 0x1A, 0xDB, 0x99, 0x8D, 0x33, 0x9F, 0x11, 0x83, 0x14, }; const char *MD2_options(void) { if (sizeof(MD2_INT) == 1) return "md2(char)"; else return "md2(int)"; } int MD2_Init(MD2_CTX *c) { c->num = 0; memset(c->state, 0, sizeof(c->state)); memset(c->cksm, 0, sizeof(c->cksm)); memset(c->data, 0, sizeof(c->data)); return 1; } int MD2_Update(MD2_CTX *c, const unsigned char *data, size_t len) { register UCHAR *p; if (len == 0) return 1; p = c->data; if (c->num != 0) { if ((c->num + len) >= MD2_BLOCK) { memcpy(&(p[c->num]), data, MD2_BLOCK - c->num); md2_block(c, c->data); data += (MD2_BLOCK - c->num); len -= (MD2_BLOCK - c->num); c->num = 0; /* drop through and do the rest */ } else { memcpy(&(p[c->num]), data, len); /* data+=len; */ c->num += (int)len; return 1; } } /* * we now can process the input data in blocks of MD2_BLOCK chars and * save the leftovers to c->data. */ while (len >= MD2_BLOCK) { md2_block(c, data); data += MD2_BLOCK; len -= MD2_BLOCK; } memcpy(p, data, len); c->num = (int)len; return 1; } static void md2_block(MD2_CTX *c, const unsigned char *d) { register MD2_INT t, *sp1, *sp2; register int i, j; MD2_INT state[48]; sp1 = c->state; sp2 = c->cksm; j = sp2[MD2_BLOCK - 1]; for (i = 0; i < 16; i++) { state[i] = sp1[i]; state[i + 16] = t = d[i]; state[i + 32] = (t ^ sp1[i]); j = sp2[i] ^= S[t ^ j]; } t = 0; for (i = 0; i < 18; i++) { for (j = 0; j < 48; j += 8) { t = state[j + 0] ^= S[t]; t = state[j + 1] ^= S[t]; t = state[j + 2] ^= S[t]; t = state[j + 3] ^= S[t]; t = state[j + 4] ^= S[t]; t = state[j + 5] ^= S[t]; t = state[j + 6] ^= S[t]; t = state[j + 7] ^= S[t]; } t = (t + i) & 0xff; } memcpy(sp1, state, 16 * sizeof(MD2_INT)); OPENSSL_cleanse(state, 48 * sizeof(MD2_INT)); } int MD2_Final(unsigned char *md, MD2_CTX *c) { int i, v; register UCHAR *cp; register MD2_INT *p1, *p2; cp = c->data; p1 = c->state; p2 = c->cksm; v = MD2_BLOCK - c->num; for (i = c->num; i < MD2_BLOCK; i++) cp[i] = (UCHAR) v; md2_block(c, cp); for (i = 0; i < MD2_BLOCK; i++) cp[i] = (UCHAR) p2[i]; md2_block(c, cp); for (i = 0; i < 16; i++) md[i] = (UCHAR) (p1[i] & 0xff); OPENSSL_cleanse(c, sizeof(*c)); return 1; }
5,231
28.066667
76
c
openssl
openssl-master/crypto/md2/md2_one.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 */ /* * MD2 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/md2.h> /* * This is a separate file so that #defines in cryptlib.h can map my MD * functions to different names */ unsigned char *MD2(const unsigned char *d, size_t n, unsigned char *md) { MD2_CTX c; static unsigned char m[MD2_DIGEST_LENGTH]; if (md == NULL) md = m; if (!MD2_Init(&c)) return NULL; #ifndef CHARSET_EBCDIC MD2_Update(&c, d, n); #else { char temp[1024]; unsigned long chunk; while (n > 0) { chunk = (n > sizeof(temp)) ? sizeof(temp) : n; ebcdic2ascii(temp, d, chunk); MD2_Update(&c, temp, chunk); n -= chunk; d += chunk; } } #endif MD2_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); /* Security consideration */ return md; }
1,328
23.611111
74
c
openssl
openssl-master/crypto/md4/md4_dgst.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 */ /* * MD4 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <openssl/opensslv.h> #include "md4_local.h" /* * Implemented from RFC1186 The MD4 Message-Digest Algorithm */ #define INIT_DATA_A (unsigned long)0x67452301L #define INIT_DATA_B (unsigned long)0xefcdab89L #define INIT_DATA_C (unsigned long)0x98badcfeL #define INIT_DATA_D (unsigned long)0x10325476L int MD4_Init(MD4_CTX *c) { memset(c, 0, sizeof(*c)); c->A = INIT_DATA_A; c->B = INIT_DATA_B; c->C = INIT_DATA_C; c->D = INIT_DATA_D; return 1; } #ifndef md4_block_data_order # ifdef X # undef X # endif void md4_block_data_order(MD4_CTX *c, const void *data_, size_t num) { const unsigned char *data = data_; register unsigned MD32_REG_T A, B, C, D, l; # ifndef MD32_XARRAY /* See comment in crypto/sha/sha_local.h for details. */ unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, XX8, XX9, XX10, XX11, XX12, XX13, XX14, XX15; # define X(i) XX##i # else MD4_LONG XX[MD4_LBLOCK]; # define X(i) XX[i] # endif A = c->A; B = c->B; C = c->C; D = c->D; for (; num--;) { (void)HOST_c2l(data, l); X(0) = l; (void)HOST_c2l(data, l); X(1) = l; /* Round 0 */ R0(A, B, C, D, X(0), 3, 0); (void)HOST_c2l(data, l); X(2) = l; R0(D, A, B, C, X(1), 7, 0); (void)HOST_c2l(data, l); X(3) = l; R0(C, D, A, B, X(2), 11, 0); (void)HOST_c2l(data, l); X(4) = l; R0(B, C, D, A, X(3), 19, 0); (void)HOST_c2l(data, l); X(5) = l; R0(A, B, C, D, X(4), 3, 0); (void)HOST_c2l(data, l); X(6) = l; R0(D, A, B, C, X(5), 7, 0); (void)HOST_c2l(data, l); X(7) = l; R0(C, D, A, B, X(6), 11, 0); (void)HOST_c2l(data, l); X(8) = l; R0(B, C, D, A, X(7), 19, 0); (void)HOST_c2l(data, l); X(9) = l; R0(A, B, C, D, X(8), 3, 0); (void)HOST_c2l(data, l); X(10) = l; R0(D, A, B, C, X(9), 7, 0); (void)HOST_c2l(data, l); X(11) = l; R0(C, D, A, B, X(10), 11, 0); (void)HOST_c2l(data, l); X(12) = l; R0(B, C, D, A, X(11), 19, 0); (void)HOST_c2l(data, l); X(13) = l; R0(A, B, C, D, X(12), 3, 0); (void)HOST_c2l(data, l); X(14) = l; R0(D, A, B, C, X(13), 7, 0); (void)HOST_c2l(data, l); X(15) = l; R0(C, D, A, B, X(14), 11, 0); R0(B, C, D, A, X(15), 19, 0); /* Round 1 */ R1(A, B, C, D, X(0), 3, 0x5A827999L); R1(D, A, B, C, X(4), 5, 0x5A827999L); R1(C, D, A, B, X(8), 9, 0x5A827999L); R1(B, C, D, A, X(12), 13, 0x5A827999L); R1(A, B, C, D, X(1), 3, 0x5A827999L); R1(D, A, B, C, X(5), 5, 0x5A827999L); R1(C, D, A, B, X(9), 9, 0x5A827999L); R1(B, C, D, A, X(13), 13, 0x5A827999L); R1(A, B, C, D, X(2), 3, 0x5A827999L); R1(D, A, B, C, X(6), 5, 0x5A827999L); R1(C, D, A, B, X(10), 9, 0x5A827999L); R1(B, C, D, A, X(14), 13, 0x5A827999L); R1(A, B, C, D, X(3), 3, 0x5A827999L); R1(D, A, B, C, X(7), 5, 0x5A827999L); R1(C, D, A, B, X(11), 9, 0x5A827999L); R1(B, C, D, A, X(15), 13, 0x5A827999L); /* Round 2 */ R2(A, B, C, D, X(0), 3, 0x6ED9EBA1L); R2(D, A, B, C, X(8), 9, 0x6ED9EBA1L); R2(C, D, A, B, X(4), 11, 0x6ED9EBA1L); R2(B, C, D, A, X(12), 15, 0x6ED9EBA1L); R2(A, B, C, D, X(2), 3, 0x6ED9EBA1L); R2(D, A, B, C, X(10), 9, 0x6ED9EBA1L); R2(C, D, A, B, X(6), 11, 0x6ED9EBA1L); R2(B, C, D, A, X(14), 15, 0x6ED9EBA1L); R2(A, B, C, D, X(1), 3, 0x6ED9EBA1L); R2(D, A, B, C, X(9), 9, 0x6ED9EBA1L); R2(C, D, A, B, X(5), 11, 0x6ED9EBA1L); R2(B, C, D, A, X(13), 15, 0x6ED9EBA1L); R2(A, B, C, D, X(3), 3, 0x6ED9EBA1L); R2(D, A, B, C, X(11), 9, 0x6ED9EBA1L); R2(C, D, A, B, X(7), 11, 0x6ED9EBA1L); R2(B, C, D, A, X(15), 15, 0x6ED9EBA1L); A = c->A += A; B = c->B += B; C = c->C += C; D = c->D += D; } } #endif
4,633
29.090909
74
c
openssl
openssl-master/crypto/md4/md4_local.h
/* * Copyright 1995-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 <stdlib.h> #include <string.h> #include <openssl/opensslconf.h> #include <openssl/md4.h> void md4_block_data_order(MD4_CTX *c, const void *p, size_t num); #define DATA_ORDER_IS_LITTLE_ENDIAN #define HASH_LONG MD4_LONG #define HASH_CTX MD4_CTX #define HASH_CBLOCK MD4_CBLOCK #define HASH_UPDATE MD4_Update #define HASH_TRANSFORM MD4_Transform #define HASH_FINAL MD4_Final #define HASH_MAKE_STRING(c,s) do { \ unsigned long ll; \ ll=(c)->A; (void)HOST_l2c(ll,(s)); \ ll=(c)->B; (void)HOST_l2c(ll,(s)); \ ll=(c)->C; (void)HOST_l2c(ll,(s)); \ ll=(c)->D; (void)HOST_l2c(ll,(s)); \ } while (0) #define HASH_BLOCK_DATA_ORDER md4_block_data_order #include "crypto/md32_common.h" /*- #define F(x,y,z) (((x) & (y)) | ((~(x)) & (z))) #define G(x,y,z) (((x) & (y)) | ((x) & ((z))) | ((y) & ((z)))) */ /* * As pointed out by Wei Dai, the above can be simplified to the code * below. Wei attributes these optimizations to Peter Gutmann's SHS code, * and he attributes it to Rich Schroeppel. */ #define F(b,c,d) ((((c) ^ (d)) & (b)) ^ (d)) #define G(b,c,d) (((b) & (c)) | ((b) & (d)) | ((c) & (d))) #define H(b,c,d) ((b) ^ (c) ^ (d)) #define R0(a,b,c,d,k,s,t) { \ a+=((k)+(t)+F((b),(c),(d))); \ a=ROTATE(a,s); }; #define R1(a,b,c,d,k,s,t) { \ a+=((k)+(t)+G((b),(c),(d))); \ a=ROTATE(a,s); }; #define R2(a,b,c,d,k,s,t) { \ a+=((k)+(t)+H((b),(c),(d))); \ a=ROTATE(a,s); };
1,967
31.262295
74
h
openssl
openssl-master/crypto/md4/md4_one.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 */ /* * MD4 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <string.h> #include <openssl/md4.h> #include <openssl/crypto.h> #ifdef CHARSET_EBCDIC # include <openssl/ebcdic.h> #endif unsigned char *MD4(const unsigned char *d, size_t n, unsigned char *md) { MD4_CTX c; static unsigned char m[MD4_DIGEST_LENGTH]; if (md == NULL) md = m; if (!MD4_Init(&c)) return NULL; #ifndef CHARSET_EBCDIC MD4_Update(&c, d, n); #else { char temp[1024]; unsigned long chunk; while (n > 0) { chunk = (n > sizeof(temp)) ? sizeof(temp) : n; ebcdic2ascii(temp, d, chunk); MD4_Update(&c, temp, chunk); n -= chunk; d += chunk; } } #endif MD4_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); /* security consideration */ return md; }
1,292
22.944444
74
c
openssl
openssl-master/crypto/md5/md5_dgst.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 */ /* * MD5 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include "md5_local.h" #include <openssl/opensslv.h> /* * Implemented from RFC1321 The MD5 Message-Digest Algorithm */ #define INIT_DATA_A (unsigned long)0x67452301L #define INIT_DATA_B (unsigned long)0xefcdab89L #define INIT_DATA_C (unsigned long)0x98badcfeL #define INIT_DATA_D (unsigned long)0x10325476L int MD5_Init(MD5_CTX *c) { memset(c, 0, sizeof(*c)); c->A = INIT_DATA_A; c->B = INIT_DATA_B; c->C = INIT_DATA_C; c->D = INIT_DATA_D; return 1; } #ifndef md5_block_data_order # ifdef X # undef X # endif void md5_block_data_order(MD5_CTX *c, const void *data_, size_t num) { const unsigned char *data = data_; register unsigned MD32_REG_T A, B, C, D, l; # ifndef MD32_XARRAY /* See comment in crypto/sha/sha_local.h for details. */ unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, XX8, XX9, XX10, XX11, XX12, XX13, XX14, XX15; # define X(i) XX##i # else MD5_LONG XX[MD5_LBLOCK]; # define X(i) XX[i] # endif A = c->A; B = c->B; C = c->C; D = c->D; for (; num--;) { (void)HOST_c2l(data, l); X(0) = l; (void)HOST_c2l(data, l); X(1) = l; /* Round 0 */ R0(A, B, C, D, X(0), 7, 0xd76aa478L); (void)HOST_c2l(data, l); X(2) = l; R0(D, A, B, C, X(1), 12, 0xe8c7b756L); (void)HOST_c2l(data, l); X(3) = l; R0(C, D, A, B, X(2), 17, 0x242070dbL); (void)HOST_c2l(data, l); X(4) = l; R0(B, C, D, A, X(3), 22, 0xc1bdceeeL); (void)HOST_c2l(data, l); X(5) = l; R0(A, B, C, D, X(4), 7, 0xf57c0fafL); (void)HOST_c2l(data, l); X(6) = l; R0(D, A, B, C, X(5), 12, 0x4787c62aL); (void)HOST_c2l(data, l); X(7) = l; R0(C, D, A, B, X(6), 17, 0xa8304613L); (void)HOST_c2l(data, l); X(8) = l; R0(B, C, D, A, X(7), 22, 0xfd469501L); (void)HOST_c2l(data, l); X(9) = l; R0(A, B, C, D, X(8), 7, 0x698098d8L); (void)HOST_c2l(data, l); X(10) = l; R0(D, A, B, C, X(9), 12, 0x8b44f7afL); (void)HOST_c2l(data, l); X(11) = l; R0(C, D, A, B, X(10), 17, 0xffff5bb1L); (void)HOST_c2l(data, l); X(12) = l; R0(B, C, D, A, X(11), 22, 0x895cd7beL); (void)HOST_c2l(data, l); X(13) = l; R0(A, B, C, D, X(12), 7, 0x6b901122L); (void)HOST_c2l(data, l); X(14) = l; R0(D, A, B, C, X(13), 12, 0xfd987193L); (void)HOST_c2l(data, l); X(15) = l; R0(C, D, A, B, X(14), 17, 0xa679438eL); R0(B, C, D, A, X(15), 22, 0x49b40821L); /* Round 1 */ R1(A, B, C, D, X(1), 5, 0xf61e2562L); R1(D, A, B, C, X(6), 9, 0xc040b340L); R1(C, D, A, B, X(11), 14, 0x265e5a51L); R1(B, C, D, A, X(0), 20, 0xe9b6c7aaL); R1(A, B, C, D, X(5), 5, 0xd62f105dL); R1(D, A, B, C, X(10), 9, 0x02441453L); R1(C, D, A, B, X(15), 14, 0xd8a1e681L); R1(B, C, D, A, X(4), 20, 0xe7d3fbc8L); R1(A, B, C, D, X(9), 5, 0x21e1cde6L); R1(D, A, B, C, X(14), 9, 0xc33707d6L); R1(C, D, A, B, X(3), 14, 0xf4d50d87L); R1(B, C, D, A, X(8), 20, 0x455a14edL); R1(A, B, C, D, X(13), 5, 0xa9e3e905L); R1(D, A, B, C, X(2), 9, 0xfcefa3f8L); R1(C, D, A, B, X(7), 14, 0x676f02d9L); R1(B, C, D, A, X(12), 20, 0x8d2a4c8aL); /* Round 2 */ R2(A, B, C, D, X(5), 4, 0xfffa3942L); R2(D, A, B, C, X(8), 11, 0x8771f681L); R2(C, D, A, B, X(11), 16, 0x6d9d6122L); R2(B, C, D, A, X(14), 23, 0xfde5380cL); R2(A, B, C, D, X(1), 4, 0xa4beea44L); R2(D, A, B, C, X(4), 11, 0x4bdecfa9L); R2(C, D, A, B, X(7), 16, 0xf6bb4b60L); R2(B, C, D, A, X(10), 23, 0xbebfbc70L); R2(A, B, C, D, X(13), 4, 0x289b7ec6L); R2(D, A, B, C, X(0), 11, 0xeaa127faL); R2(C, D, A, B, X(3), 16, 0xd4ef3085L); R2(B, C, D, A, X(6), 23, 0x04881d05L); R2(A, B, C, D, X(9), 4, 0xd9d4d039L); R2(D, A, B, C, X(12), 11, 0xe6db99e5L); R2(C, D, A, B, X(15), 16, 0x1fa27cf8L); R2(B, C, D, A, X(2), 23, 0xc4ac5665L); /* Round 3 */ R3(A, B, C, D, X(0), 6, 0xf4292244L); R3(D, A, B, C, X(7), 10, 0x432aff97L); R3(C, D, A, B, X(14), 15, 0xab9423a7L); R3(B, C, D, A, X(5), 21, 0xfc93a039L); R3(A, B, C, D, X(12), 6, 0x655b59c3L); R3(D, A, B, C, X(3), 10, 0x8f0ccc92L); R3(C, D, A, B, X(10), 15, 0xffeff47dL); R3(B, C, D, A, X(1), 21, 0x85845dd1L); R3(A, B, C, D, X(8), 6, 0x6fa87e4fL); R3(D, A, B, C, X(15), 10, 0xfe2ce6e0L); R3(C, D, A, B, X(6), 15, 0xa3014314L); R3(B, C, D, A, X(13), 21, 0x4e0811a1L); R3(A, B, C, D, X(4), 6, 0xf7537e82L); R3(D, A, B, C, X(11), 10, 0xbd3af235L); R3(C, D, A, B, X(2), 15, 0x2ad7d2bbL); R3(B, C, D, A, X(9), 21, 0xeb86d391L); A = c->A += A; B = c->B += B; C = c->C += C; D = c->D += D; } } #endif
5,581
31.643275
74
c
openssl
openssl-master/crypto/md5/md5_local.h
/* * 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 <stdlib.h> #include <string.h> #include <openssl/e_os2.h> #include <openssl/md5.h> #ifdef MD5_ASM # if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \ defined(__x86_64) || defined(__x86_64__) || defined(_M_AMD64) || \ defined(_M_X64) || defined(__aarch64__) # define md5_block_data_order ossl_md5_block_asm_data_order # elif defined(__ia64) || defined(__ia64__) || defined(_M_IA64) # define md5_block_data_order ossl_md5_block_asm_data_order # elif defined(__sparc) || defined(__sparc__) # define md5_block_data_order ossl_md5_block_asm_data_order # endif #endif void md5_block_data_order(MD5_CTX *c, const void *p, size_t num); #define DATA_ORDER_IS_LITTLE_ENDIAN #define HASH_LONG MD5_LONG #define HASH_CTX MD5_CTX #define HASH_CBLOCK MD5_CBLOCK #define HASH_UPDATE MD5_Update #define HASH_TRANSFORM MD5_Transform #define HASH_FINAL MD5_Final #define HASH_MAKE_STRING(c,s) do { \ unsigned long ll; \ ll=(c)->A; (void)HOST_l2c(ll,(s)); \ ll=(c)->B; (void)HOST_l2c(ll,(s)); \ ll=(c)->C; (void)HOST_l2c(ll,(s)); \ ll=(c)->D; (void)HOST_l2c(ll,(s)); \ } while (0) #define HASH_BLOCK_DATA_ORDER md5_block_data_order #include "crypto/md32_common.h" /*- #define F(x,y,z) (((x) & (y)) | ((~(x)) & (z))) #define G(x,y,z) (((x) & (z)) | ((y) & (~(z)))) */ /* * As pointed out by Wei Dai, the above can be simplified to the code * below. Wei attributes these optimizations to Peter Gutmann's * SHS code, and he attributes it to Rich Schroeppel. */ #define F(b,c,d) ((((c) ^ (d)) & (b)) ^ (d)) #define G(b,c,d) ((((b) ^ (c)) & (d)) ^ (c)) #define H(b,c,d) ((b) ^ (c) ^ (d)) #define I(b,c,d) (((~(d)) | (b)) ^ (c)) #define R0(a,b,c,d,k,s,t) { \ a+=((k)+(t)+F((b),(c),(d))); \ a=ROTATE(a,s); \ a+=b; }; #define R1(a,b,c,d,k,s,t) { \ a+=((k)+(t)+G((b),(c),(d))); \ a=ROTATE(a,s); \ a+=b; }; #define R2(a,b,c,d,k,s,t) { \ a+=((k)+(t)+H((b),(c),(d))); \ a=ROTATE(a,s); \ a+=b; }; #define R3(a,b,c,d,k,s,t) { \ a+=((k)+(t)+I((b),(c),(d))); \ a=ROTATE(a,s); \ a+=b; };
2,647
31.292683
74
h
openssl
openssl-master/crypto/md5/md5_one.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 */ /* * MD5 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <string.h> #include <openssl/md5.h> #include <openssl/crypto.h> #ifdef CHARSET_EBCDIC # include <openssl/ebcdic.h> #endif unsigned char *MD5(const unsigned char *d, size_t n, unsigned char *md) { MD5_CTX c; static unsigned char m[MD5_DIGEST_LENGTH]; if (md == NULL) md = m; if (!MD5_Init(&c)) return NULL; #ifndef CHARSET_EBCDIC MD5_Update(&c, d, n); #else { char temp[1024]; unsigned long chunk; while (n > 0) { chunk = (n > sizeof(temp)) ? sizeof(temp) : n; ebcdic2ascii(temp, d, chunk); MD5_Update(&c, temp, chunk); n -= chunk; d += chunk; } } #endif MD5_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); /* security consideration */ return md; }
1,292
22.944444
74
c
openssl
openssl-master/crypto/md5/md5_sha1.c
/* * 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 */ /* * MD5 and SHA-1 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <string.h> #include "prov/md5_sha1.h" #include <openssl/evp.h> int ossl_md5_sha1_init(MD5_SHA1_CTX *mctx) { if (!MD5_Init(&mctx->md5)) return 0; return SHA1_Init(&mctx->sha1); } int ossl_md5_sha1_update(MD5_SHA1_CTX *mctx, const void *data, size_t count) { if (!MD5_Update(&mctx->md5, data, count)) return 0; return SHA1_Update(&mctx->sha1, data, count); } int ossl_md5_sha1_final(unsigned char *md, MD5_SHA1_CTX *mctx) { if (!MD5_Final(md, &mctx->md5)) return 0; return SHA1_Final(md + MD5_DIGEST_LENGTH, &mctx->sha1); } int ossl_md5_sha1_ctrl(MD5_SHA1_CTX *mctx, int cmd, int mslen, void *ms) { unsigned char padtmp[48]; unsigned char md5tmp[MD5_DIGEST_LENGTH]; unsigned char sha1tmp[SHA_DIGEST_LENGTH]; if (cmd != EVP_CTRL_SSL3_MASTER_SECRET) return -2; if (mctx == NULL) return 0; /* SSLv3 client auth handling: see RFC-6101 5.6.8 */ if (mslen != 48) return 0; /* At this point hash contains all handshake messages, update * with master secret and pad_1. */ if (ossl_md5_sha1_update(mctx, ms, mslen) <= 0) return 0; /* Set padtmp to pad_1 value */ memset(padtmp, 0x36, sizeof(padtmp)); if (!MD5_Update(&mctx->md5, padtmp, sizeof(padtmp))) return 0; if (!MD5_Final(md5tmp, &mctx->md5)) return 0; if (!SHA1_Update(&mctx->sha1, padtmp, 40)) return 0; if (!SHA1_Final(sha1tmp, &mctx->sha1)) return 0; /* Reinitialise context */ if (!ossl_md5_sha1_init(mctx)) return 0; if (ossl_md5_sha1_update(mctx, ms, mslen) <= 0) return 0; /* Set padtmp to pad_2 value */ memset(padtmp, 0x5c, sizeof(padtmp)); if (!MD5_Update(&mctx->md5, padtmp, sizeof(padtmp))) return 0; if (!MD5_Update(&mctx->md5, md5tmp, sizeof(md5tmp))) return 0; if (!SHA1_Update(&mctx->sha1, padtmp, 40)) return 0; if (!SHA1_Update(&mctx->sha1, sha1tmp, sizeof(sha1tmp))) return 0; /* Now when ctx is finalised it will return the SSL v3 hash value */ OPENSSL_cleanse(md5tmp, sizeof(md5tmp)); OPENSSL_cleanse(sha1tmp, sizeof(sha1tmp)); return 1; }
2,699
23.770642
79
c
openssl
openssl-master/crypto/mdc2/mdc2_one.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 */ /* * MD2 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/mdc2.h> unsigned char *MDC2(const unsigned char *d, size_t n, unsigned char *md) { MDC2_CTX c; static unsigned char m[MDC2_DIGEST_LENGTH]; if (md == NULL) md = m; if (!MDC2_Init(&c)) return NULL; MDC2_Update(&c, d, n); MDC2_Final(md, &c); OPENSSL_cleanse(&c, sizeof(c)); /* security consideration */ return md; }
896
25.382353
74
c
openssl
openssl-master/crypto/mdc2/mdc2dgst.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 */ /* * MD2 low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/crypto.h> #include <openssl/des.h> #include <openssl/mdc2.h> #undef c2l #define c2l(c,l) (l =((DES_LONG)(*((c)++))) , \ l|=((DES_LONG)(*((c)++)))<< 8L, \ l|=((DES_LONG)(*((c)++)))<<16L, \ l|=((DES_LONG)(*((c)++)))<<24L) #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)) static void mdc2_body(MDC2_CTX *c, const unsigned char *in, size_t len); int MDC2_Init(MDC2_CTX *c) { c->num = 0; c->pad_type = 1; memset(&(c->h[0]), 0x52, MDC2_BLOCK); memset(&(c->hh[0]), 0x25, MDC2_BLOCK); return 1; } int MDC2_Update(MDC2_CTX *c, const unsigned char *in, size_t len) { size_t i, j; i = c->num; if (i != 0) { if (len < MDC2_BLOCK - i) { /* partial block */ memcpy(&(c->data[i]), in, len); c->num += (int)len; return 1; } else { /* filled one */ j = MDC2_BLOCK - i; memcpy(&(c->data[i]), in, j); len -= j; in += j; c->num = 0; mdc2_body(c, &(c->data[0]), MDC2_BLOCK); } } i = len & ~((size_t)MDC2_BLOCK - 1); if (i > 0) mdc2_body(c, in, i); j = len - i; if (j > 0) { memcpy(&(c->data[0]), &(in[i]), j); c->num = (int)j; } return 1; } static void mdc2_body(MDC2_CTX *c, const unsigned char *in, size_t len) { register DES_LONG tin0, tin1; register DES_LONG ttin0, ttin1; DES_LONG d[2], dd[2]; DES_key_schedule k; unsigned char *p; size_t i; for (i = 0; i < len; i += 8) { c2l(in, tin0); d[0] = dd[0] = tin0; c2l(in, tin1); d[1] = dd[1] = tin1; c->h[0] = (c->h[0] & 0x9f) | 0x40; c->hh[0] = (c->hh[0] & 0x9f) | 0x20; DES_set_odd_parity(&c->h); DES_set_key_unchecked(&c->h, &k); DES_encrypt1(d, &k, 1); DES_set_odd_parity(&c->hh); DES_set_key_unchecked(&c->hh, &k); DES_encrypt1(dd, &k, 1); ttin0 = tin0 ^ dd[0]; ttin1 = tin1 ^ dd[1]; tin0 ^= d[0]; tin1 ^= d[1]; p = c->h; l2c(tin0, p); l2c(ttin1, p); p = c->hh; l2c(ttin0, p); l2c(tin1, p); } } int MDC2_Final(unsigned char *md, MDC2_CTX *c) { unsigned int i; int j; i = c->num; j = c->pad_type; if ((i > 0) || (j == 2)) { if (j == 2) c->data[i++] = 0x80; memset(&(c->data[i]), 0, MDC2_BLOCK - i); mdc2_body(c, c->data, MDC2_BLOCK); } memcpy(md, (char *)c->h, MDC2_BLOCK); memcpy(&(md[MDC2_BLOCK]), (char *)c->hh, MDC2_BLOCK); return 1; }
3,470
25.097744
74
c
openssl
openssl-master/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; } }
4,934
27.526012
78
c
openssl
openssl-master/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; }
11,953
25.984199
77
c
openssl
openssl-master/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); }
7,005
32.04717
77
c
openssl
openssl-master/crypto/modes/ctr128.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 "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 /* * NOTE: the IV/counter CTR mode is big-endian. The code itself is * endian-neutral. */ /* increment counter (128-bit int) by 1 */ static void ctr128_inc(unsigned char *counter) { u32 n = 16, c = 1; do { --n; c += counter[n]; counter[n] = (u8)c; c >>= 8; } while (n); } #if !defined(OPENSSL_SMALL_FOOTPRINT) static void ctr128_inc_aligned(unsigned char *counter) { size_t *data, c, d, n; DECLARE_IS_ENDIAN; if (IS_LITTLE_ENDIAN || ((size_t)counter % sizeof(size_t)) != 0) { ctr128_inc(counter); return; } data = (size_t *)counter; c = 1; n = 16 / sizeof(size_t); do { --n; d = data[n] += c; /* did addition carry? */ c = ((d - c) & ~d) >> (sizeof(size_t) * 8 - 1); } while (n); } #endif /* * The input encrypted as though 128bit counter mode is being used. The * extra state information to record how much of the 128bit block we have * used is contained in *num, and the encrypted counter is kept in * ecount_buf. Both *num and ecount_buf must be initialised with zeros * before the first call to CRYPTO_ctr128_encrypt(). This algorithm assumes * that the counter is in the x lower bits of the IV (ivec), and that the * application has full control over overflow and the rest of the IV. This * implementation takes NO responsibility for checking that the counter * doesn't overflow into the rest of the IV when incremented. */ void CRYPTO_ctr128_encrypt(const unsigned char *in, unsigned char *out, size_t len, const void *key, unsigned char ivec[16], unsigned char ecount_buf[16], unsigned int *num, block128_f block) { unsigned int n; size_t l = 0; n = *num; #if !defined(OPENSSL_SMALL_FOOTPRINT) if (16 % sizeof(size_t) == 0) { /* always true actually */ do { while (n && len) { *(out++) = *(in++) ^ ecount_buf[n]; --len; n = (n + 1) % 16; } # if defined(STRICT_ALIGNMENT) if (((size_t)in | (size_t)out | (size_t)ecount_buf) % sizeof(size_t) != 0) break; # endif while (len >= 16) { (*block) (ivec, ecount_buf, key); ctr128_inc_aligned(ivec); for (n = 0; n < 16; n += sizeof(size_t)) *(size_t_aX *)(out + n) = *(size_t_aX *)(in + n) ^ *(size_t_aX *)(ecount_buf + n); len -= 16; out += 16; in += 16; n = 0; } if (len) { (*block) (ivec, ecount_buf, key); ctr128_inc_aligned(ivec); while (len--) { out[n] = in[n] ^ ecount_buf[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, ecount_buf, key); ctr128_inc(ivec); } out[l] = in[l] ^ ecount_buf[n]; ++l; n = (n + 1) % 16; } *num = n; } /* increment upper 96 bits of 128-bit counter by 1 */ static void ctr96_inc(unsigned char *counter) { u32 n = 12, c = 1; do { --n; c += counter[n]; counter[n] = (u8)c; c >>= 8; } while (n); } void CRYPTO_ctr128_encrypt_ctr32(const unsigned char *in, unsigned char *out, size_t len, const void *key, unsigned char ivec[16], unsigned char ecount_buf[16], unsigned int *num, ctr128_f func) { unsigned int n, ctr32; n = *num; while (n && len) { *(out++) = *(in++) ^ ecount_buf[n]; --len; n = (n + 1) % 16; } ctr32 = GETU32(ivec + 12); while (len >= 16) { size_t blocks = len / 16; /* * 1<<28 is just a not-so-small yet not-so-large number... * Below condition is practically never met, but it has to * be checked for code correctness. */ if (sizeof(size_t) > sizeof(unsigned int) && blocks > (1U << 28)) blocks = (1U << 28); /* * As (*func) operates on 32-bit counter, caller * has to handle overflow. 'if' below detects the * overflow, which is then handled by limiting the * amount of blocks to the exact overflow point... */ ctr32 += (u32)blocks; if (ctr32 < blocks) { blocks -= ctr32; ctr32 = 0; } (*func) (in, out, blocks, key, ivec); /* (*ctr) does not update ivec, caller does: */ PUTU32(ivec + 12, ctr32); /* ... overflow was detected, propagate carry. */ if (ctr32 == 0) ctr96_inc(ivec); blocks *= 16; len -= blocks; out += blocks; in += blocks; } if (len) { memset(ecount_buf, 0, 16); (*func) (ecount_buf, ecount_buf, 1, key, ivec); ++ctr32; PUTU32(ivec + 12, ctr32); if (ctr32 == 0) ctr96_inc(ivec); while (len--) { out[n] = in[n] ^ ecount_buf[n]; ++n; } } *num = n; }
6,108
27.680751
77
c
openssl
openssl-master/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; }
8,231
23.870091
77
c
openssl
openssl-master/crypto/modes/ocb128.c
/* * Copyright 2014-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 <openssl/err.h> #include "crypto/modes.h" #ifndef OPENSSL_NO_OCB /* * Calculate the number of binary trailing zero's in any given number */ static u32 ocb_ntz(u64 n) { u32 cnt = 0; /* * We do a right-to-left simple sequential search. This is surprisingly * efficient as the distribution of trailing zeros is not uniform, * e.g. the number of possible inputs with no trailing zeros is equal to * the number with 1 or more; the number with exactly 1 is equal to the * number with 2 or more, etc. Checking the last two bits covers 75% of * all numbers. Checking the last three covers 87.5% */ while (!(n & 1)) { n >>= 1; cnt++; } return cnt; } /* * Shift a block of 16 bytes left by shift bits */ static void ocb_block_lshift(const unsigned char *in, size_t shift, unsigned char *out) { int i; unsigned char carry = 0, carry_next; for (i = 15; i >= 0; i--) { carry_next = in[i] >> (8 - shift); out[i] = (in[i] << shift) | carry; carry = carry_next; } } /* * Perform a "double" operation as per OCB spec */ static void ocb_double(OCB_BLOCK *in, OCB_BLOCK *out) { unsigned char mask; /* * Calculate the mask based on the most significant bit. There are more * efficient ways to do this - but this way is constant time */ mask = in->c[0] & 0x80; mask >>= 7; mask = (0 - mask) & 0x87; ocb_block_lshift(in->c, 1, out->c); out->c[15] ^= mask; } /* * Perform an xor on in1 and in2 - each of len bytes. Store result in out */ static void ocb_block_xor(const unsigned char *in1, const unsigned char *in2, size_t len, unsigned char *out) { size_t i; for (i = 0; i < len; i++) { out[i] = in1[i] ^ in2[i]; } } /* * Lookup L_index in our lookup table. If we haven't already got it we need to * calculate it */ static OCB_BLOCK *ocb_lookup_l(OCB128_CONTEXT *ctx, size_t idx) { size_t l_index = ctx->l_index; if (idx <= l_index) { return ctx->l + idx; } /* We don't have it - so calculate it */ if (idx >= ctx->max_l_index) { void *tmp_ptr; /* * Each additional entry allows to process almost double as * much data, so that in linear world the table will need to * be expanded with smaller and smaller increments. Originally * it was doubling in size, which was a waste. Growing it * linearly is not formally optimal, but is simpler to implement. * We grow table by minimally required 4*n that would accommodate * the index. */ ctx->max_l_index += (idx - ctx->max_l_index + 4) & ~3; tmp_ptr = OPENSSL_realloc(ctx->l, ctx->max_l_index * sizeof(OCB_BLOCK)); if (tmp_ptr == NULL) /* prevent ctx->l from being clobbered */ return NULL; ctx->l = tmp_ptr; } while (l_index < idx) { ocb_double(ctx->l + l_index, ctx->l + l_index + 1); l_index++; } ctx->l_index = l_index; return ctx->l + idx; } /* * Create a new OCB128_CONTEXT */ OCB128_CONTEXT *CRYPTO_ocb128_new(void *keyenc, void *keydec, block128_f encrypt, block128_f decrypt, ocb128_f stream) { OCB128_CONTEXT *octx; int ret; if ((octx = OPENSSL_malloc(sizeof(*octx))) != NULL) { ret = CRYPTO_ocb128_init(octx, keyenc, keydec, encrypt, decrypt, stream); if (ret) return octx; OPENSSL_free(octx); } return NULL; } /* * Initialise an existing OCB128_CONTEXT */ int CRYPTO_ocb128_init(OCB128_CONTEXT *ctx, void *keyenc, void *keydec, block128_f encrypt, block128_f decrypt, ocb128_f stream) { memset(ctx, 0, sizeof(*ctx)); ctx->l_index = 0; ctx->max_l_index = 5; if ((ctx->l = OPENSSL_malloc(ctx->max_l_index * 16)) == NULL) return 0; /* * We set both the encryption and decryption key schedules - decryption * needs both. Don't really need decryption schedule if only doing * encryption - but it simplifies things to take it anyway */ ctx->encrypt = encrypt; ctx->decrypt = decrypt; ctx->stream = stream; ctx->keyenc = keyenc; ctx->keydec = keydec; /* L_* = ENCIPHER(K, zeros(128)) */ ctx->encrypt(ctx->l_star.c, ctx->l_star.c, ctx->keyenc); /* L_$ = double(L_*) */ ocb_double(&ctx->l_star, &ctx->l_dollar); /* L_0 = double(L_$) */ ocb_double(&ctx->l_dollar, ctx->l); /* L_{i} = double(L_{i-1}) */ ocb_double(ctx->l, ctx->l+1); ocb_double(ctx->l+1, ctx->l+2); ocb_double(ctx->l+2, ctx->l+3); ocb_double(ctx->l+3, ctx->l+4); ctx->l_index = 4; /* enough to process up to 496 bytes */ return 1; } /* * Copy an OCB128_CONTEXT object */ int CRYPTO_ocb128_copy_ctx(OCB128_CONTEXT *dest, OCB128_CONTEXT *src, void *keyenc, void *keydec) { memcpy(dest, src, sizeof(OCB128_CONTEXT)); if (keyenc) dest->keyenc = keyenc; if (keydec) dest->keydec = keydec; if (src->l) { if ((dest->l = OPENSSL_malloc(src->max_l_index * 16)) == NULL) return 0; memcpy(dest->l, src->l, (src->l_index + 1) * 16); } return 1; } /* * Set the IV to be used for this operation. Must be 1 - 15 bytes. */ int CRYPTO_ocb128_setiv(OCB128_CONTEXT *ctx, const unsigned char *iv, size_t len, size_t taglen) { unsigned char ktop[16], tmp[16], mask; unsigned char stretch[24], nonce[16]; size_t bottom, shift; /* * Spec says IV is 120 bits or fewer - it allows non byte aligned lengths. * We don't support this at this stage */ if ((len > 15) || (len < 1) || (taglen > 16) || (taglen < 1)) { return -1; } /* Reset nonce-dependent variables */ memset(&ctx->sess, 0, sizeof(ctx->sess)); /* Nonce = num2str(TAGLEN mod 128,7) || zeros(120-bitlen(N)) || 1 || N */ nonce[0] = ((taglen * 8) % 128) << 1; memset(nonce + 1, 0, 15); memcpy(nonce + 16 - len, iv, len); nonce[15 - len] |= 1; /* Ktop = ENCIPHER(K, Nonce[1..122] || zeros(6)) */ memcpy(tmp, nonce, 16); tmp[15] &= 0xc0; ctx->encrypt(tmp, ktop, ctx->keyenc); /* Stretch = Ktop || (Ktop[1..64] xor Ktop[9..72]) */ memcpy(stretch, ktop, 16); ocb_block_xor(ktop, ktop + 1, 8, stretch + 16); /* bottom = str2num(Nonce[123..128]) */ bottom = nonce[15] & 0x3f; /* Offset_0 = Stretch[1+bottom..128+bottom] */ shift = bottom % 8; ocb_block_lshift(stretch + (bottom / 8), shift, ctx->sess.offset.c); mask = 0xff; mask <<= 8 - shift; ctx->sess.offset.c[15] |= (*(stretch + (bottom / 8) + 16) & mask) >> (8 - shift); return 1; } /* * Provide any AAD. This can be called multiple times. Only the final time can * have a partial block */ int CRYPTO_ocb128_aad(OCB128_CONTEXT *ctx, const unsigned char *aad, size_t len) { u64 i, all_num_blocks; size_t num_blocks, last_len; OCB_BLOCK tmp; /* Calculate the number of blocks of AAD provided now, and so far */ num_blocks = len / 16; all_num_blocks = num_blocks + ctx->sess.blocks_hashed; /* Loop through all full blocks of AAD */ for (i = ctx->sess.blocks_hashed + 1; i <= all_num_blocks; i++) { OCB_BLOCK *lookup; /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ lookup = ocb_lookup_l(ctx, ocb_ntz(i)); if (lookup == NULL) return 0; ocb_block16_xor(&ctx->sess.offset_aad, lookup, &ctx->sess.offset_aad); memcpy(tmp.c, aad, 16); aad += 16; /* Sum_i = Sum_{i-1} xor ENCIPHER(K, A_i xor Offset_i) */ ocb_block16_xor(&ctx->sess.offset_aad, &tmp, &tmp); ctx->encrypt(tmp.c, tmp.c, ctx->keyenc); ocb_block16_xor(&tmp, &ctx->sess.sum, &ctx->sess.sum); } /* * Check if we have any partial blocks left over. This is only valid in the * last call to this function */ last_len = len % 16; if (last_len > 0) { /* Offset_* = Offset_m xor L_* */ ocb_block16_xor(&ctx->sess.offset_aad, &ctx->l_star, &ctx->sess.offset_aad); /* CipherInput = (A_* || 1 || zeros(127-bitlen(A_*))) xor Offset_* */ memset(tmp.c, 0, 16); memcpy(tmp.c, aad, last_len); tmp.c[last_len] = 0x80; ocb_block16_xor(&ctx->sess.offset_aad, &tmp, &tmp); /* Sum = Sum_m xor ENCIPHER(K, CipherInput) */ ctx->encrypt(tmp.c, tmp.c, ctx->keyenc); ocb_block16_xor(&tmp, &ctx->sess.sum, &ctx->sess.sum); } ctx->sess.blocks_hashed = all_num_blocks; return 1; } /* * Provide any data to be encrypted. This can be called multiple times. Only * the final time can have a partial block */ int CRYPTO_ocb128_encrypt(OCB128_CONTEXT *ctx, const unsigned char *in, unsigned char *out, size_t len) { u64 i, all_num_blocks; size_t num_blocks, last_len; /* * Calculate the number of blocks of data to be encrypted provided now, and * so far */ num_blocks = len / 16; all_num_blocks = num_blocks + ctx->sess.blocks_processed; if (num_blocks && all_num_blocks == (size_t)all_num_blocks && ctx->stream != NULL) { size_t max_idx = 0, top = (size_t)all_num_blocks; /* * See how many L_{i} entries we need to process data at hand * and pre-compute missing entries in the table [if any]... */ while (top >>= 1) max_idx++; if (ocb_lookup_l(ctx, max_idx) == NULL) return 0; ctx->stream(in, out, num_blocks, ctx->keyenc, (size_t)ctx->sess.blocks_processed + 1, ctx->sess.offset.c, (const unsigned char (*)[16])ctx->l, ctx->sess.checksum.c); } else { /* Loop through all full blocks to be encrypted */ for (i = ctx->sess.blocks_processed + 1; i <= all_num_blocks; i++) { OCB_BLOCK *lookup; OCB_BLOCK tmp; /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ lookup = ocb_lookup_l(ctx, ocb_ntz(i)); if (lookup == NULL) return 0; ocb_block16_xor(&ctx->sess.offset, lookup, &ctx->sess.offset); memcpy(tmp.c, in, 16); in += 16; /* Checksum_i = Checksum_{i-1} xor P_i */ ocb_block16_xor(&tmp, &ctx->sess.checksum, &ctx->sess.checksum); /* C_i = Offset_i xor ENCIPHER(K, P_i xor Offset_i) */ ocb_block16_xor(&ctx->sess.offset, &tmp, &tmp); ctx->encrypt(tmp.c, tmp.c, ctx->keyenc); ocb_block16_xor(&ctx->sess.offset, &tmp, &tmp); memcpy(out, tmp.c, 16); out += 16; } } /* * Check if we have any partial blocks left over. This is only valid in the * last call to this function */ last_len = len % 16; if (last_len > 0) { OCB_BLOCK pad; /* Offset_* = Offset_m xor L_* */ ocb_block16_xor(&ctx->sess.offset, &ctx->l_star, &ctx->sess.offset); /* Pad = ENCIPHER(K, Offset_*) */ ctx->encrypt(ctx->sess.offset.c, pad.c, ctx->keyenc); /* C_* = P_* xor Pad[1..bitlen(P_*)] */ ocb_block_xor(in, pad.c, last_len, out); /* Checksum_* = Checksum_m xor (P_* || 1 || zeros(127-bitlen(P_*))) */ memset(pad.c, 0, 16); /* borrow pad */ memcpy(pad.c, in, last_len); pad.c[last_len] = 0x80; ocb_block16_xor(&pad, &ctx->sess.checksum, &ctx->sess.checksum); } ctx->sess.blocks_processed = all_num_blocks; return 1; } /* * Provide any data to be decrypted. This can be called multiple times. Only * the final time can have a partial block */ int CRYPTO_ocb128_decrypt(OCB128_CONTEXT *ctx, const unsigned char *in, unsigned char *out, size_t len) { u64 i, all_num_blocks; size_t num_blocks, last_len; /* * Calculate the number of blocks of data to be decrypted provided now, and * so far */ num_blocks = len / 16; all_num_blocks = num_blocks + ctx->sess.blocks_processed; if (num_blocks && all_num_blocks == (size_t)all_num_blocks && ctx->stream != NULL) { size_t max_idx = 0, top = (size_t)all_num_blocks; /* * See how many L_{i} entries we need to process data at hand * and pre-compute missing entries in the table [if any]... */ while (top >>= 1) max_idx++; if (ocb_lookup_l(ctx, max_idx) == NULL) return 0; ctx->stream(in, out, num_blocks, ctx->keydec, (size_t)ctx->sess.blocks_processed + 1, ctx->sess.offset.c, (const unsigned char (*)[16])ctx->l, ctx->sess.checksum.c); } else { OCB_BLOCK tmp; /* Loop through all full blocks to be decrypted */ for (i = ctx->sess.blocks_processed + 1; i <= all_num_blocks; i++) { /* Offset_i = Offset_{i-1} xor L_{ntz(i)} */ OCB_BLOCK *lookup = ocb_lookup_l(ctx, ocb_ntz(i)); if (lookup == NULL) return 0; ocb_block16_xor(&ctx->sess.offset, lookup, &ctx->sess.offset); memcpy(tmp.c, in, 16); in += 16; /* P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) */ ocb_block16_xor(&ctx->sess.offset, &tmp, &tmp); ctx->decrypt(tmp.c, tmp.c, ctx->keydec); ocb_block16_xor(&ctx->sess.offset, &tmp, &tmp); /* Checksum_i = Checksum_{i-1} xor P_i */ ocb_block16_xor(&tmp, &ctx->sess.checksum, &ctx->sess.checksum); memcpy(out, tmp.c, 16); out += 16; } } /* * Check if we have any partial blocks left over. This is only valid in the * last call to this function */ last_len = len % 16; if (last_len > 0) { OCB_BLOCK pad; /* Offset_* = Offset_m xor L_* */ ocb_block16_xor(&ctx->sess.offset, &ctx->l_star, &ctx->sess.offset); /* Pad = ENCIPHER(K, Offset_*) */ ctx->encrypt(ctx->sess.offset.c, pad.c, ctx->keyenc); /* P_* = C_* xor Pad[1..bitlen(C_*)] */ ocb_block_xor(in, pad.c, last_len, out); /* Checksum_* = Checksum_m xor (P_* || 1 || zeros(127-bitlen(P_*))) */ memset(pad.c, 0, 16); /* borrow pad */ memcpy(pad.c, out, last_len); pad.c[last_len] = 0x80; ocb_block16_xor(&pad, &ctx->sess.checksum, &ctx->sess.checksum); } ctx->sess.blocks_processed = all_num_blocks; return 1; } static int ocb_finish(OCB128_CONTEXT *ctx, unsigned char *tag, size_t len, int write) { OCB_BLOCK tmp; if (len > 16 || len < 1) { return -1; } /* * Tag = ENCIPHER(K, Checksum_* xor Offset_* xor L_$) xor HASH(K,A) */ ocb_block16_xor(&ctx->sess.checksum, &ctx->sess.offset, &tmp); ocb_block16_xor(&ctx->l_dollar, &tmp, &tmp); ctx->encrypt(tmp.c, tmp.c, ctx->keyenc); ocb_block16_xor(&tmp, &ctx->sess.sum, &tmp); if (write) { memcpy(tag, &tmp, len); return 1; } else { return CRYPTO_memcmp(&tmp, tag, len); } } /* * Calculate the tag and verify it against the supplied tag */ int CRYPTO_ocb128_finish(OCB128_CONTEXT *ctx, const unsigned char *tag, size_t len) { return ocb_finish(ctx, (unsigned char*)tag, len, 0); } /* * Retrieve the calculated tag */ int CRYPTO_ocb128_tag(OCB128_CONTEXT *ctx, unsigned char *tag, size_t len) { return ocb_finish(ctx, tag, len, 1); } /* * Release all resources */ void CRYPTO_ocb128_cleanup(OCB128_CONTEXT *ctx) { if (ctx) { OPENSSL_clear_free(ctx->l, ctx->max_l_index * 16); OPENSSL_cleanse(ctx, sizeof(*ctx)); } } #endif /* OPENSSL_NO_OCB */
16,602
28.701252
80
c
openssl
openssl-master/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; }
2,489
27.62069
78
c
openssl
openssl-master/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 */
10,595
25.893401
88
c
openssl
openssl-master/crypto/modes/wrap128.c
/* * Copyright 2013-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 */ /** Beware! * * Following wrapping modes were designed for AES but this implementation * allows you to use them for any 128 bit block cipher. */ #include "internal/cryptlib.h" #include <openssl/modes.h> /** RFC 3394 section 2.2.3.1 Default Initial Value */ static const unsigned char default_iv[] = { 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, }; /** RFC 5649 section 3 Alternative Initial Value 32-bit constant */ static const unsigned char default_aiv[] = { 0xA6, 0x59, 0x59, 0xA6 }; /** Input size limit: lower than maximum of standards but far larger than * anything that will be used in practice. */ #define CRYPTO128_WRAP_MAX (1UL << 31) /** Wrapping according to RFC 3394 section 2.2.1. * * @param[in] key Key value. * @param[in] iv IV value. Length = 8 bytes. NULL = use default_iv. * @param[in] in Plaintext as n 64-bit blocks, n >= 2. * @param[in] inlen Length of in. * @param[out] out Ciphertext. Minimal buffer length = (inlen + 8) bytes. * Input and output buffers can overlap if block function * supports that. * @param[in] block Block processing function. * @return 0 if inlen does not consist of n 64-bit blocks, n >= 2. * or if inlen > CRYPTO128_WRAP_MAX. * Output length if wrapping succeeded. */ size_t CRYPTO_128_wrap(void *key, const unsigned char *iv, unsigned char *out, const unsigned char *in, size_t inlen, block128_f block) { unsigned char *A, B[16], *R; size_t i, j, t; if ((inlen & 0x7) || (inlen < 16) || (inlen > CRYPTO128_WRAP_MAX)) return 0; A = B; t = 1; memmove(out + 8, in, inlen); if (!iv) iv = default_iv; memcpy(A, iv, 8); for (j = 0; j < 6; j++) { R = out + 8; for (i = 0; i < inlen; i += 8, t++, R += 8) { memcpy(B + 8, R, 8); block(B, B, key); A[7] ^= (unsigned char)(t & 0xff); if (t > 0xff) { A[6] ^= (unsigned char)((t >> 8) & 0xff); A[5] ^= (unsigned char)((t >> 16) & 0xff); A[4] ^= (unsigned char)((t >> 24) & 0xff); } memcpy(R, B + 8, 8); } } memcpy(out, A, 8); return inlen + 8; } /** Unwrapping according to RFC 3394 section 2.2.2 steps 1-2. * The IV check (step 3) is responsibility of the caller. * * @param[in] key Key value. * @param[out] iv Unchecked IV value. Minimal buffer length = 8 bytes. * @param[out] out Plaintext without IV. * Minimal buffer length = (inlen - 8) bytes. * Input and output buffers can overlap if block function * supports that. * @param[in] in Ciphertext as n 64-bit blocks. * @param[in] inlen Length of in. * @param[in] block Block processing function. * @return 0 if inlen is out of range [24, CRYPTO128_WRAP_MAX] * or if inlen is not a multiple of 8. * Output length otherwise. */ static size_t crypto_128_unwrap_raw(void *key, unsigned char *iv, unsigned char *out, const unsigned char *in, size_t inlen, block128_f block) { unsigned char *A, B[16], *R; size_t i, j, t; inlen -= 8; if ((inlen & 0x7) || (inlen < 16) || (inlen > CRYPTO128_WRAP_MAX)) return 0; A = B; t = 6 * (inlen >> 3); memcpy(A, in, 8); memmove(out, in + 8, inlen); for (j = 0; j < 6; j++) { R = out + inlen - 8; for (i = 0; i < inlen; i += 8, t--, R -= 8) { A[7] ^= (unsigned char)(t & 0xff); if (t > 0xff) { A[6] ^= (unsigned char)((t >> 8) & 0xff); A[5] ^= (unsigned char)((t >> 16) & 0xff); A[4] ^= (unsigned char)((t >> 24) & 0xff); } memcpy(B + 8, R, 8); block(B, B, key); memcpy(R, B + 8, 8); } } memcpy(iv, A, 8); return inlen; } /** Unwrapping according to RFC 3394 section 2.2.2, including the IV check. * The first block of plaintext has to match the supplied IV, otherwise an * error is returned. * * @param[in] key Key value. * @param[out] iv IV value to match against. Length = 8 bytes. * NULL = use default_iv. * @param[out] out Plaintext without IV. * Minimal buffer length = (inlen - 8) bytes. * Input and output buffers can overlap if block function * supports that. * @param[in] in Ciphertext as n 64-bit blocks. * @param[in] inlen Length of in. * @param[in] block Block processing function. * @return 0 if inlen is out of range [24, CRYPTO128_WRAP_MAX] * or if inlen is not a multiple of 8 * or if IV doesn't match expected value. * Output length otherwise. */ size_t CRYPTO_128_unwrap(void *key, const unsigned char *iv, unsigned char *out, const unsigned char *in, size_t inlen, block128_f block) { size_t ret; unsigned char got_iv[8]; ret = crypto_128_unwrap_raw(key, got_iv, out, in, inlen, block); if (ret == 0) return 0; if (!iv) iv = default_iv; if (CRYPTO_memcmp(got_iv, iv, 8)) { OPENSSL_cleanse(out, ret); return 0; } return ret; } /** Wrapping according to RFC 5649 section 4.1. * * @param[in] key Key value. * @param[in] icv (Non-standard) IV, 4 bytes. NULL = use default_aiv. * @param[out] out Ciphertext. Minimal buffer length = (inlen + 15) bytes. * Input and output buffers can overlap if block function * supports that. * @param[in] in Plaintext as n 64-bit blocks, n >= 2. * @param[in] inlen Length of in. * @param[in] block Block processing function. * @return 0 if inlen is out of range [1, CRYPTO128_WRAP_MAX]. * Output length if wrapping succeeded. */ size_t CRYPTO_128_wrap_pad(void *key, const unsigned char *icv, unsigned char *out, const unsigned char *in, size_t inlen, block128_f block) { /* n: number of 64-bit blocks in the padded key data * * If length of plain text is not a multiple of 8, pad the plain text octet * string on the right with octets of zeros, where final length is the * smallest multiple of 8 that is greater than length of plain text. * If length of plain text is a multiple of 8, then there is no padding. */ const size_t blocks_padded = (inlen + 7) / 8; /* CEILING(m/8) */ const size_t padded_len = blocks_padded * 8; const size_t padding_len = padded_len - inlen; /* RFC 5649 section 3: Alternative Initial Value */ unsigned char aiv[8]; int ret; /* Section 1: use 32-bit fixed field for plaintext octet length */ if (inlen == 0 || inlen >= CRYPTO128_WRAP_MAX) return 0; /* Section 3: Alternative Initial Value */ if (!icv) memcpy(aiv, default_aiv, 4); else memcpy(aiv, icv, 4); /* Standard doesn't mention this. */ aiv[4] = (inlen >> 24) & 0xFF; aiv[5] = (inlen >> 16) & 0xFF; aiv[6] = (inlen >> 8) & 0xFF; aiv[7] = inlen & 0xFF; if (padded_len == 8) { /* * Section 4.1 - special case in step 2: If the padded plaintext * contains exactly eight octets, then prepend the AIV and encrypt * the resulting 128-bit block using AES in ECB mode. */ memmove(out + 8, in, inlen); memcpy(out, aiv, 8); memset(out + 8 + inlen, 0, padding_len); block(out, out, key); ret = 16; /* AIV + padded input */ } else { memmove(out, in, inlen); memset(out + inlen, 0, padding_len); /* Section 4.1 step 1 */ ret = CRYPTO_128_wrap(key, aiv, out, out, padded_len, block); } return ret; } /** Unwrapping according to RFC 5649 section 4.2. * * @param[in] key Key value. * @param[in] icv (Non-standard) IV, 4 bytes. NULL = use default_aiv. * @param[out] out Plaintext. Minimal buffer length = (inlen - 8) bytes. * Input and output buffers can overlap if block function * supports that. * @param[in] in Ciphertext as n 64-bit blocks. * @param[in] inlen Length of in. * @param[in] block Block processing function. * @return 0 if inlen is out of range [16, CRYPTO128_WRAP_MAX], * or if inlen is not a multiple of 8 * or if IV and message length indicator doesn't match. * Output length if unwrapping succeeded and IV matches. */ size_t CRYPTO_128_unwrap_pad(void *key, const unsigned char *icv, unsigned char *out, const unsigned char *in, size_t inlen, block128_f block) { /* n: number of 64-bit blocks in the padded key data */ size_t n = inlen / 8 - 1; size_t padded_len; size_t padding_len; size_t ptext_len; /* RFC 5649 section 3: Alternative Initial Value */ unsigned char aiv[8]; static unsigned char zeros[8] = { 0x0 }; size_t ret; /* Section 4.2: Ciphertext length has to be (n+1) 64-bit blocks. */ if ((inlen & 0x7) != 0 || inlen < 16 || inlen >= CRYPTO128_WRAP_MAX) return 0; if (inlen == 16) { /* * Section 4.2 - special case in step 1: When n=1, the ciphertext * contains exactly two 64-bit blocks and they are decrypted as a * single AES block using AES in ECB mode: AIV | P[1] = DEC(K, C[0] | * C[1]) */ unsigned char buff[16]; block(in, buff, key); memcpy(aiv, buff, 8); /* Remove AIV */ memcpy(out, buff + 8, 8); padded_len = 8; OPENSSL_cleanse(buff, inlen); } else { padded_len = inlen - 8; ret = crypto_128_unwrap_raw(key, aiv, out, in, inlen, block); if (padded_len != ret) { OPENSSL_cleanse(out, inlen); return 0; } } /* * Section 3: AIV checks: Check that MSB(32,A) = A65959A6. Optionally a * user-supplied value can be used (even if standard doesn't mention * this). */ if ((!icv && CRYPTO_memcmp(aiv, default_aiv, 4)) || (icv && CRYPTO_memcmp(aiv, icv, 4))) { OPENSSL_cleanse(out, inlen); return 0; } /* * Check that 8*(n-1) < LSB(32,AIV) <= 8*n. If so, let ptext_len = * LSB(32,AIV). */ ptext_len = ((unsigned int)aiv[4] << 24) | ((unsigned int)aiv[5] << 16) | ((unsigned int)aiv[6] << 8) | (unsigned int)aiv[7]; if (8 * (n - 1) >= ptext_len || ptext_len > 8 * n) { OPENSSL_cleanse(out, inlen); return 0; } /* * Check that the rightmost padding_len octets of the output data are * zero. */ padding_len = padded_len - ptext_len; if (CRYPTO_memcmp(out + ptext_len, zeros, padding_len) != 0) { OPENSSL_cleanse(out, inlen); return 0; } /* Section 4.2 step 3: Remove padding */ return ptext_len; }
11,908
34.870482
79
c
openssl
openssl-master/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; }
4,570
27.216049
74
c
openssl
openssl-master/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; }
5,551
26.76
78
c
openssl
openssl-master/crypto/objects/o_names.c
/* * Copyright 1998-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 <stdlib.h> #include <string.h> #include <openssl/err.h> #include <openssl/lhash.h> #include <openssl/objects.h> #include <openssl/safestack.h> #include <openssl/e_os2.h> #include "internal/thread_once.h" #include "crypto/lhash.h" #include "obj_local.h" #include "internal/e_os.h" /* * I use the ex_data stuff to manage the identifiers for the obj_name_types * that applications may define. I only really use the free function field. */ static LHASH_OF(OBJ_NAME) *names_lh = NULL; static int names_type_num = OBJ_NAME_TYPE_NUM; static CRYPTO_RWLOCK *obj_lock = NULL; struct name_funcs_st { unsigned long (*hash_func) (const char *name); int (*cmp_func) (const char *a, const char *b); void (*free_func) (const char *, int, const char *); }; static STACK_OF(NAME_FUNCS) *name_funcs_stack; /* * The LHASH callbacks now use the raw "void *" prototypes and do * per-variable casting in the functions. This prevents function pointer * casting without the need for macro-generated wrapper functions. */ static unsigned long obj_name_hash(const OBJ_NAME *a); static int obj_name_cmp(const OBJ_NAME *a, const OBJ_NAME *b); static CRYPTO_ONCE init = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(o_names_init) { names_lh = NULL; obj_lock = CRYPTO_THREAD_lock_new(); if (obj_lock != NULL) names_lh = lh_OBJ_NAME_new(obj_name_hash, obj_name_cmp); if (names_lh == NULL) { CRYPTO_THREAD_lock_free(obj_lock); obj_lock = NULL; } return names_lh != NULL && obj_lock != NULL; } int OBJ_NAME_init(void) { return RUN_ONCE(&init, o_names_init); } int OBJ_NAME_new_index(unsigned long (*hash_func) (const char *), int (*cmp_func) (const char *, const char *), void (*free_func) (const char *, int, const char *)) { int ret = 0, i, push; NAME_FUNCS *name_funcs; if (!OBJ_NAME_init()) return 0; if (!CRYPTO_THREAD_write_lock(obj_lock)) return 0; if (name_funcs_stack == NULL) name_funcs_stack = sk_NAME_FUNCS_new_null(); if (name_funcs_stack == NULL) { /* ERROR */ goto out; } ret = names_type_num; names_type_num++; for (i = sk_NAME_FUNCS_num(name_funcs_stack); i < names_type_num; i++) { name_funcs = OPENSSL_zalloc(sizeof(*name_funcs)); if (name_funcs == NULL) { ret = 0; goto out; } name_funcs->hash_func = ossl_lh_strcasehash; name_funcs->cmp_func = OPENSSL_strcasecmp; push = sk_NAME_FUNCS_push(name_funcs_stack, name_funcs); if (!push) { ERR_raise(ERR_LIB_OBJ, ERR_R_CRYPTO_LIB); OPENSSL_free(name_funcs); ret = 0; goto out; } } name_funcs = sk_NAME_FUNCS_value(name_funcs_stack, ret); if (hash_func != NULL) name_funcs->hash_func = hash_func; if (cmp_func != NULL) name_funcs->cmp_func = cmp_func; if (free_func != NULL) name_funcs->free_func = free_func; out: CRYPTO_THREAD_unlock(obj_lock); return ret; } static int obj_name_cmp(const OBJ_NAME *a, const OBJ_NAME *b) { int ret; ret = a->type - b->type; if (ret == 0) { if ((name_funcs_stack != NULL) && (sk_NAME_FUNCS_num(name_funcs_stack) > a->type)) { ret = sk_NAME_FUNCS_value(name_funcs_stack, a->type)->cmp_func(a->name, b->name); } else ret = OPENSSL_strcasecmp(a->name, b->name); } return ret; } static unsigned long obj_name_hash(const OBJ_NAME *a) { unsigned long ret; if ((name_funcs_stack != NULL) && (sk_NAME_FUNCS_num(name_funcs_stack) > a->type)) { ret = sk_NAME_FUNCS_value(name_funcs_stack, a->type)->hash_func(a->name); } else { ret = ossl_lh_strcasehash(a->name); } ret ^= a->type; return ret; } const char *OBJ_NAME_get(const char *name, int type) { OBJ_NAME on, *ret; int num = 0, alias; const char *value = NULL; if (name == NULL) return NULL; if (!OBJ_NAME_init()) return NULL; if (!CRYPTO_THREAD_read_lock(obj_lock)) return NULL; alias = type & OBJ_NAME_ALIAS; type &= ~OBJ_NAME_ALIAS; on.name = name; on.type = type; for (;;) { ret = lh_OBJ_NAME_retrieve(names_lh, &on); if (ret == NULL) break; if ((ret->alias) && !alias) { if (++num > 10) break; on.name = ret->data; } else { value = ret->data; break; } } CRYPTO_THREAD_unlock(obj_lock); return value; } int OBJ_NAME_add(const char *name, int type, const char *data) { OBJ_NAME *onp, *ret; int alias, ok = 0; if (!OBJ_NAME_init()) return 0; alias = type & OBJ_NAME_ALIAS; type &= ~OBJ_NAME_ALIAS; onp = OPENSSL_malloc(sizeof(*onp)); if (onp == NULL) return 0; onp->name = name; onp->alias = alias; onp->type = type; onp->data = data; if (!CRYPTO_THREAD_write_lock(obj_lock)) { OPENSSL_free(onp); return 0; } ret = lh_OBJ_NAME_insert(names_lh, onp); if (ret != NULL) { /* free things */ if ((name_funcs_stack != NULL) && (sk_NAME_FUNCS_num(name_funcs_stack) > ret->type)) { /* * XXX: I'm not sure I understand why the free function should * get three arguments... -- Richard Levitte */ sk_NAME_FUNCS_value(name_funcs_stack, ret->type)->free_func(ret->name, ret->type, ret->data); } OPENSSL_free(ret); } else { if (lh_OBJ_NAME_error(names_lh)) { /* ERROR */ OPENSSL_free(onp); goto unlock; } } ok = 1; unlock: CRYPTO_THREAD_unlock(obj_lock); return ok; } int OBJ_NAME_remove(const char *name, int type) { OBJ_NAME on, *ret; int ok = 0; if (!OBJ_NAME_init()) return 0; if (!CRYPTO_THREAD_write_lock(obj_lock)) return 0; type &= ~OBJ_NAME_ALIAS; on.name = name; on.type = type; ret = lh_OBJ_NAME_delete(names_lh, &on); if (ret != NULL) { /* free things */ if ((name_funcs_stack != NULL) && (sk_NAME_FUNCS_num(name_funcs_stack) > ret->type)) { /* * XXX: I'm not sure I understand why the free function should * get three arguments... -- Richard Levitte */ sk_NAME_FUNCS_value(name_funcs_stack, ret->type)->free_func(ret->name, ret->type, ret->data); } OPENSSL_free(ret); ok = 1; } CRYPTO_THREAD_unlock(obj_lock); return ok; } typedef struct { int type; void (*fn) (const OBJ_NAME *, void *arg); void *arg; } OBJ_DOALL; static void do_all_fn(const OBJ_NAME *name, OBJ_DOALL *d) { if (name->type == d->type) d->fn(name, d->arg); } IMPLEMENT_LHASH_DOALL_ARG_CONST(OBJ_NAME, OBJ_DOALL); void OBJ_NAME_do_all(int type, void (*fn) (const OBJ_NAME *, void *arg), void *arg) { OBJ_DOALL d; d.type = type; d.fn = fn; d.arg = arg; lh_OBJ_NAME_doall_OBJ_DOALL(names_lh, do_all_fn, &d); } struct doall_sorted { int type; int n; const OBJ_NAME **names; }; static void do_all_sorted_fn(const OBJ_NAME *name, void *d_) { struct doall_sorted *d = d_; if (name->type != d->type) return; d->names[d->n++] = name; } static int do_all_sorted_cmp(const void *n1_, const void *n2_) { const OBJ_NAME *const *n1 = n1_; const OBJ_NAME *const *n2 = n2_; return strcmp((*n1)->name, (*n2)->name); } void OBJ_NAME_do_all_sorted(int type, void (*fn) (const OBJ_NAME *, void *arg), void *arg) { struct doall_sorted d; int n; d.type = type; d.names = OPENSSL_malloc(sizeof(*d.names) * lh_OBJ_NAME_num_items(names_lh)); /* Really should return an error if !d.names...but its a void function! */ if (d.names != NULL) { d.n = 0; OBJ_NAME_do_all(type, do_all_sorted_fn, &d); qsort((void *)d.names, d.n, sizeof(*d.names), do_all_sorted_cmp); for (n = 0; n < d.n; ++n) fn(d.names[n], arg); OPENSSL_free((void *)d.names); } } static int free_type; static void names_lh_free_doall(OBJ_NAME *onp) { if (onp == NULL) return; if (free_type < 0 || free_type == onp->type) OBJ_NAME_remove(onp->name, onp->type); } static void name_funcs_free(NAME_FUNCS *ptr) { OPENSSL_free(ptr); } void OBJ_NAME_cleanup(int type) { unsigned long down_load; if (names_lh == NULL) return; free_type = type; down_load = lh_OBJ_NAME_get_down_load(names_lh); lh_OBJ_NAME_set_down_load(names_lh, 0); lh_OBJ_NAME_doall(names_lh, names_lh_free_doall); if (type < 0) { lh_OBJ_NAME_free(names_lh); sk_NAME_FUNCS_pop_free(name_funcs_stack, name_funcs_free); CRYPTO_THREAD_lock_free(obj_lock); names_lh = NULL; name_funcs_stack = NULL; obj_lock = NULL; } else lh_OBJ_NAME_set_down_load(names_lh, down_load); }
9,857
24.341902
78
c
openssl
openssl-master/crypto/objects/obj_compat.h
/* * 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 */ #ifndef OPENSSL_NO_DEPRECATED_3_0 #define SN_id_tc26_cipher_gostr3412_2015_magma_ctracpkm SN_magma_ctr_acpkm #define NID_id_tc26_cipher_gostr3412_2015_magma_ctracpkm NID_magma_ctr_acpkm #define OBJ_id_tc26_cipher_gostr3412_2015_magma_ctracpkm OBJ_magma_ctr_acpkm #define SN_id_tc26_cipher_gostr3412_2015_magma_ctracpkm_omac SN_magma_ctr_acpkm_omac #define NID_id_tc26_cipher_gostr3412_2015_magma_ctracpkm_omac NID_magma_ctr_acpkm_omac #define OBJ_id_tc26_cipher_gostr3412_2015_magma_ctracpkm_omac OBJ_magma_ctr_acpkm_omac #define SN_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm SN_kuznyechik_ctr_acpkm #define NID_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm NID_kuznyechik_ctr_acpkm #define OBJ_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm OBJ_kuznyechik_ctr_acpkm #define SN_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac SN_kuznyechik_ctr_acpkm_omac #define NID_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac NID_kuznyechik_ctr_acpkm_omac #define OBJ_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac OBJ_kuznyechik_ctr_acpkm_omac #define SN_id_tc26_wrap_gostr3412_2015_magma_kexp15 SN_magma_kexp15 #define NID_id_tc26_wrap_gostr3412_2015_magma_kexp15 NID_magma_kexp15 #define OBJ_id_tc26_wrap_gostr3412_2015_magma_kexp15 OBJ_magma_kexp15 #define SN_id_tc26_wrap_gostr3412_2015_kuznyechik_kexp15 SN_kuznyechik_kexp15 #define NID_id_tc26_wrap_gostr3412_2015_kuznyechik_kexp15 NID_kuznyechik_kexp15 #define OBJ_id_tc26_wrap_gostr3412_2015_kuznyechik_kexp15 OBJ_kuznyechik_kexp15 #define SN_grasshopper_ecb SN_kuznyechik_ecb #define NID_grasshopper_ecb NID_kuznyechik_ecb #define SN_grasshopper_ctr SN_kuznyechik_ctr #define NID_grasshopper_ctr NID_kuznyechik_ctr #define SN_grasshopper_ofb SN_kuznyechik_ofb #define NID_grasshopper_ofb NID_kuznyechik_ofb #define SN_grasshopper_cbc SN_kuznyechik_cbc #define NID_grasshopper_cbc NID_kuznyechik_cbc #define SN_grasshopper_cfb SN_kuznyechik_cfb #define NID_grasshopper_cfb NID_kuznyechik_cfb #define SN_grasshopper_mac SN_kuznyechik_mac #define NID_grasshopper_mac NID_kuznyechik_mac #endif /* OPENSSL_NO_DEPRECATED_3_0 */
2,828
50.436364
109
h
openssl
openssl-master/crypto/objects/obj_dat.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 "crypto/ctype.h" #include <limits.h> #include "internal/cryptlib.h" #include "internal/thread_once.h" #include "internal/tsan_assist.h" #include <openssl/lhash.h> #include <openssl/asn1.h> #include "crypto/objects.h" #include <openssl/bn.h> #include "crypto/asn1.h" #include "obj_local.h" /* obj_dat.h is generated from objects.txt and obj_mac.{num,h} by obj_dat.pl */ #include "obj_dat.h" DECLARE_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, sn); DECLARE_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, ln); DECLARE_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, obj); #define ADDED_DATA 0 #define ADDED_SNAME 1 #define ADDED_LNAME 2 #define ADDED_NID 3 struct added_obj_st { int type; ASN1_OBJECT *obj; }; static LHASH_OF(ADDED_OBJ) *added = NULL; static CRYPTO_RWLOCK *ossl_obj_lock = NULL; #ifdef TSAN_REQUIRES_LOCKING static CRYPTO_RWLOCK *ossl_obj_nid_lock = NULL; #endif static CRYPTO_ONCE ossl_obj_lock_init = CRYPTO_ONCE_STATIC_INIT; static ossl_inline void objs_free_locks(void) { CRYPTO_THREAD_lock_free(ossl_obj_lock); ossl_obj_lock = NULL; #ifdef TSAN_REQUIRES_LOCKING CRYPTO_THREAD_lock_free(ossl_obj_nid_lock); ossl_obj_nid_lock = NULL; #endif } DEFINE_RUN_ONCE_STATIC(obj_lock_initialise) { ossl_obj_lock = CRYPTO_THREAD_lock_new(); if (ossl_obj_lock == NULL) return 0; #ifdef TSAN_REQUIRES_LOCKING ossl_obj_nid_lock = CRYPTO_THREAD_lock_new(); if (ossl_obj_nid_lock == NULL) { objs_free_locks(); return 0; } #endif return 1; } static ossl_inline int ossl_init_added_lock(void) { /* Make sure we've loaded config before checking for any "added" objects */ OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL); return RUN_ONCE(&ossl_obj_lock_init, obj_lock_initialise); } static ossl_inline int ossl_obj_write_lock(int lock) { if (!lock) return 1; if (!ossl_init_added_lock()) return 0; return CRYPTO_THREAD_write_lock(ossl_obj_lock); } static ossl_inline int ossl_obj_read_lock(int lock) { if (!lock) return 1; if (!ossl_init_added_lock()) return 0; return CRYPTO_THREAD_read_lock(ossl_obj_lock); } static ossl_inline void ossl_obj_unlock(int lock) { if (lock) CRYPTO_THREAD_unlock(ossl_obj_lock); } static int sn_cmp(const ASN1_OBJECT *const *a, const unsigned int *b) { return strcmp((*a)->sn, nid_objs[*b].sn); } IMPLEMENT_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, sn); static int ln_cmp(const ASN1_OBJECT *const *a, const unsigned int *b) { return strcmp((*a)->ln, nid_objs[*b].ln); } IMPLEMENT_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, ln); static unsigned long added_obj_hash(const ADDED_OBJ *ca) { const ASN1_OBJECT *a; int i; unsigned long ret = 0; unsigned char *p; a = ca->obj; switch (ca->type) { case ADDED_DATA: ret = a->length << 20L; p = (unsigned char *)a->data; for (i = 0; i < a->length; i++) ret ^= p[i] << ((i * 3) % 24); break; case ADDED_SNAME: ret = OPENSSL_LH_strhash(a->sn); break; case ADDED_LNAME: ret = OPENSSL_LH_strhash(a->ln); break; case ADDED_NID: ret = a->nid; break; default: /* abort(); */ return 0; } ret &= 0x3fffffffL; ret |= ((unsigned long)ca->type) << 30L; return ret; } static int added_obj_cmp(const ADDED_OBJ *ca, const ADDED_OBJ *cb) { ASN1_OBJECT *a, *b; int i; i = ca->type - cb->type; if (i) return i; a = ca->obj; b = cb->obj; switch (ca->type) { case ADDED_DATA: i = (a->length - b->length); if (i) return i; return memcmp(a->data, b->data, (size_t)a->length); case ADDED_SNAME: if (a->sn == NULL) return -1; else if (b->sn == NULL) return 1; else return strcmp(a->sn, b->sn); case ADDED_LNAME: if (a->ln == NULL) return -1; else if (b->ln == NULL) return 1; else return strcmp(a->ln, b->ln); case ADDED_NID: return a->nid - b->nid; default: /* abort(); */ return 0; } } static void cleanup1_doall(ADDED_OBJ *a) { a->obj->nid = 0; a->obj->flags |= ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS | ASN1_OBJECT_FLAG_DYNAMIC_DATA; } static void cleanup2_doall(ADDED_OBJ *a) { a->obj->nid++; } static void cleanup3_doall(ADDED_OBJ *a) { if (--a->obj->nid == 0) ASN1_OBJECT_free(a->obj); OPENSSL_free(a); } void ossl_obj_cleanup_int(void) { if (added != NULL) { lh_ADDED_OBJ_set_down_load(added, 0); lh_ADDED_OBJ_doall(added, cleanup1_doall); /* zero counters */ lh_ADDED_OBJ_doall(added, cleanup2_doall); /* set counters */ lh_ADDED_OBJ_doall(added, cleanup3_doall); /* free objects */ lh_ADDED_OBJ_free(added); added = NULL; } objs_free_locks(); } int OBJ_new_nid(int num) { static TSAN_QUALIFIER int new_nid = NUM_NID; #ifdef TSAN_REQUIRES_LOCKING int i; if (!CRYPTO_THREAD_write_lock(ossl_obj_nid_lock)) { ERR_raise(ERR_LIB_OBJ, ERR_R_UNABLE_TO_GET_WRITE_LOCK); return NID_undef; } i = new_nid; new_nid += num; CRYPTO_THREAD_unlock(ossl_obj_nid_lock); return i; #else return tsan_add(&new_nid, num); #endif } static int ossl_obj_add_object(const ASN1_OBJECT *obj, int lock) { ASN1_OBJECT *o = NULL; ADDED_OBJ *ao[4] = { NULL, NULL, NULL, NULL }, *aop; int i; if ((o = OBJ_dup(obj)) == NULL) return NID_undef; if ((ao[ADDED_NID] = OPENSSL_malloc(sizeof(*ao[0]))) == NULL || (o->length != 0 && obj->data != NULL && (ao[ADDED_DATA] = OPENSSL_malloc(sizeof(*ao[0]))) == NULL) || (o->sn != NULL && (ao[ADDED_SNAME] = OPENSSL_malloc(sizeof(*ao[0]))) == NULL) || (o->ln != NULL && (ao[ADDED_LNAME] = OPENSSL_malloc(sizeof(*ao[0]))) == NULL)) goto err2; if (!ossl_obj_write_lock(lock)) { ERR_raise(ERR_LIB_OBJ, ERR_R_UNABLE_TO_GET_WRITE_LOCK); goto err2; } if (added == NULL) { added = lh_ADDED_OBJ_new(added_obj_hash, added_obj_cmp); if (added == NULL) { ERR_raise(ERR_LIB_OBJ, ERR_R_CRYPTO_LIB); goto err; } } for (i = ADDED_DATA; i <= ADDED_NID; i++) { if (ao[i] != NULL) { ao[i]->type = i; ao[i]->obj = o; aop = lh_ADDED_OBJ_insert(added, ao[i]); /* memory leak, but should not normally matter */ OPENSSL_free(aop); } } o->flags &= ~(ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS | ASN1_OBJECT_FLAG_DYNAMIC_DATA); ossl_obj_unlock(lock); return o->nid; err: ossl_obj_unlock(lock); err2: for (i = ADDED_DATA; i <= ADDED_NID; i++) OPENSSL_free(ao[i]); ASN1_OBJECT_free(o); return NID_undef; } ASN1_OBJECT *OBJ_nid2obj(int n) { ADDED_OBJ ad, *adp = NULL; ASN1_OBJECT ob; if (n == NID_undef || (n > 0 && n < NUM_NID && nid_objs[n].nid != NID_undef)) return (ASN1_OBJECT *)&(nid_objs[n]); ad.type = ADDED_NID; ad.obj = &ob; ob.nid = n; if (!ossl_obj_read_lock(1)) { ERR_raise(ERR_LIB_OBJ, ERR_R_UNABLE_TO_GET_READ_LOCK); return NULL; } if (added != NULL) adp = lh_ADDED_OBJ_retrieve(added, &ad); ossl_obj_unlock(1); if (adp != NULL) return adp->obj; ERR_raise(ERR_LIB_OBJ, OBJ_R_UNKNOWN_NID); return NULL; } const char *OBJ_nid2sn(int n) { ASN1_OBJECT *ob = OBJ_nid2obj(n); return ob == NULL ? NULL : ob->sn; } const char *OBJ_nid2ln(int n) { ASN1_OBJECT *ob = OBJ_nid2obj(n); return ob == NULL ? NULL : ob->ln; } static int obj_cmp(const ASN1_OBJECT *const *ap, const unsigned int *bp) { int j; const ASN1_OBJECT *a = *ap; const ASN1_OBJECT *b = &nid_objs[*bp]; j = (a->length - b->length); if (j) return j; if (a->length == 0) return 0; return memcmp(a->data, b->data, a->length); } IMPLEMENT_OBJ_BSEARCH_CMP_FN(const ASN1_OBJECT *, unsigned int, obj); static int ossl_obj_obj2nid(const ASN1_OBJECT *a, const int lock) { int nid = NID_undef; const unsigned int *op; ADDED_OBJ ad, *adp; if (a == NULL) return NID_undef; if (a->nid != NID_undef) return a->nid; if (a->length == 0) return NID_undef; op = OBJ_bsearch_obj(&a, obj_objs, NUM_OBJ); if (op != NULL) return nid_objs[*op].nid; if (!ossl_obj_read_lock(lock)) { ERR_raise(ERR_LIB_OBJ, ERR_R_UNABLE_TO_GET_READ_LOCK); return NID_undef; } if (added != NULL) { ad.type = ADDED_DATA; ad.obj = (ASN1_OBJECT *)a; /* casting away const is harmless here */ adp = lh_ADDED_OBJ_retrieve(added, &ad); if (adp != NULL) nid = adp->obj->nid; } ossl_obj_unlock(lock); return nid; } /* * Convert an object name into an ASN1_OBJECT if "noname" is not set then * search for short and long names first. This will convert the "dotted" form * into an object: unlike OBJ_txt2nid it can be used with any objects, not * just registered ones. */ ASN1_OBJECT *OBJ_txt2obj(const char *s, int no_name) { int nid = NID_undef; ASN1_OBJECT *op = NULL; unsigned char *buf; unsigned char *p; const unsigned char *cp; int i, j; if (!no_name) { if ((nid = OBJ_sn2nid(s)) != NID_undef || (nid = OBJ_ln2nid(s)) != NID_undef) { return OBJ_nid2obj(nid); } if (!ossl_isdigit(*s)) { ERR_raise(ERR_LIB_OBJ, OBJ_R_UNKNOWN_OBJECT_NAME); return NULL; } } /* Work out size of content octets */ i = a2d_ASN1_OBJECT(NULL, 0, s, -1); if (i <= 0) return NULL; /* Work out total size */ j = ASN1_object_size(0, i, V_ASN1_OBJECT); if (j < 0) return NULL; if ((buf = OPENSSL_malloc(j)) == NULL) return NULL; p = buf; /* Write out tag+length */ ASN1_put_object(&p, 0, i, V_ASN1_OBJECT, V_ASN1_UNIVERSAL); /* Write out contents */ a2d_ASN1_OBJECT(p, i, s, -1); cp = buf; op = d2i_ASN1_OBJECT(NULL, &cp, j); OPENSSL_free(buf); return op; } int OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name) { int i, n = 0, len, nid, first, use_bn; BIGNUM *bl; unsigned long l; const unsigned char *p; char tbuf[DECIMAL_SIZE(i) + DECIMAL_SIZE(l) + 2]; const char *s; /* Ensure that, at every state, |buf| is NUL-terminated. */ if (buf != NULL && buf_len > 0) buf[0] = '\0'; if (a == NULL || a->data == NULL) return 0; if (!no_name && (nid = OBJ_obj2nid(a)) != NID_undef) { s = OBJ_nid2ln(nid); if (s == NULL) s = OBJ_nid2sn(nid); if (s != NULL) { if (buf != NULL) OPENSSL_strlcpy(buf, s, buf_len); return (int)strlen(s); } } len = a->length; p = a->data; first = 1; bl = NULL; /* * RFC 2578 (STD 58) says this about OBJECT IDENTIFIERs: * * > 3.5. OBJECT IDENTIFIER values * > * > An OBJECT IDENTIFIER value is an ordered list of non-negative * > numbers. For the SMIv2, each number in the list is referred to as a * > sub-identifier, there are at most 128 sub-identifiers in a value, * > and each sub-identifier has a maximum value of 2^32-1 (4294967295 * > decimal). * * So a legitimate OID according to this RFC is at most (32 * 128 / 7), * i.e. 586 bytes long. * * Ref: https://datatracker.ietf.org/doc/html/rfc2578#section-3.5 */ if (len > 586) goto err; while (len > 0) { l = 0; use_bn = 0; for (;;) { unsigned char c = *p++; len--; if (len == 0 && (c & 0x80) != 0) goto err; if (use_bn) { if (!BN_add_word(bl, c & 0x7f)) goto err; } else { l |= c & 0x7f; } if ((c & 0x80) == 0) break; if (!use_bn && l > (ULONG_MAX >> 7L)) { if (bl == NULL && (bl = BN_new()) == NULL) goto err; if (!BN_set_word(bl, l)) goto err; use_bn = 1; } if (use_bn) { if (!BN_lshift(bl, bl, 7)) goto err; } else { l <<= 7L; } } if (first) { first = 0; if (l >= 80) { i = 2; if (use_bn) { if (!BN_sub_word(bl, 80)) goto err; } else { l -= 80; } } else { i = (int)(l / 40); l -= (long)(i * 40); } if (buf != NULL && buf_len > 1) { *buf++ = i + '0'; *buf = '\0'; buf_len--; } n++; } if (use_bn) { char *bndec; bndec = BN_bn2dec(bl); if (!bndec) goto err; i = strlen(bndec); if (buf != NULL) { if (buf_len > 1) { *buf++ = '.'; *buf = '\0'; buf_len--; } OPENSSL_strlcpy(buf, bndec, buf_len); if (i > buf_len) { buf += buf_len; buf_len = 0; } else { buf += i; buf_len -= i; } } n++; n += i; OPENSSL_free(bndec); } else { BIO_snprintf(tbuf, sizeof(tbuf), ".%lu", l); i = strlen(tbuf); if (buf && buf_len > 0) { OPENSSL_strlcpy(buf, tbuf, buf_len); if (i > buf_len) { buf += buf_len; buf_len = 0; } else { buf += i; buf_len -= i; } } n += i; l = 0; } } BN_free(bl); return n; err: BN_free(bl); return -1; } int OBJ_txt2nid(const char *s) { ASN1_OBJECT *obj = OBJ_txt2obj(s, 0); int nid = NID_undef; if (obj != NULL) { nid = OBJ_obj2nid(obj); ASN1_OBJECT_free(obj); } return nid; } int OBJ_ln2nid(const char *s) { ASN1_OBJECT o; const ASN1_OBJECT *oo = &o; ADDED_OBJ ad, *adp; const unsigned int *op; int nid = NID_undef; o.ln = s; op = OBJ_bsearch_ln(&oo, ln_objs, NUM_LN); if (op != NULL) return nid_objs[*op].nid; if (!ossl_obj_read_lock(1)) { ERR_raise(ERR_LIB_OBJ, ERR_R_UNABLE_TO_GET_READ_LOCK); return NID_undef; } if (added != NULL) { ad.type = ADDED_LNAME; ad.obj = &o; adp = lh_ADDED_OBJ_retrieve(added, &ad); if (adp != NULL) nid = adp->obj->nid; } ossl_obj_unlock(1); return nid; } int OBJ_sn2nid(const char *s) { ASN1_OBJECT o; const ASN1_OBJECT *oo = &o; ADDED_OBJ ad, *adp; const unsigned int *op; int nid = NID_undef; o.sn = s; op = OBJ_bsearch_sn(&oo, sn_objs, NUM_SN); if (op != NULL) return nid_objs[*op].nid; if (!ossl_obj_read_lock(1)) { ERR_raise(ERR_LIB_OBJ, ERR_R_UNABLE_TO_GET_READ_LOCK); return NID_undef; } if (added != NULL) { ad.type = ADDED_SNAME; ad.obj = &o; adp = lh_ADDED_OBJ_retrieve(added, &ad); if (adp != NULL) nid = adp->obj->nid; } ossl_obj_unlock(1); return nid; } const void *OBJ_bsearch_(const void *key, const void *base, int num, int size, int (*cmp) (const void *, const void *)) { return OBJ_bsearch_ex_(key, base, num, size, cmp, 0); } const void *OBJ_bsearch_ex_(const void *key, const void *base, int num, int size, int (*cmp) (const void *, const void *), int flags) { const char *p = ossl_bsearch(key, base, num, size, cmp, flags); #ifdef CHARSET_EBCDIC /* * THIS IS A KLUDGE - Because the *_obj is sorted in ASCII order, and I * don't have perl (yet), we revert to a *LINEAR* search when the object * wasn't found in the binary search. */ if (p == NULL) { const char *base_ = base; int l, h, i = 0, c = 0; for (i = 0; i < num; ++i) { p = &(base_[i * size]); c = (*cmp) (key, p); if (c == 0 || (c < 0 && (flags & OBJ_BSEARCH_VALUE_ON_NOMATCH))) return p; } } #endif return p; } /* * Parse a BIO sink to create some extra oid's objects. * Line format:<OID:isdigit or '.']><isspace><SN><isspace><LN> */ int OBJ_create_objects(BIO *in) { char buf[512]; int i, num = 0; char *o, *s, *l = NULL; for (;;) { s = o = NULL; i = BIO_gets(in, buf, 512); if (i <= 0) return num; buf[i - 1] = '\0'; if (!ossl_isalnum(buf[0])) return num; o = s = buf; while (ossl_isdigit(*s) || *s == '.') s++; if (*s != '\0') { *(s++) = '\0'; while (ossl_isspace(*s)) s++; if (*s == '\0') { s = NULL; } else { l = s; while (*l != '\0' && !ossl_isspace(*l)) l++; if (*l != '\0') { *(l++) = '\0'; while (ossl_isspace(*l)) l++; if (*l == '\0') { l = NULL; } } else { l = NULL; } } } else { s = NULL; } if (*o == '\0') return num; if (!OBJ_create(o, s, l)) return num; num++; } } int OBJ_create(const char *oid, const char *sn, const char *ln) { ASN1_OBJECT *tmpoid = NULL; int ok = 0; /* With no arguments at all, nothing can be done */ if (oid == NULL && sn == NULL && ln == NULL) { ERR_raise(ERR_LIB_OBJ, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } /* Check to see if short or long name already present */ if ((sn != NULL && OBJ_sn2nid(sn) != NID_undef) || (ln != NULL && OBJ_ln2nid(ln) != NID_undef)) { ERR_raise(ERR_LIB_OBJ, OBJ_R_OID_EXISTS); return 0; } if (oid != NULL) { /* Convert numerical OID string to an ASN1_OBJECT structure */ tmpoid = OBJ_txt2obj(oid, 1); if (tmpoid == NULL) return 0; } else { /* Create a no-OID ASN1_OBJECT */ tmpoid = ASN1_OBJECT_new(); } if (!ossl_obj_write_lock(1)) { ERR_raise(ERR_LIB_OBJ, ERR_R_UNABLE_TO_GET_WRITE_LOCK); ASN1_OBJECT_free(tmpoid); return 0; } /* If NID is not NID_undef then object already exists */ if (oid != NULL && ossl_obj_obj2nid(tmpoid, 0) != NID_undef) { ERR_raise(ERR_LIB_OBJ, OBJ_R_OID_EXISTS); goto err; } tmpoid->nid = OBJ_new_nid(1); if (tmpoid->nid == NID_undef) goto err; tmpoid->sn = (char *)sn; tmpoid->ln = (char *)ln; ok = ossl_obj_add_object(tmpoid, 0); tmpoid->sn = NULL; tmpoid->ln = NULL; err: ossl_obj_unlock(1); ASN1_OBJECT_free(tmpoid); return ok; } size_t OBJ_length(const ASN1_OBJECT *obj) { if (obj == NULL) return 0; return obj->length; } const unsigned char *OBJ_get0_data(const ASN1_OBJECT *obj) { if (obj == NULL) return NULL; return obj->data; } int OBJ_add_object(const ASN1_OBJECT *obj) { return ossl_obj_add_object(obj, 1); } int OBJ_obj2nid(const ASN1_OBJECT *a) { return ossl_obj_obj2nid(a, 1); }
20,839
24.230024
79
c
openssl
openssl-master/crypto/objects/obj_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/objectserr.h> #include "crypto/objectserr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA OBJ_str_reasons[] = { {ERR_PACK(ERR_LIB_OBJ, 0, OBJ_R_OID_EXISTS), "oid exists"}, {ERR_PACK(ERR_LIB_OBJ, 0, OBJ_R_UNKNOWN_NID), "unknown nid"}, {ERR_PACK(ERR_LIB_OBJ, 0, OBJ_R_UNKNOWN_OBJECT_NAME), "unknown object name"}, {0, NULL} }; #endif int ossl_err_load_OBJ_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(OBJ_str_reasons[0].error) == NULL) ERR_load_strings_const(OBJ_str_reasons); #endif return 1; }
985
27.171429
74
c
openssl
openssl-master/crypto/objects/obj_lib.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/buffer.h> #include "crypto/asn1.h" ASN1_OBJECT *OBJ_dup(const ASN1_OBJECT *o) { ASN1_OBJECT *r; if (o == NULL) return NULL; /* If object isn't dynamic it's an internal OID which is never freed */ if (!(o->flags & ASN1_OBJECT_FLAG_DYNAMIC)) return (ASN1_OBJECT *)o; r = ASN1_OBJECT_new(); if (r == NULL) { ERR_raise(ERR_LIB_OBJ, ERR_R_ASN1_LIB); return NULL; } /* Set dynamic flags so everything gets freed up on error */ r->flags = o->flags | (ASN1_OBJECT_FLAG_DYNAMIC | ASN1_OBJECT_FLAG_DYNAMIC_STRINGS | ASN1_OBJECT_FLAG_DYNAMIC_DATA); if (o->length > 0 && (r->data = OPENSSL_memdup(o->data, o->length)) == NULL) goto err; r->length = o->length; r->nid = o->nid; if (o->ln != NULL && (r->ln = OPENSSL_strdup(o->ln)) == NULL) goto err; if (o->sn != NULL && (r->sn = OPENSSL_strdup(o->sn)) == NULL) goto err; return r; err: ASN1_OBJECT_free(r); return NULL; } int OBJ_cmp(const ASN1_OBJECT *a, const ASN1_OBJECT *b) { int ret; ret = (a->length - b->length); if (ret) return ret; return memcmp(a->data, b->data, a->length); }
1,674
24.769231
80
c
openssl
openssl-master/crypto/objects/obj_local.h
/* * Copyright 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 */ typedef struct name_funcs_st NAME_FUNCS; DEFINE_STACK_OF(NAME_FUNCS) DEFINE_LHASH_OF_EX(OBJ_NAME); typedef struct added_obj_st ADDED_OBJ; DEFINE_LHASH_OF_EX(ADDED_OBJ);
501
32.466667
74
h
openssl
openssl-master/crypto/objects/obj_xref.c
/* * Copyright 2006-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/objects.h> #include "obj_xref.h" #include "internal/nelem.h" #include "internal/thread_once.h" #include <openssl/err.h> static STACK_OF(nid_triple) *sig_app, *sigx_app; static CRYPTO_RWLOCK *sig_lock; static int sig_cmp(const nid_triple *a, const nid_triple *b) { return a->sign_id - b->sign_id; } DECLARE_OBJ_BSEARCH_CMP_FN(nid_triple, nid_triple, sig); IMPLEMENT_OBJ_BSEARCH_CMP_FN(nid_triple, nid_triple, sig); static int sig_sk_cmp(const nid_triple *const *a, const nid_triple *const *b) { return (*a)->sign_id - (*b)->sign_id; } DECLARE_OBJ_BSEARCH_CMP_FN(const nid_triple *, const nid_triple *, sigx); static int sigx_cmp(const nid_triple *const *a, const nid_triple *const *b) { int ret; ret = (*a)->hash_id - (*b)->hash_id; /* The "b" side of the comparison carries the algorithms already * registered. A NID_undef for 'hash_id' there means that the * signature algorithm doesn't need a digest to operate OK. In * such case, any hash_id/digest algorithm on the test side (a), * incl. NID_undef, is acceptable. signature algorithm NID * (pkey_id) must match in any case. */ if ((ret != 0) && ((*b)->hash_id != NID_undef)) return ret; return (*a)->pkey_id - (*b)->pkey_id; } IMPLEMENT_OBJ_BSEARCH_CMP_FN(const nid_triple *, const nid_triple *, sigx); static CRYPTO_ONCE sig_init = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(o_sig_init) { sig_lock = CRYPTO_THREAD_lock_new(); return sig_lock != NULL; } static ossl_inline int obj_sig_init(void) { return RUN_ONCE(&sig_init, o_sig_init); } static int ossl_obj_find_sigid_algs(int signid, int *pdig_nid, int *ppkey_nid, int lock) { nid_triple tmp; const nid_triple *rv; int idx; if (signid == NID_undef) return 0; tmp.sign_id = signid; rv = OBJ_bsearch_sig(&tmp, sigoid_srt, OSSL_NELEM(sigoid_srt)); if (rv == NULL) { if (!obj_sig_init()) return 0; if (lock && !CRYPTO_THREAD_read_lock(sig_lock)) { ERR_raise(ERR_LIB_OBJ, ERR_R_UNABLE_TO_GET_READ_LOCK); return 0; } if (sig_app != NULL) { idx = sk_nid_triple_find(sig_app, &tmp); if (idx >= 0) rv = sk_nid_triple_value(sig_app, idx); } if (lock) CRYPTO_THREAD_unlock(sig_lock); if (rv == NULL) return 0; } if (pdig_nid != NULL) *pdig_nid = rv->hash_id; if (ppkey_nid != NULL) *ppkey_nid = rv->pkey_id; return 1; } int OBJ_find_sigid_algs(int signid, int *pdig_nid, int *ppkey_nid) { return ossl_obj_find_sigid_algs(signid, pdig_nid, ppkey_nid, 1); } int OBJ_find_sigid_by_algs(int *psignid, int dig_nid, int pkey_nid) { nid_triple tmp; const nid_triple *t = &tmp; const nid_triple **rv; int idx; /* permitting searches for sig algs without digest: */ if (pkey_nid == NID_undef) return 0; tmp.hash_id = dig_nid; tmp.pkey_id = pkey_nid; rv = OBJ_bsearch_sigx(&t, sigoid_srt_xref, OSSL_NELEM(sigoid_srt_xref)); if (rv == NULL) { if (!obj_sig_init()) return 0; if (!CRYPTO_THREAD_read_lock(sig_lock)) { ERR_raise(ERR_LIB_OBJ, ERR_R_UNABLE_TO_GET_READ_LOCK); return 0; } if (sigx_app != NULL) { idx = sk_nid_triple_find(sigx_app, &tmp); if (idx >= 0) { t = sk_nid_triple_value(sigx_app, idx); rv = &t; } } CRYPTO_THREAD_unlock(sig_lock); if (rv == NULL) return 0; } if (psignid != NULL) *psignid = (*rv)->sign_id; return 1; } int OBJ_add_sigid(int signid, int dig_id, int pkey_id) { nid_triple *ntr; int dnid = NID_undef, pnid = NID_undef, ret = 0; if (signid == NID_undef || pkey_id == NID_undef) return 0; if (!obj_sig_init()) return 0; if ((ntr = OPENSSL_malloc(sizeof(*ntr))) == NULL) return 0; ntr->sign_id = signid; ntr->hash_id = dig_id; ntr->pkey_id = pkey_id; if (!CRYPTO_THREAD_write_lock(sig_lock)) { ERR_raise(ERR_LIB_OBJ, ERR_R_UNABLE_TO_GET_WRITE_LOCK); OPENSSL_free(ntr); return 0; } /* Check that the entry doesn't exist or exists as desired */ if (ossl_obj_find_sigid_algs(signid, &dnid, &pnid, 0)) { ret = dnid == dig_id && pnid == pkey_id; goto err; } if (sig_app == NULL) { sig_app = sk_nid_triple_new(sig_sk_cmp); if (sig_app == NULL) goto err; } if (sigx_app == NULL) { sigx_app = sk_nid_triple_new(sigx_cmp); if (sigx_app == NULL) goto err; } /* * Better might be to find where to insert the element and insert it there. * This would avoid the sorting steps below. */ if (!sk_nid_triple_push(sig_app, ntr)) goto err; if (!sk_nid_triple_push(sigx_app, ntr)) { ntr = NULL; /* This is referenced by sig_app still */ goto err; } sk_nid_triple_sort(sig_app); sk_nid_triple_sort(sigx_app); ntr = NULL; ret = 1; err: OPENSSL_free(ntr); CRYPTO_THREAD_unlock(sig_lock); return ret; } static void sid_free(nid_triple *tt) { OPENSSL_free(tt); } void OBJ_sigid_free(void) { sk_nid_triple_pop_free(sig_app, sid_free); sk_nid_triple_free(sigx_app); CRYPTO_THREAD_lock_free(sig_lock); sig_app = NULL; sigx_app = NULL; sig_lock = NULL; }
5,930
25.596413
79
c
openssl
openssl-master/crypto/objects/obj_xref.h
/* * WARNING: do not edit! * Generated by objxref.pl * * Copyright 1998-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 */ typedef struct { int sign_id; int hash_id; int pkey_id; } nid_triple; DEFINE_STACK_OF(nid_triple) static const nid_triple sigoid_srt[] = { {NID_md2WithRSAEncryption, NID_md2, NID_rsaEncryption}, {NID_md5WithRSAEncryption, NID_md5, NID_rsaEncryption}, {NID_shaWithRSAEncryption, NID_sha, NID_rsaEncryption}, {NID_sha1WithRSAEncryption, NID_sha1, NID_rsaEncryption}, {NID_dsaWithSHA, NID_sha, NID_dsa}, {NID_dsaWithSHA1_2, NID_sha1, NID_dsa_2}, {NID_mdc2WithRSA, NID_mdc2, NID_rsaEncryption}, {NID_md5WithRSA, NID_md5, NID_rsa}, {NID_dsaWithSHA1, NID_sha1, NID_dsa}, {NID_sha1WithRSA, NID_sha1, NID_rsa}, {NID_ripemd160WithRSA, NID_ripemd160, NID_rsaEncryption}, {NID_md4WithRSAEncryption, NID_md4, NID_rsaEncryption}, {NID_ecdsa_with_SHA1, NID_sha1, NID_X9_62_id_ecPublicKey}, {NID_sha256WithRSAEncryption, NID_sha256, NID_rsaEncryption}, {NID_sha384WithRSAEncryption, NID_sha384, NID_rsaEncryption}, {NID_sha512WithRSAEncryption, NID_sha512, NID_rsaEncryption}, {NID_sha224WithRSAEncryption, NID_sha224, NID_rsaEncryption}, {NID_ecdsa_with_Recommended, NID_undef, NID_X9_62_id_ecPublicKey}, {NID_ecdsa_with_Specified, NID_undef, NID_X9_62_id_ecPublicKey}, {NID_ecdsa_with_SHA224, NID_sha224, NID_X9_62_id_ecPublicKey}, {NID_ecdsa_with_SHA256, NID_sha256, NID_X9_62_id_ecPublicKey}, {NID_ecdsa_with_SHA384, NID_sha384, NID_X9_62_id_ecPublicKey}, {NID_ecdsa_with_SHA512, NID_sha512, NID_X9_62_id_ecPublicKey}, {NID_dsa_with_SHA224, NID_sha224, NID_dsa}, {NID_dsa_with_SHA256, NID_sha256, NID_dsa}, {NID_id_GostR3411_94_with_GostR3410_2001, NID_id_GostR3411_94, NID_id_GostR3410_2001}, {NID_id_GostR3411_94_with_GostR3410_94, NID_id_GostR3411_94, NID_id_GostR3410_94}, {NID_id_GostR3411_94_with_GostR3410_94_cc, NID_id_GostR3411_94, NID_id_GostR3410_94_cc}, {NID_id_GostR3411_94_with_GostR3410_2001_cc, NID_id_GostR3411_94, NID_id_GostR3410_2001_cc}, {NID_rsassaPss, NID_undef, NID_rsassaPss}, {NID_dhSinglePass_stdDH_sha1kdf_scheme, NID_sha1, NID_dh_std_kdf}, {NID_dhSinglePass_stdDH_sha224kdf_scheme, NID_sha224, NID_dh_std_kdf}, {NID_dhSinglePass_stdDH_sha256kdf_scheme, NID_sha256, NID_dh_std_kdf}, {NID_dhSinglePass_stdDH_sha384kdf_scheme, NID_sha384, NID_dh_std_kdf}, {NID_dhSinglePass_stdDH_sha512kdf_scheme, NID_sha512, NID_dh_std_kdf}, {NID_dhSinglePass_cofactorDH_sha1kdf_scheme, NID_sha1, NID_dh_cofactor_kdf}, {NID_dhSinglePass_cofactorDH_sha224kdf_scheme, NID_sha224, NID_dh_cofactor_kdf}, {NID_dhSinglePass_cofactorDH_sha256kdf_scheme, NID_sha256, NID_dh_cofactor_kdf}, {NID_dhSinglePass_cofactorDH_sha384kdf_scheme, NID_sha384, NID_dh_cofactor_kdf}, {NID_dhSinglePass_cofactorDH_sha512kdf_scheme, NID_sha512, NID_dh_cofactor_kdf}, {NID_id_tc26_signwithdigest_gost3410_2012_256, NID_id_GostR3411_2012_256, NID_id_GostR3410_2012_256}, {NID_id_tc26_signwithdigest_gost3410_2012_512, NID_id_GostR3411_2012_512, NID_id_GostR3410_2012_512}, {NID_ED25519, NID_undef, NID_ED25519}, {NID_ED448, NID_undef, NID_ED448}, {NID_RSA_SHA3_224, NID_sha3_224, NID_rsaEncryption}, {NID_RSA_SHA3_256, NID_sha3_256, NID_rsaEncryption}, {NID_RSA_SHA3_384, NID_sha3_384, NID_rsaEncryption}, {NID_RSA_SHA3_512, NID_sha3_512, NID_rsaEncryption}, {NID_SM2_with_SM3, NID_sm3, NID_sm2}, }; static const nid_triple *const sigoid_srt_xref[] = { &sigoid_srt[0], &sigoid_srt[1], &sigoid_srt[7], &sigoid_srt[2], &sigoid_srt[4], &sigoid_srt[3], &sigoid_srt[9], &sigoid_srt[5], &sigoid_srt[8], &sigoid_srt[12], &sigoid_srt[30], &sigoid_srt[35], &sigoid_srt[6], &sigoid_srt[10], &sigoid_srt[11], &sigoid_srt[13], &sigoid_srt[24], &sigoid_srt[20], &sigoid_srt[32], &sigoid_srt[37], &sigoid_srt[14], &sigoid_srt[21], &sigoid_srt[33], &sigoid_srt[38], &sigoid_srt[15], &sigoid_srt[22], &sigoid_srt[34], &sigoid_srt[39], &sigoid_srt[16], &sigoid_srt[23], &sigoid_srt[19], &sigoid_srt[31], &sigoid_srt[36], &sigoid_srt[25], &sigoid_srt[26], &sigoid_srt[27], &sigoid_srt[28], &sigoid_srt[40], &sigoid_srt[41], &sigoid_srt[44], &sigoid_srt[45], &sigoid_srt[46], &sigoid_srt[47], &sigoid_srt[48], };
4,803
35.671756
77
h
openssl
openssl-master/crypto/ocsp/ocsp_asn.c
/* * Copyright 2000-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/ocsp.h> #include "ocsp_local.h" ASN1_SEQUENCE(OCSP_SIGNATURE) = { ASN1_EMBED(OCSP_SIGNATURE, signatureAlgorithm, X509_ALGOR), ASN1_SIMPLE(OCSP_SIGNATURE, signature, ASN1_BIT_STRING), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_SIGNATURE, certs, X509, 0) } ASN1_SEQUENCE_END(OCSP_SIGNATURE) IMPLEMENT_ASN1_FUNCTIONS(OCSP_SIGNATURE) ASN1_SEQUENCE(OCSP_CERTID) = { ASN1_EMBED(OCSP_CERTID, hashAlgorithm, X509_ALGOR), ASN1_EMBED(OCSP_CERTID, issuerNameHash, ASN1_OCTET_STRING), ASN1_EMBED(OCSP_CERTID, issuerKeyHash, ASN1_OCTET_STRING), ASN1_EMBED(OCSP_CERTID, serialNumber, ASN1_INTEGER) } ASN1_SEQUENCE_END(OCSP_CERTID) IMPLEMENT_ASN1_FUNCTIONS(OCSP_CERTID) ASN1_SEQUENCE(OCSP_ONEREQ) = { ASN1_SIMPLE(OCSP_ONEREQ, reqCert, OCSP_CERTID), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_ONEREQ, singleRequestExtensions, X509_EXTENSION, 0) } ASN1_SEQUENCE_END(OCSP_ONEREQ) IMPLEMENT_ASN1_FUNCTIONS(OCSP_ONEREQ) ASN1_SEQUENCE(OCSP_REQINFO) = { ASN1_EXP_OPT(OCSP_REQINFO, version, ASN1_INTEGER, 0), ASN1_EXP_OPT(OCSP_REQINFO, requestorName, GENERAL_NAME, 1), ASN1_SEQUENCE_OF(OCSP_REQINFO, requestList, OCSP_ONEREQ), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_REQINFO, requestExtensions, X509_EXTENSION, 2) } ASN1_SEQUENCE_END(OCSP_REQINFO) IMPLEMENT_ASN1_FUNCTIONS(OCSP_REQINFO) ASN1_SEQUENCE(OCSP_REQUEST) = { ASN1_EMBED(OCSP_REQUEST, tbsRequest, OCSP_REQINFO), ASN1_EXP_OPT(OCSP_REQUEST, optionalSignature, OCSP_SIGNATURE, 0) } ASN1_SEQUENCE_END(OCSP_REQUEST) IMPLEMENT_ASN1_FUNCTIONS(OCSP_REQUEST) /* OCSP_RESPONSE templates */ ASN1_SEQUENCE(OCSP_RESPBYTES) = { ASN1_SIMPLE(OCSP_RESPBYTES, responseType, ASN1_OBJECT), ASN1_SIMPLE(OCSP_RESPBYTES, response, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(OCSP_RESPBYTES) IMPLEMENT_ASN1_FUNCTIONS(OCSP_RESPBYTES) ASN1_SEQUENCE(OCSP_RESPONSE) = { ASN1_SIMPLE(OCSP_RESPONSE, responseStatus, ASN1_ENUMERATED), ASN1_EXP_OPT(OCSP_RESPONSE, responseBytes, OCSP_RESPBYTES, 0) } ASN1_SEQUENCE_END(OCSP_RESPONSE) IMPLEMENT_ASN1_FUNCTIONS(OCSP_RESPONSE) ASN1_CHOICE(OCSP_RESPID) = { ASN1_EXP(OCSP_RESPID, value.byName, X509_NAME, 1), ASN1_EXP(OCSP_RESPID, value.byKey, ASN1_OCTET_STRING, 2) } ASN1_CHOICE_END(OCSP_RESPID) IMPLEMENT_ASN1_FUNCTIONS(OCSP_RESPID) ASN1_SEQUENCE(OCSP_REVOKEDINFO) = { ASN1_SIMPLE(OCSP_REVOKEDINFO, revocationTime, ASN1_GENERALIZEDTIME), ASN1_EXP_OPT(OCSP_REVOKEDINFO, revocationReason, ASN1_ENUMERATED, 0) } ASN1_SEQUENCE_END(OCSP_REVOKEDINFO) IMPLEMENT_ASN1_FUNCTIONS(OCSP_REVOKEDINFO) ASN1_CHOICE(OCSP_CERTSTATUS) = { ASN1_IMP(OCSP_CERTSTATUS, value.good, ASN1_NULL, 0), ASN1_IMP(OCSP_CERTSTATUS, value.revoked, OCSP_REVOKEDINFO, 1), ASN1_IMP(OCSP_CERTSTATUS, value.unknown, ASN1_NULL, 2) } ASN1_CHOICE_END(OCSP_CERTSTATUS) IMPLEMENT_ASN1_FUNCTIONS(OCSP_CERTSTATUS) ASN1_SEQUENCE(OCSP_SINGLERESP) = { ASN1_SIMPLE(OCSP_SINGLERESP, certId, OCSP_CERTID), ASN1_SIMPLE(OCSP_SINGLERESP, certStatus, OCSP_CERTSTATUS), ASN1_SIMPLE(OCSP_SINGLERESP, thisUpdate, ASN1_GENERALIZEDTIME), ASN1_EXP_OPT(OCSP_SINGLERESP, nextUpdate, ASN1_GENERALIZEDTIME, 0), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_SINGLERESP, singleExtensions, X509_EXTENSION, 1) } ASN1_SEQUENCE_END(OCSP_SINGLERESP) IMPLEMENT_ASN1_FUNCTIONS(OCSP_SINGLERESP) ASN1_SEQUENCE(OCSP_RESPDATA) = { ASN1_EXP_OPT(OCSP_RESPDATA, version, ASN1_INTEGER, 0), ASN1_EMBED(OCSP_RESPDATA, responderId, OCSP_RESPID), ASN1_SIMPLE(OCSP_RESPDATA, producedAt, ASN1_GENERALIZEDTIME), ASN1_SEQUENCE_OF(OCSP_RESPDATA, responses, OCSP_SINGLERESP), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_RESPDATA, responseExtensions, X509_EXTENSION, 1) } ASN1_SEQUENCE_END(OCSP_RESPDATA) IMPLEMENT_ASN1_FUNCTIONS(OCSP_RESPDATA) ASN1_SEQUENCE(OCSP_BASICRESP) = { ASN1_EMBED(OCSP_BASICRESP, tbsResponseData, OCSP_RESPDATA), ASN1_EMBED(OCSP_BASICRESP, signatureAlgorithm, X509_ALGOR), ASN1_SIMPLE(OCSP_BASICRESP, signature, ASN1_BIT_STRING), ASN1_EXP_SEQUENCE_OF_OPT(OCSP_BASICRESP, certs, X509, 0) } ASN1_SEQUENCE_END(OCSP_BASICRESP) IMPLEMENT_ASN1_FUNCTIONS(OCSP_BASICRESP) ASN1_SEQUENCE(OCSP_CRLID) = { ASN1_EXP_OPT(OCSP_CRLID, crlUrl, ASN1_IA5STRING, 0), ASN1_EXP_OPT(OCSP_CRLID, crlNum, ASN1_INTEGER, 1), ASN1_EXP_OPT(OCSP_CRLID, crlTime, ASN1_GENERALIZEDTIME, 2) } ASN1_SEQUENCE_END(OCSP_CRLID) IMPLEMENT_ASN1_FUNCTIONS(OCSP_CRLID) ASN1_SEQUENCE(OCSP_SERVICELOC) = { ASN1_SIMPLE(OCSP_SERVICELOC, issuer, X509_NAME), ASN1_SEQUENCE_OF_OPT(OCSP_SERVICELOC, locator, ACCESS_DESCRIPTION) } ASN1_SEQUENCE_END(OCSP_SERVICELOC) IMPLEMENT_ASN1_FUNCTIONS(OCSP_SERVICELOC)
5,231
37.470588
89
c
openssl
openssl-master/crypto/ocsp/ocsp_cl.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <time.h> #include "internal/cryptlib.h" #include <openssl/asn1.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/ocsp.h> #include "ocsp_local.h" /* * Utility functions related to sending OCSP requests and extracting relevant * information from the response. */ /* * Add an OCSP_CERTID to an OCSP request. Return new OCSP_ONEREQ pointer: * useful if we want to add extensions. */ OCSP_ONEREQ *OCSP_request_add0_id(OCSP_REQUEST *req, OCSP_CERTID *cid) { OCSP_ONEREQ *one = NULL; if ((one = OCSP_ONEREQ_new()) == NULL) return NULL; OCSP_CERTID_free(one->reqCert); one->reqCert = cid; if (req && !sk_OCSP_ONEREQ_push(req->tbsRequest.requestList, one)) { one->reqCert = NULL; /* do not free on error */ OCSP_ONEREQ_free(one); return NULL; } return one; } /* Set requestorName from an X509_NAME structure */ int OCSP_request_set1_name(OCSP_REQUEST *req, const X509_NAME *nm) { GENERAL_NAME *gen = GENERAL_NAME_new(); if (gen == NULL) return 0; if (!X509_NAME_set(&gen->d.directoryName, nm)) { GENERAL_NAME_free(gen); return 0; } gen->type = GEN_DIRNAME; GENERAL_NAME_free(req->tbsRequest.requestorName); req->tbsRequest.requestorName = gen; return 1; } /* Add a certificate to an OCSP request */ int OCSP_request_add1_cert(OCSP_REQUEST *req, X509 *cert) { if (req->optionalSignature == NULL && (req->optionalSignature = OCSP_SIGNATURE_new()) == NULL) return 0; if (cert == NULL) return 1; return ossl_x509_add_cert_new(&req->optionalSignature->certs, cert, X509_ADD_FLAG_UP_REF); } /* * Sign an OCSP request set the requestorName to the subject name of an * optional signers certificate and include one or more optional certificates * in the request. Behaves like PKCS7_sign(). */ int OCSP_request_sign(OCSP_REQUEST *req, X509 *signer, EVP_PKEY *key, const EVP_MD *dgst, STACK_OF(X509) *certs, unsigned long flags) { if (!OCSP_request_set1_name(req, X509_get_subject_name(signer))) goto err; if ((req->optionalSignature = OCSP_SIGNATURE_new()) == NULL) goto err; if (key != NULL) { if (!X509_check_private_key(signer, key)) { ERR_raise(ERR_LIB_OCSP, OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE); goto err; } if (!OCSP_REQUEST_sign(req, key, dgst, signer->libctx, signer->propq)) goto err; } if ((flags & OCSP_NOCERTS) == 0) { if (!OCSP_request_add1_cert(req, signer) || !X509_add_certs(req->optionalSignature->certs, certs, X509_ADD_FLAG_UP_REF)) goto err; } return 1; err: OCSP_SIGNATURE_free(req->optionalSignature); req->optionalSignature = NULL; return 0; } /* Get response status */ int OCSP_response_status(OCSP_RESPONSE *resp) { return ASN1_ENUMERATED_get(resp->responseStatus); } /* * Extract basic response from OCSP_RESPONSE or NULL if no basic response * present. */ OCSP_BASICRESP *OCSP_response_get1_basic(OCSP_RESPONSE *resp) { OCSP_RESPBYTES *rb = resp->responseBytes; if (rb == NULL) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NO_RESPONSE_DATA); return NULL; } if (OBJ_obj2nid(rb->responseType) != NID_id_pkix_OCSP_basic) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NOT_BASIC_RESPONSE); return NULL; } return ASN1_item_unpack(rb->response, ASN1_ITEM_rptr(OCSP_BASICRESP)); } const ASN1_OCTET_STRING *OCSP_resp_get0_signature(const OCSP_BASICRESP *bs) { return bs->signature; } const X509_ALGOR *OCSP_resp_get0_tbs_sigalg(const OCSP_BASICRESP *bs) { return &bs->signatureAlgorithm; } const OCSP_RESPDATA *OCSP_resp_get0_respdata(const OCSP_BASICRESP *bs) { return &bs->tbsResponseData; } /* Return number of OCSP_SINGLERESP responses present in a basic response */ int OCSP_resp_count(OCSP_BASICRESP *bs) { if (bs == NULL) return -1; return sk_OCSP_SINGLERESP_num(bs->tbsResponseData.responses); } /* Extract an OCSP_SINGLERESP response with a given index */ OCSP_SINGLERESP *OCSP_resp_get0(OCSP_BASICRESP *bs, int idx) { if (bs == NULL) return NULL; return sk_OCSP_SINGLERESP_value(bs->tbsResponseData.responses, idx); } const ASN1_GENERALIZEDTIME *OCSP_resp_get0_produced_at(const OCSP_BASICRESP *bs) { return bs->tbsResponseData.producedAt; } const STACK_OF(X509) *OCSP_resp_get0_certs(const OCSP_BASICRESP *bs) { return bs->certs; } int OCSP_resp_get0_id(const OCSP_BASICRESP *bs, const ASN1_OCTET_STRING **pid, const X509_NAME **pname) { const OCSP_RESPID *rid = &bs->tbsResponseData.responderId; if (rid->type == V_OCSP_RESPID_NAME) { *pname = rid->value.byName; *pid = NULL; } else if (rid->type == V_OCSP_RESPID_KEY) { *pid = rid->value.byKey; *pname = NULL; } else { return 0; } return 1; } int OCSP_resp_get1_id(const OCSP_BASICRESP *bs, ASN1_OCTET_STRING **pid, X509_NAME **pname) { const OCSP_RESPID *rid = &bs->tbsResponseData.responderId; if (rid->type == V_OCSP_RESPID_NAME) { *pname = X509_NAME_dup(rid->value.byName); *pid = NULL; } else if (rid->type == V_OCSP_RESPID_KEY) { *pid = ASN1_OCTET_STRING_dup(rid->value.byKey); *pname = NULL; } else { return 0; } if (*pname == NULL && *pid == NULL) return 0; return 1; } /* Look single response matching a given certificate ID */ int OCSP_resp_find(OCSP_BASICRESP *bs, OCSP_CERTID *id, int last) { int i; STACK_OF(OCSP_SINGLERESP) *sresp; OCSP_SINGLERESP *single; if (bs == NULL) return -1; if (last < 0) last = 0; else last++; sresp = bs->tbsResponseData.responses; for (i = last; i < sk_OCSP_SINGLERESP_num(sresp); i++) { single = sk_OCSP_SINGLERESP_value(sresp, i); if (!OCSP_id_cmp(id, single->certId)) return i; } return -1; } /* * Extract status information from an OCSP_SINGLERESP structure. Note: the * revtime and reason values are only set if the certificate status is * revoked. Returns numerical value of status. */ int OCSP_single_get0_status(OCSP_SINGLERESP *single, int *reason, ASN1_GENERALIZEDTIME **revtime, ASN1_GENERALIZEDTIME **thisupd, ASN1_GENERALIZEDTIME **nextupd) { int ret; OCSP_CERTSTATUS *cst; if (single == NULL) return -1; cst = single->certStatus; ret = cst->type; if (ret == V_OCSP_CERTSTATUS_REVOKED) { OCSP_REVOKEDINFO *rev = cst->value.revoked; if (revtime) *revtime = rev->revocationTime; if (reason) { if (rev->revocationReason) *reason = ASN1_ENUMERATED_get(rev->revocationReason); else *reason = -1; } } if (thisupd != NULL) *thisupd = single->thisUpdate; if (nextupd != NULL) *nextupd = single->nextUpdate; return ret; } /* * This function combines the previous ones: look up a certificate ID and if * found extract status information. Return 0 is successful. */ int OCSP_resp_find_status(OCSP_BASICRESP *bs, OCSP_CERTID *id, int *status, int *reason, ASN1_GENERALIZEDTIME **revtime, ASN1_GENERALIZEDTIME **thisupd, ASN1_GENERALIZEDTIME **nextupd) { int i = OCSP_resp_find(bs, id, -1); OCSP_SINGLERESP *single; /* Maybe check for multiple responses and give an error? */ if (i < 0) return 0; single = OCSP_resp_get0(bs, i); i = OCSP_single_get0_status(single, reason, revtime, thisupd, nextupd); if (status != NULL) *status = i; return 1; } /* * Check validity of thisUpdate and nextUpdate fields. It is possible that * the request will take a few seconds to process and/or the time won't be * totally accurate. Therefore to avoid rejecting otherwise valid time we * allow the times to be within 'nsec' of the current time. Also to avoid * accepting very old responses without a nextUpdate field an optional maxage * parameter specifies the maximum age the thisUpdate field can be. */ int OCSP_check_validity(ASN1_GENERALIZEDTIME *thisupd, ASN1_GENERALIZEDTIME *nextupd, long nsec, long maxsec) { int ret = 1; time_t t_now, t_tmp; time(&t_now); /* Check thisUpdate is valid and not more than nsec in the future */ if (!ASN1_GENERALIZEDTIME_check(thisupd)) { ERR_raise(ERR_LIB_OCSP, OCSP_R_ERROR_IN_THISUPDATE_FIELD); ret = 0; } else { t_tmp = t_now + nsec; if (X509_cmp_time(thisupd, &t_tmp) > 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_STATUS_NOT_YET_VALID); ret = 0; } /* * If maxsec specified check thisUpdate is not more than maxsec in * the past */ if (maxsec >= 0) { t_tmp = t_now - maxsec; if (X509_cmp_time(thisupd, &t_tmp) < 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_STATUS_TOO_OLD); ret = 0; } } } if (nextupd == NULL) return ret; /* Check nextUpdate is valid and not more than nsec in the past */ if (!ASN1_GENERALIZEDTIME_check(nextupd)) { ERR_raise(ERR_LIB_OCSP, OCSP_R_ERROR_IN_NEXTUPDATE_FIELD); ret = 0; } else { t_tmp = t_now - nsec; if (X509_cmp_time(nextupd, &t_tmp) < 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_STATUS_EXPIRED); ret = 0; } } /* Also don't allow nextUpdate to precede thisUpdate */ if (ASN1_STRING_cmp(nextupd, thisupd) < 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NEXTUPDATE_BEFORE_THISUPDATE); ret = 0; } return ret; } const OCSP_CERTID *OCSP_SINGLERESP_get0_id(const OCSP_SINGLERESP *single) { return single->certId; }
10,712
28.03252
80
c
openssl
openssl-master/crypto/ocsp/ocsp_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/ocsperr.h> #include "crypto/ocsperr.h" #ifndef OPENSSL_NO_OCSP # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA OCSP_str_reasons[] = { {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_CERTIFICATE_VERIFY_ERROR), "certificate verify error"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_DIGEST_ERR), "digest err"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_DIGEST_NAME_ERR), "digest name err"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_DIGEST_SIZE_ERR), "digest size err"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_ERROR_IN_NEXTUPDATE_FIELD), "error in nextupdate field"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_ERROR_IN_THISUPDATE_FIELD), "error in thisupdate field"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_MISSING_OCSPSIGNING_USAGE), "missing ocspsigning usage"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NEXTUPDATE_BEFORE_THISUPDATE), "nextupdate before thisupdate"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NOT_BASIC_RESPONSE), "not basic response"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NO_CERTIFICATES_IN_CHAIN), "no certificates in chain"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NO_RESPONSE_DATA), "no response data"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NO_REVOKED_TIME), "no revoked time"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_NO_SIGNER_KEY), "no signer key"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), "private key does not match certificate"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_REQUEST_NOT_SIGNED), "request not signed"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_RESPONSE_CONTAINS_NO_REVOCATION_DATA), "response contains no revocation data"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_ROOT_CA_NOT_TRUSTED), "root ca not trusted"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_SIGNATURE_FAILURE), "signature failure"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND), "signer certificate not found"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_STATUS_EXPIRED), "status expired"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_STATUS_NOT_YET_VALID), "status not yet valid"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_STATUS_TOO_OLD), "status too old"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_UNKNOWN_MESSAGE_DIGEST), "unknown message digest"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_UNKNOWN_NID), "unknown nid"}, {ERR_PACK(ERR_LIB_OCSP, 0, OCSP_R_UNSUPPORTED_REQUESTORNAME_TYPE), "unsupported requestorname type"}, {0, NULL} }; # endif int ossl_err_load_OCSP_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(OCSP_str_reasons[0].error) == NULL) ERR_load_strings_const(OCSP_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
3,086
39.618421
79
c
openssl
openssl-master/crypto/ocsp/ocsp_ext.c
/* * Copyright 2000-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/ocsp.h> #include "ocsp_local.h" #include <openssl/rand.h> #include <openssl/x509v3.h> /* Standard wrapper functions for extensions */ /* OCSP request extensions */ int OCSP_REQUEST_get_ext_count(OCSP_REQUEST *x) { return X509v3_get_ext_count(x->tbsRequest.requestExtensions); } int OCSP_REQUEST_get_ext_by_NID(OCSP_REQUEST *x, int nid, int lastpos) { return (X509v3_get_ext_by_NID (x->tbsRequest.requestExtensions, nid, lastpos)); } int OCSP_REQUEST_get_ext_by_OBJ(OCSP_REQUEST *x, const ASN1_OBJECT *obj, int lastpos) { return (X509v3_get_ext_by_OBJ (x->tbsRequest.requestExtensions, obj, lastpos)); } int OCSP_REQUEST_get_ext_by_critical(OCSP_REQUEST *x, int crit, int lastpos) { return (X509v3_get_ext_by_critical (x->tbsRequest.requestExtensions, crit, lastpos)); } X509_EXTENSION *OCSP_REQUEST_get_ext(OCSP_REQUEST *x, int loc) { return X509v3_get_ext(x->tbsRequest.requestExtensions, loc); } X509_EXTENSION *OCSP_REQUEST_delete_ext(OCSP_REQUEST *x, int loc) { return X509v3_delete_ext(x->tbsRequest.requestExtensions, loc); } void *OCSP_REQUEST_get1_ext_d2i(OCSP_REQUEST *x, int nid, int *crit, int *idx) { return X509V3_get_d2i(x->tbsRequest.requestExtensions, nid, crit, idx); } int OCSP_REQUEST_add1_ext_i2d(OCSP_REQUEST *x, int nid, void *value, int crit, unsigned long flags) { return X509V3_add1_i2d(&x->tbsRequest.requestExtensions, nid, value, crit, flags); } int OCSP_REQUEST_add_ext(OCSP_REQUEST *x, X509_EXTENSION *ex, int loc) { return (X509v3_add_ext(&(x->tbsRequest.requestExtensions), ex, loc) != NULL); } /* Single extensions */ int OCSP_ONEREQ_get_ext_count(OCSP_ONEREQ *x) { return X509v3_get_ext_count(x->singleRequestExtensions); } int OCSP_ONEREQ_get_ext_by_NID(OCSP_ONEREQ *x, int nid, int lastpos) { return X509v3_get_ext_by_NID(x->singleRequestExtensions, nid, lastpos); } int OCSP_ONEREQ_get_ext_by_OBJ(OCSP_ONEREQ *x, const ASN1_OBJECT *obj, int lastpos) { return X509v3_get_ext_by_OBJ(x->singleRequestExtensions, obj, lastpos); } int OCSP_ONEREQ_get_ext_by_critical(OCSP_ONEREQ *x, int crit, int lastpos) { return (X509v3_get_ext_by_critical (x->singleRequestExtensions, crit, lastpos)); } X509_EXTENSION *OCSP_ONEREQ_get_ext(OCSP_ONEREQ *x, int loc) { return X509v3_get_ext(x->singleRequestExtensions, loc); } X509_EXTENSION *OCSP_ONEREQ_delete_ext(OCSP_ONEREQ *x, int loc) { return X509v3_delete_ext(x->singleRequestExtensions, loc); } void *OCSP_ONEREQ_get1_ext_d2i(OCSP_ONEREQ *x, int nid, int *crit, int *idx) { return X509V3_get_d2i(x->singleRequestExtensions, nid, crit, idx); } int OCSP_ONEREQ_add1_ext_i2d(OCSP_ONEREQ *x, int nid, void *value, int crit, unsigned long flags) { return X509V3_add1_i2d(&x->singleRequestExtensions, nid, value, crit, flags); } int OCSP_ONEREQ_add_ext(OCSP_ONEREQ *x, X509_EXTENSION *ex, int loc) { return (X509v3_add_ext(&(x->singleRequestExtensions), ex, loc) != NULL); } /* OCSP Basic response */ int OCSP_BASICRESP_get_ext_count(OCSP_BASICRESP *x) { return X509v3_get_ext_count(x->tbsResponseData.responseExtensions); } int OCSP_BASICRESP_get_ext_by_NID(OCSP_BASICRESP *x, int nid, int lastpos) { return (X509v3_get_ext_by_NID (x->tbsResponseData.responseExtensions, nid, lastpos)); } int OCSP_BASICRESP_get_ext_by_OBJ(OCSP_BASICRESP *x, const ASN1_OBJECT *obj, int lastpos) { return (X509v3_get_ext_by_OBJ (x->tbsResponseData.responseExtensions, obj, lastpos)); } int OCSP_BASICRESP_get_ext_by_critical(OCSP_BASICRESP *x, int crit, int lastpos) { return (X509v3_get_ext_by_critical (x->tbsResponseData.responseExtensions, crit, lastpos)); } X509_EXTENSION *OCSP_BASICRESP_get_ext(OCSP_BASICRESP *x, int loc) { return X509v3_get_ext(x->tbsResponseData.responseExtensions, loc); } X509_EXTENSION *OCSP_BASICRESP_delete_ext(OCSP_BASICRESP *x, int loc) { return X509v3_delete_ext(x->tbsResponseData.responseExtensions, loc); } void *OCSP_BASICRESP_get1_ext_d2i(OCSP_BASICRESP *x, int nid, int *crit, int *idx) { return X509V3_get_d2i(x->tbsResponseData.responseExtensions, nid, crit, idx); } int OCSP_BASICRESP_add1_ext_i2d(OCSP_BASICRESP *x, int nid, void *value, int crit, unsigned long flags) { return X509V3_add1_i2d(&x->tbsResponseData.responseExtensions, nid, value, crit, flags); } int OCSP_BASICRESP_add_ext(OCSP_BASICRESP *x, X509_EXTENSION *ex, int loc) { return (X509v3_add_ext(&(x->tbsResponseData.responseExtensions), ex, loc) != NULL); } /* OCSP single response extensions */ int OCSP_SINGLERESP_get_ext_count(OCSP_SINGLERESP *x) { return X509v3_get_ext_count(x->singleExtensions); } int OCSP_SINGLERESP_get_ext_by_NID(OCSP_SINGLERESP *x, int nid, int lastpos) { return X509v3_get_ext_by_NID(x->singleExtensions, nid, lastpos); } int OCSP_SINGLERESP_get_ext_by_OBJ(OCSP_SINGLERESP *x, const ASN1_OBJECT *obj, int lastpos) { return X509v3_get_ext_by_OBJ(x->singleExtensions, obj, lastpos); } int OCSP_SINGLERESP_get_ext_by_critical(OCSP_SINGLERESP *x, int crit, int lastpos) { return X509v3_get_ext_by_critical(x->singleExtensions, crit, lastpos); } X509_EXTENSION *OCSP_SINGLERESP_get_ext(OCSP_SINGLERESP *x, int loc) { return X509v3_get_ext(x->singleExtensions, loc); } X509_EXTENSION *OCSP_SINGLERESP_delete_ext(OCSP_SINGLERESP *x, int loc) { return X509v3_delete_ext(x->singleExtensions, loc); } void *OCSP_SINGLERESP_get1_ext_d2i(OCSP_SINGLERESP *x, int nid, int *crit, int *idx) { return X509V3_get_d2i(x->singleExtensions, nid, crit, idx); } int OCSP_SINGLERESP_add1_ext_i2d(OCSP_SINGLERESP *x, int nid, void *value, int crit, unsigned long flags) { return X509V3_add1_i2d(&x->singleExtensions, nid, value, crit, flags); } int OCSP_SINGLERESP_add_ext(OCSP_SINGLERESP *x, X509_EXTENSION *ex, int loc) { return (X509v3_add_ext(&(x->singleExtensions), ex, loc) != NULL); } /* also CRL Entry Extensions */ /* Nonce handling functions */ /* * Add a nonce to an extension stack. A nonce can be specified or if NULL a * random nonce will be generated. Note: OpenSSL 0.9.7d and later create an * OCTET STRING containing the nonce, previous versions used the raw nonce. */ static int ocsp_add1_nonce(STACK_OF(X509_EXTENSION) **exts, unsigned char *val, int len) { unsigned char *tmpval; ASN1_OCTET_STRING os; int ret = 0; if (len <= 0) len = OCSP_DEFAULT_NONCE_LENGTH; /* * Create the OCTET STRING manually by writing out the header and * appending the content octets. This avoids an extra memory allocation * operation in some cases. Applications should *NOT* do this because it * relies on library internals. */ os.length = ASN1_object_size(0, len, V_ASN1_OCTET_STRING); if (os.length < 0) return 0; os.data = OPENSSL_malloc(os.length); if (os.data == NULL) goto err; tmpval = os.data; ASN1_put_object(&tmpval, 0, len, V_ASN1_OCTET_STRING, V_ASN1_UNIVERSAL); if (val) memcpy(tmpval, val, len); else if (RAND_bytes(tmpval, len) <= 0) goto err; if (X509V3_add1_i2d(exts, NID_id_pkix_OCSP_Nonce, &os, 0, X509V3_ADD_REPLACE) <= 0) goto err; ret = 1; err: OPENSSL_free(os.data); return ret; } /* Add nonce to an OCSP request */ int OCSP_request_add1_nonce(OCSP_REQUEST *req, unsigned char *val, int len) { return ocsp_add1_nonce(&req->tbsRequest.requestExtensions, val, len); } /* Same as above but for a response */ int OCSP_basic_add1_nonce(OCSP_BASICRESP *resp, unsigned char *val, int len) { return ocsp_add1_nonce(&resp->tbsResponseData.responseExtensions, val, len); } /*- * Check nonce validity in a request and response. * Return value reflects result: * 1: nonces present and equal. * 2: nonces both absent. * 3: nonce present in response only. * 0: nonces both present and not equal. * -1: nonce in request only. * * For most responders clients can check return > 0. * If responder doesn't handle nonces return != 0 may be * necessary. return == 0 is always an error. */ int OCSP_check_nonce(OCSP_REQUEST *req, OCSP_BASICRESP *bs) { /* * Since we are only interested in the presence or absence of * the nonce and comparing its value there is no need to use * the X509V3 routines: this way we can avoid them allocating an * ASN1_OCTET_STRING structure for the value which would be * freed immediately anyway. */ int req_idx, resp_idx; X509_EXTENSION *req_ext, *resp_ext; req_idx = OCSP_REQUEST_get_ext_by_NID(req, NID_id_pkix_OCSP_Nonce, -1); resp_idx = OCSP_BASICRESP_get_ext_by_NID(bs, NID_id_pkix_OCSP_Nonce, -1); /* Check both absent */ if ((req_idx < 0) && (resp_idx < 0)) return 2; /* Check in request only */ if ((req_idx >= 0) && (resp_idx < 0)) return -1; /* Check in response but not request */ if ((req_idx < 0) && (resp_idx >= 0)) return 3; /* * Otherwise nonce in request and response so retrieve the extensions */ req_ext = OCSP_REQUEST_get_ext(req, req_idx); resp_ext = OCSP_BASICRESP_get_ext(bs, resp_idx); if (ASN1_OCTET_STRING_cmp(X509_EXTENSION_get_data(req_ext), X509_EXTENSION_get_data(resp_ext))) return 0; return 1; } /* * Copy the nonce value (if any) from an OCSP request to a response. */ int OCSP_copy_nonce(OCSP_BASICRESP *resp, OCSP_REQUEST *req) { X509_EXTENSION *req_ext; int req_idx; /* Check for nonce in request */ req_idx = OCSP_REQUEST_get_ext_by_NID(req, NID_id_pkix_OCSP_Nonce, -1); /* If no nonce that's OK */ if (req_idx < 0) return 2; req_ext = OCSP_REQUEST_get_ext(req, req_idx); return OCSP_BASICRESP_add_ext(resp, req_ext, -1); } X509_EXTENSION *OCSP_crlID_new(const char *url, long *n, char *tim) { X509_EXTENSION *x = NULL; OCSP_CRLID *cid = NULL; if ((cid = OCSP_CRLID_new()) == NULL) goto err; if (url) { if ((cid->crlUrl = ASN1_IA5STRING_new()) == NULL) goto err; if (!(ASN1_STRING_set(cid->crlUrl, url, -1))) goto err; } if (n) { if ((cid->crlNum = ASN1_INTEGER_new()) == NULL) goto err; if (!(ASN1_INTEGER_set(cid->crlNum, *n))) goto err; } if (tim) { if ((cid->crlTime = ASN1_GENERALIZEDTIME_new()) == NULL) goto err; if (!(ASN1_GENERALIZEDTIME_set_string(cid->crlTime, tim))) goto err; } x = X509V3_EXT_i2d(NID_id_pkix_OCSP_CrlID, 0, cid); err: OCSP_CRLID_free(cid); return x; } /* AcceptableResponses ::= SEQUENCE OF OBJECT IDENTIFIER */ X509_EXTENSION *OCSP_accept_responses_new(char **oids) { int nid; STACK_OF(ASN1_OBJECT) *sk = NULL; ASN1_OBJECT *o = NULL; X509_EXTENSION *x = NULL; if ((sk = sk_ASN1_OBJECT_new_null()) == NULL) goto err; while (oids && *oids) { if ((nid = OBJ_txt2nid(*oids)) != NID_undef && (o = OBJ_nid2obj(nid))) sk_ASN1_OBJECT_push(sk, o); oids++; } x = X509V3_EXT_i2d(NID_id_pkix_OCSP_acceptableResponses, 0, sk); err: sk_ASN1_OBJECT_pop_free(sk, ASN1_OBJECT_free); return x; } /* ArchiveCutoff ::= GeneralizedTime */ X509_EXTENSION *OCSP_archive_cutoff_new(char *tim) { X509_EXTENSION *x = NULL; ASN1_GENERALIZEDTIME *gt = NULL; if ((gt = ASN1_GENERALIZEDTIME_new()) == NULL) goto err; if (!(ASN1_GENERALIZEDTIME_set_string(gt, tim))) goto err; x = X509V3_EXT_i2d(NID_id_pkix_OCSP_archiveCutoff, 0, gt); err: ASN1_GENERALIZEDTIME_free(gt); return x; } /* * per ACCESS_DESCRIPTION parameter are oids, of which there are currently * two--NID_ad_ocsp, NID_id_ad_caIssuers--and GeneralName value. This method * forces NID_ad_ocsp and uniformResourceLocator [6] IA5String. */ X509_EXTENSION *OCSP_url_svcloc_new(const X509_NAME *issuer, const char **urls) { X509_EXTENSION *x = NULL; ASN1_IA5STRING *ia5 = NULL; OCSP_SERVICELOC *sloc = NULL; ACCESS_DESCRIPTION *ad = NULL; if ((sloc = OCSP_SERVICELOC_new()) == NULL) goto err; X509_NAME_free(sloc->issuer); if ((sloc->issuer = X509_NAME_dup(issuer)) == NULL) goto err; if (urls && *urls && (sloc->locator = sk_ACCESS_DESCRIPTION_new_null()) == NULL) goto err; while (urls && *urls) { if ((ad = ACCESS_DESCRIPTION_new()) == NULL) goto err; if ((ad->method = OBJ_nid2obj(NID_ad_OCSP)) == NULL) goto err; if ((ia5 = ASN1_IA5STRING_new()) == NULL) goto err; if (!ASN1_STRING_set((ASN1_STRING *)ia5, *urls, -1)) goto err; /* ad->location is allocated inside ACCESS_DESCRIPTION_new */ ad->location->type = GEN_URI; ad->location->d.ia5 = ia5; ia5 = NULL; if (!sk_ACCESS_DESCRIPTION_push(sloc->locator, ad)) goto err; ad = NULL; urls++; } x = X509V3_EXT_i2d(NID_id_pkix_OCSP_serviceLocator, 0, sloc); err: ASN1_IA5STRING_free(ia5); ACCESS_DESCRIPTION_free(ad); OCSP_SERVICELOC_free(sloc); return x; }
14,303
29.241015
79
c
openssl
openssl-master/crypto/ocsp/ocsp_http.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/ocsp.h> #include <openssl/http.h> #ifndef OPENSSL_NO_OCSP OSSL_HTTP_REQ_CTX *OCSP_sendreq_new(BIO *io, const char *path, const OCSP_REQUEST *req, int buf_size) { OSSL_HTTP_REQ_CTX *rctx = OSSL_HTTP_REQ_CTX_new(io, io, buf_size); if (rctx == NULL) return NULL; /*- * by default: * no bio_update_fn (and consequently no arg) * no ssl * no proxy * no timeout (blocking indefinitely) * no expected content type * max_resp_len = 100 KiB */ if (!OSSL_HTTP_REQ_CTX_set_request_line(rctx, 1 /* POST */, NULL, NULL, path)) goto err; /* by default, no extra headers */ if (!OSSL_HTTP_REQ_CTX_set_expected(rctx, NULL /* content_type */, 1 /* asn1 */, 0 /* timeout */, 0 /* keep_alive */)) goto err; if (req != NULL && !OSSL_HTTP_REQ_CTX_set1_req(rctx, "application/ocsp-request", ASN1_ITEM_rptr(OCSP_REQUEST), (const ASN1_VALUE *)req)) goto err; return rctx; err: OSSL_HTTP_REQ_CTX_free(rctx); return NULL; } OCSP_RESPONSE *OCSP_sendreq_bio(BIO *b, const char *path, OCSP_REQUEST *req) { OCSP_RESPONSE *resp = NULL; OSSL_HTTP_REQ_CTX *ctx; BIO *mem; ctx = OCSP_sendreq_new(b, path, req, 0 /* default buf_size */); if (ctx == NULL) return NULL; mem = OSSL_HTTP_REQ_CTX_exchange(ctx); /* ASN1_item_d2i_bio handles NULL bio gracefully */ resp = (OCSP_RESPONSE *)ASN1_item_d2i_bio(ASN1_ITEM_rptr(OCSP_RESPONSE), mem, NULL); OSSL_HTTP_REQ_CTX_free(ctx); return resp; } #endif /* !defined(OPENSSL_NO_OCSP) */
2,207
31
78
c
openssl
openssl-master/crypto/ocsp/ocsp_lib.c
/* * Copyright 2000-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/objects.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/ocsp.h> #include "ocsp_local.h" #include <openssl/asn1t.h> /* Convert a certificate and its issuer to an OCSP_CERTID */ OCSP_CERTID *OCSP_cert_to_id(const EVP_MD *dgst, const X509 *subject, const X509 *issuer) { const X509_NAME *iname; const ASN1_INTEGER *serial; ASN1_BIT_STRING *ikey; if (!dgst) dgst = EVP_sha1(); if (subject) { iname = X509_get_issuer_name(subject); serial = X509_get0_serialNumber(subject); } else { iname = X509_get_subject_name(issuer); serial = NULL; } ikey = X509_get0_pubkey_bitstr(issuer); return OCSP_cert_id_new(dgst, iname, ikey, serial); } OCSP_CERTID *OCSP_cert_id_new(const EVP_MD *dgst, const X509_NAME *issuerName, const ASN1_BIT_STRING *issuerKey, const ASN1_INTEGER *serialNumber) { int nid; unsigned int i; X509_ALGOR *alg; OCSP_CERTID *cid = NULL; unsigned char md[EVP_MAX_MD_SIZE]; if ((cid = OCSP_CERTID_new()) == NULL) goto err; alg = &cid->hashAlgorithm; ASN1_OBJECT_free(alg->algorithm); if ((nid = EVP_MD_get_type(dgst)) == NID_undef) { ERR_raise(ERR_LIB_OCSP, OCSP_R_UNKNOWN_NID); goto err; } if ((alg->algorithm = OBJ_nid2obj(nid)) == NULL) goto err; if ((alg->parameter = ASN1_TYPE_new()) == NULL) goto err; alg->parameter->type = V_ASN1_NULL; if (!X509_NAME_digest(issuerName, dgst, md, &i)) goto digerr; if (!(ASN1_OCTET_STRING_set(&cid->issuerNameHash, md, i))) goto err; /* Calculate the issuerKey hash, excluding tag and length */ if (!EVP_Digest(issuerKey->data, issuerKey->length, md, &i, dgst, NULL)) goto err; if (!(ASN1_OCTET_STRING_set(&cid->issuerKeyHash, md, i))) goto err; if (serialNumber) { if (ASN1_STRING_copy(&cid->serialNumber, serialNumber) == 0) goto err; } return cid; digerr: ERR_raise(ERR_LIB_OCSP, OCSP_R_DIGEST_ERR); err: OCSP_CERTID_free(cid); return NULL; } int OCSP_id_issuer_cmp(const OCSP_CERTID *a, const OCSP_CERTID *b) { int ret; ret = OBJ_cmp(a->hashAlgorithm.algorithm, b->hashAlgorithm.algorithm); if (ret) return ret; ret = ASN1_OCTET_STRING_cmp(&a->issuerNameHash, &b->issuerNameHash); if (ret) return ret; return ASN1_OCTET_STRING_cmp(&a->issuerKeyHash, &b->issuerKeyHash); } int OCSP_id_cmp(const OCSP_CERTID *a, const OCSP_CERTID *b) { int ret; ret = OCSP_id_issuer_cmp(a, b); if (ret) return ret; return ASN1_INTEGER_cmp(&a->serialNumber, &b->serialNumber); } IMPLEMENT_ASN1_DUP_FUNCTION(OCSP_CERTID)
3,269
27.684211
76
c
openssl
openssl-master/crypto/ocsp/ocsp_local.h
/* * Copyright 2015-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 "crypto/x509.h" /* for ossl_x509_add_cert_new() */ /*- CertID ::= SEQUENCE { * hashAlgorithm AlgorithmIdentifier, * issuerNameHash OCTET STRING, -- Hash of Issuer's DN * issuerKeyHash OCTET STRING, -- Hash of Issuers public key (excluding the tag & length fields) * serialNumber CertificateSerialNumber } */ struct ocsp_cert_id_st { X509_ALGOR hashAlgorithm; ASN1_OCTET_STRING issuerNameHash; ASN1_OCTET_STRING issuerKeyHash; ASN1_INTEGER serialNumber; }; /*- Request ::= SEQUENCE { * reqCert CertID, * singleRequestExtensions [0] EXPLICIT Extensions OPTIONAL } */ struct ocsp_one_request_st { OCSP_CERTID *reqCert; STACK_OF(X509_EXTENSION) *singleRequestExtensions; }; /*- TBSRequest ::= SEQUENCE { * version [0] EXPLICIT Version DEFAULT v1, * requestorName [1] EXPLICIT GeneralName OPTIONAL, * requestList SEQUENCE OF Request, * requestExtensions [2] EXPLICIT Extensions OPTIONAL } */ struct ocsp_req_info_st { ASN1_INTEGER *version; GENERAL_NAME *requestorName; STACK_OF(OCSP_ONEREQ) *requestList; STACK_OF(X509_EXTENSION) *requestExtensions; }; /*- Signature ::= SEQUENCE { * signatureAlgorithm AlgorithmIdentifier, * signature BIT STRING, * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } */ struct ocsp_signature_st { X509_ALGOR signatureAlgorithm; ASN1_BIT_STRING *signature; STACK_OF(X509) *certs; }; /*- OCSPRequest ::= SEQUENCE { * tbsRequest TBSRequest, * optionalSignature [0] EXPLICIT Signature OPTIONAL } */ struct ocsp_request_st { OCSP_REQINFO tbsRequest; OCSP_SIGNATURE *optionalSignature; /* OPTIONAL */ }; /*- OCSPResponseStatus ::= ENUMERATED { * successful (0), --Response has valid confirmations * malformedRequest (1), --Illegal confirmation request * internalError (2), --Internal error in issuer * tryLater (3), --Try again later * --(4) is not used * sigRequired (5), --Must sign the request * unauthorized (6) --Request unauthorized * } */ /*- ResponseBytes ::= SEQUENCE { * responseType OBJECT IDENTIFIER, * response OCTET STRING } */ struct ocsp_resp_bytes_st { ASN1_OBJECT *responseType; ASN1_OCTET_STRING *response; }; /*- OCSPResponse ::= SEQUENCE { * responseStatus OCSPResponseStatus, * responseBytes [0] EXPLICIT ResponseBytes OPTIONAL } */ struct ocsp_response_st { ASN1_ENUMERATED *responseStatus; OCSP_RESPBYTES *responseBytes; }; /*- ResponderID ::= CHOICE { * byName [1] Name, * byKey [2] KeyHash } */ struct ocsp_responder_id_st { int type; union { X509_NAME *byName; ASN1_OCTET_STRING *byKey; } value; }; /*- KeyHash ::= OCTET STRING --SHA-1 hash of responder's public key * --(excluding the tag and length fields) */ /*- RevokedInfo ::= SEQUENCE { * revocationTime GeneralizedTime, * revocationReason [0] EXPLICIT CRLReason OPTIONAL } */ struct ocsp_revoked_info_st { ASN1_GENERALIZEDTIME *revocationTime; ASN1_ENUMERATED *revocationReason; }; /*- CertStatus ::= CHOICE { * good [0] IMPLICIT NULL, * revoked [1] IMPLICIT RevokedInfo, * unknown [2] IMPLICIT UnknownInfo } */ struct ocsp_cert_status_st { int type; union { ASN1_NULL *good; OCSP_REVOKEDINFO *revoked; ASN1_NULL *unknown; } value; }; /*- SingleResponse ::= SEQUENCE { * certID CertID, * certStatus CertStatus, * thisUpdate GeneralizedTime, * nextUpdate [0] EXPLICIT GeneralizedTime OPTIONAL, * singleExtensions [1] EXPLICIT Extensions OPTIONAL } */ struct ocsp_single_response_st { OCSP_CERTID *certId; OCSP_CERTSTATUS *certStatus; ASN1_GENERALIZEDTIME *thisUpdate; ASN1_GENERALIZEDTIME *nextUpdate; STACK_OF(X509_EXTENSION) *singleExtensions; }; /*- ResponseData ::= SEQUENCE { * version [0] EXPLICIT Version DEFAULT v1, * responderID ResponderID, * producedAt GeneralizedTime, * responses SEQUENCE OF SingleResponse, * responseExtensions [1] EXPLICIT Extensions OPTIONAL } */ struct ocsp_response_data_st { ASN1_INTEGER *version; OCSP_RESPID responderId; ASN1_GENERALIZEDTIME *producedAt; STACK_OF(OCSP_SINGLERESP) *responses; STACK_OF(X509_EXTENSION) *responseExtensions; }; /*- BasicOCSPResponse ::= SEQUENCE { * tbsResponseData ResponseData, * signatureAlgorithm AlgorithmIdentifier, * signature BIT STRING, * certs [0] EXPLICIT SEQUENCE OF Certificate OPTIONAL } */ /* * Note 1: The value for "signature" is specified in the OCSP rfc2560 as * follows: "The value for the signature SHALL be computed on the hash of * the DER encoding ResponseData." This means that you must hash the * DER-encoded tbsResponseData, and then run it through a crypto-signing * function, which will (at least w/RSA) do a hash-'n'-private-encrypt * operation. This seems a bit odd, but that's the spec. Also note that * the data structures do not leave anywhere to independently specify the * algorithm used for the initial hash. So, we look at the * signature-specification algorithm, and try to do something intelligent. * -- Kathy Weinhold, CertCo */ /* * Note 2: It seems that the mentioned passage from RFC 2560 (section * 4.2.1) is open for interpretation. I've done tests against another * responder, and found that it doesn't do the double hashing that the RFC * seems to say one should. Therefore, all relevant functions take a flag * saying which variant should be used. -- Richard Levitte, OpenSSL team * and CeloCom */ struct ocsp_basic_response_st { OCSP_RESPDATA tbsResponseData; X509_ALGOR signatureAlgorithm; ASN1_BIT_STRING *signature; STACK_OF(X509) *certs; }; /*- * CrlID ::= SEQUENCE { * crlUrl [0] EXPLICIT IA5String OPTIONAL, * crlNum [1] EXPLICIT INTEGER OPTIONAL, * crlTime [2] EXPLICIT GeneralizedTime OPTIONAL } */ struct ocsp_crl_id_st { ASN1_IA5STRING *crlUrl; ASN1_INTEGER *crlNum; ASN1_GENERALIZEDTIME *crlTime; }; /*- * ServiceLocator ::= SEQUENCE { * issuer Name, * locator AuthorityInfoAccessSyntax OPTIONAL } */ struct ocsp_service_locator_st { X509_NAME *issuer; STACK_OF(ACCESS_DESCRIPTION) *locator; }; # define OCSP_REQUEST_sign(o, pkey, md, libctx, propq)\ ASN1_item_sign_ex(ASN1_ITEM_rptr(OCSP_REQINFO),\ &(o)->optionalSignature->signatureAlgorithm, NULL,\ (o)->optionalSignature->signature, &(o)->tbsRequest,\ NULL, pkey, md, libctx, propq) # define OCSP_BASICRESP_sign(o, pkey, md, d, libctx, propq)\ ASN1_item_sign_ex(ASN1_ITEM_rptr(OCSP_RESPDATA),\ &(o)->signatureAlgorithm, NULL,\ (o)->signature, &(o)->tbsResponseData,\ NULL, pkey, md, libctx, propq) # define OCSP_BASICRESP_sign_ctx(o, ctx, d)\ ASN1_item_sign_ctx(ASN1_ITEM_rptr(OCSP_RESPDATA),\ &(o)->signatureAlgorithm, NULL,\ (o)->signature, &(o)->tbsResponseData, ctx) # define OCSP_REQUEST_verify(a, r, libctx, propq)\ ASN1_item_verify_ex(ASN1_ITEM_rptr(OCSP_REQINFO),\ &(a)->optionalSignature->signatureAlgorithm,\ (a)->optionalSignature->signature, &(a)->tbsRequest,\ NULL, r, libctx, propq) # define OCSP_BASICRESP_verify(a, r, libctx, propq)\ ASN1_item_verify_ex(ASN1_ITEM_rptr(OCSP_RESPDATA),\ &(a)->signatureAlgorithm, (a)->signature,\ &(a)->tbsResponseData, NULL, r, libctx, propq)
8,859
34.870445
107
h
openssl
openssl-master/crypto/ocsp/ocsp_prn.c
/* * Copyright 2000-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/bio.h> #include <openssl/err.h> #include <openssl/ocsp.h> #include "ocsp_local.h" #include "internal/cryptlib.h" #include <openssl/pem.h> static int ocsp_certid_print(BIO *bp, OCSP_CERTID *a, int indent) { BIO_printf(bp, "%*sCertificate ID:\n", indent, ""); indent += 2; BIO_printf(bp, "%*sHash Algorithm: ", indent, ""); i2a_ASN1_OBJECT(bp, a->hashAlgorithm.algorithm); BIO_printf(bp, "\n%*sIssuer Name Hash: ", indent, ""); i2a_ASN1_STRING(bp, &a->issuerNameHash, 0); BIO_printf(bp, "\n%*sIssuer Key Hash: ", indent, ""); i2a_ASN1_STRING(bp, &a->issuerKeyHash, 0); BIO_printf(bp, "\n%*sSerial Number: ", indent, ""); i2a_ASN1_INTEGER(bp, &a->serialNumber); BIO_printf(bp, "\n"); return 1; } typedef struct { long t; const char *m; } OCSP_TBLSTR; static const char *do_table2string(long s, const OCSP_TBLSTR *ts, size_t len) { size_t i; for (i = 0; i < len; i++, ts++) if (ts->t == s) return ts->m; return "(UNKNOWN)"; } #define table2string(s, tbl) do_table2string(s, tbl, OSSL_NELEM(tbl)) const char *OCSP_response_status_str(long s) { static const OCSP_TBLSTR rstat_tbl[] = { {OCSP_RESPONSE_STATUS_SUCCESSFUL, "successful"}, {OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, "malformedrequest"}, {OCSP_RESPONSE_STATUS_INTERNALERROR, "internalerror"}, {OCSP_RESPONSE_STATUS_TRYLATER, "trylater"}, {OCSP_RESPONSE_STATUS_SIGREQUIRED, "sigrequired"}, {OCSP_RESPONSE_STATUS_UNAUTHORIZED, "unauthorized"} }; return table2string(s, rstat_tbl); } const char *OCSP_cert_status_str(long s) { static const OCSP_TBLSTR cstat_tbl[] = { {V_OCSP_CERTSTATUS_GOOD, "good"}, {V_OCSP_CERTSTATUS_REVOKED, "revoked"}, {V_OCSP_CERTSTATUS_UNKNOWN, "unknown"} }; return table2string(s, cstat_tbl); } const char *OCSP_crl_reason_str(long s) { static const OCSP_TBLSTR reason_tbl[] = { {OCSP_REVOKED_STATUS_UNSPECIFIED, "unspecified"}, {OCSP_REVOKED_STATUS_KEYCOMPROMISE, "keyCompromise"}, {OCSP_REVOKED_STATUS_CACOMPROMISE, "cACompromise"}, {OCSP_REVOKED_STATUS_AFFILIATIONCHANGED, "affiliationChanged"}, {OCSP_REVOKED_STATUS_SUPERSEDED, "superseded"}, {OCSP_REVOKED_STATUS_CESSATIONOFOPERATION, "cessationOfOperation"}, {OCSP_REVOKED_STATUS_CERTIFICATEHOLD, "certificateHold"}, {OCSP_REVOKED_STATUS_REMOVEFROMCRL, "removeFromCRL"} }; return table2string(s, reason_tbl); } int OCSP_REQUEST_print(BIO *bp, OCSP_REQUEST *o, unsigned long flags) { int i; long l; OCSP_CERTID *cid = NULL; OCSP_ONEREQ *one = NULL; OCSP_REQINFO *inf = &o->tbsRequest; OCSP_SIGNATURE *sig = o->optionalSignature; if (BIO_write(bp, "OCSP Request Data:\n", 19) <= 0) goto err; l = ASN1_INTEGER_get(inf->version); if (BIO_printf(bp, " Version: %lu (0x%lx)", l + 1, l) <= 0) goto err; if (inf->requestorName != NULL) { if (BIO_write(bp, "\n Requestor Name: ", 21) <= 0) goto err; GENERAL_NAME_print(bp, inf->requestorName); } if (BIO_write(bp, "\n Requestor List:\n", 21) <= 0) goto err; for (i = 0; i < sk_OCSP_ONEREQ_num(inf->requestList); i++) { one = sk_OCSP_ONEREQ_value(inf->requestList, i); cid = one->reqCert; ocsp_certid_print(bp, cid, 8); if (!X509V3_extensions_print(bp, "Request Single Extensions", one->singleRequestExtensions, flags, 8)) goto err; } if (!X509V3_extensions_print(bp, "Request Extensions", inf->requestExtensions, flags, 4)) goto err; if (sig) { X509_signature_print(bp, &sig->signatureAlgorithm, sig->signature); for (i = 0; i < sk_X509_num(sig->certs); i++) { X509_print(bp, sk_X509_value(sig->certs, i)); PEM_write_bio_X509(bp, sk_X509_value(sig->certs, i)); } } return 1; err: return 0; } int OCSP_RESPONSE_print(BIO *bp, OCSP_RESPONSE *o, unsigned long flags) { int i, ret = 0; long l; OCSP_CERTID *cid = NULL; OCSP_BASICRESP *br = NULL; OCSP_RESPID *rid = NULL; OCSP_RESPDATA *rd = NULL; OCSP_CERTSTATUS *cst = NULL; OCSP_REVOKEDINFO *rev = NULL; OCSP_SINGLERESP *single = NULL; OCSP_RESPBYTES *rb = o->responseBytes; if (BIO_puts(bp, "OCSP Response Data:\n") <= 0) goto err; l = ASN1_ENUMERATED_get(o->responseStatus); if (BIO_printf(bp, " OCSP Response Status: %s (0x%lx)\n", OCSP_response_status_str(l), l) <= 0) goto err; if (rb == NULL) return 1; if (BIO_puts(bp, " Response Type: ") <= 0) goto err; if (i2a_ASN1_OBJECT(bp, rb->responseType) <= 0) goto err; if (OBJ_obj2nid(rb->responseType) != NID_id_pkix_OCSP_basic) { BIO_puts(bp, " (unknown response type)\n"); return 1; } if ((br = OCSP_response_get1_basic(o)) == NULL) goto err; rd = &br->tbsResponseData; l = ASN1_INTEGER_get(rd->version); if (BIO_printf(bp, "\n Version: %lu (0x%lx)\n", l + 1, l) <= 0) goto err; if (BIO_puts(bp, " Responder Id: ") <= 0) goto err; rid = &rd->responderId; switch (rid->type) { case V_OCSP_RESPID_NAME: X509_NAME_print_ex(bp, rid->value.byName, 0, XN_FLAG_ONELINE); break; case V_OCSP_RESPID_KEY: i2a_ASN1_STRING(bp, rid->value.byKey, 0); break; } if (BIO_printf(bp, "\n Produced At: ") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, rd->producedAt)) goto err; if (BIO_printf(bp, "\n Responses:\n") <= 0) goto err; for (i = 0; i < sk_OCSP_SINGLERESP_num(rd->responses); i++) { if (!sk_OCSP_SINGLERESP_value(rd->responses, i)) continue; single = sk_OCSP_SINGLERESP_value(rd->responses, i); cid = single->certId; if (ocsp_certid_print(bp, cid, 4) <= 0) goto err; cst = single->certStatus; if (BIO_printf(bp, " Cert Status: %s", OCSP_cert_status_str(cst->type)) <= 0) goto err; if (cst->type == V_OCSP_CERTSTATUS_REVOKED) { rev = cst->value.revoked; if (BIO_printf(bp, "\n Revocation Time: ") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, rev->revocationTime)) goto err; if (rev->revocationReason) { l = ASN1_ENUMERATED_get(rev->revocationReason); if (BIO_printf(bp, "\n Revocation Reason: %s (0x%lx)", OCSP_crl_reason_str(l), l) <= 0) goto err; } } if (BIO_printf(bp, "\n This Update: ") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, single->thisUpdate)) goto err; if (single->nextUpdate) { if (BIO_printf(bp, "\n Next Update: ") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, single->nextUpdate)) goto err; } if (BIO_write(bp, "\n", 1) <= 0) goto err; if (!X509V3_extensions_print(bp, "Response Single Extensions", single->singleExtensions, flags, 8)) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (!X509V3_extensions_print(bp, "Response Extensions", rd->responseExtensions, flags, 4)) goto err; if (X509_signature_print(bp, &br->signatureAlgorithm, br->signature) <= 0) goto err; for (i = 0; i < sk_X509_num(br->certs); i++) { X509_print(bp, sk_X509_value(br->certs, i)); PEM_write_bio_X509(bp, sk_X509_value(br->certs, i)); } ret = 1; err: OCSP_BASICRESP_free(br); return ret; }
8,451
33.218623
78
c
openssl
openssl-master/crypto/ocsp/ocsp_srv.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/ocsp.h> #include "ocsp_local.h" /* * Utility functions related to sending OCSP responses and extracting * relevant information from the request. */ int OCSP_request_onereq_count(OCSP_REQUEST *req) { return sk_OCSP_ONEREQ_num(req->tbsRequest.requestList); } OCSP_ONEREQ *OCSP_request_onereq_get0(OCSP_REQUEST *req, int i) { return sk_OCSP_ONEREQ_value(req->tbsRequest.requestList, i); } OCSP_CERTID *OCSP_onereq_get0_id(OCSP_ONEREQ *one) { return one->reqCert; } int OCSP_id_get0_info(ASN1_OCTET_STRING **piNameHash, ASN1_OBJECT **pmd, ASN1_OCTET_STRING **pikeyHash, ASN1_INTEGER **pserial, OCSP_CERTID *cid) { if (!cid) return 0; if (pmd) *pmd = cid->hashAlgorithm.algorithm; if (piNameHash) *piNameHash = &cid->issuerNameHash; if (pikeyHash) *pikeyHash = &cid->issuerKeyHash; if (pserial) *pserial = &cid->serialNumber; return 1; } int OCSP_request_is_signed(OCSP_REQUEST *req) { if (req->optionalSignature) return 1; return 0; } /* Create an OCSP response and encode an optional basic response */ OCSP_RESPONSE *OCSP_response_create(int status, OCSP_BASICRESP *bs) { OCSP_RESPONSE *rsp = NULL; if ((rsp = OCSP_RESPONSE_new()) == NULL) goto err; if (!(ASN1_ENUMERATED_set(rsp->responseStatus, status))) goto err; if (!bs) return rsp; if ((rsp->responseBytes = OCSP_RESPBYTES_new()) == NULL) goto err; rsp->responseBytes->responseType = OBJ_nid2obj(NID_id_pkix_OCSP_basic); if (!ASN1_item_pack (bs, ASN1_ITEM_rptr(OCSP_BASICRESP), &rsp->responseBytes->response)) goto err; return rsp; err: OCSP_RESPONSE_free(rsp); return NULL; } OCSP_SINGLERESP *OCSP_basic_add1_status(OCSP_BASICRESP *rsp, OCSP_CERTID *cid, int status, int reason, ASN1_TIME *revtime, ASN1_TIME *thisupd, ASN1_TIME *nextupd) { OCSP_SINGLERESP *single = NULL; OCSP_CERTSTATUS *cs; OCSP_REVOKEDINFO *ri; if (rsp->tbsResponseData.responses == NULL && (rsp->tbsResponseData.responses = sk_OCSP_SINGLERESP_new_null()) == NULL) goto err; if ((single = OCSP_SINGLERESP_new()) == NULL) goto err; if (!ASN1_TIME_to_generalizedtime(thisupd, &single->thisUpdate)) goto err; if (nextupd && !ASN1_TIME_to_generalizedtime(nextupd, &single->nextUpdate)) goto err; OCSP_CERTID_free(single->certId); if ((single->certId = OCSP_CERTID_dup(cid)) == NULL) goto err; cs = single->certStatus; switch (cs->type = status) { case V_OCSP_CERTSTATUS_REVOKED: if (!revtime) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NO_REVOKED_TIME); goto err; } if ((cs->value.revoked = ri = OCSP_REVOKEDINFO_new()) == NULL) goto err; if (!ASN1_TIME_to_generalizedtime(revtime, &ri->revocationTime)) goto err; if (reason != OCSP_REVOKED_STATUS_NOSTATUS) { if ((ri->revocationReason = ASN1_ENUMERATED_new()) == NULL) goto err; if (!(ASN1_ENUMERATED_set(ri->revocationReason, reason))) goto err; } break; case V_OCSP_CERTSTATUS_GOOD: if ((cs->value.good = ASN1_NULL_new()) == NULL) goto err; break; case V_OCSP_CERTSTATUS_UNKNOWN: if ((cs->value.unknown = ASN1_NULL_new()) == NULL) goto err; break; default: goto err; } if (!(sk_OCSP_SINGLERESP_push(rsp->tbsResponseData.responses, single))) goto err; return single; err: OCSP_SINGLERESP_free(single); return NULL; } /* Add a certificate to an OCSP request */ int OCSP_basic_add1_cert(OCSP_BASICRESP *resp, X509 *cert) { return ossl_x509_add_cert_new(&resp->certs, cert, X509_ADD_FLAG_UP_REF); } /* * Sign an OCSP response using the parameters contained in the digest context, * set the responderID to the subject name in the signer's certificate, and * include one or more optional certificates in the response. */ int OCSP_basic_sign_ctx(OCSP_BASICRESP *brsp, X509 *signer, EVP_MD_CTX *ctx, STACK_OF(X509) *certs, unsigned long flags) { OCSP_RESPID *rid; EVP_PKEY *pkey; if (ctx == NULL || EVP_MD_CTX_get_pkey_ctx(ctx) == NULL) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NO_SIGNER_KEY); goto err; } pkey = EVP_PKEY_CTX_get0_pkey(EVP_MD_CTX_get_pkey_ctx(ctx)); if (pkey == NULL || !X509_check_private_key(signer, pkey)) { ERR_raise(ERR_LIB_OCSP, OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE); goto err; } if (!(flags & OCSP_NOCERTS)) { if (!OCSP_basic_add1_cert(brsp, signer) || !X509_add_certs(brsp->certs, certs, X509_ADD_FLAG_UP_REF)) goto err; } rid = &brsp->tbsResponseData.responderId; if (flags & OCSP_RESPID_KEY) { if (!OCSP_RESPID_set_by_key(rid, signer)) goto err; } else if (!OCSP_RESPID_set_by_name(rid, signer)) { goto err; } if (!(flags & OCSP_NOTIME) && !X509_gmtime_adj(brsp->tbsResponseData.producedAt, 0)) goto err; /* * Right now, I think that not doing double hashing is the right thing. * -- Richard Levitte */ if (!OCSP_BASICRESP_sign_ctx(brsp, ctx, 0)) goto err; return 1; err: return 0; } int OCSP_basic_sign(OCSP_BASICRESP *brsp, X509 *signer, EVP_PKEY *key, const EVP_MD *dgst, STACK_OF(X509) *certs, unsigned long flags) { EVP_MD_CTX *ctx = EVP_MD_CTX_new(); EVP_PKEY_CTX *pkctx = NULL; int i; if (ctx == NULL) return 0; if (!EVP_DigestSignInit_ex(ctx, &pkctx, EVP_MD_get0_name(dgst), signer->libctx, signer->propq, key, NULL)) { EVP_MD_CTX_free(ctx); return 0; } i = OCSP_basic_sign_ctx(brsp, signer, ctx, certs, flags); EVP_MD_CTX_free(ctx); return i; } int OCSP_RESPID_set_by_name(OCSP_RESPID *respid, X509 *cert) { if (!X509_NAME_set(&respid->value.byName, X509_get_subject_name(cert))) return 0; respid->type = V_OCSP_RESPID_NAME; return 1; } int OCSP_RESPID_set_by_key_ex(OCSP_RESPID *respid, X509 *cert, OSSL_LIB_CTX *libctx, const char *propq) { ASN1_OCTET_STRING *byKey = NULL; unsigned char md[SHA_DIGEST_LENGTH]; EVP_MD *sha1 = EVP_MD_fetch(libctx, "SHA1", propq); int ret = 0; if (sha1 == NULL) return 0; /* RFC2560 requires SHA1 */ if (!X509_pubkey_digest(cert, sha1, md, NULL)) goto err; byKey = ASN1_OCTET_STRING_new(); if (byKey == NULL) goto err; if (!(ASN1_OCTET_STRING_set(byKey, md, SHA_DIGEST_LENGTH))) { ASN1_OCTET_STRING_free(byKey); goto err; } respid->type = V_OCSP_RESPID_KEY; respid->value.byKey = byKey; ret = 1; err: EVP_MD_free(sha1); return ret; } int OCSP_RESPID_set_by_key(OCSP_RESPID *respid, X509 *cert) { if (cert == NULL) return 0; return OCSP_RESPID_set_by_key_ex(respid, cert, cert->libctx, cert->propq); } int OCSP_RESPID_match_ex(OCSP_RESPID *respid, X509 *cert, OSSL_LIB_CTX *libctx, const char *propq) { EVP_MD *sha1 = NULL; int ret = 0; if (respid->type == V_OCSP_RESPID_KEY) { unsigned char md[SHA_DIGEST_LENGTH]; sha1 = EVP_MD_fetch(libctx, "SHA1", propq); if (sha1 == NULL) goto err; if (respid->value.byKey == NULL) goto err; /* RFC2560 requires SHA1 */ if (!X509_pubkey_digest(cert, sha1, md, NULL)) goto err; ret = (ASN1_STRING_length(respid->value.byKey) == SHA_DIGEST_LENGTH) && (memcmp(ASN1_STRING_get0_data(respid->value.byKey), md, SHA_DIGEST_LENGTH) == 0); } else if (respid->type == V_OCSP_RESPID_NAME) { if (respid->value.byName == NULL) return 0; return X509_NAME_cmp(respid->value.byName, X509_get_subject_name(cert)) == 0; } err: EVP_MD_free(sha1); return ret; } int OCSP_RESPID_match(OCSP_RESPID *respid, X509 *cert) { if (cert == NULL) return 0; return OCSP_RESPID_match_ex(respid, cert, cert->libctx, cert->propq); }
9,152
26.905488
79
c
openssl
openssl-master/crypto/ocsp/ocsp_vfy.c
/* * Copyright 2001-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/ocsp.h> #include <openssl/err.h> #include "internal/sizes.h" #include "ocsp_local.h" static int ocsp_find_signer(X509 **psigner, OCSP_BASICRESP *bs, STACK_OF(X509) *certs, unsigned long flags); static X509 *ocsp_find_signer_sk(STACK_OF(X509) *certs, OCSP_RESPID *id); static int ocsp_check_issuer(OCSP_BASICRESP *bs, STACK_OF(X509) *chain); static int ocsp_check_ids(STACK_OF(OCSP_SINGLERESP) *sresp, OCSP_CERTID **ret); static int ocsp_match_issuerid(X509 *cert, OCSP_CERTID *cid, STACK_OF(OCSP_SINGLERESP) *sresp); static int ocsp_check_delegated(X509 *x); static int ocsp_req_find_signer(X509 **psigner, OCSP_REQUEST *req, const X509_NAME *nm, STACK_OF(X509) *certs, unsigned long flags); /* Returns 1 on success, 0 on failure, or -1 on fatal error */ static int ocsp_verify_signer(X509 *signer, int response, X509_STORE *st, unsigned long flags, STACK_OF(X509) *untrusted, STACK_OF(X509) **chain) { X509_STORE_CTX *ctx = X509_STORE_CTX_new(); X509_VERIFY_PARAM *vp; int ret = -1; if (ctx == NULL) { ERR_raise(ERR_LIB_OCSP, ERR_R_X509_LIB); goto end; } if (!X509_STORE_CTX_init(ctx, st, signer, untrusted)) { ERR_raise(ERR_LIB_OCSP, ERR_R_X509_LIB); goto end; } if ((vp = X509_STORE_CTX_get0_param(ctx)) == NULL) goto end; if ((flags & OCSP_PARTIAL_CHAIN) != 0) X509_VERIFY_PARAM_set_flags(vp, X509_V_FLAG_PARTIAL_CHAIN); if (response && X509_get_ext_by_NID(signer, NID_id_pkix_OCSP_noCheck, -1) >= 0) /* * Locally disable revocation status checking for OCSP responder cert. * Done here for CRLs; should be done also for OCSP-based checks. */ X509_VERIFY_PARAM_clear_flags(vp, X509_V_FLAG_CRL_CHECK); X509_STORE_CTX_set_purpose(ctx, X509_PURPOSE_OCSP_HELPER); X509_STORE_CTX_set_trust(ctx, X509_TRUST_OCSP_REQUEST); ret = X509_verify_cert(ctx); if (ret <= 0) { int err = X509_STORE_CTX_get_error(ctx); ERR_raise_data(ERR_LIB_OCSP, OCSP_R_CERTIFICATE_VERIFY_ERROR, "Verify error: %s", X509_verify_cert_error_string(err)); goto end; } if (chain != NULL) *chain = X509_STORE_CTX_get1_chain(ctx); end: X509_STORE_CTX_free(ctx); return ret; } static int ocsp_verify(OCSP_REQUEST *req, OCSP_BASICRESP *bs, X509 *signer, unsigned long flags) { EVP_PKEY *skey; int ret = 1; if ((flags & OCSP_NOSIGS) == 0) { if ((skey = X509_get0_pubkey(signer)) == NULL) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NO_SIGNER_KEY); return -1; } if (req != NULL) ret = OCSP_REQUEST_verify(req, skey, signer->libctx, signer->propq); else ret = OCSP_BASICRESP_verify(bs, skey, signer->libctx, signer->propq); if (ret <= 0) ERR_raise(ERR_LIB_OCSP, OCSP_R_SIGNATURE_FAILURE); } return ret; } /* Verify a basic response message */ int OCSP_basic_verify(OCSP_BASICRESP *bs, STACK_OF(X509) *certs, X509_STORE *st, unsigned long flags) { X509 *signer, *x; STACK_OF(X509) *chain = NULL; STACK_OF(X509) *untrusted = NULL; int ret = ocsp_find_signer(&signer, bs, certs, flags); if (ret == 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND); goto end; } if ((ret == 2) && (flags & OCSP_TRUSTOTHER) != 0) flags |= OCSP_NOVERIFY; if ((ret = ocsp_verify(NULL, bs, signer, flags)) <= 0) goto end; if ((flags & OCSP_NOVERIFY) == 0) { ret = -1; if ((flags & OCSP_NOCHAIN) == 0) { if ((untrusted = sk_X509_dup(bs->certs)) == NULL) goto end; if (!X509_add_certs(untrusted, certs, X509_ADD_FLAG_DEFAULT)) goto end; } ret = ocsp_verify_signer(signer, 1, st, flags, untrusted, &chain); if (ret <= 0) goto end; if ((flags & OCSP_NOCHECKS) != 0) { ret = 1; goto end; } /* * At this point we have a valid certificate chain need to verify it * against the OCSP issuer criteria. */ ret = ocsp_check_issuer(bs, chain); /* If fatal error or valid match then finish */ if (ret != 0) goto end; /* * Easy case: explicitly trusted. Get root CA and check for explicit * trust */ if ((flags & OCSP_NOEXPLICIT) != 0) goto end; x = sk_X509_value(chain, sk_X509_num(chain) - 1); if (X509_check_trust(x, NID_OCSP_sign, 0) != X509_TRUST_TRUSTED) { ERR_raise(ERR_LIB_OCSP, OCSP_R_ROOT_CA_NOT_TRUSTED); ret = 0; goto end; } ret = 1; } end: OSSL_STACK_OF_X509_free(chain); sk_X509_free(untrusted); return ret; } int OCSP_resp_get0_signer(OCSP_BASICRESP *bs, X509 **signer, STACK_OF(X509) *extra_certs) { return ocsp_find_signer(signer, bs, extra_certs, 0) > 0; } static int ocsp_find_signer(X509 **psigner, OCSP_BASICRESP *bs, STACK_OF(X509) *certs, unsigned long flags) { X509 *signer; OCSP_RESPID *rid = &bs->tbsResponseData.responderId; if ((signer = ocsp_find_signer_sk(certs, rid)) != NULL) { *psigner = signer; return 2; } if ((flags & OCSP_NOINTERN) == 0 && (signer = ocsp_find_signer_sk(bs->certs, rid))) { *psigner = signer; return 1; } /* Maybe lookup from store if by subject name */ *psigner = NULL; return 0; } static X509 *ocsp_find_signer_sk(STACK_OF(X509) *certs, OCSP_RESPID *id) { int i, r; unsigned char tmphash[SHA_DIGEST_LENGTH], *keyhash; EVP_MD *md; X509 *x; /* Easy if lookup by name */ if (id->type == V_OCSP_RESPID_NAME) return X509_find_by_subject(certs, id->value.byName); /* Lookup by key hash */ /* If key hash isn't SHA1 length then forget it */ if (id->value.byKey->length != SHA_DIGEST_LENGTH) return NULL; keyhash = id->value.byKey->data; /* Calculate hash of each key and compare */ for (i = 0; i < sk_X509_num(certs); i++) { if ((x = sk_X509_value(certs, i)) != NULL) { if ((md = EVP_MD_fetch(x->libctx, SN_sha1, x->propq)) == NULL) break; r = X509_pubkey_digest(x, md, tmphash, NULL); EVP_MD_free(md); if (!r) break; if (memcmp(keyhash, tmphash, SHA_DIGEST_LENGTH) == 0) return x; } } return NULL; } static int ocsp_check_issuer(OCSP_BASICRESP *bs, STACK_OF(X509) *chain) { STACK_OF(OCSP_SINGLERESP) *sresp = bs->tbsResponseData.responses; X509 *signer, *sca; OCSP_CERTID *caid = NULL; int ret; if (sk_X509_num(chain) <= 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_NO_CERTIFICATES_IN_CHAIN); return -1; } /* See if the issuer IDs match. */ ret = ocsp_check_ids(sresp, &caid); /* If ID mismatch or other error then return */ if (ret <= 0) return ret; signer = sk_X509_value(chain, 0); /* Check to see if OCSP responder CA matches request CA */ if (sk_X509_num(chain) > 1) { sca = sk_X509_value(chain, 1); ret = ocsp_match_issuerid(sca, caid, sresp); if (ret < 0) return ret; if (ret != 0) { /* We have a match, if extensions OK then success */ if (ocsp_check_delegated(signer)) return 1; return 0; } } /* Otherwise check if OCSP request signed directly by request CA */ return ocsp_match_issuerid(signer, caid, sresp); } /* * Check the issuer certificate IDs for equality. If there is a mismatch with * the same algorithm then there's no point trying to match any certificates * against the issuer. If the issuer IDs all match then we just need to check * equality against one of them. */ static int ocsp_check_ids(STACK_OF(OCSP_SINGLERESP) *sresp, OCSP_CERTID **ret) { OCSP_CERTID *tmpid, *cid; int i, idcount; idcount = sk_OCSP_SINGLERESP_num(sresp); if (idcount <= 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_RESPONSE_CONTAINS_NO_REVOCATION_DATA); return -1; } cid = sk_OCSP_SINGLERESP_value(sresp, 0)->certId; *ret = NULL; for (i = 1; i < idcount; i++) { tmpid = sk_OCSP_SINGLERESP_value(sresp, i)->certId; /* Check to see if IDs match */ if (OCSP_id_issuer_cmp(cid, tmpid)) { /* If algorithm mismatch let caller deal with it */ if (OBJ_cmp(tmpid->hashAlgorithm.algorithm, cid->hashAlgorithm.algorithm)) return 2; /* Else mismatch */ return 0; } } /* All IDs match: only need to check one ID */ *ret = cid; return 1; } /* * Match the certificate issuer ID. * Returns -1 on fatal error, 0 if there is no match and 1 if there is a match. */ static int ocsp_match_issuerid(X509 *cert, OCSP_CERTID *cid, STACK_OF(OCSP_SINGLERESP) *sresp) { int ret = -1; EVP_MD *dgst = NULL; /* If only one ID to match then do it */ if (cid != NULL) { char name[OSSL_MAX_NAME_SIZE]; const X509_NAME *iname; int mdlen; unsigned char md[EVP_MAX_MD_SIZE]; OBJ_obj2txt(name, sizeof(name), cid->hashAlgorithm.algorithm, 0); (void)ERR_set_mark(); dgst = EVP_MD_fetch(NULL, name, NULL); if (dgst == NULL) dgst = (EVP_MD *)EVP_get_digestbyname(name); if (dgst == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_OCSP, OCSP_R_UNKNOWN_MESSAGE_DIGEST); goto end; } (void)ERR_pop_to_mark(); mdlen = EVP_MD_get_size(dgst); if (mdlen < 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_DIGEST_SIZE_ERR); goto end; } if (cid->issuerNameHash.length != mdlen || cid->issuerKeyHash.length != mdlen) { ret = 0; goto end; } iname = X509_get_subject_name(cert); if (!X509_NAME_digest(iname, dgst, md, NULL)) goto end; if (memcmp(md, cid->issuerNameHash.data, mdlen) != 0) { ret = 0; goto end; } if (!X509_pubkey_digest(cert, dgst, md, NULL)) { ERR_raise(ERR_LIB_OCSP, OCSP_R_DIGEST_ERR); goto end; } ret = memcmp(md, cid->issuerKeyHash.data, mdlen) == 0; goto end; } else { /* We have to match the whole lot */ int i; OCSP_CERTID *tmpid; for (i = 0; i < sk_OCSP_SINGLERESP_num(sresp); i++) { tmpid = sk_OCSP_SINGLERESP_value(sresp, i)->certId; ret = ocsp_match_issuerid(cert, tmpid, NULL); if (ret <= 0) return ret; } } return 1; end: EVP_MD_free(dgst); return ret; } static int ocsp_check_delegated(X509 *x) { if ((X509_get_extension_flags(x) & EXFLAG_XKUSAGE) && (X509_get_extended_key_usage(x) & XKU_OCSP_SIGN)) return 1; ERR_raise(ERR_LIB_OCSP, OCSP_R_MISSING_OCSPSIGNING_USAGE); return 0; } /* * Verify an OCSP request. This is much easier than OCSP response verify. * Just find the signer's certificate and verify it against a given trust value. * Returns 1 on success, 0 on failure and on fatal error. */ int OCSP_request_verify(OCSP_REQUEST *req, STACK_OF(X509) *certs, X509_STORE *store, unsigned long flags) { X509 *signer; const X509_NAME *nm; GENERAL_NAME *gen; int ret; if (!req->optionalSignature) { ERR_raise(ERR_LIB_OCSP, OCSP_R_REQUEST_NOT_SIGNED); return 0; } gen = req->tbsRequest.requestorName; if (!gen || gen->type != GEN_DIRNAME) { ERR_raise(ERR_LIB_OCSP, OCSP_R_UNSUPPORTED_REQUESTORNAME_TYPE); return 0; /* not returning -1 here for backward compatibility*/ } nm = gen->d.directoryName; ret = ocsp_req_find_signer(&signer, req, nm, certs, flags); if (ret <= 0) { ERR_raise(ERR_LIB_OCSP, OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND); return 0; /* not returning -1 here for backward compatibility*/ } if ((ret == 2) && (flags & OCSP_TRUSTOTHER) != 0) flags |= OCSP_NOVERIFY; if ((ret = ocsp_verify(req, NULL, signer, flags)) <= 0) return 0; /* not returning 'ret' here for backward compatibility*/ if ((flags & OCSP_NOVERIFY) != 0) return 1; return ocsp_verify_signer(signer, 0, store, flags, (flags & OCSP_NOCHAIN) != 0 ? NULL : req->optionalSignature->certs, NULL) > 0; /* using '> 0' here to avoid breaking backward compatibility returning -1 */ } static int ocsp_req_find_signer(X509 **psigner, OCSP_REQUEST *req, const X509_NAME *nm, STACK_OF(X509) *certs, unsigned long flags) { X509 *signer; if ((flags & OCSP_NOINTERN) == 0) { signer = X509_find_by_subject(req->optionalSignature->certs, nm); if (signer != NULL) { *psigner = signer; return 1; } } if ((signer = X509_find_by_subject(certs, nm)) != NULL) { *psigner = signer; return 2; } return 0; }
14,084
30.938776
81
c
openssl
openssl-master/crypto/ocsp/v3_ocsp.c
/* * Copyright 2000-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/ocsp.h> #include "ocsp_local.h" #include <openssl/x509v3.h> #include "../x509/ext_dat.h" /* * OCSP extensions and a couple of CRL entry extensions */ static int i2r_ocsp_crlid(const X509V3_EXT_METHOD *method, void *nonce, BIO *out, int indent); static int i2r_ocsp_acutoff(const X509V3_EXT_METHOD *method, void *nonce, BIO *out, int indent); static int i2r_object(const X509V3_EXT_METHOD *method, void *obj, BIO *out, int indent); static void *ocsp_nonce_new(void); static int i2d_ocsp_nonce(const void *a, unsigned char **pp); static void *d2i_ocsp_nonce(void *a, const unsigned char **pp, long length); static void ocsp_nonce_free(void *a); static int i2r_ocsp_nonce(const X509V3_EXT_METHOD *method, void *nonce, BIO *out, int indent); static int i2r_ocsp_nocheck(const X509V3_EXT_METHOD *method, void *nocheck, BIO *out, int indent); static void *s2i_ocsp_nocheck(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *str); static int i2r_ocsp_serviceloc(const X509V3_EXT_METHOD *method, void *in, BIO *bp, int ind); const X509V3_EXT_METHOD ossl_v3_ocsp_crlid = { NID_id_pkix_OCSP_CrlID, 0, ASN1_ITEM_ref(OCSP_CRLID), 0, 0, 0, 0, 0, 0, 0, 0, i2r_ocsp_crlid, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_ocsp_acutoff = { NID_id_pkix_OCSP_archiveCutoff, 0, ASN1_ITEM_ref(ASN1_GENERALIZEDTIME), 0, 0, 0, 0, 0, 0, 0, 0, i2r_ocsp_acutoff, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_crl_invdate = { NID_invalidity_date, 0, ASN1_ITEM_ref(ASN1_GENERALIZEDTIME), 0, 0, 0, 0, 0, 0, 0, 0, i2r_ocsp_acutoff, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_crl_hold = { NID_hold_instruction_code, 0, ASN1_ITEM_ref(ASN1_OBJECT), 0, 0, 0, 0, 0, 0, 0, 0, i2r_object, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_ocsp_nonce = { NID_id_pkix_OCSP_Nonce, 0, NULL, ocsp_nonce_new, ocsp_nonce_free, d2i_ocsp_nonce, i2d_ocsp_nonce, 0, 0, 0, 0, i2r_ocsp_nonce, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_ocsp_nocheck = { NID_id_pkix_OCSP_noCheck, 0, ASN1_ITEM_ref(ASN1_NULL), 0, 0, 0, 0, 0, s2i_ocsp_nocheck, 0, 0, i2r_ocsp_nocheck, 0, NULL }; const X509V3_EXT_METHOD ossl_v3_ocsp_serviceloc = { NID_id_pkix_OCSP_serviceLocator, 0, ASN1_ITEM_ref(OCSP_SERVICELOC), 0, 0, 0, 0, 0, 0, 0, 0, i2r_ocsp_serviceloc, 0, NULL }; static int i2r_ocsp_crlid(const X509V3_EXT_METHOD *method, void *in, BIO *bp, int ind) { OCSP_CRLID *a = in; if (a->crlUrl) { if (BIO_printf(bp, "%*scrlUrl: ", ind, "") <= 0) goto err; if (!ASN1_STRING_print(bp, (ASN1_STRING *)a->crlUrl)) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (a->crlNum) { if (BIO_printf(bp, "%*scrlNum: ", ind, "") <= 0) goto err; if (i2a_ASN1_INTEGER(bp, a->crlNum) <= 0) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } if (a->crlTime) { if (BIO_printf(bp, "%*scrlTime: ", ind, "") <= 0) goto err; if (!ASN1_GENERALIZEDTIME_print(bp, a->crlTime)) goto err; if (BIO_write(bp, "\n", 1) <= 0) goto err; } return 1; err: return 0; } static int i2r_ocsp_acutoff(const X509V3_EXT_METHOD *method, void *cutoff, BIO *bp, int ind) { if (BIO_printf(bp, "%*s", ind, "") <= 0) return 0; if (!ASN1_GENERALIZEDTIME_print(bp, cutoff)) return 0; return 1; } static int i2r_object(const X509V3_EXT_METHOD *method, void *oid, BIO *bp, int ind) { if (BIO_printf(bp, "%*s", ind, "") <= 0) return 0; if (i2a_ASN1_OBJECT(bp, oid) <= 0) return 0; return 1; } /* * OCSP nonce. This is needs special treatment because it doesn't have an * ASN1 encoding at all: it just contains arbitrary data. */ static void *ocsp_nonce_new(void) { return ASN1_OCTET_STRING_new(); } static int i2d_ocsp_nonce(const void *a, unsigned char **pp) { const ASN1_OCTET_STRING *os = a; if (pp) { memcpy(*pp, os->data, os->length); *pp += os->length; } return os->length; } static void *d2i_ocsp_nonce(void *a, const unsigned char **pp, long length) { ASN1_OCTET_STRING *os, **pos; pos = a; if (pos == NULL || *pos == NULL) { os = ASN1_OCTET_STRING_new(); if (os == NULL) goto err; } else { os = *pos; } if (!ASN1_OCTET_STRING_set(os, *pp, length)) goto err; *pp += length; if (pos) *pos = os; return os; err: if ((pos == NULL) || (*pos != os)) ASN1_OCTET_STRING_free(os); ERR_raise(ERR_LIB_OCSP, ERR_R_ASN1_LIB); return NULL; } static void ocsp_nonce_free(void *a) { ASN1_OCTET_STRING_free(a); } static int i2r_ocsp_nonce(const X509V3_EXT_METHOD *method, void *nonce, BIO *out, int indent) { if (BIO_printf(out, "%*s", indent, "") <= 0) return 0; if (i2a_ASN1_STRING(out, nonce, V_ASN1_OCTET_STRING) <= 0) return 0; return 1; } /* Nocheck is just a single NULL. Don't print anything and always set it */ static int i2r_ocsp_nocheck(const X509V3_EXT_METHOD *method, void *nocheck, BIO *out, int indent) { return 1; } static void *s2i_ocsp_nocheck(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *str) { return ASN1_NULL_new(); } static int i2r_ocsp_serviceloc(const X509V3_EXT_METHOD *method, void *in, BIO *bp, int ind) { int i; OCSP_SERVICELOC *a = in; ACCESS_DESCRIPTION *ad; if (BIO_printf(bp, "%*sIssuer: ", ind, "") <= 0) goto err; if (X509_NAME_print_ex(bp, a->issuer, 0, XN_FLAG_ONELINE) <= 0) goto err; for (i = 0; i < sk_ACCESS_DESCRIPTION_num(a->locator); i++) { ad = sk_ACCESS_DESCRIPTION_value(a->locator, i); if (BIO_printf(bp, "\n%*s", (2 * ind), "") <= 0) goto err; if (i2a_ASN1_OBJECT(bp, ad->method) <= 0) goto err; if (BIO_puts(bp, " - ") <= 0) goto err; if (GENERAL_NAME_print(bp, ad->location) <= 0) goto err; } return 1; err: return 0; }
7,020
25.49434
77
c
openssl
openssl-master/crypto/pem/pem_all.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * 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/bio.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pkcs7.h> #include <openssl/pem.h> #include <openssl/rsa.h> #include <openssl/dsa.h> #include <openssl/dh.h> #include "pem_local.h" static RSA *pkey_get_rsa(EVP_PKEY *key, RSA **rsa); #ifndef OPENSSL_NO_DSA static DSA *pkey_get_dsa(EVP_PKEY *key, DSA **dsa); #endif #ifndef OPENSSL_NO_EC static EC_KEY *pkey_get_eckey(EVP_PKEY *key, EC_KEY **eckey); #endif IMPLEMENT_PEM_rw(X509_REQ, X509_REQ, PEM_STRING_X509_REQ, X509_REQ) IMPLEMENT_PEM_write(X509_REQ_NEW, X509_REQ, PEM_STRING_X509_REQ_OLD, X509_REQ) IMPLEMENT_PEM_rw(X509_CRL, X509_CRL, PEM_STRING_X509_CRL, X509_CRL) IMPLEMENT_PEM_rw(X509_PUBKEY, X509_PUBKEY, PEM_STRING_PUBLIC, X509_PUBKEY) IMPLEMENT_PEM_rw(PKCS7, PKCS7, PEM_STRING_PKCS7, PKCS7) IMPLEMENT_PEM_rw(NETSCAPE_CERT_SEQUENCE, NETSCAPE_CERT_SEQUENCE, PEM_STRING_X509, NETSCAPE_CERT_SEQUENCE) #ifndef OPENSSL_NO_DEPRECATED_3_0 /* * We treat RSA or DSA private keys as a special case. For private keys we * read in an EVP_PKEY structure with PEM_read_bio_PrivateKey() and extract * the relevant private key: this means can handle "traditional" and PKCS#8 * formats transparently. */ static RSA *pkey_get_rsa(EVP_PKEY *key, RSA **rsa) { RSA *rtmp; if (!key) return NULL; rtmp = EVP_PKEY_get1_RSA(key); EVP_PKEY_free(key); if (!rtmp) return NULL; if (rsa) { RSA_free(*rsa); *rsa = rtmp; } return rtmp; } RSA *PEM_read_bio_RSAPrivateKey(BIO *bp, RSA **rsa, pem_password_cb *cb, void *u) { EVP_PKEY *pktmp; pktmp = PEM_read_bio_PrivateKey(bp, NULL, cb, u); return pkey_get_rsa(pktmp, rsa); } # ifndef OPENSSL_NO_STDIO RSA *PEM_read_RSAPrivateKey(FILE *fp, RSA **rsa, pem_password_cb *cb, void *u) { EVP_PKEY *pktmp; pktmp = PEM_read_PrivateKey(fp, NULL, cb, u); return pkey_get_rsa(pktmp, rsa); } # endif IMPLEMENT_PEM_write_cb(RSAPrivateKey, RSA, PEM_STRING_RSA, RSAPrivateKey) IMPLEMENT_PEM_rw(RSAPublicKey, RSA, PEM_STRING_RSA_PUBLIC, RSAPublicKey) IMPLEMENT_PEM_rw(RSA_PUBKEY, RSA, PEM_STRING_PUBLIC, RSA_PUBKEY) #endif #ifndef OPENSSL_NO_DSA static DSA *pkey_get_dsa(EVP_PKEY *key, DSA **dsa) { DSA *dtmp; if (!key) return NULL; dtmp = EVP_PKEY_get1_DSA(key); EVP_PKEY_free(key); if (!dtmp) return NULL; if (dsa) { DSA_free(*dsa); *dsa = dtmp; } return dtmp; } DSA *PEM_read_bio_DSAPrivateKey(BIO *bp, DSA **dsa, pem_password_cb *cb, void *u) { EVP_PKEY *pktmp; pktmp = PEM_read_bio_PrivateKey(bp, NULL, cb, u); return pkey_get_dsa(pktmp, dsa); /* will free pktmp */ } IMPLEMENT_PEM_write_cb(DSAPrivateKey, DSA, PEM_STRING_DSA, DSAPrivateKey) IMPLEMENT_PEM_rw(DSA_PUBKEY, DSA, PEM_STRING_PUBLIC, DSA_PUBKEY) # ifndef OPENSSL_NO_STDIO DSA *PEM_read_DSAPrivateKey(FILE *fp, DSA **dsa, pem_password_cb *cb, void *u) { EVP_PKEY *pktmp; pktmp = PEM_read_PrivateKey(fp, NULL, cb, u); return pkey_get_dsa(pktmp, dsa); /* will free pktmp */ } # endif IMPLEMENT_PEM_rw(DSAparams, DSA, PEM_STRING_DSAPARAMS, DSAparams) #endif #ifndef OPENSSL_NO_DEPRECATED_3_0 # ifndef OPENSSL_NO_EC static EC_KEY *pkey_get_eckey(EVP_PKEY *key, EC_KEY **eckey) { EC_KEY *dtmp; if (!key) return NULL; dtmp = EVP_PKEY_get1_EC_KEY(key); EVP_PKEY_free(key); if (!dtmp) return NULL; if (eckey) { EC_KEY_free(*eckey); *eckey = dtmp; } return dtmp; } EC_KEY *PEM_read_bio_ECPrivateKey(BIO *bp, EC_KEY **key, pem_password_cb *cb, void *u) { EVP_PKEY *pktmp; pktmp = PEM_read_bio_PrivateKey(bp, NULL, cb, u); return pkey_get_eckey(pktmp, key); /* will free pktmp */ } IMPLEMENT_PEM_rw(ECPKParameters, EC_GROUP, PEM_STRING_ECPARAMETERS, ECPKParameters) IMPLEMENT_PEM_write_cb(ECPrivateKey, EC_KEY, PEM_STRING_ECPRIVATEKEY, ECPrivateKey) IMPLEMENT_PEM_rw(EC_PUBKEY, EC_KEY, PEM_STRING_PUBLIC, EC_PUBKEY) # ifndef OPENSSL_NO_STDIO EC_KEY *PEM_read_ECPrivateKey(FILE *fp, EC_KEY **eckey, pem_password_cb *cb, void *u) { EVP_PKEY *pktmp; pktmp = PEM_read_PrivateKey(fp, NULL, cb, u); return pkey_get_eckey(pktmp, eckey); /* will free pktmp */ } # endif # endif /* !OPENSSL_NO_EC */ #endif /* !OPENSSL_NO_DEPRECATED_3_0 */ #ifndef OPENSSL_NO_DH IMPLEMENT_PEM_write(DHparams, DH, PEM_STRING_DHPARAMS, DHparams) IMPLEMENT_PEM_write(DHxparams, DH, PEM_STRING_DHXPARAMS, DHxparams) /* Transparently read in PKCS#3 or X9.42 DH parameters */ DH *PEM_read_bio_DHparams(BIO *bp, DH **x, pem_password_cb *cb, void *u) { char *nm = NULL; const unsigned char *p = NULL; unsigned char *data = NULL; long len; DH *ret = NULL; if (!PEM_bytes_read_bio(&data, &len, &nm, PEM_STRING_DHPARAMS, bp, cb, u)) return NULL; p = data; if (strcmp(nm, PEM_STRING_DHXPARAMS) == 0) ret = d2i_DHxparams(x, &p, len); else ret = d2i_DHparams(x, &p, len); if (ret == NULL) ERR_raise(ERR_LIB_PEM, ERR_R_ASN1_LIB); OPENSSL_free(nm); OPENSSL_free(data); return ret; } # ifndef OPENSSL_NO_STDIO DH *PEM_read_DHparams(FILE *fp, DH **x, pem_password_cb *cb, void *u) { BIO *b; DH *ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_read_bio_DHparams(b, x, cb, u); BIO_free(b); return ret; } # endif #endif IMPLEMENT_PEM_provided_write(PUBKEY, EVP_PKEY, pkey, PEM_STRING_PUBLIC, PUBKEY)
6,237
26.480176
79
c
openssl
openssl-master/crypto/pem/pem_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/pemerr.h> #include "crypto/pemerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA PEM_str_reasons[] = { {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_BASE64_DECODE), "bad base64 decode"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_DECRYPT), "bad decrypt"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_END_LINE), "bad end line"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_IV_CHARS), "bad iv chars"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_MAGIC_NUMBER), "bad magic number"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_PASSWORD_READ), "bad password read"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BAD_VERSION_NUMBER), "bad version number"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_BIO_WRITE_FAILURE), "bio write failure"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_CIPHER_IS_NULL), "cipher is null"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_ERROR_CONVERTING_PRIVATE_KEY), "error converting private key"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_EXPECTING_DSS_KEY_BLOB), "expecting dss key blob"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_EXPECTING_PRIVATE_KEY_BLOB), "expecting private key blob"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_EXPECTING_PUBLIC_KEY_BLOB), "expecting public key blob"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_EXPECTING_RSA_KEY_BLOB), "expecting rsa key blob"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_HEADER_TOO_LONG), "header too long"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_INCONSISTENT_HEADER), "inconsistent header"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_KEYBLOB_HEADER_PARSE_ERROR), "keyblob header parse error"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_KEYBLOB_TOO_SHORT), "keyblob too short"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_MISSING_DEK_IV), "missing dek iv"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_NOT_DEK_INFO), "not dek info"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_NOT_ENCRYPTED), "not encrypted"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_NOT_PROC_TYPE), "not proc type"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_NO_START_LINE), "no start line"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_PROBLEMS_GETTING_PASSWORD), "problems getting password"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_PVK_DATA_TOO_SHORT), "pvk data too short"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_PVK_TOO_SHORT), "pvk too short"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_READ_KEY), "read key"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_SHORT_HEADER), "short header"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_UNEXPECTED_DEK_IV), "unexpected dek iv"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_UNSUPPORTED_CIPHER), "unsupported cipher"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_UNSUPPORTED_ENCRYPTION), "unsupported encryption"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_UNSUPPORTED_KEY_COMPONENTS), "unsupported key components"}, {ERR_PACK(ERR_LIB_PEM, 0, PEM_R_UNSUPPORTED_PUBLIC_KEY_TYPE), "unsupported public key type"}, {0, NULL} }; #endif int ossl_err_load_PEM_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(PEM_str_reasons[0].error) == NULL) ERR_load_strings_const(PEM_str_reasons); #endif return 1; }
3,427
44.706667
79
c
openssl
openssl-master/crypto/pem/pem_info.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 */ /* * 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/buffer.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/rsa.h> #include <openssl/dsa.h> #include "crypto/evp.h" #ifndef OPENSSL_NO_STDIO STACK_OF(X509_INFO) *PEM_X509_INFO_read_ex(FILE *fp, STACK_OF(X509_INFO) *sk, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq) { BIO *b; STACK_OF(X509_INFO) *ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_X509_INFO_read_bio_ex(b, sk, cb, u, libctx, propq); BIO_free(b); return ret; } STACK_OF(X509_INFO) *PEM_X509_INFO_read(FILE *fp, STACK_OF(X509_INFO) *sk, pem_password_cb *cb, void *u) { return PEM_X509_INFO_read_ex(fp, sk, cb, u, NULL, NULL); } #endif STACK_OF(X509_INFO) *PEM_X509_INFO_read_bio_ex(BIO *bp, STACK_OF(X509_INFO) *sk, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq) { X509_INFO *xi = NULL; char *name = NULL, *header = NULL, *str; void *pp; unsigned char *data = NULL; const unsigned char *p; long len, error = 0; int ok = 0; STACK_OF(X509_INFO) *ret = NULL; unsigned int i, raw, ptype; d2i_of_void *d2i = 0; if (sk == NULL) { if ((ret = sk_X509_INFO_new_null()) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_CRYPTO_LIB); goto err; } } else ret = sk; if ((xi = X509_INFO_new()) == NULL) goto err; for (;;) { raw = 0; ptype = 0; ERR_set_mark(); i = PEM_read_bio(bp, &name, &header, &data, &len); if (i == 0) { error = ERR_GET_REASON(ERR_peek_last_error()); if (error == PEM_R_NO_START_LINE) { ERR_pop_to_mark(); break; } ERR_clear_last_mark(); goto err; } ERR_clear_last_mark(); start: if (strcmp(name, PEM_STRING_X509) == 0 || strcmp(name, PEM_STRING_X509_OLD) == 0 || strcmp(name, PEM_STRING_X509_TRUSTED) == 0) { if (xi->x509 != NULL) { if (!sk_X509_INFO_push(ret, xi)) goto err; if ((xi = X509_INFO_new()) == NULL) goto err; goto start; } if ((strcmp(name, PEM_STRING_X509_TRUSTED) == 0)) d2i = (D2I_OF(void)) d2i_X509_AUX; else d2i = (D2I_OF(void)) d2i_X509; xi->x509 = X509_new_ex(libctx, propq); if (xi->x509 == NULL) goto err; pp = &(xi->x509); } else if (strcmp(name, PEM_STRING_X509_CRL) == 0) { d2i = (D2I_OF(void)) d2i_X509_CRL; if (xi->crl != NULL) { if (!sk_X509_INFO_push(ret, xi)) goto err; if ((xi = X509_INFO_new()) == NULL) goto err; goto start; } pp = &(xi->crl); } else if ((str = strstr(name, PEM_STRING_PKCS8INF)) != NULL) { if (xi->x_pkey != NULL) { if (!sk_X509_INFO_push(ret, xi)) goto err; if ((xi = X509_INFO_new()) == NULL) goto err; goto start; } if (str == name || strcmp(name, PEM_STRING_PKCS8) == 0) { ptype = EVP_PKEY_NONE; } else { /* chop " PRIVATE KEY" */ *--str = '\0'; ptype = evp_pkey_name2type(name); } xi->enc_data = NULL; xi->enc_len = 0; d2i = (D2I_OF(void)) d2i_AutoPrivateKey; xi->x_pkey = X509_PKEY_new(); if (xi->x_pkey == NULL) goto err; pp = &xi->x_pkey->dec_pkey; if ((int)strlen(header) > 10 /* assume encrypted */ || strcmp(name, PEM_STRING_PKCS8) == 0) raw = 1; } else { /* unknown */ d2i = NULL; pp = NULL; } if (d2i != NULL) { if (!raw) { EVP_CIPHER_INFO cipher; if (!PEM_get_EVP_CIPHER_INFO(header, &cipher)) goto err; if (!PEM_do_header(&cipher, data, &len, cb, u)) goto err; p = data; if (ptype) { if (d2i_PrivateKey_ex(ptype, pp, &p, len, libctx, propq) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_ASN1_LIB); goto err; } } else if (d2i(pp, &p, len) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_ASN1_LIB); goto err; } } else { /* encrypted key data */ if (!PEM_get_EVP_CIPHER_INFO(header, &xi->enc_cipher)) goto err; xi->enc_data = (char *)data; xi->enc_len = (int)len; data = NULL; } } OPENSSL_free(name); name = NULL; OPENSSL_free(header); header = NULL; OPENSSL_free(data); data = NULL; } /* * if the last one hasn't been pushed yet and there is anything in it * then add it to the stack ... */ if ((xi->x509 != NULL) || (xi->crl != NULL) || (xi->x_pkey != NULL) || (xi->enc_data != NULL)) { if (!sk_X509_INFO_push(ret, xi)) goto err; xi = NULL; } ok = 1; err: X509_INFO_free(xi); if (!ok) { for (i = 0; ((int)i) < sk_X509_INFO_num(ret); i++) { xi = sk_X509_INFO_value(ret, i); X509_INFO_free(xi); } if (ret != sk) sk_X509_INFO_free(ret); ret = NULL; } OPENSSL_free(name); OPENSSL_free(header); OPENSSL_free(data); return ret; } STACK_OF(X509_INFO) *PEM_X509_INFO_read_bio(BIO *bp, STACK_OF(X509_INFO) *sk, pem_password_cb *cb, void *u) { return PEM_X509_INFO_read_bio_ex(bp, sk, cb, u, NULL, NULL); } /* A TJH addition */ int PEM_X509_INFO_write_bio(BIO *bp, const X509_INFO *xi, EVP_CIPHER *enc, const unsigned char *kstr, int klen, pem_password_cb *cb, void *u) { int i, ret = 0; unsigned char *data = NULL; const char *objstr = NULL; char buf[PEM_BUFSIZE]; const unsigned char *iv = NULL; if (enc != NULL) { objstr = EVP_CIPHER_get0_name(enc); if (objstr == NULL /* * Check "Proc-Type: 4,Encrypted\nDEK-Info: objstr,hex-iv\n" * fits into buf */ || strlen(objstr) + 23 + 2 * EVP_CIPHER_get_iv_length(enc) + 13 > sizeof(buf)) { ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_CIPHER); goto err; } } /* * now for the fun part ... if we have a private key then we have to be * able to handle a not-yet-decrypted key being written out correctly ... * if it is decrypted or it is non-encrypted then we use the base code */ if (xi->x_pkey != NULL) { if ((xi->enc_data != NULL) && (xi->enc_len > 0)) { if (enc == NULL) { ERR_raise(ERR_LIB_PEM, PEM_R_CIPHER_IS_NULL); goto err; } /* copy from weirdo names into more normal things */ iv = xi->enc_cipher.iv; data = (unsigned char *)xi->enc_data; i = xi->enc_len; /* * we take the encryption data from the internal stuff rather * than what the user has passed us ... as we have to match * exactly for some strange reason */ objstr = EVP_CIPHER_get0_name(xi->enc_cipher.cipher); if (objstr == NULL) { ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_CIPHER); goto err; } /* Create the right magic header stuff */ buf[0] = '\0'; PEM_proc_type(buf, PEM_TYPE_ENCRYPTED); PEM_dek_info(buf, objstr, EVP_CIPHER_get_iv_length(enc), (const char *)iv); /* use the normal code to write things out */ i = PEM_write_bio(bp, PEM_STRING_RSA, buf, data, i); if (i <= 0) goto err; } else { /* Add DSA/DH */ /* normal optionally encrypted stuff */ if (PEM_write_bio_RSAPrivateKey(bp, EVP_PKEY_get0_RSA(xi->x_pkey->dec_pkey), enc, kstr, klen, cb, u) <= 0) goto err; } } /* if we have a certificate then write it out now */ if ((xi->x509 != NULL) && (PEM_write_bio_X509(bp, xi->x509) <= 0)) goto err; /* * we are ignoring anything else that is loaded into the X509_INFO * structure for the moment ... as I don't need it so I'm not coding it * here and Eric can do it when this makes it into the base library --tjh */ ret = 1; err: OPENSSL_cleanse(buf, PEM_BUFSIZE); return ret; }
10,144
31.516026
84
c
openssl
openssl-master/crypto/pem/pem_local.h
/* * 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/core_dispatch.h> #include <openssl/pem.h> #include <openssl/encoder.h> /* * Selectors, named according to the ASN.1 names used throughout libcrypto. * * Note that these are not absolutely mandatory, they are rather a wishlist * of sorts. The provider implementations are free to make choices that * make sense for them, based on these selectors. * For example, the EC backend is likely to really just output the private * key to a PKCS#8 structure, even thought PEM_SELECTION_PrivateKey specifies * the public key as well. This is fine, as long as the corresponding * decoding operation can return an object that contains what libcrypto * expects. */ # define PEM_SELECTION_PUBKEY EVP_PKEY_PUBLIC_KEY # define PEM_SELECTION_PrivateKey EVP_PKEY_KEYPAIR # define PEM_SELECTION_Parameters EVP_PKEY_KEY_PARAMETERS /* * Properties, named according to the ASN.1 names used throughout libcrypto. */ # define PEM_STRUCTURE_PUBKEY "SubjectPublicKeyInfo" # define PEM_STRUCTURE_PrivateKey "PrivateKeyInfo" # define PEM_STRUCTURE_Parameters "type-specific" # define PEM_STRUCTURE_RSAPrivateKey "type-specific" # define PEM_STRUCTURE_RSAPublicKey "type-specific" /* Alternative IMPLEMENT macros for provided encoders */ # define IMPLEMENT_PEM_provided_write_body_vars(type, asn1, pq) \ int ret = 0; \ OSSL_ENCODER_CTX *ctx = \ OSSL_ENCODER_CTX_new_for_##type(x, PEM_SELECTION_##asn1, \ "PEM", PEM_STRUCTURE_##asn1, \ (pq)); \ \ if (OSSL_ENCODER_CTX_get_num_encoders(ctx) == 0) { \ OSSL_ENCODER_CTX_free(ctx); \ goto legacy; \ } # define IMPLEMENT_PEM_provided_write_body_pass() \ ret = 1; \ if (kstr == NULL && cb == NULL) { \ if (u != NULL) { \ kstr = u; \ klen = strlen(u); \ } else { \ cb = PEM_def_callback; \ } \ } \ if (enc != NULL) { \ ret = 0; \ if (OSSL_ENCODER_CTX_set_cipher(ctx, EVP_CIPHER_get0_name(enc), \ NULL)) { \ ret = 1; \ if (kstr != NULL \ && !OSSL_ENCODER_CTX_set_passphrase(ctx, kstr, klen)) \ ret = 0; \ else if (cb != NULL \ && !OSSL_ENCODER_CTX_set_pem_password_cb(ctx, \ cb, u)) \ ret = 0; \ } \ } \ if (!ret) { \ OSSL_ENCODER_CTX_free(ctx); \ return 0; \ } # define IMPLEMENT_PEM_provided_write_body_main(type, outtype) \ ret = OSSL_ENCODER_to_##outtype(ctx, out); \ OSSL_ENCODER_CTX_free(ctx); \ return ret # define IMPLEMENT_PEM_provided_write_body_fallback(str, asn1, \ writename) \ legacy: \ return PEM_ASN1_##writename((i2d_of_void *)i2d_##asn1, str, out, \ x, NULL, NULL, 0, NULL, NULL) # define IMPLEMENT_PEM_provided_write_body_fallback_cb(str, asn1, \ writename) \ legacy: \ return PEM_ASN1_##writename##((i2d_of_void *)i2d_##asn1, str, out, \ x, enc, kstr, klen, cb, u) # define IMPLEMENT_PEM_provided_write_to(name, TYPE, type, str, asn1, \ OUTTYPE, outtype, writename) \ PEM_write_fnsig(name, TYPE, OUTTYPE, writename) \ { \ IMPLEMENT_PEM_provided_write_body_vars(type, asn1, NULL); \ IMPLEMENT_PEM_provided_write_body_main(type, outtype); \ IMPLEMENT_PEM_provided_write_body_fallback(str, asn1, \ writename); \ } \ PEM_write_ex_fnsig(name, TYPE, OUTTYPE, writename) \ { \ IMPLEMENT_PEM_provided_write_body_vars(type, asn1, propq); \ IMPLEMENT_PEM_provided_write_body_main(type, outtype); \ IMPLEMENT_PEM_provided_write_body_fallback(str, asn1, \ writename); \ } # define IMPLEMENT_PEM_provided_write_cb_to(name, TYPE, type, str, asn1, \ OUTTYPE, outtype, writename) \ PEM_write_cb_fnsig(name, TYPE, OUTTYPE, writename) \ { \ IMPLEMENT_PEM_provided_write_body_vars(type, asn1, NULL); \ IMPLEMENT_PEM_provided_write_body_pass(); \ IMPLEMENT_PEM_provided_write_body_main(type, outtype); \ IMPLEMENT_PEM_provided_write_body_fallback_cb(str, asn1, \ writename); \ } \ PEM_write_ex_cb_fnsig(name, TYPE, OUTTYPE, writename) \ { \ IMPLEMENT_PEM_provided_write_body_vars(type, asn1, propq); \ IMPLEMENT_PEM_provided_write_body_pass(); \ IMPLEMENT_PEM_provided_write_body_main(type, outtype); \ IMPLEMENT_PEM_provided_write_body_fallback(str, asn1, \ writename); \ } # ifdef OPENSSL_NO_STDIO # define IMPLEMENT_PEM_provided_write_fp(name, TYPE, type, str, asn1) # define IMPLEMENT_PEM_provided_write_cb_fp(name, TYPE, type, str, asn1) # else # define IMPLEMENT_PEM_provided_write_fp(name, TYPE, type, str, asn1) \ IMPLEMENT_PEM_provided_write_to(name, TYPE, type, str, asn1, FILE, fp, write) # define IMPLEMENT_PEM_provided_write_cb_fp(name, TYPE, type, str, asn1) \ IMPLEMENT_PEM_provided_write_cb_to(name, TYPE, type, str, asn1, FILE, fp, write) # endif # define IMPLEMENT_PEM_provided_write_bio(name, TYPE, type, str, asn1) \ IMPLEMENT_PEM_provided_write_to(name, TYPE, type, str, asn1, BIO, bio, write_bio) # define IMPLEMENT_PEM_provided_write_cb_bio(name, TYPE, type, str, asn1) \ IMPLEMENT_PEM_provided_write_cb_to(name, TYPE, type, str, asn1, BIO, bio, write_bio) # define IMPLEMENT_PEM_provided_write(name, TYPE, type, str, asn1) \ IMPLEMENT_PEM_provided_write_bio(name, TYPE, type, str, asn1) \ IMPLEMENT_PEM_provided_write_fp(name, TYPE, type, str, asn1) # define IMPLEMENT_PEM_provided_write_cb(name, TYPE, type, str, asn1) \ IMPLEMENT_PEM_provided_write_cb_bio(name, TYPE, type, str, asn1) \ IMPLEMENT_PEM_provided_write_cb_fp(name, TYPE, type, str, asn1) # define IMPLEMENT_PEM_provided_rw(name, TYPE, type, str, asn1) \ IMPLEMENT_PEM_read(name, TYPE, str, asn1) \ IMPLEMENT_PEM_provided_write(name, TYPE, type, str, asn1) # define IMPLEMENT_PEM_provided_rw_cb(name, TYPE, type, str, asn1) \ IMPLEMENT_PEM_read(name, TYPE, str, asn1) \ IMPLEMENT_PEM_provided_write_cb(name, TYPE, type, str, asn1)
9,402
54.970238
88
h
openssl
openssl-master/crypto/pem/pem_oth.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/buffer.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pem.h> /* Handle 'other' PEMs: not private keys */ void *PEM_ASN1_read_bio(d2i_of_void *d2i, const char *name, BIO *bp, void **x, pem_password_cb *cb, void *u) { const unsigned char *p = NULL; unsigned char *data = NULL; long len; char *ret = NULL; if (!PEM_bytes_read_bio(&data, &len, NULL, name, bp, cb, u)) return NULL; p = data; ret = d2i(x, &p, len); if (ret == NULL) ERR_raise(ERR_LIB_PEM, ERR_R_ASN1_LIB); OPENSSL_free(data); return ret; }
1,043
27.216216
78
c
openssl
openssl-master/crypto/pem/pem_pk8.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/core_dispatch.h> #include <openssl/buffer.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pkcs12.h> #include <openssl/pem.h> #include <openssl/encoder.h> static int do_pk8pkey(BIO *bp, const EVP_PKEY *x, int isder, int nid, const EVP_CIPHER *enc, const char *kstr, int klen, pem_password_cb *cb, void *u, const char *propq); #ifndef OPENSSL_NO_STDIO static int do_pk8pkey_fp(FILE *bp, const EVP_PKEY *x, int isder, int nid, const EVP_CIPHER *enc, const char *kstr, int klen, pem_password_cb *cb, void *u, const char *propq); #endif /* * These functions write a private key in PKCS#8 format: it is a "drop in" * replacement for PEM_write_bio_PrivateKey() and friends. As usual if 'enc' * is NULL then it uses the unencrypted private key form. The 'nid' versions * uses PKCS#5 v1.5 PBE algorithms whereas the others use PKCS#5 v2.0. */ int PEM_write_bio_PKCS8PrivateKey_nid(BIO *bp, const EVP_PKEY *x, int nid, const char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey(bp, x, 0, nid, NULL, kstr, klen, cb, u, NULL); } int PEM_write_bio_PKCS8PrivateKey(BIO *bp, const EVP_PKEY *x, const EVP_CIPHER *enc, const char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey(bp, x, 0, -1, enc, kstr, klen, cb, u, NULL); } int i2d_PKCS8PrivateKey_bio(BIO *bp, const EVP_PKEY *x, const EVP_CIPHER *enc, const char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey(bp, x, 1, -1, enc, kstr, klen, cb, u, NULL); } int i2d_PKCS8PrivateKey_nid_bio(BIO *bp, const EVP_PKEY *x, int nid, const char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey(bp, x, 1, nid, NULL, kstr, klen, cb, u, NULL); } static int do_pk8pkey(BIO *bp, const EVP_PKEY *x, int isder, int nid, const EVP_CIPHER *enc, const char *kstr, int klen, pem_password_cb *cb, void *u, const char *propq) { int ret = 0; const char *outtype = isder ? "DER" : "PEM"; OSSL_ENCODER_CTX *ctx = OSSL_ENCODER_CTX_new_for_pkey(x, OSSL_KEYMGMT_SELECT_ALL, outtype, "PrivateKeyInfo", propq); if (ctx == NULL) return 0; /* * If no keystring or callback is set, OpenSSL traditionally uses the * user's cb argument as a password string, or if that's NULL, it falls * back on PEM_def_callback(). */ if (kstr == NULL && cb == NULL) { if (u != NULL) { kstr = u; klen = strlen(u); } else { cb = PEM_def_callback; } } /* * NOTE: There is no attempt to do a EVP_CIPHER_fetch() using the nid, * since the nid is a PBE algorithm which can't be fetched currently. * (e.g. NID_pbe_WithSHA1And2_Key_TripleDES_CBC). Just use the legacy * path if the NID is passed. */ if (nid == -1 && OSSL_ENCODER_CTX_get_num_encoders(ctx) != 0) { ret = 1; if (enc != NULL) { ret = 0; if (OSSL_ENCODER_CTX_set_cipher(ctx, EVP_CIPHER_get0_name(enc), NULL)) { const unsigned char *ukstr = (const unsigned char *)kstr; /* * Try to pass the passphrase if one was given, or the * passphrase callback if one was given. If none of them * are given and that's wrong, we rely on the _to_bio() * call to generate errors. */ ret = 1; if (kstr != NULL && !OSSL_ENCODER_CTX_set_passphrase(ctx, ukstr, klen)) ret = 0; else if (cb != NULL && !OSSL_ENCODER_CTX_set_pem_password_cb(ctx, cb, u)) ret = 0; } } ret = ret && OSSL_ENCODER_to_bio(ctx, bp); } else { X509_SIG *p8; PKCS8_PRIV_KEY_INFO *p8inf; char buf[PEM_BUFSIZE]; ret = 0; if ((p8inf = EVP_PKEY2PKCS8(x)) == NULL) { ERR_raise(ERR_LIB_PEM, PEM_R_ERROR_CONVERTING_PRIVATE_KEY); goto legacy_end; } if (enc || (nid != -1)) { if (kstr == NULL) { klen = cb(buf, PEM_BUFSIZE, 1, u); if (klen < 0) { ERR_raise(ERR_LIB_PEM, PEM_R_READ_KEY); goto legacy_end; } kstr = buf; } p8 = PKCS8_encrypt(nid, enc, kstr, klen, NULL, 0, 0, p8inf); if (kstr == buf) OPENSSL_cleanse(buf, klen); if (p8 == NULL) goto legacy_end; if (isder) ret = i2d_PKCS8_bio(bp, p8); else ret = PEM_write_bio_PKCS8(bp, p8); X509_SIG_free(p8); } else { if (isder) ret = i2d_PKCS8_PRIV_KEY_INFO_bio(bp, p8inf); else ret = PEM_write_bio_PKCS8_PRIV_KEY_INFO(bp, p8inf); } legacy_end: PKCS8_PRIV_KEY_INFO_free(p8inf); } OSSL_ENCODER_CTX_free(ctx); return ret; } EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) { PKCS8_PRIV_KEY_INFO *p8inf = NULL; X509_SIG *p8 = NULL; int klen; EVP_PKEY *ret; char psbuf[PEM_BUFSIZE]; p8 = d2i_PKCS8_bio(bp, NULL); if (p8 == NULL) return NULL; if (cb != NULL) klen = cb(psbuf, PEM_BUFSIZE, 0, u); else klen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u); if (klen < 0) { ERR_raise(ERR_LIB_PEM, PEM_R_BAD_PASSWORD_READ); X509_SIG_free(p8); return NULL; } p8inf = PKCS8_decrypt(p8, psbuf, klen); X509_SIG_free(p8); OPENSSL_cleanse(psbuf, klen); if (p8inf == NULL) return NULL; ret = EVP_PKCS82PKEY(p8inf); PKCS8_PRIV_KEY_INFO_free(p8inf); if (!ret) return NULL; if (x != NULL) { EVP_PKEY_free(*x); *x = ret; } return ret; } #ifndef OPENSSL_NO_STDIO int i2d_PKCS8PrivateKey_fp(FILE *fp, const EVP_PKEY *x, const EVP_CIPHER *enc, const char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey_fp(fp, x, 1, -1, enc, kstr, klen, cb, u, NULL); } int i2d_PKCS8PrivateKey_nid_fp(FILE *fp, const EVP_PKEY *x, int nid, const char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey_fp(fp, x, 1, nid, NULL, kstr, klen, cb, u, NULL); } int PEM_write_PKCS8PrivateKey_nid(FILE *fp, const EVP_PKEY *x, int nid, const char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey_fp(fp, x, 0, nid, NULL, kstr, klen, cb, u, NULL); } int PEM_write_PKCS8PrivateKey(FILE *fp, const EVP_PKEY *x, const EVP_CIPHER *enc, const char *kstr, int klen, pem_password_cb *cb, void *u) { return do_pk8pkey_fp(fp, x, 0, -1, enc, kstr, klen, cb, u, NULL); } static int do_pk8pkey_fp(FILE *fp, const EVP_PKEY *x, int isder, int nid, const EVP_CIPHER *enc, const char *kstr, int klen, pem_password_cb *cb, void *u, const char *propq) { BIO *bp; int ret; if ((bp = BIO_new_fp(fp, BIO_NOCLOSE)) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB); return 0; } ret = do_pk8pkey(bp, x, isder, nid, enc, kstr, klen, cb, u, propq); BIO_free(bp); return ret; } EVP_PKEY *d2i_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u) { BIO *bp; EVP_PKEY *ret; if ((bp = BIO_new_fp(fp, BIO_NOCLOSE)) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB); return NULL; } ret = d2i_PKCS8PrivateKey_bio(bp, x, cb, u); BIO_free(bp); return ret; } #endif IMPLEMENT_PEM_rw(PKCS8, X509_SIG, PEM_STRING_PKCS8, X509_SIG) IMPLEMENT_PEM_rw(PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO, PEM_STRING_PKCS8INF, PKCS8_PRIV_KEY_INFO)
9,107
32.240876
84
c
openssl
openssl-master/crypto/pem/pem_pkey.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 */ /* We need to use some deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <openssl/buffer.h> #include <openssl/objects.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pkcs12.h> #include <openssl/pem.h> #include <openssl/engine.h> #include <openssl/dh.h> #include <openssl/decoder.h> #include <openssl/ui.h> #include "internal/cryptlib.h" #include "internal/passphrase.h" #include "crypto/asn1.h" #include "crypto/x509.h" #include "crypto/evp.h" #include "pem_local.h" int ossl_pem_check_suffix(const char *pem_str, const char *suffix); static EVP_PKEY *pem_read_bio_key_decoder(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq, int selection) { EVP_PKEY *pkey = NULL; OSSL_DECODER_CTX *dctx = NULL; int pos, newpos; if ((pos = BIO_tell(bp)) < 0) /* We can depend on BIO_tell() thanks to the BIO_f_readbuffer() */ return NULL; dctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "PEM", NULL, NULL, selection, libctx, propq); if (dctx == NULL) return NULL; if (cb == NULL) cb = PEM_def_callback; if (!OSSL_DECODER_CTX_set_pem_password_cb(dctx, cb, u)) goto err; ERR_set_mark(); while (!OSSL_DECODER_from_bio(dctx, bp) || pkey == NULL) if (BIO_eof(bp) != 0 || (newpos = BIO_tell(bp)) < 0 || newpos <= pos) { ERR_clear_last_mark(); goto err; } else { if (ERR_GET_REASON(ERR_peek_error()) == ERR_R_UNSUPPORTED) { /* unsupported PEM data, try again */ ERR_pop_to_mark(); ERR_set_mark(); } else { /* other error, bail out */ ERR_clear_last_mark(); goto err; } pos = newpos; } ERR_pop_to_mark(); /* if we were asked for private key, the public key is optional */ if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) selection = selection & ~OSSL_KEYMGMT_SELECT_PUBLIC_KEY; if (!evp_keymgmt_util_has(pkey, selection)) { EVP_PKEY_free(pkey); pkey = NULL; ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_KEY_COMPONENTS); goto err; } if (x != NULL) { EVP_PKEY_free(*x); *x = pkey; } err: OSSL_DECODER_CTX_free(dctx); return pkey; } static EVP_PKEY *pem_read_bio_key_legacy(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq, int selection) { char *nm = NULL; const unsigned char *p = NULL; unsigned char *data = NULL; long len; int slen; EVP_PKEY *ret = NULL; ERR_set_mark(); /* not interested in PEM read errors */ if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0) { if (!PEM_bytes_read_bio_secmem(&data, &len, &nm, PEM_STRING_EVP_PKEY, bp, cb, u)) { ERR_pop_to_mark(); return NULL; } } else { const char *pem_string = PEM_STRING_PARAMETERS; if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) pem_string = PEM_STRING_PUBLIC; if (!PEM_bytes_read_bio(&data, &len, &nm, pem_string, bp, cb, u)) { ERR_pop_to_mark(); return NULL; } } ERR_clear_last_mark(); p = data; if (strcmp(nm, PEM_STRING_PKCS8INF) == 0) { PKCS8_PRIV_KEY_INFO *p8inf; if ((p8inf = d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, len)) == NULL) goto p8err; ret = evp_pkcs82pkey_legacy(p8inf, libctx, propq); if (x != NULL) { EVP_PKEY_free(*x); *x = ret; } PKCS8_PRIV_KEY_INFO_free(p8inf); } else if (strcmp(nm, PEM_STRING_PKCS8) == 0) { PKCS8_PRIV_KEY_INFO *p8inf; X509_SIG *p8; int klen; char psbuf[PEM_BUFSIZE]; if ((p8 = d2i_X509_SIG(NULL, &p, len)) == NULL) goto p8err; if (cb != NULL) klen = cb(psbuf, PEM_BUFSIZE, 0, u); else klen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u); if (klen < 0) { ERR_raise(ERR_LIB_PEM, PEM_R_BAD_PASSWORD_READ); X509_SIG_free(p8); goto err; } p8inf = PKCS8_decrypt(p8, psbuf, klen); X509_SIG_free(p8); OPENSSL_cleanse(psbuf, klen); if (p8inf == NULL) goto p8err; ret = evp_pkcs82pkey_legacy(p8inf, libctx, propq); if (x != NULL) { EVP_PKEY_free(*x); *x = ret; } PKCS8_PRIV_KEY_INFO_free(p8inf); } else if ((slen = ossl_pem_check_suffix(nm, "PRIVATE KEY")) > 0) { const EVP_PKEY_ASN1_METHOD *ameth; ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen); if (ameth == NULL || ameth->old_priv_decode == NULL) goto p8err; ret = ossl_d2i_PrivateKey_legacy(ameth->pkey_id, x, &p, len, libctx, propq); } else if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) == 0 && (selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0) { /* Trying legacy PUBKEY decoding only if we do not want private key. */ ret = ossl_d2i_PUBKEY_legacy(x, &p, len); } else if ((selection & EVP_PKEY_KEYPAIR) == 0 && (slen = ossl_pem_check_suffix(nm, "PARAMETERS")) > 0) { /* Trying legacy params decoding only if we do not want a key. */ ret = EVP_PKEY_new(); if (ret == NULL) goto err; if (!EVP_PKEY_set_type_str(ret, nm, slen) || !ret->ameth->param_decode || !ret->ameth->param_decode(ret, &p, len)) { EVP_PKEY_free(ret); ret = NULL; goto err; } if (x) { EVP_PKEY_free(*x); *x = ret; } } p8err: if (ret == NULL && ERR_peek_last_error() == 0) /* ensure some error is reported but do not hide the real one */ ERR_raise(ERR_LIB_PEM, ERR_R_ASN1_LIB); err: OPENSSL_secure_free(nm); OPENSSL_secure_clear_free(data, len); return ret; } static EVP_PKEY *pem_read_bio_key(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq, int selection) { EVP_PKEY *ret = NULL; BIO *new_bio = NULL; int pos; struct ossl_passphrase_data_st pwdata = { 0 }; if ((pos = BIO_tell(bp)) < 0) { new_bio = BIO_new(BIO_f_readbuffer()); if (new_bio == NULL) return NULL; bp = BIO_push(new_bio, bp); pos = BIO_tell(bp); } if (cb == NULL) cb = PEM_def_callback; if (!ossl_pw_set_pem_password_cb(&pwdata, cb, u) || !ossl_pw_enable_passphrase_caching(&pwdata)) goto err; ERR_set_mark(); ret = pem_read_bio_key_decoder(bp, x, ossl_pw_pem_password, &pwdata, libctx, propq, selection); if (ret == NULL && (BIO_seek(bp, pos) < 0 || (ret = pem_read_bio_key_legacy(bp, x, ossl_pw_pem_password, &pwdata, libctx, propq, selection)) == NULL)) ERR_clear_last_mark(); else ERR_pop_to_mark(); err: ossl_pw_clear_passphrase_data(&pwdata); if (new_bio != NULL) { BIO_pop(new_bio); BIO_free(new_bio); } return ret; } EVP_PKEY *PEM_read_bio_PUBKEY_ex(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq) { return pem_read_bio_key(bp, x, cb, u, libctx, propq, EVP_PKEY_PUBLIC_KEY); } EVP_PKEY *PEM_read_bio_PUBKEY(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) { return PEM_read_bio_PUBKEY_ex(bp, x, cb, u, NULL, NULL); } #ifndef OPENSSL_NO_STDIO EVP_PKEY *PEM_read_PUBKEY_ex(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq) { BIO *b; EVP_PKEY *ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_read_bio_PUBKEY_ex(b, x, cb, u, libctx, propq); BIO_free(b); return ret; } EVP_PKEY *PEM_read_PUBKEY(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u) { return PEM_read_PUBKEY_ex(fp, x, cb, u, NULL, NULL); } #endif EVP_PKEY *PEM_read_bio_PrivateKey_ex(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq) { return pem_read_bio_key(bp, x, cb, u, libctx, propq, /* we also want the public key, if available */ EVP_PKEY_KEYPAIR); } EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) { return PEM_read_bio_PrivateKey_ex(bp, x, cb, u, NULL, NULL); } PEM_write_cb_ex_fnsig(PrivateKey, EVP_PKEY, BIO, write_bio) { IMPLEMENT_PEM_provided_write_body_vars(pkey, PrivateKey, propq); IMPLEMENT_PEM_provided_write_body_pass(); IMPLEMENT_PEM_provided_write_body_main(pkey, bio); legacy: if (x != NULL && (x->ameth == NULL || x->ameth->priv_encode != NULL)) return PEM_write_bio_PKCS8PrivateKey(out, x, enc, (const char *)kstr, klen, cb, u); return PEM_write_bio_PrivateKey_traditional(out, x, enc, kstr, klen, cb, u); } PEM_write_cb_fnsig(PrivateKey, EVP_PKEY, BIO, write_bio) { return PEM_write_bio_PrivateKey_ex(out, x, enc, kstr, klen, cb, u, NULL, NULL); } /* * Note: there is no way to tell a provided pkey encoder to use "traditional" * encoding. Therefore, if the pkey is provided, we try to take a copy */ int PEM_write_bio_PrivateKey_traditional(BIO *bp, const EVP_PKEY *x, const EVP_CIPHER *enc, const unsigned char *kstr, int klen, pem_password_cb *cb, void *u) { char pem_str[80]; EVP_PKEY *copy = NULL; int ret; if (x == NULL) return 0; if (evp_pkey_is_assigned(x) && evp_pkey_is_provided(x) && evp_pkey_copy_downgraded(&copy, x)) x = copy; if (x->ameth == NULL || x->ameth->old_priv_encode == NULL) { ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_PUBLIC_KEY_TYPE); EVP_PKEY_free(copy); return 0; } BIO_snprintf(pem_str, 80, "%s PRIVATE KEY", x->ameth->pem_str); ret = PEM_ASN1_write_bio((i2d_of_void *)i2d_PrivateKey, pem_str, bp, x, enc, kstr, klen, cb, u); EVP_PKEY_free(copy); return ret; } EVP_PKEY *PEM_read_bio_Parameters_ex(BIO *bp, EVP_PKEY **x, OSSL_LIB_CTX *libctx, const char *propq) { return pem_read_bio_key(bp, x, NULL, NULL, libctx, propq, EVP_PKEY_KEY_PARAMETERS); } EVP_PKEY *PEM_read_bio_Parameters(BIO *bp, EVP_PKEY **x) { return PEM_read_bio_Parameters_ex(bp, x, NULL, NULL); } PEM_write_fnsig(Parameters, EVP_PKEY, BIO, write_bio) { char pem_str[80]; IMPLEMENT_PEM_provided_write_body_vars(pkey, Parameters, NULL); IMPLEMENT_PEM_provided_write_body_main(pkey, bio); legacy: if (!x->ameth || !x->ameth->param_encode) return 0; BIO_snprintf(pem_str, 80, "%s PARAMETERS", x->ameth->pem_str); return PEM_ASN1_write_bio((i2d_of_void *)x->ameth->param_encode, pem_str, out, x, NULL, NULL, 0, 0, NULL); } #ifndef OPENSSL_NO_STDIO EVP_PKEY *PEM_read_PrivateKey_ex(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx, const char *propq) { BIO *b; EVP_PKEY *ret; if ((b = BIO_new(BIO_s_file())) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB); return 0; } BIO_set_fp(b, fp, BIO_NOCLOSE); ret = PEM_read_bio_PrivateKey_ex(b, x, cb, u, libctx, propq); BIO_free(b); return ret; } EVP_PKEY *PEM_read_PrivateKey(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u) { return PEM_read_PrivateKey_ex(fp, x, cb, u, NULL, NULL); } PEM_write_cb_ex_fnsig(PrivateKey, EVP_PKEY, FILE, write) { BIO *b; int ret; if ((b = BIO_new_fp(out, BIO_NOCLOSE)) == NULL) { ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB); return 0; } ret = PEM_write_bio_PrivateKey_ex(b, x, enc, kstr, klen, cb, u, libctx, propq); BIO_free(b); return ret; } PEM_write_cb_fnsig(PrivateKey, EVP_PKEY, FILE, write) { return PEM_write_PrivateKey_ex(out, x, enc, kstr, klen, cb, u, NULL, NULL); } #endif
14,045
30.85034
80
c
openssl
openssl-master/crypto/pem/pem_sign.c
/* * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/pem.h> int PEM_SignInit(EVP_MD_CTX *ctx, EVP_MD *type) { return EVP_DigestInit_ex(ctx, type, NULL); } int PEM_SignUpdate(EVP_MD_CTX *ctx, const unsigned char *data, unsigned int count) { return EVP_DigestUpdate(ctx, data, count); } int PEM_SignFinal(EVP_MD_CTX *ctx, unsigned char *sigret, unsigned int *siglen, EVP_PKEY *pkey) { unsigned char *m; int i, ret = 0; unsigned int m_len; m = OPENSSL_malloc(EVP_PKEY_get_size(pkey)); if (m == NULL) goto err; if (EVP_SignFinal(ctx, m, &m_len, pkey) <= 0) goto err; i = EVP_EncodeBlock(sigret, m, m_len); *siglen = i; ret = 1; err: /* ctx has been zeroed by EVP_SignFinal() */ OPENSSL_free(m); return ret; }
1,253
24.08
74
c
openssl
openssl-master/crypto/pem/pem_x509.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/bio.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pkcs7.h> #include <openssl/pem.h> IMPLEMENT_PEM_rw(X509, X509, PEM_STRING_X509, X509)
568
28.947368
74
c
openssl
openssl-master/crypto/pem/pem_xaux.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/bio.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/pkcs7.h> #include <openssl/pem.h> IMPLEMENT_PEM_rw(X509_AUX, X509, PEM_STRING_X509_TRUSTED, X509_AUX)
584
29.789474
74
c
openssl
openssl-master/crypto/pkcs12/p12_add.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/core.h> #include <openssl/core_names.h> #include <openssl/pkcs12.h> #include "p12_local.h" #include "crypto/pkcs7/pk7_local.h" /* Pack an object into an OCTET STRING and turn into a safebag */ PKCS12_SAFEBAG *PKCS12_item_pack_safebag(void *obj, const ASN1_ITEM *it, int nid1, int nid2) { PKCS12_BAGS *bag; PKCS12_SAFEBAG *safebag; if ((bag = PKCS12_BAGS_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } bag->type = OBJ_nid2obj(nid1); if (!ASN1_item_pack(obj, it, &bag->value.octet)) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } if ((safebag = PKCS12_SAFEBAG_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } safebag->value.bag = bag; safebag->type = OBJ_nid2obj(nid2); return safebag; err: PKCS12_BAGS_free(bag); return NULL; } /* Turn a stack of SAFEBAGS into a PKCS#7 data Contentinfo */ PKCS7 *PKCS12_pack_p7data(STACK_OF(PKCS12_SAFEBAG) *sk) { PKCS7 *p7; if ((p7 = PKCS7_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } p7->type = OBJ_nid2obj(NID_pkcs7_data); if ((p7->d.data = ASN1_OCTET_STRING_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } if (!ASN1_item_pack(sk, ASN1_ITEM_rptr(PKCS12_SAFEBAGS), &p7->d.data)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CANT_PACK_STRUCTURE); goto err; } return p7; err: PKCS7_free(p7); return NULL; } /* Unpack SAFEBAGS from PKCS#7 data ContentInfo */ STACK_OF(PKCS12_SAFEBAG) *PKCS12_unpack_p7data(PKCS7 *p7) { if (!PKCS7_type_is_data(p7)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CONTENT_TYPE_NOT_DATA); return NULL; } return ASN1_item_unpack_ex(p7->d.data, ASN1_ITEM_rptr(PKCS12_SAFEBAGS), ossl_pkcs7_ctx_get0_libctx(&p7->ctx), ossl_pkcs7_ctx_get0_propq(&p7->ctx)); } /* Turn a stack of SAFEBAGS into a PKCS#7 encrypted data ContentInfo */ PKCS7 *PKCS12_pack_p7encdata_ex(int pbe_nid, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, STACK_OF(PKCS12_SAFEBAG) *bags, OSSL_LIB_CTX *ctx, const char *propq) { PKCS7 *p7; X509_ALGOR *pbe; const EVP_CIPHER *pbe_ciph = NULL; EVP_CIPHER *pbe_ciph_fetch = NULL; if ((p7 = PKCS7_new_ex(ctx, propq)) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } if (!PKCS7_set_type(p7, NID_pkcs7_encrypted)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_ERROR_SETTING_ENCRYPTED_DATA_TYPE); goto err; } ERR_set_mark(); pbe_ciph = pbe_ciph_fetch = EVP_CIPHER_fetch(ctx, OBJ_nid2sn(pbe_nid), propq); if (pbe_ciph == NULL) pbe_ciph = EVP_get_cipherbynid(pbe_nid); ERR_pop_to_mark(); if (pbe_ciph != NULL) { pbe = PKCS5_pbe2_set_iv_ex(pbe_ciph, iter, salt, saltlen, NULL, -1, ctx); } else { pbe = PKCS5_pbe_set_ex(pbe_nid, iter, salt, saltlen, ctx); } if (pbe == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } X509_ALGOR_free(p7->d.encrypted->enc_data->algorithm); p7->d.encrypted->enc_data->algorithm = pbe; ASN1_OCTET_STRING_free(p7->d.encrypted->enc_data->enc_data); if (!(p7->d.encrypted->enc_data->enc_data = PKCS12_item_i2d_encrypt_ex(pbe, ASN1_ITEM_rptr(PKCS12_SAFEBAGS), pass, passlen, bags, 1, ctx, propq))) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_ENCRYPT_ERROR); goto err; } EVP_CIPHER_free(pbe_ciph_fetch); return p7; err: PKCS7_free(p7); EVP_CIPHER_free(pbe_ciph_fetch); return NULL; } PKCS7 *PKCS12_pack_p7encdata(int pbe_nid, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, STACK_OF(PKCS12_SAFEBAG) *bags) { return PKCS12_pack_p7encdata_ex(pbe_nid, pass, passlen, salt, saltlen, iter, bags, NULL, NULL); } STACK_OF(PKCS12_SAFEBAG) *PKCS12_unpack_p7encdata(PKCS7 *p7, const char *pass, int passlen) { if (!PKCS7_type_is_encrypted(p7)) return NULL; return PKCS12_item_decrypt_d2i_ex(p7->d.encrypted->enc_data->algorithm, ASN1_ITEM_rptr(PKCS12_SAFEBAGS), pass, passlen, p7->d.encrypted->enc_data->enc_data, 1, p7->ctx.libctx, p7->ctx.propq); } PKCS8_PRIV_KEY_INFO *PKCS12_decrypt_skey_ex(const PKCS12_SAFEBAG *bag, const char *pass, int passlen, OSSL_LIB_CTX *ctx, const char *propq) { return PKCS8_decrypt_ex(bag->value.shkeybag, pass, passlen, ctx, propq); } PKCS8_PRIV_KEY_INFO *PKCS12_decrypt_skey(const PKCS12_SAFEBAG *bag, const char *pass, int passlen) { return PKCS12_decrypt_skey_ex(bag, pass, passlen, NULL, NULL); } int PKCS12_pack_authsafes(PKCS12 *p12, STACK_OF(PKCS7) *safes) { if (ASN1_item_pack(safes, ASN1_ITEM_rptr(PKCS12_AUTHSAFES), &p12->authsafes->d.data)) return 1; return 0; } STACK_OF(PKCS7) *PKCS12_unpack_authsafes(const PKCS12 *p12) { STACK_OF(PKCS7) *p7s; PKCS7_CTX *p7ctx; PKCS7 *p7; int i; if (!PKCS7_type_is_data(p12->authsafes)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CONTENT_TYPE_NOT_DATA); return NULL; } p7ctx = &p12->authsafes->ctx; p7s = ASN1_item_unpack_ex(p12->authsafes->d.data, ASN1_ITEM_rptr(PKCS12_AUTHSAFES), ossl_pkcs7_ctx_get0_libctx(p7ctx), ossl_pkcs7_ctx_get0_propq(p7ctx)); if (p7s != NULL) { for (i = 0; i < sk_PKCS7_num(p7s); i++) { p7 = sk_PKCS7_value(p7s, i); if (!ossl_pkcs7_ctx_propagate(p12->authsafes, p7)) goto err; } } return p7s; err: sk_PKCS7_free(p7s); return NULL; }
6,779
31.132701
82
c
openssl
openssl-master/crypto/pkcs12/p12_asn.c
/* * Copyright 2000-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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/pkcs12.h> #include "p12_local.h" #include "crypto/pkcs7.h" /* PKCS#12 ASN1 module */ ASN1_SEQUENCE(PKCS12) = { ASN1_SIMPLE(PKCS12, version, ASN1_INTEGER), ASN1_SIMPLE(PKCS12, authsafes, PKCS7), ASN1_OPT(PKCS12, mac, PKCS12_MAC_DATA) } ASN1_SEQUENCE_END(PKCS12) IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(PKCS12, PKCS12, PKCS12) PKCS12 *PKCS12_new(void) { return (PKCS12 *)ASN1_item_new(ASN1_ITEM_rptr(PKCS12)); } void PKCS12_free(PKCS12 *p12) { if (p12 != NULL && p12->authsafes != NULL) { OPENSSL_free(p12->authsafes->ctx.propq); p12->authsafes->ctx.propq = NULL; } ASN1_item_free((ASN1_VALUE *)p12, ASN1_ITEM_rptr(PKCS12)); } ASN1_SEQUENCE(PKCS12_MAC_DATA) = { ASN1_SIMPLE(PKCS12_MAC_DATA, dinfo, X509_SIG), ASN1_SIMPLE(PKCS12_MAC_DATA, salt, ASN1_OCTET_STRING), ASN1_OPT(PKCS12_MAC_DATA, iter, ASN1_INTEGER) } ASN1_SEQUENCE_END(PKCS12_MAC_DATA) IMPLEMENT_ASN1_FUNCTIONS(PKCS12_MAC_DATA) ASN1_ADB_TEMPLATE(bag_default) = ASN1_EXP(PKCS12_BAGS, value.other, ASN1_ANY, 0); ASN1_ADB(PKCS12_BAGS) = { ADB_ENTRY(NID_x509Certificate, ASN1_EXP(PKCS12_BAGS, value.x509cert, ASN1_OCTET_STRING, 0)), ADB_ENTRY(NID_x509Crl, ASN1_EXP(PKCS12_BAGS, value.x509crl, ASN1_OCTET_STRING, 0)), ADB_ENTRY(NID_sdsiCertificate, ASN1_EXP(PKCS12_BAGS, value.sdsicert, ASN1_IA5STRING, 0)), } ASN1_ADB_END(PKCS12_BAGS, 0, type, 0, &bag_default_tt, NULL); ASN1_SEQUENCE(PKCS12_BAGS) = { ASN1_SIMPLE(PKCS12_BAGS, type, ASN1_OBJECT), ASN1_ADB_OBJECT(PKCS12_BAGS), } ASN1_SEQUENCE_END(PKCS12_BAGS) IMPLEMENT_ASN1_FUNCTIONS(PKCS12_BAGS) ASN1_ADB_TEMPLATE(safebag_default) = ASN1_EXP(PKCS12_SAFEBAG, value.other, ASN1_ANY, 0); ASN1_ADB(PKCS12_SAFEBAG) = { ADB_ENTRY(NID_keyBag, ASN1_EXP(PKCS12_SAFEBAG, value.keybag, PKCS8_PRIV_KEY_INFO, 0)), ADB_ENTRY(NID_pkcs8ShroudedKeyBag, ASN1_EXP(PKCS12_SAFEBAG, value.shkeybag, X509_SIG, 0)), ADB_ENTRY(NID_safeContentsBag, ASN1_EXP_SEQUENCE_OF(PKCS12_SAFEBAG, value.safes, PKCS12_SAFEBAG, 0)), ADB_ENTRY(NID_certBag, ASN1_EXP(PKCS12_SAFEBAG, value.bag, PKCS12_BAGS, 0)), ADB_ENTRY(NID_crlBag, ASN1_EXP(PKCS12_SAFEBAG, value.bag, PKCS12_BAGS, 0)), ADB_ENTRY(NID_secretBag, ASN1_EXP(PKCS12_SAFEBAG, value.bag, PKCS12_BAGS, 0)) } ASN1_ADB_END(PKCS12_SAFEBAG, 0, type, 0, &safebag_default_tt, NULL); ASN1_SEQUENCE(PKCS12_SAFEBAG) = { ASN1_SIMPLE(PKCS12_SAFEBAG, type, ASN1_OBJECT), ASN1_ADB_OBJECT(PKCS12_SAFEBAG), ASN1_SET_OF_OPT(PKCS12_SAFEBAG, attrib, X509_ATTRIBUTE) } ASN1_SEQUENCE_END(PKCS12_SAFEBAG) IMPLEMENT_ASN1_FUNCTIONS(PKCS12_SAFEBAG) /* SEQUENCE OF SafeBag */ ASN1_ITEM_TEMPLATE(PKCS12_SAFEBAGS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, PKCS12_SAFEBAGS, PKCS12_SAFEBAG) ASN1_ITEM_TEMPLATE_END(PKCS12_SAFEBAGS) /* Authsafes: SEQUENCE OF PKCS7 */ ASN1_ITEM_TEMPLATE(PKCS12_AUTHSAFES) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, PKCS12_AUTHSAFES, PKCS7) ASN1_ITEM_TEMPLATE_END(PKCS12_AUTHSAFES)
3,479
36.826087
109
c
openssl
openssl-master/crypto/pkcs12/p12_attr.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 */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/pkcs12.h> #include "p12_local.h" /* Add a local keyid to a safebag */ int PKCS12_add_localkeyid(PKCS12_SAFEBAG *bag, unsigned char *name, int namelen) { if (X509at_add1_attr_by_NID(&bag->attrib, NID_localKeyID, V_ASN1_OCTET_STRING, name, namelen) != NULL) return 1; else return 0; } /* Add key usage to PKCS#8 structure */ int PKCS8_add_keyusage(PKCS8_PRIV_KEY_INFO *p8, int usage) { unsigned char us_val = (unsigned char)usage; return PKCS8_pkey_add1_attr_by_NID(p8, NID_key_usage, V_ASN1_BIT_STRING, &us_val, 1); } /* Add a friendlyname to a safebag */ int PKCS12_add_friendlyname_asc(PKCS12_SAFEBAG *bag, const char *name, int namelen) { if (X509at_add1_attr_by_NID(&bag->attrib, NID_friendlyName, MBSTRING_ASC, (unsigned char *)name, namelen) != NULL) return 1; else return 0; } int PKCS12_add_friendlyname_utf8(PKCS12_SAFEBAG *bag, const char *name, int namelen) { if (X509at_add1_attr_by_NID(&bag->attrib, NID_friendlyName, MBSTRING_UTF8, (unsigned char *)name, namelen) != NULL) return 1; else return 0; } int PKCS12_add_friendlyname_uni(PKCS12_SAFEBAG *bag, const unsigned char *name, int namelen) { if (X509at_add1_attr_by_NID(&bag->attrib, NID_friendlyName, MBSTRING_BMP, name, namelen) != NULL) return 1; else return 0; } int PKCS12_add_CSPName_asc(PKCS12_SAFEBAG *bag, const char *name, int namelen) { if (X509at_add1_attr_by_NID(&bag->attrib, NID_ms_csp_name, MBSTRING_ASC, (unsigned char *)name, namelen) != NULL) return 1; else return 0; } int PKCS12_add1_attr_by_NID(PKCS12_SAFEBAG *bag, int nid, int type, const unsigned char *bytes, int len) { if (X509at_add1_attr_by_NID(&bag->attrib, nid, type, bytes, len) != NULL) return 1; else return 0; } int PKCS12_add1_attr_by_txt(PKCS12_SAFEBAG *bag, const char *attrname, int type, const unsigned char *bytes, int len) { if (X509at_add1_attr_by_txt(&bag->attrib, attrname, type, bytes, len) != NULL) return 1; else return 0; } ASN1_TYPE *PKCS12_get_attr_gen(const STACK_OF(X509_ATTRIBUTE) *attrs, int attr_nid) { int i = X509at_get_attr_by_NID(attrs, attr_nid, -1); if (i < 0) return NULL; return X509_ATTRIBUTE_get0_type(X509at_get_attr(attrs, i), 0); } char *PKCS12_get_friendlyname(PKCS12_SAFEBAG *bag) { const ASN1_TYPE *atype; if ((atype = PKCS12_SAFEBAG_get0_attr(bag, NID_friendlyName)) == NULL) return NULL; if (atype->type != V_ASN1_BMPSTRING) return NULL; return OPENSSL_uni2utf8(atype->value.bmpstring->data, atype->value.bmpstring->length); } const STACK_OF(X509_ATTRIBUTE) * PKCS12_SAFEBAG_get0_attrs(const PKCS12_SAFEBAG *bag) { return bag->attrib; } void PKCS12_SAFEBAG_set0_attrs(PKCS12_SAFEBAG *bag, STACK_OF(X509_ATTRIBUTE) *attrs) { if (bag->attrib != attrs) sk_X509_ATTRIBUTE_free(bag->attrib); bag->attrib = attrs; }
3,806
28.284615
87
c
openssl
openssl-master/crypto/pkcs12/p12_crpt.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/core.h> #include <openssl/core_names.h> #include "crypto/evp.h" #include <openssl/pkcs12.h> /* PKCS#12 PBE algorithms now in static table */ void PKCS12_PBE_add(void) { } int PKCS12_PBE_keyivgen_ex(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md, int en_de, OSSL_LIB_CTX *libctx, const char *propq) { PBEPARAM *pbe; int saltlen, iter, ret; unsigned char *salt; unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH]; unsigned char *piv = iv; if (cipher == NULL) return 0; /* Extract useful info from parameter */ pbe = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(PBEPARAM), param); if (pbe == NULL) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_DECODE_ERROR); return 0; } if (pbe->iter == NULL) iter = 1; else iter = ASN1_INTEGER_get(pbe->iter); salt = pbe->salt->data; saltlen = pbe->salt->length; if (!PKCS12_key_gen_utf8_ex(pass, passlen, salt, saltlen, PKCS12_KEY_ID, iter, EVP_CIPHER_get_key_length(cipher), key, md, libctx, propq)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_KEY_GEN_ERROR); PBEPARAM_free(pbe); return 0; } if (EVP_CIPHER_get_iv_length(cipher) > 0) { if (!PKCS12_key_gen_utf8_ex(pass, passlen, salt, saltlen, PKCS12_IV_ID, iter, EVP_CIPHER_get_iv_length(cipher), iv, md, libctx, propq)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_IV_GEN_ERROR); PBEPARAM_free(pbe); return 0; } } else { piv = NULL; } PBEPARAM_free(pbe); ret = EVP_CipherInit_ex(ctx, cipher, NULL, key, piv, en_de); OPENSSL_cleanse(key, EVP_MAX_KEY_LENGTH); OPENSSL_cleanse(iv, EVP_MAX_IV_LENGTH); return ret; } int PKCS12_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen, ASN1_TYPE *param, const EVP_CIPHER *cipher, const EVP_MD *md, int en_de) { return PKCS12_PBE_keyivgen_ex(ctx, pass, passlen, param, cipher, md, en_de, NULL, NULL); }
2,793
31.488372
79
c
openssl
openssl-master/crypto/pkcs12/p12_crt.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/pkcs12.h> #include "p12_local.h" static int pkcs12_add_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, PKCS12_SAFEBAG *bag); static int pkcs12_remove_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, PKCS12_SAFEBAG *bag); static int copy_bag_attr(PKCS12_SAFEBAG *bag, EVP_PKEY *pkey, int nid) { int idx = EVP_PKEY_get_attr_by_NID(pkey, nid, -1); if (idx < 0) return 1; return X509at_add1_attr(&bag->attrib, EVP_PKEY_get_attr(pkey, idx)) != NULL; } PKCS12 *PKCS12_create_ex2(const char *pass, const char *name, EVP_PKEY *pkey, X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert, int iter, int mac_iter, int keytype, OSSL_LIB_CTX *ctx, const char *propq, PKCS12_create_cb *cb, void *cbarg) { PKCS12 *p12 = NULL; STACK_OF(PKCS7) *safes = NULL; STACK_OF(PKCS12_SAFEBAG) *bags = NULL; PKCS12_SAFEBAG *bag = NULL; int i, cbret; unsigned char keyid[EVP_MAX_MD_SIZE]; unsigned int keyidlen = 0; /* Set defaults */ if (nid_cert == NID_undef) nid_cert = NID_aes_256_cbc; if (nid_key == NID_undef) nid_key = NID_aes_256_cbc; if (!iter) iter = PKCS12_DEFAULT_ITER; if (!mac_iter) mac_iter = PKCS12_DEFAULT_ITER; if (pkey == NULL && cert == NULL && ca == NULL) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_INVALID_NULL_ARGUMENT); return NULL; } if (pkey && cert) { if (!X509_check_private_key(cert, pkey)) return NULL; if (!X509_digest(cert, EVP_sha1(), keyid, &keyidlen)) return NULL; } if (cert) { bag = PKCS12_add_cert(&bags, cert); if (name && !PKCS12_add_friendlyname(bag, name, -1)) goto err; if (keyidlen && !PKCS12_add_localkeyid(bag, keyid, keyidlen)) goto err; if (cb != NULL) { cbret = cb(bag, cbarg); if (cbret == -1) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CALLBACK_FAILED); goto err; } else if (cbret == 0) { pkcs12_remove_bag(&bags, bag); } } } /* Add all other certificates */ for (i = 0; i < sk_X509_num(ca); i++) { if ((bag = PKCS12_add_cert(&bags, sk_X509_value(ca, i))) == NULL) goto err; if (cb != NULL) { cbret = cb(bag, cbarg); if (cbret == -1) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CALLBACK_FAILED); goto err; } else if (cbret == 0) { pkcs12_remove_bag(&bags, bag); } } } if (bags && !PKCS12_add_safe_ex(&safes, bags, nid_cert, iter, pass, ctx, propq)) goto err; sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); bags = NULL; if (pkey) { bag = PKCS12_add_key_ex(&bags, pkey, keytype, iter, nid_key, pass, ctx, propq); if (!bag) goto err; if (!copy_bag_attr(bag, pkey, NID_ms_csp_name)) goto err; if (!copy_bag_attr(bag, pkey, NID_LocalKeySet)) goto err; if (name && !PKCS12_add_friendlyname(bag, name, -1)) goto err; if (keyidlen && !PKCS12_add_localkeyid(bag, keyid, keyidlen)) goto err; if (cb != NULL) { cbret = cb(bag, cbarg); if (cbret == -1) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CALLBACK_FAILED); goto err; } else if (cbret == 0) { pkcs12_remove_bag(&bags, bag); } } } if (bags && !PKCS12_add_safe(&safes, bags, -1, 0, NULL)) goto err; sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); bags = NULL; p12 = PKCS12_add_safes_ex(safes, 0, ctx, propq); if (p12 == NULL) goto err; sk_PKCS7_pop_free(safes, PKCS7_free); safes = NULL; if ((mac_iter != -1) && !PKCS12_set_mac(p12, pass, -1, NULL, 0, mac_iter, NULL)) goto err; return p12; err: PKCS12_free(p12); sk_PKCS7_pop_free(safes, PKCS7_free); sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); return NULL; } PKCS12 *PKCS12_create_ex(const char *pass, const char *name, EVP_PKEY *pkey, X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert, int iter, int mac_iter, int keytype, OSSL_LIB_CTX *ctx, const char *propq) { return PKCS12_create_ex2(pass, name, pkey, cert, ca, nid_key, nid_cert, iter, mac_iter, keytype, ctx, propq, NULL, NULL); } PKCS12 *PKCS12_create(const char *pass, const char *name, EVP_PKEY *pkey, X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert, int iter, int mac_iter, int keytype) { return PKCS12_create_ex(pass, name, pkey, cert, ca, nid_key, nid_cert, iter, mac_iter, keytype, NULL, NULL); } PKCS12_SAFEBAG *PKCS12_add_cert(STACK_OF(PKCS12_SAFEBAG) **pbags, X509 *cert) { PKCS12_SAFEBAG *bag = NULL; char *name; int namelen = -1; unsigned char *keyid; int keyidlen = -1; /* Add user certificate */ if ((bag = PKCS12_SAFEBAG_create_cert(cert)) == NULL) goto err; /* * Use friendlyName and localKeyID in certificate. (if present) */ name = (char *)X509_alias_get0(cert, &namelen); if (name && !PKCS12_add_friendlyname(bag, name, namelen)) goto err; keyid = X509_keyid_get0(cert, &keyidlen); if (keyid && !PKCS12_add_localkeyid(bag, keyid, keyidlen)) goto err; if (!pkcs12_add_bag(pbags, bag)) goto err; return bag; err: PKCS12_SAFEBAG_free(bag); return NULL; } PKCS12_SAFEBAG *PKCS12_add_key_ex(STACK_OF(PKCS12_SAFEBAG) **pbags, EVP_PKEY *key, int key_usage, int iter, int nid_key, const char *pass, OSSL_LIB_CTX *ctx, const char *propq) { PKCS12_SAFEBAG *bag = NULL; PKCS8_PRIV_KEY_INFO *p8 = NULL; /* Make a PKCS#8 structure */ if ((p8 = EVP_PKEY2PKCS8(key)) == NULL) goto err; if (key_usage && !PKCS8_add_keyusage(p8, key_usage)) goto err; if (nid_key != -1) { bag = PKCS12_SAFEBAG_create_pkcs8_encrypt_ex(nid_key, pass, -1, NULL, 0, iter, p8, ctx, propq); PKCS8_PRIV_KEY_INFO_free(p8); } else bag = PKCS12_SAFEBAG_create0_p8inf(p8); if (!bag) goto err; if (!pkcs12_add_bag(pbags, bag)) goto err; return bag; err: PKCS12_SAFEBAG_free(bag); return NULL; } PKCS12_SAFEBAG *PKCS12_add_key(STACK_OF(PKCS12_SAFEBAG) **pbags, EVP_PKEY *key, int key_usage, int iter, int nid_key, const char *pass) { return PKCS12_add_key_ex(pbags, key, key_usage, iter, nid_key, pass, NULL, NULL); } PKCS12_SAFEBAG *PKCS12_add_secret(STACK_OF(PKCS12_SAFEBAG) **pbags, int nid_type, const unsigned char *value, int len) { PKCS12_SAFEBAG *bag = NULL; /* Add secret, storing the value as an octet string */ if ((bag = PKCS12_SAFEBAG_create_secret(nid_type, V_ASN1_OCTET_STRING, value, len)) == NULL) goto err; if (!pkcs12_add_bag(pbags, bag)) goto err; return bag; err: PKCS12_SAFEBAG_free(bag); return NULL; } int PKCS12_add_safe_ex(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags, int nid_safe, int iter, const char *pass, OSSL_LIB_CTX *ctx, const char *propq) { PKCS7 *p7 = NULL; int free_safes = 0; if (*psafes == NULL) { *psafes = sk_PKCS7_new_null(); if (*psafes == NULL) return 0; free_safes = 1; } if (nid_safe == 0) #ifdef OPENSSL_NO_RC2 nid_safe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC; #else nid_safe = NID_pbe_WithSHA1And40BitRC2_CBC; #endif if (nid_safe == -1) p7 = PKCS12_pack_p7data(bags); else p7 = PKCS12_pack_p7encdata_ex(nid_safe, pass, -1, NULL, 0, iter, bags, ctx, propq); if (p7 == NULL) goto err; if (!sk_PKCS7_push(*psafes, p7)) goto err; return 1; err: if (free_safes) { sk_PKCS7_free(*psafes); *psafes = NULL; } PKCS7_free(p7); return 0; } int PKCS12_add_safe(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags, int nid_safe, int iter, const char *pass) { return PKCS12_add_safe_ex(psafes, bags, nid_safe, iter, pass, NULL, NULL); } static int pkcs12_remove_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, PKCS12_SAFEBAG *bag) { PKCS12_SAFEBAG *tmp; if (pbags == NULL || bag == NULL) return 1; if ((tmp = sk_PKCS12_SAFEBAG_delete_ptr(*pbags, bag)) == NULL) return 0; PKCS12_SAFEBAG_free(tmp); return 1; } static int pkcs12_add_bag(STACK_OF(PKCS12_SAFEBAG) **pbags, PKCS12_SAFEBAG *bag) { int free_bags = 0; if (pbags == NULL) return 1; if (*pbags == NULL) { *pbags = sk_PKCS12_SAFEBAG_new_null(); if (*pbags == NULL) return 0; free_bags = 1; } if (!sk_PKCS12_SAFEBAG_push(*pbags, bag)) { if (free_bags) { sk_PKCS12_SAFEBAG_free(*pbags); *pbags = NULL; } return 0; } return 1; } PKCS12 *PKCS12_add_safes_ex(STACK_OF(PKCS7) *safes, int nid_p7, OSSL_LIB_CTX *ctx, const char *propq) { PKCS12 *p12; if (nid_p7 <= 0) nid_p7 = NID_pkcs7_data; p12 = PKCS12_init_ex(nid_p7, ctx, propq); if (p12 == NULL) return NULL; if (!PKCS12_pack_authsafes(p12, safes)) { PKCS12_free(p12); return NULL; } return p12; } PKCS12 *PKCS12_add_safes(STACK_OF(PKCS7) *safes, int nid_p7) { return PKCS12_add_safes_ex(safes, nid_p7, NULL, NULL); }
10,723
26.497436
96
c
openssl
openssl-master/crypto/pkcs12/p12_decr.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/pkcs12.h> #include <openssl/trace.h> /* * Encrypt/Decrypt a buffer based on password and algor, result in a * OPENSSL_malloc'ed buffer */ unsigned char *PKCS12_pbe_crypt_ex(const X509_ALGOR *algor, const char *pass, int passlen, const unsigned char *in, int inlen, unsigned char **data, int *datalen, int en_de, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char *out = NULL; int outlen, i; EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); int max_out_len, mac_len = 0; if (ctx == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_EVP_LIB); goto err; } /* Process data */ if (!EVP_PBE_CipherInit_ex(algor->algorithm, pass, passlen, algor->parameter, ctx, en_de, libctx, propq)) goto err; /* * GOST algorithm specifics: * OMAC algorithm calculate and encrypt MAC of the encrypted objects * It's appended to encrypted text on encrypting * MAC should be processed on decrypting separately from plain text */ max_out_len = inlen + EVP_CIPHER_CTX_get_block_size(ctx); if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx)) & EVP_CIPH_FLAG_CIPHER_WITH_MAC) != 0) { if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_TLS1_AAD, 0, &mac_len) < 0) { ERR_raise(ERR_LIB_PKCS12, ERR_R_INTERNAL_ERROR); goto err; } if (EVP_CIPHER_CTX_is_encrypting(ctx)) { max_out_len += mac_len; } else { if (inlen < mac_len) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_UNSUPPORTED_PKCS12_MODE); goto err; } inlen -= mac_len; if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, (int)mac_len, (unsigned char *)in+inlen) < 0) { ERR_raise(ERR_LIB_PKCS12, ERR_R_INTERNAL_ERROR); goto err; } } } if ((out = OPENSSL_malloc(max_out_len)) == NULL) goto err; if (!EVP_CipherUpdate(ctx, out, &i, in, inlen)) { OPENSSL_free(out); out = NULL; ERR_raise(ERR_LIB_PKCS12, ERR_R_EVP_LIB); goto err; } outlen = i; if (!EVP_CipherFinal_ex(ctx, out + i, &i)) { OPENSSL_free(out); out = NULL; ERR_raise_data(ERR_LIB_PKCS12, PKCS12_R_PKCS12_CIPHERFINAL_ERROR, passlen == 0 ? "empty password" : "maybe wrong password"); goto err; } outlen += i; if ((EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(ctx)) & EVP_CIPH_FLAG_CIPHER_WITH_MAC) != 0) { if (EVP_CIPHER_CTX_is_encrypting(ctx)) { if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, (int)mac_len, out+outlen) < 0) { OPENSSL_free(out); out = NULL; ERR_raise(ERR_LIB_PKCS12, ERR_R_INTERNAL_ERROR); goto err; } outlen += mac_len; } } if (datalen) *datalen = outlen; if (data) *data = out; err: EVP_CIPHER_CTX_free(ctx); return out; } unsigned char *PKCS12_pbe_crypt(const X509_ALGOR *algor, const char *pass, int passlen, const unsigned char *in, int inlen, unsigned char **data, int *datalen, int en_de) { return PKCS12_pbe_crypt_ex(algor, pass, passlen, in, inlen, data, datalen, en_de, NULL, NULL); } /* * Decrypt an OCTET STRING and decode ASN1 structure if zbuf set zero buffer * after use. */ void *PKCS12_item_decrypt_d2i_ex(const X509_ALGOR *algor, const ASN1_ITEM *it, const char *pass, int passlen, const ASN1_OCTET_STRING *oct, int zbuf, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char *out = NULL; const unsigned char *p; void *ret; int outlen = 0; if (!PKCS12_pbe_crypt_ex(algor, pass, passlen, oct->data, oct->length, &out, &outlen, 0, libctx, propq)) return NULL; p = out; OSSL_TRACE_BEGIN(PKCS12_DECRYPT) { BIO_printf(trc_out, "\n"); BIO_dump(trc_out, out, outlen); BIO_printf(trc_out, "\n"); } OSSL_TRACE_END(PKCS12_DECRYPT); ret = ASN1_item_d2i(NULL, &p, outlen, it); if (zbuf) OPENSSL_cleanse(out, outlen); if (!ret) ERR_raise(ERR_LIB_PKCS12, PKCS12_R_DECODE_ERROR); OPENSSL_free(out); return ret; } void *PKCS12_item_decrypt_d2i(const X509_ALGOR *algor, const ASN1_ITEM *it, const char *pass, int passlen, const ASN1_OCTET_STRING *oct, int zbuf) { return PKCS12_item_decrypt_d2i_ex(algor, it, pass, passlen, oct, zbuf, NULL, NULL); } /* * Encode ASN1 structure and encrypt, return OCTET STRING if zbuf set zero * encoding. */ ASN1_OCTET_STRING *PKCS12_item_i2d_encrypt_ex(X509_ALGOR *algor, const ASN1_ITEM *it, const char *pass, int passlen, void *obj, int zbuf, OSSL_LIB_CTX *ctx, const char *propq) { ASN1_OCTET_STRING *oct = NULL; unsigned char *in = NULL; int inlen; if ((oct = ASN1_OCTET_STRING_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } inlen = ASN1_item_i2d(obj, &in, it); if (!in) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_ENCODE_ERROR); goto err; } if (!PKCS12_pbe_crypt_ex(algor, pass, passlen, in, inlen, &oct->data, &oct->length, 1, ctx, propq)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_ENCRYPT_ERROR); OPENSSL_free(in); goto err; } if (zbuf) OPENSSL_cleanse(in, inlen); OPENSSL_free(in); return oct; err: ASN1_OCTET_STRING_free(oct); return NULL; } ASN1_OCTET_STRING *PKCS12_item_i2d_encrypt(X509_ALGOR *algor, const ASN1_ITEM *it, const char *pass, int passlen, void *obj, int zbuf) { return PKCS12_item_i2d_encrypt_ex(algor, it, pass, passlen, obj, zbuf, NULL, NULL); }
7,114
32.720379
87
c
openssl
openssl-master/crypto/pkcs12/p12_init.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/pkcs12.h> #include "crypto/pkcs7.h" #include "p12_local.h" /* Initialise a PKCS12 structure to take data */ PKCS12 *PKCS12_init_ex(int mode, OSSL_LIB_CTX *ctx, const char *propq) { PKCS12 *pkcs12; if ((pkcs12 = PKCS12_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } if (!ASN1_INTEGER_set(pkcs12->version, 3)) goto err; pkcs12->authsafes->type = OBJ_nid2obj(mode); ossl_pkcs7_set0_libctx(pkcs12->authsafes, ctx); if (!ossl_pkcs7_set1_propq(pkcs12->authsafes, propq)) { ERR_raise(ERR_LIB_PKCS12, ERR_R_PKCS7_LIB); goto err; } switch (mode) { case NID_pkcs7_data: if ((pkcs12->authsafes->d.data = ASN1_OCTET_STRING_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } break; default: ERR_raise(ERR_LIB_PKCS12, PKCS12_R_UNSUPPORTED_PKCS12_MODE); goto err; } return pkcs12; err: PKCS12_free(pkcs12); return NULL; } PKCS12 *PKCS12_init(int mode) { return PKCS12_init_ex(mode, NULL, NULL); } const PKCS7_CTX *ossl_pkcs12_get0_pkcs7ctx(const PKCS12 *p12) { if (p12 == NULL || p12->authsafes == NULL) return NULL; return &p12->authsafes->ctx; }
1,682
24.892308
76
c
openssl
openssl-master/crypto/pkcs12/p12_key.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/pkcs12.h> #include <openssl/bn.h> #include <openssl/trace.h> #include <openssl/kdf.h> #include <openssl/core_names.h> #include "internal/provider.h" int PKCS12_key_gen_asc_ex(const char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type, OSSL_LIB_CTX *ctx, const char *propq) { int ret; unsigned char *unipass; int uniplen; if (pass == NULL) { unipass = NULL; uniplen = 0; } else if (!OPENSSL_asc2uni(pass, passlen, &unipass, &uniplen)) { ERR_raise(ERR_LIB_PKCS12, ERR_R_PKCS12_LIB); return 0; } ret = PKCS12_key_gen_uni_ex(unipass, uniplen, salt, saltlen, id, iter, n, out, md_type, ctx, propq); OPENSSL_clear_free(unipass, uniplen); return ret > 0; } int PKCS12_key_gen_asc(const char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type) { return PKCS12_key_gen_asc_ex(pass, passlen, salt, saltlen, id, iter, n, out, md_type, NULL, NULL); } int PKCS12_key_gen_utf8_ex(const char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type, OSSL_LIB_CTX *ctx, const char *propq) { int ret; unsigned char *unipass; int uniplen; if (pass == NULL) { unipass = NULL; uniplen = 0; } else if (!OPENSSL_utf82uni(pass, passlen, &unipass, &uniplen)) { ERR_raise(ERR_LIB_PKCS12, ERR_R_PKCS12_LIB); return 0; } ret = PKCS12_key_gen_uni_ex(unipass, uniplen, salt, saltlen, id, iter, n, out, md_type, ctx, propq); OPENSSL_clear_free(unipass, uniplen); return ret > 0; } int PKCS12_key_gen_utf8(const char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type) { return PKCS12_key_gen_utf8_ex(pass, passlen, salt, saltlen, id, iter, n, out, md_type, NULL, NULL); } int PKCS12_key_gen_uni_ex(unsigned char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type, OSSL_LIB_CTX *libctx, const char *propq) { int res = 0; EVP_KDF *kdf; EVP_KDF_CTX *ctx; OSSL_PARAM params[6], *p = params; if (n <= 0) return 0; kdf = EVP_KDF_fetch(libctx, "PKCS12KDF", propq); if (kdf == NULL) return 0; ctx = EVP_KDF_CTX_new(kdf); EVP_KDF_free(kdf); if (ctx == NULL) return 0; *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST, (char *)EVP_MD_get0_name(md_type), 0); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PASSWORD, pass, passlen); *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT, salt, saltlen); *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_PKCS12_ID, &id); *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_ITER, &iter); *p = OSSL_PARAM_construct_end(); OSSL_TRACE_BEGIN(PKCS12_KEYGEN) { BIO_printf(trc_out, "PKCS12_key_gen_uni_ex(): ID %d, ITER %d\n", id, iter); BIO_printf(trc_out, "Password (length %d):\n", passlen); BIO_hex_string(trc_out, 0, passlen, pass, passlen); BIO_printf(trc_out, "\n"); BIO_printf(trc_out, "Salt (length %d):\n", saltlen); BIO_hex_string(trc_out, 0, saltlen, salt, saltlen); BIO_printf(trc_out, "\n"); } OSSL_TRACE_END(PKCS12_KEYGEN); if (EVP_KDF_derive(ctx, out, (size_t)n, params)) { res = 1; OSSL_TRACE_BEGIN(PKCS12_KEYGEN) { BIO_printf(trc_out, "Output KEY (length %d)\n", n); BIO_hex_string(trc_out, 0, n, out, n); BIO_printf(trc_out, "\n"); } OSSL_TRACE_END(PKCS12_KEYGEN); } EVP_KDF_CTX_free(ctx); return res; } int PKCS12_key_gen_uni(unsigned char *pass, int passlen, unsigned char *salt, int saltlen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type) { return PKCS12_key_gen_uni_ex(pass, passlen, salt, saltlen, id, iter, n, out, md_type, NULL, NULL); }
5,138
35.971223
102
c
openssl
openssl-master/crypto/pkcs12/p12_kiss.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/pkcs12.h> #include "crypto/x509.h" /* for ossl_x509_add_cert_new() */ /* Simplified PKCS#12 routines */ static int parse_pk12(PKCS12 *p12, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts); static int parse_bags(const STACK_OF(PKCS12_SAFEBAG) *bags, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts, OSSL_LIB_CTX *libctx, const char *propq); static int parse_bag(PKCS12_SAFEBAG *bag, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts, OSSL_LIB_CTX *libctx, const char *propq); /* * Parse and decrypt a PKCS#12 structure returning user key, user cert and * other (CA) certs. Note either ca should be NULL, *ca should be NULL, or it * should point to a valid STACK structure. pkey and/or cert may be NULL; * if non-NULL the variables they point to can be passed uninitialised. */ int PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey, X509 **cert, STACK_OF(X509) **ca) { STACK_OF(X509) *ocerts = NULL; X509 *x = NULL; if (pkey != NULL) *pkey = NULL; if (cert != NULL) *cert = NULL; /* Check for NULL PKCS12 structure */ if (p12 == NULL) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_INVALID_NULL_PKCS12_POINTER); return 0; } /* Check the mac */ if (PKCS12_mac_present(p12)) { /* * If password is zero length or NULL then try verifying both cases to * determine which password is correct. The reason for this is that under * PKCS#12 password based encryption no password and a zero length * password are two different things... */ if (pass == NULL || *pass == '\0') { if (PKCS12_verify_mac(p12, NULL, 0)) pass = NULL; else if (PKCS12_verify_mac(p12, "", 0)) pass = ""; else { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_VERIFY_FAILURE); goto err; } } else if (!PKCS12_verify_mac(p12, pass, -1)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_VERIFY_FAILURE); goto err; } } else if (pass == NULL || *pass == '\0') { pass = NULL; } /* If needed, allocate stack for other certificates */ if ((cert != NULL || ca != NULL) && (ocerts = sk_X509_new_null()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_CRYPTO_LIB); goto err; } if (!parse_pk12(p12, pass, -1, pkey, ocerts)) { int err = ERR_peek_last_error(); if (ERR_GET_LIB(err) != ERR_LIB_EVP && ERR_GET_REASON(err) != EVP_R_UNSUPPORTED_ALGORITHM) ERR_raise(ERR_LIB_PKCS12, PKCS12_R_PARSE_ERROR); goto err; } /* Split the certs in ocerts over *cert and *ca as far as requested */ while ((x = sk_X509_shift(ocerts)) != NULL) { if (pkey != NULL && *pkey != NULL && cert != NULL && *cert == NULL) { int match; ERR_set_mark(); match = X509_check_private_key(x, *pkey); ERR_pop_to_mark(); if (match) { *cert = x; continue; } } if (ca != NULL) { if (!ossl_x509_add_cert_new(ca, x, X509_ADD_FLAG_DEFAULT)) goto err; continue; } X509_free(x); } sk_X509_free(ocerts); return 1; err: if (pkey != NULL) { EVP_PKEY_free(*pkey); *pkey = NULL; } if (cert != NULL) { X509_free(*cert); *cert = NULL; } X509_free(x); OSSL_STACK_OF_X509_free(ocerts); return 0; } /* Parse the outer PKCS#12 structure */ /* pkey and/or ocerts may be NULL */ static int parse_pk12(PKCS12 *p12, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts) { STACK_OF(PKCS7) *asafes; STACK_OF(PKCS12_SAFEBAG) *bags; int i, bagnid; PKCS7 *p7; if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL) return 0; for (i = 0; i < sk_PKCS7_num(asafes); i++) { p7 = sk_PKCS7_value(asafes, i); bagnid = OBJ_obj2nid(p7->type); if (bagnid == NID_pkcs7_data) { bags = PKCS12_unpack_p7data(p7); } else if (bagnid == NID_pkcs7_encrypted) { bags = PKCS12_unpack_p7encdata(p7, pass, passlen); } else continue; if (!bags) { sk_PKCS7_pop_free(asafes, PKCS7_free); return 0; } if (!parse_bags(bags, pass, passlen, pkey, ocerts, p7->ctx.libctx, p7->ctx.propq)) { sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); sk_PKCS7_pop_free(asafes, PKCS7_free); return 0; } sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); } sk_PKCS7_pop_free(asafes, PKCS7_free); return 1; } /* pkey and/or ocerts may be NULL */ static int parse_bags(const STACK_OF(PKCS12_SAFEBAG) *bags, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts, OSSL_LIB_CTX *libctx, const char *propq) { int i; for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) { if (!parse_bag(sk_PKCS12_SAFEBAG_value(bags, i), pass, passlen, pkey, ocerts, libctx, propq)) return 0; } return 1; } /* pkey and/or ocerts may be NULL */ static int parse_bag(PKCS12_SAFEBAG *bag, const char *pass, int passlen, EVP_PKEY **pkey, STACK_OF(X509) *ocerts, OSSL_LIB_CTX *libctx, const char *propq) { PKCS8_PRIV_KEY_INFO *p8; X509 *x509; const ASN1_TYPE *attrib; ASN1_BMPSTRING *fname = NULL; ASN1_OCTET_STRING *lkid = NULL; if ((attrib = PKCS12_SAFEBAG_get0_attr(bag, NID_friendlyName))) fname = attrib->value.bmpstring; if ((attrib = PKCS12_SAFEBAG_get0_attr(bag, NID_localKeyID))) lkid = attrib->value.octet_string; switch (PKCS12_SAFEBAG_get_nid(bag)) { case NID_keyBag: if (pkey == NULL || *pkey != NULL) return 1; *pkey = EVP_PKCS82PKEY_ex(PKCS12_SAFEBAG_get0_p8inf(bag), libctx, propq); if (*pkey == NULL) return 0; break; case NID_pkcs8ShroudedKeyBag: if (pkey == NULL || *pkey != NULL) return 1; if ((p8 = PKCS12_decrypt_skey_ex(bag, pass, passlen, libctx, propq)) == NULL) return 0; *pkey = EVP_PKCS82PKEY_ex(p8, libctx, propq); PKCS8_PRIV_KEY_INFO_free(p8); if (!(*pkey)) return 0; break; case NID_certBag: if (ocerts == NULL || PKCS12_SAFEBAG_get_bag_nid(bag) != NID_x509Certificate) return 1; if ((x509 = PKCS12_SAFEBAG_get1_cert_ex(bag, libctx, propq)) == NULL) return 0; if (lkid && !X509_keyid_set1(x509, lkid->data, lkid->length)) { X509_free(x509); return 0; } if (fname) { int len, r; unsigned char *data; len = ASN1_STRING_to_UTF8(&data, fname); if (len >= 0) { r = X509_alias_set1(x509, data, len); OPENSSL_free(data); if (!r) { X509_free(x509); return 0; } } } if (!sk_X509_push(ocerts, x509)) { X509_free(x509); return 0; } break; case NID_safeContentsBag: return parse_bags(PKCS12_SAFEBAG_get0_safes(bag), pass, passlen, pkey, ocerts, libctx, propq); default: return 1; } return 1; }
8,350
30.04461
81
c
openssl
openssl-master/crypto/pkcs12/p12_local.h
/* * Copyright 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 */ struct PKCS12_MAC_DATA_st { X509_SIG *dinfo; ASN1_OCTET_STRING *salt; ASN1_INTEGER *iter; /* defaults to 1 */ }; struct PKCS12_st { ASN1_INTEGER *version; PKCS12_MAC_DATA *mac; PKCS7 *authsafes; }; struct PKCS12_SAFEBAG_st { ASN1_OBJECT *type; union { struct pkcs12_bag_st *bag; /* secret, crl and certbag */ struct pkcs8_priv_key_info_st *keybag; /* keybag */ X509_SIG *shkeybag; /* shrouded key bag */ STACK_OF(PKCS12_SAFEBAG) *safes; ASN1_TYPE *other; } value; STACK_OF(X509_ATTRIBUTE) *attrib; }; struct pkcs12_bag_st { ASN1_OBJECT *type; union { ASN1_OCTET_STRING *x509cert; ASN1_OCTET_STRING *x509crl; ASN1_OCTET_STRING *octet; ASN1_IA5STRING *sdsicert; ASN1_TYPE *other; /* Secret or other bag */ } value; }; const PKCS7_CTX *ossl_pkcs12_get0_pkcs7ctx(const PKCS12 *p12);
1,265
26.521739
74
h
openssl
openssl-master/crypto/pkcs12/p12_mutl.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 */ /* * HMAC 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/crypto.h> #include <openssl/hmac.h> #include <openssl/rand.h> #include <openssl/pkcs12.h> #include "p12_local.h" int PKCS12_mac_present(const PKCS12 *p12) { return p12->mac ? 1 : 0; } void PKCS12_get0_mac(const ASN1_OCTET_STRING **pmac, const X509_ALGOR **pmacalg, const ASN1_OCTET_STRING **psalt, const ASN1_INTEGER **piter, const PKCS12 *p12) { if (p12->mac) { X509_SIG_get0(p12->mac->dinfo, pmacalg, pmac); if (psalt) *psalt = p12->mac->salt; if (piter) *piter = p12->mac->iter; } else { if (pmac) *pmac = NULL; if (pmacalg) *pmacalg = NULL; if (psalt) *psalt = NULL; if (piter) *piter = NULL; } } #define TK26_MAC_KEY_LEN 32 static int pkcs12_gen_gost_mac_key(const char *pass, int passlen, const unsigned char *salt, int saltlen, int iter, int keylen, unsigned char *key, const EVP_MD *digest) { unsigned char out[96]; if (keylen != TK26_MAC_KEY_LEN) { return 0; } if (!PKCS5_PBKDF2_HMAC(pass, passlen, salt, saltlen, iter, digest, sizeof(out), out)) { return 0; } memcpy(key, out + sizeof(out) - TK26_MAC_KEY_LEN, TK26_MAC_KEY_LEN); OPENSSL_cleanse(out, sizeof(out)); return 1; } /* Generate a MAC */ static int pkcs12_gen_mac(PKCS12 *p12, const char *pass, int passlen, unsigned char *mac, unsigned int *maclen, int (*pkcs12_key_gen)(const char *pass, int passlen, unsigned char *salt, int slen, int id, int iter, int n, unsigned char *out, const EVP_MD *md_type)) { int ret = 0; const EVP_MD *md; EVP_MD *md_fetch; HMAC_CTX *hmac = NULL; unsigned char key[EVP_MAX_MD_SIZE], *salt; int saltlen, iter; char md_name[80]; int md_size = 0; int md_nid; const X509_ALGOR *macalg; const ASN1_OBJECT *macoid; if (!PKCS7_type_is_data(p12->authsafes)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_CONTENT_TYPE_NOT_DATA); return 0; } salt = p12->mac->salt->data; saltlen = p12->mac->salt->length; if (p12->mac->iter == NULL) iter = 1; else iter = ASN1_INTEGER_get(p12->mac->iter); X509_SIG_get0(p12->mac->dinfo, &macalg, NULL); X509_ALGOR_get0(&macoid, NULL, NULL, macalg); if (OBJ_obj2txt(md_name, sizeof(md_name), macoid, 0) < 0) return 0; (void)ERR_set_mark(); md = md_fetch = EVP_MD_fetch(p12->authsafes->ctx.libctx, md_name, p12->authsafes->ctx.propq); if (md == NULL) md = EVP_get_digestbynid(OBJ_obj2nid(macoid)); if (md == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_PKCS12, PKCS12_R_UNKNOWN_DIGEST_ALGORITHM); return 0; } (void)ERR_pop_to_mark(); md_size = EVP_MD_get_size(md); md_nid = EVP_MD_get_type(md); if (md_size < 0) goto err; if ((md_nid == NID_id_GostR3411_94 || md_nid == NID_id_GostR3411_2012_256 || md_nid == NID_id_GostR3411_2012_512) && ossl_safe_getenv("LEGACY_GOST_PKCS12") == NULL) { md_size = TK26_MAC_KEY_LEN; if (!pkcs12_gen_gost_mac_key(pass, passlen, salt, saltlen, iter, md_size, key, md)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_KEY_GEN_ERROR); goto err; } } else { if (pkcs12_key_gen != NULL) { if (!(*pkcs12_key_gen)(pass, passlen, salt, saltlen, PKCS12_MAC_ID, iter, md_size, key, md)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_KEY_GEN_ERROR); goto err; } } else { /* Default to UTF-8 password */ if (!PKCS12_key_gen_utf8_ex(pass, passlen, salt, saltlen, PKCS12_MAC_ID, iter, md_size, key, md, p12->authsafes->ctx.libctx, p12->authsafes->ctx.propq)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_KEY_GEN_ERROR); goto err; } } } if ((hmac = HMAC_CTX_new()) == NULL || !HMAC_Init_ex(hmac, key, md_size, md, NULL) || !HMAC_Update(hmac, p12->authsafes->d.data->data, p12->authsafes->d.data->length) || !HMAC_Final(hmac, mac, maclen)) { goto err; } ret = 1; err: OPENSSL_cleanse(key, sizeof(key)); HMAC_CTX_free(hmac); EVP_MD_free(md_fetch); return ret; } int PKCS12_gen_mac(PKCS12 *p12, const char *pass, int passlen, unsigned char *mac, unsigned int *maclen) { return pkcs12_gen_mac(p12, pass, passlen, mac, maclen, NULL); } /* Verify the mac */ int PKCS12_verify_mac(PKCS12 *p12, const char *pass, int passlen) { unsigned char mac[EVP_MAX_MD_SIZE]; unsigned int maclen; const ASN1_OCTET_STRING *macoct; if (p12->mac == NULL) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_ABSENT); return 0; } if (!pkcs12_gen_mac(p12, pass, passlen, mac, &maclen, NULL)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_GENERATION_ERROR); return 0; } X509_SIG_get0(p12->mac->dinfo, NULL, &macoct); if ((maclen != (unsigned int)ASN1_STRING_length(macoct)) || CRYPTO_memcmp(mac, ASN1_STRING_get0_data(macoct), maclen) != 0) return 0; return 1; } /* Set a mac */ int PKCS12_set_mac(PKCS12 *p12, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, const EVP_MD *md_type) { unsigned char mac[EVP_MAX_MD_SIZE]; unsigned int maclen; ASN1_OCTET_STRING *macoct; if (md_type == NULL) /* No need to do a fetch as the md_type is used only to get a NID */ md_type = EVP_sha256(); if (!iter) iter = PKCS12_DEFAULT_ITER; if (PKCS12_setup_mac(p12, iter, salt, saltlen, md_type) == PKCS12_ERROR) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_SETUP_ERROR); return 0; } /* * Note that output mac is forced to UTF-8... */ if (!pkcs12_gen_mac(p12, pass, passlen, mac, &maclen, NULL)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_GENERATION_ERROR); return 0; } X509_SIG_getm(p12->mac->dinfo, NULL, &macoct); if (!ASN1_OCTET_STRING_set(macoct, mac, maclen)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_STRING_SET_ERROR); return 0; } return 1; } /* Set up a mac structure */ int PKCS12_setup_mac(PKCS12 *p12, int iter, unsigned char *salt, int saltlen, const EVP_MD *md_type) { X509_ALGOR *macalg; PKCS12_MAC_DATA_free(p12->mac); p12->mac = NULL; if ((p12->mac = PKCS12_MAC_DATA_new()) == NULL) return PKCS12_ERROR; if (iter > 1) { if ((p12->mac->iter = ASN1_INTEGER_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return 0; } if (!ASN1_INTEGER_set(p12->mac->iter, iter)) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return 0; } } if (saltlen == 0) saltlen = PKCS12_SALT_LEN; else if (saltlen < 0) return 0; if ((p12->mac->salt->data = OPENSSL_malloc(saltlen)) == NULL) return 0; p12->mac->salt->length = saltlen; if (salt == NULL) { if (RAND_bytes_ex(p12->authsafes->ctx.libctx, p12->mac->salt->data, (size_t)saltlen, 0) <= 0) return 0; } else { memcpy(p12->mac->salt->data, salt, saltlen); } X509_SIG_getm(p12->mac->dinfo, &macalg, NULL); if (!X509_ALGOR_set0(macalg, OBJ_nid2obj(EVP_MD_get_type(md_type)), V_ASN1_NULL, NULL)) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return 0; } return 1; }
8,813
30.478571
84
c
openssl
openssl-master/crypto/pkcs12/p12_npas.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 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/pkcs12.h> #include "p12_local.h" /* PKCS#12 password change routine */ static int newpass_p12(PKCS12 *p12, const char *oldpass, const char *newpass); static int newpass_bags(STACK_OF(PKCS12_SAFEBAG) *bags, const char *oldpass, const char *newpass, OSSL_LIB_CTX *libctx, const char *propq); static int newpass_bag(PKCS12_SAFEBAG *bag, const char *oldpass, const char *newpass, OSSL_LIB_CTX *libctx, const char *propq); static int alg_get(const X509_ALGOR *alg, int *pnid, int *piter, int *psaltlen, int *cipherid); /* * Change the password on a PKCS#12 structure. */ int PKCS12_newpass(PKCS12 *p12, const char *oldpass, const char *newpass) { /* Check for NULL PKCS12 structure */ if (p12 == NULL) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_INVALID_NULL_PKCS12_POINTER); return 0; } /* Check the mac */ if (p12->mac != NULL) { if (!PKCS12_verify_mac(p12, oldpass, -1)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_MAC_VERIFY_FAILURE); return 0; } } if (!newpass_p12(p12, oldpass, newpass)) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_PARSE_ERROR); return 0; } return 1; } /* Parse the outer PKCS#12 structure */ static int newpass_p12(PKCS12 *p12, const char *oldpass, const char *newpass) { STACK_OF(PKCS7) *asafes = NULL, *newsafes = NULL; STACK_OF(PKCS12_SAFEBAG) *bags = NULL; int i, bagnid, pbe_nid = 0, pbe_iter = 0, pbe_saltlen = 0, cipherid = NID_undef; PKCS7 *p7, *p7new; ASN1_OCTET_STRING *p12_data_tmp = NULL, *macoct = NULL; unsigned char mac[EVP_MAX_MD_SIZE]; unsigned int maclen; int rv = 0; if ((asafes = PKCS12_unpack_authsafes(p12)) == NULL) goto err; if ((newsafes = sk_PKCS7_new_null()) == NULL) goto err; for (i = 0; i < sk_PKCS7_num(asafes); i++) { p7 = sk_PKCS7_value(asafes, i); bagnid = OBJ_obj2nid(p7->type); if (bagnid == NID_pkcs7_data) { bags = PKCS12_unpack_p7data(p7); } else if (bagnid == NID_pkcs7_encrypted) { bags = PKCS12_unpack_p7encdata(p7, oldpass, -1); if (!alg_get(p7->d.encrypted->enc_data->algorithm, &pbe_nid, &pbe_iter, &pbe_saltlen, &cipherid)) goto err; } else { continue; } if (bags == NULL) goto err; if (!newpass_bags(bags, oldpass, newpass, p7->ctx.libctx, p7->ctx.propq)) goto err; /* Repack bag in same form with new password */ if (bagnid == NID_pkcs7_data) p7new = PKCS12_pack_p7data(bags); else p7new = PKCS12_pack_p7encdata_ex(pbe_nid, newpass, -1, NULL, pbe_saltlen, pbe_iter, bags, p7->ctx.libctx, p7->ctx.propq); if (p7new == NULL || !sk_PKCS7_push(newsafes, p7new)) goto err; sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); bags = NULL; } /* Repack safe: save old safe in case of error */ p12_data_tmp = p12->authsafes->d.data; if ((p12->authsafes->d.data = ASN1_OCTET_STRING_new()) == NULL) goto err; if (!PKCS12_pack_authsafes(p12, newsafes)) goto err; if (p12->mac != NULL) { if (!PKCS12_gen_mac(p12, newpass, -1, mac, &maclen)) goto err; X509_SIG_getm(p12->mac->dinfo, NULL, &macoct); if (!ASN1_OCTET_STRING_set(macoct, mac, maclen)) goto err; } rv = 1; err: /* Restore old safe if necessary */ if (rv == 1) { ASN1_OCTET_STRING_free(p12_data_tmp); } else if (p12_data_tmp != NULL) { ASN1_OCTET_STRING_free(p12->authsafes->d.data); p12->authsafes->d.data = p12_data_tmp; } sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free); sk_PKCS7_pop_free(asafes, PKCS7_free); sk_PKCS7_pop_free(newsafes, PKCS7_free); return rv; } static int newpass_bags(STACK_OF(PKCS12_SAFEBAG) *bags, const char *oldpass, const char *newpass, OSSL_LIB_CTX *libctx, const char *propq) { int i; for (i = 0; i < sk_PKCS12_SAFEBAG_num(bags); i++) { if (!newpass_bag(sk_PKCS12_SAFEBAG_value(bags, i), oldpass, newpass, libctx, propq)) return 0; } return 1; } /* Change password of safebag: only needs handle shrouded keybags */ static int newpass_bag(PKCS12_SAFEBAG *bag, const char *oldpass, const char *newpass, OSSL_LIB_CTX *libctx, const char *propq) { EVP_CIPHER *cipher = NULL; PKCS8_PRIV_KEY_INFO *p8; X509_SIG *p8new; int p8_nid, p8_saltlen, p8_iter, cipherid = 0; const X509_ALGOR *shalg; if (PKCS12_SAFEBAG_get_nid(bag) != NID_pkcs8ShroudedKeyBag) return 1; if ((p8 = PKCS8_decrypt_ex(bag->value.shkeybag, oldpass, -1, libctx, propq)) == NULL) return 0; X509_SIG_get0(bag->value.shkeybag, &shalg, NULL); if (!alg_get(shalg, &p8_nid, &p8_iter, &p8_saltlen, &cipherid)) { PKCS8_PRIV_KEY_INFO_free(p8); return 0; } if (cipherid != NID_undef) { cipher = EVP_CIPHER_fetch(libctx, OBJ_nid2sn(cipherid), propq); if (cipher == NULL) { PKCS8_PRIV_KEY_INFO_free(p8); return 0; } } p8new = PKCS8_encrypt_ex(p8_nid, cipher, newpass, -1, NULL, p8_saltlen, p8_iter, p8, libctx, propq); PKCS8_PRIV_KEY_INFO_free(p8); EVP_CIPHER_free(cipher); if (p8new == NULL) return 0; X509_SIG_free(bag->value.shkeybag); bag->value.shkeybag = p8new; return 1; } static int alg_get(const X509_ALGOR *alg, int *pnid, int *piter, int *psaltlen, int *cipherid) { int ret = 0, pbenid, aparamtype; int encnid, prfnid; const ASN1_OBJECT *aoid; const void *aparam; PBEPARAM *pbe = NULL; PBE2PARAM *pbe2 = NULL; PBKDF2PARAM *kdf = NULL; X509_ALGOR_get0(&aoid, &aparamtype, &aparam, alg); pbenid = OBJ_obj2nid(aoid); switch (pbenid) { case NID_pbes2: if (aparamtype == V_ASN1_SEQUENCE) pbe2 = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBE2PARAM)); if (pbe2 == NULL) goto done; X509_ALGOR_get0(&aoid, &aparamtype, &aparam, pbe2->keyfunc); pbenid = OBJ_obj2nid(aoid); X509_ALGOR_get0(&aoid, NULL, NULL, pbe2->encryption); encnid = OBJ_obj2nid(aoid); if (aparamtype == V_ASN1_SEQUENCE) kdf = ASN1_item_unpack(aparam, ASN1_ITEM_rptr(PBKDF2PARAM)); if (kdf == NULL) goto done; /* Only OCTET_STRING is supported */ if (kdf->salt->type != V_ASN1_OCTET_STRING) goto done; if (kdf->prf == NULL) { prfnid = NID_hmacWithSHA1; } else { X509_ALGOR_get0(&aoid, NULL, NULL, kdf->prf); prfnid = OBJ_obj2nid(aoid); } *psaltlen = kdf->salt->value.octet_string->length; *piter = ASN1_INTEGER_get(kdf->iter); *pnid = prfnid; *cipherid = encnid; break; default: pbe = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(PBEPARAM), alg->parameter); if (pbe == NULL) goto done; *pnid = OBJ_obj2nid(alg->algorithm); *piter = ASN1_INTEGER_get(pbe->iter); *psaltlen = pbe->salt->length; *cipherid = NID_undef; ret = 1; break; } ret = 1; done: if (kdf != NULL) PBKDF2PARAM_free(kdf); if (pbe2 != NULL) PBE2PARAM_free(pbe2); if (pbe != NULL) PBEPARAM_free(pbe); return ret; }
8,341
31.084615
84
c
openssl
openssl-master/crypto/pkcs12/p12_p8d.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/pkcs12.h> PKCS8_PRIV_KEY_INFO *PKCS8_decrypt_ex(const X509_SIG *p8, const char *pass, int passlen, OSSL_LIB_CTX *ctx, const char *propq) { const X509_ALGOR *dalg; const ASN1_OCTET_STRING *doct; X509_SIG_get0(p8, &dalg, &doct); return PKCS12_item_decrypt_d2i_ex(dalg, ASN1_ITEM_rptr(PKCS8_PRIV_KEY_INFO), pass, passlen, doct, 1, ctx, propq); } PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(const X509_SIG *p8, const char *pass, int passlen) { return PKCS8_decrypt_ex(p8, pass, passlen, NULL, NULL); }
1,099
32.333333
77
c
openssl
openssl-master/crypto/pkcs12/p12_p8e.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/core.h> #include <openssl/pkcs12.h> #include "crypto/x509.h" X509_SIG *PKCS8_encrypt_ex(int pbe_nid, const EVP_CIPHER *cipher, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *libctx, const char *propq) { X509_SIG *p8 = NULL; X509_ALGOR *pbe; if (pbe_nid == -1) { if (cipher == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_PASSED_NULL_PARAMETER); return NULL; } pbe = PKCS5_pbe2_set_iv_ex(cipher, iter, salt, saltlen, NULL, -1, libctx); } else { ERR_set_mark(); if (EVP_PBE_find(EVP_PBE_TYPE_PRF, pbe_nid, NULL, NULL, 0)) { ERR_clear_last_mark(); if (cipher == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_PASSED_NULL_PARAMETER); return NULL; } pbe = PKCS5_pbe2_set_iv_ex(cipher, iter, salt, saltlen, NULL, pbe_nid, libctx); } else { ERR_pop_to_mark(); pbe = PKCS5_pbe_set_ex(pbe_nid, iter, salt, saltlen, libctx); } } if (pbe == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } p8 = PKCS8_set0_pbe_ex(pass, passlen, p8inf, pbe, libctx, propq); if (p8 == NULL) { X509_ALGOR_free(pbe); return NULL; } return p8; } X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8inf) { return PKCS8_encrypt_ex(pbe_nid, cipher, pass, passlen, salt, saltlen, iter, p8inf, NULL, NULL); } X509_SIG *PKCS8_set0_pbe_ex(const char *pass, int passlen, PKCS8_PRIV_KEY_INFO *p8inf, X509_ALGOR *pbe, OSSL_LIB_CTX *ctx, const char *propq) { X509_SIG *p8; ASN1_OCTET_STRING *enckey; enckey = PKCS12_item_i2d_encrypt_ex(pbe, ASN1_ITEM_rptr(PKCS8_PRIV_KEY_INFO), pass, passlen, p8inf, 1, ctx, propq); if (!enckey) { ERR_raise(ERR_LIB_PKCS12, PKCS12_R_ENCRYPT_ERROR); return NULL; } p8 = OPENSSL_zalloc(sizeof(*p8)); if (p8 == NULL) { ASN1_OCTET_STRING_free(enckey); return NULL; } p8->algor = pbe; p8->digest = enckey; return p8; } X509_SIG *PKCS8_set0_pbe(const char *pass, int passlen, PKCS8_PRIV_KEY_INFO *p8inf, X509_ALGOR *pbe) { return PKCS8_set0_pbe_ex(pass, passlen, p8inf, pbe, NULL, NULL); }
3,222
30.910891
80
c
openssl
openssl-master/crypto/pkcs12/p12_sbag.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/pkcs12.h> #include "p12_local.h" #include "crypto/x509.h" #ifndef OPENSSL_NO_DEPRECATED_1_1_0 ASN1_TYPE *PKCS12_get_attr(const PKCS12_SAFEBAG *bag, int attr_nid) { return PKCS12_get_attr_gen(bag->attrib, attr_nid); } #endif const ASN1_TYPE *PKCS12_SAFEBAG_get0_attr(const PKCS12_SAFEBAG *bag, int attr_nid) { return PKCS12_get_attr_gen(bag->attrib, attr_nid); } ASN1_TYPE *PKCS8_get_attr(PKCS8_PRIV_KEY_INFO *p8, int attr_nid) { return PKCS12_get_attr_gen(PKCS8_pkey_get0_attrs(p8), attr_nid); } const PKCS8_PRIV_KEY_INFO *PKCS12_SAFEBAG_get0_p8inf(const PKCS12_SAFEBAG *bag) { if (PKCS12_SAFEBAG_get_nid(bag) != NID_keyBag) return NULL; return bag->value.keybag; } const X509_SIG *PKCS12_SAFEBAG_get0_pkcs8(const PKCS12_SAFEBAG *bag) { if (OBJ_obj2nid(bag->type) != NID_pkcs8ShroudedKeyBag) return NULL; return bag->value.shkeybag; } const STACK_OF(PKCS12_SAFEBAG) * PKCS12_SAFEBAG_get0_safes(const PKCS12_SAFEBAG *bag) { if (OBJ_obj2nid(bag->type) != NID_safeContentsBag) return NULL; return bag->value.safes; } const ASN1_OBJECT *PKCS12_SAFEBAG_get0_type(const PKCS12_SAFEBAG *bag) { return bag->type; } int PKCS12_SAFEBAG_get_nid(const PKCS12_SAFEBAG *bag) { return OBJ_obj2nid(bag->type); } int PKCS12_SAFEBAG_get_bag_nid(const PKCS12_SAFEBAG *bag) { int btype = PKCS12_SAFEBAG_get_nid(bag); if (btype != NID_certBag && btype != NID_crlBag && btype != NID_secretBag) return -1; return OBJ_obj2nid(bag->value.bag->type); } const ASN1_OBJECT *PKCS12_SAFEBAG_get0_bag_type(const PKCS12_SAFEBAG *bag) { return bag->value.bag->type; } const ASN1_TYPE *PKCS12_SAFEBAG_get0_bag_obj(const PKCS12_SAFEBAG *bag) { return bag->value.bag->value.other; } X509 *PKCS12_SAFEBAG_get1_cert(const PKCS12_SAFEBAG *bag) { if (PKCS12_SAFEBAG_get_nid(bag) != NID_certBag) return NULL; if (OBJ_obj2nid(bag->value.bag->type) != NID_x509Certificate) return NULL; return ASN1_item_unpack(bag->value.bag->value.octet, ASN1_ITEM_rptr(X509)); } X509_CRL *PKCS12_SAFEBAG_get1_crl(const PKCS12_SAFEBAG *bag) { if (PKCS12_SAFEBAG_get_nid(bag) != NID_crlBag) return NULL; if (OBJ_obj2nid(bag->value.bag->type) != NID_x509Crl) return NULL; return ASN1_item_unpack(bag->value.bag->value.octet, ASN1_ITEM_rptr(X509_CRL)); } X509 *PKCS12_SAFEBAG_get1_cert_ex(const PKCS12_SAFEBAG *bag, OSSL_LIB_CTX *libctx, const char *propq) { X509 *ret = NULL; if (PKCS12_SAFEBAG_get_nid(bag) != NID_certBag) return NULL; if (OBJ_obj2nid(bag->value.bag->type) != NID_x509Certificate) return NULL; ret = ASN1_item_unpack_ex(bag->value.bag->value.octet, ASN1_ITEM_rptr(X509), libctx, propq); if (!ossl_x509_set0_libctx(ret, libctx, propq)) { X509_free(ret); return NULL; } return ret; } X509_CRL *PKCS12_SAFEBAG_get1_crl_ex(const PKCS12_SAFEBAG *bag, OSSL_LIB_CTX *libctx, const char *propq) { X509_CRL *ret = NULL; if (PKCS12_SAFEBAG_get_nid(bag) != NID_crlBag) return NULL; if (OBJ_obj2nid(bag->value.bag->type) != NID_x509Crl) return NULL; ret = ASN1_item_unpack_ex(bag->value.bag->value.octet, ASN1_ITEM_rptr(X509_CRL), libctx, propq); if (!ossl_x509_crl_set0_libctx(ret, libctx, propq)) { X509_CRL_free(ret); return NULL; } return ret; } PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_cert(X509 *x509) { return PKCS12_item_pack_safebag(x509, ASN1_ITEM_rptr(X509), NID_x509Certificate, NID_certBag); } PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_crl(X509_CRL *crl) { return PKCS12_item_pack_safebag(crl, ASN1_ITEM_rptr(X509_CRL), NID_x509Crl, NID_crlBag); } PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_secret(int type, int vtype, const unsigned char *value, int len) { PKCS12_BAGS *bag; PKCS12_SAFEBAG *safebag; if ((bag = PKCS12_BAGS_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } bag->type = OBJ_nid2obj(type); switch (vtype) { case V_ASN1_OCTET_STRING: { ASN1_OCTET_STRING *strtmp = ASN1_OCTET_STRING_new(); if (strtmp == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } /* Pack data into an octet string */ if (!ASN1_OCTET_STRING_set(strtmp, value, len)) { ASN1_OCTET_STRING_free(strtmp); ERR_raise(ERR_LIB_PKCS12, PKCS12_R_ENCODE_ERROR); goto err; } bag->value.other = ASN1_TYPE_new(); if (bag->value.other == NULL) { ASN1_OCTET_STRING_free(strtmp); ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } ASN1_TYPE_set(bag->value.other, vtype, strtmp); } break; default: ERR_raise(ERR_LIB_PKCS12, PKCS12_R_INVALID_TYPE); goto err; } if ((safebag = PKCS12_SAFEBAG_new()) == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); goto err; } safebag->value.bag = bag; safebag->type = OBJ_nid2obj(NID_secretBag); return safebag; err: PKCS12_BAGS_free(bag); return NULL; } /* Turn PKCS8 object into a keybag */ PKCS12_SAFEBAG *PKCS12_SAFEBAG_create0_p8inf(PKCS8_PRIV_KEY_INFO *p8) { PKCS12_SAFEBAG *bag = PKCS12_SAFEBAG_new(); if (bag == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } bag->type = OBJ_nid2obj(NID_keyBag); bag->value.keybag = p8; return bag; } /* Turn PKCS8 object into a shrouded keybag */ PKCS12_SAFEBAG *PKCS12_SAFEBAG_create0_pkcs8(X509_SIG *p8) { PKCS12_SAFEBAG *bag = PKCS12_SAFEBAG_new(); /* Set up the safe bag */ if (bag == NULL) { ERR_raise(ERR_LIB_PKCS12, ERR_R_ASN1_LIB); return NULL; } bag->type = OBJ_nid2obj(NID_pkcs8ShroudedKeyBag); bag->value.shkeybag = p8; return bag; } PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_pkcs8_encrypt_ex(int pbe_nid, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8inf, OSSL_LIB_CTX *ctx, const char *propq) { PKCS12_SAFEBAG *bag = NULL; const EVP_CIPHER *pbe_ciph = NULL; EVP_CIPHER *pbe_ciph_fetch = NULL; X509_SIG *p8; ERR_set_mark(); pbe_ciph = pbe_ciph_fetch = EVP_CIPHER_fetch(ctx, OBJ_nid2sn(pbe_nid), propq); if (pbe_ciph == NULL) pbe_ciph = EVP_get_cipherbynid(pbe_nid); ERR_pop_to_mark(); if (pbe_ciph != NULL) pbe_nid = -1; p8 = PKCS8_encrypt_ex(pbe_nid, pbe_ciph, pass, passlen, salt, saltlen, iter, p8inf, ctx, propq); if (p8 == NULL) goto err; bag = PKCS12_SAFEBAG_create0_pkcs8(p8); if (bag == NULL) X509_SIG_free(p8); err: EVP_CIPHER_free(pbe_ciph_fetch); return bag; } PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_pkcs8_encrypt(int pbe_nid, const char *pass, int passlen, unsigned char *salt, int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8inf) { return PKCS12_SAFEBAG_create_pkcs8_encrypt_ex(pbe_nid, pass, passlen, salt, saltlen, iter, p8inf, NULL, NULL); }
8,631
29.181818
102
c
openssl
openssl-master/crypto/pkcs12/p12_utl.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/pkcs12.h> #include "p12_local.h" #include "crypto/pkcs7/pk7_local.h" /* Cheap and nasty Unicode stuff */ unsigned char *OPENSSL_asc2uni(const char *asc, int asclen, unsigned char **uni, int *unilen) { int ulen, i; unsigned char *unitmp; if (asclen == -1) asclen = strlen(asc); if (asclen < 0) return NULL; ulen = asclen * 2 + 2; if ((unitmp = OPENSSL_malloc(ulen)) == NULL) return NULL; for (i = 0; i < ulen - 2; i += 2) { unitmp[i] = 0; unitmp[i + 1] = asc[i >> 1]; } /* Make result double null terminated */ unitmp[ulen - 2] = 0; unitmp[ulen - 1] = 0; if (unilen) *unilen = ulen; if (uni) *uni = unitmp; return unitmp; } char *OPENSSL_uni2asc(const unsigned char *uni, int unilen) { int asclen, i; char *asctmp; /* string must contain an even number of bytes */ if (unilen & 1) return NULL; if (unilen < 0) return NULL; asclen = unilen / 2; /* If no terminating zero allow for one */ if (!unilen || uni[unilen - 1]) asclen++; uni++; if ((asctmp = OPENSSL_malloc(asclen)) == NULL) return NULL; for (i = 0; i < unilen; i += 2) asctmp[i >> 1] = uni[i]; asctmp[asclen - 1] = 0; return asctmp; } /* * OPENSSL_{utf82uni|uni2utf8} perform conversion between UTF-8 and * PKCS#12 BMPString format, which is specified as big-endian UTF-16. * One should keep in mind that even though BMPString is passed as * unsigned char *, it's not the kind of string you can exercise e.g. * strlen on. Caller also has to keep in mind that its length is * expressed not in number of UTF-16 characters, but in number of * bytes the string occupies, and treat it, the length, accordingly. */ unsigned char *OPENSSL_utf82uni(const char *asc, int asclen, unsigned char **uni, int *unilen) { int ulen, i, j; unsigned char *unitmp, *ret; unsigned long utf32chr = 0; if (asclen == -1) asclen = strlen(asc); for (ulen = 0, i = 0; i < asclen; i += j) { j = UTF8_getc((const unsigned char *)asc+i, asclen-i, &utf32chr); /* * Following condition is somewhat opportunistic is sense that * decoding failure is used as *indirect* indication that input * string might in fact be extended ASCII/ANSI/ISO-8859-X. The * fallback is taken in hope that it would allow to process * files created with previous OpenSSL version, which used the * naive OPENSSL_asc2uni all along. It might be worth noting * that probability of false positive depends on language. In * cases covered by ISO Latin 1 probability is very low, because * any printable non-ASCII alphabet letter followed by another * or any ASCII character will trigger failure and fallback. * In other cases situation can be intensified by the fact that * English letters are not part of alternative keyboard layout, * but even then there should be plenty of pairs that trigger * decoding failure... */ if (j < 0) return OPENSSL_asc2uni(asc, asclen, uni, unilen); if (utf32chr > 0x10FFFF) /* UTF-16 cap */ return NULL; if (utf32chr >= 0x10000) /* pair of UTF-16 characters */ ulen += 2*2; else /* or just one */ ulen += 2; } ulen += 2; /* for trailing UTF16 zero */ if ((ret = OPENSSL_malloc(ulen)) == NULL) return NULL; /* re-run the loop writing down UTF-16 characters in big-endian order */ for (unitmp = ret, i = 0; i < asclen; i += j) { j = UTF8_getc((const unsigned char *)asc+i, asclen-i, &utf32chr); if (utf32chr >= 0x10000) { /* pair if UTF-16 characters */ unsigned int hi, lo; utf32chr -= 0x10000; hi = 0xD800 + (utf32chr>>10); lo = 0xDC00 + (utf32chr&0x3ff); *unitmp++ = (unsigned char)(hi>>8); *unitmp++ = (unsigned char)(hi); *unitmp++ = (unsigned char)(lo>>8); *unitmp++ = (unsigned char)(lo); } else { /* or just one */ *unitmp++ = (unsigned char)(utf32chr>>8); *unitmp++ = (unsigned char)(utf32chr); } } /* Make result double null terminated */ *unitmp++ = 0; *unitmp++ = 0; if (unilen) *unilen = ulen; if (uni) *uni = ret; return ret; } static int bmp_to_utf8(char *str, const unsigned char *utf16, int len) { unsigned long utf32chr; if (len == 0) return 0; if (len < 2) return -1; /* pull UTF-16 character in big-endian order */ utf32chr = (utf16[0]<<8) | utf16[1]; if (utf32chr >= 0xD800 && utf32chr < 0xE000) { /* two chars */ unsigned int lo; if (len < 4) return -1; utf32chr -= 0xD800; utf32chr <<= 10; lo = (utf16[2]<<8) | utf16[3]; if (lo < 0xDC00 || lo >= 0xE000) return -1; utf32chr |= lo-0xDC00; utf32chr += 0x10000; } return UTF8_putc((unsigned char *)str, len > 4 ? 4 : len, utf32chr); } char *OPENSSL_uni2utf8(const unsigned char *uni, int unilen) { int asclen, i, j; char *asctmp; /* string must contain an even number of bytes */ if (unilen & 1) return NULL; for (asclen = 0, i = 0; i < unilen; ) { j = bmp_to_utf8(NULL, uni+i, unilen-i); /* * falling back to OPENSSL_uni2asc makes lesser sense [than * falling back to OPENSSL_asc2uni in OPENSSL_utf82uni above], * it's done rather to maintain symmetry... */ if (j < 0) return OPENSSL_uni2asc(uni, unilen); if (j == 4) i += 4; else i += 2; asclen += j; } /* If no terminating zero allow for one */ if (!unilen || (uni[unilen-2]||uni[unilen - 1])) asclen++; if ((asctmp = OPENSSL_malloc(asclen)) == NULL) return NULL; /* re-run the loop emitting UTF-8 string */ for (asclen = 0, i = 0; i < unilen; ) { j = bmp_to_utf8(asctmp+asclen, uni+i, unilen-i); if (j == 4) i += 4; else i += 2; asclen += j; } /* If no terminating zero write one */ if (!unilen || (uni[unilen-2]||uni[unilen - 1])) asctmp[asclen] = '\0'; return asctmp; } int i2d_PKCS12_bio(BIO *bp, const PKCS12 *p12) { return ASN1_item_i2d_bio(ASN1_ITEM_rptr(PKCS12), bp, p12); } #ifndef OPENSSL_NO_STDIO int i2d_PKCS12_fp(FILE *fp, const PKCS12 *p12) { return ASN1_item_i2d_fp(ASN1_ITEM_rptr(PKCS12), fp, p12); } #endif PKCS12 *d2i_PKCS12_bio(BIO *bp, PKCS12 **p12) { OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; const PKCS7_CTX *p7ctx = NULL; if (p12 != NULL) { p7ctx = ossl_pkcs12_get0_pkcs7ctx(*p12); if (p7ctx != NULL) { libctx = ossl_pkcs7_ctx_get0_libctx(p7ctx); propq = ossl_pkcs7_ctx_get0_propq(p7ctx); } } return ASN1_item_d2i_bio_ex(ASN1_ITEM_rptr(PKCS12), bp, p12, libctx, propq); } #ifndef OPENSSL_NO_STDIO PKCS12 *d2i_PKCS12_fp(FILE *fp, PKCS12 **p12) { OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; const PKCS7_CTX *p7ctx = NULL; if (p12 != NULL) { p7ctx = ossl_pkcs12_get0_pkcs7ctx(*p12); if (p7ctx != NULL) { libctx = ossl_pkcs7_ctx_get0_libctx(p7ctx); propq = ossl_pkcs7_ctx_get0_propq(p7ctx); } } return ASN1_item_d2i_fp_ex(ASN1_ITEM_rptr(PKCS12), fp, p12, libctx, propq); } #endif
8,114
29.507519
80
c
openssl
openssl-master/crypto/pkcs12/pk12err.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/pkcs12err.h> #include "crypto/pkcs12err.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA PKCS12_str_reasons[] = { {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_CALLBACK_FAILED), "callback failed"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_CANT_PACK_STRUCTURE), "can't pack structure"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_CONTENT_TYPE_NOT_DATA), "content type not data"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_DECODE_ERROR), "decode error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_ENCODE_ERROR), "encode error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_ENCRYPT_ERROR), "encrypt error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_ERROR_SETTING_ENCRYPTED_DATA_TYPE), "error setting encrypted data type"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_INVALID_NULL_ARGUMENT), "invalid null argument"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_INVALID_NULL_PKCS12_POINTER), "invalid null pkcs12 pointer"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_INVALID_TYPE), "invalid type"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_IV_GEN_ERROR), "iv gen error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_KEY_GEN_ERROR), "key gen error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_ABSENT), "mac absent"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_GENERATION_ERROR), "mac generation error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_SETUP_ERROR), "mac setup error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_STRING_SET_ERROR), "mac string set error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_MAC_VERIFY_FAILURE), "mac verify failure"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_PARSE_ERROR), "parse error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_PKCS12_CIPHERFINAL_ERROR), "pkcs12 cipherfinal error"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_UNKNOWN_DIGEST_ALGORITHM), "unknown digest algorithm"}, {ERR_PACK(ERR_LIB_PKCS12, 0, PKCS12_R_UNSUPPORTED_PKCS12_MODE), "unsupported pkcs12 mode"}, {0, NULL} }; #endif int ossl_err_load_PKCS12_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(PKCS12_str_reasons[0].error) == NULL) ERR_load_strings_const(PKCS12_str_reasons); #endif return 1; }
2,624
40.666667
79
c
openssl
openssl-master/crypto/pkcs7/bio_pk7.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 */ #include <openssl/asn1.h> #include <openssl/pkcs7.h> #include <openssl/bio.h> /* Streaming encode support for PKCS#7 */ BIO *BIO_new_PKCS7(BIO *out, PKCS7 *p7) { return BIO_new_NDEF(out, (ASN1_VALUE *)p7, ASN1_ITEM_rptr(PKCS7)); }
574
27.75
74
c
openssl
openssl-master/crypto/pkcs7/pk7_asn1.c
/* * Copyright 2000-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/pkcs7.h> #include <openssl/x509.h> #include "pk7_local.h" /* PKCS#7 ASN1 module */ /* This is the ANY DEFINED BY table for the top level PKCS#7 structure */ ASN1_ADB_TEMPLATE(p7default) = ASN1_EXP_OPT(PKCS7, d.other, ASN1_ANY, 0); ASN1_ADB(PKCS7) = { ADB_ENTRY(NID_pkcs7_data, ASN1_NDEF_EXP_OPT(PKCS7, d.data, ASN1_OCTET_STRING_NDEF, 0)), ADB_ENTRY(NID_pkcs7_signed, ASN1_NDEF_EXP_OPT(PKCS7, d.sign, PKCS7_SIGNED, 0)), ADB_ENTRY(NID_pkcs7_enveloped, ASN1_NDEF_EXP_OPT(PKCS7, d.enveloped, PKCS7_ENVELOPE, 0)), ADB_ENTRY(NID_pkcs7_signedAndEnveloped, ASN1_NDEF_EXP_OPT(PKCS7, d.signed_and_enveloped, PKCS7_SIGN_ENVELOPE, 0)), ADB_ENTRY(NID_pkcs7_digest, ASN1_NDEF_EXP_OPT(PKCS7, d.digest, PKCS7_DIGEST, 0)), ADB_ENTRY(NID_pkcs7_encrypted, ASN1_NDEF_EXP_OPT(PKCS7, d.encrypted, PKCS7_ENCRYPT, 0)) } ASN1_ADB_END(PKCS7, 0, type, 0, &p7default_tt, NULL); /* PKCS#7 streaming support */ static int pk7_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { ASN1_STREAM_ARG *sarg = exarg; PKCS7 **pp7 = (PKCS7 **)pval; switch (operation) { case ASN1_OP_STREAM_PRE: if (PKCS7_stream(&sarg->boundary, *pp7) <= 0) return 0; /* fall through */ case ASN1_OP_DETACHED_PRE: sarg->ndef_bio = PKCS7_dataInit(*pp7, sarg->out); if (!sarg->ndef_bio) return 0; break; case ASN1_OP_STREAM_POST: case ASN1_OP_DETACHED_POST: if (PKCS7_dataFinal(*pp7, sarg->ndef_bio) <= 0) return 0; break; } return 1; } ASN1_NDEF_SEQUENCE_cb(PKCS7, pk7_cb) = { ASN1_SIMPLE(PKCS7, type, ASN1_OBJECT), ASN1_ADB_OBJECT(PKCS7) }ASN1_NDEF_SEQUENCE_END_cb(PKCS7, PKCS7) PKCS7 *d2i_PKCS7(PKCS7 **a, const unsigned char **in, long len) { PKCS7 *ret; OSSL_LIB_CTX *libctx = NULL; const char *propq = NULL; if (a != NULL && *a != NULL) { libctx = (*a)->ctx.libctx; propq = (*a)->ctx.propq; } ret = (PKCS7 *)ASN1_item_d2i_ex((ASN1_VALUE **)a, in, len, (PKCS7_it()), libctx, propq); if (ret != NULL) ossl_pkcs7_resolve_libctx(ret); return ret; } int i2d_PKCS7(const PKCS7 *a, unsigned char **out) { return ASN1_item_i2d((const ASN1_VALUE *)a, out, (PKCS7_it()));\ } PKCS7 *PKCS7_new(void) { return (PKCS7 *)ASN1_item_new(ASN1_ITEM_rptr(PKCS7)); } PKCS7 *PKCS7_new_ex(OSSL_LIB_CTX *libctx, const char *propq) { PKCS7 *pkcs7 = (PKCS7 *)ASN1_item_new_ex(ASN1_ITEM_rptr(PKCS7), libctx, propq); if (pkcs7 != NULL) { pkcs7->ctx.libctx = libctx; pkcs7->ctx.propq = NULL; if (propq != NULL) { pkcs7->ctx.propq = OPENSSL_strdup(propq); if (pkcs7->ctx.propq == NULL) { PKCS7_free(pkcs7); pkcs7 = NULL; } } } return pkcs7; } void PKCS7_free(PKCS7 *p7) { if (p7 != NULL) { OPENSSL_free(p7->ctx.propq); ASN1_item_free((ASN1_VALUE *)p7, ASN1_ITEM_rptr(PKCS7)); } } IMPLEMENT_ASN1_NDEF_FUNCTION(PKCS7) IMPLEMENT_ASN1_DUP_FUNCTION(PKCS7) ASN1_NDEF_SEQUENCE(PKCS7_SIGNED) = { ASN1_SIMPLE(PKCS7_SIGNED, version, ASN1_INTEGER), ASN1_SET_OF(PKCS7_SIGNED, md_algs, X509_ALGOR), ASN1_SIMPLE(PKCS7_SIGNED, contents, PKCS7), ASN1_IMP_SEQUENCE_OF_OPT(PKCS7_SIGNED, cert, X509, 0), ASN1_IMP_SET_OF_OPT(PKCS7_SIGNED, crl, X509_CRL, 1), ASN1_SET_OF(PKCS7_SIGNED, signer_info, PKCS7_SIGNER_INFO) } ASN1_NDEF_SEQUENCE_END(PKCS7_SIGNED) IMPLEMENT_ASN1_FUNCTIONS(PKCS7_SIGNED) /* Minor tweak to operation: free up EVP_PKEY */ static int si_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_FREE_POST) { PKCS7_SIGNER_INFO *si = (PKCS7_SIGNER_INFO *)*pval; EVP_PKEY_free(si->pkey); } return 1; } ASN1_SEQUENCE_cb(PKCS7_SIGNER_INFO, si_cb) = { ASN1_SIMPLE(PKCS7_SIGNER_INFO, version, ASN1_INTEGER), ASN1_SIMPLE(PKCS7_SIGNER_INFO, issuer_and_serial, PKCS7_ISSUER_AND_SERIAL), ASN1_SIMPLE(PKCS7_SIGNER_INFO, digest_alg, X509_ALGOR), /* NB this should be a SET OF but we use a SEQUENCE OF so the * original order * is retained when the structure is reencoded. * Since the attributes are implicitly tagged this will not affect * the encoding. */ ASN1_IMP_SEQUENCE_OF_OPT(PKCS7_SIGNER_INFO, auth_attr, X509_ATTRIBUTE, 0), ASN1_SIMPLE(PKCS7_SIGNER_INFO, digest_enc_alg, X509_ALGOR), ASN1_SIMPLE(PKCS7_SIGNER_INFO, enc_digest, ASN1_OCTET_STRING), ASN1_IMP_SET_OF_OPT(PKCS7_SIGNER_INFO, unauth_attr, X509_ATTRIBUTE, 1) } ASN1_SEQUENCE_END_cb(PKCS7_SIGNER_INFO, PKCS7_SIGNER_INFO) IMPLEMENT_ASN1_FUNCTIONS(PKCS7_SIGNER_INFO) ASN1_SEQUENCE(PKCS7_ISSUER_AND_SERIAL) = { ASN1_SIMPLE(PKCS7_ISSUER_AND_SERIAL, issuer, X509_NAME), ASN1_SIMPLE(PKCS7_ISSUER_AND_SERIAL, serial, ASN1_INTEGER) } ASN1_SEQUENCE_END(PKCS7_ISSUER_AND_SERIAL) IMPLEMENT_ASN1_FUNCTIONS(PKCS7_ISSUER_AND_SERIAL) ASN1_NDEF_SEQUENCE(PKCS7_ENVELOPE) = { ASN1_SIMPLE(PKCS7_ENVELOPE, version, ASN1_INTEGER), ASN1_SET_OF(PKCS7_ENVELOPE, recipientinfo, PKCS7_RECIP_INFO), ASN1_SIMPLE(PKCS7_ENVELOPE, enc_data, PKCS7_ENC_CONTENT) } ASN1_NDEF_SEQUENCE_END(PKCS7_ENVELOPE) IMPLEMENT_ASN1_FUNCTIONS(PKCS7_ENVELOPE) /* Minor tweak to operation: free up X509 */ static int ri_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_FREE_POST) { PKCS7_RECIP_INFO *ri = (PKCS7_RECIP_INFO *)*pval; X509_free(ri->cert); } return 1; } ASN1_SEQUENCE_cb(PKCS7_RECIP_INFO, ri_cb) = { ASN1_SIMPLE(PKCS7_RECIP_INFO, version, ASN1_INTEGER), ASN1_SIMPLE(PKCS7_RECIP_INFO, issuer_and_serial, PKCS7_ISSUER_AND_SERIAL), ASN1_SIMPLE(PKCS7_RECIP_INFO, key_enc_algor, X509_ALGOR), ASN1_SIMPLE(PKCS7_RECIP_INFO, enc_key, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END_cb(PKCS7_RECIP_INFO, PKCS7_RECIP_INFO) IMPLEMENT_ASN1_FUNCTIONS(PKCS7_RECIP_INFO) ASN1_NDEF_SEQUENCE(PKCS7_ENC_CONTENT) = { ASN1_SIMPLE(PKCS7_ENC_CONTENT, content_type, ASN1_OBJECT), ASN1_SIMPLE(PKCS7_ENC_CONTENT, algorithm, X509_ALGOR), ASN1_IMP_OPT(PKCS7_ENC_CONTENT, enc_data, ASN1_OCTET_STRING_NDEF, 0) } ASN1_NDEF_SEQUENCE_END(PKCS7_ENC_CONTENT) IMPLEMENT_ASN1_FUNCTIONS(PKCS7_ENC_CONTENT) ASN1_NDEF_SEQUENCE(PKCS7_SIGN_ENVELOPE) = { ASN1_SIMPLE(PKCS7_SIGN_ENVELOPE, version, ASN1_INTEGER), ASN1_SET_OF(PKCS7_SIGN_ENVELOPE, recipientinfo, PKCS7_RECIP_INFO), ASN1_SET_OF(PKCS7_SIGN_ENVELOPE, md_algs, X509_ALGOR), ASN1_SIMPLE(PKCS7_SIGN_ENVELOPE, enc_data, PKCS7_ENC_CONTENT), ASN1_IMP_SET_OF_OPT(PKCS7_SIGN_ENVELOPE, cert, X509, 0), ASN1_IMP_SET_OF_OPT(PKCS7_SIGN_ENVELOPE, crl, X509_CRL, 1), ASN1_SET_OF(PKCS7_SIGN_ENVELOPE, signer_info, PKCS7_SIGNER_INFO) } ASN1_NDEF_SEQUENCE_END(PKCS7_SIGN_ENVELOPE) IMPLEMENT_ASN1_FUNCTIONS(PKCS7_SIGN_ENVELOPE) ASN1_NDEF_SEQUENCE(PKCS7_ENCRYPT) = { ASN1_SIMPLE(PKCS7_ENCRYPT, version, ASN1_INTEGER), ASN1_SIMPLE(PKCS7_ENCRYPT, enc_data, PKCS7_ENC_CONTENT) } ASN1_NDEF_SEQUENCE_END(PKCS7_ENCRYPT) IMPLEMENT_ASN1_FUNCTIONS(PKCS7_ENCRYPT) ASN1_NDEF_SEQUENCE(PKCS7_DIGEST) = { ASN1_SIMPLE(PKCS7_DIGEST, version, ASN1_INTEGER), ASN1_SIMPLE(PKCS7_DIGEST, md, X509_ALGOR), ASN1_SIMPLE(PKCS7_DIGEST, contents, PKCS7), ASN1_SIMPLE(PKCS7_DIGEST, digest, ASN1_OCTET_STRING) } ASN1_NDEF_SEQUENCE_END(PKCS7_DIGEST) IMPLEMENT_ASN1_FUNCTIONS(PKCS7_DIGEST) /* Specials for authenticated attributes */ /* * When signing attributes we want to reorder them to match the sorted * encoding. */ ASN1_ITEM_TEMPLATE(PKCS7_ATTR_SIGN) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_ORDER, 0, PKCS7_ATTRIBUTES, X509_ATTRIBUTE) ASN1_ITEM_TEMPLATE_END(PKCS7_ATTR_SIGN) /* * When verifying attributes we need to use the received order. So we use * SEQUENCE OF and tag it to SET OF */ ASN1_ITEM_TEMPLATE(PKCS7_ATTR_VERIFY) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF | ASN1_TFLG_IMPTAG | ASN1_TFLG_UNIVERSAL, V_ASN1_SET, PKCS7_ATTRIBUTES, X509_ATTRIBUTE) ASN1_ITEM_TEMPLATE_END(PKCS7_ATTR_VERIFY) IMPLEMENT_ASN1_PRINT_FUNCTION(PKCS7)
8,913
33.684825
122
c
openssl
openssl-master/crypto/pkcs7/pk7_attr.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 */ #include <stdio.h> #include <stdlib.h> #include <openssl/bio.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/pem.h> #include <openssl/pkcs7.h> #include <openssl/x509.h> #include <openssl/err.h> int PKCS7_add_attrib_smimecap(PKCS7_SIGNER_INFO *si, STACK_OF(X509_ALGOR) *cap) { ASN1_STRING *seq; if ((seq = ASN1_STRING_new()) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_ASN1_LIB); return 0; } seq->length = ASN1_item_i2d((ASN1_VALUE *)cap, &seq->data, ASN1_ITEM_rptr(X509_ALGORS)); return PKCS7_add_signed_attribute(si, NID_SMIMECapabilities, V_ASN1_SEQUENCE, seq); } STACK_OF(X509_ALGOR) *PKCS7_get_smimecap(PKCS7_SIGNER_INFO *si) { ASN1_TYPE *cap; const unsigned char *p; cap = PKCS7_get_signed_attribute(si, NID_SMIMECapabilities); if (cap == NULL || (cap->type != V_ASN1_SEQUENCE)) return NULL; p = cap->value.sequence->data; return (STACK_OF(X509_ALGOR) *) ASN1_item_d2i(NULL, &p, cap->value.sequence->length, ASN1_ITEM_rptr(X509_ALGORS)); } /* Basic smime-capabilities OID and optional integer arg */ int PKCS7_simple_smimecap(STACK_OF(X509_ALGOR) *sk, int nid, int arg) { ASN1_INTEGER *nbit = NULL; X509_ALGOR *alg; if ((alg = X509_ALGOR_new()) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_ASN1_LIB); return 0; } ASN1_OBJECT_free(alg->algorithm); alg->algorithm = OBJ_nid2obj(nid); if (arg > 0) { if ((alg->parameter = ASN1_TYPE_new()) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_ASN1_LIB); goto err; } if ((nbit = ASN1_INTEGER_new()) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_ASN1_LIB); goto err; } if (!ASN1_INTEGER_set(nbit, arg)) { ERR_raise(ERR_LIB_PKCS7, ERR_R_ASN1_LIB); goto err; } alg->parameter->value.integer = nbit; alg->parameter->type = V_ASN1_INTEGER; nbit = NULL; } if (!sk_X509_ALGOR_push(sk, alg)) { ERR_raise(ERR_LIB_PKCS7, ERR_R_CRYPTO_LIB); goto err; } return 1; err: ASN1_INTEGER_free(nbit); X509_ALGOR_free(alg); return 0; } int PKCS7_add_attrib_content_type(PKCS7_SIGNER_INFO *si, ASN1_OBJECT *coid) { if (PKCS7_get_signed_attribute(si, NID_pkcs9_contentType)) return 0; if (!coid) coid = OBJ_nid2obj(NID_pkcs7_data); return PKCS7_add_signed_attribute(si, NID_pkcs9_contentType, V_ASN1_OBJECT, coid); } int PKCS7_add0_attrib_signing_time(PKCS7_SIGNER_INFO *si, ASN1_TIME *t) { if (t == NULL && (t = X509_gmtime_adj(NULL, 0)) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_X509_LIB); return 0; } return PKCS7_add_signed_attribute(si, NID_pkcs9_signingTime, V_ASN1_UTCTIME, t); } int PKCS7_add1_attrib_digest(PKCS7_SIGNER_INFO *si, const unsigned char *md, int mdlen) { ASN1_OCTET_STRING *os; os = ASN1_OCTET_STRING_new(); if (os == NULL) return 0; if (!ASN1_STRING_set(os, md, mdlen) || !PKCS7_add_signed_attribute(si, NID_pkcs9_messageDigest, V_ASN1_OCTET_STRING, os)) { ASN1_OCTET_STRING_free(os); return 0; } return 1; }
3,798
29.637097
75
c
openssl
openssl-master/crypto/pkcs7/pk7_lib.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/objects.h> #include <openssl/x509.h> #include <openssl/pkcs7.h> #include "crypto/asn1.h" #include "crypto/evp.h" #include "crypto/x509.h" /* for sk_X509_add1_cert() */ #include "pk7_local.h" long PKCS7_ctrl(PKCS7 *p7, int cmd, long larg, char *parg) { int nid; long ret; nid = OBJ_obj2nid(p7->type); switch (cmd) { /* NOTE(emilia): does not support detached digested data. */ case PKCS7_OP_SET_DETACHED_SIGNATURE: if (nid == NID_pkcs7_signed) { ret = p7->detached = (int)larg; if (ret && PKCS7_type_is_data(p7->d.sign->contents)) { ASN1_OCTET_STRING *os; os = p7->d.sign->contents->d.data; ASN1_OCTET_STRING_free(os); p7->d.sign->contents->d.data = NULL; } } else { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE); ret = 0; } break; case PKCS7_OP_GET_DETACHED_SIGNATURE: if (nid == NID_pkcs7_signed) { if (p7->d.sign == NULL || p7->d.sign->contents->d.ptr == NULL) ret = 1; else ret = 0; p7->detached = ret; } else { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE); ret = 0; } break; default: ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNKNOWN_OPERATION); ret = 0; } return ret; } int PKCS7_content_new(PKCS7 *p7, int type) { PKCS7 *ret = NULL; if ((ret = PKCS7_new()) == NULL) goto err; if (!PKCS7_set_type(ret, type)) goto err; if (!PKCS7_set_content(p7, ret)) goto err; return 1; err: PKCS7_free(ret); return 0; } int PKCS7_set_content(PKCS7 *p7, PKCS7 *p7_data) { int i; i = OBJ_obj2nid(p7->type); switch (i) { case NID_pkcs7_signed: PKCS7_free(p7->d.sign->contents); p7->d.sign->contents = p7_data; break; case NID_pkcs7_digest: PKCS7_free(p7->d.digest->contents); p7->d.digest->contents = p7_data; break; case NID_pkcs7_data: case NID_pkcs7_enveloped: case NID_pkcs7_signedAndEnveloped: case NID_pkcs7_encrypted: default: ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNSUPPORTED_CONTENT_TYPE); goto err; } return 1; err: return 0; } int PKCS7_set_type(PKCS7 *p7, int type) { ASN1_OBJECT *obj; /* * PKCS7_content_free(p7); */ obj = OBJ_nid2obj(type); /* will not fail */ switch (type) { case NID_pkcs7_signed: p7->type = obj; if ((p7->d.sign = PKCS7_SIGNED_new()) == NULL) goto err; if (!ASN1_INTEGER_set(p7->d.sign->version, 1)) { PKCS7_SIGNED_free(p7->d.sign); p7->d.sign = NULL; goto err; } break; case NID_pkcs7_data: p7->type = obj; if ((p7->d.data = ASN1_OCTET_STRING_new()) == NULL) goto err; break; case NID_pkcs7_signedAndEnveloped: p7->type = obj; if ((p7->d.signed_and_enveloped = PKCS7_SIGN_ENVELOPE_new()) == NULL) goto err; if (!ASN1_INTEGER_set(p7->d.signed_and_enveloped->version, 1)) goto err; p7->d.signed_and_enveloped->enc_data->content_type = OBJ_nid2obj(NID_pkcs7_data); break; case NID_pkcs7_enveloped: p7->type = obj; if ((p7->d.enveloped = PKCS7_ENVELOPE_new()) == NULL) goto err; if (!ASN1_INTEGER_set(p7->d.enveloped->version, 0)) goto err; p7->d.enveloped->enc_data->content_type = OBJ_nid2obj(NID_pkcs7_data); break; case NID_pkcs7_encrypted: p7->type = obj; if ((p7->d.encrypted = PKCS7_ENCRYPT_new()) == NULL) goto err; if (!ASN1_INTEGER_set(p7->d.encrypted->version, 0)) goto err; p7->d.encrypted->enc_data->content_type = OBJ_nid2obj(NID_pkcs7_data); break; case NID_pkcs7_digest: p7->type = obj; if ((p7->d.digest = PKCS7_DIGEST_new()) == NULL) goto err; if (!ASN1_INTEGER_set(p7->d.digest->version, 0)) goto err; break; default: ERR_raise(ERR_LIB_PKCS7, PKCS7_R_UNSUPPORTED_CONTENT_TYPE); goto err; } return 1; err: return 0; } int PKCS7_set0_type_other(PKCS7 *p7, int type, ASN1_TYPE *other) { p7->type = OBJ_nid2obj(type); p7->d.other = other; return 1; } int PKCS7_add_signer(PKCS7 *p7, PKCS7_SIGNER_INFO *psi) { int i, j; ASN1_OBJECT *obj; X509_ALGOR *alg; STACK_OF(PKCS7_SIGNER_INFO) *signer_sk; STACK_OF(X509_ALGOR) *md_sk; i = OBJ_obj2nid(p7->type); switch (i) { case NID_pkcs7_signed: signer_sk = p7->d.sign->signer_info; md_sk = p7->d.sign->md_algs; break; case NID_pkcs7_signedAndEnveloped: signer_sk = p7->d.signed_and_enveloped->signer_info; md_sk = p7->d.signed_and_enveloped->md_algs; break; default: ERR_raise(ERR_LIB_PKCS7, PKCS7_R_WRONG_CONTENT_TYPE); return 0; } obj = psi->digest_alg->algorithm; /* If the digest is not currently listed, add it */ j = 0; for (i = 0; i < sk_X509_ALGOR_num(md_sk); i++) { alg = sk_X509_ALGOR_value(md_sk, i); if (OBJ_cmp(obj, alg->algorithm) == 0) { j = 1; break; } } if (!j) { /* we need to add another algorithm */ int nid; if ((alg = X509_ALGOR_new()) == NULL || (alg->parameter = ASN1_TYPE_new()) == NULL) { X509_ALGOR_free(alg); ERR_raise(ERR_LIB_PKCS7, ERR_R_ASN1_LIB); return 0; } /* * If there is a constant copy of the ASN1 OBJECT in libcrypto, then * use that. Otherwise, use a dynamically duplicated copy */ if ((nid = OBJ_obj2nid(obj)) != NID_undef) alg->algorithm = OBJ_nid2obj(nid); else alg->algorithm = OBJ_dup(obj); alg->parameter->type = V_ASN1_NULL; if (alg->algorithm == NULL || !sk_X509_ALGOR_push(md_sk, alg)) { X509_ALGOR_free(alg); return 0; } } psi->ctx = ossl_pkcs7_get0_ctx(p7); if (!sk_PKCS7_SIGNER_INFO_push(signer_sk, psi)) return 0; return 1; } int PKCS7_add_certificate(PKCS7 *p7, X509 *x509) { int i; STACK_OF(X509) **sk; i = OBJ_obj2nid(p7->type); switch (i) { case NID_pkcs7_signed: sk = &(p7->d.sign->cert); break; case NID_pkcs7_signedAndEnveloped: sk = &(p7->d.signed_and_enveloped->cert); break; default: ERR_raise(ERR_LIB_PKCS7, PKCS7_R_WRONG_CONTENT_TYPE); return 0; } return ossl_x509_add_cert_new(sk, x509, X509_ADD_FLAG_UP_REF); } int PKCS7_add_crl(PKCS7 *p7, X509_CRL *crl) { int i; STACK_OF(X509_CRL) **sk; i = OBJ_obj2nid(p7->type); switch (i) { case NID_pkcs7_signed: sk = &(p7->d.sign->crl); break; case NID_pkcs7_signedAndEnveloped: sk = &(p7->d.signed_and_enveloped->crl); break; default: ERR_raise(ERR_LIB_PKCS7, PKCS7_R_WRONG_CONTENT_TYPE); return 0; } if (*sk == NULL) *sk = sk_X509_CRL_new_null(); if (*sk == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_CRYPTO_LIB); return 0; } X509_CRL_up_ref(crl); if (!sk_X509_CRL_push(*sk, crl)) { X509_CRL_free(crl); return 0; } return 1; } static int pkcs7_ecdsa_or_dsa_sign_verify_setup(PKCS7_SIGNER_INFO *si, int verify) { if (!verify) { int snid, hnid; X509_ALGOR *alg1, *alg2; EVP_PKEY *pkey = si->pkey; PKCS7_SIGNER_INFO_get0_algs(si, NULL, &alg1, &alg2); if (alg1 == NULL || alg1->algorithm == NULL) return -1; hnid = OBJ_obj2nid(alg1->algorithm); if (hnid == NID_undef) return -1; if (!OBJ_find_sigid_by_algs(&snid, hnid, EVP_PKEY_get_id(pkey))) return -1; return X509_ALGOR_set0(alg2, OBJ_nid2obj(snid), V_ASN1_UNDEF, NULL); } return 1; } static int pkcs7_rsa_sign_verify_setup(PKCS7_SIGNER_INFO *si, int verify) { if (!verify) { X509_ALGOR *alg = NULL; PKCS7_SIGNER_INFO_get0_algs(si, NULL, NULL, &alg); if (alg != NULL) return X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, NULL); } return 1; } int PKCS7_SIGNER_INFO_set(PKCS7_SIGNER_INFO *p7i, X509 *x509, EVP_PKEY *pkey, const EVP_MD *dgst) { int ret; /* We now need to add another PKCS7_SIGNER_INFO entry */ if (!ASN1_INTEGER_set(p7i->version, 1)) return 0; if (!X509_NAME_set(&p7i->issuer_and_serial->issuer, X509_get_issuer_name(x509))) return 0; /* * because ASN1_INTEGER_set is used to set a 'long' we will do things the * ugly way. */ ASN1_INTEGER_free(p7i->issuer_and_serial->serial); if (!(p7i->issuer_and_serial->serial = ASN1_INTEGER_dup(X509_get0_serialNumber(x509)))) return 0; /* lets keep the pkey around for a while */ EVP_PKEY_up_ref(pkey); p7i->pkey = pkey; /* Set the algorithms */ if (!X509_ALGOR_set0(p7i->digest_alg, OBJ_nid2obj(EVP_MD_get_type(dgst)), V_ASN1_NULL, NULL)) return 0; if (EVP_PKEY_is_a(pkey, "EC") || EVP_PKEY_is_a(pkey, "DSA")) return pkcs7_ecdsa_or_dsa_sign_verify_setup(p7i, 0); if (EVP_PKEY_is_a(pkey, "RSA")) return pkcs7_rsa_sign_verify_setup(p7i, 0); if (pkey->ameth != NULL && pkey->ameth->pkey_ctrl != NULL) { ret = pkey->ameth->pkey_ctrl(pkey, ASN1_PKEY_CTRL_PKCS7_SIGN, 0, p7i); if (ret > 0) return 1; if (ret != -2) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_SIGNING_CTRL_FAILURE); return 0; } } ERR_raise(ERR_LIB_PKCS7, PKCS7_R_SIGNING_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); return 0; } PKCS7_SIGNER_INFO *PKCS7_add_signature(PKCS7 *p7, X509 *x509, EVP_PKEY *pkey, const EVP_MD *dgst) { PKCS7_SIGNER_INFO *si = NULL; if (dgst == NULL) { int def_nid; if (EVP_PKEY_get_default_digest_nid(pkey, &def_nid) <= 0) goto err; dgst = EVP_get_digestbynid(def_nid); if (dgst == NULL) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_NO_DEFAULT_DIGEST); goto err; } } if ((si = PKCS7_SIGNER_INFO_new()) == NULL) goto err; if (PKCS7_SIGNER_INFO_set(si, x509, pkey, dgst) <= 0) goto err; if (!PKCS7_add_signer(p7, si)) goto err; return si; err: PKCS7_SIGNER_INFO_free(si); return NULL; } static STACK_OF(X509) *pkcs7_get_signer_certs(const PKCS7 *p7) { if (p7->d.ptr == NULL) return NULL; if (PKCS7_type_is_signed(p7)) return p7->d.sign->cert; if (PKCS7_type_is_signedAndEnveloped(p7)) return p7->d.signed_and_enveloped->cert; return NULL; } static STACK_OF(PKCS7_RECIP_INFO) *pkcs7_get_recipient_info(const PKCS7 *p7) { if (p7->d.ptr == NULL) return NULL; if (PKCS7_type_is_signedAndEnveloped(p7)) return p7->d.signed_and_enveloped->recipientinfo; if (PKCS7_type_is_enveloped(p7)) return p7->d.enveloped->recipientinfo; return NULL; } /* * Set up the library context into any loaded structure that needs it. * i.e loaded X509 objects. */ void ossl_pkcs7_resolve_libctx(PKCS7 *p7) { int i; const PKCS7_CTX *ctx = ossl_pkcs7_get0_ctx(p7); OSSL_LIB_CTX *libctx = ossl_pkcs7_ctx_get0_libctx(ctx); const char *propq = ossl_pkcs7_ctx_get0_propq(ctx); STACK_OF(PKCS7_RECIP_INFO) *rinfos; STACK_OF(PKCS7_SIGNER_INFO) *sinfos; STACK_OF(X509) *certs; if (ctx == NULL || p7->d.ptr == NULL) return; rinfos = pkcs7_get_recipient_info(p7); sinfos = PKCS7_get_signer_info(p7); certs = pkcs7_get_signer_certs(p7); for (i = 0; i < sk_X509_num(certs); i++) ossl_x509_set0_libctx(sk_X509_value(certs, i), libctx, propq); for (i = 0; i < sk_PKCS7_RECIP_INFO_num(rinfos); i++) { PKCS7_RECIP_INFO *ri = sk_PKCS7_RECIP_INFO_value(rinfos, i); ossl_x509_set0_libctx(ri->cert, libctx, propq); } for (i = 0; i < sk_PKCS7_SIGNER_INFO_num(sinfos); i++) { PKCS7_SIGNER_INFO *si = sk_PKCS7_SIGNER_INFO_value(sinfos, i); if (si != NULL) si->ctx = ctx; } } const PKCS7_CTX *ossl_pkcs7_get0_ctx(const PKCS7 *p7) { return p7 != NULL ? &p7->ctx : NULL; } void ossl_pkcs7_set0_libctx(PKCS7 *p7, OSSL_LIB_CTX *ctx) { p7->ctx.libctx = ctx; } int ossl_pkcs7_set1_propq(PKCS7 *p7, const char *propq) { if (p7->ctx.propq != NULL) { OPENSSL_free(p7->ctx.propq); p7->ctx.propq = NULL; } if (propq != NULL) { p7->ctx.propq = OPENSSL_strdup(propq); if (p7->ctx.propq == NULL) return 0; } return 1; } int ossl_pkcs7_ctx_propagate(const PKCS7 *from, PKCS7 *to) { ossl_pkcs7_set0_libctx(to, from->ctx.libctx); if (!ossl_pkcs7_set1_propq(to, from->ctx.propq)) return 0; ossl_pkcs7_resolve_libctx(to); return 1; } OSSL_LIB_CTX *ossl_pkcs7_ctx_get0_libctx(const PKCS7_CTX *ctx) { return ctx != NULL ? ctx->libctx : NULL; } const char *ossl_pkcs7_ctx_get0_propq(const PKCS7_CTX *ctx) { return ctx != NULL ? ctx->propq : NULL; } int PKCS7_set_digest(PKCS7 *p7, const EVP_MD *md) { if (PKCS7_type_is_digest(p7)) { if ((p7->d.digest->md->parameter = ASN1_TYPE_new()) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_ASN1_LIB); return 0; } p7->d.digest->md->parameter->type = V_ASN1_NULL; p7->d.digest->md->algorithm = OBJ_nid2obj(EVP_MD_nid(md)); return 1; } ERR_raise(ERR_LIB_PKCS7, PKCS7_R_WRONG_CONTENT_TYPE); return 1; } STACK_OF(PKCS7_SIGNER_INFO) *PKCS7_get_signer_info(PKCS7 *p7) { if (p7 == NULL || p7->d.ptr == NULL) return NULL; if (PKCS7_type_is_signed(p7)) { return p7->d.sign->signer_info; } else if (PKCS7_type_is_signedAndEnveloped(p7)) { return p7->d.signed_and_enveloped->signer_info; } else return NULL; } void PKCS7_SIGNER_INFO_get0_algs(PKCS7_SIGNER_INFO *si, EVP_PKEY **pk, X509_ALGOR **pdig, X509_ALGOR **psig) { if (pk) *pk = si->pkey; if (pdig) *pdig = si->digest_alg; if (psig) *psig = si->digest_enc_alg; } void PKCS7_RECIP_INFO_get0_alg(PKCS7_RECIP_INFO *ri, X509_ALGOR **penc) { if (penc) *penc = ri->key_enc_algor; } PKCS7_RECIP_INFO *PKCS7_add_recipient(PKCS7 *p7, X509 *x509) { PKCS7_RECIP_INFO *ri; if ((ri = PKCS7_RECIP_INFO_new()) == NULL) goto err; if (PKCS7_RECIP_INFO_set(ri, x509) <= 0) goto err; if (!PKCS7_add_recipient_info(p7, ri)) goto err; ri->ctx = ossl_pkcs7_get0_ctx(p7); return ri; err: PKCS7_RECIP_INFO_free(ri); return NULL; } int PKCS7_add_recipient_info(PKCS7 *p7, PKCS7_RECIP_INFO *ri) { int i; STACK_OF(PKCS7_RECIP_INFO) *sk; i = OBJ_obj2nid(p7->type); switch (i) { case NID_pkcs7_signedAndEnveloped: sk = p7->d.signed_and_enveloped->recipientinfo; break; case NID_pkcs7_enveloped: sk = p7->d.enveloped->recipientinfo; break; default: ERR_raise(ERR_LIB_PKCS7, PKCS7_R_WRONG_CONTENT_TYPE); return 0; } if (!sk_PKCS7_RECIP_INFO_push(sk, ri)) return 0; return 1; } static int pkcs7_rsa_encrypt_decrypt_setup(PKCS7_RECIP_INFO *ri, int decrypt) { X509_ALGOR *alg = NULL; if (!decrypt) { PKCS7_RECIP_INFO_get0_alg(ri, &alg); if (alg != NULL) return X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, NULL); } return 1; } int PKCS7_RECIP_INFO_set(PKCS7_RECIP_INFO *p7i, X509 *x509) { int ret; EVP_PKEY *pkey = NULL; if (!ASN1_INTEGER_set(p7i->version, 0)) return 0; if (!X509_NAME_set(&p7i->issuer_and_serial->issuer, X509_get_issuer_name(x509))) return 0; ASN1_INTEGER_free(p7i->issuer_and_serial->serial); if (!(p7i->issuer_and_serial->serial = ASN1_INTEGER_dup(X509_get0_serialNumber(x509)))) return 0; pkey = X509_get0_pubkey(x509); if (pkey == NULL) return 0; if (EVP_PKEY_is_a(pkey, "RSA-PSS")) return -2; if (EVP_PKEY_is_a(pkey, "RSA")) { if (pkcs7_rsa_encrypt_decrypt_setup(p7i, 0) <= 0) goto err; goto finished; } if (pkey->ameth == NULL || pkey->ameth->pkey_ctrl == NULL) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_ENCRYPTION_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); goto err; } ret = pkey->ameth->pkey_ctrl(pkey, ASN1_PKEY_CTRL_PKCS7_ENCRYPT, 0, p7i); if (ret == -2) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_ENCRYPTION_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); goto err; } if (ret <= 0) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_ENCRYPTION_CTRL_FAILURE); goto err; } finished: X509_up_ref(x509); p7i->cert = x509; return 1; err: return 0; } X509 *PKCS7_cert_from_signer_info(PKCS7 *p7, PKCS7_SIGNER_INFO *si) { if (PKCS7_type_is_signed(p7)) return (X509_find_by_issuer_and_serial(p7->d.sign->cert, si->issuer_and_serial->issuer, si-> issuer_and_serial->serial)); else return NULL; } int PKCS7_set_cipher(PKCS7 *p7, const EVP_CIPHER *cipher) { int i; PKCS7_ENC_CONTENT *ec; i = OBJ_obj2nid(p7->type); switch (i) { case NID_pkcs7_signedAndEnveloped: ec = p7->d.signed_and_enveloped->enc_data; break; case NID_pkcs7_enveloped: ec = p7->d.enveloped->enc_data; break; default: ERR_raise(ERR_LIB_PKCS7, PKCS7_R_WRONG_CONTENT_TYPE); return 0; } /* Check cipher OID exists and has data in it */ i = EVP_CIPHER_get_type(cipher); if (i == NID_undef) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER); return 0; } ec->cipher = cipher; ec->ctx = ossl_pkcs7_get0_ctx(p7); return 1; } /* unfortunately cannot constify BIO_new_NDEF() due to this and CMS_stream() */ int PKCS7_stream(unsigned char ***boundary, PKCS7 *p7) { ASN1_OCTET_STRING *os = NULL; switch (OBJ_obj2nid(p7->type)) { case NID_pkcs7_data: os = p7->d.data; break; case NID_pkcs7_signedAndEnveloped: os = p7->d.signed_and_enveloped->enc_data->enc_data; if (os == NULL) { os = ASN1_OCTET_STRING_new(); p7->d.signed_and_enveloped->enc_data->enc_data = os; } break; case NID_pkcs7_enveloped: os = p7->d.enveloped->enc_data->enc_data; if (os == NULL) { os = ASN1_OCTET_STRING_new(); p7->d.enveloped->enc_data->enc_data = os; } break; case NID_pkcs7_signed: os = p7->d.sign->contents->d.data; break; default: os = NULL; break; } if (os == NULL) return 0; os->flags |= ASN1_STRING_FLAG_NDEF; *boundary = &os->data; return 1; }
20,230
25.831565
79
c
openssl
openssl-master/crypto/pkcs7/pk7_local.h
/* * 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 */ #include "crypto/pkcs7.h" const PKCS7_CTX *ossl_pkcs7_get0_ctx(const PKCS7 *p7); OSSL_LIB_CTX *ossl_pkcs7_ctx_get0_libctx(const PKCS7_CTX *ctx); const char *ossl_pkcs7_ctx_get0_propq(const PKCS7_CTX *ctx); int ossl_pkcs7_ctx_propagate(const PKCS7 *from, PKCS7 *to);
605
34.647059
74
h
openssl
openssl-master/crypto/pkcs7/pk7_mime.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> #include <openssl/asn1.h> #include "pk7_local.h" /* PKCS#7 wrappers round generalised stream and MIME routines */ int i2d_PKCS7_bio_stream(BIO *out, PKCS7 *p7, BIO *in, int flags) { return i2d_ASN1_bio_stream(out, (ASN1_VALUE *)p7, in, flags, ASN1_ITEM_rptr(PKCS7)); } int PEM_write_bio_PKCS7_stream(BIO *out, PKCS7 *p7, BIO *in, int flags) { return PEM_write_bio_ASN1_stream(out, (ASN1_VALUE *)p7, in, flags, "PKCS7", ASN1_ITEM_rptr(PKCS7)); } int SMIME_write_PKCS7(BIO *bio, PKCS7 *p7, BIO *data, int flags) { STACK_OF(X509_ALGOR) *mdalgs; int ctype_nid = OBJ_obj2nid(p7->type); const PKCS7_CTX *ctx = ossl_pkcs7_get0_ctx(p7); if (ctype_nid == NID_pkcs7_signed) mdalgs = p7->d.sign->md_algs; else mdalgs = NULL; flags ^= SMIME_OLDMIME; return SMIME_write_ASN1_ex(bio, (ASN1_VALUE *)p7, data, flags, ctype_nid, NID_undef, mdalgs, ASN1_ITEM_rptr(PKCS7), ossl_pkcs7_ctx_get0_libctx(ctx), ossl_pkcs7_ctx_get0_propq(ctx)); } PKCS7 *SMIME_read_PKCS7_ex(BIO *bio, BIO **bcont, 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 = (PKCS7 *)SMIME_read_ASN1_ex(bio, 0, bcont, ASN1_ITEM_rptr(PKCS7), (ASN1_VALUE **)p7, libctx, propq); if (ret != NULL) ossl_pkcs7_resolve_libctx(ret); return ret; } PKCS7 *SMIME_read_PKCS7(BIO *bio, BIO **bcont) { return SMIME_read_PKCS7_ex(bio, bcont, NULL); }
2,144
29.211268
77
c
openssl
openssl-master/crypto/pkcs7/pk7_smime.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 */ /* Simple PKCS#7 processing functions */ #include <stdio.h> #include "internal/cryptlib.h" #include <openssl/x509.h> #include <openssl/x509v3.h> #include "pk7_local.h" #define BUFFERSIZE 4096 static int pkcs7_copy_existing_digest(PKCS7 *p7, PKCS7_SIGNER_INFO *si); PKCS7 *PKCS7_sign_ex(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, BIO *data, int flags, OSSL_LIB_CTX *libctx, const char *propq) { PKCS7 *p7; int i; if ((p7 = PKCS7_new_ex(libctx, propq)) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_PKCS7_LIB); return NULL; } if (!PKCS7_set_type(p7, NID_pkcs7_signed)) goto err; if (!PKCS7_content_new(p7, NID_pkcs7_data)) goto err; if (pkey && !PKCS7_sign_add_signer(p7, signcert, pkey, NULL, flags)) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_PKCS7_ADD_SIGNER_ERROR); goto err; } if (!(flags & PKCS7_NOCERTS)) { for (i = 0; i < sk_X509_num(certs); i++) { if (!PKCS7_add_certificate(p7, sk_X509_value(certs, i))) goto err; } } if (flags & PKCS7_DETACHED) PKCS7_set_detached(p7, 1); if (flags & (PKCS7_STREAM | PKCS7_PARTIAL)) return p7; if (PKCS7_final(p7, data, flags)) return p7; err: PKCS7_free(p7); return NULL; } PKCS7 *PKCS7_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs, BIO *data, int flags) { return PKCS7_sign_ex(signcert, pkey, certs, data, flags, NULL, NULL); } int PKCS7_final(PKCS7 *p7, BIO *data, int flags) { BIO *p7bio; int ret = 0; if ((p7bio = PKCS7_dataInit(p7, NULL)) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_PKCS7_LIB); return 0; } if (!SMIME_crlf_copy(data, p7bio, flags)) goto err; (void)BIO_flush(p7bio); if (!PKCS7_dataFinal(p7, p7bio)) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_PKCS7_DATASIGN); goto err; } ret = 1; err: BIO_free_all(p7bio); return ret; } /* Check to see if a cipher exists and if so add S/MIME capabilities */ static int add_cipher_smcap(STACK_OF(X509_ALGOR) *sk, int nid, int arg) { if (EVP_get_cipherbynid(nid)) return PKCS7_simple_smimecap(sk, nid, arg); return 1; } static int add_digest_smcap(STACK_OF(X509_ALGOR) *sk, int nid, int arg) { if (EVP_get_digestbynid(nid)) return PKCS7_simple_smimecap(sk, nid, arg); return 1; } PKCS7_SIGNER_INFO *PKCS7_sign_add_signer(PKCS7 *p7, X509 *signcert, EVP_PKEY *pkey, const EVP_MD *md, int flags) { PKCS7_SIGNER_INFO *si = NULL; STACK_OF(X509_ALGOR) *smcap = NULL; if (!X509_check_private_key(signcert, pkey)) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE); return NULL; } if ((si = PKCS7_add_signature(p7, signcert, pkey, md)) == NULL) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_PKCS7_ADD_SIGNATURE_ERROR); return NULL; } si->ctx = ossl_pkcs7_get0_ctx(p7); if (!(flags & PKCS7_NOCERTS)) { if (!PKCS7_add_certificate(p7, signcert)) goto err; } if (!(flags & PKCS7_NOATTR)) { if (!PKCS7_add_attrib_content_type(si, NULL)) goto err; /* Add SMIMECapabilities */ if (!(flags & PKCS7_NOSMIMECAP)) { if ((smcap = sk_X509_ALGOR_new_null()) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_CRYPTO_LIB); goto err; } if (!add_cipher_smcap(smcap, NID_aes_256_cbc, -1) || !add_digest_smcap(smcap, NID_id_GostR3411_2012_256, -1) || !add_digest_smcap(smcap, NID_id_GostR3411_2012_512, -1) || !add_digest_smcap(smcap, NID_id_GostR3411_94, -1) || !add_cipher_smcap(smcap, NID_id_Gost28147_89, -1) || !add_cipher_smcap(smcap, NID_aes_192_cbc, -1) || !add_cipher_smcap(smcap, NID_aes_128_cbc, -1) || !add_cipher_smcap(smcap, NID_des_ede3_cbc, -1) || !add_cipher_smcap(smcap, NID_rc2_cbc, 128) || !add_cipher_smcap(smcap, NID_rc2_cbc, 64) || !add_cipher_smcap(smcap, NID_des_cbc, -1) || !add_cipher_smcap(smcap, NID_rc2_cbc, 40) || !PKCS7_add_attrib_smimecap(si, smcap)) goto err; sk_X509_ALGOR_pop_free(smcap, X509_ALGOR_free); smcap = NULL; } if (flags & PKCS7_REUSE_DIGEST) { if (!pkcs7_copy_existing_digest(p7, si)) goto err; if (!(flags & PKCS7_PARTIAL) && !PKCS7_SIGNER_INFO_sign(si)) goto err; } } return si; err: sk_X509_ALGOR_pop_free(smcap, X509_ALGOR_free); return NULL; } /* * Search for a digest matching SignerInfo digest type and if found copy * across. */ static int pkcs7_copy_existing_digest(PKCS7 *p7, PKCS7_SIGNER_INFO *si) { int i; STACK_OF(PKCS7_SIGNER_INFO) *sinfos; PKCS7_SIGNER_INFO *sitmp; ASN1_OCTET_STRING *osdig = NULL; sinfos = PKCS7_get_signer_info(p7); for (i = 0; i < sk_PKCS7_SIGNER_INFO_num(sinfos); i++) { sitmp = sk_PKCS7_SIGNER_INFO_value(sinfos, i); if (si == sitmp) break; if (sk_X509_ATTRIBUTE_num(sitmp->auth_attr) <= 0) continue; if (!OBJ_cmp(si->digest_alg->algorithm, sitmp->digest_alg->algorithm)) { osdig = PKCS7_digest_from_attributes(sitmp->auth_attr); break; } } if (osdig != NULL) return PKCS7_add1_attrib_digest(si, osdig->data, osdig->length); ERR_raise(ERR_LIB_PKCS7, PKCS7_R_NO_MATCHING_DIGEST_TYPE_FOUND); return 0; } /* This strongly overlaps with CMS_verify(), partly with PKCS7_dataVerify() */ int PKCS7_verify(PKCS7 *p7, STACK_OF(X509) *certs, X509_STORE *store, BIO *indata, BIO *out, int flags) { STACK_OF(X509) *signers; X509 *signer; STACK_OF(PKCS7_SIGNER_INFO) *sinfos; PKCS7_SIGNER_INFO *si; X509_STORE_CTX *cert_ctx = NULL; char *buf = NULL; int i, j = 0, k, ret = 0; BIO *p7bio = NULL; BIO *tmpout = NULL; const PKCS7_CTX *p7_ctx; if (p7 == NULL) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_INVALID_NULL_POINTER); return 0; } if (!PKCS7_type_is_signed(p7)) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_WRONG_CONTENT_TYPE); return 0; } /* Check for no data and no content: no data to verify signature */ if (PKCS7_get_detached(p7) && indata == NULL) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_NO_CONTENT); return 0; } if (flags & PKCS7_NO_DUAL_CONTENT) { /* * This was originally "#if 0" because we thought that only old broken * Netscape did this. It turns out that Authenticode uses this kind * of "extended" PKCS7 format, and things like UEFI secure boot and * tools like osslsigncode need it. In Authenticode the verification * process is different, but the existing PKCs7 verification works. */ if (!PKCS7_get_detached(p7) && indata != NULL) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_CONTENT_AND_DATA_PRESENT); return 0; } } sinfos = PKCS7_get_signer_info(p7); if (!sinfos || !sk_PKCS7_SIGNER_INFO_num(sinfos)) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_NO_SIGNATURES_ON_DATA); return 0; } signers = PKCS7_get0_signers(p7, certs, flags); if (signers == NULL) return 0; /* Now verify the certificates */ p7_ctx = ossl_pkcs7_get0_ctx(p7); cert_ctx = X509_STORE_CTX_new_ex(ossl_pkcs7_ctx_get0_libctx(p7_ctx), ossl_pkcs7_ctx_get0_propq(p7_ctx)); if (cert_ctx == NULL) goto err; if (!(flags & PKCS7_NOVERIFY)) for (k = 0; k < sk_X509_num(signers); k++) { signer = sk_X509_value(signers, k); if (!(flags & PKCS7_NOCHAIN)) { if (!X509_STORE_CTX_init(cert_ctx, store, signer, p7->d.sign->cert)) { ERR_raise(ERR_LIB_PKCS7, ERR_R_X509_LIB); goto err; } if (!X509_STORE_CTX_set_default(cert_ctx, "smime_sign")) goto err; } else if (!X509_STORE_CTX_init(cert_ctx, store, signer, NULL)) { ERR_raise(ERR_LIB_PKCS7, ERR_R_X509_LIB); goto err; } if (!(flags & PKCS7_NOCRL)) X509_STORE_CTX_set0_crls(cert_ctx, p7->d.sign->crl); i = X509_verify_cert(cert_ctx); if (i <= 0) j = X509_STORE_CTX_get_error(cert_ctx); if (i <= 0) { ERR_raise_data(ERR_LIB_PKCS7, PKCS7_R_CERTIFICATE_VERIFY_ERROR, "Verify error: %s", X509_verify_cert_error_string(j)); goto err; } /* Check for revocation status here */ } if ((p7bio = PKCS7_dataInit(p7, indata)) == NULL) goto err; if (flags & PKCS7_TEXT) { if ((tmpout = BIO_new(BIO_s_mem())) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_BIO_LIB); goto err; } BIO_set_mem_eof_return(tmpout, 0); } else tmpout = out; /* We now have to 'read' from p7bio to calculate digests etc. */ if ((buf = OPENSSL_malloc(BUFFERSIZE)) == NULL) goto err; for (;;) { i = BIO_read(p7bio, buf, BUFFERSIZE); if (i <= 0) break; if (tmpout) BIO_write(tmpout, buf, i); } if (flags & PKCS7_TEXT) { if (!SMIME_text(tmpout, out)) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_SMIME_TEXT_ERROR); BIO_free(tmpout); goto err; } BIO_free(tmpout); } /* Now Verify All Signatures */ if (!(flags & PKCS7_NOSIGS)) for (i = 0; i < sk_PKCS7_SIGNER_INFO_num(sinfos); i++) { si = sk_PKCS7_SIGNER_INFO_value(sinfos, i); signer = sk_X509_value(signers, i); j = PKCS7_signatureVerify(p7bio, p7, si, signer); if (j <= 0) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_SIGNATURE_FAILURE); goto err; } } ret = 1; err: X509_STORE_CTX_free(cert_ctx); OPENSSL_free(buf); if (indata != NULL) BIO_pop(p7bio); BIO_free_all(p7bio); sk_X509_free(signers); return ret; } STACK_OF(X509) *PKCS7_get0_signers(PKCS7 *p7, STACK_OF(X509) *certs, int flags) { STACK_OF(X509) *signers; STACK_OF(PKCS7_SIGNER_INFO) *sinfos; PKCS7_SIGNER_INFO *si; PKCS7_ISSUER_AND_SERIAL *ias; X509 *signer; int i; if (p7 == NULL) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_INVALID_NULL_POINTER); return NULL; } if (!PKCS7_type_is_signed(p7)) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_WRONG_CONTENT_TYPE); return NULL; } /* Collect all the signers together */ sinfos = PKCS7_get_signer_info(p7); if (sk_PKCS7_SIGNER_INFO_num(sinfos) <= 0) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_NO_SIGNERS); return 0; } if ((signers = sk_X509_new_null()) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_CRYPTO_LIB); return NULL; } for (i = 0; i < sk_PKCS7_SIGNER_INFO_num(sinfos); i++) { si = sk_PKCS7_SIGNER_INFO_value(sinfos, i); ias = si->issuer_and_serial; signer = NULL; /* If any certificates passed they take priority */ if (certs != NULL) signer = X509_find_by_issuer_and_serial(certs, ias->issuer, ias->serial); if (signer == NULL && !(flags & PKCS7_NOINTERN) && p7->d.sign->cert) signer = X509_find_by_issuer_and_serial(p7->d.sign->cert, ias->issuer, ias->serial); if (signer == NULL) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_SIGNER_CERTIFICATE_NOT_FOUND); sk_X509_free(signers); return 0; } if (!sk_X509_push(signers, signer)) { sk_X509_free(signers); return NULL; } } return signers; } /* Build a complete PKCS#7 enveloped data */ PKCS7 *PKCS7_encrypt_ex(STACK_OF(X509) *certs, BIO *in, const EVP_CIPHER *cipher, int flags, OSSL_LIB_CTX *libctx, const char *propq) { PKCS7 *p7; BIO *p7bio = NULL; int i; X509 *x509; if ((p7 = PKCS7_new_ex(libctx, propq)) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_PKCS7_LIB); return NULL; } if (!PKCS7_set_type(p7, NID_pkcs7_enveloped)) goto err; if (!PKCS7_set_cipher(p7, cipher)) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_ERROR_SETTING_CIPHER); goto err; } for (i = 0; i < sk_X509_num(certs); i++) { x509 = sk_X509_value(certs, i); if (!PKCS7_add_recipient(p7, x509)) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_ERROR_ADDING_RECIPIENT); goto err; } } if (flags & PKCS7_STREAM) return p7; if (PKCS7_final(p7, in, flags)) return p7; err: BIO_free_all(p7bio); PKCS7_free(p7); return NULL; } PKCS7 *PKCS7_encrypt(STACK_OF(X509) *certs, BIO *in, const EVP_CIPHER *cipher, int flags) { return PKCS7_encrypt_ex(certs, in, cipher, flags, NULL, NULL); } int PKCS7_decrypt(PKCS7 *p7, EVP_PKEY *pkey, X509 *cert, BIO *data, int flags) { BIO *tmpmem; int ret = 0, i; char *buf = NULL; if (p7 == NULL) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_INVALID_NULL_POINTER); return 0; } if (!PKCS7_type_is_enveloped(p7) && !PKCS7_type_is_signedAndEnveloped(p7)) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_WRONG_CONTENT_TYPE); return 0; } if (cert && !X509_check_private_key(cert, pkey)) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE); return 0; } if ((tmpmem = PKCS7_dataDecode(p7, pkey, NULL, cert)) == NULL) { ERR_raise(ERR_LIB_PKCS7, PKCS7_R_DECRYPT_ERROR); return 0; } if (flags & PKCS7_TEXT) { BIO *tmpbuf, *bread; /* Encrypt BIOs can't do BIO_gets() so add a buffer BIO */ if ((tmpbuf = BIO_new(BIO_f_buffer())) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_BIO_LIB); BIO_free_all(tmpmem); return 0; } if ((bread = BIO_push(tmpbuf, tmpmem)) == NULL) { ERR_raise(ERR_LIB_PKCS7, ERR_R_BIO_LIB); BIO_free_all(tmpbuf); BIO_free_all(tmpmem); return 0; } ret = SMIME_text(bread, data); if (ret > 0 && BIO_method_type(tmpmem) == BIO_TYPE_CIPHER) { if (BIO_get_cipher_status(tmpmem) <= 0) ret = 0; } BIO_free_all(bread); return ret; } if ((buf = OPENSSL_malloc(BUFFERSIZE)) == NULL) goto err; for (;;) { i = BIO_read(tmpmem, buf, BUFFERSIZE); if (i <= 0) { ret = 1; if (BIO_method_type(tmpmem) == BIO_TYPE_CIPHER) { if (BIO_get_cipher_status(tmpmem) <= 0) ret = 0; } break; } if (BIO_write(data, buf, i) != i) { break; } } err: OPENSSL_free(buf); BIO_free_all(tmpmem); return ret; }
16,116
28.572477
80
c
openssl
openssl-master/crypto/pkcs7/pkcs7err.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/pkcs7err.h> #include "crypto/pkcs7err.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA PKCS7_str_reasons[] = { {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_CERTIFICATE_VERIFY_ERROR), "certificate verify error"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER), "cipher has no object identifier"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_CIPHER_NOT_INITIALIZED), "cipher not initialized"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_CONTENT_AND_DATA_PRESENT), "content and data present"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_CTRL_ERROR), "ctrl error"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_DECRYPT_ERROR), "decrypt error"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_DIGEST_FAILURE), "digest failure"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_ENCRYPTION_CTRL_FAILURE), "encryption ctrl failure"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_ENCRYPTION_NOT_SUPPORTED_FOR_THIS_KEY_TYPE), "encryption not supported for this key type"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_ERROR_ADDING_RECIPIENT), "error adding recipient"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_ERROR_SETTING_CIPHER), "error setting cipher"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_INVALID_NULL_POINTER), "invalid null pointer"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_INVALID_SIGNED_DATA_TYPE), "invalid signed data type"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_NO_CONTENT), "no content"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_NO_DEFAULT_DIGEST), "no default digest"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_NO_MATCHING_DIGEST_TYPE_FOUND), "no matching digest type found"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE), "no recipient matches certificate"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_NO_SIGNATURES_ON_DATA), "no signatures on data"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_NO_SIGNERS), "no signers"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE), "operation not supported on this type"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_PKCS7_ADD_SIGNATURE_ERROR), "pkcs7 add signature error"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_PKCS7_ADD_SIGNER_ERROR), "pkcs7 add signer error"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_PKCS7_DATASIGN), "pkcs7 datasign"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), "private key does not match certificate"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_SIGNATURE_FAILURE), "signature failure"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_SIGNER_CERTIFICATE_NOT_FOUND), "signer certificate not found"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_SIGNING_CTRL_FAILURE), "signing ctrl failure"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_SIGNING_NOT_SUPPORTED_FOR_THIS_KEY_TYPE), "signing not supported for this key type"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_SMIME_TEXT_ERROR), "smime text error"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNABLE_TO_FIND_CERTIFICATE), "unable to find certificate"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNABLE_TO_FIND_MEM_BIO), "unable to find mem bio"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST), "unable to find message digest"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNKNOWN_DIGEST_TYPE), "unknown digest type"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNKNOWN_OPERATION), "unknown operation"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNSUPPORTED_CIPHER_TYPE), "unsupported cipher type"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_UNSUPPORTED_CONTENT_TYPE), "unsupported content type"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_WRONG_CONTENT_TYPE), "wrong content type"}, {ERR_PACK(ERR_LIB_PKCS7, 0, PKCS7_R_WRONG_PKCS7_TYPE), "wrong pkcs7 type"}, {0, NULL} }; #endif int ossl_err_load_PKCS7_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(PKCS7_str_reasons[0].error) == NULL) ERR_load_strings_const(PKCS7_str_reasons); #endif return 1; }
4,431
43.767677
84
c
openssl
openssl-master/crypto/poly1305/poly1305.c
/* * Copyright 2015-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 <stdlib.h> #include <string.h> #include <openssl/crypto.h> #include "crypto/poly1305.h" size_t Poly1305_ctx_size(void) { return sizeof(struct poly1305_context); } /* pick 32-bit unsigned integer in little endian order */ static unsigned int U8TOU32(const unsigned char *p) { return (((unsigned int)(p[0] & 0xff)) | ((unsigned int)(p[1] & 0xff) << 8) | ((unsigned int)(p[2] & 0xff) << 16) | ((unsigned int)(p[3] & 0xff) << 24)); } /* * Implementations can be classified by amount of significant bits in * words making up the multi-precision value, or in other words radix * or base of numerical representation, e.g. base 2^64, base 2^32, * base 2^26. Complementary characteristic is how wide is the result of * multiplication of pair of digits, e.g. it would take 128 bits to * accommodate multiplication result in base 2^64 case. These are used * interchangeably. To describe implementation that is. But interface * is designed to isolate this so that low-level primitives implemented * in assembly can be self-contained/self-coherent. */ #ifndef POLY1305_ASM /* * Even though there is __int128 reference implementation targeting * 64-bit platforms provided below, it's not obvious that it's optimal * choice for every one of them. Depending on instruction set overall * amount of instructions can be comparable to one in __int64 * implementation. Amount of multiplication instructions would be lower, * but not necessarily overall. And in out-of-order execution context, * it is the latter that can be crucial... * * On related note. Poly1305 author, D. J. Bernstein, discusses and * provides floating-point implementations of the algorithm in question. * It made a lot of sense by the time of introduction, because most * then-modern processors didn't have pipelined integer multiplier. * [Not to mention that some had non-constant timing for integer * multiplications.] Floating-point instructions on the other hand could * be issued every cycle, which allowed to achieve better performance. * Nowadays, with SIMD and/or out-or-order execution, shared or * even emulated FPU, it's more complicated, and floating-point * implementation is not necessarily optimal choice in every situation, * rather contrary... * * <[email protected]> */ typedef unsigned int u32; /* * poly1305_blocks processes a multiple of POLY1305_BLOCK_SIZE blocks * of |inp| no longer than |len|. Behaviour for |len| not divisible by * block size is unspecified in general case, even though in reference * implementation the trailing chunk is simply ignored. Per algorithm * specification, every input block, complete or last partial, is to be * padded with a bit past most significant byte. The latter kind is then * padded with zeros till block size. This last partial block padding * is caller(*)'s responsibility, and because of this the last partial * block is always processed with separate call with |len| set to * POLY1305_BLOCK_SIZE and |padbit| to 0. In all other cases |padbit| * should be set to 1 to perform implicit padding with 128th bit. * poly1305_blocks does not actually check for this constraint though, * it's caller(*)'s responsibility to comply. * * (*) In the context "caller" is not application code, but higher * level Poly1305_* from this very module, so that quirks are * handled locally. */ static void poly1305_blocks(void *ctx, const unsigned char *inp, size_t len, u32 padbit); /* * Type-agnostic "rip-off" from constant_time.h */ # define CONSTANT_TIME_CARRY(a,b) ( \ (a ^ ((a ^ b) | ((a - b) ^ b))) >> (sizeof(a) * 8 - 1) \ ) # if defined(INT64_MAX) && defined(INT128_MAX) typedef unsigned long u64; typedef uint128_t u128; typedef struct { u64 h[3]; u64 r[2]; } poly1305_internal; /* pick 32-bit unsigned integer in little endian order */ static u64 U8TOU64(const unsigned char *p) { return (((u64)(p[0] & 0xff)) | ((u64)(p[1] & 0xff) << 8) | ((u64)(p[2] & 0xff) << 16) | ((u64)(p[3] & 0xff) << 24) | ((u64)(p[4] & 0xff) << 32) | ((u64)(p[5] & 0xff) << 40) | ((u64)(p[6] & 0xff) << 48) | ((u64)(p[7] & 0xff) << 56)); } /* store a 32-bit unsigned integer in little endian */ static void U64TO8(unsigned char *p, u64 v) { p[0] = (unsigned char)((v) & 0xff); p[1] = (unsigned char)((v >> 8) & 0xff); p[2] = (unsigned char)((v >> 16) & 0xff); p[3] = (unsigned char)((v >> 24) & 0xff); p[4] = (unsigned char)((v >> 32) & 0xff); p[5] = (unsigned char)((v >> 40) & 0xff); p[6] = (unsigned char)((v >> 48) & 0xff); p[7] = (unsigned char)((v >> 56) & 0xff); } static void poly1305_init(void *ctx, const unsigned char key[16]) { poly1305_internal *st = (poly1305_internal *) ctx; /* h = 0 */ st->h[0] = 0; st->h[1] = 0; st->h[2] = 0; /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */ st->r[0] = U8TOU64(&key[0]) & 0x0ffffffc0fffffff; st->r[1] = U8TOU64(&key[8]) & 0x0ffffffc0ffffffc; } static void poly1305_blocks(void *ctx, const unsigned char *inp, size_t len, u32 padbit) { poly1305_internal *st = (poly1305_internal *)ctx; u64 r0, r1; u64 s1; u64 h0, h1, h2, c; u128 d0, d1; r0 = st->r[0]; r1 = st->r[1]; s1 = r1 + (r1 >> 2); h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; while (len >= POLY1305_BLOCK_SIZE) { /* h += m[i] */ h0 = (u64)(d0 = (u128)h0 + U8TOU64(inp + 0)); h1 = (u64)(d1 = (u128)h1 + (d0 >> 64) + U8TOU64(inp + 8)); /* * padbit can be zero only when original len was * POLY1306_BLOCK_SIZE, but we don't check */ h2 += (u64)(d1 >> 64) + padbit; /* h *= r "%" p, where "%" stands for "partial remainder" */ d0 = ((u128)h0 * r0) + ((u128)h1 * s1); d1 = ((u128)h0 * r1) + ((u128)h1 * r0) + (h2 * s1); h2 = (h2 * r0); /* last reduction step: */ /* a) h2:h0 = h2<<128 + d1<<64 + d0 */ h0 = (u64)d0; h1 = (u64)(d1 += d0 >> 64); h2 += (u64)(d1 >> 64); /* b) (h2:h0 += (h2:h0>>130) * 5) %= 2^130 */ c = (h2 >> 2) + (h2 & ~3UL); h2 &= 3; h0 += c; h1 += (c = CONSTANT_TIME_CARRY(h0,c)); h2 += CONSTANT_TIME_CARRY(h1,c); /* * Occasional overflows to 3rd bit of h2 are taken care of * "naturally". If after this point we end up at the top of * this loop, then the overflow bit will be accounted for * in next iteration. If we end up in poly1305_emit, then * comparison to modulus below will still count as "carry * into 131st bit", so that properly reduced value will be * picked in conditional move. */ inp += POLY1305_BLOCK_SIZE; len -= POLY1305_BLOCK_SIZE; } st->h[0] = h0; st->h[1] = h1; st->h[2] = h2; } static void poly1305_emit(void *ctx, unsigned char mac[16], const u32 nonce[4]) { poly1305_internal *st = (poly1305_internal *) ctx; u64 h0, h1, h2; u64 g0, g1, g2; u128 t; u64 mask; h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; /* compare to modulus by computing h + -p */ g0 = (u64)(t = (u128)h0 + 5); g1 = (u64)(t = (u128)h1 + (t >> 64)); g2 = h2 + (u64)(t >> 64); /* if there was carry into 131st bit, h1:h0 = g1:g0 */ mask = 0 - (g2 >> 2); g0 &= mask; g1 &= mask; mask = ~mask; h0 = (h0 & mask) | g0; h1 = (h1 & mask) | g1; /* mac = (h + nonce) % (2^128) */ h0 = (u64)(t = (u128)h0 + nonce[0] + ((u64)nonce[1]<<32)); h1 = (u64)(t = (u128)h1 + nonce[2] + ((u64)nonce[3]<<32) + (t >> 64)); U64TO8(mac + 0, h0); U64TO8(mac + 8, h1); } # else # if defined(_WIN32) && !defined(__MINGW32__) typedef unsigned __int64 u64; # elif defined(__arch64__) typedef unsigned long u64; # else typedef unsigned long long u64; # endif typedef struct { u32 h[5]; u32 r[4]; } poly1305_internal; /* store a 32-bit unsigned integer in little endian */ static void U32TO8(unsigned char *p, unsigned int v) { p[0] = (unsigned char)((v) & 0xff); p[1] = (unsigned char)((v >> 8) & 0xff); p[2] = (unsigned char)((v >> 16) & 0xff); p[3] = (unsigned char)((v >> 24) & 0xff); } static void poly1305_init(void *ctx, const unsigned char key[16]) { poly1305_internal *st = (poly1305_internal *) ctx; /* h = 0 */ st->h[0] = 0; st->h[1] = 0; st->h[2] = 0; st->h[3] = 0; st->h[4] = 0; /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */ st->r[0] = U8TOU32(&key[0]) & 0x0fffffff; st->r[1] = U8TOU32(&key[4]) & 0x0ffffffc; st->r[2] = U8TOU32(&key[8]) & 0x0ffffffc; st->r[3] = U8TOU32(&key[12]) & 0x0ffffffc; } static void poly1305_blocks(void *ctx, const unsigned char *inp, size_t len, u32 padbit) { poly1305_internal *st = (poly1305_internal *)ctx; u32 r0, r1, r2, r3; u32 s1, s2, s3; u32 h0, h1, h2, h3, h4, c; u64 d0, d1, d2, d3; r0 = st->r[0]; r1 = st->r[1]; r2 = st->r[2]; r3 = st->r[3]; s1 = r1 + (r1 >> 2); s2 = r2 + (r2 >> 2); s3 = r3 + (r3 >> 2); h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; h3 = st->h[3]; h4 = st->h[4]; while (len >= POLY1305_BLOCK_SIZE) { /* h += m[i] */ h0 = (u32)(d0 = (u64)h0 + U8TOU32(inp + 0)); h1 = (u32)(d1 = (u64)h1 + (d0 >> 32) + U8TOU32(inp + 4)); h2 = (u32)(d2 = (u64)h2 + (d1 >> 32) + U8TOU32(inp + 8)); h3 = (u32)(d3 = (u64)h3 + (d2 >> 32) + U8TOU32(inp + 12)); h4 += (u32)(d3 >> 32) + padbit; /* h *= r "%" p, where "%" stands for "partial remainder" */ d0 = ((u64)h0 * r0) + ((u64)h1 * s3) + ((u64)h2 * s2) + ((u64)h3 * s1); d1 = ((u64)h0 * r1) + ((u64)h1 * r0) + ((u64)h2 * s3) + ((u64)h3 * s2) + (h4 * s1); d2 = ((u64)h0 * r2) + ((u64)h1 * r1) + ((u64)h2 * r0) + ((u64)h3 * s3) + (h4 * s2); d3 = ((u64)h0 * r3) + ((u64)h1 * r2) + ((u64)h2 * r1) + ((u64)h3 * r0) + (h4 * s3); h4 = (h4 * r0); /* last reduction step: */ /* a) h4:h0 = h4<<128 + d3<<96 + d2<<64 + d1<<32 + d0 */ h0 = (u32)d0; h1 = (u32)(d1 += d0 >> 32); h2 = (u32)(d2 += d1 >> 32); h3 = (u32)(d3 += d2 >> 32); h4 += (u32)(d3 >> 32); /* b) (h4:h0 += (h4:h0>>130) * 5) %= 2^130 */ c = (h4 >> 2) + (h4 & ~3U); h4 &= 3; h0 += c; h1 += (c = CONSTANT_TIME_CARRY(h0,c)); h2 += (c = CONSTANT_TIME_CARRY(h1,c)); h3 += (c = CONSTANT_TIME_CARRY(h2,c)); h4 += CONSTANT_TIME_CARRY(h3,c); /* * Occasional overflows to 3rd bit of h4 are taken care of * "naturally". If after this point we end up at the top of * this loop, then the overflow bit will be accounted for * in next iteration. If we end up in poly1305_emit, then * comparison to modulus below will still count as "carry * into 131st bit", so that properly reduced value will be * picked in conditional move. */ inp += POLY1305_BLOCK_SIZE; len -= POLY1305_BLOCK_SIZE; } st->h[0] = h0; st->h[1] = h1; st->h[2] = h2; st->h[3] = h3; st->h[4] = h4; } static void poly1305_emit(void *ctx, unsigned char mac[16], const u32 nonce[4]) { poly1305_internal *st = (poly1305_internal *) ctx; u32 h0, h1, h2, h3, h4; u32 g0, g1, g2, g3, g4; u64 t; u32 mask; h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; h3 = st->h[3]; h4 = st->h[4]; /* compare to modulus by computing h + -p */ g0 = (u32)(t = (u64)h0 + 5); g1 = (u32)(t = (u64)h1 + (t >> 32)); g2 = (u32)(t = (u64)h2 + (t >> 32)); g3 = (u32)(t = (u64)h3 + (t >> 32)); g4 = h4 + (u32)(t >> 32); /* if there was carry into 131st bit, h3:h0 = g3:g0 */ mask = 0 - (g4 >> 2); g0 &= mask; g1 &= mask; g2 &= mask; g3 &= mask; mask = ~mask; h0 = (h0 & mask) | g0; h1 = (h1 & mask) | g1; h2 = (h2 & mask) | g2; h3 = (h3 & mask) | g3; /* mac = (h + nonce) % (2^128) */ h0 = (u32)(t = (u64)h0 + nonce[0]); h1 = (u32)(t = (u64)h1 + (t >> 32) + nonce[1]); h2 = (u32)(t = (u64)h2 + (t >> 32) + nonce[2]); h3 = (u32)(t = (u64)h3 + (t >> 32) + nonce[3]); U32TO8(mac + 0, h0); U32TO8(mac + 4, h1); U32TO8(mac + 8, h2); U32TO8(mac + 12, h3); } # endif #else int poly1305_init(void *ctx, const unsigned char key[16], void *func); void poly1305_blocks(void *ctx, const unsigned char *inp, size_t len, unsigned int padbit); void poly1305_emit(void *ctx, unsigned char mac[16], const unsigned int nonce[4]); #endif void Poly1305_Init(POLY1305 *ctx, const unsigned char key[32]) { ctx->nonce[0] = U8TOU32(&key[16]); ctx->nonce[1] = U8TOU32(&key[20]); ctx->nonce[2] = U8TOU32(&key[24]); ctx->nonce[3] = U8TOU32(&key[28]); #ifndef POLY1305_ASM poly1305_init(ctx->opaque, key); #else /* * Unlike reference poly1305_init assembly counterpart is expected * to return a value: non-zero if it initializes ctx->func, and zero * otherwise. Latter is to simplify assembly in cases when there no * multiple code paths to switch between. */ if (!poly1305_init(ctx->opaque, key, &ctx->func)) { ctx->func.blocks = poly1305_blocks; ctx->func.emit = poly1305_emit; } #endif ctx->num = 0; } #ifdef POLY1305_ASM /* * This "eclipses" poly1305_blocks and poly1305_emit, but it's * conscious choice imposed by -Wshadow compiler warnings. */ # define poly1305_blocks (*poly1305_blocks_p) # define poly1305_emit (*poly1305_emit_p) #endif void Poly1305_Update(POLY1305 *ctx, const unsigned char *inp, size_t len) { #ifdef POLY1305_ASM /* * As documented, poly1305_blocks is never called with input * longer than single block and padbit argument set to 0. This * property is fluently used in assembly modules to optimize * padbit handling on loop boundary. */ poly1305_blocks_f poly1305_blocks_p = ctx->func.blocks; #endif size_t rem, num; if ((num = ctx->num)) { rem = POLY1305_BLOCK_SIZE - num; if (len >= rem) { memcpy(ctx->data + num, inp, rem); poly1305_blocks(ctx->opaque, ctx->data, POLY1305_BLOCK_SIZE, 1); inp += rem; len -= rem; } else { /* Still not enough data to process a block. */ memcpy(ctx->data + num, inp, len); ctx->num = num + len; return; } } rem = len % POLY1305_BLOCK_SIZE; len -= rem; if (len >= POLY1305_BLOCK_SIZE) { poly1305_blocks(ctx->opaque, inp, len, 1); inp += len; } if (rem) memcpy(ctx->data, inp, rem); ctx->num = rem; } void Poly1305_Final(POLY1305 *ctx, unsigned char mac[16]) { #ifdef POLY1305_ASM poly1305_blocks_f poly1305_blocks_p = ctx->func.blocks; poly1305_emit_f poly1305_emit_p = ctx->func.emit; #endif size_t num; if ((num = ctx->num)) { ctx->data[num++] = 1; /* pad bit */ while (num < POLY1305_BLOCK_SIZE) ctx->data[num++] = 0; poly1305_blocks(ctx->opaque, ctx->data, POLY1305_BLOCK_SIZE, 0); } poly1305_emit(ctx->opaque, mac, ctx->nonce); /* zero out the state */ OPENSSL_cleanse(ctx, sizeof(*ctx)); }
16,175
29.520755
77
c
openssl
openssl-master/crypto/poly1305/poly1305_base2_44.c
/* * Copyright 2016-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 module is meant to be used as template for base 2^44 assembly * implementation[s]. On side note compiler-generated code is not * slower than compiler-generated base 2^64 code on [high-end] x86_64, * even though amount of multiplications is 50% higher. Go figure... */ #include <stdlib.h> typedef unsigned char u8; typedef unsigned int u32; typedef unsigned long u64; typedef uint128_t u128; typedef struct { u64 h[3]; u64 s[2]; u64 r[3]; } poly1305_internal; #define POLY1305_BLOCK_SIZE 16 /* pick 64-bit unsigned integer in little endian order */ static u64 U8TOU64(const unsigned char *p) { return (((u64)(p[0] & 0xff)) | ((u64)(p[1] & 0xff) << 8) | ((u64)(p[2] & 0xff) << 16) | ((u64)(p[3] & 0xff) << 24) | ((u64)(p[4] & 0xff) << 32) | ((u64)(p[5] & 0xff) << 40) | ((u64)(p[6] & 0xff) << 48) | ((u64)(p[7] & 0xff) << 56)); } /* store a 64-bit unsigned integer in little endian */ static void U64TO8(unsigned char *p, u64 v) { p[0] = (unsigned char)((v) & 0xff); p[1] = (unsigned char)((v >> 8) & 0xff); p[2] = (unsigned char)((v >> 16) & 0xff); p[3] = (unsigned char)((v >> 24) & 0xff); p[4] = (unsigned char)((v >> 32) & 0xff); p[5] = (unsigned char)((v >> 40) & 0xff); p[6] = (unsigned char)((v >> 48) & 0xff); p[7] = (unsigned char)((v >> 56) & 0xff); } int poly1305_init(void *ctx, const unsigned char key[16]) { poly1305_internal *st = (poly1305_internal *)ctx; u64 r0, r1; /* h = 0 */ st->h[0] = 0; st->h[1] = 0; st->h[2] = 0; r0 = U8TOU64(&key[0]) & 0x0ffffffc0fffffff; r1 = U8TOU64(&key[8]) & 0x0ffffffc0ffffffc; /* break r1:r0 to three 44-bit digits, masks are 1<<44-1 */ st->r[0] = r0 & 0x0fffffffffff; st->r[1] = ((r0 >> 44) | (r1 << 20)) & 0x0fffffffffff; st->r[2] = (r1 >> 24); st->s[0] = (st->r[1] + (st->r[1] << 2)) << 2; st->s[1] = (st->r[2] + (st->r[2] << 2)) << 2; return 0; } void poly1305_blocks(void *ctx, const unsigned char *inp, size_t len, u32 padbit) { poly1305_internal *st = (poly1305_internal *)ctx; u64 r0, r1, r2; u64 s1, s2; u64 h0, h1, h2, c; u128 d0, d1, d2; u64 pad = (u64)padbit << 40; r0 = st->r[0]; r1 = st->r[1]; r2 = st->r[2]; s1 = st->s[0]; s2 = st->s[1]; h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; while (len >= POLY1305_BLOCK_SIZE) { u64 m0, m1; m0 = U8TOU64(inp + 0); m1 = U8TOU64(inp + 8); /* h += m[i], m[i] is broken to 44-bit digits */ h0 += m0 & 0x0fffffffffff; h1 += ((m0 >> 44) | (m1 << 20)) & 0x0fffffffffff; h2 += (m1 >> 24) + pad; /* h *= r "%" p, where "%" stands for "partial remainder" */ d0 = ((u128)h0 * r0) + ((u128)h1 * s2) + ((u128)h2 * s1); d1 = ((u128)h0 * r1) + ((u128)h1 * r0) + ((u128)h2 * s2); d2 = ((u128)h0 * r2) + ((u128)h1 * r1) + ((u128)h2 * r0); /* "lazy" reduction step */ h0 = (u64)d0 & 0x0fffffffffff; h1 = (u64)(d1 += (u64)(d0 >> 44)) & 0x0fffffffffff; h2 = (u64)(d2 += (u64)(d1 >> 44)) & 0x03ffffffffff; /* last 42 bits */ c = (d2 >> 42); h0 += c + (c << 2); inp += POLY1305_BLOCK_SIZE; len -= POLY1305_BLOCK_SIZE; } st->h[0] = h0; st->h[1] = h1; st->h[2] = h2; } void poly1305_emit(void *ctx, unsigned char mac[16], const u32 nonce[4]) { poly1305_internal *st = (poly1305_internal *) ctx; u64 h0, h1, h2; u64 g0, g1, g2; u128 t; u64 mask; h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; /* after "lazy" reduction, convert 44+bit digits to 64-bit ones */ h0 = (u64)(t = (u128)h0 + (h1 << 44)); h1 >>= 20; h1 = (u64)(t = (u128)h1 + (h2 << 24) + (t >> 64)); h2 >>= 40; h2 += (u64)(t >> 64); /* compare to modulus by computing h + -p */ g0 = (u64)(t = (u128)h0 + 5); g1 = (u64)(t = (u128)h1 + (t >> 64)); g2 = h2 + (u64)(t >> 64); /* if there was carry into 131st bit, h1:h0 = g1:g0 */ mask = 0 - (g2 >> 2); g0 &= mask; g1 &= mask; mask = ~mask; h0 = (h0 & mask) | g0; h1 = (h1 & mask) | g1; /* mac = (h + nonce) % (2^128) */ h0 = (u64)(t = (u128)h0 + nonce[0] + ((u64)nonce[1]<<32)); h1 = (u64)(t = (u128)h1 + nonce[2] + ((u64)nonce[3]<<32) + (t >> 64)); U64TO8(mac + 0, h0); U64TO8(mac + 8, h1); }
4,830
27.087209
78
c
openssl
openssl-master/crypto/poly1305/poly1305_ieee754.c
/* * Copyright 2016-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 */ /* * This module is meant to be used as template for non-x87 floating- * point assembly modules. The template itself is x86_64-specific * though, as it was debugged on x86_64. So that implementor would * have to recognize platform-specific parts, UxTOy and inline asm, * and act accordingly. * * Huh? x86_64-specific code as template for non-x87? Note seven, which * is not a typo, but reference to 80-bit precision. This module on the * other hand relies on 64-bit precision operations, which are default * for x86_64 code. And since we are at it, just for sense of it, * large-block performance in cycles per processed byte for *this* code * is: * gcc-4.8 icc-15.0 clang-3.4(*) * * Westmere 4.96 5.09 4.37 * Sandy Bridge 4.95 4.90 4.17 * Haswell 4.92 4.87 3.78 * Bulldozer 4.67 4.49 4.68 * VIA Nano 7.07 7.05 5.98 * Silvermont 10.6 9.61 12.6 * * (*) clang managed to discover parallelism and deployed SIMD; * * And for range of other platforms with unspecified gcc versions: * * Freescale e300 12.5 * PPC74x0 10.8 * POWER6 4.92 * POWER7 4.50 * POWER8 4.10 * * z10 11.2 * z196+ 7.30 * * UltraSPARC III 16.0 * SPARC T4 16.1 */ #if !(defined(__GNUC__) && __GNUC__>=2) # error "this is gcc-specific template" #endif #include <stdlib.h> typedef unsigned char u8; typedef unsigned int u32; typedef unsigned long long u64; typedef union { double d; u64 u; } elem64; #define TWO(p) ((double)(1ULL<<(p))) #define TWO0 TWO(0) #define TWO32 TWO(32) #define TWO64 (TWO32*TWO(32)) #define TWO96 (TWO64*TWO(32)) #define TWO130 (TWO96*TWO(34)) #define EXP(p) ((1023ULL+(p))<<52) #if defined(__x86_64__) || (defined(__PPC__) && defined(__LITTLE_ENDIAN__)) # define U8TOU32(p) (*(const u32 *)(p)) # define U32TO8(p,v) (*(u32 *)(p) = (v)) #elif defined(__PPC__) # define U8TOU32(p) ({u32 ret; asm ("lwbrx %0,0,%1":"=r"(ret):"b"(p)); ret; }) # define U32TO8(p,v) asm ("stwbrx %0,0,%1"::"r"(v),"b"(p):"memory") #elif defined(__s390x__) # define U8TOU32(p) ({u32 ret; asm ("lrv %0,%1":"=d"(ret):"m"(*(u32 *)(p))); ret; }) # define U32TO8(p,v) asm ("strv %1,%0":"=m"(*(u32 *)(p)):"d"(v)) #endif #ifndef U8TOU32 # define U8TOU32(p) ((u32)(p)[0] | (u32)(p)[1]<<8 | \ (u32)(p)[2]<<16 | (u32)(p)[3]<<24 ) #endif #ifndef U32TO8 # define U32TO8(p,v) ((p)[0] = (u8)(v), (p)[1] = (u8)((v)>>8), \ (p)[2] = (u8)((v)>>16), (p)[3] = (u8)((v)>>24) ) #endif typedef struct { elem64 h[4]; double r[8]; double s[6]; } poly1305_internal; /* "round toward zero (truncate), mask all exceptions" */ #if defined(__x86_64__) static const u32 mxcsr = 0x7f80; #elif defined(__PPC__) static const u64 one = 1; #elif defined(__s390x__) static const u32 fpc = 1; #elif defined(__sparc__) static const u64 fsr = 1ULL<<30; #elif defined(__mips__) static const u32 fcsr = 1; #else #error "unrecognized platform" #endif int poly1305_init(void *ctx, const unsigned char key[16]) { poly1305_internal *st = (poly1305_internal *) ctx; elem64 r0, r1, r2, r3; /* h = 0, biased */ #if 0 st->h[0].d = TWO(52)*TWO0; st->h[1].d = TWO(52)*TWO32; st->h[2].d = TWO(52)*TWO64; st->h[3].d = TWO(52)*TWO96; #else st->h[0].u = EXP(52+0); st->h[1].u = EXP(52+32); st->h[2].u = EXP(52+64); st->h[3].u = EXP(52+96); #endif if (key) { /* * set "truncate" rounding mode */ #if defined(__x86_64__) u32 mxcsr_orig; asm volatile ("stmxcsr %0":"=m"(mxcsr_orig)); asm volatile ("ldmxcsr %0"::"m"(mxcsr)); #elif defined(__PPC__) double fpscr_orig, fpscr = *(double *)&one; asm volatile ("mffs %0":"=f"(fpscr_orig)); asm volatile ("mtfsf 255,%0"::"f"(fpscr)); #elif defined(__s390x__) u32 fpc_orig; asm volatile ("stfpc %0":"=m"(fpc_orig)); asm volatile ("lfpc %0"::"m"(fpc)); #elif defined(__sparc__) u64 fsr_orig; asm volatile ("stx %%fsr,%0":"=m"(fsr_orig)); asm volatile ("ldx %0,%%fsr"::"m"(fsr)); #elif defined(__mips__) u32 fcsr_orig; asm volatile ("cfc1 %0,$31":"=r"(fcsr_orig)); asm volatile ("ctc1 %0,$31"::"r"(fcsr)); #endif /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */ r0.u = EXP(52+0) | (U8TOU32(&key[0]) & 0x0fffffff); r1.u = EXP(52+32) | (U8TOU32(&key[4]) & 0x0ffffffc); r2.u = EXP(52+64) | (U8TOU32(&key[8]) & 0x0ffffffc); r3.u = EXP(52+96) | (U8TOU32(&key[12]) & 0x0ffffffc); st->r[0] = r0.d - TWO(52)*TWO0; st->r[2] = r1.d - TWO(52)*TWO32; st->r[4] = r2.d - TWO(52)*TWO64; st->r[6] = r3.d - TWO(52)*TWO96; st->s[0] = st->r[2] * (5.0/TWO130); st->s[2] = st->r[4] * (5.0/TWO130); st->s[4] = st->r[6] * (5.0/TWO130); /* * base 2^32 -> base 2^16 */ st->r[1] = (st->r[0] + TWO(52)*TWO(16)*TWO0) - TWO(52)*TWO(16)*TWO0; st->r[0] -= st->r[1]; st->r[3] = (st->r[2] + TWO(52)*TWO(16)*TWO32) - TWO(52)*TWO(16)*TWO32; st->r[2] -= st->r[3]; st->r[5] = (st->r[4] + TWO(52)*TWO(16)*TWO64) - TWO(52)*TWO(16)*TWO64; st->r[4] -= st->r[5]; st->r[7] = (st->r[6] + TWO(52)*TWO(16)*TWO96) - TWO(52)*TWO(16)*TWO96; st->r[6] -= st->r[7]; st->s[1] = (st->s[0] + TWO(52)*TWO(16)*TWO0/TWO96) - TWO(52)*TWO(16)*TWO0/TWO96; st->s[0] -= st->s[1]; st->s[3] = (st->s[2] + TWO(52)*TWO(16)*TWO32/TWO96) - TWO(52)*TWO(16)*TWO32/TWO96; st->s[2] -= st->s[3]; st->s[5] = (st->s[4] + TWO(52)*TWO(16)*TWO64/TWO96) - TWO(52)*TWO(16)*TWO64/TWO96; st->s[4] -= st->s[5]; /* * restore original FPU control register */ #if defined(__x86_64__) asm volatile ("ldmxcsr %0"::"m"(mxcsr_orig)); #elif defined(__PPC__) asm volatile ("mtfsf 255,%0"::"f"(fpscr_orig)); #elif defined(__s390x__) asm volatile ("lfpc %0"::"m"(fpc_orig)); #elif defined(__sparc__) asm volatile ("ldx %0,%%fsr"::"m"(fsr_orig)); #elif defined(__mips__) asm volatile ("ctc1 %0,$31"::"r"(fcsr_orig)); #endif } return 0; } void poly1305_blocks(void *ctx, const unsigned char *inp, size_t len, int padbit) { poly1305_internal *st = (poly1305_internal *)ctx; elem64 in0, in1, in2, in3; u64 pad = (u64)padbit<<32; double x0, x1, x2, x3; double h0lo, h0hi, h1lo, h1hi, h2lo, h2hi, h3lo, h3hi; double c0lo, c0hi, c1lo, c1hi, c2lo, c2hi, c3lo, c3hi; const double r0lo = st->r[0]; const double r0hi = st->r[1]; const double r1lo = st->r[2]; const double r1hi = st->r[3]; const double r2lo = st->r[4]; const double r2hi = st->r[5]; const double r3lo = st->r[6]; const double r3hi = st->r[7]; const double s1lo = st->s[0]; const double s1hi = st->s[1]; const double s2lo = st->s[2]; const double s2hi = st->s[3]; const double s3lo = st->s[4]; const double s3hi = st->s[5]; /* * set "truncate" rounding mode */ #if defined(__x86_64__) u32 mxcsr_orig; asm volatile ("stmxcsr %0":"=m"(mxcsr_orig)); asm volatile ("ldmxcsr %0"::"m"(mxcsr)); #elif defined(__PPC__) double fpscr_orig, fpscr = *(double *)&one; asm volatile ("mffs %0":"=f"(fpscr_orig)); asm volatile ("mtfsf 255,%0"::"f"(fpscr)); #elif defined(__s390x__) u32 fpc_orig; asm volatile ("stfpc %0":"=m"(fpc_orig)); asm volatile ("lfpc %0"::"m"(fpc)); #elif defined(__sparc__) u64 fsr_orig; asm volatile ("stx %%fsr,%0":"=m"(fsr_orig)); asm volatile ("ldx %0,%%fsr"::"m"(fsr)); #elif defined(__mips__) u32 fcsr_orig; asm volatile ("cfc1 %0,$31":"=r"(fcsr_orig)); asm volatile ("ctc1 %0,$31"::"r"(fcsr)); #endif /* * load base 2^32 and de-bias */ h0lo = st->h[0].d - TWO(52)*TWO0; h1lo = st->h[1].d - TWO(52)*TWO32; h2lo = st->h[2].d - TWO(52)*TWO64; h3lo = st->h[3].d - TWO(52)*TWO96; #ifdef __clang__ h0hi = 0; h1hi = 0; h2hi = 0; h3hi = 0; #else in0.u = EXP(52+0) | U8TOU32(&inp[0]); in1.u = EXP(52+32) | U8TOU32(&inp[4]); in2.u = EXP(52+64) | U8TOU32(&inp[8]); in3.u = EXP(52+96) | U8TOU32(&inp[12]) | pad; x0 = in0.d - TWO(52)*TWO0; x1 = in1.d - TWO(52)*TWO32; x2 = in2.d - TWO(52)*TWO64; x3 = in3.d - TWO(52)*TWO96; x0 += h0lo; x1 += h1lo; x2 += h2lo; x3 += h3lo; goto fast_entry; #endif do { in0.u = EXP(52+0) | U8TOU32(&inp[0]); in1.u = EXP(52+32) | U8TOU32(&inp[4]); in2.u = EXP(52+64) | U8TOU32(&inp[8]); in3.u = EXP(52+96) | U8TOU32(&inp[12]) | pad; x0 = in0.d - TWO(52)*TWO0; x1 = in1.d - TWO(52)*TWO32; x2 = in2.d - TWO(52)*TWO64; x3 = in3.d - TWO(52)*TWO96; /* * note that there are multiple ways to accumulate input, e.g. * one can as well accumulate to h0lo-h1lo-h1hi-h2hi... */ h0lo += x0; h0hi += x1; h2lo += x2; h2hi += x3; /* * carries that cross 32n-bit (and 130-bit) boundaries */ c0lo = (h0lo + TWO(52)*TWO32) - TWO(52)*TWO32; c1lo = (h1lo + TWO(52)*TWO64) - TWO(52)*TWO64; c2lo = (h2lo + TWO(52)*TWO96) - TWO(52)*TWO96; c3lo = (h3lo + TWO(52)*TWO130) - TWO(52)*TWO130; c0hi = (h0hi + TWO(52)*TWO32) - TWO(52)*TWO32; c1hi = (h1hi + TWO(52)*TWO64) - TWO(52)*TWO64; c2hi = (h2hi + TWO(52)*TWO96) - TWO(52)*TWO96; c3hi = (h3hi + TWO(52)*TWO130) - TWO(52)*TWO130; /* * base 2^48 -> base 2^32 with last reduction step */ x1 = (h1lo - c1lo) + c0lo; x2 = (h2lo - c2lo) + c1lo; x3 = (h3lo - c3lo) + c2lo; x0 = (h0lo - c0lo) + c3lo * (5.0/TWO130); x1 += (h1hi - c1hi) + c0hi; x2 += (h2hi - c2hi) + c1hi; x3 += (h3hi - c3hi) + c2hi; x0 += (h0hi - c0hi) + c3hi * (5.0/TWO130); #ifndef __clang__ fast_entry: #endif /* * base 2^32 * base 2^16 = base 2^48 */ h0lo = s3lo * x1 + s2lo * x2 + s1lo * x3 + r0lo * x0; h1lo = r0lo * x1 + s3lo * x2 + s2lo * x3 + r1lo * x0; h2lo = r1lo * x1 + r0lo * x2 + s3lo * x3 + r2lo * x0; h3lo = r2lo * x1 + r1lo * x2 + r0lo * x3 + r3lo * x0; h0hi = s3hi * x1 + s2hi * x2 + s1hi * x3 + r0hi * x0; h1hi = r0hi * x1 + s3hi * x2 + s2hi * x3 + r1hi * x0; h2hi = r1hi * x1 + r0hi * x2 + s3hi * x3 + r2hi * x0; h3hi = r2hi * x1 + r1hi * x2 + r0hi * x3 + r3hi * x0; inp += 16; len -= 16; } while (len >= 16); /* * carries that cross 32n-bit (and 130-bit) boundaries */ c0lo = (h0lo + TWO(52)*TWO32) - TWO(52)*TWO32; c1lo = (h1lo + TWO(52)*TWO64) - TWO(52)*TWO64; c2lo = (h2lo + TWO(52)*TWO96) - TWO(52)*TWO96; c3lo = (h3lo + TWO(52)*TWO130) - TWO(52)*TWO130; c0hi = (h0hi + TWO(52)*TWO32) - TWO(52)*TWO32; c1hi = (h1hi + TWO(52)*TWO64) - TWO(52)*TWO64; c2hi = (h2hi + TWO(52)*TWO96) - TWO(52)*TWO96; c3hi = (h3hi + TWO(52)*TWO130) - TWO(52)*TWO130; /* * base 2^48 -> base 2^32 with last reduction step */ x1 = (h1lo - c1lo) + c0lo; x2 = (h2lo - c2lo) + c1lo; x3 = (h3lo - c3lo) + c2lo; x0 = (h0lo - c0lo) + c3lo * (5.0/TWO130); x1 += (h1hi - c1hi) + c0hi; x2 += (h2hi - c2hi) + c1hi; x3 += (h3hi - c3hi) + c2hi; x0 += (h0hi - c0hi) + c3hi * (5.0/TWO130); /* * store base 2^32, with bias */ st->h[1].d = x1 + TWO(52)*TWO32; st->h[2].d = x2 + TWO(52)*TWO64; st->h[3].d = x3 + TWO(52)*TWO96; st->h[0].d = x0 + TWO(52)*TWO0; /* * restore original FPU control register */ #if defined(__x86_64__) asm volatile ("ldmxcsr %0"::"m"(mxcsr_orig)); #elif defined(__PPC__) asm volatile ("mtfsf 255,%0"::"f"(fpscr_orig)); #elif defined(__s390x__) asm volatile ("lfpc %0"::"m"(fpc_orig)); #elif defined(__sparc__) asm volatile ("ldx %0,%%fsr"::"m"(fsr_orig)); #elif defined(__mips__) asm volatile ("ctc1 %0,$31"::"r"(fcsr_orig)); #endif } void poly1305_emit(void *ctx, unsigned char mac[16], const u32 nonce[4]) { poly1305_internal *st = (poly1305_internal *) ctx; u64 h0, h1, h2, h3, h4; u32 g0, g1, g2, g3, g4; u64 t; u32 mask; /* * thanks to bias masking exponent gives integer result */ h0 = st->h[0].u & 0x000fffffffffffffULL; h1 = st->h[1].u & 0x000fffffffffffffULL; h2 = st->h[2].u & 0x000fffffffffffffULL; h3 = st->h[3].u & 0x000fffffffffffffULL; /* * can be partially reduced, so reduce... */ h4 = h3>>32; h3 &= 0xffffffffU; g4 = h4&-4; h4 &= 3; g4 += g4>>2; h0 += g4; h1 += h0>>32; h0 &= 0xffffffffU; h2 += h1>>32; h1 &= 0xffffffffU; h3 += h2>>32; h2 &= 0xffffffffU; /* compute h + -p */ g0 = (u32)(t = h0 + 5); g1 = (u32)(t = h1 + (t >> 32)); g2 = (u32)(t = h2 + (t >> 32)); g3 = (u32)(t = h3 + (t >> 32)); g4 = h4 + (u32)(t >> 32); /* if there was carry, select g0-g3 */ mask = 0 - (g4 >> 2); g0 &= mask; g1 &= mask; g2 &= mask; g3 &= mask; mask = ~mask; g0 |= (h0 & mask); g1 |= (h1 & mask); g2 |= (h2 & mask); g3 |= (h3 & mask); /* mac = (h + nonce) % (2^128) */ g0 = (u32)(t = (u64)g0 + nonce[0]); g1 = (u32)(t = (u64)g1 + (t >> 32) + nonce[1]); g2 = (u32)(t = (u64)g2 + (t >> 32) + nonce[2]); g3 = (u32)(t = (u64)g3 + (t >> 32) + nonce[3]); U32TO8(mac + 0, g0); U32TO8(mac + 4, g1); U32TO8(mac + 8, g2); U32TO8(mac + 12, g3); }
14,640
28.940695
88
c
openssl
openssl-master/crypto/poly1305/poly1305_ppc.c
/* * Copyright 2009-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/opensslconf.h> #include <openssl/types.h> #include "crypto/poly1305.h" #include "crypto/ppc_arch.h" void poly1305_init_int(void *ctx, const unsigned char key[16]); void poly1305_blocks(void *ctx, const unsigned char *inp, size_t len, unsigned int padbit); void poly1305_emit(void *ctx, unsigned char mac[16], const unsigned int nonce[4]); void poly1305_init_fpu(void *ctx, const unsigned char key[16]); void poly1305_blocks_fpu(void *ctx, const unsigned char *inp, size_t len, unsigned int padbit); void poly1305_emit_fpu(void *ctx, unsigned char mac[16], const unsigned int nonce[4]); void poly1305_init_vsx(void *ctx, const unsigned char key[16]); void poly1305_blocks_vsx(void *ctx, const unsigned char *inp, size_t len, unsigned int padbit); void poly1305_emit_vsx(void *ctx, unsigned char mac[16], const unsigned int nonce[4]); int poly1305_init(void *ctx, const unsigned char key[16], void *func[2]); int poly1305_init(void *ctx, const unsigned char key[16], void *func[2]) { if (OPENSSL_ppccap_P & PPC_CRYPTO207) { poly1305_init_int(ctx, key); func[0] = (void*)(uintptr_t)poly1305_blocks_vsx; func[1] = (void*)(uintptr_t)poly1305_emit; } else if (sizeof(size_t) == 4 && (OPENSSL_ppccap_P & PPC_FPU)) { poly1305_init_fpu(ctx, key); func[0] = (void*)(uintptr_t)poly1305_blocks_fpu; func[1] = (void*)(uintptr_t)poly1305_emit_fpu; } else { poly1305_init_int(ctx, key); func[0] = (void*)(uintptr_t)poly1305_blocks; func[1] = (void*)(uintptr_t)poly1305_emit; } return 1; }
2,066
42.0625
74
c
openssl
openssl-master/crypto/property/defn_cache.c
/* * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2019, Oracle and/or its affiliates. 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/lhash.h> #include "internal/propertyerr.h" #include "internal/property.h" #include "internal/core.h" #include "property_local.h" #include "crypto/context.h" /* * Implement a property definition cache. * These functions assume that they are called under a write lock. * No attempt is made to clean out the cache, except when it is shut down. */ typedef struct { const char *prop; OSSL_PROPERTY_LIST *defn; char body[1]; } PROPERTY_DEFN_ELEM; DEFINE_LHASH_OF_EX(PROPERTY_DEFN_ELEM); static unsigned long property_defn_hash(const PROPERTY_DEFN_ELEM *a) { return OPENSSL_LH_strhash(a->prop); } static int property_defn_cmp(const PROPERTY_DEFN_ELEM *a, const PROPERTY_DEFN_ELEM *b) { return strcmp(a->prop, b->prop); } static void property_defn_free(PROPERTY_DEFN_ELEM *elem) { ossl_property_free(elem->defn); OPENSSL_free(elem); } void ossl_property_defns_free(void *vproperty_defns) { LHASH_OF(PROPERTY_DEFN_ELEM) *property_defns = vproperty_defns; if (property_defns != NULL) { lh_PROPERTY_DEFN_ELEM_doall(property_defns, &property_defn_free); lh_PROPERTY_DEFN_ELEM_free(property_defns); } } void *ossl_property_defns_new(OSSL_LIB_CTX *ctx) { return lh_PROPERTY_DEFN_ELEM_new(&property_defn_hash, &property_defn_cmp); } OSSL_PROPERTY_LIST *ossl_prop_defn_get(OSSL_LIB_CTX *ctx, const char *prop) { PROPERTY_DEFN_ELEM elem, *r; LHASH_OF(PROPERTY_DEFN_ELEM) *property_defns; property_defns = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_PROPERTY_DEFN_INDEX); if (!ossl_assert(property_defns != NULL) || !ossl_lib_ctx_read_lock(ctx)) return NULL; elem.prop = prop; r = lh_PROPERTY_DEFN_ELEM_retrieve(property_defns, &elem); ossl_lib_ctx_unlock(ctx); if (r == NULL || !ossl_assert(r->defn != NULL)) return NULL; return r->defn; } /* * Cache the property list for a given property string *pl. * If an entry already exists in the cache *pl is freed and * overwritten with the existing entry from the cache. */ int ossl_prop_defn_set(OSSL_LIB_CTX *ctx, const char *prop, OSSL_PROPERTY_LIST **pl) { PROPERTY_DEFN_ELEM elem, *old, *p = NULL; size_t len; LHASH_OF(PROPERTY_DEFN_ELEM) *property_defns; int res = 1; property_defns = ossl_lib_ctx_get_data(ctx, OSSL_LIB_CTX_PROPERTY_DEFN_INDEX); if (property_defns == NULL) return 0; if (prop == NULL) return 1; if (!ossl_lib_ctx_write_lock(ctx)) return 0; elem.prop = prop; if (pl == NULL) { lh_PROPERTY_DEFN_ELEM_delete(property_defns, &elem); goto end; } /* check if property definition is in the cache already */ if ((p = lh_PROPERTY_DEFN_ELEM_retrieve(property_defns, &elem)) != NULL) { ossl_property_free(*pl); *pl = p->defn; goto end; } len = strlen(prop); p = OPENSSL_malloc(sizeof(*p) + len); if (p != NULL) { p->prop = p->body; p->defn = *pl; memcpy(p->body, prop, len + 1); old = lh_PROPERTY_DEFN_ELEM_insert(property_defns, p); if (!ossl_assert(old == NULL)) /* This should not happen. An existing entry is handled above. */ goto end; if (!lh_PROPERTY_DEFN_ELEM_error(property_defns)) goto end; } OPENSSL_free(p); res = 0; end: ossl_lib_ctx_unlock(ctx); return res; }
4,032
28.437956
78
c
openssl
openssl-master/crypto/property/property.c
/* * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2019, Oracle and/or its affiliates. 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 <stdio.h> #include <stdarg.h> #include <openssl/crypto.h> #include "internal/core.h" #include "internal/property.h" #include "internal/provider.h" #include "internal/tsan_assist.h" #include "crypto/ctype.h" #include <openssl/lhash.h> #include <openssl/rand.h> #include "internal/thread_once.h" #include "crypto/lhash.h" #include "crypto/sparse_array.h" #include "property_local.h" #include "crypto/context.h" /* * The number of elements in the query cache before we initiate a flush. * If reducing this, also ensure the stochastic test in test/property_test.c * isn't likely to fail. */ #define IMPL_CACHE_FLUSH_THRESHOLD 500 typedef struct { void *method; int (*up_ref)(void *); void (*free)(void *); } METHOD; typedef struct { const OSSL_PROVIDER *provider; OSSL_PROPERTY_LIST *properties; METHOD method; } IMPLEMENTATION; DEFINE_STACK_OF(IMPLEMENTATION) typedef struct { const OSSL_PROVIDER *provider; const char *query; METHOD method; char body[1]; } QUERY; DEFINE_LHASH_OF_EX(QUERY); typedef struct { int nid; STACK_OF(IMPLEMENTATION) *impls; LHASH_OF(QUERY) *cache; } ALGORITHM; struct ossl_method_store_st { OSSL_LIB_CTX *ctx; SPARSE_ARRAY_OF(ALGORITHM) *algs; /* * Lock to protect the |algs| array from concurrent writing, when * individual implementations or queries are inserted. This is used * by the appropriate functions here. */ CRYPTO_RWLOCK *lock; /* * Lock to reserve the whole store. This is used when fetching a set * of algorithms, via these functions, found in crypto/core_fetch.c: * ossl_method_construct_reserve_store() * ossl_method_construct_unreserve_store() */ CRYPTO_RWLOCK *biglock; /* query cache specific values */ /* Count of the query cache entries for all algs */ size_t cache_nelem; /* Flag: 1 if query cache entries for all algs need flushing */ int cache_need_flush; }; typedef struct { LHASH_OF(QUERY) *cache; size_t nelem; uint32_t seed; unsigned char using_global_seed; } IMPL_CACHE_FLUSH; DEFINE_SPARSE_ARRAY_OF(ALGORITHM); typedef struct ossl_global_properties_st { OSSL_PROPERTY_LIST *list; #ifndef FIPS_MODULE unsigned int no_mirrored : 1; #endif } OSSL_GLOBAL_PROPERTIES; static void ossl_method_cache_flush_alg(OSSL_METHOD_STORE *store, ALGORITHM *alg); static void ossl_method_cache_flush(OSSL_METHOD_STORE *store, int nid); /* Global properties are stored per library context */ void ossl_ctx_global_properties_free(void *vglobp) { OSSL_GLOBAL_PROPERTIES *globp = vglobp; if (globp != NULL) { ossl_property_free(globp->list); OPENSSL_free(globp); } } void *ossl_ctx_global_properties_new(OSSL_LIB_CTX *ctx) { return OPENSSL_zalloc(sizeof(OSSL_GLOBAL_PROPERTIES)); } OSSL_PROPERTY_LIST **ossl_ctx_global_properties(OSSL_LIB_CTX *libctx, int loadconfig) { OSSL_GLOBAL_PROPERTIES *globp; #ifndef FIPS_MODULE if (loadconfig && !OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL)) return NULL; #endif globp = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES); return globp != NULL ? &globp->list : NULL; } #ifndef FIPS_MODULE int ossl_global_properties_no_mirrored(OSSL_LIB_CTX *libctx) { OSSL_GLOBAL_PROPERTIES *globp = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES); return globp != NULL && globp->no_mirrored ? 1 : 0; } void ossl_global_properties_stop_mirroring(OSSL_LIB_CTX *libctx) { OSSL_GLOBAL_PROPERTIES *globp = ossl_lib_ctx_get_data(libctx, OSSL_LIB_CTX_GLOBAL_PROPERTIES); if (globp != NULL) globp->no_mirrored = 1; } #endif static int ossl_method_up_ref(METHOD *method) { return (*method->up_ref)(method->method); } static void ossl_method_free(METHOD *method) { (*method->free)(method->method); } static __owur int ossl_property_read_lock(OSSL_METHOD_STORE *p) { return p != NULL ? CRYPTO_THREAD_read_lock(p->lock) : 0; } static __owur int ossl_property_write_lock(OSSL_METHOD_STORE *p) { return p != NULL ? CRYPTO_THREAD_write_lock(p->lock) : 0; } static int ossl_property_unlock(OSSL_METHOD_STORE *p) { return p != 0 ? CRYPTO_THREAD_unlock(p->lock) : 0; } static unsigned long query_hash(const QUERY *a) { return OPENSSL_LH_strhash(a->query); } static int query_cmp(const QUERY *a, const QUERY *b) { int res = strcmp(a->query, b->query); if (res == 0 && a->provider != NULL && b->provider != NULL) res = b->provider > a->provider ? 1 : b->provider < a->provider ? -1 : 0; return res; } static void impl_free(IMPLEMENTATION *impl) { if (impl != NULL) { ossl_method_free(&impl->method); OPENSSL_free(impl); } } static void impl_cache_free(QUERY *elem) { if (elem != NULL) { ossl_method_free(&elem->method); OPENSSL_free(elem); } } static void impl_cache_flush_alg(ossl_uintmax_t idx, ALGORITHM *alg) { lh_QUERY_doall(alg->cache, &impl_cache_free); lh_QUERY_flush(alg->cache); } static void alg_cleanup(ossl_uintmax_t idx, ALGORITHM *a, void *arg) { OSSL_METHOD_STORE *store = arg; if (a != NULL) { sk_IMPLEMENTATION_pop_free(a->impls, &impl_free); lh_QUERY_doall(a->cache, &impl_cache_free); lh_QUERY_free(a->cache); OPENSSL_free(a); } if (store != NULL) ossl_sa_ALGORITHM_set(store->algs, idx, NULL); } /* * The OSSL_LIB_CTX param here allows access to underlying property data needed * for computation */ OSSL_METHOD_STORE *ossl_method_store_new(OSSL_LIB_CTX *ctx) { OSSL_METHOD_STORE *res; res = OPENSSL_zalloc(sizeof(*res)); if (res != NULL) { res->ctx = ctx; if ((res->algs = ossl_sa_ALGORITHM_new()) == NULL || (res->lock = CRYPTO_THREAD_lock_new()) == NULL || (res->biglock = CRYPTO_THREAD_lock_new()) == NULL) { ossl_method_store_free(res); return NULL; } } return res; } void ossl_method_store_free(OSSL_METHOD_STORE *store) { if (store != NULL) { if (store->algs != NULL) ossl_sa_ALGORITHM_doall_arg(store->algs, &alg_cleanup, store); ossl_sa_ALGORITHM_free(store->algs); CRYPTO_THREAD_lock_free(store->lock); CRYPTO_THREAD_lock_free(store->biglock); OPENSSL_free(store); } } int ossl_method_lock_store(OSSL_METHOD_STORE *store) { return store != NULL ? CRYPTO_THREAD_write_lock(store->biglock) : 0; } int ossl_method_unlock_store(OSSL_METHOD_STORE *store) { return store != NULL ? CRYPTO_THREAD_unlock(store->biglock) : 0; } static ALGORITHM *ossl_method_store_retrieve(OSSL_METHOD_STORE *store, int nid) { return ossl_sa_ALGORITHM_get(store->algs, nid); } static int ossl_method_store_insert(OSSL_METHOD_STORE *store, ALGORITHM *alg) { return ossl_sa_ALGORITHM_set(store->algs, alg->nid, alg); } int ossl_method_store_add(OSSL_METHOD_STORE *store, const OSSL_PROVIDER *prov, int nid, const char *properties, void *method, int (*method_up_ref)(void *), void (*method_destruct)(void *)) { ALGORITHM *alg = NULL; IMPLEMENTATION *impl; int ret = 0; int i; if (nid <= 0 || method == NULL || store == NULL) return 0; if (properties == NULL) properties = ""; if (!ossl_assert(prov != NULL)) return 0; /* Create new entry */ impl = OPENSSL_malloc(sizeof(*impl)); if (impl == NULL) return 0; impl->method.method = method; impl->method.up_ref = method_up_ref; impl->method.free = method_destruct; if (!ossl_method_up_ref(&impl->method)) { OPENSSL_free(impl); return 0; } impl->provider = prov; /* Insert into the hash table if required */ if (!ossl_property_write_lock(store)) { OPENSSL_free(impl); return 0; } ossl_method_cache_flush(store, nid); if ((impl->properties = ossl_prop_defn_get(store->ctx, properties)) == NULL) { impl->properties = ossl_parse_property(store->ctx, properties); if (impl->properties == NULL) goto err; if (!ossl_prop_defn_set(store->ctx, properties, &impl->properties)) { ossl_property_free(impl->properties); impl->properties = NULL; goto err; } } alg = ossl_method_store_retrieve(store, nid); if (alg == NULL) { if ((alg = OPENSSL_zalloc(sizeof(*alg))) == NULL || (alg->impls = sk_IMPLEMENTATION_new_null()) == NULL || (alg->cache = lh_QUERY_new(&query_hash, &query_cmp)) == NULL) goto err; alg->nid = nid; if (!ossl_method_store_insert(store, alg)) goto err; } /* Push onto stack if there isn't one there already */ for (i = 0; i < sk_IMPLEMENTATION_num(alg->impls); i++) { const IMPLEMENTATION *tmpimpl = sk_IMPLEMENTATION_value(alg->impls, i); if (tmpimpl->provider == impl->provider && tmpimpl->properties == impl->properties) break; } if (i == sk_IMPLEMENTATION_num(alg->impls) && sk_IMPLEMENTATION_push(alg->impls, impl)) ret = 1; ossl_property_unlock(store); if (ret == 0) impl_free(impl); return ret; err: ossl_property_unlock(store); alg_cleanup(0, alg, NULL); impl_free(impl); return 0; } int ossl_method_store_remove(OSSL_METHOD_STORE *store, int nid, const void *method) { ALGORITHM *alg = NULL; int i; if (nid <= 0 || method == NULL || store == NULL) return 0; if (!ossl_property_write_lock(store)) return 0; ossl_method_cache_flush(store, nid); alg = ossl_method_store_retrieve(store, nid); if (alg == NULL) { ossl_property_unlock(store); return 0; } /* * A sorting find then a delete could be faster but these stacks should be * relatively small, so we avoid the overhead. Sorting could also surprise * users when result orderings change (even though they are not guaranteed). */ for (i = 0; i < sk_IMPLEMENTATION_num(alg->impls); i++) { IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i); if (impl->method.method == method) { impl_free(impl); (void)sk_IMPLEMENTATION_delete(alg->impls, i); ossl_property_unlock(store); return 1; } } ossl_property_unlock(store); return 0; } struct alg_cleanup_by_provider_data_st { OSSL_METHOD_STORE *store; const OSSL_PROVIDER *prov; }; static void alg_cleanup_by_provider(ossl_uintmax_t idx, ALGORITHM *alg, void *arg) { struct alg_cleanup_by_provider_data_st *data = arg; int i, count; /* * We walk the stack backwards, to avoid having to deal with stack shifts * caused by deletion */ for (count = 0, i = sk_IMPLEMENTATION_num(alg->impls); i-- > 0;) { IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i); if (impl->provider == data->prov) { impl_free(impl); (void)sk_IMPLEMENTATION_delete(alg->impls, i); count++; } } /* * If we removed any implementation, we also clear the whole associated * cache, 'cause that's the sensible thing to do. * There's no point flushing the cache entries where we didn't remove * any implementation, though. */ if (count > 0) ossl_method_cache_flush_alg(data->store, alg); } int ossl_method_store_remove_all_provided(OSSL_METHOD_STORE *store, const OSSL_PROVIDER *prov) { struct alg_cleanup_by_provider_data_st data; if (!ossl_property_write_lock(store)) return 0; data.prov = prov; data.store = store; ossl_sa_ALGORITHM_doall_arg(store->algs, &alg_cleanup_by_provider, &data); ossl_property_unlock(store); return 1; } static void alg_do_one(ALGORITHM *alg, IMPLEMENTATION *impl, void (*fn)(int id, void *method, void *fnarg), void *fnarg) { fn(alg->nid, impl->method.method, fnarg); } struct alg_do_each_data_st { void (*fn)(int id, void *method, void *fnarg); void *fnarg; }; static void alg_do_each(ossl_uintmax_t idx, ALGORITHM *alg, void *arg) { struct alg_do_each_data_st *data = arg; int i, end = sk_IMPLEMENTATION_num(alg->impls); for (i = 0; i < end; i++) { IMPLEMENTATION *impl = sk_IMPLEMENTATION_value(alg->impls, i); alg_do_one(alg, impl, data->fn, data->fnarg); } } void ossl_method_store_do_all(OSSL_METHOD_STORE *store, void (*fn)(int id, void *method, void *fnarg), void *fnarg) { struct alg_do_each_data_st data; data.fn = fn; data.fnarg = fnarg; if (store != NULL) ossl_sa_ALGORITHM_doall_arg(store->algs, alg_do_each, &data); } int ossl_method_store_fetch(OSSL_METHOD_STORE *store, int nid, const char *prop_query, const OSSL_PROVIDER **prov_rw, void **method) { OSSL_PROPERTY_LIST **plp; ALGORITHM *alg; IMPLEMENTATION *impl, *best_impl = NULL; OSSL_PROPERTY_LIST *pq = NULL, *p2 = NULL; const OSSL_PROVIDER *prov = prov_rw != NULL ? *prov_rw : NULL; int ret = 0; int j, best = -1, score, optional; if (nid <= 0 || method == NULL || store == NULL) return 0; #ifndef FIPS_MODULE if (ossl_lib_ctx_is_default(store->ctx) && !OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, NULL)) return 0; #endif /* This only needs to be a read lock, because the query won't create anything */ if (!ossl_property_read_lock(store)) return 0; alg = ossl_method_store_retrieve(store, nid); if (alg == NULL) { ossl_property_unlock(store); return 0; } if (prop_query != NULL) p2 = pq = ossl_parse_query(store->ctx, prop_query, 0); plp = ossl_ctx_global_properties(store->ctx, 0); if (plp != NULL && *plp != NULL) { if (pq == NULL) { pq = *plp; } else { p2 = ossl_property_merge(pq, *plp); ossl_property_free(pq); if (p2 == NULL) goto fin; pq = p2; } } if (pq == NULL) { for (j = 0; j < sk_IMPLEMENTATION_num(alg->impls); j++) { if ((impl = sk_IMPLEMENTATION_value(alg->impls, j)) != NULL && (prov == NULL || impl->provider == prov)) { best_impl = impl; ret = 1; break; } } goto fin; } optional = ossl_property_has_optional(pq); for (j = 0; j < sk_IMPLEMENTATION_num(alg->impls); j++) { if ((impl = sk_IMPLEMENTATION_value(alg->impls, j)) != NULL && (prov == NULL || impl->provider == prov)) { score = ossl_property_match_count(pq, impl->properties); if (score > best) { best_impl = impl; best = score; ret = 1; if (!optional) goto fin; } } } fin: if (ret && ossl_method_up_ref(&best_impl->method)) { *method = best_impl->method.method; if (prov_rw != NULL) *prov_rw = best_impl->provider; } else { ret = 0; } ossl_property_unlock(store); ossl_property_free(p2); return ret; } static void ossl_method_cache_flush_alg(OSSL_METHOD_STORE *store, ALGORITHM *alg) { store->cache_nelem -= lh_QUERY_num_items(alg->cache); impl_cache_flush_alg(0, alg); } static void ossl_method_cache_flush(OSSL_METHOD_STORE *store, int nid) { ALGORITHM *alg = ossl_method_store_retrieve(store, nid); if (alg != NULL) ossl_method_cache_flush_alg(store, alg); } int ossl_method_store_cache_flush_all(OSSL_METHOD_STORE *store) { if (!ossl_property_write_lock(store)) return 0; ossl_sa_ALGORITHM_doall(store->algs, &impl_cache_flush_alg); store->cache_nelem = 0; ossl_property_unlock(store); return 1; } IMPLEMENT_LHASH_DOALL_ARG(QUERY, IMPL_CACHE_FLUSH); /* * Flush an element from the query cache (perhaps). * * In order to avoid taking a write lock or using atomic operations * to keep accurate least recently used (LRU) or least frequently used * (LFU) information, the procedure used here is to stochastically * flush approximately half the cache. * * This procedure isn't ideal, LRU or LFU would be better. However, * in normal operation, reaching a full cache would be unexpected. * It means that no steady state of algorithm queries has been reached. * That is, it is most likely an attack of some form. A suboptimal clearance * strategy that doesn't degrade performance of the normal case is * preferable to a more refined approach that imposes a performance * impact. */ static void impl_cache_flush_cache(QUERY *c, IMPL_CACHE_FLUSH *state) { uint32_t n; /* * Implement the 32 bit xorshift as suggested by George Marsaglia in: * https://doi.org/10.18637/jss.v008.i14 * * This is a very fast PRNG so there is no need to extract bits one at a * time and use the entire value each time. */ n = state->seed; n ^= n << 13; n ^= n >> 17; n ^= n << 5; state->seed = n; if ((n & 1) != 0) impl_cache_free(lh_QUERY_delete(state->cache, c)); else state->nelem++; } static void impl_cache_flush_one_alg(ossl_uintmax_t idx, ALGORITHM *alg, void *v) { IMPL_CACHE_FLUSH *state = (IMPL_CACHE_FLUSH *)v; state->cache = alg->cache; lh_QUERY_doall_IMPL_CACHE_FLUSH(state->cache, &impl_cache_flush_cache, state); } static void ossl_method_cache_flush_some(OSSL_METHOD_STORE *store) { IMPL_CACHE_FLUSH state; static TSAN_QUALIFIER uint32_t global_seed = 1; state.nelem = 0; state.using_global_seed = 0; if ((state.seed = OPENSSL_rdtsc()) == 0) { /* If there is no timer available, seed another way */ state.using_global_seed = 1; state.seed = tsan_load(&global_seed); } store->cache_need_flush = 0; ossl_sa_ALGORITHM_doall_arg(store->algs, &impl_cache_flush_one_alg, &state); store->cache_nelem = state.nelem; /* Without a timer, update the global seed */ if (state.using_global_seed) tsan_add(&global_seed, state.seed); } int ossl_method_store_cache_get(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov, int nid, const char *prop_query, void **method) { ALGORITHM *alg; QUERY elem, *r; int res = 0; if (nid <= 0 || store == NULL || prop_query == NULL) return 0; if (!ossl_property_read_lock(store)) return 0; alg = ossl_method_store_retrieve(store, nid); if (alg == NULL) goto err; elem.query = prop_query; elem.provider = prov; r = lh_QUERY_retrieve(alg->cache, &elem); if (r == NULL) goto err; if (ossl_method_up_ref(&r->method)) { *method = r->method.method; res = 1; } err: ossl_property_unlock(store); return res; } int ossl_method_store_cache_set(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov, int nid, const char *prop_query, void *method, int (*method_up_ref)(void *), void (*method_destruct)(void *)) { QUERY elem, *old, *p = NULL; ALGORITHM *alg; size_t len; int res = 1; if (nid <= 0 || store == NULL || prop_query == NULL) return 0; if (!ossl_assert(prov != NULL)) return 0; if (!ossl_property_write_lock(store)) return 0; if (store->cache_need_flush) ossl_method_cache_flush_some(store); alg = ossl_method_store_retrieve(store, nid); if (alg == NULL) goto err; if (method == NULL) { elem.query = prop_query; elem.provider = prov; if ((old = lh_QUERY_delete(alg->cache, &elem)) != NULL) { impl_cache_free(old); store->cache_nelem--; } goto end; } p = OPENSSL_malloc(sizeof(*p) + (len = strlen(prop_query))); if (p != NULL) { p->query = p->body; p->provider = prov; p->method.method = method; p->method.up_ref = method_up_ref; p->method.free = method_destruct; if (!ossl_method_up_ref(&p->method)) goto err; memcpy((char *)p->query, prop_query, len + 1); if ((old = lh_QUERY_insert(alg->cache, p)) != NULL) { impl_cache_free(old); goto end; } if (!lh_QUERY_error(alg->cache)) { if (++store->cache_nelem >= IMPL_CACHE_FLUSH_THRESHOLD) store->cache_need_flush = 1; goto end; } ossl_method_free(&p->method); } err: res = 0; OPENSSL_free(p); end: ossl_property_unlock(store); return res; }
21,808
27.583224
84
c
openssl
openssl-master/crypto/property/property_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 "internal/propertyerr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA PROP_str_reasons[] = { {ERR_PACK(ERR_LIB_PROP, 0, PROP_R_NAME_TOO_LONG), "name too long"}, {ERR_PACK(ERR_LIB_PROP, 0, PROP_R_NOT_AN_ASCII_CHARACTER), "not an ascii character"}, {ERR_PACK(ERR_LIB_PROP, 0, PROP_R_NOT_AN_HEXADECIMAL_DIGIT), "not an hexadecimal digit"}, {ERR_PACK(ERR_LIB_PROP, 0, PROP_R_NOT_AN_IDENTIFIER), "not an identifier"}, {ERR_PACK(ERR_LIB_PROP, 0, PROP_R_NOT_AN_OCTAL_DIGIT), "not an octal digit"}, {ERR_PACK(ERR_LIB_PROP, 0, PROP_R_NOT_A_DECIMAL_DIGIT), "not a decimal digit"}, {ERR_PACK(ERR_LIB_PROP, 0, PROP_R_NO_MATCHING_STRING_DELIMITER), "no matching string delimiter"}, {ERR_PACK(ERR_LIB_PROP, 0, PROP_R_NO_VALUE), "no value"}, {ERR_PACK(ERR_LIB_PROP, 0, PROP_R_PARSE_FAILED), "parse failed"}, {ERR_PACK(ERR_LIB_PROP, 0, PROP_R_STRING_TOO_LONG), "string too long"}, {ERR_PACK(ERR_LIB_PROP, 0, PROP_R_TRAILING_CHARACTERS), "trailing characters"}, {0, NULL} }; #endif int ossl_err_load_PROP_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(PROP_str_reasons[0].error) == NULL) ERR_load_strings_const(PROP_str_reasons); #endif return 1; }
1,664
34.425532
79
c
openssl
openssl-master/crypto/property/property_local.h
/* * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2019, Oracle and/or its affiliates. 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/crypto.h> #include "internal/property.h" typedef int OSSL_PROPERTY_IDX; typedef enum { OSSL_PROPERTY_OPER_EQ, OSSL_PROPERTY_OPER_NE, OSSL_PROPERTY_OVERRIDE } OSSL_PROPERTY_OPER; struct ossl_property_definition_st { OSSL_PROPERTY_IDX name_idx; OSSL_PROPERTY_TYPE type; OSSL_PROPERTY_OPER oper; unsigned int optional : 1; union { int64_t int_val; /* Signed integer */ OSSL_PROPERTY_IDX str_val; /* String */ } v; }; struct ossl_property_list_st { int num_properties; unsigned int has_optional : 1; OSSL_PROPERTY_DEFINITION properties[1]; }; #define OSSL_PROPERTY_TRUE 1 #define OSSL_PROPERTY_FALSE 2 /* Property string functions */ OSSL_PROPERTY_IDX ossl_property_name(OSSL_LIB_CTX *ctx, const char *s, int create); const char *ossl_property_name_str(OSSL_LIB_CTX *ctx, OSSL_PROPERTY_IDX idx); OSSL_PROPERTY_IDX ossl_property_value(OSSL_LIB_CTX *ctx, const char *s, int create); const char *ossl_property_value_str(OSSL_LIB_CTX *ctx, OSSL_PROPERTY_IDX idx); /* Property list functions */ void ossl_property_free(OSSL_PROPERTY_LIST *p); int ossl_property_has_optional(const OSSL_PROPERTY_LIST *query); /* Property definition cache functions */ OSSL_PROPERTY_LIST *ossl_prop_defn_get(OSSL_LIB_CTX *ctx, const char *prop); int ossl_prop_defn_set(OSSL_LIB_CTX *ctx, const char *prop, OSSL_PROPERTY_LIST **pl);
1,927
33.428571
78
h
openssl
openssl-master/crypto/property/property_parse.c
/* * Copyright 2019-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2019, Oracle and/or its affiliates. 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 <stdio.h> #include <stdarg.h> #include <openssl/err.h> #include "internal/propertyerr.h" #include "internal/property.h" #include "crypto/ctype.h" #include "internal/nelem.h" #include "property_local.h" #include "internal/e_os.h" DEFINE_STACK_OF(OSSL_PROPERTY_DEFINITION) static const char *skip_space(const char *s) { while (ossl_isspace(*s)) s++; return s; } static int match_ch(const char *t[], char m) { const char *s = *t; if (*s == m) { *t = skip_space(s + 1); return 1; } return 0; } #define MATCH(s, m) match(s, m, sizeof(m) - 1) static int match(const char *t[], const char m[], size_t m_len) { const char *s = *t; if (OPENSSL_strncasecmp(s, m, m_len) == 0) { *t = skip_space(s + m_len); return 1; } return 0; } static int parse_name(OSSL_LIB_CTX *ctx, const char *t[], int create, OSSL_PROPERTY_IDX *idx) { char name[100]; int err = 0; size_t i = 0; const char *s = *t; int user_name = 0; for (;;) { if (!ossl_isalpha(*s)) { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_AN_IDENTIFIER, "HERE-->%s", *t); return 0; } do { if (i < sizeof(name) - 1) name[i++] = ossl_tolower(*s); else err = 1; } while (*++s == '_' || ossl_isalnum(*s)); if (*s != '.') break; user_name = 1; if (i < sizeof(name) - 1) name[i++] = *s; else err = 1; s++; } name[i] = '\0'; if (err) { ERR_raise_data(ERR_LIB_PROP, PROP_R_NAME_TOO_LONG, "HERE-->%s", *t); return 0; } *t = skip_space(s); *idx = ossl_property_name(ctx, name, user_name && create); return 1; } static int parse_number(const char *t[], OSSL_PROPERTY_DEFINITION *res) { const char *s = *t; int64_t v = 0; if (!ossl_isdigit(*s)) return 0; do { v = v * 10 + (*s++ - '0'); } while (ossl_isdigit(*s)); if (!ossl_isspace(*s) && *s != '\0' && *s != ',') { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_A_DECIMAL_DIGIT, "HERE-->%s", *t); return 0; } *t = skip_space(s); res->type = OSSL_PROPERTY_TYPE_NUMBER; res->v.int_val = v; return 1; } static int parse_hex(const char *t[], OSSL_PROPERTY_DEFINITION *res) { const char *s = *t; int64_t v = 0; if (!ossl_isxdigit(*s)) return 0; do { v <<= 4; if (ossl_isdigit(*s)) v += *s - '0'; else v += ossl_tolower(*s) - 'a'; } while (ossl_isxdigit(*++s)); if (!ossl_isspace(*s) && *s != '\0' && *s != ',') { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_AN_HEXADECIMAL_DIGIT, "HERE-->%s", *t); return 0; } *t = skip_space(s); res->type = OSSL_PROPERTY_TYPE_NUMBER; res->v.int_val = v; return 1; } static int parse_oct(const char *t[], OSSL_PROPERTY_DEFINITION *res) { const char *s = *t; int64_t v = 0; if (*s == '9' || *s == '8' || !ossl_isdigit(*s)) return 0; do { v = (v << 3) + (*s - '0'); } while (ossl_isdigit(*++s) && *s != '9' && *s != '8'); if (!ossl_isspace(*s) && *s != '\0' && *s != ',') { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_AN_OCTAL_DIGIT, "HERE-->%s", *t); return 0; } *t = skip_space(s); res->type = OSSL_PROPERTY_TYPE_NUMBER; res->v.int_val = v; return 1; } static int parse_string(OSSL_LIB_CTX *ctx, const char *t[], char delim, OSSL_PROPERTY_DEFINITION *res, const int create) { char v[1000]; const char *s = *t; size_t i = 0; int err = 0; while (*s != '\0' && *s != delim) { if (i < sizeof(v) - 1) v[i++] = *s; else err = 1; s++; } if (*s == '\0') { ERR_raise_data(ERR_LIB_PROP, PROP_R_NO_MATCHING_STRING_DELIMITER, "HERE-->%c%s", delim, *t); return 0; } v[i] = '\0'; if (err) { ERR_raise_data(ERR_LIB_PROP, PROP_R_STRING_TOO_LONG, "HERE-->%s", *t); } else { res->v.str_val = ossl_property_value(ctx, v, create); } *t = skip_space(s + 1); res->type = OSSL_PROPERTY_TYPE_STRING; return !err; } static int parse_unquoted(OSSL_LIB_CTX *ctx, const char *t[], OSSL_PROPERTY_DEFINITION *res, const int create) { char v[1000]; const char *s = *t; size_t i = 0; int err = 0; if (*s == '\0' || *s == ',') return 0; while (ossl_isprint(*s) && !ossl_isspace(*s) && *s != ',') { if (i < sizeof(v) - 1) v[i++] = ossl_tolower(*s); else err = 1; s++; } if (!ossl_isspace(*s) && *s != '\0' && *s != ',') { ERR_raise_data(ERR_LIB_PROP, PROP_R_NOT_AN_ASCII_CHARACTER, "HERE-->%s", s); return 0; } v[i] = 0; if (err) ERR_raise_data(ERR_LIB_PROP, PROP_R_STRING_TOO_LONG, "HERE-->%s", *t); else if ((res->v.str_val = ossl_property_value(ctx, v, create)) == 0) err = 1; *t = skip_space(s); res->type = OSSL_PROPERTY_TYPE_STRING; return !err; } static int parse_value(OSSL_LIB_CTX *ctx, const char *t[], OSSL_PROPERTY_DEFINITION *res, int create) { const char *s = *t; int r = 0; if (*s == '"' || *s == '\'') { s++; r = parse_string(ctx, &s, s[-1], res, create); } else if (*s == '+') { s++; r = parse_number(&s, res); } else if (*s == '-') { s++; r = parse_number(&s, res); res->v.int_val = -res->v.int_val; } else if (*s == '0' && s[1] == 'x') { s += 2; r = parse_hex(&s, res); } else if (*s == '0' && ossl_isdigit(s[1])) { s++; r = parse_oct(&s, res); } else if (ossl_isdigit(*s)) { return parse_number(t, res); } else if (ossl_isalpha(*s)) return parse_unquoted(ctx, t, res, create); if (r) *t = s; return r; } static int pd_compare(const OSSL_PROPERTY_DEFINITION *const *p1, const OSSL_PROPERTY_DEFINITION *const *p2) { const OSSL_PROPERTY_DEFINITION *pd1 = *p1; const OSSL_PROPERTY_DEFINITION *pd2 = *p2; if (pd1->name_idx < pd2->name_idx) return -1; if (pd1->name_idx > pd2->name_idx) return 1; return 0; } static void pd_free(OSSL_PROPERTY_DEFINITION *pd) { OPENSSL_free(pd); } /* * Convert a stack of property definitions and queries into a fixed array. * The items are sorted for efficient query. The stack is not freed. * This function also checks for duplicated names and returns an error if * any exist. */ static OSSL_PROPERTY_LIST * stack_to_property_list(OSSL_LIB_CTX *ctx, STACK_OF(OSSL_PROPERTY_DEFINITION) *sk) { const int n = sk_OSSL_PROPERTY_DEFINITION_num(sk); OSSL_PROPERTY_LIST *r; OSSL_PROPERTY_IDX prev_name_idx = 0; int i; r = OPENSSL_malloc(sizeof(*r) + (n <= 0 ? 0 : n - 1) * sizeof(r->properties[0])); if (r != NULL) { sk_OSSL_PROPERTY_DEFINITION_sort(sk); r->has_optional = 0; for (i = 0; i < n; i++) { r->properties[i] = *sk_OSSL_PROPERTY_DEFINITION_value(sk, i); r->has_optional |= r->properties[i].optional; /* Check for duplicated names */ if (i > 0 && r->properties[i].name_idx == prev_name_idx) { OPENSSL_free(r); ERR_raise_data(ERR_LIB_PROP, PROP_R_PARSE_FAILED, "Duplicated name `%s'", ossl_property_name_str(ctx, prev_name_idx)); return NULL; } prev_name_idx = r->properties[i].name_idx; } r->num_properties = n; } return r; } OSSL_PROPERTY_LIST *ossl_parse_property(OSSL_LIB_CTX *ctx, const char *defn) { OSSL_PROPERTY_DEFINITION *prop = NULL; OSSL_PROPERTY_LIST *res = NULL; STACK_OF(OSSL_PROPERTY_DEFINITION) *sk; const char *s = defn; int done; if (s == NULL || (sk = sk_OSSL_PROPERTY_DEFINITION_new(&pd_compare)) == NULL) return NULL; s = skip_space(s); done = *s == '\0'; while (!done) { const char *start = s; prop = OPENSSL_malloc(sizeof(*prop)); if (prop == NULL) goto err; memset(&prop->v, 0, sizeof(prop->v)); prop->optional = 0; if (!parse_name(ctx, &s, 1, &prop->name_idx)) goto err; prop->oper = OSSL_PROPERTY_OPER_EQ; if (prop->name_idx == 0) { ERR_raise_data(ERR_LIB_PROP, PROP_R_PARSE_FAILED, "Unknown name HERE-->%s", start); goto err; } if (match_ch(&s, '=')) { if (!parse_value(ctx, &s, prop, 1)) { ERR_raise_data(ERR_LIB_PROP, PROP_R_NO_VALUE, "HERE-->%s", start); goto err; } } else { /* A name alone means a true Boolean */ prop->type = OSSL_PROPERTY_TYPE_STRING; prop->v.str_val = OSSL_PROPERTY_TRUE; } if (!sk_OSSL_PROPERTY_DEFINITION_push(sk, prop)) goto err; prop = NULL; done = !match_ch(&s, ','); } if (*s != '\0') { ERR_raise_data(ERR_LIB_PROP, PROP_R_TRAILING_CHARACTERS, "HERE-->%s", s); goto err; } res = stack_to_property_list(ctx, sk); err: OPENSSL_free(prop); sk_OSSL_PROPERTY_DEFINITION_pop_free(sk, &pd_free); return res; } OSSL_PROPERTY_LIST *ossl_parse_query(OSSL_LIB_CTX *ctx, const char *s, int create_values) { STACK_OF(OSSL_PROPERTY_DEFINITION) *sk; OSSL_PROPERTY_LIST *res = NULL; OSSL_PROPERTY_DEFINITION *prop = NULL; int done; if (s == NULL || (sk = sk_OSSL_PROPERTY_DEFINITION_new(&pd_compare)) == NULL) return NULL; s = skip_space(s); done = *s == '\0'; while (!done) { prop = OPENSSL_malloc(sizeof(*prop)); if (prop == NULL) goto err; memset(&prop->v, 0, sizeof(prop->v)); if (match_ch(&s, '-')) { prop->oper = OSSL_PROPERTY_OVERRIDE; prop->optional = 0; if (!parse_name(ctx, &s, 1, &prop->name_idx)) goto err; goto skip_value; } prop->optional = match_ch(&s, '?'); if (!parse_name(ctx, &s, 1, &prop->name_idx)) goto err; if (match_ch(&s, '=')) { prop->oper = OSSL_PROPERTY_OPER_EQ; } else if (MATCH(&s, "!=")) { prop->oper = OSSL_PROPERTY_OPER_NE; } else { /* A name alone is a Boolean comparison for true */ prop->oper = OSSL_PROPERTY_OPER_EQ; prop->type = OSSL_PROPERTY_TYPE_STRING; prop->v.str_val = OSSL_PROPERTY_TRUE; goto skip_value; } if (!parse_value(ctx, &s, prop, create_values)) prop->type = OSSL_PROPERTY_TYPE_VALUE_UNDEFINED; skip_value: if (!sk_OSSL_PROPERTY_DEFINITION_push(sk, prop)) goto err; prop = NULL; done = !match_ch(&s, ','); } if (*s != '\0') { ERR_raise_data(ERR_LIB_PROP, PROP_R_TRAILING_CHARACTERS, "HERE-->%s", s); goto err; } res = stack_to_property_list(ctx, sk); err: OPENSSL_free(prop); sk_OSSL_PROPERTY_DEFINITION_pop_free(sk, &pd_free); return res; } /* * Compare a query against a definition. * Return the number of clauses matched or -1 if a mandatory clause is false. */ int ossl_property_match_count(const OSSL_PROPERTY_LIST *query, const OSSL_PROPERTY_LIST *defn) { const OSSL_PROPERTY_DEFINITION *const q = query->properties; const OSSL_PROPERTY_DEFINITION *const d = defn->properties; int i = 0, j = 0, matches = 0; OSSL_PROPERTY_OPER oper; while (i < query->num_properties) { if ((oper = q[i].oper) == OSSL_PROPERTY_OVERRIDE) { i++; continue; } if (j < defn->num_properties) { if (q[i].name_idx > d[j].name_idx) { /* skip defn, not in query */ j++; continue; } if (q[i].name_idx == d[j].name_idx) { /* both in defn and query */ const int eq = q[i].type == d[j].type && memcmp(&q[i].v, &d[j].v, sizeof(q[i].v)) == 0; if ((eq && oper == OSSL_PROPERTY_OPER_EQ) || (!eq && oper == OSSL_PROPERTY_OPER_NE)) matches++; else if (!q[i].optional) return -1; i++; j++; continue; } } /* * Handle the cases of a missing value and a query with no corresponding * definition. The former fails for any comparison except inequality, * the latter is treated as a comparison against the Boolean false. */ if (q[i].type == OSSL_PROPERTY_TYPE_VALUE_UNDEFINED) { if (oper == OSSL_PROPERTY_OPER_NE) matches++; else if (!q[i].optional) return -1; } else if (q[i].type != OSSL_PROPERTY_TYPE_STRING || (oper == OSSL_PROPERTY_OPER_EQ && q[i].v.str_val != OSSL_PROPERTY_FALSE) || (oper == OSSL_PROPERTY_OPER_NE && q[i].v.str_val == OSSL_PROPERTY_FALSE)) { if (!q[i].optional) return -1; } else { matches++; } i++; } return matches; } void ossl_property_free(OSSL_PROPERTY_LIST *p) { OPENSSL_free(p); } /* * Merge two property lists. * If there is a common name, the one from the first list is used. */ OSSL_PROPERTY_LIST *ossl_property_merge(const OSSL_PROPERTY_LIST *a, const OSSL_PROPERTY_LIST *b) { const OSSL_PROPERTY_DEFINITION *const ap = a->properties; const OSSL_PROPERTY_DEFINITION *const bp = b->properties; const OSSL_PROPERTY_DEFINITION *copy; OSSL_PROPERTY_LIST *r; int i, j, n; const int t = a->num_properties + b->num_properties; r = OPENSSL_malloc(sizeof(*r) + (t == 0 ? 0 : t - 1) * sizeof(r->properties[0])); if (r == NULL) return NULL; r->has_optional = 0; for (i = j = n = 0; i < a->num_properties || j < b->num_properties; n++) { if (i >= a->num_properties) { copy = &bp[j++]; } else if (j >= b->num_properties) { copy = &ap[i++]; } else if (ap[i].name_idx <= bp[j].name_idx) { if (ap[i].name_idx == bp[j].name_idx) j++; copy = &ap[i++]; } else { copy = &bp[j++]; } memcpy(r->properties + n, copy, sizeof(r->properties[0])); r->has_optional |= copy->optional; } r->num_properties = n; if (n != t) r = OPENSSL_realloc(r, sizeof(*r) + (n - 1) * sizeof(r->properties[0])); return r; } int ossl_property_parse_init(OSSL_LIB_CTX *ctx) { static const char *const predefined_names[] = { "provider", /* Name of provider (default, legacy, fips) */ "version", /* Version number of this provider */ "fips", /* FIPS validated or FIPS supporting algorithm */ "output", /* Output type for encoders */ "input", /* Input type for decoders */ "structure", /* Structure name for encoders and decoders */ }; size_t i; for (i = 0; i < OSSL_NELEM(predefined_names); i++) if (ossl_property_name(ctx, predefined_names[i], 1) == 0) goto err; /* * Pre-populate the two Boolean values. We must do them before any other * values and in this order so that we get the same index as the global * OSSL_PROPERTY_TRUE and OSSL_PROPERTY_FALSE values */ if ((ossl_property_value(ctx, "yes", 1) != OSSL_PROPERTY_TRUE) || (ossl_property_value(ctx, "no", 1) != OSSL_PROPERTY_FALSE)) goto err; return 1; err: return 0; } static void put_char(char ch, char **buf, size_t *remain, size_t *needed) { if (*remain == 0) { ++*needed; return; } if (*remain == 1) **buf = '\0'; else **buf = ch; ++*buf; ++*needed; --*remain; } static void put_str(const char *str, char **buf, size_t *remain, size_t *needed) { size_t olen, len; len = olen = strlen(str); *needed += len; if (*remain == 0) return; if (*remain < len + 1) len = *remain - 1; if (len > 0) { memcpy(*buf, str, len); *buf += len; *remain -= len; } if (len < olen && *remain == 1) { **buf = '\0'; ++*buf; --*remain; } } static void put_num(int64_t val, char **buf, size_t *remain, size_t *needed) { int64_t tmpval = val; size_t len = 1; if (tmpval < 0) { len++; tmpval = -tmpval; } for (; tmpval > 9; len++, tmpval /= 10); *needed += len; if (*remain == 0) return; BIO_snprintf(*buf, *remain, "%lld", (long long int)val); if (*remain < len) { *buf += *remain; *remain = 0; } else { *buf += len; *remain -= len; } } size_t ossl_property_list_to_string(OSSL_LIB_CTX *ctx, const OSSL_PROPERTY_LIST *list, char *buf, size_t bufsize) { int i; const OSSL_PROPERTY_DEFINITION *prop = NULL; size_t needed = 0; const char *val; if (list == NULL) { if (bufsize > 0) *buf = '\0'; return 1; } if (list->num_properties != 0) prop = &list->properties[list->num_properties - 1]; for (i = 0; i < list->num_properties; i++, prop--) { /* Skip invalid names */ if (prop->name_idx == 0) continue; if (needed > 0) put_char(',', &buf, &bufsize, &needed); if (prop->optional) put_char('?', &buf, &bufsize, &needed); else if (prop->oper == OSSL_PROPERTY_OVERRIDE) put_char('-', &buf, &bufsize, &needed); val = ossl_property_name_str(ctx, prop->name_idx); if (val == NULL) return 0; put_str(val, &buf, &bufsize, &needed); switch (prop->oper) { case OSSL_PROPERTY_OPER_NE: put_char('!', &buf, &bufsize, &needed); /* fall through */ case OSSL_PROPERTY_OPER_EQ: put_char('=', &buf, &bufsize, &needed); /* put value */ switch (prop->type) { case OSSL_PROPERTY_TYPE_STRING: val = ossl_property_value_str(ctx, prop->v.str_val); if (val == NULL) return 0; put_str(val, &buf, &bufsize, &needed); break; case OSSL_PROPERTY_TYPE_NUMBER: put_num(prop->v.int_val, &buf, &bufsize, &needed); break; default: return 0; } break; default: /* do nothing */ break; } } put_char('\0', &buf, &bufsize, &needed); return needed; }
20,192
27.561528
81
c
openssl
openssl-master/crypto/property/property_query.c
/* * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/propertyerr.h" #include "internal/property.h" #include "property_local.h" static int property_idx_cmp(const void *keyp, const void *compare) { OSSL_PROPERTY_IDX key = *(const OSSL_PROPERTY_IDX *)keyp; const OSSL_PROPERTY_DEFINITION *defn = (const OSSL_PROPERTY_DEFINITION *)compare; return key - defn->name_idx; } const OSSL_PROPERTY_DEFINITION * ossl_property_find_property(const OSSL_PROPERTY_LIST *list, OSSL_LIB_CTX *libctx, const char *name) { OSSL_PROPERTY_IDX name_idx; if (list == NULL || name == NULL || (name_idx = ossl_property_name(libctx, name, 0)) == 0) return NULL; return ossl_bsearch(&name_idx, list->properties, list->num_properties, sizeof(*list->properties), &property_idx_cmp, 0); } OSSL_PROPERTY_TYPE ossl_property_get_type(const OSSL_PROPERTY_DEFINITION *prop) { return prop->type; } const char *ossl_property_get_string_value(OSSL_LIB_CTX *libctx, const OSSL_PROPERTY_DEFINITION *prop) { const char *value = NULL; if (prop != NULL && prop->type == OSSL_PROPERTY_TYPE_STRING) value = ossl_property_value_str(libctx, prop->v.str_val); return value; } int64_t ossl_property_get_number_value(const OSSL_PROPERTY_DEFINITION *prop) { int64_t value = 0; if (prop != NULL && prop->type == OSSL_PROPERTY_TYPE_NUMBER) value = prop->v.int_val; return value; } /* Does a property query have any optional clauses */ int ossl_property_has_optional(const OSSL_PROPERTY_LIST *query) { return query->has_optional ? 1 : 0; } int ossl_property_is_enabled(OSSL_LIB_CTX *ctx, const char *property_name, const OSSL_PROPERTY_LIST *prop_list) { const OSSL_PROPERTY_DEFINITION *prop; prop = ossl_property_find_property(prop_list, ctx, property_name); /* Do a separate check for override as it does not set type */ if (prop == NULL || prop->optional || prop->oper == OSSL_PROPERTY_OVERRIDE) return 0; return (prop->type == OSSL_PROPERTY_TYPE_STRING && ((prop->oper == OSSL_PROPERTY_OPER_EQ && prop->v.str_val == OSSL_PROPERTY_TRUE) || (prop->oper == OSSL_PROPERTY_OPER_NE && prop->v.str_val != OSSL_PROPERTY_TRUE))); }
2,706
31.614458
80
c