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/bn/bn_shift.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 <assert.h> #include "internal/cryptlib.h" #include "bn_local.h" int BN_lshift1(BIGNUM *r, const BIGNUM *a) { register BN_ULONG *ap, *rp, t, c; int i; bn_check_top(r); bn_check_top(a); if (r != a) { r->neg = a->neg; if (bn_wexpand(r, a->top + 1) == NULL) return 0; r->top = a->top; } else { if (bn_wexpand(r, a->top + 1) == NULL) return 0; } ap = a->d; rp = r->d; c = 0; for (i = 0; i < a->top; i++) { t = *(ap++); *(rp++) = ((t << 1) | c) & BN_MASK2; c = t >> (BN_BITS2 - 1); } *rp = c; r->top += c; bn_check_top(r); return 1; } int BN_rshift1(BIGNUM *r, const BIGNUM *a) { BN_ULONG *ap, *rp, t, c; int i; bn_check_top(r); bn_check_top(a); if (BN_is_zero(a)) { BN_zero(r); return 1; } i = a->top; ap = a->d; if (a != r) { if (bn_wexpand(r, i) == NULL) return 0; r->neg = a->neg; } rp = r->d; r->top = i; t = ap[--i]; rp[i] = t >> 1; c = t << (BN_BITS2 - 1); r->top -= (t == 1); while (i > 0) { t = ap[--i]; rp[i] = ((t >> 1) & BN_MASK2) | c; c = t << (BN_BITS2 - 1); } if (!r->top) r->neg = 0; /* don't allow negative zero */ bn_check_top(r); return 1; } int BN_lshift(BIGNUM *r, const BIGNUM *a, int n) { int ret; if (n < 0) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_SHIFT); return 0; } ret = bn_lshift_fixed_top(r, a, n); bn_correct_top(r); bn_check_top(r); return ret; } /* * In respect to shift factor the execution time is invariant of * |n % BN_BITS2|, but not |n / BN_BITS2|. Or in other words pre-condition * for constant-time-ness is |n < BN_BITS2| or |n / BN_BITS2| being * non-secret. */ int bn_lshift_fixed_top(BIGNUM *r, const BIGNUM *a, int n) { int i, nw; unsigned int lb, rb; BN_ULONG *t, *f; BN_ULONG l, m, rmask = 0; assert(n >= 0); bn_check_top(r); bn_check_top(a); nw = n / BN_BITS2; if (bn_wexpand(r, a->top + nw + 1) == NULL) return 0; if (a->top != 0) { lb = (unsigned int)n % BN_BITS2; rb = BN_BITS2 - lb; rb %= BN_BITS2; /* say no to undefined behaviour */ rmask = (BN_ULONG)0 - rb; /* rmask = 0 - (rb != 0) */ rmask |= rmask >> 8; f = &(a->d[0]); t = &(r->d[nw]); l = f[a->top - 1]; t[a->top] = (l >> rb) & rmask; for (i = a->top - 1; i > 0; i--) { m = l << lb; l = f[i - 1]; t[i] = (m | ((l >> rb) & rmask)) & BN_MASK2; } t[0] = (l << lb) & BN_MASK2; } else { /* shouldn't happen, but formally required */ r->d[nw] = 0; } if (nw != 0) memset(r->d, 0, sizeof(*t) * nw); r->neg = a->neg; r->top = a->top + nw + 1; r->flags |= BN_FLG_FIXED_TOP; return 1; } int BN_rshift(BIGNUM *r, const BIGNUM *a, int n) { int ret = 0; if (n < 0) { ERR_raise(ERR_LIB_BN, BN_R_INVALID_SHIFT); return 0; } ret = bn_rshift_fixed_top(r, a, n); bn_correct_top(r); bn_check_top(r); return ret; } /* * In respect to shift factor the execution time is invariant of * |n % BN_BITS2|, but not |n / BN_BITS2|. Or in other words pre-condition * for constant-time-ness for sufficiently[!] zero-padded inputs is * |n < BN_BITS2| or |n / BN_BITS2| being non-secret. */ int bn_rshift_fixed_top(BIGNUM *r, const BIGNUM *a, int n) { int i, top, nw; unsigned int lb, rb; BN_ULONG *t, *f; BN_ULONG l, m, mask; bn_check_top(r); bn_check_top(a); assert(n >= 0); nw = n / BN_BITS2; if (nw >= a->top) { /* shouldn't happen, but formally required */ BN_zero(r); return 1; } rb = (unsigned int)n % BN_BITS2; lb = BN_BITS2 - rb; lb %= BN_BITS2; /* say no to undefined behaviour */ mask = (BN_ULONG)0 - lb; /* mask = 0 - (lb != 0) */ mask |= mask >> 8; top = a->top - nw; if (r != a && bn_wexpand(r, top) == NULL) return 0; t = &(r->d[0]); f = &(a->d[nw]); l = f[0]; for (i = 0; i < top - 1; i++) { m = f[i + 1]; t[i] = (l >> rb) | ((m << lb) & mask); l = m; } t[i] = l >> rb; r->neg = a->neg; r->top = top; r->flags |= BN_FLG_FIXED_TOP; return 1; }
4,826
21.24424
74
c
openssl
openssl-master/crypto/bn/bn_sparc.c
/* * Copyright 2005-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 <openssl/bn.h> #include "internal/cryptlib.h" #include "crypto/sparc_arch.h" #include "bn_local.h" /* for definition of bn_mul_mont */ int bn_mul_mont(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num) { int bn_mul_mont_vis3(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); int bn_mul_mont_fpu(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); int bn_mul_mont_int(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0, int num); if (!(num & 1) && num >= 6) { if ((num & 15) == 0 && num <= 64 && (OPENSSL_sparcv9cap_P[1] & (CFR_MONTMUL | CFR_MONTSQR)) == (CFR_MONTMUL | CFR_MONTSQR)) { typedef int (*bn_mul_mont_f) (BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_8(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_16(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_24(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0); int bn_mul_mont_t4_32(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, const BN_ULONG *np, const BN_ULONG *n0); static const bn_mul_mont_f funcs[4] = { bn_mul_mont_t4_8, bn_mul_mont_t4_16, bn_mul_mont_t4_24, bn_mul_mont_t4_32 }; bn_mul_mont_f worker = funcs[num / 16 - 1]; if ((*worker) (rp, ap, bp, np, n0)) return 1; /* retry once and fall back */ if ((*worker) (rp, ap, bp, np, n0)) return 1; return bn_mul_mont_vis3(rp, ap, bp, np, n0, num); } if ((OPENSSL_sparcv9cap_P[0] & SPARCV9_VIS3)) return bn_mul_mont_vis3(rp, ap, bp, np, n0, num); else if (num >= 8 && /* * bn_mul_mont_fpu doesn't use FMADD, we just use the * flag to detect when FPU path is preferable in cases * when current heuristics is unreliable. [it works * out because FMADD-capable processors where FPU * code path is undesirable are also VIS3-capable and * VIS3 code path takes precedence.] */ ( (OPENSSL_sparcv9cap_P[0] & SPARCV9_FMADD) || (OPENSSL_sparcv9cap_P[0] & (SPARCV9_PREFER_FPU | SPARCV9_VIS1)) == (SPARCV9_PREFER_FPU | SPARCV9_VIS1) )) return bn_mul_mont_fpu(rp, ap, bp, np, n0, num); } return bn_mul_mont_int(rp, ap, bp, np, n0, num); }
3,774
47.397436
78
c
openssl
openssl-master/crypto/bn/bn_sqr.c
/* * Copyright 1995-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 "internal/cryptlib.h" #include "bn_local.h" /* r must not be a */ /* * I've just gone over this and it is now %20 faster on x86 - eay - 27 Jun 96 */ int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { int ret = bn_sqr_fixed_top(r, a, ctx); bn_correct_top(r); bn_check_top(r); return ret; } int bn_sqr_fixed_top(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx) { int max, al; int ret = 0; BIGNUM *tmp, *rr; bn_check_top(a); al = a->top; if (al <= 0) { r->top = 0; r->neg = 0; return 1; } BN_CTX_start(ctx); rr = (a != r) ? r : BN_CTX_get(ctx); tmp = BN_CTX_get(ctx); if (rr == NULL || tmp == NULL) goto err; max = 2 * al; /* Non-zero (from above) */ if (bn_wexpand(rr, max) == NULL) goto err; if (al == 4) { #ifndef BN_SQR_COMBA BN_ULONG t[8]; bn_sqr_normal(rr->d, a->d, 4, t); #else bn_sqr_comba4(rr->d, a->d); #endif } else if (al == 8) { #ifndef BN_SQR_COMBA BN_ULONG t[16]; bn_sqr_normal(rr->d, a->d, 8, t); #else bn_sqr_comba8(rr->d, a->d); #endif } else { #if defined(BN_RECURSION) if (al < BN_SQR_RECURSIVE_SIZE_NORMAL) { BN_ULONG t[BN_SQR_RECURSIVE_SIZE_NORMAL * 2]; bn_sqr_normal(rr->d, a->d, al, t); } else { int j, k; j = BN_num_bits_word((BN_ULONG)al); j = 1 << (j - 1); k = j + j; if (al == j) { if (bn_wexpand(tmp, k * 2) == NULL) goto err; bn_sqr_recursive(rr->d, a->d, al, tmp->d); } else { if (bn_wexpand(tmp, max) == NULL) goto err; bn_sqr_normal(rr->d, a->d, al, tmp->d); } } #else if (bn_wexpand(tmp, max) == NULL) goto err; bn_sqr_normal(rr->d, a->d, al, tmp->d); #endif } rr->neg = 0; rr->top = max; rr->flags |= BN_FLG_FIXED_TOP; if (r != rr && BN_copy(r, rr) == NULL) goto err; ret = 1; err: bn_check_top(rr); bn_check_top(tmp); BN_CTX_end(ctx); return ret; } /* tmp must have 2*n words */ void bn_sqr_normal(BN_ULONG *r, const BN_ULONG *a, int n, BN_ULONG *tmp) { int i, j, max; const BN_ULONG *ap; BN_ULONG *rp; max = n * 2; ap = a; rp = r; rp[0] = rp[max - 1] = 0; rp++; j = n; if (--j > 0) { ap++; rp[j] = bn_mul_words(rp, ap, j, ap[-1]); rp += 2; } for (i = n - 2; i > 0; i--) { j--; ap++; rp[j] = bn_mul_add_words(rp, ap, j, ap[-1]); rp += 2; } bn_add_words(r, r, r, max); /* There will not be a carry */ bn_sqr_words(tmp, a, n); bn_add_words(r, r, tmp, max); } #ifdef BN_RECURSION /*- * r is 2*n words in size, * a and b are both n words in size. (There's not actually a 'b' here ...) * n must be a power of 2. * We multiply and return the result. * t must be 2*n words in size * We calculate * a[0]*b[0] * a[0]*b[0]+a[1]*b[1]+(a[0]-a[1])*(b[1]-b[0]) * a[1]*b[1] */ void bn_sqr_recursive(BN_ULONG *r, const BN_ULONG *a, int n2, BN_ULONG *t) { int n = n2 / 2; int zero, c1; BN_ULONG ln, lo, *p; if (n2 == 4) { # ifndef BN_SQR_COMBA bn_sqr_normal(r, a, 4, t); # else bn_sqr_comba4(r, a); # endif return; } else if (n2 == 8) { # ifndef BN_SQR_COMBA bn_sqr_normal(r, a, 8, t); # else bn_sqr_comba8(r, a); # endif return; } if (n2 < BN_SQR_RECURSIVE_SIZE_NORMAL) { bn_sqr_normal(r, a, n2, t); return; } /* r=(a[0]-a[1])*(a[1]-a[0]) */ c1 = bn_cmp_words(a, &(a[n]), n); zero = 0; if (c1 > 0) bn_sub_words(t, a, &(a[n]), n); else if (c1 < 0) bn_sub_words(t, &(a[n]), a, n); else zero = 1; /* The result will always be negative unless it is zero */ p = &(t[n2 * 2]); if (!zero) bn_sqr_recursive(&(t[n2]), t, n, p); else memset(&t[n2], 0, sizeof(*t) * n2); bn_sqr_recursive(r, a, n, p); bn_sqr_recursive(&(r[n2]), &(a[n]), n, p); /*- * t[32] holds (a[0]-a[1])*(a[1]-a[0]), it is negative or zero * r[10] holds (a[0]*b[0]) * r[32] holds (b[1]*b[1]) */ c1 = (int)(bn_add_words(t, r, &(r[n2]), n2)); /* t[32] is negative */ c1 -= (int)(bn_sub_words(&(t[n2]), t, &(t[n2]), n2)); /*- * t[32] holds (a[0]-a[1])*(a[1]-a[0])+(a[0]*a[0])+(a[1]*a[1]) * r[10] holds (a[0]*a[0]) * r[32] holds (a[1]*a[1]) * c1 holds the carry bits */ c1 += (int)(bn_add_words(&(r[n]), &(r[n]), &(t[n2]), n2)); if (c1) { p = &(r[n + n2]); lo = *p; ln = (lo + c1) & BN_MASK2; *p = ln; /* * The overflow will stop before we over write words we should not * overwrite */ if (ln < (BN_ULONG)c1) { do { p++; lo = *p; ln = (lo + 1) & BN_MASK2; *p = ln; } while (ln == 0); } } } #endif
5,505
21.941667
77
c
openssl
openssl-master/crypto/bn/bn_sqrt.c
/* * Copyright 2000-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include "bn_local.h" BIGNUM *BN_mod_sqrt(BIGNUM *in, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx) /* * Returns 'ret' such that ret^2 == a (mod p), using the Tonelli/Shanks * algorithm (cf. Henri Cohen, "A Course in Algebraic Computational Number * Theory", algorithm 1.5.1). 'p' must be prime, otherwise an error or * an incorrect "result" will be returned. */ { BIGNUM *ret = in; int err = 1; int r; BIGNUM *A, *b, *q, *t, *x, *y; int e, i, j; int used_ctx = 0; if (!BN_is_odd(p) || BN_abs_is_word(p, 1)) { if (BN_abs_is_word(p, 2)) { if (ret == NULL) ret = BN_new(); if (ret == NULL) goto end; if (!BN_set_word(ret, BN_is_bit_set(a, 0))) { if (ret != in) BN_free(ret); return NULL; } bn_check_top(ret); return ret; } ERR_raise(ERR_LIB_BN, BN_R_P_IS_NOT_PRIME); return NULL; } if (BN_is_zero(a) || BN_is_one(a)) { if (ret == NULL) ret = BN_new(); if (ret == NULL) goto end; if (!BN_set_word(ret, BN_is_one(a))) { if (ret != in) BN_free(ret); return NULL; } bn_check_top(ret); return ret; } BN_CTX_start(ctx); used_ctx = 1; A = BN_CTX_get(ctx); b = BN_CTX_get(ctx); q = BN_CTX_get(ctx); t = BN_CTX_get(ctx); x = BN_CTX_get(ctx); y = BN_CTX_get(ctx); if (y == NULL) goto end; if (ret == NULL) ret = BN_new(); if (ret == NULL) goto end; /* A = a mod p */ if (!BN_nnmod(A, a, p, ctx)) goto end; /* now write |p| - 1 as 2^e*q where q is odd */ e = 1; while (!BN_is_bit_set(p, e)) e++; /* we'll set q later (if needed) */ if (e == 1) { /*- * The easy case: (|p|-1)/2 is odd, so 2 has an inverse * modulo (|p|-1)/2, and square roots can be computed * directly by modular exponentiation. * We have * 2 * (|p|+1)/4 == 1 (mod (|p|-1)/2), * so we can use exponent (|p|+1)/4, i.e. (|p|-3)/4 + 1. */ if (!BN_rshift(q, p, 2)) goto end; q->neg = 0; if (!BN_add_word(q, 1)) goto end; if (!BN_mod_exp(ret, A, q, p, ctx)) goto end; err = 0; goto vrfy; } if (e == 2) { /*- * |p| == 5 (mod 8) * * In this case 2 is always a non-square since * Legendre(2,p) = (-1)^((p^2-1)/8) for any odd prime. * So if a really is a square, then 2*a is a non-square. * Thus for * b := (2*a)^((|p|-5)/8), * i := (2*a)*b^2 * we have * i^2 = (2*a)^((1 + (|p|-5)/4)*2) * = (2*a)^((p-1)/2) * = -1; * so if we set * x := a*b*(i-1), * then * x^2 = a^2 * b^2 * (i^2 - 2*i + 1) * = a^2 * b^2 * (-2*i) * = a*(-i)*(2*a*b^2) * = a*(-i)*i * = a. * * (This is due to A.O.L. Atkin, * Subject: Square Roots and Cognate Matters modulo p=8n+5. * URL: https://listserv.nodak.edu/cgi-bin/wa.exe?A2=ind9211&L=NMBRTHRY&P=4026 * November 1992.) */ /* t := 2*a */ if (!BN_mod_lshift1_quick(t, A, p)) goto end; /* b := (2*a)^((|p|-5)/8) */ if (!BN_rshift(q, p, 3)) goto end; q->neg = 0; if (!BN_mod_exp(b, t, q, p, ctx)) goto end; /* y := b^2 */ if (!BN_mod_sqr(y, b, p, ctx)) goto end; /* t := (2*a)*b^2 - 1 */ if (!BN_mod_mul(t, t, y, p, ctx)) goto end; if (!BN_sub_word(t, 1)) goto end; /* x = a*b*t */ if (!BN_mod_mul(x, A, b, p, ctx)) goto end; if (!BN_mod_mul(x, x, t, p, ctx)) goto end; if (!BN_copy(ret, x)) goto end; err = 0; goto vrfy; } /* * e > 2, so we really have to use the Tonelli/Shanks algorithm. First, * find some y that is not a square. */ if (!BN_copy(q, p)) goto end; /* use 'q' as temp */ q->neg = 0; i = 2; do { /* * For efficiency, try small numbers first; if this fails, try random * numbers. */ if (i < 22) { if (!BN_set_word(y, i)) goto end; } else { if (!BN_priv_rand_ex(y, BN_num_bits(p), 0, 0, 0, ctx)) goto end; if (BN_ucmp(y, p) >= 0) { if (!(p->neg ? BN_add : BN_sub) (y, y, p)) goto end; } /* now 0 <= y < |p| */ if (BN_is_zero(y)) if (!BN_set_word(y, i)) goto end; } r = BN_kronecker(y, q, ctx); /* here 'q' is |p| */ if (r < -1) goto end; if (r == 0) { /* m divides p */ ERR_raise(ERR_LIB_BN, BN_R_P_IS_NOT_PRIME); goto end; } } while (r == 1 && ++i < 82); if (r != -1) { /* * Many rounds and still no non-square -- this is more likely a bug * than just bad luck. Even if p is not prime, we should have found * some y such that r == -1. */ ERR_raise(ERR_LIB_BN, BN_R_TOO_MANY_ITERATIONS); goto end; } /* Here's our actual 'q': */ if (!BN_rshift(q, q, e)) goto end; /* * Now that we have some non-square, we can find an element of order 2^e * by computing its q'th power. */ if (!BN_mod_exp(y, y, q, p, ctx)) goto end; if (BN_is_one(y)) { ERR_raise(ERR_LIB_BN, BN_R_P_IS_NOT_PRIME); goto end; } /*- * Now we know that (if p is indeed prime) there is an integer * k, 0 <= k < 2^e, such that * * a^q * y^k == 1 (mod p). * * As a^q is a square and y is not, k must be even. * q+1 is even, too, so there is an element * * X := a^((q+1)/2) * y^(k/2), * * and it satisfies * * X^2 = a^q * a * y^k * = a, * * so it is the square root that we are looking for. */ /* t := (q-1)/2 (note that q is odd) */ if (!BN_rshift1(t, q)) goto end; /* x := a^((q-1)/2) */ if (BN_is_zero(t)) { /* special case: p = 2^e + 1 */ if (!BN_nnmod(t, A, p, ctx)) goto end; if (BN_is_zero(t)) { /* special case: a == 0 (mod p) */ BN_zero(ret); err = 0; goto end; } else if (!BN_one(x)) goto end; } else { if (!BN_mod_exp(x, A, t, p, ctx)) goto end; if (BN_is_zero(x)) { /* special case: a == 0 (mod p) */ BN_zero(ret); err = 0; goto end; } } /* b := a*x^2 (= a^q) */ if (!BN_mod_sqr(b, x, p, ctx)) goto end; if (!BN_mod_mul(b, b, A, p, ctx)) goto end; /* x := a*x (= a^((q+1)/2)) */ if (!BN_mod_mul(x, x, A, p, ctx)) goto end; while (1) { /*- * Now b is a^q * y^k for some even k (0 <= k < 2^E * where E refers to the original value of e, which we * don't keep in a variable), and x is a^((q+1)/2) * y^(k/2). * * We have a*b = x^2, * y^2^(e-1) = -1, * b^2^(e-1) = 1. */ if (BN_is_one(b)) { if (!BN_copy(ret, x)) goto end; err = 0; goto vrfy; } /* Find the smallest i, 0 < i < e, such that b^(2^i) = 1. */ for (i = 1; i < e; i++) { if (i == 1) { if (!BN_mod_sqr(t, b, p, ctx)) goto end; } else { if (!BN_mod_mul(t, t, t, p, ctx)) goto end; } if (BN_is_one(t)) break; } /* If not found, a is not a square or p is not prime. */ if (i >= e) { ERR_raise(ERR_LIB_BN, BN_R_NOT_A_SQUARE); goto end; } /* t := y^2^(e - i - 1) */ if (!BN_copy(t, y)) goto end; for (j = e - i - 1; j > 0; j--) { if (!BN_mod_sqr(t, t, p, ctx)) goto end; } if (!BN_mod_mul(y, t, t, p, ctx)) goto end; if (!BN_mod_mul(x, x, t, p, ctx)) goto end; if (!BN_mod_mul(b, b, y, p, ctx)) goto end; e = i; } vrfy: if (!err) { /* * verify the result -- the input might have been not a square (test * added in 0.9.8) */ if (!BN_mod_sqr(x, ret, p, ctx)) err = 1; if (!err && 0 != BN_cmp(x, A)) { ERR_raise(ERR_LIB_BN, BN_R_NOT_A_SQUARE); err = 1; } } end: if (err) { if (ret != in) BN_clear_free(ret); ret = NULL; } if (used_ctx) BN_CTX_end(ctx); bn_check_top(ret); return ret; }
9,803
25.569106
86
c
openssl
openssl-master/crypto/bn/bn_srp.c
/* * Copyright 2014-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "bn_local.h" #include "internal/nelem.h" #ifndef OPENSSL_NO_SRP #include <openssl/srp.h> #include "crypto/bn_srp.h" # if (BN_BYTES == 8) # if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32__) # define bn_pack4(a1,a2,a3,a4) ((a1##UI64<<48)|(a2##UI64<<32)|(a3##UI64<<16)|a4##UI64) # elif defined(__arch64__) # define bn_pack4(a1,a2,a3,a4) ((a1##UL<<48)|(a2##UL<<32)|(a3##UL<<16)|a4##UL) # else # define bn_pack4(a1,a2,a3,a4) ((a1##ULL<<48)|(a2##ULL<<32)|(a3##ULL<<16)|a4##ULL) # endif # elif (BN_BYTES == 4) # define bn_pack4(a1,a2,a3,a4) ((a3##UL<<16)|a4##UL), ((a1##UL<<16)|a2##UL) # else # error "unsupported BN_BYTES" # endif static const BN_ULONG bn_group_1024_value[] = { bn_pack4(0x9FC6, 0x1D2F, 0xC0EB, 0x06E3), bn_pack4(0xFD51, 0x38FE, 0x8376, 0x435B), bn_pack4(0x2FD4, 0xCBF4, 0x976E, 0xAA9A), bn_pack4(0x68ED, 0xBC3C, 0x0572, 0x6CC0), bn_pack4(0xC529, 0xF566, 0x660E, 0x57EC), bn_pack4(0x8255, 0x9B29, 0x7BCF, 0x1885), bn_pack4(0xCE8E, 0xF4AD, 0x69B1, 0x5D49), bn_pack4(0x5DC7, 0xD7B4, 0x6154, 0xD6B6), bn_pack4(0x8E49, 0x5C1D, 0x6089, 0xDAD1), bn_pack4(0xE0D5, 0xD8E2, 0x50B9, 0x8BE4), bn_pack4(0x383B, 0x4813, 0xD692, 0xC6E0), bn_pack4(0xD674, 0xDF74, 0x96EA, 0x81D3), bn_pack4(0x9EA2, 0x314C, 0x9C25, 0x6576), bn_pack4(0x6072, 0x6187, 0x75FF, 0x3C0B), bn_pack4(0x9C33, 0xF80A, 0xFA8F, 0xC5E8), bn_pack4(0xEEAF, 0x0AB9, 0xADB3, 0x8DD6) }; const BIGNUM ossl_bn_group_1024 = { (BN_ULONG *)bn_group_1024_value, OSSL_NELEM(bn_group_1024_value), OSSL_NELEM(bn_group_1024_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_group_1536_value[] = { bn_pack4(0xCF76, 0xE3FE, 0xD135, 0xF9BB), bn_pack4(0x1518, 0x0F93, 0x499A, 0x234D), bn_pack4(0x8CE7, 0xA28C, 0x2442, 0xC6F3), bn_pack4(0x5A02, 0x1FFF, 0x5E91, 0x479E), bn_pack4(0x7F8A, 0x2FE9, 0xB8B5, 0x292E), bn_pack4(0x837C, 0x264A, 0xE3A9, 0xBEB8), bn_pack4(0xE442, 0x734A, 0xF7CC, 0xB7AE), bn_pack4(0x6577, 0x2E43, 0x7D6C, 0x7F8C), bn_pack4(0xDB2F, 0xD53D, 0x24B7, 0xC486), bn_pack4(0x6EDF, 0x0195, 0x3934, 0x9627), bn_pack4(0x158B, 0xFD3E, 0x2B9C, 0x8CF5), bn_pack4(0x764E, 0x3F4B, 0x53DD, 0x9DA1), bn_pack4(0x4754, 0x8381, 0xDBC5, 0xB1FC), bn_pack4(0x9B60, 0x9E0B, 0xE3BA, 0xB63D), bn_pack4(0x8134, 0xB1C8, 0xB979, 0x8914), bn_pack4(0xDF02, 0x8A7C, 0xEC67, 0xF0D0), bn_pack4(0x80B6, 0x55BB, 0x9A22, 0xE8DC), bn_pack4(0x1558, 0x903B, 0xA0D0, 0xF843), bn_pack4(0x51C6, 0xA94B, 0xE460, 0x7A29), bn_pack4(0x5F4F, 0x5F55, 0x6E27, 0xCBDE), bn_pack4(0xBEEE, 0xA961, 0x4B19, 0xCC4D), bn_pack4(0xDBA5, 0x1DF4, 0x99AC, 0x4C80), bn_pack4(0xB1F1, 0x2A86, 0x17A4, 0x7BBB), bn_pack4(0x9DEF, 0x3CAF, 0xB939, 0x277A) }; const BIGNUM ossl_bn_group_1536 = { (BN_ULONG *)bn_group_1536_value, OSSL_NELEM(bn_group_1536_value), OSSL_NELEM(bn_group_1536_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_group_2048_value[] = { bn_pack4(0x0FA7, 0x111F, 0x9E4A, 0xFF73), bn_pack4(0x9B65, 0xE372, 0xFCD6, 0x8EF2), bn_pack4(0x35DE, 0x236D, 0x525F, 0x5475), bn_pack4(0x94B5, 0xC803, 0xD89F, 0x7AE4), bn_pack4(0x71AE, 0x35F8, 0xE9DB, 0xFBB6), bn_pack4(0x2A56, 0x98F3, 0xA8D0, 0xC382), bn_pack4(0x9CCC, 0x041C, 0x7BC3, 0x08D8), bn_pack4(0xAF87, 0x4E73, 0x03CE, 0x5329), bn_pack4(0x6160, 0x2790, 0x04E5, 0x7AE6), bn_pack4(0x032C, 0xFBDB, 0xF52F, 0xB378), bn_pack4(0x5EA7, 0x7A27, 0x75D2, 0xECFA), bn_pack4(0x5445, 0x23B5, 0x24B0, 0xD57D), bn_pack4(0x5B9D, 0x32E6, 0x88F8, 0x7748), bn_pack4(0xF1D2, 0xB907, 0x8717, 0x461A), bn_pack4(0x76BD, 0x207A, 0x436C, 0x6481), bn_pack4(0xCA97, 0xB43A, 0x23FB, 0x8016), bn_pack4(0x1D28, 0x1E44, 0x6B14, 0x773B), bn_pack4(0x7359, 0xD041, 0xD5C3, 0x3EA7), bn_pack4(0xA80D, 0x740A, 0xDBF4, 0xFF74), bn_pack4(0x55F9, 0x7993, 0xEC97, 0x5EEA), bn_pack4(0x2918, 0xA996, 0x2F0B, 0x93B8), bn_pack4(0x661A, 0x05FB, 0xD5FA, 0xAAE8), bn_pack4(0xCF60, 0x9517, 0x9A16, 0x3AB3), bn_pack4(0xE808, 0x3969, 0xEDB7, 0x67B0), bn_pack4(0xCD7F, 0x48A9, 0xDA04, 0xFD50), bn_pack4(0xD523, 0x12AB, 0x4B03, 0x310D), bn_pack4(0x8193, 0xE075, 0x7767, 0xA13D), bn_pack4(0xA373, 0x29CB, 0xB4A0, 0x99ED), bn_pack4(0xFC31, 0x9294, 0x3DB5, 0x6050), bn_pack4(0xAF72, 0xB665, 0x1987, 0xEE07), bn_pack4(0xF166, 0xDE5E, 0x1389, 0x582F), bn_pack4(0xAC6B, 0xDB41, 0x324A, 0x9A9B) }; const BIGNUM ossl_bn_group_2048 = { (BN_ULONG *)bn_group_2048_value, OSSL_NELEM(bn_group_2048_value), OSSL_NELEM(bn_group_2048_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_group_3072_value[] = { bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF), bn_pack4(0x4B82, 0xD120, 0xA93A, 0xD2CA), bn_pack4(0x43DB, 0x5BFC, 0xE0FD, 0x108E), bn_pack4(0x08E2, 0x4FA0, 0x74E5, 0xAB31), bn_pack4(0x7709, 0x88C0, 0xBAD9, 0x46E2), bn_pack4(0xBBE1, 0x1757, 0x7A61, 0x5D6C), bn_pack4(0x521F, 0x2B18, 0x177B, 0x200C), bn_pack4(0xD876, 0x0273, 0x3EC8, 0x6A64), bn_pack4(0xF12F, 0xFA06, 0xD98A, 0x0864), bn_pack4(0xCEE3, 0xD226, 0x1AD2, 0xEE6B), bn_pack4(0x1E8C, 0x94E0, 0x4A25, 0x619D), bn_pack4(0xABF5, 0xAE8C, 0xDB09, 0x33D7), bn_pack4(0xB397, 0x0F85, 0xA6E1, 0xE4C7), bn_pack4(0x8AEA, 0x7157, 0x5D06, 0x0C7D), bn_pack4(0xECFB, 0x8504, 0x58DB, 0xEF0A), bn_pack4(0xA855, 0x21AB, 0xDF1C, 0xBA64), bn_pack4(0xAD33, 0x170D, 0x0450, 0x7A33), bn_pack4(0x1572, 0x8E5A, 0x8AAA, 0xC42D), bn_pack4(0x15D2, 0x2618, 0x98FA, 0x0510), bn_pack4(0x3995, 0x497C, 0xEA95, 0x6AE5), bn_pack4(0xDE2B, 0xCBF6, 0x9558, 0x1718), bn_pack4(0xB5C5, 0x5DF0, 0x6F4C, 0x52C9), bn_pack4(0x9B27, 0x83A2, 0xEC07, 0xA28F), bn_pack4(0xE39E, 0x772C, 0x180E, 0x8603), bn_pack4(0x3290, 0x5E46, 0x2E36, 0xCE3B), bn_pack4(0xF174, 0x6C08, 0xCA18, 0x217C), bn_pack4(0x670C, 0x354E, 0x4ABC, 0x9804), bn_pack4(0x9ED5, 0x2907, 0x7096, 0x966D), bn_pack4(0x1C62, 0xF356, 0x2085, 0x52BB), bn_pack4(0x8365, 0x5D23, 0xDCA3, 0xAD96), bn_pack4(0x6916, 0x3FA8, 0xFD24, 0xCF5F), bn_pack4(0x98DA, 0x4836, 0x1C55, 0xD39A), bn_pack4(0xC200, 0x7CB8, 0xA163, 0xBF05), bn_pack4(0x4928, 0x6651, 0xECE4, 0x5B3D), bn_pack4(0xAE9F, 0x2411, 0x7C4B, 0x1FE6), bn_pack4(0xEE38, 0x6BFB, 0x5A89, 0x9FA5), bn_pack4(0x0BFF, 0x5CB6, 0xF406, 0xB7ED), bn_pack4(0xF44C, 0x42E9, 0xA637, 0xED6B), bn_pack4(0xE485, 0xB576, 0x625E, 0x7EC6), bn_pack4(0x4FE1, 0x356D, 0x6D51, 0xC245), bn_pack4(0x302B, 0x0A6D, 0xF25F, 0x1437), bn_pack4(0xEF95, 0x19B3, 0xCD3A, 0x431B), bn_pack4(0x514A, 0x0879, 0x8E34, 0x04DD), bn_pack4(0x020B, 0xBEA6, 0x3B13, 0x9B22), bn_pack4(0x2902, 0x4E08, 0x8A67, 0xCC74), bn_pack4(0xC4C6, 0x628B, 0x80DC, 0x1CD1), bn_pack4(0xC90F, 0xDAA2, 0x2168, 0xC234), bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF) }; const BIGNUM ossl_bn_group_3072 = { (BN_ULONG *)bn_group_3072_value, OSSL_NELEM(bn_group_3072_value), OSSL_NELEM(bn_group_3072_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_group_4096_value[] = { bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF), bn_pack4(0x4DF4, 0x35C9, 0x3406, 0x3199), bn_pack4(0x86FF, 0xB7DC, 0x90A6, 0xC08F), bn_pack4(0x93B4, 0xEA98, 0x8D8F, 0xDDC1), bn_pack4(0xD006, 0x9127, 0xD5B0, 0x5AA9), bn_pack4(0xB81B, 0xDD76, 0x2170, 0x481C), bn_pack4(0x1F61, 0x2970, 0xCEE2, 0xD7AF), bn_pack4(0x233B, 0xA186, 0x515B, 0xE7ED), bn_pack4(0x99B2, 0x964F, 0xA090, 0xC3A2), bn_pack4(0x287C, 0x5947, 0x4E6B, 0xC05D), bn_pack4(0x2E8E, 0xFC14, 0x1FBE, 0xCAA6), bn_pack4(0xDBBB, 0xC2DB, 0x04DE, 0x8EF9), bn_pack4(0x2583, 0xE9CA, 0x2AD4, 0x4CE8), bn_pack4(0x1A94, 0x6834, 0xB615, 0x0BDA), bn_pack4(0x99C3, 0x2718, 0x6AF4, 0xE23C), bn_pack4(0x8871, 0x9A10, 0xBDBA, 0x5B26), bn_pack4(0x1A72, 0x3C12, 0xA787, 0xE6D7), bn_pack4(0x4B82, 0xD120, 0xA921, 0x0801), bn_pack4(0x43DB, 0x5BFC, 0xE0FD, 0x108E), bn_pack4(0x08E2, 0x4FA0, 0x74E5, 0xAB31), bn_pack4(0x7709, 0x88C0, 0xBAD9, 0x46E2), bn_pack4(0xBBE1, 0x1757, 0x7A61, 0x5D6C), bn_pack4(0x521F, 0x2B18, 0x177B, 0x200C), bn_pack4(0xD876, 0x0273, 0x3EC8, 0x6A64), bn_pack4(0xF12F, 0xFA06, 0xD98A, 0x0864), bn_pack4(0xCEE3, 0xD226, 0x1AD2, 0xEE6B), bn_pack4(0x1E8C, 0x94E0, 0x4A25, 0x619D), bn_pack4(0xABF5, 0xAE8C, 0xDB09, 0x33D7), bn_pack4(0xB397, 0x0F85, 0xA6E1, 0xE4C7), bn_pack4(0x8AEA, 0x7157, 0x5D06, 0x0C7D), bn_pack4(0xECFB, 0x8504, 0x58DB, 0xEF0A), bn_pack4(0xA855, 0x21AB, 0xDF1C, 0xBA64), bn_pack4(0xAD33, 0x170D, 0x0450, 0x7A33), bn_pack4(0x1572, 0x8E5A, 0x8AAA, 0xC42D), bn_pack4(0x15D2, 0x2618, 0x98FA, 0x0510), bn_pack4(0x3995, 0x497C, 0xEA95, 0x6AE5), bn_pack4(0xDE2B, 0xCBF6, 0x9558, 0x1718), bn_pack4(0xB5C5, 0x5DF0, 0x6F4C, 0x52C9), bn_pack4(0x9B27, 0x83A2, 0xEC07, 0xA28F), bn_pack4(0xE39E, 0x772C, 0x180E, 0x8603), bn_pack4(0x3290, 0x5E46, 0x2E36, 0xCE3B), bn_pack4(0xF174, 0x6C08, 0xCA18, 0x217C), bn_pack4(0x670C, 0x354E, 0x4ABC, 0x9804), bn_pack4(0x9ED5, 0x2907, 0x7096, 0x966D), bn_pack4(0x1C62, 0xF356, 0x2085, 0x52BB), bn_pack4(0x8365, 0x5D23, 0xDCA3, 0xAD96), bn_pack4(0x6916, 0x3FA8, 0xFD24, 0xCF5F), bn_pack4(0x98DA, 0x4836, 0x1C55, 0xD39A), bn_pack4(0xC200, 0x7CB8, 0xA163, 0xBF05), bn_pack4(0x4928, 0x6651, 0xECE4, 0x5B3D), bn_pack4(0xAE9F, 0x2411, 0x7C4B, 0x1FE6), bn_pack4(0xEE38, 0x6BFB, 0x5A89, 0x9FA5), bn_pack4(0x0BFF, 0x5CB6, 0xF406, 0xB7ED), bn_pack4(0xF44C, 0x42E9, 0xA637, 0xED6B), bn_pack4(0xE485, 0xB576, 0x625E, 0x7EC6), bn_pack4(0x4FE1, 0x356D, 0x6D51, 0xC245), bn_pack4(0x302B, 0x0A6D, 0xF25F, 0x1437), bn_pack4(0xEF95, 0x19B3, 0xCD3A, 0x431B), bn_pack4(0x514A, 0x0879, 0x8E34, 0x04DD), bn_pack4(0x020B, 0xBEA6, 0x3B13, 0x9B22), bn_pack4(0x2902, 0x4E08, 0x8A67, 0xCC74), bn_pack4(0xC4C6, 0x628B, 0x80DC, 0x1CD1), bn_pack4(0xC90F, 0xDAA2, 0x2168, 0xC234), bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF) }; const BIGNUM ossl_bn_group_4096 = { (BN_ULONG *)bn_group_4096_value, OSSL_NELEM(bn_group_4096_value), OSSL_NELEM(bn_group_4096_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_group_6144_value[] = { bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF), bn_pack4(0xE694, 0xF91E, 0x6DCC, 0x4024), bn_pack4(0x12BF, 0x2D5B, 0x0B74, 0x74D6), bn_pack4(0x043E, 0x8F66, 0x3F48, 0x60EE), bn_pack4(0x387F, 0xE8D7, 0x6E3C, 0x0468), bn_pack4(0xDA56, 0xC9EC, 0x2EF2, 0x9632), bn_pack4(0xEB19, 0xCCB1, 0xA313, 0xD55C), bn_pack4(0xF550, 0xAA3D, 0x8A1F, 0xBFF0), bn_pack4(0x06A1, 0xD58B, 0xB7C5, 0xDA76), bn_pack4(0xA797, 0x15EE, 0xF29B, 0xE328), bn_pack4(0x14CC, 0x5ED2, 0x0F80, 0x37E0), bn_pack4(0xCC8F, 0x6D7E, 0xBF48, 0xE1D8), bn_pack4(0x4BD4, 0x07B2, 0x2B41, 0x54AA), bn_pack4(0x0F1D, 0x45B7, 0xFF58, 0x5AC5), bn_pack4(0x23A9, 0x7A7E, 0x36CC, 0x88BE), bn_pack4(0x59E7, 0xC97F, 0xBEC7, 0xE8F3), bn_pack4(0xB5A8, 0x4031, 0x900B, 0x1C9E), bn_pack4(0xD55E, 0x702F, 0x4698, 0x0C82), bn_pack4(0xF482, 0xD7CE, 0x6E74, 0xFEF6), bn_pack4(0xF032, 0xEA15, 0xD172, 0x1D03), bn_pack4(0x5983, 0xCA01, 0xC64B, 0x92EC), bn_pack4(0x6FB8, 0xF401, 0x378C, 0xD2BF), bn_pack4(0x3320, 0x5151, 0x2BD7, 0xAF42), bn_pack4(0xDB7F, 0x1447, 0xE6CC, 0x254B), bn_pack4(0x44CE, 0x6CBA, 0xCED4, 0xBB1B), bn_pack4(0xDA3E, 0xDBEB, 0xCF9B, 0x14ED), bn_pack4(0x1797, 0x27B0, 0x865A, 0x8918), bn_pack4(0xB06A, 0x53ED, 0x9027, 0xD831), bn_pack4(0xE5DB, 0x382F, 0x4130, 0x01AE), bn_pack4(0xF8FF, 0x9406, 0xAD9E, 0x530E), bn_pack4(0xC975, 0x1E76, 0x3DBA, 0x37BD), bn_pack4(0xC1D4, 0xDCB2, 0x6026, 0x46DE), bn_pack4(0x36C3, 0xFAB4, 0xD27C, 0x7026), bn_pack4(0x4DF4, 0x35C9, 0x3402, 0x8492), bn_pack4(0x86FF, 0xB7DC, 0x90A6, 0xC08F), bn_pack4(0x93B4, 0xEA98, 0x8D8F, 0xDDC1), bn_pack4(0xD006, 0x9127, 0xD5B0, 0x5AA9), bn_pack4(0xB81B, 0xDD76, 0x2170, 0x481C), bn_pack4(0x1F61, 0x2970, 0xCEE2, 0xD7AF), bn_pack4(0x233B, 0xA186, 0x515B, 0xE7ED), bn_pack4(0x99B2, 0x964F, 0xA090, 0xC3A2), bn_pack4(0x287C, 0x5947, 0x4E6B, 0xC05D), bn_pack4(0x2E8E, 0xFC14, 0x1FBE, 0xCAA6), bn_pack4(0xDBBB, 0xC2DB, 0x04DE, 0x8EF9), bn_pack4(0x2583, 0xE9CA, 0x2AD4, 0x4CE8), bn_pack4(0x1A94, 0x6834, 0xB615, 0x0BDA), bn_pack4(0x99C3, 0x2718, 0x6AF4, 0xE23C), bn_pack4(0x8871, 0x9A10, 0xBDBA, 0x5B26), bn_pack4(0x1A72, 0x3C12, 0xA787, 0xE6D7), bn_pack4(0x4B82, 0xD120, 0xA921, 0x0801), bn_pack4(0x43DB, 0x5BFC, 0xE0FD, 0x108E), bn_pack4(0x08E2, 0x4FA0, 0x74E5, 0xAB31), bn_pack4(0x7709, 0x88C0, 0xBAD9, 0x46E2), bn_pack4(0xBBE1, 0x1757, 0x7A61, 0x5D6C), bn_pack4(0x521F, 0x2B18, 0x177B, 0x200C), bn_pack4(0xD876, 0x0273, 0x3EC8, 0x6A64), bn_pack4(0xF12F, 0xFA06, 0xD98A, 0x0864), bn_pack4(0xCEE3, 0xD226, 0x1AD2, 0xEE6B), bn_pack4(0x1E8C, 0x94E0, 0x4A25, 0x619D), bn_pack4(0xABF5, 0xAE8C, 0xDB09, 0x33D7), bn_pack4(0xB397, 0x0F85, 0xA6E1, 0xE4C7), bn_pack4(0x8AEA, 0x7157, 0x5D06, 0x0C7D), bn_pack4(0xECFB, 0x8504, 0x58DB, 0xEF0A), bn_pack4(0xA855, 0x21AB, 0xDF1C, 0xBA64), bn_pack4(0xAD33, 0x170D, 0x0450, 0x7A33), bn_pack4(0x1572, 0x8E5A, 0x8AAA, 0xC42D), bn_pack4(0x15D2, 0x2618, 0x98FA, 0x0510), bn_pack4(0x3995, 0x497C, 0xEA95, 0x6AE5), bn_pack4(0xDE2B, 0xCBF6, 0x9558, 0x1718), bn_pack4(0xB5C5, 0x5DF0, 0x6F4C, 0x52C9), bn_pack4(0x9B27, 0x83A2, 0xEC07, 0xA28F), bn_pack4(0xE39E, 0x772C, 0x180E, 0x8603), bn_pack4(0x3290, 0x5E46, 0x2E36, 0xCE3B), bn_pack4(0xF174, 0x6C08, 0xCA18, 0x217C), bn_pack4(0x670C, 0x354E, 0x4ABC, 0x9804), bn_pack4(0x9ED5, 0x2907, 0x7096, 0x966D), bn_pack4(0x1C62, 0xF356, 0x2085, 0x52BB), bn_pack4(0x8365, 0x5D23, 0xDCA3, 0xAD96), bn_pack4(0x6916, 0x3FA8, 0xFD24, 0xCF5F), bn_pack4(0x98DA, 0x4836, 0x1C55, 0xD39A), bn_pack4(0xC200, 0x7CB8, 0xA163, 0xBF05), bn_pack4(0x4928, 0x6651, 0xECE4, 0x5B3D), bn_pack4(0xAE9F, 0x2411, 0x7C4B, 0x1FE6), bn_pack4(0xEE38, 0x6BFB, 0x5A89, 0x9FA5), bn_pack4(0x0BFF, 0x5CB6, 0xF406, 0xB7ED), bn_pack4(0xF44C, 0x42E9, 0xA637, 0xED6B), bn_pack4(0xE485, 0xB576, 0x625E, 0x7EC6), bn_pack4(0x4FE1, 0x356D, 0x6D51, 0xC245), bn_pack4(0x302B, 0x0A6D, 0xF25F, 0x1437), bn_pack4(0xEF95, 0x19B3, 0xCD3A, 0x431B), bn_pack4(0x514A, 0x0879, 0x8E34, 0x04DD), bn_pack4(0x020B, 0xBEA6, 0x3B13, 0x9B22), bn_pack4(0x2902, 0x4E08, 0x8A67, 0xCC74), bn_pack4(0xC4C6, 0x628B, 0x80DC, 0x1CD1), bn_pack4(0xC90F, 0xDAA2, 0x2168, 0xC234), bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF) }; const BIGNUM ossl_bn_group_6144 = { (BN_ULONG *)bn_group_6144_value, OSSL_NELEM(bn_group_6144_value), OSSL_NELEM(bn_group_6144_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_group_8192_value[] = { bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF), bn_pack4(0x60C9, 0x80DD, 0x98ED, 0xD3DF), bn_pack4(0xC81F, 0x56E8, 0x80B9, 0x6E71), bn_pack4(0x9E30, 0x50E2, 0x7656, 0x94DF), bn_pack4(0x9558, 0xE447, 0x5677, 0xE9AA), bn_pack4(0xC919, 0x0DA6, 0xFC02, 0x6E47), bn_pack4(0x889A, 0x002E, 0xD5EE, 0x382B), bn_pack4(0x4009, 0x438B, 0x481C, 0x6CD7), bn_pack4(0x3590, 0x46F4, 0xEB87, 0x9F92), bn_pack4(0xFAF3, 0x6BC3, 0x1ECF, 0xA268), bn_pack4(0xB1D5, 0x10BD, 0x7EE7, 0x4D73), bn_pack4(0xF9AB, 0x4819, 0x5DED, 0x7EA1), bn_pack4(0x64F3, 0x1CC5, 0x0846, 0x851D), bn_pack4(0x4597, 0xE899, 0xA025, 0x5DC1), bn_pack4(0xDF31, 0x0EE0, 0x74AB, 0x6A36), bn_pack4(0x6D2A, 0x13F8, 0x3F44, 0xF82D), bn_pack4(0x062B, 0x3CF5, 0xB3A2, 0x78A6), bn_pack4(0x7968, 0x3303, 0xED5B, 0xDD3A), bn_pack4(0xFA9D, 0x4B7F, 0xA2C0, 0x87E8), bn_pack4(0x4BCB, 0xC886, 0x2F83, 0x85DD), bn_pack4(0x3473, 0xFC64, 0x6CEA, 0x306B), bn_pack4(0x13EB, 0x57A8, 0x1A23, 0xF0C7), bn_pack4(0x2222, 0x2E04, 0xA403, 0x7C07), bn_pack4(0xE3FD, 0xB8BE, 0xFC84, 0x8AD9), bn_pack4(0x238F, 0x16CB, 0xE39D, 0x652D), bn_pack4(0x3423, 0xB474, 0x2BF1, 0xC978), bn_pack4(0x3AAB, 0x639C, 0x5AE4, 0xF568), bn_pack4(0x2576, 0xF693, 0x6BA4, 0x2466), bn_pack4(0x741F, 0xA7BF, 0x8AFC, 0x47ED), bn_pack4(0x3BC8, 0x32B6, 0x8D9D, 0xD300), bn_pack4(0xD8BE, 0xC4D0, 0x73B9, 0x31BA), bn_pack4(0x3877, 0x7CB6, 0xA932, 0xDF8C), bn_pack4(0x74A3, 0x926F, 0x12FE, 0xE5E4), bn_pack4(0xE694, 0xF91E, 0x6DBE, 0x1159), bn_pack4(0x12BF, 0x2D5B, 0x0B74, 0x74D6), bn_pack4(0x043E, 0x8F66, 0x3F48, 0x60EE), bn_pack4(0x387F, 0xE8D7, 0x6E3C, 0x0468), bn_pack4(0xDA56, 0xC9EC, 0x2EF2, 0x9632), bn_pack4(0xEB19, 0xCCB1, 0xA313, 0xD55C), bn_pack4(0xF550, 0xAA3D, 0x8A1F, 0xBFF0), bn_pack4(0x06A1, 0xD58B, 0xB7C5, 0xDA76), bn_pack4(0xA797, 0x15EE, 0xF29B, 0xE328), bn_pack4(0x14CC, 0x5ED2, 0x0F80, 0x37E0), bn_pack4(0xCC8F, 0x6D7E, 0xBF48, 0xE1D8), bn_pack4(0x4BD4, 0x07B2, 0x2B41, 0x54AA), bn_pack4(0x0F1D, 0x45B7, 0xFF58, 0x5AC5), bn_pack4(0x23A9, 0x7A7E, 0x36CC, 0x88BE), bn_pack4(0x59E7, 0xC97F, 0xBEC7, 0xE8F3), bn_pack4(0xB5A8, 0x4031, 0x900B, 0x1C9E), bn_pack4(0xD55E, 0x702F, 0x4698, 0x0C82), bn_pack4(0xF482, 0xD7CE, 0x6E74, 0xFEF6), bn_pack4(0xF032, 0xEA15, 0xD172, 0x1D03), bn_pack4(0x5983, 0xCA01, 0xC64B, 0x92EC), bn_pack4(0x6FB8, 0xF401, 0x378C, 0xD2BF), bn_pack4(0x3320, 0x5151, 0x2BD7, 0xAF42), bn_pack4(0xDB7F, 0x1447, 0xE6CC, 0x254B), bn_pack4(0x44CE, 0x6CBA, 0xCED4, 0xBB1B), bn_pack4(0xDA3E, 0xDBEB, 0xCF9B, 0x14ED), bn_pack4(0x1797, 0x27B0, 0x865A, 0x8918), bn_pack4(0xB06A, 0x53ED, 0x9027, 0xD831), bn_pack4(0xE5DB, 0x382F, 0x4130, 0x01AE), bn_pack4(0xF8FF, 0x9406, 0xAD9E, 0x530E), bn_pack4(0xC975, 0x1E76, 0x3DBA, 0x37BD), bn_pack4(0xC1D4, 0xDCB2, 0x6026, 0x46DE), bn_pack4(0x36C3, 0xFAB4, 0xD27C, 0x7026), bn_pack4(0x4DF4, 0x35C9, 0x3402, 0x8492), bn_pack4(0x86FF, 0xB7DC, 0x90A6, 0xC08F), bn_pack4(0x93B4, 0xEA98, 0x8D8F, 0xDDC1), bn_pack4(0xD006, 0x9127, 0xD5B0, 0x5AA9), bn_pack4(0xB81B, 0xDD76, 0x2170, 0x481C), bn_pack4(0x1F61, 0x2970, 0xCEE2, 0xD7AF), bn_pack4(0x233B, 0xA186, 0x515B, 0xE7ED), bn_pack4(0x99B2, 0x964F, 0xA090, 0xC3A2), bn_pack4(0x287C, 0x5947, 0x4E6B, 0xC05D), bn_pack4(0x2E8E, 0xFC14, 0x1FBE, 0xCAA6), bn_pack4(0xDBBB, 0xC2DB, 0x04DE, 0x8EF9), bn_pack4(0x2583, 0xE9CA, 0x2AD4, 0x4CE8), bn_pack4(0x1A94, 0x6834, 0xB615, 0x0BDA), bn_pack4(0x99C3, 0x2718, 0x6AF4, 0xE23C), bn_pack4(0x8871, 0x9A10, 0xBDBA, 0x5B26), bn_pack4(0x1A72, 0x3C12, 0xA787, 0xE6D7), bn_pack4(0x4B82, 0xD120, 0xA921, 0x0801), bn_pack4(0x43DB, 0x5BFC, 0xE0FD, 0x108E), bn_pack4(0x08E2, 0x4FA0, 0x74E5, 0xAB31), bn_pack4(0x7709, 0x88C0, 0xBAD9, 0x46E2), bn_pack4(0xBBE1, 0x1757, 0x7A61, 0x5D6C), bn_pack4(0x521F, 0x2B18, 0x177B, 0x200C), bn_pack4(0xD876, 0x0273, 0x3EC8, 0x6A64), bn_pack4(0xF12F, 0xFA06, 0xD98A, 0x0864), bn_pack4(0xCEE3, 0xD226, 0x1AD2, 0xEE6B), bn_pack4(0x1E8C, 0x94E0, 0x4A25, 0x619D), bn_pack4(0xABF5, 0xAE8C, 0xDB09, 0x33D7), bn_pack4(0xB397, 0x0F85, 0xA6E1, 0xE4C7), bn_pack4(0x8AEA, 0x7157, 0x5D06, 0x0C7D), bn_pack4(0xECFB, 0x8504, 0x58DB, 0xEF0A), bn_pack4(0xA855, 0x21AB, 0xDF1C, 0xBA64), bn_pack4(0xAD33, 0x170D, 0x0450, 0x7A33), bn_pack4(0x1572, 0x8E5A, 0x8AAA, 0xC42D), bn_pack4(0x15D2, 0x2618, 0x98FA, 0x0510), bn_pack4(0x3995, 0x497C, 0xEA95, 0x6AE5), bn_pack4(0xDE2B, 0xCBF6, 0x9558, 0x1718), bn_pack4(0xB5C5, 0x5DF0, 0x6F4C, 0x52C9), bn_pack4(0x9B27, 0x83A2, 0xEC07, 0xA28F), bn_pack4(0xE39E, 0x772C, 0x180E, 0x8603), bn_pack4(0x3290, 0x5E46, 0x2E36, 0xCE3B), bn_pack4(0xF174, 0x6C08, 0xCA18, 0x217C), bn_pack4(0x670C, 0x354E, 0x4ABC, 0x9804), bn_pack4(0x9ED5, 0x2907, 0x7096, 0x966D), bn_pack4(0x1C62, 0xF356, 0x2085, 0x52BB), bn_pack4(0x8365, 0x5D23, 0xDCA3, 0xAD96), bn_pack4(0x6916, 0x3FA8, 0xFD24, 0xCF5F), bn_pack4(0x98DA, 0x4836, 0x1C55, 0xD39A), bn_pack4(0xC200, 0x7CB8, 0xA163, 0xBF05), bn_pack4(0x4928, 0x6651, 0xECE4, 0x5B3D), bn_pack4(0xAE9F, 0x2411, 0x7C4B, 0x1FE6), bn_pack4(0xEE38, 0x6BFB, 0x5A89, 0x9FA5), bn_pack4(0x0BFF, 0x5CB6, 0xF406, 0xB7ED), bn_pack4(0xF44C, 0x42E9, 0xA637, 0xED6B), bn_pack4(0xE485, 0xB576, 0x625E, 0x7EC6), bn_pack4(0x4FE1, 0x356D, 0x6D51, 0xC245), bn_pack4(0x302B, 0x0A6D, 0xF25F, 0x1437), bn_pack4(0xEF95, 0x19B3, 0xCD3A, 0x431B), bn_pack4(0x514A, 0x0879, 0x8E34, 0x04DD), bn_pack4(0x020B, 0xBEA6, 0x3B13, 0x9B22), bn_pack4(0x2902, 0x4E08, 0x8A67, 0xCC74), bn_pack4(0xC4C6, 0x628B, 0x80DC, 0x1CD1), bn_pack4(0xC90F, 0xDAA2, 0x2168, 0xC234), bn_pack4(0xFFFF, 0xFFFF, 0xFFFF, 0xFFFF) }; const BIGNUM ossl_bn_group_8192 = { (BN_ULONG *)bn_group_8192_value, OSSL_NELEM(bn_group_8192_value), OSSL_NELEM(bn_group_8192_value), 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_generator_19_value[] = { 19 }; const BIGNUM ossl_bn_generator_19 = { (BN_ULONG *)bn_generator_19_value, 1, 1, 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_generator_5_value[] = { 5 }; const BIGNUM ossl_bn_generator_5 = { (BN_ULONG *)bn_generator_5_value, 1, 1, 0, BN_FLG_STATIC_DATA }; static const BN_ULONG bn_generator_2_value[] = { 2 }; const BIGNUM ossl_bn_generator_2 = { (BN_ULONG *)bn_generator_2_value, 1, 1, 0, BN_FLG_STATIC_DATA }; #endif
21,938
39.181319
88
c
openssl
openssl-master/crypto/bn/bn_word.c
/* * 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 "internal/cryptlib.h" #include "bn_local.h" BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w) { #ifndef BN_LLONG BN_ULONG ret = 0; #else BN_ULLONG ret = 0; #endif int i; if (w == 0) return (BN_ULONG)-1; #ifndef BN_LLONG /* * If |w| is too long and we don't have BN_ULLONG then we need to fall * back to using BN_div_word */ if (w > ((BN_ULONG)1 << BN_BITS4)) { BIGNUM *tmp = BN_dup(a); if (tmp == NULL) return (BN_ULONG)-1; ret = BN_div_word(tmp, w); BN_free(tmp); return ret; } #endif bn_check_top(a); w &= BN_MASK2; for (i = a->top - 1; i >= 0; i--) { #ifndef BN_LLONG /* * We can assume here that | w <= ((BN_ULONG)1 << BN_BITS4) | and so * | ret < ((BN_ULONG)1 << BN_BITS4) | and therefore the shifts here are * safe and will not overflow */ ret = ((ret << BN_BITS4) | ((a->d[i] >> BN_BITS4) & BN_MASK2l)) % w; ret = ((ret << BN_BITS4) | (a->d[i] & BN_MASK2l)) % w; #else ret = (BN_ULLONG) (((ret << (BN_ULLONG) BN_BITS2) | a->d[i]) % (BN_ULLONG) w); #endif } return (BN_ULONG)ret; } BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w) { BN_ULONG ret = 0; int i, j; bn_check_top(a); w &= BN_MASK2; if (!w) /* actually this an error (division by zero) */ return (BN_ULONG)-1; if (a->top == 0) return 0; /* normalize input (so bn_div_words doesn't complain) */ j = BN_BITS2 - BN_num_bits_word(w); w <<= j; if (!BN_lshift(a, a, j)) return (BN_ULONG)-1; for (i = a->top - 1; i >= 0; i--) { BN_ULONG l, d; l = a->d[i]; d = bn_div_words(ret, l, w); ret = (l - ((d * w) & BN_MASK2)) & BN_MASK2; a->d[i] = d; } if ((a->top > 0) && (a->d[a->top - 1] == 0)) a->top--; ret >>= j; if (!a->top) a->neg = 0; /* don't allow negative zero */ bn_check_top(a); return ret; } int BN_add_word(BIGNUM *a, BN_ULONG w) { BN_ULONG l; int i; bn_check_top(a); w &= BN_MASK2; /* degenerate case: w is zero */ if (!w) return 1; /* degenerate case: a is zero */ if (BN_is_zero(a)) return BN_set_word(a, w); /* handle 'a' when negative */ if (a->neg) { a->neg = 0; i = BN_sub_word(a, w); if (!BN_is_zero(a)) a->neg = !(a->neg); return i; } for (i = 0; w != 0 && i < a->top; i++) { a->d[i] = l = (a->d[i] + w) & BN_MASK2; w = (w > l) ? 1 : 0; } if (w && i == a->top) { if (bn_wexpand(a, a->top + 1) == NULL) return 0; a->top++; a->d[i] = w; } bn_check_top(a); return 1; } int BN_sub_word(BIGNUM *a, BN_ULONG w) { int i; bn_check_top(a); w &= BN_MASK2; /* degenerate case: w is zero */ if (!w) return 1; /* degenerate case: a is zero */ if (BN_is_zero(a)) { i = BN_set_word(a, w); if (i != 0) BN_set_negative(a, 1); return i; } /* handle 'a' when negative */ if (a->neg) { a->neg = 0; i = BN_add_word(a, w); a->neg = 1; return i; } if ((a->top == 1) && (a->d[0] < w)) { a->d[0] = w - a->d[0]; a->neg = 1; return 1; } i = 0; for (;;) { if (a->d[i] >= w) { a->d[i] -= w; break; } else { a->d[i] = (a->d[i] - w) & BN_MASK2; i++; w = 1; } } if ((a->d[i] == 0) && (i == (a->top - 1))) a->top--; bn_check_top(a); return 1; } int BN_mul_word(BIGNUM *a, BN_ULONG w) { BN_ULONG ll; bn_check_top(a); w &= BN_MASK2; if (a->top) { if (w == 0) BN_zero(a); else { ll = bn_mul_words(a->d, a->d, a->top, w); if (ll) { if (bn_wexpand(a, a->top + 1) == NULL) return 0; a->d[a->top++] = ll; } } } bn_check_top(a); return 1; }
4,512
21.341584
80
c
openssl
openssl-master/crypto/bn/bn_x931p.c
/* * Copyright 2011-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <openssl/bn.h> #include "bn_local.h" /* X9.31 routines for prime derivation */ /* * X9.31 prime derivation. This is used to generate the primes pi (p1, p2, * q1, q2) from a parameter Xpi by checking successive odd integers. */ static int bn_x931_derive_pi(BIGNUM *pi, const BIGNUM *Xpi, BN_CTX *ctx, BN_GENCB *cb) { int i = 0, is_prime; if (!BN_copy(pi, Xpi)) return 0; if (!BN_is_odd(pi) && !BN_add_word(pi, 1)) return 0; for (;;) { i++; BN_GENCB_call(cb, 0, i); /* NB 27 MR is specified in X9.31 */ is_prime = BN_check_prime(pi, ctx, cb); if (is_prime < 0) return 0; if (is_prime) break; if (!BN_add_word(pi, 2)) return 0; } BN_GENCB_call(cb, 2, i); return 1; } /* * This is the main X9.31 prime derivation function. From parameters Xp1, Xp2 * and Xp derive the prime p. If the parameters p1 or p2 are not NULL they * will be returned too: this is needed for testing. */ int BN_X931_derive_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, const BIGNUM *Xp, const BIGNUM *Xp1, const BIGNUM *Xp2, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb) { int ret = 0; BIGNUM *t, *p1p2, *pm1; /* Only even e supported */ if (!BN_is_odd(e)) return 0; BN_CTX_start(ctx); if (p1 == NULL) p1 = BN_CTX_get(ctx); if (p2 == NULL) p2 = BN_CTX_get(ctx); t = BN_CTX_get(ctx); p1p2 = BN_CTX_get(ctx); pm1 = BN_CTX_get(ctx); if (pm1 == NULL) goto err; if (!bn_x931_derive_pi(p1, Xp1, ctx, cb)) goto err; if (!bn_x931_derive_pi(p2, Xp2, ctx, cb)) goto err; if (!BN_mul(p1p2, p1, p2, ctx)) goto err; /* First set p to value of Rp */ if (!BN_mod_inverse(p, p2, p1, ctx)) goto err; if (!BN_mul(p, p, p2, ctx)) goto err; if (!BN_mod_inverse(t, p1, p2, ctx)) goto err; if (!BN_mul(t, t, p1, ctx)) goto err; if (!BN_sub(p, p, t)) goto err; if (p->neg && !BN_add(p, p, p1p2)) goto err; /* p now equals Rp */ if (!BN_mod_sub(p, p, Xp, p1p2, ctx)) goto err; if (!BN_add(p, p, Xp)) goto err; /* p now equals Yp0 */ for (;;) { int i = 1; BN_GENCB_call(cb, 0, i++); if (!BN_copy(pm1, p)) goto err; if (!BN_sub_word(pm1, 1)) goto err; if (!BN_gcd(t, pm1, e, ctx)) goto err; if (BN_is_one(t)) { /* * X9.31 specifies 8 MR and 1 Lucas test or any prime test * offering similar or better guarantees 50 MR is considerably * better. */ int r = BN_check_prime(p, ctx, cb); if (r < 0) goto err; if (r) break; } if (!BN_add(p, p, p1p2)) goto err; } BN_GENCB_call(cb, 3, 0); ret = 1; err: BN_CTX_end(ctx); return ret; } /* * Generate pair of parameters Xp, Xq for X9.31 prime generation. Note: nbits * parameter is sum of number of bits in both. */ int BN_X931_generate_Xpq(BIGNUM *Xp, BIGNUM *Xq, int nbits, BN_CTX *ctx) { BIGNUM *t; int i; /* * Number of bits for each prime is of the form 512+128s for s = 0, 1, * ... */ if ((nbits < 1024) || (nbits & 0xff)) return 0; nbits >>= 1; /* * The random value Xp must be between sqrt(2) * 2^(nbits-1) and 2^nbits * - 1. By setting the top two bits we ensure that the lower bound is * exceeded. */ if (!BN_priv_rand_ex(Xp, nbits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ANY, 0, ctx)) return 0; BN_CTX_start(ctx); t = BN_CTX_get(ctx); if (t == NULL) goto err; for (i = 0; i < 1000; i++) { if (!BN_priv_rand_ex(Xq, nbits, BN_RAND_TOP_TWO, BN_RAND_BOTTOM_ANY, 0, ctx)) goto err; /* Check that |Xp - Xq| > 2^(nbits - 100) */ if (!BN_sub(t, Xp, Xq)) goto err; if (BN_num_bits(t) > (nbits - 100)) break; } BN_CTX_end(ctx); if (i < 1000) return 1; return 0; err: BN_CTX_end(ctx); return 0; } /* * Generate primes using X9.31 algorithm. Of the values p, p1, p2, Xp1 and * Xp2 only 'p' needs to be non-NULL. If any of the others are not NULL the * relevant parameter will be stored in it. Due to the fact that |Xp - Xq| > * 2^(nbits - 100) must be satisfied Xp and Xq are generated using the * previous function and supplied as input. */ int BN_X931_generate_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, BIGNUM *Xp1, BIGNUM *Xp2, const BIGNUM *Xp, const BIGNUM *e, BN_CTX *ctx, BN_GENCB *cb) { int ret = 0; BN_CTX_start(ctx); if (Xp1 == NULL) Xp1 = BN_CTX_get(ctx); if (Xp2 == NULL) Xp2 = BN_CTX_get(ctx); if (Xp1 == NULL || Xp2 == NULL) goto error; if (!BN_priv_rand_ex(Xp1, 101, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY, 0, ctx)) goto error; if (!BN_priv_rand_ex(Xp2, 101, BN_RAND_TOP_ONE, BN_RAND_BOTTOM_ANY, 0, ctx)) goto error; if (!BN_X931_derive_prime_ex(p, p1, p2, Xp, Xp1, Xp2, e, ctx, cb)) goto error; ret = 1; error: BN_CTX_end(ctx); return ret; }
5,975
23
80
c
openssl
openssl-master/crypto/bn/rsaz_exp.c
/* * Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2012, Intel Corporation. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) * (1) Intel Corporation, Israel Development Center, Haifa, Israel * (2) University of Haifa, Israel */ #include <openssl/opensslconf.h> #include "rsaz_exp.h" #ifndef RSAZ_ENABLED NON_EMPTY_TRANSLATION_UNIT #else /* * See crypto/bn/asm/rsaz-avx2.pl for further details. */ void rsaz_1024_norm2red_avx2(void *red, const void *norm); void rsaz_1024_mul_avx2(void *ret, const void *a, const void *b, const void *n, BN_ULONG k); void rsaz_1024_sqr_avx2(void *ret, const void *a, const void *n, BN_ULONG k, int cnt); void rsaz_1024_scatter5_avx2(void *tbl, const void *val, int i); void rsaz_1024_gather5_avx2(void *val, const void *tbl, int i); void rsaz_1024_red2norm_avx2(void *norm, const void *red); #if defined(__GNUC__) # define ALIGN64 __attribute__((aligned(64))) #elif defined(_MSC_VER) # define ALIGN64 __declspec(align(64)) #elif defined(__SUNPRO_C) # define ALIGN64 # pragma align 64(one,two80) #else /* not fatal, might hurt performance a little */ # define ALIGN64 #endif ALIGN64 static const BN_ULONG one[40] = { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; ALIGN64 static const BN_ULONG two80[40] = { 0, 0, 1 << 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; void RSAZ_1024_mod_exp_avx2(BN_ULONG result_norm[16], const BN_ULONG base_norm[16], const BN_ULONG exponent[16], const BN_ULONG m_norm[16], const BN_ULONG RR[16], BN_ULONG k0) { unsigned char storage[320 * 3 + 32 * 9 * 16 + 64]; /* 5.5KB */ unsigned char *p_str = storage + (64 - ((size_t)storage % 64)); unsigned char *a_inv, *m, *result; unsigned char *table_s = p_str + 320 * 3; unsigned char *R2 = table_s; /* borrow */ int index; int wvalue; BN_ULONG tmp[16]; if ((((size_t)p_str & 4095) + 320) >> 12) { result = p_str; a_inv = p_str + 320; m = p_str + 320 * 2; /* should not cross page */ } else { m = p_str; /* should not cross page */ result = p_str + 320; a_inv = p_str + 320 * 2; } rsaz_1024_norm2red_avx2(m, m_norm); rsaz_1024_norm2red_avx2(a_inv, base_norm); rsaz_1024_norm2red_avx2(R2, RR); rsaz_1024_mul_avx2(R2, R2, R2, m, k0); rsaz_1024_mul_avx2(R2, R2, two80, m, k0); /* table[0] = 1 */ rsaz_1024_mul_avx2(result, R2, one, m, k0); /* table[1] = a_inv^1 */ rsaz_1024_mul_avx2(a_inv, a_inv, R2, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 0); rsaz_1024_scatter5_avx2(table_s, a_inv, 1); /* table[2] = a_inv^2 */ rsaz_1024_sqr_avx2(result, a_inv, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 2); #if 0 /* this is almost 2x smaller and less than 1% slower */ for (index = 3; index < 32; index++) { rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, index); } #else /* table[4] = a_inv^4 */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 4); /* table[8] = a_inv^8 */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 8); /* table[16] = a_inv^16 */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 16); /* table[17] = a_inv^17 */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 17); /* table[3] */ rsaz_1024_gather5_avx2(result, table_s, 2); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 3); /* table[6] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 6); /* table[12] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 12); /* table[24] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 24); /* table[25] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 25); /* table[5] */ rsaz_1024_gather5_avx2(result, table_s, 4); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 5); /* table[10] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 10); /* table[20] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 20); /* table[21] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 21); /* table[7] */ rsaz_1024_gather5_avx2(result, table_s, 6); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 7); /* table[14] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 14); /* table[28] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 28); /* table[29] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 29); /* table[9] */ rsaz_1024_gather5_avx2(result, table_s, 8); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 9); /* table[18] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 18); /* table[19] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 19); /* table[11] */ rsaz_1024_gather5_avx2(result, table_s, 10); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 11); /* table[22] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 22); /* table[23] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 23); /* table[13] */ rsaz_1024_gather5_avx2(result, table_s, 12); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 13); /* table[26] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 26); /* table[27] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 27); /* table[15] */ rsaz_1024_gather5_avx2(result, table_s, 14); rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 15); /* table[30] */ rsaz_1024_sqr_avx2(result, result, m, k0, 1); rsaz_1024_scatter5_avx2(table_s, result, 30); /* table[31] */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); rsaz_1024_scatter5_avx2(table_s, result, 31); #endif /* load first window */ p_str = (unsigned char *)exponent; wvalue = p_str[127] >> 3; rsaz_1024_gather5_avx2(result, table_s, wvalue); index = 1014; while (index > -1) { /* loop for the remaining 127 windows */ rsaz_1024_sqr_avx2(result, result, m, k0, 5); wvalue = (p_str[(index / 8) + 1] << 8) | p_str[index / 8]; wvalue = (wvalue >> (index % 8)) & 31; index -= 5; rsaz_1024_gather5_avx2(a_inv, table_s, wvalue); /* borrow a_inv */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); } /* square four times */ rsaz_1024_sqr_avx2(result, result, m, k0, 4); wvalue = p_str[0] & 15; rsaz_1024_gather5_avx2(a_inv, table_s, wvalue); /* borrow a_inv */ rsaz_1024_mul_avx2(result, result, a_inv, m, k0); /* from Montgomery */ rsaz_1024_mul_avx2(result, result, one, m, k0); rsaz_1024_red2norm_avx2(result_norm, result); bn_reduce_once_in_place(result_norm, /*carry=*/0, m_norm, tmp, 16); OPENSSL_cleanse(storage, sizeof(storage)); OPENSSL_cleanse(tmp, sizeof(tmp)); } /* * See crypto/bn/rsaz-x86_64.pl for further details. */ void rsaz_512_mul(void *ret, const void *a, const void *b, const void *n, BN_ULONG k); void rsaz_512_mul_scatter4(void *ret, const void *a, const void *n, BN_ULONG k, const void *tbl, unsigned int power); void rsaz_512_mul_gather4(void *ret, const void *a, const void *tbl, const void *n, BN_ULONG k, unsigned int power); void rsaz_512_mul_by_one(void *ret, const void *a, const void *n, BN_ULONG k); void rsaz_512_sqr(void *ret, const void *a, const void *n, BN_ULONG k, int cnt); void rsaz_512_scatter4(void *tbl, const BN_ULONG *val, int power); void rsaz_512_gather4(BN_ULONG *val, const void *tbl, int power); void RSAZ_512_mod_exp(BN_ULONG result[8], const BN_ULONG base[8], const BN_ULONG exponent[8], const BN_ULONG m[8], BN_ULONG k0, const BN_ULONG RR[8]) { unsigned char storage[16 * 8 * 8 + 64 * 2 + 64]; /* 1.2KB */ unsigned char *table = storage + (64 - ((size_t)storage % 64)); BN_ULONG *a_inv = (BN_ULONG *)(table + 16 * 8 * 8); BN_ULONG *temp = (BN_ULONG *)(table + 16 * 8 * 8 + 8 * 8); unsigned char *p_str = (unsigned char *)exponent; int index; unsigned int wvalue; BN_ULONG tmp[8]; /* table[0] = 1_inv */ temp[0] = 0 - m[0]; temp[1] = ~m[1]; temp[2] = ~m[2]; temp[3] = ~m[3]; temp[4] = ~m[4]; temp[5] = ~m[5]; temp[6] = ~m[6]; temp[7] = ~m[7]; rsaz_512_scatter4(table, temp, 0); /* table [1] = a_inv^1 */ rsaz_512_mul(a_inv, base, RR, m, k0); rsaz_512_scatter4(table, a_inv, 1); /* table [2] = a_inv^2 */ rsaz_512_sqr(temp, a_inv, m, k0, 1); rsaz_512_scatter4(table, temp, 2); for (index = 3; index < 16; index++) rsaz_512_mul_scatter4(temp, a_inv, m, k0, table, index); /* load first window */ wvalue = p_str[63]; rsaz_512_gather4(temp, table, wvalue >> 4); rsaz_512_sqr(temp, temp, m, k0, 4); rsaz_512_mul_gather4(temp, temp, table, m, k0, wvalue & 0xf); for (index = 62; index >= 0; index--) { wvalue = p_str[index]; rsaz_512_sqr(temp, temp, m, k0, 4); rsaz_512_mul_gather4(temp, temp, table, m, k0, wvalue >> 4); rsaz_512_sqr(temp, temp, m, k0, 4); rsaz_512_mul_gather4(temp, temp, table, m, k0, wvalue & 0x0f); } /* from Montgomery */ rsaz_512_mul_by_one(result, temp, m, k0); bn_reduce_once_in_place(result, /*carry=*/0, m, tmp, 8); OPENSSL_cleanse(storage, sizeof(storage)); OPENSSL_cleanse(tmp, sizeof(tmp)); } #endif
11,282
33.824074
78
c
openssl
openssl-master/crypto/bn/rsaz_exp.h
/* * Copyright 2013-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2020, Intel Corporation. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * Originally written by Shay Gueron (1, 2), and Vlad Krasnov (1) * (1) Intel Corporation, Israel Development Center, Haifa, Israel * (2) University of Haifa, Israel */ #ifndef OSSL_CRYPTO_BN_RSAZ_EXP_H # define OSSL_CRYPTO_BN_RSAZ_EXP_H # undef RSAZ_ENABLED # if defined(OPENSSL_BN_ASM_MONT) && \ (defined(__x86_64) || defined(__x86_64__) || \ defined(_M_AMD64) || defined(_M_X64)) # define RSAZ_ENABLED # include <openssl/bn.h> # include "internal/constant_time.h" # include "bn_local.h" void RSAZ_1024_mod_exp_avx2(BN_ULONG result[16], const BN_ULONG base_norm[16], const BN_ULONG exponent[16], const BN_ULONG m_norm[16], const BN_ULONG RR[16], BN_ULONG k0); int rsaz_avx2_eligible(void); void RSAZ_512_mod_exp(BN_ULONG result[8], const BN_ULONG base_norm[8], const BN_ULONG exponent[8], const BN_ULONG m_norm[8], BN_ULONG k0, const BN_ULONG RR[8]); int ossl_rsaz_avx512ifma_eligible(void); int ossl_rsaz_mod_exp_avx512_x2(BN_ULONG *res1, const BN_ULONG *base1, const BN_ULONG *exponent1, const BN_ULONG *m1, const BN_ULONG *RR1, BN_ULONG k0_1, BN_ULONG *res2, const BN_ULONG *base2, const BN_ULONG *exponent2, const BN_ULONG *m2, const BN_ULONG *RR2, BN_ULONG k0_2, int factor_size); static ossl_inline void bn_select_words(BN_ULONG *r, BN_ULONG mask, const BN_ULONG *a, const BN_ULONG *b, size_t num) { size_t i; for (i = 0; i < num; i++) { r[i] = constant_time_select_64(mask, a[i], b[i]); } } static ossl_inline BN_ULONG bn_reduce_once_in_place(BN_ULONG *r, BN_ULONG carry, const BN_ULONG *m, BN_ULONG *tmp, size_t num) { carry -= bn_sub_words(tmp, r, m, num); bn_select_words(r, carry, r /* tmp < 0 */, tmp /* tmp >= 0 */, num); return carry; } # endif #endif
2,933
35.222222
78
h
openssl
openssl-master/crypto/bn/rsaz_exp_x2.c
/* * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright (c) 2020-2021, Intel Corporation. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * * Originally written by Sergey Kirillov and Andrey Matyukov. * Special thanks to Ilya Albrekht for his valuable hints. * Intel Corporation * */ #include <openssl/opensslconf.h> #include <openssl/crypto.h> #include "rsaz_exp.h" #ifndef RSAZ_ENABLED NON_EMPTY_TRANSLATION_UNIT #else # include <assert.h> # include <string.h> # define ALIGN_OF(ptr, boundary) \ ((unsigned char *)(ptr) + (boundary - (((size_t)(ptr)) & (boundary - 1)))) /* Internal radix */ # define DIGIT_SIZE (52) /* 52-bit mask */ # define DIGIT_MASK ((uint64_t)0xFFFFFFFFFFFFF) # define BITS2WORD8_SIZE(x) (((x) + 7) >> 3) # define BITS2WORD64_SIZE(x) (((x) + 63) >> 6) /* Number of registers required to hold |digits_num| amount of qword digits */ # define NUMBER_OF_REGISTERS(digits_num, register_size) \ (((digits_num) * 64 + (register_size) - 1) / (register_size)) static ossl_inline uint64_t get_digit(const uint8_t *in, int in_len); static ossl_inline void put_digit(uint8_t *out, int out_len, uint64_t digit); static void to_words52(BN_ULONG *out, int out_len, const BN_ULONG *in, int in_bitsize); static void from_words52(BN_ULONG *bn_out, int out_bitsize, const BN_ULONG *in); static ossl_inline void set_bit(BN_ULONG *a, int idx); /* Number of |digit_size|-bit digits in |bitsize|-bit value */ static ossl_inline int number_of_digits(int bitsize, int digit_size) { return (bitsize + digit_size - 1) / digit_size; } /* * For details of the methods declared below please refer to * crypto/bn/asm/rsaz-avx512.pl * * Naming conventions: * amm = Almost Montgomery Multiplication * ams = Almost Montgomery Squaring * 52xZZ - data represented as array of ZZ digits in 52-bit radix * _x1_/_x2_ - 1 or 2 independent inputs/outputs * _ifma256 - uses 256-bit wide IFMA ISA (AVX512_IFMA256) */ void ossl_rsaz_amm52x20_x1_ifma256(BN_ULONG *res, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, BN_ULONG k0); void ossl_rsaz_amm52x20_x2_ifma256(BN_ULONG *out, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, const BN_ULONG k0[2]); void ossl_extract_multiplier_2x20_win5(BN_ULONG *red_Y, const BN_ULONG *red_table, int red_table_idx1, int red_table_idx2); void ossl_rsaz_amm52x30_x1_ifma256(BN_ULONG *res, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, BN_ULONG k0); void ossl_rsaz_amm52x30_x2_ifma256(BN_ULONG *out, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, const BN_ULONG k0[2]); void ossl_extract_multiplier_2x30_win5(BN_ULONG *red_Y, const BN_ULONG *red_table, int red_table_idx1, int red_table_idx2); void ossl_rsaz_amm52x40_x1_ifma256(BN_ULONG *res, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, BN_ULONG k0); void ossl_rsaz_amm52x40_x2_ifma256(BN_ULONG *out, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, const BN_ULONG k0[2]); void ossl_extract_multiplier_2x40_win5(BN_ULONG *red_Y, const BN_ULONG *red_table, int red_table_idx1, int red_table_idx2); static int RSAZ_mod_exp_x2_ifma256(BN_ULONG *res, const BN_ULONG *base, const BN_ULONG *exp[2], const BN_ULONG *m, const BN_ULONG *rr, const BN_ULONG k0[2], int modulus_bitsize); /* * Dual Montgomery modular exponentiation using prime moduli of the * same bit size, optimized with AVX512 ISA. * * Input and output parameters for each exponentiation are independent and * denoted here by index |i|, i = 1..2. * * Input and output are all in regular 2^64 radix. * * Each moduli shall be |factor_size| bit size. * * Supported cases: * - 2x1024 * - 2x1536 * - 2x2048 * * [out] res|i| - result of modular exponentiation: array of qword values * in regular (2^64) radix. Size of array shall be enough * to hold |factor_size| bits. * [in] base|i| - base * [in] exp|i| - exponent * [in] m|i| - moduli * [in] rr|i| - Montgomery parameter RR = R^2 mod m|i| * [in] k0_|i| - Montgomery parameter k0 = -1/m|i| mod 2^64 * [in] factor_size - moduli bit size * * \return 0 in case of failure, * 1 in case of success. */ int ossl_rsaz_mod_exp_avx512_x2(BN_ULONG *res1, const BN_ULONG *base1, const BN_ULONG *exp1, const BN_ULONG *m1, const BN_ULONG *rr1, BN_ULONG k0_1, BN_ULONG *res2, const BN_ULONG *base2, const BN_ULONG *exp2, const BN_ULONG *m2, const BN_ULONG *rr2, BN_ULONG k0_2, int factor_size) { typedef void (*AMM)(BN_ULONG *res, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, BN_ULONG k0); int ret = 0; /* * Number of word-size (BN_ULONG) digits to store exponent in redundant * representation. */ int exp_digits = number_of_digits(factor_size + 2, DIGIT_SIZE); int coeff_pow = 4 * (DIGIT_SIZE * exp_digits - factor_size); /* Number of YMM registers required to store exponent's digits */ int ymm_regs_num = NUMBER_OF_REGISTERS(exp_digits, 256 /* ymm bit size */); /* Capacity of the register set (in qwords) to store exponent */ int regs_capacity = ymm_regs_num * 4; BN_ULONG *base1_red, *m1_red, *rr1_red; BN_ULONG *base2_red, *m2_red, *rr2_red; BN_ULONG *coeff_red; BN_ULONG *storage = NULL; BN_ULONG *storage_aligned = NULL; int storage_len_bytes = 7 * regs_capacity * sizeof(BN_ULONG) + 64 /* alignment */; const BN_ULONG *exp[2] = {0}; BN_ULONG k0[2] = {0}; /* AMM = Almost Montgomery Multiplication */ AMM amm = NULL; switch (factor_size) { case 1024: amm = ossl_rsaz_amm52x20_x1_ifma256; break; case 1536: amm = ossl_rsaz_amm52x30_x1_ifma256; break; case 2048: amm = ossl_rsaz_amm52x40_x1_ifma256; break; default: goto err; } storage = (BN_ULONG *)OPENSSL_malloc(storage_len_bytes); if (storage == NULL) goto err; storage_aligned = (BN_ULONG *)ALIGN_OF(storage, 64); /* Memory layout for red(undant) representations */ base1_red = storage_aligned; base2_red = storage_aligned + 1 * regs_capacity; m1_red = storage_aligned + 2 * regs_capacity; m2_red = storage_aligned + 3 * regs_capacity; rr1_red = storage_aligned + 4 * regs_capacity; rr2_red = storage_aligned + 5 * regs_capacity; coeff_red = storage_aligned + 6 * regs_capacity; /* Convert base_i, m_i, rr_i, from regular to 52-bit radix */ to_words52(base1_red, regs_capacity, base1, factor_size); to_words52(base2_red, regs_capacity, base2, factor_size); to_words52(m1_red, regs_capacity, m1, factor_size); to_words52(m2_red, regs_capacity, m2, factor_size); to_words52(rr1_red, regs_capacity, rr1, factor_size); to_words52(rr2_red, regs_capacity, rr2, factor_size); /* * Compute target domain Montgomery converters RR' for each modulus * based on precomputed original domain's RR. * * RR -> RR' transformation steps: * (1) coeff = 2^k * (2) t = AMM(RR,RR) = RR^2 / R' mod m * (3) RR' = AMM(t, coeff) = RR^2 * 2^k / R'^2 mod m * where * k = 4 * (52 * digits52 - modlen) * R = 2^(64 * ceil(modlen/64)) mod m * RR = R^2 mod m * R' = 2^(52 * ceil(modlen/52)) mod m * * EX/ modlen = 1024: k = 64, RR = 2^2048 mod m, RR' = 2^2080 mod m */ memset(coeff_red, 0, exp_digits * sizeof(BN_ULONG)); /* (1) in reduced domain representation */ set_bit(coeff_red, 64 * (int)(coeff_pow / 52) + coeff_pow % 52); amm(rr1_red, rr1_red, rr1_red, m1_red, k0_1); /* (2) for m1 */ amm(rr1_red, rr1_red, coeff_red, m1_red, k0_1); /* (3) for m1 */ amm(rr2_red, rr2_red, rr2_red, m2_red, k0_2); /* (2) for m2 */ amm(rr2_red, rr2_red, coeff_red, m2_red, k0_2); /* (3) for m2 */ exp[0] = exp1; exp[1] = exp2; k0[0] = k0_1; k0[1] = k0_2; /* Dual (2-exps in parallel) exponentiation */ ret = RSAZ_mod_exp_x2_ifma256(rr1_red, base1_red, exp, m1_red, rr1_red, k0, factor_size); if (!ret) goto err; /* Convert rr_i back to regular radix */ from_words52(res1, factor_size, rr1_red); from_words52(res2, factor_size, rr2_red); /* bn_reduce_once_in_place expects number of BN_ULONG, not bit size */ factor_size /= sizeof(BN_ULONG) * 8; bn_reduce_once_in_place(res1, /*carry=*/0, m1, storage, factor_size); bn_reduce_once_in_place(res2, /*carry=*/0, m2, storage, factor_size); err: if (storage != NULL) { OPENSSL_cleanse(storage, storage_len_bytes); OPENSSL_free(storage); } return ret; } /* * Dual {1024,1536,2048}-bit w-ary modular exponentiation using prime moduli of * the same bit size using Almost Montgomery Multiplication, optimized with * AVX512_IFMA256 ISA. * * The parameter w (window size) = 5. * * [out] res - result of modular exponentiation: 2x{20,30,40} qword * values in 2^52 radix. * [in] base - base (2x{20,30,40} qword values in 2^52 radix) * [in] exp - array of 2 pointers to {16,24,32} qword values in 2^64 radix. * Exponent is not converted to redundant representation. * [in] m - moduli (2x{20,30,40} qword values in 2^52 radix) * [in] rr - Montgomery parameter for 2 moduli: * RR(1024) = 2^2080 mod m. * RR(1536) = 2^3120 mod m. * RR(2048) = 2^4160 mod m. * (2x{20,30,40} qword values in 2^52 radix) * [in] k0 - Montgomery parameter for 2 moduli: k0 = -1/m mod 2^64 * * \return (void). */ int RSAZ_mod_exp_x2_ifma256(BN_ULONG *out, const BN_ULONG *base, const BN_ULONG *exp[2], const BN_ULONG *m, const BN_ULONG *rr, const BN_ULONG k0[2], int modulus_bitsize) { typedef void (*DAMM)(BN_ULONG *res, const BN_ULONG *a, const BN_ULONG *b, const BN_ULONG *m, const BN_ULONG k0[2]); typedef void (*DEXTRACT)(BN_ULONG *res, const BN_ULONG *red_table, int red_table_idx, int tbl_idx); int ret = 0; int idx; /* Exponent window size */ int exp_win_size = 5; int exp_win_mask = (1U << exp_win_size) - 1; /* * Number of digits (64-bit words) in redundant representation to handle * modulus bits */ int red_digits = 0; int exp_digits = 0; BN_ULONG *storage = NULL; BN_ULONG *storage_aligned = NULL; int storage_len_bytes = 0; /* Red(undant) result Y and multiplier X */ BN_ULONG *red_Y = NULL; /* [2][red_digits] */ BN_ULONG *red_X = NULL; /* [2][red_digits] */ /* Pre-computed table of base powers */ BN_ULONG *red_table = NULL; /* [1U << exp_win_size][2][red_digits] */ /* Expanded exponent */ BN_ULONG *expz = NULL; /* [2][exp_digits + 1] */ /* Dual AMM */ DAMM damm = NULL; /* Extractor from red_table */ DEXTRACT extract = NULL; /* * Squaring is done using multiplication now. That can be a subject of * optimization in future. */ # define DAMS(r,a,m,k0) damm((r),(a),(a),(m),(k0)) switch (modulus_bitsize) { case 1024: red_digits = 20; exp_digits = 16; damm = ossl_rsaz_amm52x20_x2_ifma256; extract = ossl_extract_multiplier_2x20_win5; break; case 1536: /* Extended with 2 digits padding to avoid mask ops in high YMM register */ red_digits = 30 + 2; exp_digits = 24; damm = ossl_rsaz_amm52x30_x2_ifma256; extract = ossl_extract_multiplier_2x30_win5; break; case 2048: red_digits = 40; exp_digits = 32; damm = ossl_rsaz_amm52x40_x2_ifma256; extract = ossl_extract_multiplier_2x40_win5; break; default: goto err; } storage_len_bytes = (2 * red_digits /* red_Y */ + 2 * red_digits /* red_X */ + 2 * red_digits * (1U << exp_win_size) /* red_table */ + 2 * (exp_digits + 1)) /* expz */ * sizeof(BN_ULONG) + 64; /* alignment */ storage = (BN_ULONG *)OPENSSL_zalloc(storage_len_bytes); if (storage == NULL) goto err; storage_aligned = (BN_ULONG *)ALIGN_OF(storage, 64); red_Y = storage_aligned; red_X = red_Y + 2 * red_digits; red_table = red_X + 2 * red_digits; expz = red_table + 2 * red_digits * (1U << exp_win_size); /* * Compute table of powers base^i, i = 0, ..., (2^EXP_WIN_SIZE) - 1 * table[0] = mont(x^0) = mont(1) * table[1] = mont(x^1) = mont(x) */ red_X[0 * red_digits] = 1; red_X[1 * red_digits] = 1; damm(&red_table[0 * 2 * red_digits], (const BN_ULONG*)red_X, rr, m, k0); damm(&red_table[1 * 2 * red_digits], base, rr, m, k0); for (idx = 1; idx < (int)((1U << exp_win_size) / 2); idx++) { DAMS(&red_table[(2 * idx + 0) * 2 * red_digits], &red_table[(1 * idx) * 2 * red_digits], m, k0); damm(&red_table[(2 * idx + 1) * 2 * red_digits], &red_table[(2 * idx) * 2 * red_digits], &red_table[1 * 2 * red_digits], m, k0); } /* Copy and expand exponents */ memcpy(&expz[0 * (exp_digits + 1)], exp[0], exp_digits * sizeof(BN_ULONG)); expz[1 * (exp_digits + 1) - 1] = 0; memcpy(&expz[1 * (exp_digits + 1)], exp[1], exp_digits * sizeof(BN_ULONG)); expz[2 * (exp_digits + 1) - 1] = 0; /* Exponentiation */ { const int rem = modulus_bitsize % exp_win_size; const BN_ULONG table_idx_mask = exp_win_mask; int exp_bit_no = modulus_bitsize - rem; int exp_chunk_no = exp_bit_no / 64; int exp_chunk_shift = exp_bit_no % 64; BN_ULONG red_table_idx_0, red_table_idx_1; /* * If rem == 0, then * exp_bit_no = modulus_bitsize - exp_win_size * However, this isn't possible because rem is { 1024, 1536, 2048 } % 5 * which is { 4, 1, 3 } respectively. * * If this assertion ever fails the fix above is easy. */ OPENSSL_assert(rem != 0); /* Process 1-st exp window - just init result */ red_table_idx_0 = expz[exp_chunk_no + 0 * (exp_digits + 1)]; red_table_idx_1 = expz[exp_chunk_no + 1 * (exp_digits + 1)]; /* * The function operates with fixed moduli sizes divisible by 64, * thus table index here is always in supported range [0, EXP_WIN_SIZE). */ red_table_idx_0 >>= exp_chunk_shift; red_table_idx_1 >>= exp_chunk_shift; extract(&red_Y[0 * red_digits], (const BN_ULONG*)red_table, (int)red_table_idx_0, (int)red_table_idx_1); /* Process other exp windows */ for (exp_bit_no -= exp_win_size; exp_bit_no >= 0; exp_bit_no -= exp_win_size) { /* Extract pre-computed multiplier from the table */ { BN_ULONG T; exp_chunk_no = exp_bit_no / 64; exp_chunk_shift = exp_bit_no % 64; { red_table_idx_0 = expz[exp_chunk_no + 0 * (exp_digits + 1)]; T = expz[exp_chunk_no + 1 + 0 * (exp_digits + 1)]; red_table_idx_0 >>= exp_chunk_shift; /* * Get additional bits from then next quadword * when 64-bit boundaries are crossed. */ if (exp_chunk_shift > 64 - exp_win_size) { T <<= (64 - exp_chunk_shift); red_table_idx_0 ^= T; } red_table_idx_0 &= table_idx_mask; } { red_table_idx_1 = expz[exp_chunk_no + 1 * (exp_digits + 1)]; T = expz[exp_chunk_no + 1 + 1 * (exp_digits + 1)]; red_table_idx_1 >>= exp_chunk_shift; /* * Get additional bits from then next quadword * when 64-bit boundaries are crossed. */ if (exp_chunk_shift > 64 - exp_win_size) { T <<= (64 - exp_chunk_shift); red_table_idx_1 ^= T; } red_table_idx_1 &= table_idx_mask; } extract(&red_X[0 * red_digits], (const BN_ULONG*)red_table, (int)red_table_idx_0, (int)red_table_idx_1); } /* Series of squaring */ DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); DAMS((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, m, k0); damm((BN_ULONG*)red_Y, (const BN_ULONG*)red_Y, (const BN_ULONG*)red_X, m, k0); } } /* * * NB: After the last AMM of exponentiation in Montgomery domain, the result * may be (modulus_bitsize + 1), but the conversion out of Montgomery domain * performs an AMM(x,1) which guarantees that the final result is less than * |m|, so no conditional subtraction is needed here. See [1] for details. * * [1] Gueron, S. Efficient software implementations of modular exponentiation. * DOI: 10.1007/s13389-012-0031-5 */ /* Convert result back in regular 2^52 domain */ memset(red_X, 0, 2 * red_digits * sizeof(BN_ULONG)); red_X[0 * red_digits] = 1; red_X[1 * red_digits] = 1; damm(out, (const BN_ULONG*)red_Y, (const BN_ULONG*)red_X, m, k0); ret = 1; err: if (storage != NULL) { /* Clear whole storage */ OPENSSL_cleanse(storage, storage_len_bytes); OPENSSL_free(storage); } #undef DAMS return ret; } static ossl_inline uint64_t get_digit(const uint8_t *in, int in_len) { uint64_t digit = 0; assert(in != NULL); assert(in_len <= 8); for (; in_len > 0; in_len--) { digit <<= 8; digit += (uint64_t)(in[in_len - 1]); } return digit; } /* * Convert array of words in regular (base=2^64) representation to array of * words in redundant (base=2^52) one. */ static void to_words52(BN_ULONG *out, int out_len, const BN_ULONG *in, int in_bitsize) { uint8_t *in_str = NULL; assert(out != NULL); assert(in != NULL); /* Check destination buffer capacity */ assert(out_len >= number_of_digits(in_bitsize, DIGIT_SIZE)); in_str = (uint8_t *)in; for (; in_bitsize >= (2 * DIGIT_SIZE); in_bitsize -= (2 * DIGIT_SIZE), out += 2) { uint64_t digit; memcpy(&digit, in_str, sizeof(digit)); out[0] = digit & DIGIT_MASK; in_str += 6; memcpy(&digit, in_str, sizeof(digit)); out[1] = (digit >> 4) & DIGIT_MASK; in_str += 7; out_len -= 2; } if (in_bitsize > DIGIT_SIZE) { uint64_t digit = get_digit(in_str, 7); out[0] = digit & DIGIT_MASK; in_str += 6; in_bitsize -= DIGIT_SIZE; digit = get_digit(in_str, BITS2WORD8_SIZE(in_bitsize)); out[1] = digit >> 4; out += 2; out_len -= 2; } else if (in_bitsize > 0) { out[0] = get_digit(in_str, BITS2WORD8_SIZE(in_bitsize)); out++; out_len--; } while (out_len > 0) { *out = 0; out_len--; out++; } } static ossl_inline void put_digit(uint8_t *out, int out_len, uint64_t digit) { assert(out != NULL); assert(out_len <= 8); for (; out_len > 0; out_len--) { *out++ = (uint8_t)(digit & 0xFF); digit >>= 8; } } /* * Convert array of words in redundant (base=2^52) representation to array of * words in regular (base=2^64) one. */ static void from_words52(BN_ULONG *out, int out_bitsize, const BN_ULONG *in) { int i; int out_len = BITS2WORD64_SIZE(out_bitsize); assert(out != NULL); assert(in != NULL); for (i = 0; i < out_len; i++) out[i] = 0; { uint8_t *out_str = (uint8_t *)out; for (; out_bitsize >= (2 * DIGIT_SIZE); out_bitsize -= (2 * DIGIT_SIZE), in += 2) { uint64_t digit; digit = in[0]; memcpy(out_str, &digit, sizeof(digit)); out_str += 6; digit = digit >> 48 | in[1] << 4; memcpy(out_str, &digit, sizeof(digit)); out_str += 7; } if (out_bitsize > DIGIT_SIZE) { put_digit(out_str, 7, in[0]); out_str += 6; out_bitsize -= DIGIT_SIZE; put_digit(out_str, BITS2WORD8_SIZE(out_bitsize), (in[1] << 4 | in[0] >> 48)); } else if (out_bitsize) { put_digit(out_str, BITS2WORD8_SIZE(out_bitsize), in[0]); } } } /* * Set bit at index |idx| in the words array |a|. * It does not do any boundaries checks, make sure the index is valid before * calling the function. */ static ossl_inline void set_bit(BN_ULONG *a, int idx) { assert(a != NULL); { int i, j; i = idx / BN_BITS2; j = idx % BN_BITS2; a[i] |= (((BN_ULONG)1) << j); } } #endif
23,186
34.238602
120
c
openssl
openssl-master/crypto/bn/asm/x86_64-gcc.c
/* * Copyright 2002-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 "../bn_local.h" #if !(defined(__GNUC__) && __GNUC__>=2) # include "../bn_asm.c" /* kind of dirty hack for Sun Studio */ #else /*- * x86_64 BIGNUM accelerator version 0.1, December 2002. * * Implemented by Andy Polyakov <[email protected]> for the OpenSSL * project. * * Rights for redistribution and usage in source and binary forms are * granted according to the License. Warranty of any kind is disclaimed. * * Q. Version 0.1? It doesn't sound like Andy, he used to assign real * versions, like 1.0... * A. Well, that's because this code is basically a quick-n-dirty * proof-of-concept hack. As you can see it's implemented with * inline assembler, which means that you're bound to GCC and that * there might be enough room for further improvement. * * Q. Why inline assembler? * A. x86_64 features own ABI which I'm not familiar with. This is * why I decided to let the compiler take care of subroutine * prologue/epilogue as well as register allocation. For reference. * Win64 implements different ABI for AMD64, different from Linux. * * Q. How much faster does it get? * A. 'apps/openssl speed rsa dsa' output with no-asm: * * sign verify sign/s verify/s * rsa 512 bits 0.0006s 0.0001s 1683.8 18456.2 * rsa 1024 bits 0.0028s 0.0002s 356.0 6407.0 * rsa 2048 bits 0.0172s 0.0005s 58.0 1957.8 * rsa 4096 bits 0.1155s 0.0018s 8.7 555.6 * sign verify sign/s verify/s * dsa 512 bits 0.0005s 0.0006s 2100.8 1768.3 * dsa 1024 bits 0.0014s 0.0018s 692.3 559.2 * dsa 2048 bits 0.0049s 0.0061s 204.7 165.0 * * 'apps/openssl speed rsa dsa' output with this module: * * sign verify sign/s verify/s * rsa 512 bits 0.0004s 0.0000s 2767.1 33297.9 * rsa 1024 bits 0.0012s 0.0001s 867.4 14674.7 * rsa 2048 bits 0.0061s 0.0002s 164.0 5270.0 * rsa 4096 bits 0.0384s 0.0006s 26.1 1650.8 * sign verify sign/s verify/s * dsa 512 bits 0.0002s 0.0003s 4442.2 3786.3 * dsa 1024 bits 0.0005s 0.0007s 1835.1 1497.4 * dsa 2048 bits 0.0016s 0.0020s 620.4 504.6 * * For the reference. IA-32 assembler implementation performs * very much like 64-bit code compiled with no-asm on the same * machine. */ # undef mul # undef mul_add /*- * "m"(a), "+m"(r) is the way to favor DirectPath µ-code; * "g"(0) let the compiler to decide where does it * want to keep the value of zero; */ # define mul_add(r,a,word,carry) do { \ register BN_ULONG high,low; \ asm ("mulq %3" \ : "=a"(low),"=d"(high) \ : "a"(word),"m"(a) \ : "cc"); \ asm ("addq %2,%0; adcq %3,%1" \ : "+r"(carry),"+d"(high)\ : "a"(low),"g"(0) \ : "cc"); \ asm ("addq %2,%0; adcq %3,%1" \ : "+m"(r),"+d"(high) \ : "r"(carry),"g"(0) \ : "cc"); \ carry=high; \ } while (0) # define mul(r,a,word,carry) do { \ register BN_ULONG high,low; \ asm ("mulq %3" \ : "=a"(low),"=d"(high) \ : "a"(word),"g"(a) \ : "cc"); \ asm ("addq %2,%0; adcq %3,%1" \ : "+r"(carry),"+d"(high)\ : "a"(low),"g"(0) \ : "cc"); \ (r)=carry, carry=high; \ } while (0) # undef sqr # define sqr(r0,r1,a) \ asm ("mulq %2" \ : "=a"(r0),"=d"(r1) \ : "a"(a) \ : "cc"); BN_ULONG bn_mul_add_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) { BN_ULONG c1 = 0; if (num <= 0) return c1; while (num & ~3) { mul_add(rp[0], ap[0], w, c1); mul_add(rp[1], ap[1], w, c1); mul_add(rp[2], ap[2], w, c1); mul_add(rp[3], ap[3], w, c1); ap += 4; rp += 4; num -= 4; } if (num) { mul_add(rp[0], ap[0], w, c1); if (--num == 0) return c1; mul_add(rp[1], ap[1], w, c1); if (--num == 0) return c1; mul_add(rp[2], ap[2], w, c1); return c1; } return c1; } BN_ULONG bn_mul_words(BN_ULONG *rp, const BN_ULONG *ap, int num, BN_ULONG w) { BN_ULONG c1 = 0; if (num <= 0) return c1; while (num & ~3) { mul(rp[0], ap[0], w, c1); mul(rp[1], ap[1], w, c1); mul(rp[2], ap[2], w, c1); mul(rp[3], ap[3], w, c1); ap += 4; rp += 4; num -= 4; } if (num) { mul(rp[0], ap[0], w, c1); if (--num == 0) return c1; mul(rp[1], ap[1], w, c1); if (--num == 0) return c1; mul(rp[2], ap[2], w, c1); } return c1; } void bn_sqr_words(BN_ULONG *r, const BN_ULONG *a, int n) { if (n <= 0) return; while (n & ~3) { sqr(r[0], r[1], a[0]); sqr(r[2], r[3], a[1]); sqr(r[4], r[5], a[2]); sqr(r[6], r[7], a[3]); a += 4; r += 8; n -= 4; } if (n) { sqr(r[0], r[1], a[0]); if (--n == 0) return; sqr(r[2], r[3], a[1]); if (--n == 0) return; sqr(r[4], r[5], a[2]); } } BN_ULONG bn_div_words(BN_ULONG h, BN_ULONG l, BN_ULONG d) { BN_ULONG ret, waste; asm("divq %4":"=a"(ret), "=d"(waste) : "a"(l), "d"(h), "r"(d) : "cc"); return ret; } BN_ULONG bn_add_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, int n) { BN_ULONG ret; size_t i = 0; if (n <= 0) return 0; asm volatile (" subq %0,%0 \n" /* clear carry */ " jmp 1f \n" ".p2align 4 \n" "1: movq (%4,%2,8),%0 \n" " adcq (%5,%2,8),%0 \n" " movq %0,(%3,%2,8) \n" " lea 1(%2),%2 \n" " dec %1 \n" " jnz 1b \n" " sbbq %0,%0 \n" :"=&r" (ret), "+c"(n), "+r"(i) :"r"(rp), "r"(ap), "r"(bp) :"cc", "memory"); return ret & 1; } # ifndef SIMICS BN_ULONG bn_sub_words(BN_ULONG *rp, const BN_ULONG *ap, const BN_ULONG *bp, int n) { BN_ULONG ret; size_t i = 0; if (n <= 0) return 0; asm volatile (" subq %0,%0 \n" /* clear borrow */ " jmp 1f \n" ".p2align 4 \n" "1: movq (%4,%2,8),%0 \n" " sbbq (%5,%2,8),%0 \n" " movq %0,(%3,%2,8) \n" " lea 1(%2),%2 \n" " dec %1 \n" " jnz 1b \n" " sbbq %0,%0 \n" :"=&r" (ret), "+c"(n), "+r"(i) :"r"(rp), "r"(ap), "r"(bp) :"cc", "memory"); return ret & 1; } # else /* Simics 1.4<7 has buggy sbbq:-( */ # define BN_MASK2 0xffffffffffffffffL BN_ULONG bn_sub_words(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b, int n) { BN_ULONG t1, t2; int c = 0; if (n <= 0) return (BN_ULONG)0; for (;;) { t1 = a[0]; t2 = b[0]; r[0] = (t1 - t2 - c) & BN_MASK2; if (t1 != t2) c = (t1 < t2); if (--n <= 0) break; t1 = a[1]; t2 = b[1]; r[1] = (t1 - t2 - c) & BN_MASK2; if (t1 != t2) c = (t1 < t2); if (--n <= 0) break; t1 = a[2]; t2 = b[2]; r[2] = (t1 - t2 - c) & BN_MASK2; if (t1 != t2) c = (t1 < t2); if (--n <= 0) break; t1 = a[3]; t2 = b[3]; r[3] = (t1 - t2 - c) & BN_MASK2; if (t1 != t2) c = (t1 < t2); if (--n <= 0) break; a += 4; b += 4; r += 4; } return c; } # endif /* mul_add_c(a,b,c0,c1,c2) -- c+=a*b for three word number c=(c2,c1,c0) */ /* mul_add_c2(a,b,c0,c1,c2) -- c+=2*a*b for three word number c=(c2,c1,c0) */ /* sqr_add_c(a,i,c0,c1,c2) -- c+=a[i]^2 for three word number c=(c2,c1,c0) */ /* * sqr_add_c2(a,i,c0,c1,c2) -- c+=2*a[i]*a[j] for three word number * c=(c2,c1,c0) */ /* * Keep in mind that carrying into high part of multiplication result * can not overflow, because it cannot be all-ones. */ # if 0 /* original macros are kept for reference purposes */ # define mul_add_c(a,b,c0,c1,c2) do { \ BN_ULONG ta = (a), tb = (b); \ BN_ULONG lo, hi; \ BN_UMULT_LOHI(lo,hi,ta,tb); \ c0 += lo; hi += (c0<lo)?1:0; \ c1 += hi; c2 += (c1<hi)?1:0; \ } while(0) # define mul_add_c2(a,b,c0,c1,c2) do { \ BN_ULONG ta = (a), tb = (b); \ BN_ULONG lo, hi, tt; \ BN_UMULT_LOHI(lo,hi,ta,tb); \ c0 += lo; tt = hi+((c0<lo)?1:0); \ c1 += tt; c2 += (c1<tt)?1:0; \ c0 += lo; hi += (c0<lo)?1:0; \ c1 += hi; c2 += (c1<hi)?1:0; \ } while(0) # define sqr_add_c(a,i,c0,c1,c2) do { \ BN_ULONG ta = (a)[i]; \ BN_ULONG lo, hi; \ BN_UMULT_LOHI(lo,hi,ta,ta); \ c0 += lo; hi += (c0<lo)?1:0; \ c1 += hi; c2 += (c1<hi)?1:0; \ } while(0) # else # define mul_add_c(a,b,c0,c1,c2) do { \ BN_ULONG t1,t2; \ asm ("mulq %3" \ : "=a"(t1),"=d"(t2) \ : "a"(a),"m"(b) \ : "cc"); \ asm ("addq %3,%0; adcq %4,%1; adcq %5,%2" \ : "+r"(c0),"+r"(c1),"+r"(c2) \ : "r"(t1),"r"(t2),"g"(0) \ : "cc"); \ } while (0) # define sqr_add_c(a,i,c0,c1,c2) do { \ BN_ULONG t1,t2; \ asm ("mulq %2" \ : "=a"(t1),"=d"(t2) \ : "a"(a[i]) \ : "cc"); \ asm ("addq %3,%0; adcq %4,%1; adcq %5,%2" \ : "+r"(c0),"+r"(c1),"+r"(c2) \ : "r"(t1),"r"(t2),"g"(0) \ : "cc"); \ } while (0) # define mul_add_c2(a,b,c0,c1,c2) do { \ BN_ULONG t1,t2; \ asm ("mulq %3" \ : "=a"(t1),"=d"(t2) \ : "a"(a),"m"(b) \ : "cc"); \ asm ("addq %3,%0; adcq %4,%1; adcq %5,%2" \ : "+r"(c0),"+r"(c1),"+r"(c2) \ : "r"(t1),"r"(t2),"g"(0) \ : "cc"); \ asm ("addq %3,%0; adcq %4,%1; adcq %5,%2" \ : "+r"(c0),"+r"(c1),"+r"(c2) \ : "r"(t1),"r"(t2),"g"(0) \ : "cc"); \ } while (0) # endif # define sqr_add_c2(a,i,j,c0,c1,c2) \ mul_add_c2((a)[i],(a)[j],c0,c1,c2) void bn_mul_comba8(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG c1, c2, c3; c1 = 0; c2 = 0; c3 = 0; mul_add_c(a[0], b[0], c1, c2, c3); r[0] = c1; c1 = 0; mul_add_c(a[0], b[1], c2, c3, c1); mul_add_c(a[1], b[0], c2, c3, c1); r[1] = c2; c2 = 0; mul_add_c(a[2], b[0], c3, c1, c2); mul_add_c(a[1], b[1], c3, c1, c2); mul_add_c(a[0], b[2], c3, c1, c2); r[2] = c3; c3 = 0; mul_add_c(a[0], b[3], c1, c2, c3); mul_add_c(a[1], b[2], c1, c2, c3); mul_add_c(a[2], b[1], c1, c2, c3); mul_add_c(a[3], b[0], c1, c2, c3); r[3] = c1; c1 = 0; mul_add_c(a[4], b[0], c2, c3, c1); mul_add_c(a[3], b[1], c2, c3, c1); mul_add_c(a[2], b[2], c2, c3, c1); mul_add_c(a[1], b[3], c2, c3, c1); mul_add_c(a[0], b[4], c2, c3, c1); r[4] = c2; c2 = 0; mul_add_c(a[0], b[5], c3, c1, c2); mul_add_c(a[1], b[4], c3, c1, c2); mul_add_c(a[2], b[3], c3, c1, c2); mul_add_c(a[3], b[2], c3, c1, c2); mul_add_c(a[4], b[1], c3, c1, c2); mul_add_c(a[5], b[0], c3, c1, c2); r[5] = c3; c3 = 0; mul_add_c(a[6], b[0], c1, c2, c3); mul_add_c(a[5], b[1], c1, c2, c3); mul_add_c(a[4], b[2], c1, c2, c3); mul_add_c(a[3], b[3], c1, c2, c3); mul_add_c(a[2], b[4], c1, c2, c3); mul_add_c(a[1], b[5], c1, c2, c3); mul_add_c(a[0], b[6], c1, c2, c3); r[6] = c1; c1 = 0; mul_add_c(a[0], b[7], c2, c3, c1); mul_add_c(a[1], b[6], c2, c3, c1); mul_add_c(a[2], b[5], c2, c3, c1); mul_add_c(a[3], b[4], c2, c3, c1); mul_add_c(a[4], b[3], c2, c3, c1); mul_add_c(a[5], b[2], c2, c3, c1); mul_add_c(a[6], b[1], c2, c3, c1); mul_add_c(a[7], b[0], c2, c3, c1); r[7] = c2; c2 = 0; mul_add_c(a[7], b[1], c3, c1, c2); mul_add_c(a[6], b[2], c3, c1, c2); mul_add_c(a[5], b[3], c3, c1, c2); mul_add_c(a[4], b[4], c3, c1, c2); mul_add_c(a[3], b[5], c3, c1, c2); mul_add_c(a[2], b[6], c3, c1, c2); mul_add_c(a[1], b[7], c3, c1, c2); r[8] = c3; c3 = 0; mul_add_c(a[2], b[7], c1, c2, c3); mul_add_c(a[3], b[6], c1, c2, c3); mul_add_c(a[4], b[5], c1, c2, c3); mul_add_c(a[5], b[4], c1, c2, c3); mul_add_c(a[6], b[3], c1, c2, c3); mul_add_c(a[7], b[2], c1, c2, c3); r[9] = c1; c1 = 0; mul_add_c(a[7], b[3], c2, c3, c1); mul_add_c(a[6], b[4], c2, c3, c1); mul_add_c(a[5], b[5], c2, c3, c1); mul_add_c(a[4], b[6], c2, c3, c1); mul_add_c(a[3], b[7], c2, c3, c1); r[10] = c2; c2 = 0; mul_add_c(a[4], b[7], c3, c1, c2); mul_add_c(a[5], b[6], c3, c1, c2); mul_add_c(a[6], b[5], c3, c1, c2); mul_add_c(a[7], b[4], c3, c1, c2); r[11] = c3; c3 = 0; mul_add_c(a[7], b[5], c1, c2, c3); mul_add_c(a[6], b[6], c1, c2, c3); mul_add_c(a[5], b[7], c1, c2, c3); r[12] = c1; c1 = 0; mul_add_c(a[6], b[7], c2, c3, c1); mul_add_c(a[7], b[6], c2, c3, c1); r[13] = c2; c2 = 0; mul_add_c(a[7], b[7], c3, c1, c2); r[14] = c3; r[15] = c1; } void bn_mul_comba4(BN_ULONG *r, BN_ULONG *a, BN_ULONG *b) { BN_ULONG c1, c2, c3; c1 = 0; c2 = 0; c3 = 0; mul_add_c(a[0], b[0], c1, c2, c3); r[0] = c1; c1 = 0; mul_add_c(a[0], b[1], c2, c3, c1); mul_add_c(a[1], b[0], c2, c3, c1); r[1] = c2; c2 = 0; mul_add_c(a[2], b[0], c3, c1, c2); mul_add_c(a[1], b[1], c3, c1, c2); mul_add_c(a[0], b[2], c3, c1, c2); r[2] = c3; c3 = 0; mul_add_c(a[0], b[3], c1, c2, c3); mul_add_c(a[1], b[2], c1, c2, c3); mul_add_c(a[2], b[1], c1, c2, c3); mul_add_c(a[3], b[0], c1, c2, c3); r[3] = c1; c1 = 0; mul_add_c(a[3], b[1], c2, c3, c1); mul_add_c(a[2], b[2], c2, c3, c1); mul_add_c(a[1], b[3], c2, c3, c1); r[4] = c2; c2 = 0; mul_add_c(a[2], b[3], c3, c1, c2); mul_add_c(a[3], b[2], c3, c1, c2); r[5] = c3; c3 = 0; mul_add_c(a[3], b[3], c1, c2, c3); r[6] = c1; r[7] = c2; } void bn_sqr_comba8(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG c1, c2, c3; c1 = 0; c2 = 0; c3 = 0; sqr_add_c(a, 0, c1, c2, c3); r[0] = c1; c1 = 0; sqr_add_c2(a, 1, 0, c2, c3, c1); r[1] = c2; c2 = 0; sqr_add_c(a, 1, c3, c1, c2); sqr_add_c2(a, 2, 0, c3, c1, c2); r[2] = c3; c3 = 0; sqr_add_c2(a, 3, 0, c1, c2, c3); sqr_add_c2(a, 2, 1, c1, c2, c3); r[3] = c1; c1 = 0; sqr_add_c(a, 2, c2, c3, c1); sqr_add_c2(a, 3, 1, c2, c3, c1); sqr_add_c2(a, 4, 0, c2, c3, c1); r[4] = c2; c2 = 0; sqr_add_c2(a, 5, 0, c3, c1, c2); sqr_add_c2(a, 4, 1, c3, c1, c2); sqr_add_c2(a, 3, 2, c3, c1, c2); r[5] = c3; c3 = 0; sqr_add_c(a, 3, c1, c2, c3); sqr_add_c2(a, 4, 2, c1, c2, c3); sqr_add_c2(a, 5, 1, c1, c2, c3); sqr_add_c2(a, 6, 0, c1, c2, c3); r[6] = c1; c1 = 0; sqr_add_c2(a, 7, 0, c2, c3, c1); sqr_add_c2(a, 6, 1, c2, c3, c1); sqr_add_c2(a, 5, 2, c2, c3, c1); sqr_add_c2(a, 4, 3, c2, c3, c1); r[7] = c2; c2 = 0; sqr_add_c(a, 4, c3, c1, c2); sqr_add_c2(a, 5, 3, c3, c1, c2); sqr_add_c2(a, 6, 2, c3, c1, c2); sqr_add_c2(a, 7, 1, c3, c1, c2); r[8] = c3; c3 = 0; sqr_add_c2(a, 7, 2, c1, c2, c3); sqr_add_c2(a, 6, 3, c1, c2, c3); sqr_add_c2(a, 5, 4, c1, c2, c3); r[9] = c1; c1 = 0; sqr_add_c(a, 5, c2, c3, c1); sqr_add_c2(a, 6, 4, c2, c3, c1); sqr_add_c2(a, 7, 3, c2, c3, c1); r[10] = c2; c2 = 0; sqr_add_c2(a, 7, 4, c3, c1, c2); sqr_add_c2(a, 6, 5, c3, c1, c2); r[11] = c3; c3 = 0; sqr_add_c(a, 6, c1, c2, c3); sqr_add_c2(a, 7, 5, c1, c2, c3); r[12] = c1; c1 = 0; sqr_add_c2(a, 7, 6, c2, c3, c1); r[13] = c2; c2 = 0; sqr_add_c(a, 7, c3, c1, c2); r[14] = c3; r[15] = c1; } void bn_sqr_comba4(BN_ULONG *r, const BN_ULONG *a) { BN_ULONG c1, c2, c3; c1 = 0; c2 = 0; c3 = 0; sqr_add_c(a, 0, c1, c2, c3); r[0] = c1; c1 = 0; sqr_add_c2(a, 1, 0, c2, c3, c1); r[1] = c2; c2 = 0; sqr_add_c(a, 1, c3, c1, c2); sqr_add_c2(a, 2, 0, c3, c1, c2); r[2] = c3; c3 = 0; sqr_add_c2(a, 3, 0, c1, c2, c3); sqr_add_c2(a, 2, 1, c1, c2, c3); r[3] = c1; c1 = 0; sqr_add_c(a, 2, c2, c3, c1); sqr_add_c2(a, 3, 1, c2, c3, c1); r[4] = c2; c2 = 0; sqr_add_c2(a, 3, 2, c3, c1, c2); r[5] = c3; c3 = 0; sqr_add_c(a, 3, c1, c2, c3); r[6] = c1; r[7] = c2; } #endif
19,041
28.614308
78
c
openssl
openssl-master/crypto/buffer/buf_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/buffererr.h> #include "crypto/buffererr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA BUF_str_reasons[] = { {0, NULL} }; #endif int ossl_err_load_BUF_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(BUF_str_reasons[0].error) == NULL) ERR_load_strings_const(BUF_str_reasons); #endif return 1; }
767
23.774194
74
c
openssl
openssl-master/crypto/buffer/buffer.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> /* * LIMIT_BEFORE_EXPANSION is the maximum n such that (n+3)/3*4 < 2**31. That * function is applied in several functions in this file and this limit * ensures that the result fits in an int. */ #define LIMIT_BEFORE_EXPANSION 0x5ffffffc BUF_MEM *BUF_MEM_new_ex(unsigned long flags) { BUF_MEM *ret; ret = BUF_MEM_new(); if (ret != NULL) ret->flags = flags; return ret; } BUF_MEM *BUF_MEM_new(void) { BUF_MEM *ret; ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; return ret; } void BUF_MEM_free(BUF_MEM *a) { if (a == NULL) return; if (a->data != NULL) { if (a->flags & BUF_MEM_FLAG_SECURE) OPENSSL_secure_clear_free(a->data, a->max); else OPENSSL_clear_free(a->data, a->max); } OPENSSL_free(a); } /* Allocate a block of secure memory; copy over old data if there * was any, and then free it. */ static char *sec_alloc_realloc(BUF_MEM *str, size_t len) { char *ret; ret = OPENSSL_secure_malloc(len); if (str->data != NULL) { if (ret != NULL) { memcpy(ret, str->data, str->length); OPENSSL_secure_clear_free(str->data, str->length); str->data = NULL; } } return ret; } size_t BUF_MEM_grow(BUF_MEM *str, size_t len) { char *ret; size_t n; if (str->length >= len) { str->length = len; return len; } if (str->max >= len) { if (str->data != NULL) memset(&str->data[str->length], 0, len - str->length); str->length = len; return len; } /* This limit is sufficient to ensure (len+3)/3*4 < 2**31 */ if (len > LIMIT_BEFORE_EXPANSION) { ERR_raise(ERR_LIB_BUF, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } n = (len + 3) / 3 * 4; if ((str->flags & BUF_MEM_FLAG_SECURE)) ret = sec_alloc_realloc(str, n); else ret = OPENSSL_realloc(str->data, n); if (ret == NULL) { len = 0; } else { str->data = ret; str->max = n; memset(&str->data[str->length], 0, len - str->length); str->length = len; } return len; } size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len) { char *ret; size_t n; if (str->length >= len) { if (str->data != NULL) memset(&str->data[len], 0, str->length - len); str->length = len; return len; } if (str->max >= len) { memset(&str->data[str->length], 0, len - str->length); str->length = len; return len; } /* This limit is sufficient to ensure (len+3)/3*4 < 2**31 */ if (len > LIMIT_BEFORE_EXPANSION) { ERR_raise(ERR_LIB_BUF, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } n = (len + 3) / 3 * 4; if ((str->flags & BUF_MEM_FLAG_SECURE)) ret = sec_alloc_realloc(str, n); else ret = OPENSSL_clear_realloc(str->data, str->max, n); if (ret == NULL) { len = 0; } else { str->data = ret; str->max = n; memset(&str->data[str->length], 0, len - str->length); str->length = len; } return len; } void BUF_reverse(unsigned char *out, const unsigned char *in, size_t size) { size_t i; if (in) { out += size - 1; for (i = 0; i < size; i++) *out-- = *in++; } else { unsigned char *q; char c; q = out + size - 1; for (i = 0; i < size / 2; i++) { c = *q; *q-- = *out; *out++ = c; } } }
4,002
23.709877
76
c
openssl
openssl-master/crypto/camellia/cmll_cbc.c
/* * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Camellia low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/camellia.h> #include <openssl/modes.h> void Camellia_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t len, const CAMELLIA_KEY *key, unsigned char *ivec, const int enc) { if (enc) CRYPTO_cbc128_encrypt(in, out, len, key, ivec, (block128_f) Camellia_encrypt); else CRYPTO_cbc128_decrypt(in, out, len, key, ivec, (block128_f) Camellia_decrypt); }
985
30.806452
74
c
openssl
openssl-master/crypto/camellia/cmll_cfb.c
/* * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Camellia low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/camellia.h> #include <openssl/modes.h> /* * The input and output encrypted as though 128bit cfb mode is being used. * The extra state information to record how much of the 128bit block we have * used is contained in *num; */ void Camellia_cfb128_encrypt(const unsigned char *in, unsigned char *out, size_t length, const CAMELLIA_KEY *key, unsigned char *ivec, int *num, const int enc) { CRYPTO_cfb128_encrypt(in, out, length, key, ivec, num, enc, (block128_f) Camellia_encrypt); } /* N.B. This expects the input to be packed, MS bit first */ void Camellia_cfb1_encrypt(const unsigned char *in, unsigned char *out, size_t length, const CAMELLIA_KEY *key, unsigned char *ivec, int *num, const int enc) { CRYPTO_cfb128_1_encrypt(in, out, length, key, ivec, num, enc, (block128_f) Camellia_encrypt); } void Camellia_cfb8_encrypt(const unsigned char *in, unsigned char *out, size_t length, const CAMELLIA_KEY *key, unsigned char *ivec, int *num, const int enc) { CRYPTO_cfb128_8_encrypt(in, out, length, key, ivec, num, enc, (block128_f) Camellia_encrypt); }
1,811
35.24
77
c
openssl
openssl-master/crypto/camellia/cmll_ctr.c
/* * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Camellia low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/camellia.h> #include <openssl/modes.h> void Camellia_ctr128_encrypt(const unsigned char *in, unsigned char *out, size_t length, const CAMELLIA_KEY *key, unsigned char ivec[CAMELLIA_BLOCK_SIZE], unsigned char ecount_buf[CAMELLIA_BLOCK_SIZE], unsigned int *num) { CRYPTO_ctr128_encrypt(in, out, length, key, ivec, ecount_buf, num, (block128_f) Camellia_encrypt); }
999
33.482759
75
c
openssl
openssl-master/crypto/camellia/cmll_ecb.c
/* * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Camellia low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/camellia.h> #include "cmll_local.h" void Camellia_ecb_encrypt(const unsigned char *in, unsigned char *out, const CAMELLIA_KEY *key, const int enc) { if (CAMELLIA_ENCRYPT == enc) Camellia_encrypt(in, out, key); else Camellia_decrypt(in, out, key); }
788
28.222222
74
c
openssl
openssl-master/crypto/camellia/cmll_local.h
/* * 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 */ /* ==================================================================== * Copyright 2006 NTT (Nippon Telegraph and Telephone Corporation) . * ALL RIGHTS RESERVED. * * Intellectual Property information for Camellia: * http://info.isl.ntt.co.jp/crypt/eng/info/chiteki.html * * News Release for Announcement of Camellia open source: * http://www.ntt.co.jp/news/news06e/0604/060413a.html * * The Camellia Code included herein is developed by * NTT (Nippon Telegraph and Telephone Corporation), and is contributed * to the OpenSSL project. */ #ifndef OSSL_CRYPTO_CAMELLIA_CMLL_LOCAL_H # define OSSL_CRYPTO_CAMELLIA_CMLL_LOCAL_H typedef unsigned int u32; typedef unsigned char u8; int Camellia_Ekeygen(int keyBitLength, const u8 *rawKey, KEY_TABLE_TYPE keyTable); void Camellia_EncryptBlock_Rounds(int grandRounds, const u8 plaintext[], const KEY_TABLE_TYPE keyTable, u8 ciphertext[]); void Camellia_DecryptBlock_Rounds(int grandRounds, const u8 ciphertext[], const KEY_TABLE_TYPE keyTable, u8 plaintext[]); void Camellia_EncryptBlock(int keyBitLength, const u8 plaintext[], const KEY_TABLE_TYPE keyTable, u8 ciphertext[]); void Camellia_DecryptBlock(int keyBitLength, const u8 ciphertext[], const KEY_TABLE_TYPE keyTable, u8 plaintext[]); #endif /* #ifndef OSSL_CRYPTO_CAMELLIA_CMLL_LOCAL_H */
1,886
41.886364
79
h
openssl
openssl-master/crypto/camellia/cmll_misc.c
/* * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Camellia low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/opensslv.h> #include <openssl/camellia.h> #include "cmll_local.h" int Camellia_set_key(const unsigned char *userKey, const int bits, CAMELLIA_KEY *key) { if (!userKey || !key) return -1; if (bits != 128 && bits != 192 && bits != 256) return -2; key->grand_rounds = Camellia_Ekeygen(bits, userKey, key->u.rd_key); return 0; } void Camellia_encrypt(const unsigned char *in, unsigned char *out, const CAMELLIA_KEY *key) { Camellia_EncryptBlock_Rounds(key->grand_rounds, in, key->u.rd_key, out); } void Camellia_decrypt(const unsigned char *in, unsigned char *out, const CAMELLIA_KEY *key) { Camellia_DecryptBlock_Rounds(key->grand_rounds, in, key->u.rd_key, out); }
1,259
29
76
c
openssl
openssl-master/crypto/camellia/cmll_ofb.c
/* * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Camellia low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/camellia.h> #include <openssl/modes.h> /* * 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 Camellia_ofb128_encrypt(const unsigned char *in, unsigned char *out, size_t length, const CAMELLIA_KEY *key, unsigned char *ivec, int *num) { CRYPTO_ofb128_encrypt(in, out, length, key, ivec, num, (block128_f) Camellia_encrypt); }
1,042
32.645161
77
c
openssl
openssl-master/crypto/cast/c_cfb64.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 */ /* * CAST low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/cast.h> #include "cast_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 CAST_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, const CAST_KEY *schedule, unsigned char *ivec, int *num, int enc) { register CAST_LONG v0, v1, t; register int n = *num; register long l = length; CAST_LONG ti[2]; unsigned char *iv, c, cc; iv = ivec; if (enc) { while (l--) { if (n == 0) { n2l(iv, v0); ti[0] = v0; n2l(iv, v1); ti[1] = v1; CAST_encrypt((CAST_LONG *)ti, schedule); iv = ivec; t = ti[0]; l2n(t, iv); t = ti[1]; l2n(t, iv); iv = 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; CAST_encrypt((CAST_LONG *)ti, schedule); iv = ivec; t = ti[0]; l2n(t, iv); t = ti[1]; l2n(t, iv); iv = 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,222
26.444444
76
c
openssl
openssl-master/crypto/cast/c_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 */ /* * CAST low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/cast.h> #include "cast_local.h" #include <openssl/opensslv.h> void CAST_ecb_encrypt(const unsigned char *in, unsigned char *out, const CAST_KEY *ks, int enc) { CAST_LONG l, d[2]; n2l(in, l); d[0] = l; n2l(in, l); d[1] = l; if (enc) CAST_encrypt(d, ks); else CAST_decrypt(d, ks); l = d[0]; l2n(l, out); l = d[1]; l2n(l, out); l = d[0] = d[1] = 0; }
920
22.615385
74
c
openssl
openssl-master/crypto/cast/c_enc.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * CAST low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/cast.h> #include "cast_local.h" void CAST_encrypt(CAST_LONG *data, const CAST_KEY *key) { CAST_LONG l, r, t; const CAST_LONG *k; k = &(key->data[0]); l = data[0]; r = data[1]; E_CAST(0, k, l, r, +, ^, -); E_CAST(1, k, r, l, ^, -, +); E_CAST(2, k, l, r, -, +, ^); E_CAST(3, k, r, l, +, ^, -); E_CAST(4, k, l, r, ^, -, +); E_CAST(5, k, r, l, -, +, ^); E_CAST(6, k, l, r, +, ^, -); E_CAST(7, k, r, l, ^, -, +); E_CAST(8, k, l, r, -, +, ^); E_CAST(9, k, r, l, +, ^, -); E_CAST(10, k, l, r, ^, -, +); E_CAST(11, k, r, l, -, +, ^); if (!key->short_key) { E_CAST(12, k, l, r, +, ^, -); E_CAST(13, k, r, l, ^, -, +); E_CAST(14, k, l, r, -, +, ^); E_CAST(15, k, r, l, +, ^, -); } data[1] = l & 0xffffffffL; data[0] = r & 0xffffffffL; } void CAST_decrypt(CAST_LONG *data, const CAST_KEY *key) { CAST_LONG l, r, t; const CAST_LONG *k; k = &(key->data[0]); l = data[0]; r = data[1]; if (!key->short_key) { E_CAST(15, k, l, r, +, ^, -); E_CAST(14, k, r, l, -, +, ^); E_CAST(13, k, l, r, ^, -, +); E_CAST(12, k, r, l, +, ^, -); } E_CAST(11, k, l, r, -, +, ^); E_CAST(10, k, r, l, ^, -, +); E_CAST(9, k, l, r, +, ^, -); E_CAST(8, k, r, l, -, +, ^); E_CAST(7, k, l, r, ^, -, +); E_CAST(6, k, r, l, +, ^, -); E_CAST(5, k, l, r, -, +, ^); E_CAST(4, k, r, l, ^, -, +); E_CAST(3, k, l, r, +, ^, -); E_CAST(2, k, r, l, -, +, ^); E_CAST(1, k, l, r, ^, -, +); E_CAST(0, k, r, l, +, ^, -); data[1] = l & 0xffffffffL; data[0] = r & 0xffffffffL; } void CAST_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, const CAST_KEY *ks, unsigned char *iv, int enc) { register CAST_LONG tin0, tin1; register CAST_LONG tout0, tout1, xor0, xor1; register long l = length; CAST_LONG tin[2]; if (enc) { 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; CAST_encrypt(tin, ks); tout0 = tin[0]; tout1 = tin[1]; l2n(tout0, out); l2n(tout1, out); } if (l != -8) { n2ln(in, tin0, tin1, l + 8); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; CAST_encrypt(tin, ks); tout0 = tin[0]; tout1 = tin[1]; l2n(tout0, out); 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); n2l(in, tin1); tin[0] = tin0; tin[1] = tin1; CAST_decrypt(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); n2l(in, tin1); tin[0] = tin0; tin[1] = tin1; CAST_decrypt(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; }
4,193
25.544304
74
c
openssl
openssl-master/crypto/cast/c_ofb64.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 */ /* * CAST low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/cast.h> #include "cast_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 CAST_ofb64_encrypt(const unsigned char *in, unsigned char *out, long length, const CAST_KEY *schedule, unsigned char *ivec, int *num) { register CAST_LONG v0, v1, t; register int n = *num; register long l = length; unsigned char d[8]; register char *dp; CAST_LONG ti[2]; unsigned char *iv; int save = 0; iv = 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) { CAST_encrypt((CAST_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 = ivec; l2n(v0, iv); l2n(v1, iv); } t = v0 = v1 = ti[0] = ti[1] = 0; *num = n; }
1,720
24.308824
76
c
openssl
openssl-master/crypto/cast/c_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 */ /* * CAST low level APIs are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include <openssl/cast.h> #include "cast_local.h" #include "cast_s.h" #define CAST_exp(l,A,a,n) \ A[n/4]=l; \ a[n+3]=(l )&0xff; \ a[n+2]=(l>> 8)&0xff; \ a[n+1]=(l>>16)&0xff; \ a[n+0]=(l>>24)&0xff; #define S4 CAST_S_table4 #define S5 CAST_S_table5 #define S6 CAST_S_table6 #define S7 CAST_S_table7 void CAST_set_key(CAST_KEY *key, int len, const unsigned char *data) { CAST_LONG x[16]; CAST_LONG z[16]; CAST_LONG k[32]; CAST_LONG X[4], Z[4]; CAST_LONG l, *K; int i; for (i = 0; i < 16; i++) x[i] = 0; if (len > 16) len = 16; for (i = 0; i < len; i++) x[i] = data[i]; if (len <= 10) key->short_key = 1; else key->short_key = 0; K = &k[0]; X[0] = ((x[0] << 24) | (x[1] << 16) | (x[2] << 8) | x[3]) & 0xffffffffL; X[1] = ((x[4] << 24) | (x[5] << 16) | (x[6] << 8) | x[7]) & 0xffffffffL; X[2] = ((x[8] << 24) | (x[9] << 16) | (x[10] << 8) | x[11]) & 0xffffffffL; X[3] = ((x[12] << 24) | (x[13] << 16) | (x[14] << 8) | x[15]) & 0xffffffffL; for (;;) { l = X[0] ^ S4[x[13]] ^ S5[x[15]] ^ S6[x[12]] ^ S7[x[14]] ^ S6[x[8]]; CAST_exp(l, Z, z, 0); l = X[2] ^ S4[z[0]] ^ S5[z[2]] ^ S6[z[1]] ^ S7[z[3]] ^ S7[x[10]]; CAST_exp(l, Z, z, 4); l = X[3] ^ S4[z[7]] ^ S5[z[6]] ^ S6[z[5]] ^ S7[z[4]] ^ S4[x[9]]; CAST_exp(l, Z, z, 8); l = X[1] ^ S4[z[10]] ^ S5[z[9]] ^ S6[z[11]] ^ S7[z[8]] ^ S5[x[11]]; CAST_exp(l, Z, z, 12); K[0] = S4[z[8]] ^ S5[z[9]] ^ S6[z[7]] ^ S7[z[6]] ^ S4[z[2]]; K[1] = S4[z[10]] ^ S5[z[11]] ^ S6[z[5]] ^ S7[z[4]] ^ S5[z[6]]; K[2] = S4[z[12]] ^ S5[z[13]] ^ S6[z[3]] ^ S7[z[2]] ^ S6[z[9]]; K[3] = S4[z[14]] ^ S5[z[15]] ^ S6[z[1]] ^ S7[z[0]] ^ S7[z[12]]; l = Z[2] ^ S4[z[5]] ^ S5[z[7]] ^ S6[z[4]] ^ S7[z[6]] ^ S6[z[0]]; CAST_exp(l, X, x, 0); l = Z[0] ^ S4[x[0]] ^ S5[x[2]] ^ S6[x[1]] ^ S7[x[3]] ^ S7[z[2]]; CAST_exp(l, X, x, 4); l = Z[1] ^ S4[x[7]] ^ S5[x[6]] ^ S6[x[5]] ^ S7[x[4]] ^ S4[z[1]]; CAST_exp(l, X, x, 8); l = Z[3] ^ S4[x[10]] ^ S5[x[9]] ^ S6[x[11]] ^ S7[x[8]] ^ S5[z[3]]; CAST_exp(l, X, x, 12); K[4] = S4[x[3]] ^ S5[x[2]] ^ S6[x[12]] ^ S7[x[13]] ^ S4[x[8]]; K[5] = S4[x[1]] ^ S5[x[0]] ^ S6[x[14]] ^ S7[x[15]] ^ S5[x[13]]; K[6] = S4[x[7]] ^ S5[x[6]] ^ S6[x[8]] ^ S7[x[9]] ^ S6[x[3]]; K[7] = S4[x[5]] ^ S5[x[4]] ^ S6[x[10]] ^ S7[x[11]] ^ S7[x[7]]; l = X[0] ^ S4[x[13]] ^ S5[x[15]] ^ S6[x[12]] ^ S7[x[14]] ^ S6[x[8]]; CAST_exp(l, Z, z, 0); l = X[2] ^ S4[z[0]] ^ S5[z[2]] ^ S6[z[1]] ^ S7[z[3]] ^ S7[x[10]]; CAST_exp(l, Z, z, 4); l = X[3] ^ S4[z[7]] ^ S5[z[6]] ^ S6[z[5]] ^ S7[z[4]] ^ S4[x[9]]; CAST_exp(l, Z, z, 8); l = X[1] ^ S4[z[10]] ^ S5[z[9]] ^ S6[z[11]] ^ S7[z[8]] ^ S5[x[11]]; CAST_exp(l, Z, z, 12); K[8] = S4[z[3]] ^ S5[z[2]] ^ S6[z[12]] ^ S7[z[13]] ^ S4[z[9]]; K[9] = S4[z[1]] ^ S5[z[0]] ^ S6[z[14]] ^ S7[z[15]] ^ S5[z[12]]; K[10] = S4[z[7]] ^ S5[z[6]] ^ S6[z[8]] ^ S7[z[9]] ^ S6[z[2]]; K[11] = S4[z[5]] ^ S5[z[4]] ^ S6[z[10]] ^ S7[z[11]] ^ S7[z[6]]; l = Z[2] ^ S4[z[5]] ^ S5[z[7]] ^ S6[z[4]] ^ S7[z[6]] ^ S6[z[0]]; CAST_exp(l, X, x, 0); l = Z[0] ^ S4[x[0]] ^ S5[x[2]] ^ S6[x[1]] ^ S7[x[3]] ^ S7[z[2]]; CAST_exp(l, X, x, 4); l = Z[1] ^ S4[x[7]] ^ S5[x[6]] ^ S6[x[5]] ^ S7[x[4]] ^ S4[z[1]]; CAST_exp(l, X, x, 8); l = Z[3] ^ S4[x[10]] ^ S5[x[9]] ^ S6[x[11]] ^ S7[x[8]] ^ S5[z[3]]; CAST_exp(l, X, x, 12); K[12] = S4[x[8]] ^ S5[x[9]] ^ S6[x[7]] ^ S7[x[6]] ^ S4[x[3]]; K[13] = S4[x[10]] ^ S5[x[11]] ^ S6[x[5]] ^ S7[x[4]] ^ S5[x[7]]; K[14] = S4[x[12]] ^ S5[x[13]] ^ S6[x[3]] ^ S7[x[2]] ^ S6[x[8]]; K[15] = S4[x[14]] ^ S5[x[15]] ^ S6[x[1]] ^ S7[x[0]] ^ S7[x[13]]; if (K != k) break; K += 16; } for (i = 0; i < 16; i++) { key->data[i * 2] = k[i]; key->data[i * 2 + 1] = ((k[i + 16]) + 16) & 0x1f; } }
4,587
35.704
78
c
openssl
openssl-master/crypto/cast/cast_local.h
/* * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifdef OPENSSL_SYS_WIN32 # include <stdlib.h> #endif /* 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)) #if defined(OPENSSL_SYS_WIN32) && defined(_MSC_VER) # define ROTL(a,n) (_lrotl(a,n)) #else # define ROTL(a,n) ((((a)<<(n))&0xffffffffL)|((a)>>((32-(n))&31))) #endif #define C_M 0x3fc #define C_0 22L #define C_1 14L #define C_2 6L #define C_3 2L /* left shift */ /* The rotate has an extra 16 added to it to help the x86 asm */ #if defined(CAST_PTR) # define E_CAST(n,key,L,R,OP1,OP2,OP3) \ { \ int i; \ t=(key[n*2] OP1 R)&0xffffffffL; \ i=key[n*2+1]; \ t=ROTL(t,i); \ L^= (((((*(CAST_LONG *)((unsigned char *) \ CAST_S_table0+((t>>C_2)&C_M)) OP2 \ *(CAST_LONG *)((unsigned char *) \ CAST_S_table1+((t<<C_3)&C_M)))&0xffffffffL) OP3 \ *(CAST_LONG *)((unsigned char *) \ CAST_S_table2+((t>>C_0)&C_M)))&0xffffffffL) OP1 \ *(CAST_LONG *)((unsigned char *) \ CAST_S_table3+((t>>C_1)&C_M)))&0xffffffffL; \ } #elif defined(CAST_PTR2) # define E_CAST(n,key,L,R,OP1,OP2,OP3) \ { \ int i; \ CAST_LONG u,v,w; \ w=(key[n*2] OP1 R)&0xffffffffL; \ i=key[n*2+1]; \ w=ROTL(w,i); \ u=w>>C_2; \ v=w<<C_3; \ u&=C_M; \ v&=C_M; \ t= *(CAST_LONG *)((unsigned char *)CAST_S_table0+u); \ u=w>>C_0; \ t=(t OP2 *(CAST_LONG *)((unsigned char *)CAST_S_table1+v))&0xffffffffL;\ v=w>>C_1; \ u&=C_M; \ v&=C_M; \ t=(t OP3 *(CAST_LONG *)((unsigned char *)CAST_S_table2+u)&0xffffffffL);\ t=(t OP1 *(CAST_LONG *)((unsigned char *)CAST_S_table3+v)&0xffffffffL);\ L^=(t&0xffffffff); \ } #else # define E_CAST(n,key,L,R,OP1,OP2,OP3) \ { \ CAST_LONG a,b,c,d; \ t=(key[n*2] OP1 R)&0xffffffff; \ t=ROTL(t,(key[n*2+1])); \ a=CAST_S_table0[(t>> 8)&0xff]; \ b=CAST_S_table1[(t )&0xff]; \ c=CAST_S_table2[(t>>24)&0xff]; \ d=CAST_S_table3[(t>>16)&0xff]; \ L^=(((((a OP2 b)&0xffffffffL) OP3 c)&0xffffffffL) OP1 d)&0xffffffffL; \ } #endif extern const CAST_LONG CAST_S_table0[256]; extern const CAST_LONG CAST_S_table1[256]; extern const CAST_LONG CAST_S_table2[256]; extern const CAST_LONG CAST_S_table3[256]; extern const CAST_LONG CAST_S_table4[256]; extern const CAST_LONG CAST_S_table5[256]; extern const CAST_LONG CAST_S_table6[256]; extern const CAST_LONG CAST_S_table7[256];
6,171
41.861111
80
h
openssl
openssl-master/crypto/chacha/chacha_enc.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 */ /* Adapted from the public domain code by D. Bernstein from SUPERCOP. */ #include <string.h> #include "internal/endian.h" #include "crypto/chacha.h" #include "crypto/ctype.h" typedef unsigned int u32; typedef unsigned char u8; typedef union { u32 u[16]; u8 c[64]; } chacha_buf; # define ROTATE(v, n) (((v) << (n)) | ((v) >> (32 - (n)))) # ifndef PEDANTIC # if defined(__GNUC__) && __GNUC__>=2 && \ !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM) # if defined(__riscv_zbb) || defined(__riscv_zbkb) # if __riscv_xlen == 64 # undef ROTATE # define ROTATE(x, n) ({ u32 ret; \ asm ("roriw %0, %1, %2" \ : "=r"(ret) \ : "r"(x), "i"(32 - (n))); ret;}) # endif # if __riscv_xlen == 32 # undef ROTATE # define ROTATE(x, n) ({ u32 ret; \ asm ("rori %0, %1, %2" \ : "=r"(ret) \ : "r"(x), "i"(32 - (n))); ret;}) # endif # endif # endif # endif # define U32TO8_LITTLE(p, v) do { \ (p)[0] = (u8)(v >> 0); \ (p)[1] = (u8)(v >> 8); \ (p)[2] = (u8)(v >> 16); \ (p)[3] = (u8)(v >> 24); \ } while(0) /* QUARTERROUND updates a, b, c, d with a ChaCha "quarter" round. */ # define QUARTERROUND(a,b,c,d) ( \ x[a] += x[b], x[d] = ROTATE((x[d] ^ x[a]),16), \ x[c] += x[d], x[b] = ROTATE((x[b] ^ x[c]),12), \ x[a] += x[b], x[d] = ROTATE((x[d] ^ x[a]), 8), \ x[c] += x[d], x[b] = ROTATE((x[b] ^ x[c]), 7) ) /* chacha_core performs 20 rounds of ChaCha on the input words in * |input| and writes the 64 output bytes to |output|. */ static void chacha20_core(chacha_buf *output, const u32 input[16]) { u32 x[16]; int i; DECLARE_IS_ENDIAN; memcpy(x, input, sizeof(x)); for (i = 20; i > 0; i -= 2) { QUARTERROUND(0, 4, 8, 12); QUARTERROUND(1, 5, 9, 13); QUARTERROUND(2, 6, 10, 14); QUARTERROUND(3, 7, 11, 15); QUARTERROUND(0, 5, 10, 15); QUARTERROUND(1, 6, 11, 12); QUARTERROUND(2, 7, 8, 13); QUARTERROUND(3, 4, 9, 14); } if (IS_LITTLE_ENDIAN) { for (i = 0; i < 16; ++i) output->u[i] = x[i] + input[i]; } else { for (i = 0; i < 16; ++i) U32TO8_LITTLE(output->c + 4 * i, (x[i] + input[i])); } } void ChaCha20_ctr32(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]) { u32 input[16]; chacha_buf buf; size_t todo, i; /* sigma constant "expand 32-byte k" in little-endian encoding */ input[0] = ((u32)ossl_toascii('e')) | ((u32)ossl_toascii('x') << 8) | ((u32)ossl_toascii('p') << 16) | ((u32)ossl_toascii('a') << 24); input[1] = ((u32)ossl_toascii('n')) | ((u32)ossl_toascii('d') << 8) | ((u32)ossl_toascii(' ') << 16) | ((u32)ossl_toascii('3') << 24); input[2] = ((u32)ossl_toascii('2')) | ((u32)ossl_toascii('-') << 8) | ((u32)ossl_toascii('b') << 16) | ((u32)ossl_toascii('y') << 24); input[3] = ((u32)ossl_toascii('t')) | ((u32)ossl_toascii('e') << 8) | ((u32)ossl_toascii(' ') << 16) | ((u32)ossl_toascii('k') << 24); input[4] = key[0]; input[5] = key[1]; input[6] = key[2]; input[7] = key[3]; input[8] = key[4]; input[9] = key[5]; input[10] = key[6]; input[11] = key[7]; input[12] = counter[0]; input[13] = counter[1]; input[14] = counter[2]; input[15] = counter[3]; while (len > 0) { todo = sizeof(buf); if (len < todo) todo = len; chacha20_core(&buf, input); for (i = 0; i < todo; i++) out[i] = inp[i] ^ buf.c[i]; out += todo; inp += todo; len -= todo; /* * Advance 32-bit counter. Note that as subroutine is so to * say nonce-agnostic, this limited counter width doesn't * prevent caller from implementing wider counter. It would * simply take two calls split on counter overflow... */ input[12]++; } }
4,844
31.086093
74
c
openssl
openssl-master/crypto/chacha/chacha_ppc.c
/* * Copyright 2009-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/opensslconf.h> #include "crypto/chacha.h" #include "crypto/ppc_arch.h" void ChaCha20_ctr32_int(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]); void ChaCha20_ctr32_vmx(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]); void ChaCha20_ctr32_vsx(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]); void ChaCha20_ctr32_vsx_p10(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]); void ChaCha20_ctr32(unsigned char *out, const unsigned char *inp, size_t len, const unsigned int key[8], const unsigned int counter[4]) { #if !defined(OPENSSL_SYS_AIX) && !defined(OPENSSL_SYS_MACOSX) OPENSSL_ppccap_P & PPC_BRD31 ? ChaCha20_ctr32_vsx_p10(out, inp, len, key, counter) : #endif OPENSSL_ppccap_P & PPC_CRYPTO207 ? ChaCha20_ctr32_vsx(out, inp, len, key, counter) : OPENSSL_ppccap_P & PPC_ALTIVEC ? ChaCha20_ctr32_vmx(out, inp, len, key, counter) : ChaCha20_ctr32_int(out, inp, len, key, counter); }
1,859
42.255814
74
c
openssl
openssl-master/crypto/cmac/cmac.c
/* * Copyright 2010-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 */ /* * CMAC 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 "internal/cryptlib.h" #include <openssl/cmac.h> #include <openssl/err.h> #define LOCAL_BUF_SIZE 2048 struct CMAC_CTX_st { /* Cipher context to use */ EVP_CIPHER_CTX *cctx; /* Keys k1 and k2 */ unsigned char k1[EVP_MAX_BLOCK_LENGTH]; unsigned char k2[EVP_MAX_BLOCK_LENGTH]; /* Temporary block */ unsigned char tbl[EVP_MAX_BLOCK_LENGTH]; /* Last (possibly partial) block */ unsigned char last_block[EVP_MAX_BLOCK_LENGTH]; /* Number of bytes in last block: -1 means context not initialised */ int nlast_block; }; /* Make temporary keys K1 and K2 */ static void make_kn(unsigned char *k1, const unsigned char *l, int bl) { int i; unsigned char c = l[0], carry = c >> 7, cnext; /* Shift block to left, including carry */ for (i = 0; i < bl - 1; i++, c = cnext) k1[i] = (c << 1) | ((cnext = l[i + 1]) >> 7); /* If MSB set fixup with R */ k1[i] = (c << 1) ^ ((0 - carry) & (bl == 16 ? 0x87 : 0x1b)); } CMAC_CTX *CMAC_CTX_new(void) { CMAC_CTX *ctx; if ((ctx = OPENSSL_malloc(sizeof(*ctx))) == NULL) return NULL; ctx->cctx = EVP_CIPHER_CTX_new(); if (ctx->cctx == NULL) { OPENSSL_free(ctx); return NULL; } ctx->nlast_block = -1; return ctx; } void CMAC_CTX_cleanup(CMAC_CTX *ctx) { EVP_CIPHER_CTX_reset(ctx->cctx); OPENSSL_cleanse(ctx->tbl, EVP_MAX_BLOCK_LENGTH); OPENSSL_cleanse(ctx->k1, EVP_MAX_BLOCK_LENGTH); OPENSSL_cleanse(ctx->k2, EVP_MAX_BLOCK_LENGTH); OPENSSL_cleanse(ctx->last_block, EVP_MAX_BLOCK_LENGTH); ctx->nlast_block = -1; } EVP_CIPHER_CTX *CMAC_CTX_get0_cipher_ctx(CMAC_CTX *ctx) { return ctx->cctx; } void CMAC_CTX_free(CMAC_CTX *ctx) { if (!ctx) return; CMAC_CTX_cleanup(ctx); EVP_CIPHER_CTX_free(ctx->cctx); OPENSSL_free(ctx); } int CMAC_CTX_copy(CMAC_CTX *out, const CMAC_CTX *in) { int bl; if (in->nlast_block == -1) return 0; if ((bl = EVP_CIPHER_CTX_get_block_size(in->cctx)) < 0) return 0; if (!EVP_CIPHER_CTX_copy(out->cctx, in->cctx)) return 0; memcpy(out->k1, in->k1, bl); memcpy(out->k2, in->k2, bl); memcpy(out->tbl, in->tbl, bl); memcpy(out->last_block, in->last_block, bl); out->nlast_block = in->nlast_block; return 1; } int CMAC_Init(CMAC_CTX *ctx, const void *key, size_t keylen, const EVP_CIPHER *cipher, ENGINE *impl) { static const unsigned char zero_iv[EVP_MAX_BLOCK_LENGTH] = { 0 }; /* All zeros means restart */ if (!key && !cipher && !impl && keylen == 0) { /* Not initialised */ if (ctx->nlast_block == -1) return 0; if (!EVP_EncryptInit_ex(ctx->cctx, NULL, NULL, NULL, zero_iv)) return 0; memset(ctx->tbl, 0, EVP_CIPHER_CTX_get_block_size(ctx->cctx)); ctx->nlast_block = 0; return 1; } /* Initialise context */ if (cipher != NULL) { /* Ensure we can't use this ctx until we also have a key */ ctx->nlast_block = -1; if (!EVP_EncryptInit_ex(ctx->cctx, cipher, impl, NULL, NULL)) return 0; } /* Non-NULL key means initialisation complete */ if (key != NULL) { int bl; /* If anything fails then ensure we can't use this ctx */ ctx->nlast_block = -1; if (EVP_CIPHER_CTX_get0_cipher(ctx->cctx) == NULL) return 0; if (EVP_CIPHER_CTX_set_key_length(ctx->cctx, keylen) <= 0) return 0; if (!EVP_EncryptInit_ex(ctx->cctx, NULL, NULL, key, zero_iv)) return 0; if ((bl = EVP_CIPHER_CTX_get_block_size(ctx->cctx)) < 0) return 0; if (EVP_Cipher(ctx->cctx, ctx->tbl, zero_iv, bl) <= 0) return 0; make_kn(ctx->k1, ctx->tbl, bl); make_kn(ctx->k2, ctx->k1, bl); OPENSSL_cleanse(ctx->tbl, bl); /* Reset context again ready for first data block */ if (!EVP_EncryptInit_ex(ctx->cctx, NULL, NULL, NULL, zero_iv)) return 0; /* Zero tbl so resume works */ memset(ctx->tbl, 0, bl); ctx->nlast_block = 0; } return 1; } int CMAC_Update(CMAC_CTX *ctx, const void *in, size_t dlen) { const unsigned char *data = in; int bl; size_t max_burst_blocks, cipher_blocks; unsigned char buf[LOCAL_BUF_SIZE]; if (ctx->nlast_block == -1) return 0; if (dlen == 0) return 1; if ((bl = EVP_CIPHER_CTX_get_block_size(ctx->cctx)) < 0) return 0; /* Copy into partial block if we need to */ if (ctx->nlast_block > 0) { size_t nleft; nleft = bl - ctx->nlast_block; if (dlen < nleft) nleft = dlen; memcpy(ctx->last_block + ctx->nlast_block, data, nleft); dlen -= nleft; ctx->nlast_block += nleft; /* If no more to process return */ if (dlen == 0) return 1; data += nleft; /* Else not final block so encrypt it */ if (EVP_Cipher(ctx->cctx, ctx->tbl, ctx->last_block, bl) <= 0) return 0; } /* Encrypt all but one of the complete blocks left */ max_burst_blocks = LOCAL_BUF_SIZE / bl; cipher_blocks = (dlen - 1) / bl; if (max_burst_blocks == 0) { /* * When block length is greater than local buffer size, * use ctx->tbl as cipher output. */ while (dlen > (size_t)bl) { if (EVP_Cipher(ctx->cctx, ctx->tbl, data, bl) <= 0) return 0; dlen -= bl; data += bl; } } else { while (cipher_blocks > max_burst_blocks) { if (EVP_Cipher(ctx->cctx, buf, data, max_burst_blocks * bl) <= 0) return 0; dlen -= max_burst_blocks * bl; data += max_burst_blocks * bl; cipher_blocks -= max_burst_blocks; } if (cipher_blocks > 0) { if (EVP_Cipher(ctx->cctx, buf, data, cipher_blocks * bl) <= 0) return 0; dlen -= cipher_blocks * bl; data += cipher_blocks * bl; memcpy(ctx->tbl, &buf[(cipher_blocks - 1) * bl], bl); } } /* Copy any data left to last block buffer */ memcpy(ctx->last_block, data, dlen); ctx->nlast_block = dlen; return 1; } int CMAC_Final(CMAC_CTX *ctx, unsigned char *out, size_t *poutlen) { int i, bl, lb; if (ctx->nlast_block == -1) return 0; if ((bl = EVP_CIPHER_CTX_get_block_size(ctx->cctx)) < 0) return 0; if (poutlen != NULL) *poutlen = (size_t)bl; if (!out) return 1; lb = ctx->nlast_block; /* Is last block complete? */ if (lb == bl) { for (i = 0; i < bl; i++) out[i] = ctx->last_block[i] ^ ctx->k1[i]; } else { ctx->last_block[lb] = 0x80; if (bl - lb > 1) memset(ctx->last_block + lb + 1, 0, bl - lb - 1); for (i = 0; i < bl; i++) out[i] = ctx->last_block[i] ^ ctx->k2[i]; } if (EVP_Cipher(ctx->cctx, out, out, bl) <= 0) { OPENSSL_cleanse(out, bl); return 0; } return 1; } int CMAC_resume(CMAC_CTX *ctx) { if (ctx->nlast_block == -1) return 0; /* * The buffer "tbl" contains the last fully encrypted block which is the * last IV (or all zeroes if no last encrypted block). The last block has * not been modified since CMAC_final(). So reinitialising using the last * decrypted block will allow CMAC to continue after calling * CMAC_Final(). */ return EVP_EncryptInit_ex(ctx->cctx, NULL, NULL, NULL, ctx->tbl); }
8,174
28.727273
79
c
openssl
openssl-master/crypto/cmp/cmp_asn.c
/* * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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/asn1t.h> #include "cmp_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/cmp.h> #include <openssl/crmf.h> /* ASN.1 declarations from RFC4210 */ ASN1_SEQUENCE(OSSL_CMP_REVANNCONTENT) = { /* OSSL_CMP_PKISTATUS is effectively ASN1_INTEGER so it is used directly */ ASN1_SIMPLE(OSSL_CMP_REVANNCONTENT, status, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CMP_REVANNCONTENT, certId, OSSL_CRMF_CERTID), ASN1_SIMPLE(OSSL_CMP_REVANNCONTENT, willBeRevokedAt, ASN1_GENERALIZEDTIME), ASN1_SIMPLE(OSSL_CMP_REVANNCONTENT, badSinceDate, ASN1_GENERALIZEDTIME), ASN1_OPT(OSSL_CMP_REVANNCONTENT, crlDetails, X509_EXTENSIONS) } ASN1_SEQUENCE_END(OSSL_CMP_REVANNCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_REVANNCONTENT) ASN1_SEQUENCE(OSSL_CMP_CHALLENGE) = { ASN1_OPT(OSSL_CMP_CHALLENGE, owf, X509_ALGOR), ASN1_SIMPLE(OSSL_CMP_CHALLENGE, witness, ASN1_OCTET_STRING), ASN1_SIMPLE(OSSL_CMP_CHALLENGE, challenge, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(OSSL_CMP_CHALLENGE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CHALLENGE) ASN1_ITEM_TEMPLATE(OSSL_CMP_POPODECKEYCHALLCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_POPODECKEYCHALLCONTENT, OSSL_CMP_CHALLENGE) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_POPODECKEYCHALLCONTENT) ASN1_ITEM_TEMPLATE(OSSL_CMP_POPODECKEYRESPCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_POPODECKEYRESPCONTENT, ASN1_INTEGER) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_POPODECKEYRESPCONTENT) ASN1_SEQUENCE(OSSL_CMP_CAKEYUPDANNCONTENT) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_SIMPLE(OSSL_CMP_CAKEYUPDANNCONTENT, oldWithNew, X509), /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_SIMPLE(OSSL_CMP_CAKEYUPDANNCONTENT, newWithOld, X509), /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_SIMPLE(OSSL_CMP_CAKEYUPDANNCONTENT, newWithNew, X509) } ASN1_SEQUENCE_END(OSSL_CMP_CAKEYUPDANNCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CAKEYUPDANNCONTENT) ASN1_SEQUENCE(OSSL_CMP_ERRORMSGCONTENT) = { ASN1_SIMPLE(OSSL_CMP_ERRORMSGCONTENT, pKIStatusInfo, OSSL_CMP_PKISI), ASN1_OPT(OSSL_CMP_ERRORMSGCONTENT, errorCode, ASN1_INTEGER), /* * OSSL_CMP_PKIFREETEXT is effectively a sequence of ASN1_UTF8STRING * so it is used directly * */ ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ERRORMSGCONTENT, errorDetails, ASN1_UTF8STRING) } ASN1_SEQUENCE_END(OSSL_CMP_ERRORMSGCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_ERRORMSGCONTENT) ASN1_ADB_TEMPLATE(infotypeandvalue_default) = ASN1_OPT(OSSL_CMP_ITAV, infoValue.other, ASN1_ANY); /* ITAV means InfoTypeAndValue */ ASN1_ADB(OSSL_CMP_ITAV) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ADB_ENTRY(NID_id_it_caProtEncCert, ASN1_OPT(OSSL_CMP_ITAV, infoValue.caProtEncCert, X509)), ADB_ENTRY(NID_id_it_signKeyPairTypes, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.signKeyPairTypes, X509_ALGOR)), ADB_ENTRY(NID_id_it_encKeyPairTypes, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.encKeyPairTypes, X509_ALGOR)), ADB_ENTRY(NID_id_it_preferredSymmAlg, ASN1_OPT(OSSL_CMP_ITAV, infoValue.preferredSymmAlg, X509_ALGOR)), ADB_ENTRY(NID_id_it_caKeyUpdateInfo, ASN1_OPT(OSSL_CMP_ITAV, infoValue.caKeyUpdateInfo, OSSL_CMP_CAKEYUPDANNCONTENT)), ADB_ENTRY(NID_id_it_currentCRL, ASN1_OPT(OSSL_CMP_ITAV, infoValue.currentCRL, X509_CRL)), ADB_ENTRY(NID_id_it_unsupportedOIDs, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.unsupportedOIDs, ASN1_OBJECT)), ADB_ENTRY(NID_id_it_keyPairParamReq, ASN1_OPT(OSSL_CMP_ITAV, infoValue.keyPairParamReq, ASN1_OBJECT)), ADB_ENTRY(NID_id_it_keyPairParamRep, ASN1_OPT(OSSL_CMP_ITAV, infoValue.keyPairParamRep, X509_ALGOR)), ADB_ENTRY(NID_id_it_revPassphrase, ASN1_OPT(OSSL_CMP_ITAV, infoValue.revPassphrase, OSSL_CRMF_ENCRYPTEDVALUE)), ADB_ENTRY(NID_id_it_implicitConfirm, ASN1_OPT(OSSL_CMP_ITAV, infoValue.implicitConfirm, ASN1_NULL)), ADB_ENTRY(NID_id_it_confirmWaitTime, ASN1_OPT(OSSL_CMP_ITAV, infoValue.confirmWaitTime, ASN1_GENERALIZEDTIME)), ADB_ENTRY(NID_id_it_origPKIMessage, ASN1_OPT(OSSL_CMP_ITAV, infoValue.origPKIMessage, OSSL_CMP_MSGS)), ADB_ENTRY(NID_id_it_suppLangTags, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.suppLangTagsValue, ASN1_UTF8STRING)), ADB_ENTRY(NID_id_it_caCerts, ASN1_SEQUENCE_OF_OPT(OSSL_CMP_ITAV, infoValue.caCerts, X509)), ADB_ENTRY(NID_id_it_rootCaCert, ASN1_OPT(OSSL_CMP_ITAV, infoValue.rootCaCert, X509)), ADB_ENTRY(NID_id_it_rootCaKeyUpdate, ASN1_OPT(OSSL_CMP_ITAV, infoValue.rootCaKeyUpdate, OSSL_CMP_ROOTCAKEYUPDATE)), } ASN1_ADB_END(OSSL_CMP_ITAV, 0, infoType, 0, &infotypeandvalue_default_tt, NULL); ASN1_SEQUENCE(OSSL_CMP_ITAV) = { ASN1_SIMPLE(OSSL_CMP_ITAV, infoType, ASN1_OBJECT), ASN1_ADB_OBJECT(OSSL_CMP_ITAV) } ASN1_SEQUENCE_END(OSSL_CMP_ITAV) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_ITAV) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CMP_ITAV) ASN1_SEQUENCE(OSSL_CMP_ROOTCAKEYUPDATE) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_SIMPLE(OSSL_CMP_ROOTCAKEYUPDATE, newWithNew, X509), ASN1_EXP_OPT(OSSL_CMP_ROOTCAKEYUPDATE, newWithOld, X509, 0), ASN1_EXP_OPT(OSSL_CMP_ROOTCAKEYUPDATE, oldWithNew, X509, 1) } ASN1_SEQUENCE_END(OSSL_CMP_ROOTCAKEYUPDATE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_ROOTCAKEYUPDATE) OSSL_CMP_ITAV *OSSL_CMP_ITAV_create(ASN1_OBJECT *type, ASN1_TYPE *value) { OSSL_CMP_ITAV *itav; if (type == NULL || (itav = OSSL_CMP_ITAV_new()) == NULL) return NULL; OSSL_CMP_ITAV_set0(itav, type, value); return itav; } void OSSL_CMP_ITAV_set0(OSSL_CMP_ITAV *itav, ASN1_OBJECT *type, ASN1_TYPE *value) { itav->infoType = type; itav->infoValue.other = value; } ASN1_OBJECT *OSSL_CMP_ITAV_get0_type(const OSSL_CMP_ITAV *itav) { if (itav == NULL) return NULL; return itav->infoType; } ASN1_TYPE *OSSL_CMP_ITAV_get0_value(const OSSL_CMP_ITAV *itav) { if (itav == NULL) return NULL; return itav->infoValue.other; } int OSSL_CMP_ITAV_push0_stack_item(STACK_OF(OSSL_CMP_ITAV) **itav_sk_p, OSSL_CMP_ITAV *itav) { int created = 0; if (itav_sk_p == NULL || itav == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); goto err; } if (*itav_sk_p == NULL) { if ((*itav_sk_p = sk_OSSL_CMP_ITAV_new_null()) == NULL) goto err; created = 1; } if (!sk_OSSL_CMP_ITAV_push(*itav_sk_p, itav)) goto err; return 1; err: if (created != 0) { sk_OSSL_CMP_ITAV_free(*itav_sk_p); *itav_sk_p = NULL; } return 0; } OSSL_CMP_ITAV *OSSL_CMP_ITAV_new_caCerts(const STACK_OF(X509) *caCerts) { OSSL_CMP_ITAV *itav = OSSL_CMP_ITAV_new(); if (itav == NULL) return NULL; if (sk_X509_num(caCerts) > 0 && (itav->infoValue.caCerts = sk_X509_deep_copy(caCerts, X509_dup, X509_free)) == NULL) { OSSL_CMP_ITAV_free(itav); return NULL; } itav->infoType = OBJ_nid2obj(NID_id_it_caCerts); return itav; } int OSSL_CMP_ITAV_get0_caCerts(const OSSL_CMP_ITAV *itav, STACK_OF(X509) **out) { if (itav == NULL || out == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (OBJ_obj2nid(itav->infoType) != NID_id_it_caCerts) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } *out = sk_X509_num(itav->infoValue.caCerts) > 0 ? itav->infoValue.caCerts : NULL; return 1; } OSSL_CMP_ITAV *OSSL_CMP_ITAV_new_rootCaCert(const X509 *rootCaCert) { OSSL_CMP_ITAV *itav = OSSL_CMP_ITAV_new(); if (itav == NULL) return NULL; if (rootCaCert != NULL && (itav->infoValue.rootCaCert = X509_dup(rootCaCert)) == NULL) { OSSL_CMP_ITAV_free(itav); return NULL; } itav->infoType = OBJ_nid2obj(NID_id_it_rootCaCert); return itav; } int OSSL_CMP_ITAV_get0_rootCaCert(const OSSL_CMP_ITAV *itav, X509 **out) { if (itav == NULL || out == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (OBJ_obj2nid(itav->infoType) != NID_id_it_rootCaCert) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } *out = itav->infoValue.rootCaCert; return 1; } OSSL_CMP_ITAV *OSSL_CMP_ITAV_new_rootCaKeyUpdate(const X509 *newWithNew, const X509 *newWithOld, const X509 *oldWithNew) { OSSL_CMP_ITAV *itav; OSSL_CMP_ROOTCAKEYUPDATE *upd = OSSL_CMP_ROOTCAKEYUPDATE_new(); if (upd == NULL) return NULL; if (newWithNew != NULL && (upd->newWithNew = X509_dup(newWithNew)) == NULL) goto err; if (newWithOld != NULL && (upd->newWithOld = X509_dup(newWithOld)) == NULL) goto err; if (oldWithNew != NULL && (upd->oldWithNew = X509_dup(oldWithNew)) == NULL) goto err; if ((itav = OSSL_CMP_ITAV_new()) == NULL) goto err; itav->infoType = OBJ_nid2obj(NID_id_it_rootCaKeyUpdate); itav->infoValue.rootCaKeyUpdate = upd; return itav; err: OSSL_CMP_ROOTCAKEYUPDATE_free(upd); return NULL; } int OSSL_CMP_ITAV_get0_rootCaKeyUpdate(const OSSL_CMP_ITAV *itav, X509 **newWithNew, X509 **newWithOld, X509 **oldWithNew) { OSSL_CMP_ROOTCAKEYUPDATE *upd; if (itav == NULL || newWithNew == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if (OBJ_obj2nid(itav->infoType) != NID_id_it_rootCaKeyUpdate) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } upd = itav->infoValue.rootCaKeyUpdate; *newWithNew = upd->newWithNew; if (newWithOld != NULL) *newWithOld = upd->newWithOld; if (oldWithNew != NULL) *oldWithNew = upd->oldWithNew; return 1; } /* get ASN.1 encoded integer, return -1 on error */ int ossl_cmp_asn1_get_int(const ASN1_INTEGER *a) { int64_t res; if (!ASN1_INTEGER_get_int64(&res, a)) { ERR_raise(ERR_LIB_CMP, ASN1_R_INVALID_NUMBER); return -1; } if (res < INT_MIN) { ERR_raise(ERR_LIB_CMP, ASN1_R_TOO_SMALL); return -1; } if (res > INT_MAX) { ERR_raise(ERR_LIB_CMP, ASN1_R_TOO_LARGE); return -1; } return (int)res; } static int ossl_cmp_msg_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { OSSL_CMP_MSG *msg = (OSSL_CMP_MSG *)*pval; switch (operation) { case ASN1_OP_FREE_POST: OPENSSL_free(msg->propq); break; case ASN1_OP_DUP_POST: { OSSL_CMP_MSG *old = exarg; if (!ossl_cmp_msg_set0_libctx(msg, old->libctx, old->propq)) return 0; } break; case ASN1_OP_GET0_LIBCTX: { OSSL_LIB_CTX **libctx = exarg; *libctx = msg->libctx; } break; case ASN1_OP_GET0_PROPQ: { const char **propq = exarg; *propq = msg->propq; } break; default: break; } return 1; } ASN1_CHOICE(OSSL_CMP_CERTORENCCERT) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_EXP(OSSL_CMP_CERTORENCCERT, value.certificate, X509, 0), ASN1_EXP(OSSL_CMP_CERTORENCCERT, value.encryptedCert, OSSL_CRMF_ENCRYPTEDVALUE, 1), } ASN1_CHOICE_END(OSSL_CMP_CERTORENCCERT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTORENCCERT) ASN1_SEQUENCE(OSSL_CMP_CERTIFIEDKEYPAIR) = { ASN1_SIMPLE(OSSL_CMP_CERTIFIEDKEYPAIR, certOrEncCert, OSSL_CMP_CERTORENCCERT), ASN1_EXP_OPT(OSSL_CMP_CERTIFIEDKEYPAIR, privateKey, OSSL_CRMF_ENCRYPTEDVALUE, 0), ASN1_EXP_OPT(OSSL_CMP_CERTIFIEDKEYPAIR, publicationInfo, OSSL_CRMF_PKIPUBLICATIONINFO, 1) } ASN1_SEQUENCE_END(OSSL_CMP_CERTIFIEDKEYPAIR) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTIFIEDKEYPAIR) ASN1_SEQUENCE(OSSL_CMP_REVDETAILS) = { ASN1_SIMPLE(OSSL_CMP_REVDETAILS, certDetails, OSSL_CRMF_CERTTEMPLATE), ASN1_OPT(OSSL_CMP_REVDETAILS, crlEntryDetails, X509_EXTENSIONS) } ASN1_SEQUENCE_END(OSSL_CMP_REVDETAILS) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_REVDETAILS) ASN1_ITEM_TEMPLATE(OSSL_CMP_REVREQCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_REVREQCONTENT, OSSL_CMP_REVDETAILS) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_REVREQCONTENT) ASN1_SEQUENCE(OSSL_CMP_REVREPCONTENT) = { ASN1_SEQUENCE_OF(OSSL_CMP_REVREPCONTENT, status, OSSL_CMP_PKISI), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_REVREPCONTENT, revCerts, OSSL_CRMF_CERTID, 0), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_REVREPCONTENT, crls, X509_CRL, 1) } ASN1_SEQUENCE_END(OSSL_CMP_REVREPCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_REVREPCONTENT) ASN1_SEQUENCE(OSSL_CMP_KEYRECREPCONTENT) = { ASN1_SIMPLE(OSSL_CMP_KEYRECREPCONTENT, status, OSSL_CMP_PKISI), ASN1_EXP_OPT(OSSL_CMP_KEYRECREPCONTENT, newSigCert, X509, 0), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_KEYRECREPCONTENT, caCerts, X509, 1), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_KEYRECREPCONTENT, keyPairHist, OSSL_CMP_CERTIFIEDKEYPAIR, 2) } ASN1_SEQUENCE_END(OSSL_CMP_KEYRECREPCONTENT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_KEYRECREPCONTENT) ASN1_ITEM_TEMPLATE(OSSL_CMP_PKISTATUS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_UNIVERSAL, 0, status, ASN1_INTEGER) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_PKISTATUS) ASN1_SEQUENCE(OSSL_CMP_PKISI) = { ASN1_SIMPLE(OSSL_CMP_PKISI, status, OSSL_CMP_PKISTATUS), /* * CMP_PKIFREETEXT is effectively a sequence of ASN1_UTF8STRING * so it is used directly */ ASN1_SEQUENCE_OF_OPT(OSSL_CMP_PKISI, statusString, ASN1_UTF8STRING), /* * OSSL_CMP_PKIFAILUREINFO is effectively ASN1_BIT_STRING so used directly */ ASN1_OPT(OSSL_CMP_PKISI, failInfo, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(OSSL_CMP_PKISI) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_PKISI) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CMP_PKISI) ASN1_SEQUENCE(OSSL_CMP_CERTSTATUS) = { ASN1_SIMPLE(OSSL_CMP_CERTSTATUS, certHash, ASN1_OCTET_STRING), ASN1_SIMPLE(OSSL_CMP_CERTSTATUS, certReqId, ASN1_INTEGER), ASN1_OPT(OSSL_CMP_CERTSTATUS, statusInfo, OSSL_CMP_PKISI), ASN1_EXP_OPT(OSSL_CMP_CERTSTATUS, hashAlg, X509_ALGOR, 0) } ASN1_SEQUENCE_END(OSSL_CMP_CERTSTATUS) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTSTATUS) ASN1_ITEM_TEMPLATE(OSSL_CMP_CERTCONFIRMCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_CERTCONFIRMCONTENT, OSSL_CMP_CERTSTATUS) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_CERTCONFIRMCONTENT) ASN1_SEQUENCE(OSSL_CMP_CERTRESPONSE) = { ASN1_SIMPLE(OSSL_CMP_CERTRESPONSE, certReqId, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CMP_CERTRESPONSE, status, OSSL_CMP_PKISI), ASN1_OPT(OSSL_CMP_CERTRESPONSE, certifiedKeyPair, OSSL_CMP_CERTIFIEDKEYPAIR), ASN1_OPT(OSSL_CMP_CERTRESPONSE, rspInfo, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(OSSL_CMP_CERTRESPONSE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTRESPONSE) ASN1_SEQUENCE(OSSL_CMP_POLLREQ) = { ASN1_SIMPLE(OSSL_CMP_POLLREQ, certReqId, ASN1_INTEGER) } ASN1_SEQUENCE_END(OSSL_CMP_POLLREQ) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_POLLREQ) ASN1_ITEM_TEMPLATE(OSSL_CMP_POLLREQCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_POLLREQCONTENT, OSSL_CMP_POLLREQ) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_POLLREQCONTENT) ASN1_SEQUENCE(OSSL_CMP_POLLREP) = { ASN1_SIMPLE(OSSL_CMP_POLLREP, certReqId, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CMP_POLLREP, checkAfter, ASN1_INTEGER), ASN1_SEQUENCE_OF_OPT(OSSL_CMP_POLLREP, reason, ASN1_UTF8STRING), } ASN1_SEQUENCE_END(OSSL_CMP_POLLREP) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_POLLREP) ASN1_ITEM_TEMPLATE(OSSL_CMP_POLLREPCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_POLLREPCONTENT, OSSL_CMP_POLLREP) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_POLLREPCONTENT) ASN1_SEQUENCE(OSSL_CMP_CERTREPMESSAGE) = { /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_CERTREPMESSAGE, caPubs, X509, 1), ASN1_SEQUENCE_OF(OSSL_CMP_CERTREPMESSAGE, response, OSSL_CMP_CERTRESPONSE) } ASN1_SEQUENCE_END(OSSL_CMP_CERTREPMESSAGE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_CERTREPMESSAGE) ASN1_ITEM_TEMPLATE(OSSL_CMP_GENMSGCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_GENMSGCONTENT, OSSL_CMP_ITAV) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_GENMSGCONTENT) ASN1_ITEM_TEMPLATE(OSSL_CMP_GENREPCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_GENREPCONTENT, OSSL_CMP_ITAV) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_GENREPCONTENT) ASN1_ITEM_TEMPLATE(OSSL_CMP_CRLANNCONTENT) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_CRLANNCONTENT, X509_CRL) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_CRLANNCONTENT) ASN1_CHOICE(OSSL_CMP_PKIBODY) = { ASN1_EXP(OSSL_CMP_PKIBODY, value.ir, OSSL_CRMF_MSGS, 0), ASN1_EXP(OSSL_CMP_PKIBODY, value.ip, OSSL_CMP_CERTREPMESSAGE, 1), ASN1_EXP(OSSL_CMP_PKIBODY, value.cr, OSSL_CRMF_MSGS, 2), ASN1_EXP(OSSL_CMP_PKIBODY, value.cp, OSSL_CMP_CERTREPMESSAGE, 3), ASN1_EXP(OSSL_CMP_PKIBODY, value.p10cr, X509_REQ, 4), ASN1_EXP(OSSL_CMP_PKIBODY, value.popdecc, OSSL_CMP_POPODECKEYCHALLCONTENT, 5), ASN1_EXP(OSSL_CMP_PKIBODY, value.popdecr, OSSL_CMP_POPODECKEYRESPCONTENT, 6), ASN1_EXP(OSSL_CMP_PKIBODY, value.kur, OSSL_CRMF_MSGS, 7), ASN1_EXP(OSSL_CMP_PKIBODY, value.kup, OSSL_CMP_CERTREPMESSAGE, 8), ASN1_EXP(OSSL_CMP_PKIBODY, value.krr, OSSL_CRMF_MSGS, 9), ASN1_EXP(OSSL_CMP_PKIBODY, value.krp, OSSL_CMP_KEYRECREPCONTENT, 10), ASN1_EXP(OSSL_CMP_PKIBODY, value.rr, OSSL_CMP_REVREQCONTENT, 11), ASN1_EXP(OSSL_CMP_PKIBODY, value.rp, OSSL_CMP_REVREPCONTENT, 12), ASN1_EXP(OSSL_CMP_PKIBODY, value.ccr, OSSL_CRMF_MSGS, 13), ASN1_EXP(OSSL_CMP_PKIBODY, value.ccp, OSSL_CMP_CERTREPMESSAGE, 14), ASN1_EXP(OSSL_CMP_PKIBODY, value.ckuann, OSSL_CMP_CAKEYUPDANNCONTENT, 15), ASN1_EXP(OSSL_CMP_PKIBODY, value.cann, X509, 16), ASN1_EXP(OSSL_CMP_PKIBODY, value.rann, OSSL_CMP_REVANNCONTENT, 17), ASN1_EXP(OSSL_CMP_PKIBODY, value.crlann, OSSL_CMP_CRLANNCONTENT, 18), ASN1_EXP(OSSL_CMP_PKIBODY, value.pkiconf, ASN1_ANY, 19), ASN1_EXP(OSSL_CMP_PKIBODY, value.nested, OSSL_CMP_MSGS, 20), ASN1_EXP(OSSL_CMP_PKIBODY, value.genm, OSSL_CMP_GENMSGCONTENT, 21), ASN1_EXP(OSSL_CMP_PKIBODY, value.genp, OSSL_CMP_GENREPCONTENT, 22), ASN1_EXP(OSSL_CMP_PKIBODY, value.error, OSSL_CMP_ERRORMSGCONTENT, 23), ASN1_EXP(OSSL_CMP_PKIBODY, value.certConf, OSSL_CMP_CERTCONFIRMCONTENT, 24), ASN1_EXP(OSSL_CMP_PKIBODY, value.pollReq, OSSL_CMP_POLLREQCONTENT, 25), ASN1_EXP(OSSL_CMP_PKIBODY, value.pollRep, OSSL_CMP_POLLREPCONTENT, 26), } ASN1_CHOICE_END(OSSL_CMP_PKIBODY) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_PKIBODY) ASN1_SEQUENCE(OSSL_CMP_PKIHEADER) = { ASN1_SIMPLE(OSSL_CMP_PKIHEADER, pvno, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CMP_PKIHEADER, sender, GENERAL_NAME), ASN1_SIMPLE(OSSL_CMP_PKIHEADER, recipient, GENERAL_NAME), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, messageTime, ASN1_GENERALIZEDTIME, 0), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, protectionAlg, X509_ALGOR, 1), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, senderKID, ASN1_OCTET_STRING, 2), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, recipKID, ASN1_OCTET_STRING, 3), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, transactionID, ASN1_OCTET_STRING, 4), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, senderNonce, ASN1_OCTET_STRING, 5), ASN1_EXP_OPT(OSSL_CMP_PKIHEADER, recipNonce, ASN1_OCTET_STRING, 6), /* * OSSL_CMP_PKIFREETEXT is effectively a sequence of ASN1_UTF8STRING * so it is used directly */ ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_PKIHEADER, freeText, ASN1_UTF8STRING, 7), ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_PKIHEADER, generalInfo, OSSL_CMP_ITAV, 8) } ASN1_SEQUENCE_END(OSSL_CMP_PKIHEADER) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_PKIHEADER) ASN1_SEQUENCE(OSSL_CMP_PROTECTEDPART) = { ASN1_SIMPLE(OSSL_CMP_MSG, header, OSSL_CMP_PKIHEADER), ASN1_SIMPLE(OSSL_CMP_MSG, body, OSSL_CMP_PKIBODY) } ASN1_SEQUENCE_END(OSSL_CMP_PROTECTEDPART) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CMP_PROTECTEDPART) ASN1_SEQUENCE_cb(OSSL_CMP_MSG, ossl_cmp_msg_cb) = { ASN1_SIMPLE(OSSL_CMP_MSG, header, OSSL_CMP_PKIHEADER), ASN1_SIMPLE(OSSL_CMP_MSG, body, OSSL_CMP_PKIBODY), ASN1_EXP_OPT(OSSL_CMP_MSG, protection, ASN1_BIT_STRING, 0), /* OSSL_CMP_CMPCERTIFICATE is effectively X509 so it is used directly */ ASN1_EXP_SEQUENCE_OF_OPT(OSSL_CMP_MSG, extraCerts, X509, 1) } ASN1_SEQUENCE_END_cb(OSSL_CMP_MSG, OSSL_CMP_MSG) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CMP_MSG) ASN1_ITEM_TEMPLATE(OSSL_CMP_MSGS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CMP_MSGS, OSSL_CMP_MSG) ASN1_ITEM_TEMPLATE_END(OSSL_CMP_MSGS)
22,557
38.368237
80
c
openssl
openssl-master/crypto/cmp/cmp_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2023 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/cmperr.h> #include "crypto/cmperr.h" #ifndef OPENSSL_NO_CMP # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA CMP_str_reasons[] = { {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ALGORITHM_NOT_SUPPORTED), "algorithm not supported"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_BAD_CHECKAFTER_IN_POLLREP), "bad checkafter in pollrep"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_BAD_REQUEST_ID), "bad request id"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERTHASH_UNMATCHED), "certhash unmatched"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERTID_NOT_FOUND), "certid not found"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERTIFICATE_NOT_ACCEPTED), "certificate not accepted"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERTIFICATE_NOT_FOUND), "certificate not found"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERTREQMSG_NOT_FOUND), "certreqmsg not found"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERTRESPONSE_NOT_FOUND), "certresponse not found"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CERT_AND_KEY_DO_NOT_MATCH), "cert and key do not match"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_CHECKAFTER_OUT_OF_RANGE), "checkafter out of range"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ENCOUNTERED_KEYUPDATEWARNING), "encountered keyupdatewarning"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ENCOUNTERED_WAITING), "encountered waiting"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CALCULATING_PROTECTION), "error calculating protection"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_CERTCONF), "error creating certconf"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_CERTREP), "error creating certrep"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_CERTREQ), "error creating certreq"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_ERROR), "error creating error"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_GENM), "error creating genm"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_GENP), "error creating genp"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_PKICONF), "error creating pkiconf"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_POLLREP), "error creating pollrep"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_POLLREQ), "error creating pollreq"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_RP), "error creating rp"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_CREATING_RR), "error creating rr"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_PARSING_PKISTATUS), "error parsing pkistatus"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_PROCESSING_MESSAGE), "error processing message"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_PROTECTING_MESSAGE), "error protecting message"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_SETTING_CERTHASH), "error setting certhash"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_UNEXPECTED_CERTCONF), "error unexpected certconf"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_VALIDATING_PROTECTION), "error validating protection"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_ERROR_VALIDATING_SIGNATURE), "error validating signature"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_FAILED_BUILDING_OWN_CHAIN), "failed building own chain"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_FAILED_EXTRACTING_PUBKEY), "failed extracting pubkey"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_FAILURE_OBTAINING_RANDOM), "failure obtaining random"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_FAIL_INFO_OUT_OF_RANGE), "fail info out of range"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_GETTING_GENP), "getting genp"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_INVALID_ARGS), "invalid args"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_INVALID_GENP), "invalid genp"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_INVALID_OPTION), "invalid option"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_INVALID_ROOTCAKEYUPDATE), "invalid rootcakeyupdate"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_CERTID), "missing certid"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_KEY_INPUT_FOR_CREATING_PROTECTION), "missing key input for creating protection"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_KEY_USAGE_DIGITALSIGNATURE), "missing key usage digitalsignature"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_P10CSR), "missing p10csr"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_PBM_SECRET), "missing pbm secret"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_PRIVATE_KEY), "missing private key"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_PRIVATE_KEY_FOR_POPO), "missing private key for popo"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_PROTECTION), "missing protection"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_PUBLIC_KEY), "missing public key"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_REFERENCE_CERT), "missing reference cert"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_SECRET), "missing secret"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_SENDER_IDENTIFICATION), "missing sender identification"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_TRUST_ANCHOR), "missing trust anchor"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MISSING_TRUST_STORE), "missing trust store"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MULTIPLE_REQUESTS_NOT_SUPPORTED), "multiple requests not supported"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MULTIPLE_RESPONSES_NOT_SUPPORTED), "multiple responses not supported"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_MULTIPLE_SAN_SOURCES), "multiple san sources"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_NO_STDIO), "no stdio"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_NO_SUITABLE_SENDER_CERT), "no suitable sender cert"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_NULL_ARGUMENT), "null argument"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_PKIBODY_ERROR), "pkibody error"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_PKISTATUSINFO_NOT_FOUND), "pkistatusinfo not found"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_POLLING_FAILED), "polling failed"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_POTENTIALLY_INVALID_CERTIFICATE), "potentially invalid certificate"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_RECEIVED_ERROR), "received error"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_RECIPNONCE_UNMATCHED), "recipnonce unmatched"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_REQUEST_NOT_ACCEPTED), "request not accepted"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_REQUEST_REJECTED_BY_SERVER), "request rejected by server"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED), "sender generalname type not supported"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_SRVCERT_DOES_NOT_VALIDATE_MSG), "srvcert does not validate msg"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_TOTAL_TIMEOUT), "total timeout"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_TRANSACTIONID_UNMATCHED), "transactionid unmatched"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_TRANSFER_ERROR), "transfer error"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNCLEAN_CTX), "unclean ctx"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNEXPECTED_PKIBODY), "unexpected pkibody"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNEXPECTED_PKISTATUS), "unexpected pkistatus"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNEXPECTED_PVNO), "unexpected pvno"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNKNOWN_ALGORITHM_ID), "unknown algorithm id"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNKNOWN_CERT_TYPE), "unknown cert type"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNKNOWN_PKISTATUS), "unknown pkistatus"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNSUPPORTED_ALGORITHM), "unsupported algorithm"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNSUPPORTED_KEY_TYPE), "unsupported key type"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC), "unsupported protection alg dhbasedmac"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_VALUE_TOO_LARGE), "value too large"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_VALUE_TOO_SMALL), "value too small"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_WRONG_ALGORITHM_OID), "wrong algorithm oid"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_WRONG_CERTID), "wrong certid"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_WRONG_CERTID_IN_RP), "wrong certid in rp"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_WRONG_PBM_VALUE), "wrong pbm value"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_WRONG_RP_COMPONENT_COUNT), "wrong rp component count"}, {ERR_PACK(ERR_LIB_CMP, 0, CMP_R_WRONG_SERIAL_IN_RP), "wrong serial in rp"}, {0, NULL} }; # endif int ossl_err_load_CMP_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(CMP_str_reasons[0].error) == NULL) ERR_load_strings_const(CMP_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
8,942
46.823529
79
c
openssl
openssl-master/crypto/cmp/cmp_genm.c
/* * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright Siemens AG 2022 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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 "cmp_local.h" #include <openssl/cmp_util.h> static const X509_VERIFY_PARAM *get0_trustedStore_vpm(const OSSL_CMP_CTX *ctx) { const X509_STORE *ts = OSSL_CMP_CTX_get0_trustedStore(ctx); return ts == NULL ? NULL : X509_STORE_get0_param(ts); } static void cert_msg(const char *func, const char *file, int lineno, OSSL_CMP_severity level, OSSL_CMP_CTX *ctx, const char *source, X509 *cert, const char *msg) { char *subj = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0); ossl_cmp_print_log(level, ctx, func, file, lineno, level == OSSL_CMP_LOG_WARNING ? "WARN" : "ERR", "certificate from '%s' with subject '%s' %s", source, subj, msg); OPENSSL_free(subj); } /* use |type_CA| -1 (no CA type check) or 0 (must be EE) or 1 (must be CA) */ static int ossl_X509_check(OSSL_CMP_CTX *ctx, const char *source, X509 *cert, int type_CA, const X509_VERIFY_PARAM *vpm) { uint32_t ex_flags = X509_get_extension_flags(cert); int res = X509_cmp_timeframe(vpm, X509_get0_notBefore(cert), X509_get0_notAfter(cert)); int ret = res == 0; OSSL_CMP_severity level = vpm == NULL ? OSSL_CMP_LOG_WARNING : OSSL_CMP_LOG_ERR; if (!ret) cert_msg(OPENSSL_FUNC, OPENSSL_FILE, OPENSSL_LINE, level, ctx, source, cert, res > 0 ? "has expired" : "not yet valid"); if (type_CA >= 0 && (ex_flags & EXFLAG_V1) == 0) { int is_CA = (ex_flags & EXFLAG_CA) != 0; if ((type_CA != 0) != is_CA) { cert_msg(OPENSSL_FUNC, OPENSSL_FILE, OPENSSL_LINE, level, ctx, source, cert, is_CA ? "is not an EE cert" : "is not a CA cert"); ret = 0; } } return ret; } static int ossl_X509_check_all(OSSL_CMP_CTX *ctx, const char *source, STACK_OF(X509) *certs, int type_CA, const X509_VERIFY_PARAM *vpm) { int i; int ret = 1; for (i = 0; i < sk_X509_num(certs /* may be NULL */); i++) ret = ossl_X509_check(ctx, source, sk_X509_value(certs, i), type_CA, vpm) && ret; /* Having 'ret' after the '&&', all certs are checked. */ return ret; } static OSSL_CMP_ITAV *get_genm_itav(OSSL_CMP_CTX *ctx, OSSL_CMP_ITAV *req, /* gets consumed */ int expected, const char *desc) { STACK_OF(OSSL_CMP_ITAV) *itavs = NULL; int i, n; if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); goto err; } if (OSSL_CMP_CTX_get_status(ctx) != OSSL_CMP_PKISTATUS_unspecified) { ERR_raise_data(ERR_LIB_CMP, CMP_R_UNCLEAN_CTX, "client context in unsuitable state; should call CMPclient_reinit() before"); goto err; } if (!OSSL_CMP_CTX_push0_genm_ITAV(ctx, req)) goto err; req = NULL; itavs = OSSL_CMP_exec_GENM_ses(ctx); if (itavs == NULL) { if (OSSL_CMP_CTX_get_status(ctx) != OSSL_CMP_PKISTATUS_request) ERR_raise_data(ERR_LIB_CMP, CMP_R_GETTING_GENP, "with infoType %s", desc); return NULL; } if ((n = sk_OSSL_CMP_ITAV_num(itavs)) <= 0) { ERR_raise_data(ERR_LIB_CMP, CMP_R_INVALID_GENP, "response on genm requesting infoType %s does not include suitable value", desc); sk_OSSL_CMP_ITAV_free(itavs); return NULL; } if (n > 1) ossl_cmp_log2(WARN, ctx, "response on genm contains %d ITAVs; will use the first ITAV with infoType id-it-%s", n, desc); for (i = 0; i < n; i++) { OSSL_CMP_ITAV *itav = sk_OSSL_CMP_ITAV_shift(itavs); ASN1_OBJECT *obj = OSSL_CMP_ITAV_get0_type(itav); char name[128] = "genp contains InfoType '"; size_t offset = strlen(name); if (OBJ_obj2nid(obj) == expected) { for (i++; i < n; i++) OSSL_CMP_ITAV_free(sk_OSSL_CMP_ITAV_shift(itavs)); sk_OSSL_CMP_ITAV_free(itavs); return itav; } if (OBJ_obj2txt(name + offset, sizeof(name) - offset, obj, 0) < 0) strcat(name, "<unknown>"); ossl_cmp_log2(WARN, ctx, "%s' while expecting 'id-it-%s'", name, desc); OSSL_CMP_ITAV_free(itav); } ERR_raise_data(ERR_LIB_CMP, CMP_R_INVALID_GENP, "could not find any ITAV for %s", desc); err: sk_OSSL_CMP_ITAV_free(itavs); OSSL_CMP_ITAV_free(req); return NULL; } int OSSL_CMP_get1_caCerts(OSSL_CMP_CTX *ctx, STACK_OF(X509) **out) { OSSL_CMP_ITAV *req, *itav; STACK_OF(X509) *certs = NULL; int ret = 0; if (out == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } *out = NULL; if ((req = OSSL_CMP_ITAV_new_caCerts(NULL)) == NULL) return 0; if ((itav = get_genm_itav(ctx, req, NID_id_it_caCerts, "caCerts")) == NULL) return 0; if (!OSSL_CMP_ITAV_get0_caCerts(itav, &certs)) goto end; ret = 1; if (certs == NULL) /* no CA certificate available */ goto end; if (!ossl_X509_check_all(ctx, "genp", certs, 1 /* CA */, get0_trustedStore_vpm(ctx))) { ret = 0; goto end; } *out = sk_X509_new_reserve(NULL, sk_X509_num(certs)); if (!X509_add_certs(*out, certs, X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP)) { sk_X509_pop_free(*out, X509_free); *out = NULL; ret = 0; } end: OSSL_CMP_ITAV_free(itav); return ret; } static int selfsigned_verify_cb(int ok, X509_STORE_CTX *store_ctx) { if (ok == 0 && store_ctx != NULL && X509_STORE_CTX_get_error_depth(store_ctx) == 0 && X509_STORE_CTX_get_error(store_ctx) == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) { /* in this case, custom chain building */ int i; STACK_OF(X509) *trust; STACK_OF(X509) *chain = X509_STORE_CTX_get0_chain(store_ctx); STACK_OF(X509) *untrusted = X509_STORE_CTX_get0_untrusted(store_ctx); X509_STORE_CTX_check_issued_fn check_issued = X509_STORE_CTX_get_check_issued(store_ctx); X509 *cert = sk_X509_value(chain, 0); /* target cert */ X509 *issuer; for (i = 0; i < sk_X509_num(untrusted); i++) { cert = sk_X509_value(untrusted, i); if (!X509_add_cert(chain, cert, X509_ADD_FLAG_UP_REF)) return 0; } trust = X509_STORE_get1_all_certs(X509_STORE_CTX_get0_store(store_ctx)); for (i = 0; i < sk_X509_num(trust); i++) { issuer = sk_X509_value(trust, i); if ((*check_issued)(store_ctx, cert, issuer)) { if (X509_add_cert(chain, cert, X509_ADD_FLAG_UP_REF)) ok = 1; break; } } sk_X509_pop_free(trust, X509_free); return ok; } else { X509_STORE *ts = X509_STORE_CTX_get0_store(store_ctx); X509_STORE_CTX_verify_cb verify_cb; if (ts == NULL || (verify_cb = X509_STORE_get_verify_cb(ts)) == NULL) return ok; return (*verify_cb)(ok, store_ctx); } } /* vanilla X509_verify_cert() does not support self-signed certs as target */ static int verify_ss_cert(OSSL_LIB_CTX *libctx, const char *propq, X509_STORE *ts, STACK_OF(X509) *untrusted, X509 *target) { X509_STORE_CTX *csc = NULL; int ok = 0; if (ts == NULL || target == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_NULL_PARAMETER); return 0; } if ((csc = X509_STORE_CTX_new_ex(libctx, propq)) == NULL || !X509_STORE_CTX_init(csc, ts, target, untrusted)) goto err; X509_STORE_CTX_set_verify_cb(csc, selfsigned_verify_cb); ok = X509_verify_cert(csc) > 0; err: X509_STORE_CTX_free(csc); return ok; } static int verify_ss_cert_trans(OSSL_CMP_CTX *ctx, X509 *trusted /* may be NULL */, X509 *trans /* the only untrusted cert, may be NULL */, X509 *target, const char *desc) { X509_STORE *ts = OSSL_CMP_CTX_get0_trusted(ctx); STACK_OF(X509) *untrusted = NULL; int res = 0; if (trusted != NULL) { X509_VERIFY_PARAM *vpm = X509_STORE_get0_param(ts); if ((ts = X509_STORE_new()) == NULL) return 0; if (!X509_STORE_set1_param(ts, vpm) || !X509_STORE_add_cert(ts, trusted)) goto err; } if (trans != NULL && !ossl_x509_add_cert_new(&untrusted, trans, X509_ADD_FLAG_UP_REF)) goto err; res = verify_ss_cert(OSSL_CMP_CTX_get0_libctx(ctx), OSSL_CMP_CTX_get0_propq(ctx), ts, untrusted, target); if (!res) ERR_raise_data(ERR_LIB_CMP, CMP_R_INVALID_ROOTCAKEYUPDATE, "failed to validate %s certificate received in genp %s", desc, trusted == NULL ? "using trust store" : "with given certificate as trust anchor"); err: sk_X509_pop_free(untrusted, X509_free); if (trusted != NULL) X509_STORE_free(ts); return res; } int OSSL_CMP_get1_rootCaKeyUpdate(OSSL_CMP_CTX *ctx, const X509 *oldWithOld, X509 **newWithNew, X509 **newWithOld, X509 **oldWithNew) { X509 *oldWithOld_copy = NULL, *my_newWithOld, *my_oldWithNew; OSSL_CMP_ITAV *req, *itav; int res = 0; if (newWithNew == NULL) { ERR_raise(ERR_LIB_CMP, ERR_R_PASSED_NULL_PARAMETER); return 0; } *newWithNew = NULL; if ((req = OSSL_CMP_ITAV_new_rootCaCert(oldWithOld)) == NULL) return 0; itav = get_genm_itav(ctx, req, NID_id_it_rootCaKeyUpdate, "rootCaKeyUpdate"); if (itav == NULL) return 0; if (!OSSL_CMP_ITAV_get0_rootCaKeyUpdate(itav, newWithNew, &my_newWithOld, &my_oldWithNew)) goto end; if (*newWithNew == NULL) /* no root CA cert update available */ goto end; if ((oldWithOld_copy = X509_dup(oldWithOld)) == NULL && oldWithOld != NULL) goto end; if (!verify_ss_cert_trans(ctx, oldWithOld_copy, my_newWithOld, *newWithNew, "newWithNew")) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ROOTCAKEYUPDATE); goto end; } if (oldWithOld != NULL && my_oldWithNew != NULL && !verify_ss_cert_trans(ctx, *newWithNew, my_oldWithNew, oldWithOld_copy, "oldWithOld")) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ROOTCAKEYUPDATE); goto end; } if (!X509_up_ref(*newWithNew)) goto end; if (newWithOld != NULL && (*newWithOld = my_newWithOld) != NULL && !X509_up_ref(*newWithOld)) goto free; if (oldWithNew == NULL || (*oldWithNew = my_oldWithNew) == NULL || X509_up_ref(*oldWithNew)) { res = 1; goto end; } if (newWithOld != NULL) X509_free(*newWithOld); free: X509_free(*newWithNew); end: OSSL_CMP_ITAV_free(itav); X509_free(oldWithOld_copy); return res; }
11,833
33.103746
107
c
openssl
openssl-master/crypto/cmp/cmp_hdr.c
/* * Copyright 2007-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* CMP functions for PKIHeader handling */ #include "cmp_local.h" #include <openssl/rand.h> /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/asn1t.h> #include <openssl/cmp.h> #include <openssl/err.h> int ossl_cmp_hdr_set_pvno(OSSL_CMP_PKIHEADER *hdr, int pvno) { if (!ossl_assert(hdr != NULL)) return 0; return ASN1_INTEGER_set(hdr->pvno, pvno); } int ossl_cmp_hdr_get_pvno(const OSSL_CMP_PKIHEADER *hdr) { int64_t pvno; if (!ossl_assert(hdr != NULL)) return -1; if (!ASN1_INTEGER_get_int64(&pvno, hdr->pvno) || pvno < 0 || pvno > INT_MAX) return -1; return (int)pvno; } int ossl_cmp_hdr_get_protection_nid(const OSSL_CMP_PKIHEADER *hdr) { if (!ossl_assert(hdr != NULL) || hdr->protectionAlg == NULL) return NID_undef; return OBJ_obj2nid(hdr->protectionAlg->algorithm); } ASN1_OCTET_STRING *OSSL_CMP_HDR_get0_transactionID(const OSSL_CMP_PKIHEADER *hdr) { if (hdr == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return hdr->transactionID; } ASN1_OCTET_STRING *ossl_cmp_hdr_get0_senderNonce(const OSSL_CMP_PKIHEADER *hdr) { if (!ossl_assert(hdr != NULL)) return NULL; return hdr->senderNonce; } ASN1_OCTET_STRING *OSSL_CMP_HDR_get0_recipNonce(const OSSL_CMP_PKIHEADER *hdr) { if (hdr == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return hdr->recipNonce; } /* a NULL-DN as an empty sequence of RDNs */ int ossl_cmp_general_name_is_NULL_DN(GENERAL_NAME *name) { return name == NULL || (name->type == GEN_DIRNAME && IS_NULL_DN(name->d.directoryName)); } /* assign to *tgt a copy of src (which may be NULL to indicate an empty DN) */ static int set1_general_name(GENERAL_NAME **tgt, const X509_NAME *src) { GENERAL_NAME *name; if (!ossl_assert(tgt != NULL)) return 0; if ((name = GENERAL_NAME_new()) == NULL) goto err; name->type = GEN_DIRNAME; if (src == NULL) { /* NULL-DN */ if ((name->d.directoryName = X509_NAME_new()) == NULL) goto err; } else if (!X509_NAME_set(&name->d.directoryName, src)) { goto err; } GENERAL_NAME_free(*tgt); *tgt = name; return 1; err: GENERAL_NAME_free(name); return 0; } /* * Set the sender name in PKIHeader. * when nm is NULL, sender is set to an empty string * returns 1 on success, 0 on error */ int ossl_cmp_hdr_set1_sender(OSSL_CMP_PKIHEADER *hdr, const X509_NAME *nm) { if (!ossl_assert(hdr != NULL)) return 0; return set1_general_name(&hdr->sender, nm); } int ossl_cmp_hdr_set1_recipient(OSSL_CMP_PKIHEADER *hdr, const X509_NAME *nm) { if (!ossl_assert(hdr != NULL)) return 0; return set1_general_name(&hdr->recipient, nm); } int ossl_cmp_hdr_update_messageTime(OSSL_CMP_PKIHEADER *hdr) { if (!ossl_assert(hdr != NULL)) return 0; if (hdr->messageTime == NULL && (hdr->messageTime = ASN1_GENERALIZEDTIME_new()) == NULL) return 0; return ASN1_GENERALIZEDTIME_set(hdr->messageTime, time(NULL)) != NULL; } /* assign to *tgt a random byte array of given length */ static int set_random(ASN1_OCTET_STRING **tgt, OSSL_CMP_CTX *ctx, size_t len) { unsigned char *bytes = OPENSSL_malloc(len); int res = 0; if (bytes == NULL || RAND_bytes_ex(ctx->libctx, bytes, len, 0) <= 0) ERR_raise(ERR_LIB_CMP, CMP_R_FAILURE_OBTAINING_RANDOM); else res = ossl_cmp_asn1_octet_string_set1_bytes(tgt, bytes, len); OPENSSL_free(bytes); return res; } int ossl_cmp_hdr_set1_senderKID(OSSL_CMP_PKIHEADER *hdr, const ASN1_OCTET_STRING *senderKID) { if (!ossl_assert(hdr != NULL)) return 0; return ossl_cmp_asn1_octet_string_set1(&hdr->senderKID, senderKID); } /* push the given text string to the given PKIFREETEXT ft */ int ossl_cmp_hdr_push0_freeText(OSSL_CMP_PKIHEADER *hdr, ASN1_UTF8STRING *text) { if (!ossl_assert(hdr != NULL && text != NULL)) return 0; if (hdr->freeText == NULL && (hdr->freeText = sk_ASN1_UTF8STRING_new_null()) == NULL) return 0; return sk_ASN1_UTF8STRING_push(hdr->freeText, text); } int ossl_cmp_hdr_push1_freeText(OSSL_CMP_PKIHEADER *hdr, ASN1_UTF8STRING *text) { if (!ossl_assert(hdr != NULL && text != NULL)) return 0; if (hdr->freeText == NULL && (hdr->freeText = sk_ASN1_UTF8STRING_new_null()) == NULL) return 0; return ossl_cmp_sk_ASN1_UTF8STRING_push_str(hdr->freeText, (char *)text->data, text->length); } int ossl_cmp_hdr_generalInfo_push0_item(OSSL_CMP_PKIHEADER *hdr, OSSL_CMP_ITAV *itav) { if (!ossl_assert(hdr != NULL && itav != NULL)) return 0; return OSSL_CMP_ITAV_push0_stack_item(&hdr->generalInfo, itav); } int ossl_cmp_hdr_generalInfo_push1_items(OSSL_CMP_PKIHEADER *hdr, const STACK_OF(OSSL_CMP_ITAV) *itavs) { int i; OSSL_CMP_ITAV *itav; if (!ossl_assert(hdr != NULL)) return 0; for (i = 0; i < sk_OSSL_CMP_ITAV_num(itavs); i++) { itav = OSSL_CMP_ITAV_dup(sk_OSSL_CMP_ITAV_value(itavs, i)); if (itav == NULL) return 0; if (!ossl_cmp_hdr_generalInfo_push0_item(hdr, itav)) { OSSL_CMP_ITAV_free(itav); return 0; } } return 1; } int ossl_cmp_hdr_set_implicitConfirm(OSSL_CMP_PKIHEADER *hdr) { OSSL_CMP_ITAV *itav; ASN1_TYPE *asn1null; if (!ossl_assert(hdr != NULL)) return 0; asn1null = (ASN1_TYPE *)ASN1_NULL_new(); if (asn1null == NULL) return 0; if ((itav = OSSL_CMP_ITAV_create(OBJ_nid2obj(NID_id_it_implicitConfirm), asn1null)) == NULL) goto err; if (!ossl_cmp_hdr_generalInfo_push0_item(hdr, itav)) goto err; return 1; err: ASN1_TYPE_free(asn1null); OSSL_CMP_ITAV_free(itav); return 0; } /* return 1 if implicitConfirm in the generalInfo field of the header is set */ int ossl_cmp_hdr_has_implicitConfirm(const OSSL_CMP_PKIHEADER *hdr) { int itavCount; int i; OSSL_CMP_ITAV *itav; if (!ossl_assert(hdr != NULL)) return 0; itavCount = sk_OSSL_CMP_ITAV_num(hdr->generalInfo); for (i = 0; i < itavCount; i++) { itav = sk_OSSL_CMP_ITAV_value(hdr->generalInfo, i); if (itav != NULL && OBJ_obj2nid(itav->infoType) == NID_id_it_implicitConfirm) return 1; } return 0; } /* * set ctx->transactionID in CMP header * if ctx->transactionID is NULL, a random one is created with 128 bit * according to section 5.1.1: * * It is RECOMMENDED that the clients fill the transactionID field with * 128 bits of (pseudo-) random data for the start of a transaction to * reduce the probability of having the transactionID in use at the server. */ int ossl_cmp_hdr_set_transactionID(OSSL_CMP_CTX *ctx, OSSL_CMP_PKIHEADER *hdr) { if (ctx->transactionID == NULL) { char *tid; if (!set_random(&ctx->transactionID, ctx, OSSL_CMP_TRANSACTIONID_LENGTH)) return 0; tid = i2s_ASN1_OCTET_STRING(NULL, ctx->transactionID); if (tid != NULL) ossl_cmp_log1(DEBUG, ctx, "Starting new transaction with ID=%s", tid); OPENSSL_free(tid); } return ossl_cmp_asn1_octet_string_set1(&hdr->transactionID, ctx->transactionID); } /* fill in all fields of the hdr according to the info given in ctx */ int ossl_cmp_hdr_init(OSSL_CMP_CTX *ctx, OSSL_CMP_PKIHEADER *hdr) { const X509_NAME *sender; const X509_NAME *rcp = NULL; if (!ossl_assert(ctx != NULL && hdr != NULL)) return 0; /* set the CMP version */ if (!ossl_cmp_hdr_set_pvno(hdr, OSSL_CMP_PVNO)) return 0; /* * If no protection cert nor oldCert nor CSR nor subject is given, * sender name is not known to the client and thus set to NULL-DN */ sender = ctx->cert != NULL ? X509_get_subject_name(ctx->cert) : ctx->oldCert != NULL ? X509_get_subject_name(ctx->oldCert) : ctx->p10CSR != NULL ? X509_REQ_get_subject_name(ctx->p10CSR) : ctx->subjectName; if (!ossl_cmp_hdr_set1_sender(hdr, sender)) return 0; /* determine recipient entry in PKIHeader */ if (ctx->recipient != NULL) rcp = ctx->recipient; else if (ctx->srvCert != NULL) rcp = X509_get_subject_name(ctx->srvCert); else if (ctx->issuer != NULL) rcp = ctx->issuer; else if (ctx->oldCert != NULL) rcp = X509_get_issuer_name(ctx->oldCert); else if (ctx->cert != NULL) rcp = X509_get_issuer_name(ctx->cert); if (!ossl_cmp_hdr_set1_recipient(hdr, rcp)) return 0; /* set current time as message time */ if (!ossl_cmp_hdr_update_messageTime(hdr)) return 0; if (ctx->recipNonce != NULL && !ossl_cmp_asn1_octet_string_set1(&hdr->recipNonce, ctx->recipNonce)) return 0; if (!ossl_cmp_hdr_set_transactionID(ctx, hdr)) return 0; /*- * set random senderNonce * according to section 5.1.1: * * senderNonce present * -- 128 (pseudo-)random bits * The senderNonce and recipNonce fields protect the PKIMessage against * replay attacks. The senderNonce will typically be 128 bits of * (pseudo-) random data generated by the sender, whereas the recipNonce * is copied from the senderNonce of the previous message in the * transaction. */ if (!set_random(&hdr->senderNonce, ctx, OSSL_CMP_SENDERNONCE_LENGTH)) return 0; /* store senderNonce - for cmp with recipNonce in next outgoing msg */ if (!OSSL_CMP_CTX_set1_senderNonce(ctx, hdr->senderNonce)) return 0; /*- * freeText [7] PKIFreeText OPTIONAL, * -- this may be used to indicate context-specific instructions * -- (this field is intended for human consumption) */ if (ctx->freeText != NULL && !ossl_cmp_hdr_push1_freeText(hdr, ctx->freeText)) return 0; return 1; }
10,891
28.437838
80
c
openssl
openssl-master/crypto/cmp/cmp_http.c
/* * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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 <openssl/asn1t.h> #include <openssl/http.h> #include <openssl/cmp.h> #include "cmp_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include <ctype.h> #include <fcntl.h> #include <stdlib.h> #include <openssl/bio.h> #include <openssl/buffer.h> #include <openssl/err.h> static int keep_alive(int keep_alive, int body_type) { if (keep_alive != 0 /* * Ask for persistent connection only if may need more round trips. * Do so even with disableConfirm because polling might be needed. */ && body_type != OSSL_CMP_PKIBODY_IR && body_type != OSSL_CMP_PKIBODY_CR && body_type != OSSL_CMP_PKIBODY_P10CR && body_type != OSSL_CMP_PKIBODY_KUR && body_type != OSSL_CMP_PKIBODY_POLLREQ) keep_alive = 0; return keep_alive; } /* * Send the PKIMessage req and on success return the response, else NULL. */ OSSL_CMP_MSG *OSSL_CMP_MSG_http_perform(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *req) { char server_port[32] = { '\0' }; STACK_OF(CONF_VALUE) *headers = NULL; const char content_type_pkix[] = "application/pkixcmp"; int tls_used; const ASN1_ITEM *it = ASN1_ITEM_rptr(OSSL_CMP_MSG); BIO *req_mem, *rsp; OSSL_CMP_MSG *res = NULL; if (ctx == NULL || req == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } if (!X509V3_add_value("Pragma", "no-cache", &headers)) return NULL; if ((req_mem = ASN1_item_i2d_mem_bio(it, (const ASN1_VALUE *)req)) == NULL) goto err; if (ctx->serverPort != 0) BIO_snprintf(server_port, sizeof(server_port), "%d", ctx->serverPort); tls_used = OSSL_CMP_CTX_get_http_cb_arg(ctx) != NULL; if (ctx->http_ctx == NULL) ossl_cmp_log3(DEBUG, ctx, "connecting to CMP server %s:%s%s", ctx->server, server_port, tls_used ? " using TLS" : ""); rsp = OSSL_HTTP_transfer(&ctx->http_ctx, ctx->server, server_port, ctx->serverPath, tls_used, ctx->proxy, ctx->no_proxy, NULL /* bio */, NULL /* rbio */, ctx->http_cb, OSSL_CMP_CTX_get_http_cb_arg(ctx), 0 /* buf_size */, headers, content_type_pkix, req_mem, content_type_pkix, 1 /* expect_asn1 */, OSSL_HTTP_DEFAULT_MAX_RESP_LEN, ctx->msg_timeout, keep_alive(ctx->keep_alive, req->body->type)); BIO_free(req_mem); res = (OSSL_CMP_MSG *)ASN1_item_d2i_bio(it, rsp, NULL); BIO_free(rsp); if (ctx->http_ctx == NULL) ossl_cmp_debug(ctx, "disconnected from CMP server"); /* * Note that on normal successful end of the transaction the connection * is not closed at this level, but this will be done by the CMP client * application via OSSL_CMP_CTX_free() or OSSL_CMP_CTX_reinit(). */ if (res != NULL) ossl_cmp_debug(ctx, "finished reading response from CMP server"); err: sk_CONF_VALUE_pop_free(headers, X509V3_conf_free); return res; }
3,721
34.788462
79
c
openssl
openssl-master/crypto/cmp/cmp_protect.c
/* * Copyright 2007-2022 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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 "cmp_local.h" #include "crypto/asn1.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/asn1t.h> #include <openssl/cmp.h> #include <openssl/crmf.h> #include <openssl/err.h> #include <openssl/x509.h> /* * This function is also used by the internal verify_PBMAC() in cmp_vfy.c. * * Calculate protection for given PKImessage according to * the algorithm and parameters in the message header's protectionAlg * using the credentials, library context, and property criteria in the ctx. * * returns ASN1_BIT_STRING representing the protection on success, else NULL */ ASN1_BIT_STRING *ossl_cmp_calc_protection(const OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg) { ASN1_BIT_STRING *prot = NULL; OSSL_CMP_PROTECTEDPART prot_part; const ASN1_OBJECT *algorOID = NULL; const void *ppval = NULL; int pptype = 0; if (!ossl_assert(ctx != NULL && msg != NULL)) return NULL; /* construct data to be signed */ prot_part.header = msg->header; prot_part.body = msg->body; if (msg->header->protectionAlg == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_UNKNOWN_ALGORITHM_ID); return NULL; } X509_ALGOR_get0(&algorOID, &pptype, &ppval, msg->header->protectionAlg); if (OBJ_obj2nid(algorOID) == NID_id_PasswordBasedMAC) { int len; size_t prot_part_der_len; unsigned char *prot_part_der = NULL; size_t sig_len; unsigned char *protection = NULL; OSSL_CRMF_PBMPARAMETER *pbm = NULL; ASN1_STRING *pbm_str = NULL; const unsigned char *pbm_str_uc = NULL; if (ctx->secretValue == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_PBM_SECRET); return NULL; } if (ppval == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CALCULATING_PROTECTION); return NULL; } len = i2d_OSSL_CMP_PROTECTEDPART(&prot_part, &prot_part_der); if (len < 0 || prot_part_der == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CALCULATING_PROTECTION); goto end; } prot_part_der_len = (size_t)len; pbm_str = (ASN1_STRING *)ppval; pbm_str_uc = pbm_str->data; pbm = d2i_OSSL_CRMF_PBMPARAMETER(NULL, &pbm_str_uc, pbm_str->length); if (pbm == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_WRONG_ALGORITHM_OID); goto end; } if (!OSSL_CRMF_pbm_new(ctx->libctx, ctx->propq, pbm, prot_part_der, prot_part_der_len, ctx->secretValue->data, ctx->secretValue->length, &protection, &sig_len)) goto end; if ((prot = ASN1_BIT_STRING_new()) == NULL) goto end; /* OpenSSL by default encodes all bit strings as ASN.1 NamedBitList */ ossl_asn1_string_set_bits_left(prot, 0); if (!ASN1_BIT_STRING_set(prot, protection, sig_len)) { ASN1_BIT_STRING_free(prot); prot = NULL; } end: OSSL_CRMF_PBMPARAMETER_free(pbm); OPENSSL_free(protection); OPENSSL_free(prot_part_der); return prot; } else { int md_nid; const EVP_MD *md = NULL; if (ctx->pkey == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_KEY_INPUT_FOR_CREATING_PROTECTION); return NULL; } if (!OBJ_find_sigid_algs(OBJ_obj2nid(algorOID), &md_nid, NULL) || (md = EVP_get_digestbynid(md_nid)) == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_UNKNOWN_ALGORITHM_ID); return NULL; } if ((prot = ASN1_BIT_STRING_new()) == NULL) return NULL; if (ASN1_item_sign_ex(ASN1_ITEM_rptr(OSSL_CMP_PROTECTEDPART), NULL, NULL, prot, &prot_part, NULL, ctx->pkey, md, ctx->libctx, ctx->propq)) return prot; ASN1_BIT_STRING_free(prot); return NULL; } } /* ctx is not const just because ctx->chain may get adapted */ int ossl_cmp_msg_add_extraCerts(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg) { if (!ossl_assert(ctx != NULL && msg != NULL)) return 0; /* Add first ctx->cert and its chain if using signature-based protection */ if (!ctx->unprotectedSend && ctx->secretValue == NULL && ctx->cert != NULL && ctx->pkey != NULL) { int prepend = X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP | X509_ADD_FLAG_PREPEND | X509_ADD_FLAG_NO_SS; /* if not yet done try to build chain using available untrusted certs */ if (ctx->chain == NULL) { ossl_cmp_debug(ctx, "trying to build chain for own CMP signer cert"); ctx->chain = X509_build_chain(ctx->cert, ctx->untrusted, NULL, 0, ctx->libctx, ctx->propq); if (ctx->chain != NULL) { ossl_cmp_debug(ctx, "success building chain for own CMP signer cert"); } else { /* dump errors to avoid confusion when printing further ones */ OSSL_CMP_CTX_print_errors(ctx); ossl_cmp_warn(ctx, "could not build chain for own CMP signer cert"); } } if (ctx->chain != NULL) { if (!ossl_x509_add_certs_new(&msg->extraCerts, ctx->chain, prepend)) return 0; } else { /* make sure that at least our own signer cert is included first */ if (!ossl_x509_add_cert_new(&msg->extraCerts, ctx->cert, prepend)) return 0; ossl_cmp_debug(ctx, "fallback: adding just own CMP signer cert"); } } /* add any additional certificates from ctx->extraCertsOut */ if (!ossl_x509_add_certs_new(&msg->extraCerts, ctx->extraCertsOut, X509_ADD_FLAG_UP_REF | X509_ADD_FLAG_NO_DUP)) return 0; /* in case extraCerts are empty list avoid empty ASN.1 sequence */ if (sk_X509_num(msg->extraCerts) == 0) { sk_X509_free(msg->extraCerts); msg->extraCerts = NULL; } return 1; } /* * Create an X509_ALGOR structure for PasswordBasedMAC protection based on * the pbm settings in the context */ static X509_ALGOR *pbmac_algor(const OSSL_CMP_CTX *ctx) { OSSL_CRMF_PBMPARAMETER *pbm = NULL; unsigned char *pbm_der = NULL; int pbm_der_len; ASN1_STRING *pbm_str = NULL; X509_ALGOR *alg = NULL; if (!ossl_assert(ctx != NULL)) return NULL; pbm = OSSL_CRMF_pbmp_new(ctx->libctx, ctx->pbm_slen, EVP_MD_get_type(ctx->pbm_owf), ctx->pbm_itercnt, ctx->pbm_mac); pbm_str = ASN1_STRING_new(); if (pbm == NULL || pbm_str == NULL) goto err; if ((pbm_der_len = i2d_OSSL_CRMF_PBMPARAMETER(pbm, &pbm_der)) < 0) goto err; if (!ASN1_STRING_set(pbm_str, pbm_der, pbm_der_len)) goto err; alg = ossl_X509_ALGOR_from_nid(NID_id_PasswordBasedMAC, V_ASN1_SEQUENCE, pbm_str); err: if (alg == NULL) ASN1_STRING_free(pbm_str); OPENSSL_free(pbm_der); OSSL_CRMF_PBMPARAMETER_free(pbm); return alg; } static X509_ALGOR *sig_algor(const OSSL_CMP_CTX *ctx) { int nid = 0; if (!OBJ_find_sigid_by_algs(&nid, EVP_MD_get_type(ctx->digest), EVP_PKEY_get_id(ctx->pkey))) { ERR_raise(ERR_LIB_CMP, CMP_R_UNSUPPORTED_KEY_TYPE); return 0; } return ossl_X509_ALGOR_from_nid(nid, V_ASN1_UNDEF, NULL); } static int set_senderKID(const OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg, const ASN1_OCTET_STRING *id) { if (id == NULL) id = ctx->referenceValue; /* standard for PBM, fallback for sig-based */ return id == NULL || ossl_cmp_hdr_set1_senderKID(msg->header, id); } /* ctx is not const just because ctx->chain may get adapted */ int ossl_cmp_msg_protect(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg) { if (!ossl_assert(ctx != NULL && msg != NULL)) return 0; /* * For the case of re-protection remove pre-existing protection. * Does not remove any pre-existing extraCerts. */ X509_ALGOR_free(msg->header->protectionAlg); msg->header->protectionAlg = NULL; ASN1_BIT_STRING_free(msg->protection); msg->protection = NULL; if (ctx->unprotectedSend) { if (!set_senderKID(ctx, msg, NULL)) goto err; } else if (ctx->secretValue != NULL) { /* use PasswordBasedMac according to 5.1.3.1 if secretValue is given */ if ((msg->header->protectionAlg = pbmac_algor(ctx)) == NULL) goto err; if (!set_senderKID(ctx, msg, NULL)) goto err; /* * will add any additional certificates from ctx->extraCertsOut * while not needed to validate the protection certificate, * the option to do this might be handy for certain use cases */ } else if (ctx->cert != NULL && ctx->pkey != NULL) { /* use MSG_SIG_ALG according to 5.1.3.3 if client cert and key given */ /* make sure that key and certificate match */ if (!X509_check_private_key(ctx->cert, ctx->pkey)) { ERR_raise(ERR_LIB_CMP, CMP_R_CERT_AND_KEY_DO_NOT_MATCH); goto err; } if ((msg->header->protectionAlg = sig_algor(ctx)) == NULL) goto err; /* set senderKID to keyIdentifier of the cert according to 5.1.1 */ if (!set_senderKID(ctx, msg, X509_get0_subject_key_id(ctx->cert))) goto err; /* * will add ctx->cert followed, if possible, by its chain built * from ctx->untrusted, and then ctx->extraCertsOut */ } else { ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_KEY_INPUT_FOR_CREATING_PROTECTION); goto err; } if (!ctx->unprotectedSend && ((msg->protection = ossl_cmp_calc_protection(ctx, msg)) == NULL)) goto err; /* * For signature-based protection add ctx->cert followed by its chain. * Finally add any additional certificates from ctx->extraCertsOut; * even if not needed to validate the protection * the option to do this might be handy for certain use cases. */ if (!ossl_cmp_msg_add_extraCerts(ctx, msg)) goto err; /* * As required by RFC 4210 section 5.1.1., if the sender name is not known * to the client it set to NULL-DN. In this case for identification at least * the senderKID must be set, where we took the referenceValue as fallback. */ if (!(ossl_cmp_general_name_is_NULL_DN(msg->header->sender) && msg->header->senderKID == NULL)) return 1; ERR_raise(ERR_LIB_CMP, CMP_R_MISSING_SENDER_IDENTIFICATION); err: ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROTECTING_MESSAGE); return 0; }
11,492
34.915625
81
c
openssl
openssl-master/crypto/cmp/cmp_server.c
/* * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* general CMP server functions */ #include <openssl/asn1t.h> #include "cmp_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/cmp.h> #include <openssl/err.h> /* the context for the generic CMP server */ struct ossl_cmp_srv_ctx_st { void *custom_ctx; /* pointer to application-specific server context */ OSSL_CMP_CTX *ctx; /* Client CMP context, reusing transactionID etc. */ int certReqId; /* id of last ir/cr/kur, OSSL_CMP_CERTREQID_NONE for p10cr */ OSSL_CMP_SRV_cert_request_cb_t process_cert_request; OSSL_CMP_SRV_rr_cb_t process_rr; OSSL_CMP_SRV_genm_cb_t process_genm; OSSL_CMP_SRV_error_cb_t process_error; OSSL_CMP_SRV_certConf_cb_t process_certConf; OSSL_CMP_SRV_pollReq_cb_t process_pollReq; int sendUnprotectedErrors; /* Send error and rejection msgs unprotected */ int acceptUnprotected; /* Accept requests with no/invalid prot. */ int acceptRAVerified; /* Accept ir/cr/kur with POPO RAVerified */ int grantImplicitConfirm; /* Grant implicit confirmation if requested */ }; /* OSSL_CMP_SRV_CTX */ void OSSL_CMP_SRV_CTX_free(OSSL_CMP_SRV_CTX *srv_ctx) { if (srv_ctx == NULL) return; OSSL_CMP_CTX_free(srv_ctx->ctx); OPENSSL_free(srv_ctx); } OSSL_CMP_SRV_CTX *OSSL_CMP_SRV_CTX_new(OSSL_LIB_CTX *libctx, const char *propq) { OSSL_CMP_SRV_CTX *ctx = OPENSSL_zalloc(sizeof(OSSL_CMP_SRV_CTX)); if (ctx == NULL) goto err; if ((ctx->ctx = OSSL_CMP_CTX_new(libctx, propq)) == NULL) goto err; ctx->certReqId = OSSL_CMP_CERTREQID_INVALID; /* all other elements are initialized to 0 or NULL, respectively */ return ctx; err: OSSL_CMP_SRV_CTX_free(ctx); return NULL; } int OSSL_CMP_SRV_CTX_init(OSSL_CMP_SRV_CTX *srv_ctx, void *custom_ctx, OSSL_CMP_SRV_cert_request_cb_t process_cert_request, OSSL_CMP_SRV_rr_cb_t process_rr, OSSL_CMP_SRV_genm_cb_t process_genm, OSSL_CMP_SRV_error_cb_t process_error, OSSL_CMP_SRV_certConf_cb_t process_certConf, OSSL_CMP_SRV_pollReq_cb_t process_pollReq) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } srv_ctx->custom_ctx = custom_ctx; srv_ctx->process_cert_request = process_cert_request; srv_ctx->process_rr = process_rr; srv_ctx->process_genm = process_genm; srv_ctx->process_error = process_error; srv_ctx->process_certConf = process_certConf; srv_ctx->process_pollReq = process_pollReq; return 1; } OSSL_CMP_CTX *OSSL_CMP_SRV_CTX_get0_cmp_ctx(const OSSL_CMP_SRV_CTX *srv_ctx) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return srv_ctx->ctx; } void *OSSL_CMP_SRV_CTX_get0_custom_ctx(const OSSL_CMP_SRV_CTX *srv_ctx) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return srv_ctx->custom_ctx; } int OSSL_CMP_SRV_CTX_set_send_unprotected_errors(OSSL_CMP_SRV_CTX *srv_ctx, int val) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } srv_ctx->sendUnprotectedErrors = val != 0; return 1; } int OSSL_CMP_SRV_CTX_set_accept_unprotected(OSSL_CMP_SRV_CTX *srv_ctx, int val) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } srv_ctx->acceptUnprotected = val != 0; return 1; } int OSSL_CMP_SRV_CTX_set_accept_raverified(OSSL_CMP_SRV_CTX *srv_ctx, int val) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } srv_ctx->acceptRAVerified = val != 0; return 1; } int OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(OSSL_CMP_SRV_CTX *srv_ctx, int val) { if (srv_ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } srv_ctx->grantImplicitConfirm = val != 0; return 1; } /* * Processes an ir/cr/p10cr/kur and returns a certification response. * Only handles the first certification request contained in req * returns an ip/cp/kup on success and NULL on error */ static OSSL_CMP_MSG *process_cert_request(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_MSG *msg = NULL; OSSL_CMP_PKISI *si = NULL; X509 *certOut = NULL; STACK_OF(X509) *chainOut = NULL, *caPubs = NULL; const OSSL_CRMF_MSG *crm = NULL; const X509_REQ *p10cr = NULL; int bodytype; int certReqId; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL)) return NULL; switch (OSSL_CMP_MSG_get_bodytype(req)) { case OSSL_CMP_PKIBODY_P10CR: case OSSL_CMP_PKIBODY_CR: bodytype = OSSL_CMP_PKIBODY_CP; break; case OSSL_CMP_PKIBODY_IR: bodytype = OSSL_CMP_PKIBODY_IP; break; case OSSL_CMP_PKIBODY_KUR: bodytype = OSSL_CMP_PKIBODY_KUP; break; default: ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); return NULL; } if (OSSL_CMP_MSG_get_bodytype(req) == OSSL_CMP_PKIBODY_P10CR) { certReqId = OSSL_CMP_CERTREQID_NONE; /* p10cr does not include an Id */ p10cr = req->body->value.p10cr; } else { OSSL_CRMF_MSGS *reqs = req->body->value.ir; /* same for cr and kur */ if (sk_OSSL_CRMF_MSG_num(reqs) != 1) { ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_REQUESTS_NOT_SUPPORTED); return NULL; } if ((crm = sk_OSSL_CRMF_MSG_value(reqs, OSSL_CMP_CERTREQID)) == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_CERTREQMSG_NOT_FOUND); return NULL; } certReqId = OSSL_CRMF_MSG_get_certReqId(crm); if (certReqId != OSSL_CMP_CERTREQID) { ERR_raise(ERR_LIB_CMP, CMP_R_BAD_REQUEST_ID); return 0; } } srv_ctx->certReqId = certReqId; if (!ossl_cmp_verify_popo(srv_ctx->ctx, req, srv_ctx->acceptRAVerified)) { /* Proof of possession could not be verified */ si = OSSL_CMP_STATUSINFO_new(OSSL_CMP_PKISTATUS_rejection, 1 << OSSL_CMP_PKIFAILUREINFO_badPOP, ERR_reason_error_string(ERR_peek_error())); if (si == NULL) return NULL; } else { OSSL_CMP_PKIHEADER *hdr = OSSL_CMP_MSG_get0_header(req); si = srv_ctx->process_cert_request(srv_ctx, req, certReqId, crm, p10cr, &certOut, &chainOut, &caPubs); if (si == NULL) goto err; /* set OSSL_CMP_OPT_IMPLICIT_CONFIRM if and only if transaction ends */ if (!OSSL_CMP_CTX_set_option(srv_ctx->ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM, ossl_cmp_hdr_has_implicitConfirm(hdr) && srv_ctx->grantImplicitConfirm /* do not set if polling starts: */ && certOut != NULL)) goto err; } msg = ossl_cmp_certrep_new(srv_ctx->ctx, bodytype, certReqId, si, certOut, NULL /* enc */, chainOut, caPubs, srv_ctx->sendUnprotectedErrors); /* When supporting OSSL_CRMF_POPO_KEYENC, "enc" will need to be set */ if (msg == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_CERTREP); err: OSSL_CMP_PKISI_free(si); X509_free(certOut); OSSL_STACK_OF_X509_free(chainOut); OSSL_STACK_OF_X509_free(caPubs); return msg; } static OSSL_CMP_MSG *process_rr(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_MSG *msg = NULL; OSSL_CMP_REVDETAILS *details; OSSL_CRMF_CERTID *certId = NULL; OSSL_CRMF_CERTTEMPLATE *tmpl; const X509_NAME *issuer; const ASN1_INTEGER *serial; OSSL_CMP_PKISI *si; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL)) return NULL; if (sk_OSSL_CMP_REVDETAILS_num(req->body->value.rr) != 1) { ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_REQUESTS_NOT_SUPPORTED); return NULL; } if ((details = sk_OSSL_CMP_REVDETAILS_value(req->body->value.rr, OSSL_CMP_REVREQSID)) == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_PROCESSING_MESSAGE); return NULL; } tmpl = details->certDetails; issuer = OSSL_CRMF_CERTTEMPLATE_get0_issuer(tmpl); serial = OSSL_CRMF_CERTTEMPLATE_get0_serialNumber(tmpl); if (issuer != NULL && serial != NULL && (certId = OSSL_CRMF_CERTID_gen(issuer, serial)) == NULL) return NULL; if ((si = srv_ctx->process_rr(srv_ctx, req, issuer, serial)) == NULL) goto err; if ((msg = ossl_cmp_rp_new(srv_ctx->ctx, si, certId, srv_ctx->sendUnprotectedErrors)) == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_RR); err: OSSL_CRMF_CERTID_free(certId); OSSL_CMP_PKISI_free(si); return msg; } /* * Processes genm and creates a genp message mirroring the contents of the * incoming message */ static OSSL_CMP_MSG *process_genm(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_GENMSGCONTENT *itavs; OSSL_CMP_MSG *msg; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL)) return NULL; if (!srv_ctx->process_genm(srv_ctx, req, req->body->value.genm, &itavs)) return NULL; msg = ossl_cmp_genp_new(srv_ctx->ctx, itavs); sk_OSSL_CMP_ITAV_pop_free(itavs, OSSL_CMP_ITAV_free); return msg; } static OSSL_CMP_MSG *process_error(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_ERRORMSGCONTENT *errorContent; OSSL_CMP_MSG *msg; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL)) return NULL; errorContent = req->body->value.error; srv_ctx->process_error(srv_ctx, req, errorContent->pKIStatusInfo, errorContent->errorCode, errorContent->errorDetails); if ((msg = ossl_cmp_pkiconf_new(srv_ctx->ctx)) == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_PKICONF); return msg; } static OSSL_CMP_MSG *process_certConf(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_CTX *ctx; OSSL_CMP_CERTCONFIRMCONTENT *ccc; int num; OSSL_CMP_MSG *msg = NULL; OSSL_CMP_CERTSTATUS *status = NULL; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL)) return NULL; ctx = srv_ctx->ctx; ccc = req->body->value.certConf; num = sk_OSSL_CMP_CERTSTATUS_num(ccc); if (OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM) == 1 || ctx->status != OSSL_CMP_PKISTATUS_trans) { ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_UNEXPECTED_CERTCONF); return NULL; } if (num == 0) { ossl_cmp_err(ctx, "certificate rejected by client"); } else { if (num > 1) ossl_cmp_warn(ctx, "All CertStatus but the first will be ignored"); status = sk_OSSL_CMP_CERTSTATUS_value(ccc, OSSL_CMP_CERTREQID); } if (status != NULL) { int certReqId = ossl_cmp_asn1_get_int(status->certReqId); ASN1_OCTET_STRING *certHash = status->certHash; OSSL_CMP_PKISI *si = status->statusInfo; if (certReqId != srv_ctx->certReqId) { ERR_raise(ERR_LIB_CMP, CMP_R_BAD_REQUEST_ID); return NULL; } if (!srv_ctx->process_certConf(srv_ctx, req, certReqId, certHash, si)) return NULL; /* reason code may be: CMP_R_CERTHASH_UNMATCHED */ if (si != NULL && ossl_cmp_pkisi_get_status(si) != OSSL_CMP_PKISTATUS_accepted) { int pki_status = ossl_cmp_pkisi_get_status(si); const char *str = ossl_cmp_PKIStatus_to_string(pki_status); ossl_cmp_log2(INFO, ctx, "certificate rejected by client %s %s", str == NULL ? "without" : "with", str == NULL ? "PKIStatus" : str); } } if ((msg = ossl_cmp_pkiconf_new(ctx)) == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_PKICONF); return msg; } static OSSL_CMP_MSG *process_pollReq(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_POLLREQCONTENT *prc; OSSL_CMP_POLLREQ *pr; int certReqId; OSSL_CMP_MSG *certReq; int64_t check_after = 0; OSSL_CMP_MSG *msg = NULL; if (!ossl_assert(srv_ctx != NULL && srv_ctx->ctx != NULL && req != NULL)) return NULL; prc = req->body->value.pollReq; if (sk_OSSL_CMP_POLLREQ_num(prc) != 1) { ERR_raise(ERR_LIB_CMP, CMP_R_MULTIPLE_REQUESTS_NOT_SUPPORTED); return NULL; } pr = sk_OSSL_CMP_POLLREQ_value(prc, OSSL_CMP_CERTREQID); certReqId = ossl_cmp_asn1_get_int(pr->certReqId); if (certReqId != srv_ctx->certReqId) { ERR_raise(ERR_LIB_CMP, CMP_R_BAD_REQUEST_ID); return NULL; } if (!srv_ctx->process_pollReq(srv_ctx, req, certReqId, &certReq, &check_after)) return NULL; if (certReq != NULL) { msg = process_cert_request(srv_ctx, certReq); OSSL_CMP_MSG_free(certReq); } else { if ((msg = ossl_cmp_pollRep_new(srv_ctx->ctx, certReqId, check_after)) == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_ERROR_CREATING_POLLREP); } return msg; } /* * Determine whether missing/invalid protection of request message is allowed. * Return 1 on acceptance, 0 on rejection, or -1 on (internal) error. */ static int unprotected_exception(const OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *req, int invalid_protection, int accept_unprotected_requests) { if (!ossl_assert(ctx != NULL && req != NULL)) return -1; if (accept_unprotected_requests) { ossl_cmp_log1(WARN, ctx, "ignoring %s protection of request message", invalid_protection ? "invalid" : "missing"); return 1; } if (OSSL_CMP_MSG_get_bodytype(req) == OSSL_CMP_PKIBODY_ERROR && OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_UNPROTECTED_ERRORS) == 1) { ossl_cmp_warn(ctx, "ignoring missing protection of error message"); return 1; } return 0; } /* * returns created message and NULL on internal error */ OSSL_CMP_MSG *OSSL_CMP_SRV_process_request(OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_CTX *ctx; ASN1_OCTET_STRING *backup_secret; OSSL_CMP_PKIHEADER *hdr; int req_type, rsp_type; int req_verified = 0; OSSL_CMP_MSG *rsp = NULL; if (srv_ctx == NULL || srv_ctx->ctx == NULL || req == NULL || req->body == NULL || (hdr = OSSL_CMP_MSG_get0_header(req)) == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } ctx = srv_ctx->ctx; backup_secret = ctx->secretValue; req_type = OSSL_CMP_MSG_get_bodytype(req); ossl_cmp_log1(DEBUG, ctx, "received %s", ossl_cmp_bodytype_to_string(req_type)); /* * Some things need to be done already before validating the message in * order to be able to send an error message as far as needed and possible. */ if (hdr->sender->type != GEN_DIRNAME) { ERR_raise(ERR_LIB_CMP, CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED); goto err; } if (!OSSL_CMP_CTX_set1_recipient(ctx, hdr->sender->d.directoryName)) goto err; switch (req_type) { case OSSL_CMP_PKIBODY_IR: case OSSL_CMP_PKIBODY_CR: case OSSL_CMP_PKIBODY_P10CR: case OSSL_CMP_PKIBODY_KUR: case OSSL_CMP_PKIBODY_RR: case OSSL_CMP_PKIBODY_GENM: case OSSL_CMP_PKIBODY_ERROR: if (ctx->transactionID != NULL) { char *tid = i2s_ASN1_OCTET_STRING(NULL, ctx->transactionID); if (tid != NULL) ossl_cmp_log1(WARN, ctx, "Assuming that last transaction with ID=%s got aborted", tid); OPENSSL_free(tid); } /* start of a new transaction, reset transactionID and senderNonce */ if (!OSSL_CMP_CTX_set1_transactionID(ctx, NULL) || !OSSL_CMP_CTX_set1_senderNonce(ctx, NULL)) goto err; break; default: /* transactionID should be already initialized */ if (ctx->transactionID == NULL) { #ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); goto err; #endif } } req_verified = ossl_cmp_msg_check_update(ctx, req, unprotected_exception, srv_ctx->acceptUnprotected); if (ctx->secretValue != NULL && ctx->pkey != NULL && ossl_cmp_hdr_get_protection_nid(hdr) != NID_id_PasswordBasedMAC) ctx->secretValue = NULL; /* use MSG_SIG_ALG when protecting rsp */ if (!req_verified) goto err; switch (req_type) { case OSSL_CMP_PKIBODY_IR: case OSSL_CMP_PKIBODY_CR: case OSSL_CMP_PKIBODY_P10CR: case OSSL_CMP_PKIBODY_KUR: if (srv_ctx->process_cert_request == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); else rsp = process_cert_request(srv_ctx, req); break; case OSSL_CMP_PKIBODY_RR: if (srv_ctx->process_rr == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); else rsp = process_rr(srv_ctx, req); break; case OSSL_CMP_PKIBODY_GENM: if (srv_ctx->process_genm == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); else rsp = process_genm(srv_ctx, req); break; case OSSL_CMP_PKIBODY_ERROR: if (srv_ctx->process_error == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); else rsp = process_error(srv_ctx, req); break; case OSSL_CMP_PKIBODY_CERTCONF: if (srv_ctx->process_certConf == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); else rsp = process_certConf(srv_ctx, req); break; case OSSL_CMP_PKIBODY_POLLREQ: if (srv_ctx->process_pollReq == NULL) ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); else rsp = process_pollReq(srv_ctx, req); break; default: /* Other request message types are not supported */ ERR_raise(ERR_LIB_CMP, CMP_R_UNEXPECTED_PKIBODY); break; } err: if (rsp == NULL) { /* on error, try to respond with CMP error message to client */ const char *data = NULL, *reason = NULL; int flags = 0; unsigned long err = ERR_peek_error_data(&data, &flags); int fail_info = 1 << OSSL_CMP_PKIFAILUREINFO_badRequest; /* fail_info is not very specific */ OSSL_CMP_PKISI *si = NULL; if (!req_verified) { /* * Above ossl_cmp_msg_check_update() was not successfully executed, * which normally would set ctx->transactionID and ctx->recipNonce. * So anyway try to provide the right transactionID and recipNonce, * while ignoring any (extra) error in next two function calls. */ if (ctx->transactionID == NULL) (void)OSSL_CMP_CTX_set1_transactionID(ctx, hdr->transactionID); (void)ossl_cmp_ctx_set1_recipNonce(ctx, hdr->senderNonce); } if ((flags & ERR_TXT_STRING) == 0 || *data == '\0') data = NULL; reason = ERR_reason_error_string(err); if ((si = OSSL_CMP_STATUSINFO_new(OSSL_CMP_PKISTATUS_rejection, fail_info, reason)) != NULL) { rsp = ossl_cmp_error_new(srv_ctx->ctx, si, err, data, srv_ctx->sendUnprotectedErrors); OSSL_CMP_PKISI_free(si); } } OSSL_CMP_CTX_print_errors(ctx); ctx->secretValue = backup_secret; rsp_type = rsp != NULL ? OSSL_CMP_MSG_get_bodytype(rsp) : OSSL_CMP_PKIBODY_ERROR; if (rsp != NULL) ossl_cmp_log1(DEBUG, ctx, "sending %s", ossl_cmp_bodytype_to_string(rsp_type)); else ossl_cmp_log(ERR, ctx, "cannot send proper CMP response"); /* determine whether to keep the transaction open or not */ ctx->status = OSSL_CMP_PKISTATUS_trans; switch (rsp_type) { case OSSL_CMP_PKIBODY_IP: case OSSL_CMP_PKIBODY_CP: case OSSL_CMP_PKIBODY_KUP: if (OSSL_CMP_CTX_get_option(ctx, OSSL_CMP_OPT_IMPLICIT_CONFIRM) == 0) break; /* fall through */ case OSSL_CMP_PKIBODY_RP: case OSSL_CMP_PKIBODY_PKICONF: case OSSL_CMP_PKIBODY_GENP: case OSSL_CMP_PKIBODY_ERROR: /* Other terminating response message types are not supported */ /* Prepare for next transaction, ignoring any errors here: */ (void)OSSL_CMP_CTX_set1_transactionID(ctx, NULL); (void)OSSL_CMP_CTX_set1_senderNonce(ctx, NULL); ctx->status = OSSL_CMP_PKISTATUS_unspecified; /* transaction closed */ default: /* not closing transaction in other cases */ break; } return rsp; } /* * Server interface that may substitute OSSL_CMP_MSG_http_perform at the client. * The OSSL_CMP_SRV_CTX must be set as client_ctx->transfer_cb_arg. * returns received message on success, else NULL and pushes an element on the * error stack. */ OSSL_CMP_MSG *OSSL_CMP_CTX_server_perform(OSSL_CMP_CTX *client_ctx, const OSSL_CMP_MSG *req) { OSSL_CMP_SRV_CTX *srv_ctx = NULL; if (client_ctx == NULL || req == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } if ((srv_ctx = OSSL_CMP_CTX_get_transfer_cb_arg(client_ctx)) == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_TRANSFER_ERROR); return NULL; } return OSSL_CMP_SRV_process_request(srv_ctx, req); }
23,113
33.550075
86
c
openssl
openssl-master/crypto/cmp/cmp_status.c
/* * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* CMP functions for PKIStatusInfo handling and PKIMessage decomposition */ #include <string.h> #include "cmp_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include <time.h> #include <openssl/cmp.h> #include <openssl/crmf.h> #include <openssl/err.h> /* needed in case config no-deprecated */ #include <openssl/engine.h> #include <openssl/evp.h> #include <openssl/objects.h> #include <openssl/x509.h> #include <openssl/asn1err.h> /* for ASN1_R_TOO_SMALL and ASN1_R_TOO_LARGE */ /* CMP functions related to PKIStatus */ int ossl_cmp_pkisi_get_status(const OSSL_CMP_PKISI *si) { if (!ossl_assert(si != NULL && si->status != NULL)) return -1; return ossl_cmp_asn1_get_int(si->status); } const char *ossl_cmp_PKIStatus_to_string(int status) { switch (status) { case OSSL_CMP_PKISTATUS_accepted: return "PKIStatus: accepted"; case OSSL_CMP_PKISTATUS_grantedWithMods: return "PKIStatus: granted with modifications"; case OSSL_CMP_PKISTATUS_rejection: return "PKIStatus: rejection"; case OSSL_CMP_PKISTATUS_waiting: return "PKIStatus: waiting"; case OSSL_CMP_PKISTATUS_revocationWarning: return "PKIStatus: revocation warning - a revocation of the cert is imminent"; case OSSL_CMP_PKISTATUS_revocationNotification: return "PKIStatus: revocation notification - a revocation of the cert has occurred"; case OSSL_CMP_PKISTATUS_keyUpdateWarning: return "PKIStatus: key update warning - update already done for the cert"; default: ERR_raise_data(ERR_LIB_CMP, CMP_R_ERROR_PARSING_PKISTATUS, "PKIStatus: invalid=%d", status); return NULL; } } OSSL_CMP_PKIFREETEXT *ossl_cmp_pkisi_get0_statusString(const OSSL_CMP_PKISI *si) { if (!ossl_assert(si != NULL)) return NULL; return si->statusString; } int ossl_cmp_pkisi_get_pkifailureinfo(const OSSL_CMP_PKISI *si) { int i; int res = 0; if (!ossl_assert(si != NULL)) return -1; if (si->failInfo != NULL) for (i = 0; i <= OSSL_CMP_PKIFAILUREINFO_MAX; i++) if (ASN1_BIT_STRING_get_bit(si->failInfo, i)) res |= 1 << i; return res; } /*- * convert PKIFailureInfo number to human-readable string * returns pointer to static string, or NULL on error */ static const char *CMP_PKIFAILUREINFO_to_string(int number) { switch (number) { case OSSL_CMP_PKIFAILUREINFO_badAlg: return "badAlg"; case OSSL_CMP_PKIFAILUREINFO_badMessageCheck: return "badMessageCheck"; case OSSL_CMP_PKIFAILUREINFO_badRequest: return "badRequest"; case OSSL_CMP_PKIFAILUREINFO_badTime: return "badTime"; case OSSL_CMP_PKIFAILUREINFO_badCertId: return "badCertId"; case OSSL_CMP_PKIFAILUREINFO_badDataFormat: return "badDataFormat"; case OSSL_CMP_PKIFAILUREINFO_wrongAuthority: return "wrongAuthority"; case OSSL_CMP_PKIFAILUREINFO_incorrectData: return "incorrectData"; case OSSL_CMP_PKIFAILUREINFO_missingTimeStamp: return "missingTimeStamp"; case OSSL_CMP_PKIFAILUREINFO_badPOP: return "badPOP"; case OSSL_CMP_PKIFAILUREINFO_certRevoked: return "certRevoked"; case OSSL_CMP_PKIFAILUREINFO_certConfirmed: return "certConfirmed"; case OSSL_CMP_PKIFAILUREINFO_wrongIntegrity: return "wrongIntegrity"; case OSSL_CMP_PKIFAILUREINFO_badRecipientNonce: return "badRecipientNonce"; case OSSL_CMP_PKIFAILUREINFO_timeNotAvailable: return "timeNotAvailable"; case OSSL_CMP_PKIFAILUREINFO_unacceptedPolicy: return "unacceptedPolicy"; case OSSL_CMP_PKIFAILUREINFO_unacceptedExtension: return "unacceptedExtension"; case OSSL_CMP_PKIFAILUREINFO_addInfoNotAvailable: return "addInfoNotAvailable"; case OSSL_CMP_PKIFAILUREINFO_badSenderNonce: return "badSenderNonce"; case OSSL_CMP_PKIFAILUREINFO_badCertTemplate: return "badCertTemplate"; case OSSL_CMP_PKIFAILUREINFO_signerNotTrusted: return "signerNotTrusted"; case OSSL_CMP_PKIFAILUREINFO_transactionIdInUse: return "transactionIdInUse"; case OSSL_CMP_PKIFAILUREINFO_unsupportedVersion: return "unsupportedVersion"; case OSSL_CMP_PKIFAILUREINFO_notAuthorized: return "notAuthorized"; case OSSL_CMP_PKIFAILUREINFO_systemUnavail: return "systemUnavail"; case OSSL_CMP_PKIFAILUREINFO_systemFailure: return "systemFailure"; case OSSL_CMP_PKIFAILUREINFO_duplicateCertReq: return "duplicateCertReq"; default: return NULL; /* illegal failure number */ } } int ossl_cmp_pkisi_check_pkifailureinfo(const OSSL_CMP_PKISI *si, int bit_index) { if (!ossl_assert(si != NULL && si->failInfo != NULL)) return -1; if (bit_index < 0 || bit_index > OSSL_CMP_PKIFAILUREINFO_MAX) { ERR_raise(ERR_LIB_CMP, CMP_R_INVALID_ARGS); return -1; } return ASN1_BIT_STRING_get_bit(si->failInfo, bit_index); } /*- * place human-readable error string created from PKIStatusInfo in given buffer * returns pointer to the same buffer containing the string, or NULL on error */ static char *snprint_PKIStatusInfo_parts(int status, int fail_info, const OSSL_CMP_PKIFREETEXT *status_strings, char *buf, size_t bufsize) { int failure; const char *status_string, *failure_string; ASN1_UTF8STRING *text; int i; int printed_chars; int failinfo_found = 0; int n_status_strings; char *write_ptr = buf; if (buf == NULL || status < 0 || (status_string = ossl_cmp_PKIStatus_to_string(status)) == NULL) return NULL; #define ADVANCE_BUFFER \ if (printed_chars < 0 || (size_t)printed_chars >= bufsize) \ return NULL; \ write_ptr += printed_chars; \ bufsize -= printed_chars; printed_chars = BIO_snprintf(write_ptr, bufsize, "%s", status_string); ADVANCE_BUFFER; /* * failInfo is optional and may be empty; * if present, print failInfo before statusString because it is more concise */ if (fail_info != -1 && fail_info != 0) { printed_chars = BIO_snprintf(write_ptr, bufsize, "; PKIFailureInfo: "); ADVANCE_BUFFER; for (failure = 0; failure <= OSSL_CMP_PKIFAILUREINFO_MAX; failure++) { if ((fail_info & (1 << failure)) != 0) { failure_string = CMP_PKIFAILUREINFO_to_string(failure); if (failure_string != NULL) { printed_chars = BIO_snprintf(write_ptr, bufsize, "%s%s", failinfo_found ? ", " : "", failure_string); ADVANCE_BUFFER; failinfo_found = 1; } } } } if (!failinfo_found && status != OSSL_CMP_PKISTATUS_accepted && status != OSSL_CMP_PKISTATUS_grantedWithMods) { printed_chars = BIO_snprintf(write_ptr, bufsize, "; <no failure info>"); ADVANCE_BUFFER; } /* statusString sequence is optional and may be empty */ n_status_strings = sk_ASN1_UTF8STRING_num(status_strings); if (n_status_strings > 0) { printed_chars = BIO_snprintf(write_ptr, bufsize, "; StatusString%s: ", n_status_strings > 1 ? "s" : ""); ADVANCE_BUFFER; for (i = 0; i < n_status_strings; i++) { text = sk_ASN1_UTF8STRING_value(status_strings, i); printed_chars = BIO_snprintf(write_ptr, bufsize, "\"%.*s\"%s", ASN1_STRING_length(text), ASN1_STRING_get0_data(text), i < n_status_strings - 1 ? ", " : ""); ADVANCE_BUFFER; } } #undef ADVANCE_BUFFER return buf; } char *OSSL_CMP_snprint_PKIStatusInfo(const OSSL_CMP_PKISI *statusInfo, char *buf, size_t bufsize) { int failure_info; if (statusInfo == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } failure_info = ossl_cmp_pkisi_get_pkifailureinfo(statusInfo); return snprint_PKIStatusInfo_parts(ASN1_INTEGER_get(statusInfo->status), failure_info, statusInfo->statusString, buf, bufsize); } char *OSSL_CMP_CTX_snprint_PKIStatus(const OSSL_CMP_CTX *ctx, char *buf, size_t bufsize) { if (ctx == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return NULL; } return snprint_PKIStatusInfo_parts(OSSL_CMP_CTX_get_status(ctx), OSSL_CMP_CTX_get_failInfoCode(ctx), OSSL_CMP_CTX_get0_statusString(ctx), buf, bufsize); } /*- * Creates a new PKIStatusInfo structure and fills it in * returns a pointer to the structure on success, NULL on error * note: strongly overlaps with TS_RESP_CTX_set_status_info() * and TS_RESP_CTX_add_failure_info() in ../ts/ts_rsp_sign.c */ OSSL_CMP_PKISI *OSSL_CMP_STATUSINFO_new(int status, int fail_info, const char *text) { OSSL_CMP_PKISI *si = OSSL_CMP_PKISI_new(); ASN1_UTF8STRING *utf8_text = NULL; int failure; if (si == NULL) goto err; if (!ASN1_INTEGER_set(si->status, status)) goto err; if (text != NULL) { if ((utf8_text = ASN1_UTF8STRING_new()) == NULL || !ASN1_STRING_set(utf8_text, text, -1)) goto err; if ((si->statusString = sk_ASN1_UTF8STRING_new_null()) == NULL) goto err; if (!sk_ASN1_UTF8STRING_push(si->statusString, utf8_text)) goto err; /* Ownership is lost. */ utf8_text = NULL; } for (failure = 0; failure <= OSSL_CMP_PKIFAILUREINFO_MAX; failure++) { if ((fail_info & (1 << failure)) != 0) { if (si->failInfo == NULL && (si->failInfo = ASN1_BIT_STRING_new()) == NULL) goto err; if (!ASN1_BIT_STRING_set_bit(si->failInfo, failure, 1)) goto err; } } return si; err: OSSL_CMP_PKISI_free(si); ASN1_UTF8STRING_free(utf8_text); return NULL; }
10,963
33.806349
92
c
openssl
openssl-master/crypto/cmp/cmp_util.c
/* * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with 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/cmp_util.h> #include "cmp_local.h" /* just for decls of internal functions defined here */ #include <openssl/cmperr.h> #include <openssl/err.h> /* should be implied by cmperr.h */ #include <openssl/x509v3.h> /* * use trace API for CMP-specific logging, prefixed by "CMP " and severity */ int OSSL_CMP_log_open(void) /* is designed to be idempotent */ { #ifdef OPENSSL_NO_TRACE return 1; #else # ifndef OPENSSL_NO_STDIO BIO *bio = BIO_new_fp(stdout, BIO_NOCLOSE); if (bio != NULL && OSSL_trace_set_channel(OSSL_TRACE_CATEGORY_CMP, bio)) return 1; BIO_free(bio); # endif ERR_raise(ERR_LIB_CMP, CMP_R_NO_STDIO); return 0; #endif } void OSSL_CMP_log_close(void) /* is designed to be idempotent */ { (void)OSSL_trace_set_channel(OSSL_TRACE_CATEGORY_CMP, NULL); } /* return >= 0 if level contains logging level, possibly preceded by "CMP " */ #define max_level_len 5 /* = max length of the below strings, e.g., "EMERG" */ static OSSL_CMP_severity parse_level(const char *level) { const char *end_level = strchr(level, ':'); int len; char level_copy[max_level_len + 1]; if (end_level == NULL) return -1; if (HAS_PREFIX(level, OSSL_CMP_LOG_PREFIX)) level += strlen(OSSL_CMP_LOG_PREFIX); len = end_level - level; if (len > max_level_len) return -1; OPENSSL_strlcpy(level_copy, level, len + 1); return strcmp(level_copy, "EMERG") == 0 ? OSSL_CMP_LOG_EMERG : strcmp(level_copy, "ALERT") == 0 ? OSSL_CMP_LOG_ALERT : strcmp(level_copy, "CRIT") == 0 ? OSSL_CMP_LOG_CRIT : strcmp(level_copy, "ERROR") == 0 ? OSSL_CMP_LOG_ERR : strcmp(level_copy, "WARN") == 0 ? OSSL_CMP_LOG_WARNING : strcmp(level_copy, "NOTE") == 0 ? OSSL_CMP_LOG_NOTICE : strcmp(level_copy, "INFO") == 0 ? OSSL_CMP_LOG_INFO : strcmp(level_copy, "DEBUG") == 0 ? OSSL_CMP_LOG_DEBUG : -1; } const char *ossl_cmp_log_parse_metadata(const char *buf, OSSL_CMP_severity *level, char **func, char **file, int *line) { const char *p_func = buf; const char *p_file = buf == NULL ? NULL : strchr(buf, ':'); const char *p_level = buf; const char *msg = buf; *level = -1; *func = NULL; *file = NULL; *line = 0; if (p_file != NULL) { const char *p_line = strchr(++p_file, ':'); if ((*level = parse_level(buf)) < 0 && p_line != NULL) { /* check if buf contains location info and logging level */ char *p_level_tmp = (char *)p_level; const long line_number = strtol(++p_line, &p_level_tmp, 10); p_level = p_level_tmp; if (p_level > p_line && *(p_level++) == ':') { if ((*level = parse_level(p_level)) >= 0) { *func = OPENSSL_strndup(p_func, p_file - 1 - p_func); *file = OPENSSL_strndup(p_file, p_line - 1 - p_file); /* no real problem if OPENSSL_strndup() returns NULL */ *line = (int)line_number; msg = strchr(p_level, ':'); if (msg != NULL && *++msg == ' ') msg++; } } } } return msg; } #define UNKNOWN_FUNC "(unknown function)" /* the default for OPENSSL_FUNC */ /* * substitute fallback if component/function name is NULL or empty or contains * just pseudo-information "(unknown function)" due to -pedantic and macros.h */ static const char *improve_location_name(const char *func, const char *fallback) { if (fallback == NULL) return func == NULL ? UNKNOWN_FUNC : func; return func == NULL || *func == '\0' || strcmp(func, UNKNOWN_FUNC) == 0 ? fallback : func; } int OSSL_CMP_print_to_bio(BIO *bio, const char *component, const char *file, int line, OSSL_CMP_severity level, const char *msg) { const char *level_string = level == OSSL_CMP_LOG_EMERG ? "EMERG" : level == OSSL_CMP_LOG_ALERT ? "ALERT" : level == OSSL_CMP_LOG_CRIT ? "CRIT" : level == OSSL_CMP_LOG_ERR ? "error" : level == OSSL_CMP_LOG_WARNING ? "warning" : level == OSSL_CMP_LOG_NOTICE ? "NOTE" : level == OSSL_CMP_LOG_INFO ? "info" : level == OSSL_CMP_LOG_DEBUG ? "DEBUG" : "(unknown level)"; #ifndef NDEBUG if (BIO_printf(bio, "%s:%s:%d:", improve_location_name(component, "CMP"), file, line) < 0) return 0; #endif return BIO_printf(bio, OSSL_CMP_LOG_PREFIX"%s: %s\n", level_string, msg) >= 0; } #define ERR_PRINT_BUF_SIZE 4096 /* this is similar to ERR_print_errors_cb, but uses the CMP-specific cb type */ void OSSL_CMP_print_errors_cb(OSSL_CMP_log_cb_t log_fn) { unsigned long err; char msg[ERR_PRINT_BUF_SIZE]; const char *file = NULL, *func = NULL, *data = NULL; int line, flags; while ((err = ERR_get_error_all(&file, &line, &func, &data, &flags)) != 0) { const char *component = improve_location_name(func, ERR_lib_error_string(err)); unsigned long reason = ERR_GET_REASON(err); const char *rs = NULL; char rsbuf[256]; #ifndef OPENSSL_NO_ERR if (ERR_SYSTEM_ERROR(err)) { if (openssl_strerror_r(reason, rsbuf, sizeof(rsbuf))) rs = rsbuf; } else { rs = ERR_reason_error_string(err); } #endif if (rs == NULL) { BIO_snprintf(rsbuf, sizeof(rsbuf), "reason(%lu)", reason); rs = rsbuf; } if (data != NULL && (flags & ERR_TXT_STRING) != 0) BIO_snprintf(msg, sizeof(msg), "%s:%s", rs, data); else BIO_snprintf(msg, sizeof(msg), "%s", rs); if (log_fn == NULL) { #ifndef OPENSSL_NO_STDIO BIO *bio = BIO_new_fp(stderr, BIO_NOCLOSE); if (bio != NULL) { OSSL_CMP_print_to_bio(bio, component, file, line, OSSL_CMP_LOG_ERR, msg); BIO_free(bio); } #else /* ERR_raise(..., CMP_R_NO_STDIO) would make no sense here */ #endif } else { if (log_fn(component, file, line, OSSL_CMP_LOG_ERR, msg) <= 0) break; /* abort outputting the error report */ } } } int ossl_cmp_X509_STORE_add1_certs(X509_STORE *store, STACK_OF(X509) *certs, int only_self_signed) { int i; if (store == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (certs == NULL) return 1; for (i = 0; i < sk_X509_num(certs); i++) { X509 *cert = sk_X509_value(certs, i); if (!only_self_signed || X509_self_signed(cert, 0) == 1) if (!X509_STORE_add_cert(store, cert)) /* ups cert ref counter */ return 0; } return 1; } int ossl_cmp_sk_ASN1_UTF8STRING_push_str(STACK_OF(ASN1_UTF8STRING) *sk, const char *text, int len) { ASN1_UTF8STRING *utf8string; if (!ossl_assert(sk != NULL && text != NULL)) return 0; if ((utf8string = ASN1_UTF8STRING_new()) == NULL) return 0; if (!ASN1_STRING_set(utf8string, text, len)) goto err; if (!sk_ASN1_UTF8STRING_push(sk, utf8string)) goto err; return 1; err: ASN1_UTF8STRING_free(utf8string); return 0; } int ossl_cmp_asn1_octet_string_set1(ASN1_OCTET_STRING **tgt, const ASN1_OCTET_STRING *src) { ASN1_OCTET_STRING *new; if (tgt == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (*tgt == src) /* self-assignment */ return 1; if (src != NULL) { if ((new = ASN1_OCTET_STRING_dup(src)) == NULL) return 0; } else { new = NULL; } ASN1_OCTET_STRING_free(*tgt); *tgt = new; return 1; } int ossl_cmp_asn1_octet_string_set1_bytes(ASN1_OCTET_STRING **tgt, const unsigned char *bytes, int len) { ASN1_OCTET_STRING *new = NULL; if (tgt == NULL) { ERR_raise(ERR_LIB_CMP, CMP_R_NULL_ARGUMENT); return 0; } if (bytes != NULL) { if ((new = ASN1_OCTET_STRING_new()) == NULL || !(ASN1_OCTET_STRING_set(new, bytes, len))) { ASN1_OCTET_STRING_free(new); return 0; } } ASN1_OCTET_STRING_free(*tgt); *tgt = new; return 1; }
9,036
30.487805
80
c
openssl
openssl-master/crypto/cms/cms_asn1.c
/* * Copyright 2008-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/asn1t.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/cms.h> #include "cms_local.h" ASN1_SEQUENCE(CMS_IssuerAndSerialNumber) = { ASN1_SIMPLE(CMS_IssuerAndSerialNumber, issuer, X509_NAME), ASN1_SIMPLE(CMS_IssuerAndSerialNumber, serialNumber, ASN1_INTEGER) } ASN1_SEQUENCE_END(CMS_IssuerAndSerialNumber) ASN1_SEQUENCE(CMS_OtherCertificateFormat) = { ASN1_SIMPLE(CMS_OtherCertificateFormat, otherCertFormat, ASN1_OBJECT), ASN1_OPT(CMS_OtherCertificateFormat, otherCert, ASN1_ANY) } static_ASN1_SEQUENCE_END(CMS_OtherCertificateFormat) ASN1_CHOICE(CMS_CertificateChoices) = { ASN1_SIMPLE(CMS_CertificateChoices, d.certificate, X509), ASN1_IMP(CMS_CertificateChoices, d.extendedCertificate, ASN1_SEQUENCE, 0), ASN1_IMP(CMS_CertificateChoices, d.v1AttrCert, ASN1_SEQUENCE, 1), ASN1_IMP(CMS_CertificateChoices, d.v2AttrCert, ASN1_SEQUENCE, 2), ASN1_IMP(CMS_CertificateChoices, d.other, CMS_OtherCertificateFormat, 3) } ASN1_CHOICE_END(CMS_CertificateChoices) ASN1_CHOICE(CMS_SignerIdentifier) = { ASN1_SIMPLE(CMS_SignerIdentifier, d.issuerAndSerialNumber, CMS_IssuerAndSerialNumber), ASN1_IMP(CMS_SignerIdentifier, d.subjectKeyIdentifier, ASN1_OCTET_STRING, 0) } static_ASN1_CHOICE_END(CMS_SignerIdentifier) ASN1_NDEF_SEQUENCE(CMS_EncapsulatedContentInfo) = { ASN1_SIMPLE(CMS_EncapsulatedContentInfo, eContentType, ASN1_OBJECT), ASN1_NDEF_EXP_OPT(CMS_EncapsulatedContentInfo, eContent, ASN1_OCTET_STRING_NDEF, 0) } static_ASN1_NDEF_SEQUENCE_END(CMS_EncapsulatedContentInfo) /* Minor tweak to operation: free up signer key, cert */ static int cms_si_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_FREE_POST) { CMS_SignerInfo *si = (CMS_SignerInfo *)*pval; EVP_PKEY_free(si->pkey); X509_free(si->signer); EVP_MD_CTX_free(si->mctx); } return 1; } ASN1_SEQUENCE_cb(CMS_SignerInfo, cms_si_cb) = { ASN1_EMBED(CMS_SignerInfo, version, INT32), ASN1_SIMPLE(CMS_SignerInfo, sid, CMS_SignerIdentifier), ASN1_SIMPLE(CMS_SignerInfo, digestAlgorithm, X509_ALGOR), ASN1_IMP_SET_OF_OPT(CMS_SignerInfo, signedAttrs, X509_ATTRIBUTE, 0), ASN1_SIMPLE(CMS_SignerInfo, signatureAlgorithm, X509_ALGOR), ASN1_SIMPLE(CMS_SignerInfo, signature, ASN1_OCTET_STRING), ASN1_IMP_SET_OF_OPT(CMS_SignerInfo, unsignedAttrs, X509_ATTRIBUTE, 1) } ASN1_SEQUENCE_END_cb(CMS_SignerInfo, CMS_SignerInfo) ASN1_SEQUENCE(CMS_OtherRevocationInfoFormat) = { ASN1_SIMPLE(CMS_OtherRevocationInfoFormat, otherRevInfoFormat, ASN1_OBJECT), ASN1_OPT(CMS_OtherRevocationInfoFormat, otherRevInfo, ASN1_ANY) } static_ASN1_SEQUENCE_END(CMS_OtherRevocationInfoFormat) ASN1_CHOICE(CMS_RevocationInfoChoice) = { ASN1_SIMPLE(CMS_RevocationInfoChoice, d.crl, X509_CRL), ASN1_IMP(CMS_RevocationInfoChoice, d.other, CMS_OtherRevocationInfoFormat, 1) } ASN1_CHOICE_END(CMS_RevocationInfoChoice) ASN1_NDEF_SEQUENCE(CMS_SignedData) = { ASN1_EMBED(CMS_SignedData, version, INT32), ASN1_SET_OF(CMS_SignedData, digestAlgorithms, X509_ALGOR), ASN1_SIMPLE(CMS_SignedData, encapContentInfo, CMS_EncapsulatedContentInfo), ASN1_IMP_SET_OF_OPT(CMS_SignedData, certificates, CMS_CertificateChoices, 0), ASN1_IMP_SET_OF_OPT(CMS_SignedData, crls, CMS_RevocationInfoChoice, 1), ASN1_SET_OF(CMS_SignedData, signerInfos, CMS_SignerInfo) } ASN1_NDEF_SEQUENCE_END(CMS_SignedData) IMPLEMENT_ASN1_ALLOC_FUNCTIONS(CMS_SignedData) ASN1_SEQUENCE(CMS_OriginatorInfo) = { ASN1_IMP_SET_OF_OPT(CMS_OriginatorInfo, certificates, CMS_CertificateChoices, 0), ASN1_IMP_SET_OF_OPT(CMS_OriginatorInfo, crls, CMS_RevocationInfoChoice, 1) } static_ASN1_SEQUENCE_END(CMS_OriginatorInfo) ASN1_NDEF_SEQUENCE(CMS_EncryptedContentInfo) = { ASN1_SIMPLE(CMS_EncryptedContentInfo, contentType, ASN1_OBJECT), ASN1_SIMPLE(CMS_EncryptedContentInfo, contentEncryptionAlgorithm, X509_ALGOR), ASN1_IMP_OPT(CMS_EncryptedContentInfo, encryptedContent, ASN1_OCTET_STRING_NDEF, 0) } static_ASN1_NDEF_SEQUENCE_END(CMS_EncryptedContentInfo) ASN1_SEQUENCE(CMS_KeyTransRecipientInfo) = { ASN1_EMBED(CMS_KeyTransRecipientInfo, version, INT32), ASN1_SIMPLE(CMS_KeyTransRecipientInfo, rid, CMS_SignerIdentifier), ASN1_SIMPLE(CMS_KeyTransRecipientInfo, keyEncryptionAlgorithm, X509_ALGOR), ASN1_SIMPLE(CMS_KeyTransRecipientInfo, encryptedKey, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(CMS_KeyTransRecipientInfo) ASN1_SEQUENCE(CMS_OtherKeyAttribute) = { ASN1_SIMPLE(CMS_OtherKeyAttribute, keyAttrId, ASN1_OBJECT), ASN1_OPT(CMS_OtherKeyAttribute, keyAttr, ASN1_ANY) } ASN1_SEQUENCE_END(CMS_OtherKeyAttribute) ASN1_SEQUENCE(CMS_RecipientKeyIdentifier) = { ASN1_SIMPLE(CMS_RecipientKeyIdentifier, subjectKeyIdentifier, ASN1_OCTET_STRING), ASN1_OPT(CMS_RecipientKeyIdentifier, date, ASN1_GENERALIZEDTIME), ASN1_OPT(CMS_RecipientKeyIdentifier, other, CMS_OtherKeyAttribute) } ASN1_SEQUENCE_END(CMS_RecipientKeyIdentifier) ASN1_CHOICE(CMS_KeyAgreeRecipientIdentifier) = { ASN1_SIMPLE(CMS_KeyAgreeRecipientIdentifier, d.issuerAndSerialNumber, CMS_IssuerAndSerialNumber), ASN1_IMP(CMS_KeyAgreeRecipientIdentifier, d.rKeyId, CMS_RecipientKeyIdentifier, 0) } static_ASN1_CHOICE_END(CMS_KeyAgreeRecipientIdentifier) static int cms_rek_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { CMS_RecipientEncryptedKey *rek = (CMS_RecipientEncryptedKey *)*pval; if (operation == ASN1_OP_FREE_POST) { EVP_PKEY_free(rek->pkey); } return 1; } ASN1_SEQUENCE_cb(CMS_RecipientEncryptedKey, cms_rek_cb) = { ASN1_SIMPLE(CMS_RecipientEncryptedKey, rid, CMS_KeyAgreeRecipientIdentifier), ASN1_SIMPLE(CMS_RecipientEncryptedKey, encryptedKey, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END_cb(CMS_RecipientEncryptedKey, CMS_RecipientEncryptedKey) ASN1_SEQUENCE(CMS_OriginatorPublicKey) = { ASN1_SIMPLE(CMS_OriginatorPublicKey, algorithm, X509_ALGOR), ASN1_SIMPLE(CMS_OriginatorPublicKey, publicKey, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(CMS_OriginatorPublicKey) ASN1_CHOICE(CMS_OriginatorIdentifierOrKey) = { ASN1_SIMPLE(CMS_OriginatorIdentifierOrKey, d.issuerAndSerialNumber, CMS_IssuerAndSerialNumber), ASN1_IMP(CMS_OriginatorIdentifierOrKey, d.subjectKeyIdentifier, ASN1_OCTET_STRING, 0), ASN1_IMP(CMS_OriginatorIdentifierOrKey, d.originatorKey, CMS_OriginatorPublicKey, 1) } static_ASN1_CHOICE_END(CMS_OriginatorIdentifierOrKey) static int cms_kari_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { CMS_KeyAgreeRecipientInfo *kari = (CMS_KeyAgreeRecipientInfo *)*pval; if (operation == ASN1_OP_NEW_POST) { kari->ctx = EVP_CIPHER_CTX_new(); if (kari->ctx == NULL) return 0; EVP_CIPHER_CTX_set_flags(kari->ctx, EVP_CIPHER_CTX_FLAG_WRAP_ALLOW); kari->pctx = NULL; } else if (operation == ASN1_OP_FREE_POST) { EVP_PKEY_CTX_free(kari->pctx); EVP_CIPHER_CTX_free(kari->ctx); } return 1; } ASN1_SEQUENCE_cb(CMS_KeyAgreeRecipientInfo, cms_kari_cb) = { ASN1_EMBED(CMS_KeyAgreeRecipientInfo, version, INT32), ASN1_EXP(CMS_KeyAgreeRecipientInfo, originator, CMS_OriginatorIdentifierOrKey, 0), ASN1_EXP_OPT(CMS_KeyAgreeRecipientInfo, ukm, ASN1_OCTET_STRING, 1), ASN1_SIMPLE(CMS_KeyAgreeRecipientInfo, keyEncryptionAlgorithm, X509_ALGOR), ASN1_SEQUENCE_OF(CMS_KeyAgreeRecipientInfo, recipientEncryptedKeys, CMS_RecipientEncryptedKey) } ASN1_SEQUENCE_END_cb(CMS_KeyAgreeRecipientInfo, CMS_KeyAgreeRecipientInfo) ASN1_SEQUENCE(CMS_KEKIdentifier) = { ASN1_SIMPLE(CMS_KEKIdentifier, keyIdentifier, ASN1_OCTET_STRING), ASN1_OPT(CMS_KEKIdentifier, date, ASN1_GENERALIZEDTIME), ASN1_OPT(CMS_KEKIdentifier, other, CMS_OtherKeyAttribute) } static_ASN1_SEQUENCE_END(CMS_KEKIdentifier) ASN1_SEQUENCE(CMS_KEKRecipientInfo) = { ASN1_EMBED(CMS_KEKRecipientInfo, version, INT32), ASN1_SIMPLE(CMS_KEKRecipientInfo, kekid, CMS_KEKIdentifier), ASN1_SIMPLE(CMS_KEKRecipientInfo, keyEncryptionAlgorithm, X509_ALGOR), ASN1_SIMPLE(CMS_KEKRecipientInfo, encryptedKey, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(CMS_KEKRecipientInfo) ASN1_SEQUENCE(CMS_PasswordRecipientInfo) = { ASN1_EMBED(CMS_PasswordRecipientInfo, version, INT32), ASN1_IMP_OPT(CMS_PasswordRecipientInfo, keyDerivationAlgorithm, X509_ALGOR, 0), ASN1_SIMPLE(CMS_PasswordRecipientInfo, keyEncryptionAlgorithm, X509_ALGOR), ASN1_SIMPLE(CMS_PasswordRecipientInfo, encryptedKey, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(CMS_PasswordRecipientInfo) ASN1_SEQUENCE(CMS_OtherRecipientInfo) = { ASN1_SIMPLE(CMS_OtherRecipientInfo, oriType, ASN1_OBJECT), ASN1_OPT(CMS_OtherRecipientInfo, oriValue, ASN1_ANY) } static_ASN1_SEQUENCE_END(CMS_OtherRecipientInfo) /* Free up RecipientInfo additional data */ static int cms_ri_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { if (operation == ASN1_OP_FREE_PRE) { CMS_RecipientInfo *ri = (CMS_RecipientInfo *)*pval; if (ri->type == CMS_RECIPINFO_TRANS) { CMS_KeyTransRecipientInfo *ktri = ri->d.ktri; EVP_PKEY_free(ktri->pkey); X509_free(ktri->recip); EVP_PKEY_CTX_free(ktri->pctx); } else if (ri->type == CMS_RECIPINFO_KEK) { CMS_KEKRecipientInfo *kekri = ri->d.kekri; OPENSSL_clear_free(kekri->key, kekri->keylen); } else if (ri->type == CMS_RECIPINFO_PASS) { CMS_PasswordRecipientInfo *pwri = ri->d.pwri; OPENSSL_clear_free(pwri->pass, pwri->passlen); } } return 1; } ASN1_CHOICE_cb(CMS_RecipientInfo, cms_ri_cb) = { ASN1_SIMPLE(CMS_RecipientInfo, d.ktri, CMS_KeyTransRecipientInfo), ASN1_IMP(CMS_RecipientInfo, d.kari, CMS_KeyAgreeRecipientInfo, 1), ASN1_IMP(CMS_RecipientInfo, d.kekri, CMS_KEKRecipientInfo, 2), ASN1_IMP(CMS_RecipientInfo, d.pwri, CMS_PasswordRecipientInfo, 3), ASN1_IMP(CMS_RecipientInfo, d.ori, CMS_OtherRecipientInfo, 4) } ASN1_CHOICE_END_cb(CMS_RecipientInfo, CMS_RecipientInfo, type) ASN1_NDEF_SEQUENCE(CMS_EnvelopedData) = { ASN1_EMBED(CMS_EnvelopedData, version, INT32), ASN1_IMP_OPT(CMS_EnvelopedData, originatorInfo, CMS_OriginatorInfo, 0), ASN1_SET_OF(CMS_EnvelopedData, recipientInfos, CMS_RecipientInfo), ASN1_SIMPLE(CMS_EnvelopedData, encryptedContentInfo, CMS_EncryptedContentInfo), ASN1_IMP_SET_OF_OPT(CMS_EnvelopedData, unprotectedAttrs, X509_ATTRIBUTE, 1) } ASN1_NDEF_SEQUENCE_END(CMS_EnvelopedData) ASN1_NDEF_SEQUENCE(CMS_DigestedData) = { ASN1_EMBED(CMS_DigestedData, version, INT32), ASN1_SIMPLE(CMS_DigestedData, digestAlgorithm, X509_ALGOR), ASN1_SIMPLE(CMS_DigestedData, encapContentInfo, CMS_EncapsulatedContentInfo), ASN1_SIMPLE(CMS_DigestedData, digest, ASN1_OCTET_STRING) } ASN1_NDEF_SEQUENCE_END(CMS_DigestedData) ASN1_NDEF_SEQUENCE(CMS_EncryptedData) = { ASN1_EMBED(CMS_EncryptedData, version, INT32), ASN1_SIMPLE(CMS_EncryptedData, encryptedContentInfo, CMS_EncryptedContentInfo), ASN1_IMP_SET_OF_OPT(CMS_EncryptedData, unprotectedAttrs, X509_ATTRIBUTE, 1) } ASN1_NDEF_SEQUENCE_END(CMS_EncryptedData) /* Defined in RFC 5083 - Section 2.1. AuthEnvelopedData Type */ ASN1_NDEF_SEQUENCE(CMS_AuthEnvelopedData) = { ASN1_EMBED(CMS_AuthEnvelopedData, version, INT32), ASN1_IMP_OPT(CMS_AuthEnvelopedData, originatorInfo, CMS_OriginatorInfo, 0), ASN1_SET_OF(CMS_AuthEnvelopedData, recipientInfos, CMS_RecipientInfo), ASN1_SIMPLE(CMS_AuthEnvelopedData, authEncryptedContentInfo, CMS_EncryptedContentInfo), ASN1_IMP_SET_OF_OPT(CMS_AuthEnvelopedData, authAttrs, X509_ALGOR, 2), ASN1_SIMPLE(CMS_AuthEnvelopedData, mac, ASN1_OCTET_STRING), ASN1_IMP_SET_OF_OPT(CMS_AuthEnvelopedData, unauthAttrs, X509_ALGOR, 3) } ASN1_NDEF_SEQUENCE_END(CMS_AuthEnvelopedData) ASN1_NDEF_SEQUENCE(CMS_AuthenticatedData) = { ASN1_EMBED(CMS_AuthenticatedData, version, INT32), ASN1_IMP_OPT(CMS_AuthenticatedData, originatorInfo, CMS_OriginatorInfo, 0), ASN1_SET_OF(CMS_AuthenticatedData, recipientInfos, CMS_RecipientInfo), ASN1_SIMPLE(CMS_AuthenticatedData, macAlgorithm, X509_ALGOR), ASN1_IMP(CMS_AuthenticatedData, digestAlgorithm, X509_ALGOR, 1), ASN1_SIMPLE(CMS_AuthenticatedData, encapContentInfo, CMS_EncapsulatedContentInfo), ASN1_IMP_SET_OF_OPT(CMS_AuthenticatedData, authAttrs, X509_ALGOR, 2), ASN1_SIMPLE(CMS_AuthenticatedData, mac, ASN1_OCTET_STRING), ASN1_IMP_SET_OF_OPT(CMS_AuthenticatedData, unauthAttrs, X509_ALGOR, 3) } static_ASN1_NDEF_SEQUENCE_END(CMS_AuthenticatedData) ASN1_NDEF_SEQUENCE(CMS_CompressedData) = { ASN1_EMBED(CMS_CompressedData, version, INT32), ASN1_SIMPLE(CMS_CompressedData, compressionAlgorithm, X509_ALGOR), ASN1_SIMPLE(CMS_CompressedData, encapContentInfo, CMS_EncapsulatedContentInfo), } ASN1_NDEF_SEQUENCE_END(CMS_CompressedData) /* This is the ANY DEFINED BY table for the top level ContentInfo structure */ ASN1_ADB_TEMPLATE(cms_default) = ASN1_EXP(CMS_ContentInfo, d.other, ASN1_ANY, 0); ASN1_ADB(CMS_ContentInfo) = { ADB_ENTRY(NID_pkcs7_data, ASN1_NDEF_EXP(CMS_ContentInfo, d.data, ASN1_OCTET_STRING_NDEF, 0)), ADB_ENTRY(NID_pkcs7_signed, ASN1_NDEF_EXP(CMS_ContentInfo, d.signedData, CMS_SignedData, 0)), ADB_ENTRY(NID_pkcs7_enveloped, ASN1_NDEF_EXP(CMS_ContentInfo, d.envelopedData, CMS_EnvelopedData, 0)), ADB_ENTRY(NID_pkcs7_digest, ASN1_NDEF_EXP(CMS_ContentInfo, d.digestedData, CMS_DigestedData, 0)), ADB_ENTRY(NID_pkcs7_encrypted, ASN1_NDEF_EXP(CMS_ContentInfo, d.encryptedData, CMS_EncryptedData, 0)), ADB_ENTRY(NID_id_smime_ct_authEnvelopedData, ASN1_NDEF_EXP(CMS_ContentInfo, d.authEnvelopedData, CMS_AuthEnvelopedData, 0)), ADB_ENTRY(NID_id_smime_ct_authData, ASN1_NDEF_EXP(CMS_ContentInfo, d.authenticatedData, CMS_AuthenticatedData, 0)), ADB_ENTRY(NID_id_smime_ct_compressedData, ASN1_NDEF_EXP(CMS_ContentInfo, d.compressedData, CMS_CompressedData, 0)), } ASN1_ADB_END(CMS_ContentInfo, 0, contentType, 0, &cms_default_tt, NULL); /* CMS streaming support */ static int cms_cb(int operation, ASN1_VALUE **pval, const ASN1_ITEM *it, void *exarg) { ASN1_STREAM_ARG *sarg = exarg; CMS_ContentInfo *cms = NULL; if (pval) cms = (CMS_ContentInfo *)*pval; else return 1; switch (operation) { case ASN1_OP_STREAM_PRE: if (CMS_stream(&sarg->boundary, cms) <= 0) return 0; /* fall through */ case ASN1_OP_DETACHED_PRE: sarg->ndef_bio = CMS_dataInit(cms, sarg->out); if (!sarg->ndef_bio) return 0; break; case ASN1_OP_STREAM_POST: case ASN1_OP_DETACHED_POST: if (CMS_dataFinal(cms, sarg->ndef_bio) <= 0) return 0; break; } return 1; } ASN1_NDEF_SEQUENCE_cb(CMS_ContentInfo, cms_cb) = { ASN1_SIMPLE(CMS_ContentInfo, contentType, ASN1_OBJECT), ASN1_ADB_OBJECT(CMS_ContentInfo) } ASN1_NDEF_SEQUENCE_END_cb(CMS_ContentInfo, CMS_ContentInfo) /* Specials for signed attributes */ /* * When signing attributes we want to reorder them to match the sorted * encoding. */ ASN1_ITEM_TEMPLATE(CMS_Attributes_Sign) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SET_ORDER, 0, CMS_ATTRIBUTES, X509_ATTRIBUTE) ASN1_ITEM_TEMPLATE_END(CMS_Attributes_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(CMS_Attributes_Verify) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF | ASN1_TFLG_IMPTAG | ASN1_TFLG_UNIVERSAL, V_ASN1_SET, CMS_ATTRIBUTES, X509_ATTRIBUTE) ASN1_ITEM_TEMPLATE_END(CMS_Attributes_Verify) ASN1_CHOICE(CMS_ReceiptsFrom) = { ASN1_IMP_EMBED(CMS_ReceiptsFrom, d.allOrFirstTier, INT32, 0), ASN1_IMP_SEQUENCE_OF(CMS_ReceiptsFrom, d.receiptList, GENERAL_NAMES, 1) } static_ASN1_CHOICE_END(CMS_ReceiptsFrom) ASN1_SEQUENCE(CMS_ReceiptRequest) = { ASN1_SIMPLE(CMS_ReceiptRequest, signedContentIdentifier, ASN1_OCTET_STRING), ASN1_SIMPLE(CMS_ReceiptRequest, receiptsFrom, CMS_ReceiptsFrom), ASN1_SEQUENCE_OF(CMS_ReceiptRequest, receiptsTo, GENERAL_NAMES) } ASN1_SEQUENCE_END(CMS_ReceiptRequest) ASN1_SEQUENCE(CMS_Receipt) = { ASN1_EMBED(CMS_Receipt, version, INT32), ASN1_SIMPLE(CMS_Receipt, contentType, ASN1_OBJECT), ASN1_SIMPLE(CMS_Receipt, signedContentIdentifier, ASN1_OCTET_STRING), ASN1_SIMPLE(CMS_Receipt, originatorSignatureValue, ASN1_OCTET_STRING) } ASN1_SEQUENCE_END(CMS_Receipt) /* * Utilities to encode the CMS_SharedInfo structure used during key * derivation. */ typedef struct { X509_ALGOR *keyInfo; ASN1_OCTET_STRING *entityUInfo; ASN1_OCTET_STRING *suppPubInfo; } CMS_SharedInfo; ASN1_SEQUENCE(CMS_SharedInfo) = { ASN1_SIMPLE(CMS_SharedInfo, keyInfo, X509_ALGOR), ASN1_EXP_OPT(CMS_SharedInfo, entityUInfo, ASN1_OCTET_STRING, 0), ASN1_EXP_OPT(CMS_SharedInfo, suppPubInfo, ASN1_OCTET_STRING, 2), } static_ASN1_SEQUENCE_END(CMS_SharedInfo) int CMS_SharedInfo_encode(unsigned char **pder, X509_ALGOR *kekalg, ASN1_OCTET_STRING *ukm, int keylen) { union { CMS_SharedInfo *pecsi; ASN1_VALUE *a; } intsi = { NULL }; ASN1_OCTET_STRING oklen; unsigned char kl[4]; CMS_SharedInfo ecsi; keylen <<= 3; kl[0] = (keylen >> 24) & 0xff; kl[1] = (keylen >> 16) & 0xff; kl[2] = (keylen >> 8) & 0xff; kl[3] = keylen & 0xff; oklen.length = 4; oklen.data = kl; oklen.type = V_ASN1_OCTET_STRING; oklen.flags = 0; ecsi.keyInfo = kekalg; ecsi.entityUInfo = ukm; ecsi.suppPubInfo = &oklen; intsi.pecsi = &ecsi; return ASN1_item_i2d(intsi.a, pder, ASN1_ITEM_rptr(CMS_SharedInfo)); }
18,604
43.616307
132
c
openssl
openssl-master/crypto/cms/cms_att.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 <openssl/asn1t.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include <openssl/cms.h> #include "cms_local.h" #include "internal/nelem.h" /*- * Attribute flags. * CMS attribute restrictions are discussed in * - RFC 5652 Section 11. * ESS attribute restrictions are discussed in * - RFC 2634 Section 1.3.4 AND * - RFC 5035 Section 5.4 */ /* This is a signed attribute */ #define CMS_ATTR_F_SIGNED 0x01 /* This is an unsigned attribute */ #define CMS_ATTR_F_UNSIGNED 0x02 /* Must be present if there are any other attributes of the same type */ #define CMS_ATTR_F_REQUIRED_COND 0x10 /* There can only be one instance of this attribute */ #define CMS_ATTR_F_ONLY_ONE 0x20 /* The Attribute's value must have exactly one entry */ #define CMS_ATTR_F_ONE_ATTR_VALUE 0x40 /* Attributes rules for different attributes */ static const struct { int nid; /* The attribute id */ int flags; } cms_attribute_properties[] = { /* See RFC Section 11 */ { NID_pkcs9_contentType, CMS_ATTR_F_SIGNED | CMS_ATTR_F_ONLY_ONE | CMS_ATTR_F_ONE_ATTR_VALUE | CMS_ATTR_F_REQUIRED_COND }, { NID_pkcs9_messageDigest, CMS_ATTR_F_SIGNED | CMS_ATTR_F_ONLY_ONE | CMS_ATTR_F_ONE_ATTR_VALUE | CMS_ATTR_F_REQUIRED_COND }, { NID_pkcs9_signingTime, CMS_ATTR_F_SIGNED | CMS_ATTR_F_ONLY_ONE | CMS_ATTR_F_ONE_ATTR_VALUE }, { NID_pkcs9_countersignature, CMS_ATTR_F_UNSIGNED }, /* ESS */ { NID_id_smime_aa_signingCertificate, CMS_ATTR_F_SIGNED | CMS_ATTR_F_ONLY_ONE | CMS_ATTR_F_ONE_ATTR_VALUE }, { NID_id_smime_aa_signingCertificateV2, CMS_ATTR_F_SIGNED | CMS_ATTR_F_ONLY_ONE | CMS_ATTR_F_ONE_ATTR_VALUE }, { NID_id_smime_aa_receiptRequest, CMS_ATTR_F_SIGNED | CMS_ATTR_F_ONLY_ONE | CMS_ATTR_F_ONE_ATTR_VALUE } }; /* CMS SignedData Attribute utilities */ int CMS_signed_get_attr_count(const CMS_SignerInfo *si) { return X509at_get_attr_count(si->signedAttrs); } int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid, int lastpos) { return X509at_get_attr_by_NID(si->signedAttrs, nid, lastpos); } int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, const ASN1_OBJECT *obj, int lastpos) { return X509at_get_attr_by_OBJ(si->signedAttrs, obj, lastpos); } X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc) { return X509at_get_attr(si->signedAttrs, loc); } X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc) { return X509at_delete_attr(si->signedAttrs, loc); } int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr) { if (X509at_add1_attr(&si->signedAttrs, attr)) return 1; return 0; } int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si, const ASN1_OBJECT *obj, int type, const void *bytes, int len) { if (X509at_add1_attr_by_OBJ(&si->signedAttrs, obj, type, bytes, len)) return 1; return 0; } int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si, int nid, int type, const void *bytes, int len) { if (X509at_add1_attr_by_NID(&si->signedAttrs, nid, type, bytes, len)) return 1; return 0; } int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si, const char *attrname, int type, const void *bytes, int len) { if (X509at_add1_attr_by_txt(&si->signedAttrs, attrname, type, bytes, len)) return 1; return 0; } void *CMS_signed_get0_data_by_OBJ(const CMS_SignerInfo *si, const ASN1_OBJECT *oid, int lastpos, int type) { return X509at_get0_data_by_OBJ(si->signedAttrs, oid, lastpos, type); } int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si) { return X509at_get_attr_count(si->unsignedAttrs); } int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid, int lastpos) { return X509at_get_attr_by_NID(si->unsignedAttrs, nid, lastpos); } int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si, const ASN1_OBJECT *obj, int lastpos) { return X509at_get_attr_by_OBJ(si->unsignedAttrs, obj, lastpos); } X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc) { return X509at_get_attr(si->unsignedAttrs, loc); } X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc) { return X509at_delete_attr(si->unsignedAttrs, loc); } int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr) { if (X509at_add1_attr(&si->unsignedAttrs, attr)) return 1; return 0; } int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si, const ASN1_OBJECT *obj, int type, const void *bytes, int len) { if (X509at_add1_attr_by_OBJ(&si->unsignedAttrs, obj, type, bytes, len)) return 1; return 0; } int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si, int nid, int type, const void *bytes, int len) { if (X509at_add1_attr_by_NID(&si->unsignedAttrs, nid, type, bytes, len)) return 1; return 0; } int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si, const char *attrname, int type, const void *bytes, int len) { if (X509at_add1_attr_by_txt(&si->unsignedAttrs, attrname, type, bytes, len)) return 1; return 0; } void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid, int lastpos, int type) { return X509at_get0_data_by_OBJ(si->unsignedAttrs, oid, lastpos, type); } /* * Retrieve an attribute by nid from a stack of attributes starting at index * *lastpos + 1. * Returns the attribute or NULL if there is no attribute. * If an attribute was found *lastpos returns the index of the found attribute. */ static X509_ATTRIBUTE *cms_attrib_get(int nid, const STACK_OF(X509_ATTRIBUTE) *attrs, int *lastpos) { X509_ATTRIBUTE *at; int loc; loc = X509at_get_attr_by_NID(attrs, nid, *lastpos); if (loc < 0) return NULL; at = X509at_get_attr(attrs, loc); *lastpos = loc; return at; } static int cms_check_attribute(int nid, int flags, int type, const STACK_OF(X509_ATTRIBUTE) *attrs, int have_attrs) { int lastpos = -1; X509_ATTRIBUTE *at = cms_attrib_get(nid, attrs, &lastpos); if (at != NULL) { int count = X509_ATTRIBUTE_count(at); /* Is this attribute allowed? */ if (((flags & type) == 0) /* check if multiple attributes of the same type are allowed */ || (((flags & CMS_ATTR_F_ONLY_ONE) != 0) && cms_attrib_get(nid, attrs, &lastpos) != NULL) /* Check if attribute should have exactly one value in its set */ || (((flags & CMS_ATTR_F_ONE_ATTR_VALUE) != 0) && count != 1) /* There should be at least one value */ || count == 0) return 0; } else { /* fail if a required attribute is missing */ if (have_attrs && ((flags & CMS_ATTR_F_REQUIRED_COND) != 0) && (flags & type) != 0) return 0; } return 1; } /* * Check that the signerinfo attributes obey the attribute rules which includes * the following checks * - If any signed attributes exist then there must be a Content Type * and Message Digest attribute in the signed attributes. * - The countersignature attribute is an optional unsigned attribute only. * - Content Type, Message Digest, and Signing time attributes are signed * attributes. Only one instance of each is allowed, with each of these * attributes containing a single attribute value in its set. */ int ossl_cms_si_check_attributes(const CMS_SignerInfo *si) { int i; int have_signed_attrs = (CMS_signed_get_attr_count(si) > 0); int have_unsigned_attrs = (CMS_unsigned_get_attr_count(si) > 0); for (i = 0; i < (int)OSSL_NELEM(cms_attribute_properties); ++i) { int nid = cms_attribute_properties[i].nid; int flags = cms_attribute_properties[i].flags; if (!cms_check_attribute(nid, flags, CMS_ATTR_F_SIGNED, si->signedAttrs, have_signed_attrs) || !cms_check_attribute(nid, flags, CMS_ATTR_F_UNSIGNED, si->unsignedAttrs, have_unsigned_attrs)) { ERR_raise(ERR_LIB_CMS, CMS_R_ATTRIBUTE_ERROR); return 0; } } return 1; }
9,679
32.846154
80
c
openssl
openssl-master/crypto/cms/cms_cd.c
/* * Copyright 2008-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include <openssl/cms.h> #include <openssl/bio.h> #include <openssl/comp.h> #include "cms_local.h" #ifndef OPENSSL_NO_ZLIB /* CMS CompressedData Utilities */ CMS_ContentInfo *ossl_cms_CompressedData_create(int comp_nid, OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *cms; CMS_CompressedData *cd; /* * Will need something cleverer if there is ever more than one * compression algorithm or parameters have some meaning... */ if (comp_nid != NID_zlib_compression) { ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM); return NULL; } cms = CMS_ContentInfo_new_ex(libctx, propq); if (cms == NULL) return NULL; cd = M_ASN1_new_of(CMS_CompressedData); if (cd == NULL) goto err; cms->contentType = OBJ_nid2obj(NID_id_smime_ct_compressedData); cms->d.compressedData = cd; cd->version = 0; (void)X509_ALGOR_set0(cd->compressionAlgorithm, OBJ_nid2obj(NID_zlib_compression), V_ASN1_UNDEF, NULL); /* cannot fail */ cd->encapContentInfo->eContentType = OBJ_nid2obj(NID_pkcs7_data); return cms; err: CMS_ContentInfo_free(cms); return NULL; } BIO *ossl_cms_CompressedData_init_bio(const CMS_ContentInfo *cms) { CMS_CompressedData *cd; const ASN1_OBJECT *compoid; if (OBJ_obj2nid(cms->contentType) != NID_id_smime_ct_compressedData) { ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA); return NULL; } cd = cms->d.compressedData; X509_ALGOR_get0(&compoid, NULL, NULL, cd->compressionAlgorithm); if (OBJ_obj2nid(compoid) != NID_zlib_compression) { ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM); return NULL; } return BIO_new(BIO_f_zlib()); } #endif
2,407
27.329412
74
c
openssl
openssl-master/crypto/cms/cms_dd.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 "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include <openssl/cms.h> #include "cms_local.h" /* CMS DigestedData Utilities */ CMS_ContentInfo *ossl_cms_DigestedData_create(const EVP_MD *md, OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *cms; CMS_DigestedData *dd; cms = CMS_ContentInfo_new_ex(libctx, propq); if (cms == NULL) return NULL; dd = M_ASN1_new_of(CMS_DigestedData); if (dd == NULL) goto err; cms->contentType = OBJ_nid2obj(NID_pkcs7_digest); cms->d.digestedData = dd; dd->version = 0; dd->encapContentInfo->eContentType = OBJ_nid2obj(NID_pkcs7_data); X509_ALGOR_set_md(dd->digestAlgorithm, md); return cms; err: CMS_ContentInfo_free(cms); return NULL; } BIO *ossl_cms_DigestedData_init_bio(const CMS_ContentInfo *cms) { CMS_DigestedData *dd = cms->d.digestedData; return ossl_cms_DigestAlgorithm_init_bio(dd->digestAlgorithm, ossl_cms_get0_cmsctx(cms)); } int ossl_cms_DigestedData_do_final(const CMS_ContentInfo *cms, BIO *chain, int verify) { EVP_MD_CTX *mctx = EVP_MD_CTX_new(); unsigned char md[EVP_MAX_MD_SIZE]; unsigned int mdlen; int r = 0; CMS_DigestedData *dd; if (mctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } dd = cms->d.digestedData; if (!ossl_cms_DigestAlgorithm_find_ctx(mctx, chain, dd->digestAlgorithm)) goto err; if (EVP_DigestFinal_ex(mctx, md, &mdlen) <= 0) goto err; if (verify) { if (mdlen != (unsigned int)dd->digest->length) { ERR_raise(ERR_LIB_CMS, CMS_R_MESSAGEDIGEST_WRONG_LENGTH); goto err; } if (memcmp(md, dd->digest->data, mdlen)) ERR_raise(ERR_LIB_CMS, CMS_R_VERIFICATION_FAILURE); else r = 1; } else { if (!ASN1_STRING_set(dd->digest, md, mdlen)) goto err; r = 1; } err: EVP_MD_CTX_free(mctx); return r; }
2,587
24.126214
77
c
openssl
openssl-master/crypto/cms/cms_dh.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 <assert.h> #include <openssl/cms.h> #include <openssl/dh.h> #include <openssl/err.h> #include <openssl/core_names.h> #include "internal/sizes.h" #include "crypto/asn1.h" #include "crypto/evp.h" #include "cms_local.h" static int dh_cms_set_peerkey(EVP_PKEY_CTX *pctx, X509_ALGOR *alg, ASN1_BIT_STRING *pubkey) { const ASN1_OBJECT *aoid; int atype; const void *aval; ASN1_INTEGER *public_key = NULL; int rv = 0; EVP_PKEY *pkpeer = NULL, *pk = NULL; BIGNUM *bnpub = NULL; const unsigned char *p; unsigned char *buf = NULL; int plen; X509_ALGOR_get0(&aoid, &atype, &aval, alg); if (OBJ_obj2nid(aoid) != NID_dhpublicnumber) goto err; /* Only absent parameters allowed in RFC XXXX */ if (atype != V_ASN1_UNDEF && atype == V_ASN1_NULL) goto err; pk = EVP_PKEY_CTX_get0_pkey(pctx); if (pk == NULL || !EVP_PKEY_is_a(pk, "DHX")) goto err; /* Get public key */ plen = ASN1_STRING_length(pubkey); p = ASN1_STRING_get0_data(pubkey); if (p == NULL || plen == 0) goto err; if ((public_key = d2i_ASN1_INTEGER(NULL, &p, plen)) == NULL) goto err; /* * Pad to full p parameter size as that is checked by * EVP_PKEY_set1_encoded_public_key() */ plen = EVP_PKEY_get_size(pk); if ((bnpub = ASN1_INTEGER_to_BN(public_key, NULL)) == NULL) goto err; if ((buf = OPENSSL_malloc(plen)) == NULL) goto err; if (BN_bn2binpad(bnpub, buf, plen) < 0) goto err; pkpeer = EVP_PKEY_new(); if (pkpeer == NULL || !EVP_PKEY_copy_parameters(pkpeer, pk) || !EVP_PKEY_set1_encoded_public_key(pkpeer, buf, plen)) goto err; if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0) rv = 1; err: ASN1_INTEGER_free(public_key); BN_free(bnpub); OPENSSL_free(buf); EVP_PKEY_free(pkpeer); return rv; } static int dh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri) { int rv = 0; X509_ALGOR *alg, *kekalg = NULL; ASN1_OCTET_STRING *ukm; const unsigned char *p; unsigned char *dukm = NULL; size_t dukmlen = 0; int keylen, plen; EVP_CIPHER *kekcipher = NULL; EVP_CIPHER_CTX *kekctx; char name[OSSL_MAX_NAME_SIZE]; if (!CMS_RecipientInfo_kari_get0_alg(ri, &alg, &ukm)) goto err; /* * For DH we only have one OID permissible. If ever any more get defined * we will need something cleverer. */ if (OBJ_obj2nid(alg->algorithm) != NID_id_smime_alg_ESDH) { ERR_raise(ERR_LIB_CMS, CMS_R_KDF_PARAMETER_ERROR); goto err; } if (EVP_PKEY_CTX_set_dh_kdf_type(pctx, EVP_PKEY_DH_KDF_X9_42) <= 0 || EVP_PKEY_CTX_set_dh_kdf_md(pctx, EVP_sha1()) <= 0) goto err; if (alg->parameter->type != V_ASN1_SEQUENCE) goto err; p = alg->parameter->value.sequence->data; plen = alg->parameter->value.sequence->length; kekalg = d2i_X509_ALGOR(NULL, &p, plen); if (kekalg == NULL) goto err; kekctx = CMS_RecipientInfo_kari_get0_ctx(ri); if (kekctx == NULL) goto err; if (OBJ_obj2txt(name, sizeof(name), kekalg->algorithm, 0) <= 0) goto err; kekcipher = EVP_CIPHER_fetch(pctx->libctx, name, pctx->propquery); if (kekcipher == NULL || EVP_CIPHER_get_mode(kekcipher) != EVP_CIPH_WRAP_MODE) goto err; if (!EVP_EncryptInit_ex(kekctx, kekcipher, NULL, NULL, NULL)) goto err; if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0) goto err; keylen = EVP_CIPHER_CTX_get_key_length(kekctx); if (EVP_PKEY_CTX_set_dh_kdf_outlen(pctx, keylen) <= 0) goto err; /* Use OBJ_nid2obj to ensure we use built in OID that isn't freed */ if (EVP_PKEY_CTX_set0_dh_kdf_oid(pctx, OBJ_nid2obj(EVP_CIPHER_get_type(kekcipher))) <= 0) goto err; if (ukm != NULL) { dukmlen = ASN1_STRING_length(ukm); dukm = OPENSSL_memdup(ASN1_STRING_get0_data(ukm), dukmlen); if (dukm == NULL) goto err; } if (EVP_PKEY_CTX_set0_dh_kdf_ukm(pctx, dukm, dukmlen) <= 0) goto err; dukm = NULL; rv = 1; err: X509_ALGOR_free(kekalg); EVP_CIPHER_free(kekcipher); OPENSSL_free(dukm); return rv; } static int dh_cms_decrypt(CMS_RecipientInfo *ri) { EVP_PKEY_CTX *pctx = CMS_RecipientInfo_get0_pkey_ctx(ri); if (pctx == NULL) return 0; /* See if we need to set peer key */ if (!EVP_PKEY_CTX_get0_peerkey(pctx)) { X509_ALGOR *alg; ASN1_BIT_STRING *pubkey; if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &alg, &pubkey, NULL, NULL, NULL)) return 0; if (alg == NULL || pubkey == NULL) return 0; if (!dh_cms_set_peerkey(pctx, alg, pubkey)) { ERR_raise(ERR_LIB_CMS, CMS_R_PEER_KEY_ERROR); return 0; } } /* Set DH derivation parameters and initialise unwrap context */ if (!dh_cms_set_shared_info(pctx, ri)) { ERR_raise(ERR_LIB_CMS, CMS_R_SHARED_INFO_ERROR); return 0; } return 1; } static int dh_cms_encrypt(CMS_RecipientInfo *ri) { EVP_PKEY_CTX *pctx; EVP_PKEY *pkey; EVP_CIPHER_CTX *ctx; int keylen; X509_ALGOR *talg, *wrap_alg = NULL; const ASN1_OBJECT *aoid; ASN1_BIT_STRING *pubkey; ASN1_STRING *wrap_str; ASN1_OCTET_STRING *ukm; unsigned char *penc = NULL, *dukm = NULL; int penclen; size_t dukmlen = 0; int rv = 0; int kdf_type, wrap_nid; const EVP_MD *kdf_md; pctx = CMS_RecipientInfo_get0_pkey_ctx(ri); if (pctx == NULL) return 0; /* Get ephemeral key */ pkey = EVP_PKEY_CTX_get0_pkey(pctx); if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &talg, &pubkey, NULL, NULL, NULL)) goto err; /* Is everything uninitialised? */ X509_ALGOR_get0(&aoid, NULL, NULL, talg); if (aoid == OBJ_nid2obj(NID_undef)) { BIGNUM *bn_pub_key = NULL; ASN1_INTEGER *pubk; if (!EVP_PKEY_get_bn_param(pkey, OSSL_PKEY_PARAM_PUB_KEY, &bn_pub_key)) goto err; pubk = BN_to_ASN1_INTEGER(bn_pub_key, NULL); BN_free(bn_pub_key); if (pubk == NULL) goto err; /* Set the key */ penclen = i2d_ASN1_INTEGER(pubk, &penc); ASN1_INTEGER_free(pubk); if (penclen <= 0) goto err; ASN1_STRING_set0(pubkey, penc, penclen); ossl_asn1_string_set_bits_left(pubkey, 0); penc = NULL; (void)X509_ALGOR_set0(talg, OBJ_nid2obj(NID_dhpublicnumber), V_ASN1_UNDEF, NULL); /* cannot fail */ } /* See if custom parameters set */ kdf_type = EVP_PKEY_CTX_get_dh_kdf_type(pctx); if (kdf_type <= 0 || EVP_PKEY_CTX_get_dh_kdf_md(pctx, &kdf_md) <= 0) goto err; if (kdf_type == EVP_PKEY_DH_KDF_NONE) { kdf_type = EVP_PKEY_DH_KDF_X9_42; if (EVP_PKEY_CTX_set_dh_kdf_type(pctx, kdf_type) <= 0) goto err; } else if (kdf_type != EVP_PKEY_DH_KDF_X9_42) /* Unknown KDF */ goto err; if (kdf_md == NULL) { /* Only SHA1 supported */ kdf_md = EVP_sha1(); if (EVP_PKEY_CTX_set_dh_kdf_md(pctx, kdf_md) <= 0) goto err; } else if (EVP_MD_get_type(kdf_md) != NID_sha1) /* Unsupported digest */ goto err; if (!CMS_RecipientInfo_kari_get0_alg(ri, &talg, &ukm)) goto err; /* Get wrap NID */ ctx = CMS_RecipientInfo_kari_get0_ctx(ri); wrap_nid = EVP_CIPHER_CTX_get_type(ctx); if (EVP_PKEY_CTX_set0_dh_kdf_oid(pctx, OBJ_nid2obj(wrap_nid)) <= 0) goto err; keylen = EVP_CIPHER_CTX_get_key_length(ctx); /* Package wrap algorithm in an AlgorithmIdentifier */ wrap_alg = X509_ALGOR_new(); if (wrap_alg == NULL) goto err; wrap_alg->algorithm = OBJ_nid2obj(wrap_nid); wrap_alg->parameter = ASN1_TYPE_new(); if (wrap_alg->parameter == NULL) goto err; if (EVP_CIPHER_param_to_asn1(ctx, wrap_alg->parameter) <= 0) goto err; if (ASN1_TYPE_get(wrap_alg->parameter) == NID_undef) { ASN1_TYPE_free(wrap_alg->parameter); wrap_alg->parameter = NULL; } if (EVP_PKEY_CTX_set_dh_kdf_outlen(pctx, keylen) <= 0) goto err; if (ukm != NULL) { dukmlen = ASN1_STRING_length(ukm); dukm = OPENSSL_memdup(ASN1_STRING_get0_data(ukm), dukmlen); if (dukm == NULL) goto err; } if (EVP_PKEY_CTX_set0_dh_kdf_ukm(pctx, dukm, dukmlen) <= 0) goto err; dukm = NULL; /* * Now need to wrap encoding of wrap AlgorithmIdentifier into parameter * of another AlgorithmIdentifier. */ penc = NULL; penclen = i2d_X509_ALGOR(wrap_alg, &penc); if (penclen <= 0) goto err; wrap_str = ASN1_STRING_new(); if (wrap_str == NULL) goto err; ASN1_STRING_set0(wrap_str, penc, penclen); penc = NULL; rv = X509_ALGOR_set0(talg, OBJ_nid2obj(NID_id_smime_alg_ESDH), V_ASN1_SEQUENCE, wrap_str); if (!rv) ASN1_STRING_free(wrap_str); err: OPENSSL_free(penc); X509_ALGOR_free(wrap_alg); OPENSSL_free(dukm); return rv; } int ossl_cms_dh_envelope(CMS_RecipientInfo *ri, int decrypt) { assert(decrypt == 0 || decrypt == 1); if (decrypt == 1) return dh_cms_decrypt(ri); if (decrypt == 0) return dh_cms_encrypt(ri); ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); return 0; }
10,084
28.31686
81
c
openssl
openssl-master/crypto/cms/cms_ec.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 <assert.h> #include <limits.h> #include <openssl/cms.h> #include <openssl/err.h> #include <openssl/decoder.h> #include "internal/sizes.h" #include "crypto/asn1.h" #include "crypto/evp.h" #include "cms_local.h" static EVP_PKEY *pkey_type2param(int ptype, const void *pval, OSSL_LIB_CTX *libctx, const char *propq) { EVP_PKEY *pkey = NULL; EVP_PKEY_CTX *pctx = NULL; OSSL_DECODER_CTX *ctx = NULL; if (ptype == V_ASN1_SEQUENCE) { const ASN1_STRING *pstr = pval; const unsigned char *pm = pstr->data; size_t pmlen = (size_t)pstr->length; int selection = OSSL_KEYMGMT_SELECT_ALL_PARAMETERS; ctx = OSSL_DECODER_CTX_new_for_pkey(&pkey, "DER", NULL, "EC", selection, libctx, propq); if (ctx == NULL) goto err; if (!OSSL_DECODER_from_data(ctx, &pm, &pmlen)) { ERR_raise(ERR_LIB_CMS, CMS_R_DECODE_ERROR); goto err; } OSSL_DECODER_CTX_free(ctx); return pkey; } else if (ptype == V_ASN1_OBJECT) { const ASN1_OBJECT *poid = pval; char groupname[OSSL_MAX_NAME_SIZE]; /* type == V_ASN1_OBJECT => the parameters are given by an asn1 OID */ pctx = EVP_PKEY_CTX_new_from_name(libctx, "EC", propq); if (pctx == NULL || EVP_PKEY_paramgen_init(pctx) <= 0) goto err; if (OBJ_obj2txt(groupname, sizeof(groupname), poid, 0) <= 0 || EVP_PKEY_CTX_set_group_name(pctx, groupname) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_DECODE_ERROR); goto err; } if (EVP_PKEY_paramgen(pctx, &pkey) <= 0) goto err; EVP_PKEY_CTX_free(pctx); return pkey; } ERR_raise(ERR_LIB_CMS, CMS_R_DECODE_ERROR); return NULL; err: EVP_PKEY_free(pkey); EVP_PKEY_CTX_free(pctx); OSSL_DECODER_CTX_free(ctx); return NULL; } static int ecdh_cms_set_peerkey(EVP_PKEY_CTX *pctx, X509_ALGOR *alg, ASN1_BIT_STRING *pubkey) { const ASN1_OBJECT *aoid; int atype; const void *aval; int rv = 0; EVP_PKEY *pkpeer = NULL; const unsigned char *p; int plen; X509_ALGOR_get0(&aoid, &atype, &aval, alg); if (OBJ_obj2nid(aoid) != NID_X9_62_id_ecPublicKey) goto err; /* If absent parameters get group from main key */ if (atype == V_ASN1_UNDEF || atype == V_ASN1_NULL) { EVP_PKEY *pk; pk = EVP_PKEY_CTX_get0_pkey(pctx); if (pk == NULL) goto err; pkpeer = EVP_PKEY_new(); if (pkpeer == NULL) goto err; if (!EVP_PKEY_copy_parameters(pkpeer, pk)) goto err; } else { pkpeer = pkey_type2param(atype, aval, EVP_PKEY_CTX_get0_libctx(pctx), EVP_PKEY_CTX_get0_propq(pctx)); if (pkpeer == NULL) goto err; } /* We have parameters now set public key */ plen = ASN1_STRING_length(pubkey); p = ASN1_STRING_get0_data(pubkey); if (p == NULL || plen == 0) goto err; if (!EVP_PKEY_set1_encoded_public_key(pkpeer, p, plen)) goto err; if (EVP_PKEY_derive_set_peer(pctx, pkpeer) > 0) rv = 1; err: EVP_PKEY_free(pkpeer); return rv; } /* Set KDF parameters based on KDF NID */ static int ecdh_cms_set_kdf_param(EVP_PKEY_CTX *pctx, int eckdf_nid) { int kdf_nid, kdfmd_nid, cofactor; const EVP_MD *kdf_md; if (eckdf_nid == NID_undef) return 0; /* Lookup KDF type, cofactor mode and digest */ if (!OBJ_find_sigid_algs(eckdf_nid, &kdfmd_nid, &kdf_nid)) return 0; if (kdf_nid == NID_dh_std_kdf) cofactor = 0; else if (kdf_nid == NID_dh_cofactor_kdf) cofactor = 1; else return 0; if (EVP_PKEY_CTX_set_ecdh_cofactor_mode(pctx, cofactor) <= 0) return 0; if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, EVP_PKEY_ECDH_KDF_X9_63) <= 0) return 0; kdf_md = EVP_get_digestbynid(kdfmd_nid); if (!kdf_md) return 0; if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0) return 0; return 1; } static int ecdh_cms_set_shared_info(EVP_PKEY_CTX *pctx, CMS_RecipientInfo *ri) { int rv = 0; X509_ALGOR *alg, *kekalg = NULL; ASN1_OCTET_STRING *ukm; const unsigned char *p; unsigned char *der = NULL; int plen, keylen; EVP_CIPHER *kekcipher = NULL; EVP_CIPHER_CTX *kekctx; char name[OSSL_MAX_NAME_SIZE]; if (!CMS_RecipientInfo_kari_get0_alg(ri, &alg, &ukm)) return 0; if (!ecdh_cms_set_kdf_param(pctx, OBJ_obj2nid(alg->algorithm))) { ERR_raise(ERR_LIB_CMS, CMS_R_KDF_PARAMETER_ERROR); return 0; } if (alg->parameter->type != V_ASN1_SEQUENCE) return 0; p = alg->parameter->value.sequence->data; plen = alg->parameter->value.sequence->length; kekalg = d2i_X509_ALGOR(NULL, &p, plen); if (kekalg == NULL) goto err; kekctx = CMS_RecipientInfo_kari_get0_ctx(ri); if (kekctx == NULL) goto err; OBJ_obj2txt(name, sizeof(name), kekalg->algorithm, 0); kekcipher = EVP_CIPHER_fetch(pctx->libctx, name, pctx->propquery); if (kekcipher == NULL || EVP_CIPHER_get_mode(kekcipher) != EVP_CIPH_WRAP_MODE) goto err; if (!EVP_EncryptInit_ex(kekctx, kekcipher, NULL, NULL, NULL)) goto err; if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0) goto err; keylen = EVP_CIPHER_CTX_get_key_length(kekctx); if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0) goto err; plen = CMS_SharedInfo_encode(&der, kekalg, ukm, keylen); if (plen <= 0) goto err; if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, der, plen) <= 0) goto err; der = NULL; rv = 1; err: EVP_CIPHER_free(kekcipher); X509_ALGOR_free(kekalg); OPENSSL_free(der); return rv; } static int ecdh_cms_decrypt(CMS_RecipientInfo *ri) { EVP_PKEY_CTX *pctx; pctx = CMS_RecipientInfo_get0_pkey_ctx(ri); if (pctx == NULL) return 0; /* See if we need to set peer key */ if (!EVP_PKEY_CTX_get0_peerkey(pctx)) { X509_ALGOR *alg; ASN1_BIT_STRING *pubkey; if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &alg, &pubkey, NULL, NULL, NULL)) return 0; if (alg == NULL || pubkey == NULL) return 0; if (!ecdh_cms_set_peerkey(pctx, alg, pubkey)) { ERR_raise(ERR_LIB_CMS, CMS_R_PEER_KEY_ERROR); return 0; } } /* Set ECDH derivation parameters and initialise unwrap context */ if (!ecdh_cms_set_shared_info(pctx, ri)) { ERR_raise(ERR_LIB_CMS, CMS_R_SHARED_INFO_ERROR); return 0; } return 1; } static int ecdh_cms_encrypt(CMS_RecipientInfo *ri) { EVP_PKEY_CTX *pctx; EVP_PKEY *pkey; EVP_CIPHER_CTX *ctx; int keylen; X509_ALGOR *talg, *wrap_alg = NULL; const ASN1_OBJECT *aoid; ASN1_BIT_STRING *pubkey; ASN1_STRING *wrap_str; ASN1_OCTET_STRING *ukm; unsigned char *penc = NULL; int penclen; int rv = 0; int ecdh_nid, kdf_type, kdf_nid, wrap_nid; const EVP_MD *kdf_md; pctx = CMS_RecipientInfo_get0_pkey_ctx(ri); if (pctx == NULL) return 0; /* Get ephemeral key */ pkey = EVP_PKEY_CTX_get0_pkey(pctx); if (!CMS_RecipientInfo_kari_get0_orig_id(ri, &talg, &pubkey, NULL, NULL, NULL)) goto err; X509_ALGOR_get0(&aoid, NULL, NULL, talg); /* Is everything uninitialised? */ if (aoid == OBJ_nid2obj(NID_undef)) { /* Set the key */ size_t enckeylen; enckeylen = EVP_PKEY_get1_encoded_public_key(pkey, &penc); if (enckeylen > INT_MAX || enckeylen == 0) goto err; ASN1_STRING_set0(pubkey, penc, (int)enckeylen); ossl_asn1_string_set_bits_left(pubkey, 0); penc = NULL; (void)X509_ALGOR_set0(talg, OBJ_nid2obj(NID_X9_62_id_ecPublicKey), V_ASN1_UNDEF, NULL); /* cannot fail */ } /* See if custom parameters set */ kdf_type = EVP_PKEY_CTX_get_ecdh_kdf_type(pctx); if (kdf_type <= 0) goto err; if (EVP_PKEY_CTX_get_ecdh_kdf_md(pctx, &kdf_md) <= 0) goto err; ecdh_nid = EVP_PKEY_CTX_get_ecdh_cofactor_mode(pctx); if (ecdh_nid < 0) goto err; else if (ecdh_nid == 0) ecdh_nid = NID_dh_std_kdf; else if (ecdh_nid == 1) ecdh_nid = NID_dh_cofactor_kdf; if (kdf_type == EVP_PKEY_ECDH_KDF_NONE) { kdf_type = EVP_PKEY_ECDH_KDF_X9_63; if (EVP_PKEY_CTX_set_ecdh_kdf_type(pctx, kdf_type) <= 0) goto err; } else /* Unknown KDF */ goto err; if (kdf_md == NULL) { /* Fixme later for better MD */ kdf_md = EVP_sha1(); if (EVP_PKEY_CTX_set_ecdh_kdf_md(pctx, kdf_md) <= 0) goto err; } if (!CMS_RecipientInfo_kari_get0_alg(ri, &talg, &ukm)) goto err; /* Lookup NID for KDF+cofactor+digest */ if (!OBJ_find_sigid_by_algs(&kdf_nid, EVP_MD_get_type(kdf_md), ecdh_nid)) goto err; /* Get wrap NID */ ctx = CMS_RecipientInfo_kari_get0_ctx(ri); wrap_nid = EVP_CIPHER_CTX_get_type(ctx); keylen = EVP_CIPHER_CTX_get_key_length(ctx); /* Package wrap algorithm in an AlgorithmIdentifier */ wrap_alg = X509_ALGOR_new(); if (wrap_alg == NULL) goto err; wrap_alg->algorithm = OBJ_nid2obj(wrap_nid); wrap_alg->parameter = ASN1_TYPE_new(); if (wrap_alg->parameter == NULL) goto err; if (EVP_CIPHER_param_to_asn1(ctx, wrap_alg->parameter) <= 0) goto err; if (ASN1_TYPE_get(wrap_alg->parameter) == NID_undef) { ASN1_TYPE_free(wrap_alg->parameter); wrap_alg->parameter = NULL; } if (EVP_PKEY_CTX_set_ecdh_kdf_outlen(pctx, keylen) <= 0) goto err; penclen = CMS_SharedInfo_encode(&penc, wrap_alg, ukm, keylen); if (penclen <= 0) goto err; if (EVP_PKEY_CTX_set0_ecdh_kdf_ukm(pctx, penc, penclen) <= 0) goto err; penc = NULL; /* * Now need to wrap encoding of wrap AlgorithmIdentifier into parameter * of another AlgorithmIdentifier. */ penclen = i2d_X509_ALGOR(wrap_alg, &penc); if (penclen <= 0) goto err; wrap_str = ASN1_STRING_new(); if (wrap_str == NULL) goto err; ASN1_STRING_set0(wrap_str, penc, penclen); penc = NULL; rv = X509_ALGOR_set0(talg, OBJ_nid2obj(kdf_nid), V_ASN1_SEQUENCE, wrap_str); if (!rv) ASN1_STRING_free(wrap_str); err: OPENSSL_free(penc); X509_ALGOR_free(wrap_alg); return rv; } int ossl_cms_ecdh_envelope(CMS_RecipientInfo *ri, int decrypt) { assert(decrypt == 0 || decrypt == 1); if (decrypt == 1) return ecdh_cms_decrypt(ri); if (decrypt == 0) return ecdh_cms_encrypt(ri); ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); return 0; }
11,498
28.111392
82
c
openssl
openssl-master/crypto/cms/cms_enc.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 "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include <openssl/cms.h> #include <openssl/rand.h> #include "crypto/evp.h" #include "cms_local.h" /* CMS EncryptedData Utilities */ /* Return BIO based on EncryptedContentInfo and key */ BIO *ossl_cms_EncryptedContent_init_bio(CMS_EncryptedContentInfo *ec, const CMS_CTX *cms_ctx) { BIO *b; EVP_CIPHER_CTX *ctx; EVP_CIPHER *fetched_ciph = NULL; const EVP_CIPHER *cipher = NULL; X509_ALGOR *calg = ec->contentEncryptionAlgorithm; evp_cipher_aead_asn1_params aparams; unsigned char iv[EVP_MAX_IV_LENGTH], *piv = NULL; unsigned char *tkey = NULL; int len; int ivlen = 0; size_t tkeylen = 0; int ok = 0; int enc, keep_key = 0; OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(cms_ctx); const char *propq = ossl_cms_ctx_get0_propq(cms_ctx); enc = ec->cipher ? 1 : 0; b = BIO_new(BIO_f_cipher()); if (b == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_BIO_LIB); return NULL; } BIO_get_cipher_ctx(b, &ctx); (void)ERR_set_mark(); if (enc) { cipher = ec->cipher; /* * If not keeping key set cipher to NULL so subsequent calls decrypt. */ if (ec->key != NULL) ec->cipher = NULL; } else { cipher = EVP_get_cipherbyobj(calg->algorithm); } if (cipher != NULL) { fetched_ciph = EVP_CIPHER_fetch(libctx, EVP_CIPHER_get0_name(cipher), propq); if (fetched_ciph != NULL) cipher = fetched_ciph; } if (cipher == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_CIPHER); goto err; } (void)ERR_pop_to_mark(); if (EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_INITIALISATION_ERROR); goto err; } if (enc) { calg->algorithm = OBJ_nid2obj(EVP_CIPHER_CTX_get_type(ctx)); if (calg->algorithm == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_CONTENT_ENCRYPTION_ALGORITHM); goto err; } /* Generate a random IV if we need one */ ivlen = EVP_CIPHER_CTX_get_iv_length(ctx); if (ivlen < 0) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } if (ivlen > 0) { if (RAND_bytes_ex(libctx, iv, ivlen, 0) <= 0) goto err; piv = iv; } } else { if (evp_cipher_asn1_to_param_ex(ctx, calg->parameter, &aparams) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR); goto err; } if ((EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)) { piv = aparams.iv; if (ec->taglen > 0 && EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, ec->taglen, ec->tag) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_AEAD_SET_TAG_ERROR); goto err; } } } len = EVP_CIPHER_CTX_get_key_length(ctx); if (len <= 0) goto err; tkeylen = (size_t)len; /* Generate random session key */ if (!enc || !ec->key) { tkey = OPENSSL_malloc(tkeylen); if (tkey == NULL) goto err; if (EVP_CIPHER_CTX_rand_key(ctx, tkey) <= 0) goto err; } if (!ec->key) { ec->key = tkey; ec->keylen = tkeylen; tkey = NULL; if (enc) keep_key = 1; else ERR_clear_error(); } if (ec->keylen != tkeylen) { /* If necessary set key length */ if (EVP_CIPHER_CTX_set_key_length(ctx, ec->keylen) <= 0) { /* * Only reveal failure if debugging so we don't leak information * which may be useful in MMA. */ if (enc || ec->debug) { ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_LENGTH); goto err; } else { /* Use random key */ OPENSSL_clear_free(ec->key, ec->keylen); ec->key = tkey; ec->keylen = tkeylen; tkey = NULL; ERR_clear_error(); } } } if (EVP_CipherInit_ex(ctx, NULL, NULL, ec->key, piv, enc) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_INITIALISATION_ERROR); goto err; } if (enc) { calg->parameter = ASN1_TYPE_new(); if (calg->parameter == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } if ((EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER)) { memcpy(aparams.iv, piv, ivlen); aparams.iv_len = ivlen; aparams.tag_len = EVP_CIPHER_CTX_get_tag_length(ctx); if (aparams.tag_len <= 0) goto err; } if (evp_cipher_param_to_asn1_ex(ctx, calg->parameter, &aparams) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR); goto err; } /* If parameter type not set omit parameter */ if (calg->parameter->type == V_ASN1_UNDEF) { ASN1_TYPE_free(calg->parameter); calg->parameter = NULL; } } ok = 1; err: EVP_CIPHER_free(fetched_ciph); if (!keep_key || !ok) { OPENSSL_clear_free(ec->key, ec->keylen); ec->key = NULL; } OPENSSL_clear_free(tkey, tkeylen); if (ok) return b; BIO_free(b); return NULL; } int ossl_cms_EncryptedContent_init(CMS_EncryptedContentInfo *ec, const EVP_CIPHER *cipher, const unsigned char *key, size_t keylen, const CMS_CTX *cms_ctx) { ec->cipher = cipher; if (key) { if ((ec->key = OPENSSL_malloc(keylen)) == NULL) return 0; memcpy(ec->key, key, keylen); } ec->keylen = keylen; if (cipher != NULL) ec->contentType = OBJ_nid2obj(NID_pkcs7_data); return 1; } int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph, const unsigned char *key, size_t keylen) { CMS_EncryptedContentInfo *ec; if (!key || !keylen) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_KEY); return 0; } if (ciph) { cms->d.encryptedData = M_ASN1_new_of(CMS_EncryptedData); if (!cms->d.encryptedData) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); return 0; } cms->contentType = OBJ_nid2obj(NID_pkcs7_encrypted); cms->d.encryptedData->version = 0; } else if (OBJ_obj2nid(cms->contentType) != NID_pkcs7_encrypted) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_ENCRYPTED_DATA); return 0; } ec = cms->d.encryptedData->encryptedContentInfo; return ossl_cms_EncryptedContent_init(ec, ciph, key, keylen, ossl_cms_get0_cmsctx(cms)); } BIO *ossl_cms_EncryptedData_init_bio(const CMS_ContentInfo *cms) { CMS_EncryptedData *enc = cms->d.encryptedData; if (enc->encryptedContentInfo->cipher && enc->unprotectedAttrs) enc->version = 2; return ossl_cms_EncryptedContent_init_bio(enc->encryptedContentInfo, ossl_cms_get0_cmsctx(cms)); }
7,953
30.192157
83
c
openssl
openssl-master/crypto/cms/cms_err.c
/* * Generated by util/mkerr.pl DO NOT EDIT * Copyright 1995-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/err.h> #include <openssl/cmserr.h> #include "crypto/cmserr.h" #ifndef OPENSSL_NO_CMS # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA CMS_str_reasons[] = { {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ADD_SIGNER_ERROR), "add signer error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ATTRIBUTE_ERROR), "attribute error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CERTIFICATE_ALREADY_PRESENT), "certificate already present"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CERTIFICATE_HAS_NO_KEYID), "certificate has no keyid"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CERTIFICATE_VERIFY_ERROR), "certificate verify error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CIPHER_AEAD_SET_TAG_ERROR), "cipher aead set tag error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CIPHER_GET_TAG), "cipher get tag"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CIPHER_INITIALISATION_ERROR), "cipher initialisation error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR), "cipher parameter initialisation error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CMS_DATAFINAL_ERROR), "cms datafinal error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CMS_LIB), "cms lib"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENTIDENTIFIER_MISMATCH), "contentidentifier mismatch"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_NOT_FOUND), "content not found"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_MISMATCH), "content type mismatch"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA), "content type not compressed data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA), "content type not enveloped data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA), "content type not signed data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CONTENT_VERIFY_ERROR), "content verify error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CTRL_ERROR), "ctrl error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_CTRL_FAILURE), "ctrl failure"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_DECODE_ERROR), "decode error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_DECRYPT_ERROR), "decrypt error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_GETTING_PUBLIC_KEY), "error getting public key"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE), "error reading messagedigest attribute"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_SETTING_KEY), "error setting key"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ERROR_SETTING_RECIPIENTINFO), "error setting recipientinfo"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_ESS_SIGNING_CERTID_MISMATCH_ERROR), "ess signing certid mismatch error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_ENCRYPTED_KEY_LENGTH), "invalid encrypted key length"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER), "invalid key encryption parameter"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_KEY_LENGTH), "invalid key length"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_LABEL), "invalid label"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_INVALID_OAEP_PARAMETERS), "invalid oaep parameters"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_KDF_PARAMETER_ERROR), "kdf parameter error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MD_BIO_INIT_ERROR), "md bio init error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH), "messagedigest attribute wrong length"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MESSAGEDIGEST_WRONG_LENGTH), "messagedigest wrong length"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MSGSIGDIGEST_ERROR), "msgsigdigest error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE), "msgsigdigest verification failure"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_MSGSIGDIGEST_WRONG_LENGTH), "msgsigdigest wrong length"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NEED_ONE_SIGNER), "need one signer"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_A_SIGNED_RECEIPT), "not a signed receipt"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_ENCRYPTED_DATA), "not encrypted data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_KEK), "not kek"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_KEY_AGREEMENT), "not key agreement"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_KEY_TRANSPORT), "not key transport"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_PWRI), "not pwri"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE), "not supported for this key type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_CIPHER), "no cipher"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_CONTENT), "no content"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_CONTENT_TYPE), "no content type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_DEFAULT_DIGEST), "no default digest"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_DIGEST_SET), "no digest set"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_KEY), "no key"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_KEY_OR_CERT), "no key or cert"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MATCHING_DIGEST), "no matching digest"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MATCHING_RECIPIENT), "no matching recipient"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MATCHING_SIGNATURE), "no matching signature"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_MSGSIGDIGEST), "no msgsigdigest"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_PASSWORD), "no password"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_PRIVATE_KEY), "no private key"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_PUBLIC_KEY), "no public key"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_RECEIPT_REQUEST), "no receipt request"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_NO_SIGNERS), "no signers"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_OPERATION_UNSUPPORTED), "operation unsupported"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_PEER_KEY_ERROR), "peer key error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE), "private key does not match certificate"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_RECEIPT_DECODE_ERROR), "receipt decode error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_RECIPIENT_ERROR), "recipient error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SHARED_INFO_ERROR), "shared info error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SIGNER_CERTIFICATE_NOT_FOUND), "signer certificate not found"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SIGNFINAL_ERROR), "signfinal error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_SMIME_TEXT_ERROR), "smime text error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_STORE_INIT_ERROR), "store init error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_COMPRESSED_DATA), "type not compressed data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_DATA), "type not data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_DIGESTED_DATA), "type not digested data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_ENCRYPTED_DATA), "type not encrypted data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_TYPE_NOT_ENVELOPED_DATA), "type not enveloped data"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNABLE_TO_FINALIZE_CONTEXT), "unable to finalize context"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNKNOWN_CIPHER), "unknown cipher"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNKNOWN_DIGEST_ALGORITHM), "unknown digest algorithm"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNKNOWN_ID), "unknown id"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM), "unsupported compression algorithm"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_CONTENT_ENCRYPTION_ALGORITHM), "unsupported content encryption algorithm"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_CONTENT_TYPE), "unsupported content type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_ENCRYPTION_TYPE), "unsupported encryption type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_KEK_ALGORITHM), "unsupported kek algorithm"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM), "unsupported key encryption algorithm"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_LABEL_SOURCE), "unsupported label source"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE), "unsupported recipientinfo type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_RECIPIENT_TYPE), "unsupported recipient type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNSUPPORTED_TYPE), "unsupported type"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNWRAP_ERROR), "unwrap error"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_UNWRAP_FAILURE), "unwrap failure"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_VERIFICATION_FAILURE), "verification failure"}, {ERR_PACK(ERR_LIB_CMS, 0, CMS_R_WRAP_ERROR), "wrap error"}, {0, NULL} }; # endif int ossl_err_load_CMS_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(CMS_str_reasons[0].error) == NULL) ERR_load_strings_const(CMS_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
9,163
49.629834
79
c
openssl
openssl-master/crypto/cms/cms_ess.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 "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/pem.h> #include <openssl/rand.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include <openssl/cms.h> #include <openssl/ess.h> #include "crypto/ess.h" #include "crypto/x509.h" #include "cms_local.h" IMPLEMENT_ASN1_FUNCTIONS(CMS_ReceiptRequest) /* ESS services */ int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr) { ASN1_STRING *str; CMS_ReceiptRequest *rr; ASN1_OBJECT *obj = OBJ_nid2obj(NID_id_smime_aa_receiptRequest); if (prr != NULL) *prr = NULL; str = CMS_signed_get0_data_by_OBJ(si, obj, -3, V_ASN1_SEQUENCE); if (str == NULL) return 0; rr = ASN1_item_unpack(str, ASN1_ITEM_rptr(CMS_ReceiptRequest)); if (rr == NULL) return -1; if (prr != NULL) *prr = rr; else CMS_ReceiptRequest_free(rr); return 1; } /* * Returns 0 if attribute is not found, 1 if found, * or -1 on attribute parsing failure. */ static int ossl_cms_signerinfo_get_signing_cert(const CMS_SignerInfo *si, ESS_SIGNING_CERT **psc) { ASN1_STRING *str; ESS_SIGNING_CERT *sc; ASN1_OBJECT *obj = OBJ_nid2obj(NID_id_smime_aa_signingCertificate); if (psc != NULL) *psc = NULL; str = CMS_signed_get0_data_by_OBJ(si, obj, -3, V_ASN1_SEQUENCE); if (str == NULL) return 0; sc = ASN1_item_unpack(str, ASN1_ITEM_rptr(ESS_SIGNING_CERT)); if (sc == NULL) return -1; if (psc != NULL) *psc = sc; else ESS_SIGNING_CERT_free(sc); return 1; } /* * Returns 0 if attribute is not found, 1 if found, * or -1 on attribute parsing failure. */ static int ossl_cms_signerinfo_get_signing_cert_v2(const CMS_SignerInfo *si, ESS_SIGNING_CERT_V2 **psc) { ASN1_STRING *str; ESS_SIGNING_CERT_V2 *sc; ASN1_OBJECT *obj = OBJ_nid2obj(NID_id_smime_aa_signingCertificateV2); if (psc != NULL) *psc = NULL; str = CMS_signed_get0_data_by_OBJ(si, obj, -3, V_ASN1_SEQUENCE); if (str == NULL) return 0; sc = ASN1_item_unpack(str, ASN1_ITEM_rptr(ESS_SIGNING_CERT_V2)); if (sc == NULL) return -1; if (psc != NULL) *psc = sc; else ESS_SIGNING_CERT_V2_free(sc); return 1; } int ossl_cms_check_signing_certs(const CMS_SignerInfo *si, const STACK_OF(X509) *chain) { ESS_SIGNING_CERT *ss = NULL; ESS_SIGNING_CERT_V2 *ssv2 = NULL; int ret = ossl_cms_signerinfo_get_signing_cert(si, &ss) >= 0 && ossl_cms_signerinfo_get_signing_cert_v2(si, &ssv2) >= 0 && OSSL_ESS_check_signing_certs(ss, ssv2, chain, 1) > 0; ESS_SIGNING_CERT_free(ss); ESS_SIGNING_CERT_V2_free(ssv2); return ret; } CMS_ReceiptRequest *CMS_ReceiptRequest_create0_ex( unsigned char *id, int idlen, int allorfirst, STACK_OF(GENERAL_NAMES) *receiptList, STACK_OF(GENERAL_NAMES) *receiptsTo, OSSL_LIB_CTX *libctx) { CMS_ReceiptRequest *rr; rr = CMS_ReceiptRequest_new(); if (rr == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); goto err; } if (id) ASN1_STRING_set0(rr->signedContentIdentifier, id, idlen); else { if (!ASN1_STRING_set(rr->signedContentIdentifier, NULL, 32)) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } if (RAND_bytes_ex(libctx, rr->signedContentIdentifier->data, 32, 0) <= 0) goto err; } sk_GENERAL_NAMES_pop_free(rr->receiptsTo, GENERAL_NAMES_free); rr->receiptsTo = receiptsTo; if (receiptList != NULL) { rr->receiptsFrom->type = 1; rr->receiptsFrom->d.receiptList = receiptList; } else { rr->receiptsFrom->type = 0; rr->receiptsFrom->d.allOrFirstTier = allorfirst; } return rr; err: CMS_ReceiptRequest_free(rr); return NULL; } CMS_ReceiptRequest *CMS_ReceiptRequest_create0( unsigned char *id, int idlen, int allorfirst, STACK_OF(GENERAL_NAMES) *receiptList, STACK_OF(GENERAL_NAMES) *receiptsTo) { return CMS_ReceiptRequest_create0_ex(id, idlen, allorfirst, receiptList, receiptsTo, NULL); } int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr) { unsigned char *rrder = NULL; int rrderlen, r = 0; rrderlen = i2d_CMS_ReceiptRequest(rr, &rrder); if (rrderlen < 0) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); goto err; } if (!CMS_signed_add1_attr_by_NID(si, NID_id_smime_aa_receiptRequest, V_ASN1_SEQUENCE, rrder, rrderlen)) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); goto err; } r = 1; err: OPENSSL_free(rrder); return r; } void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr, ASN1_STRING **pcid, int *pallorfirst, STACK_OF(GENERAL_NAMES) **plist, STACK_OF(GENERAL_NAMES) **prto) { if (pcid != NULL) *pcid = rr->signedContentIdentifier; if (rr->receiptsFrom->type == 0) { if (pallorfirst != NULL) *pallorfirst = (int)rr->receiptsFrom->d.allOrFirstTier; if (plist != NULL) *plist = NULL; } else { if (pallorfirst != NULL) *pallorfirst = -1; if (plist != NULL) *plist = rr->receiptsFrom->d.receiptList; } if (prto != NULL) *prto = rr->receiptsTo; } /* Digest a SignerInfo structure for msgSigDigest attribute processing */ static int cms_msgSigDigest(CMS_SignerInfo *si, unsigned char *dig, unsigned int *diglen) { const EVP_MD *md = EVP_get_digestbyobj(si->digestAlgorithm->algorithm); if (md == NULL) return 0; if (!ossl_asn1_item_digest_ex(ASN1_ITEM_rptr(CMS_Attributes_Verify), md, si->signedAttrs, dig, diglen, ossl_cms_ctx_get0_libctx(si->cms_ctx), ossl_cms_ctx_get0_propq(si->cms_ctx))) return 0; return 1; } /* Add a msgSigDigest attribute to a SignerInfo */ int ossl_cms_msgSigDigest_add1(CMS_SignerInfo *dest, CMS_SignerInfo *src) { unsigned char dig[EVP_MAX_MD_SIZE]; unsigned int diglen; if (!cms_msgSigDigest(src, dig, &diglen)) { ERR_raise(ERR_LIB_CMS, CMS_R_MSGSIGDIGEST_ERROR); return 0; } if (!CMS_signed_add1_attr_by_NID(dest, NID_id_smime_aa_msgSigDigest, V_ASN1_OCTET_STRING, dig, diglen)) { ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); return 0; } return 1; } /* Verify signed receipt after it has already passed normal CMS verify */ int ossl_cms_Receipt_verify(CMS_ContentInfo *cms, CMS_ContentInfo *req_cms) { int r = 0, i; CMS_ReceiptRequest *rr = NULL; CMS_Receipt *rct = NULL; STACK_OF(CMS_SignerInfo) *sis, *osis; CMS_SignerInfo *si, *osi = NULL; ASN1_OCTET_STRING *msig, **pcont; ASN1_OBJECT *octype; unsigned char dig[EVP_MAX_MD_SIZE]; unsigned int diglen; /* Get SignerInfos, also checks SignedData content type */ osis = CMS_get0_SignerInfos(req_cms); sis = CMS_get0_SignerInfos(cms); if (!osis || !sis) goto err; if (sk_CMS_SignerInfo_num(sis) != 1) { ERR_raise(ERR_LIB_CMS, CMS_R_NEED_ONE_SIGNER); goto err; } /* Check receipt content type */ if (OBJ_obj2nid(CMS_get0_eContentType(cms)) != NID_id_smime_ct_receipt) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_A_SIGNED_RECEIPT); goto err; } /* Extract and decode receipt content */ pcont = CMS_get0_content(cms); if (pcont == NULL || *pcont == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_CONTENT); goto err; } rct = ASN1_item_unpack(*pcont, ASN1_ITEM_rptr(CMS_Receipt)); if (!rct) { ERR_raise(ERR_LIB_CMS, CMS_R_RECEIPT_DECODE_ERROR); goto err; } /* Locate original request */ for (i = 0; i < sk_CMS_SignerInfo_num(osis); i++) { osi = sk_CMS_SignerInfo_value(osis, i); if (!ASN1_STRING_cmp(osi->signature, rct->originatorSignatureValue)) break; } if (i == sk_CMS_SignerInfo_num(osis)) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_SIGNATURE); goto err; } si = sk_CMS_SignerInfo_value(sis, 0); /* Get msgSigDigest value and compare */ msig = CMS_signed_get0_data_by_OBJ(si, OBJ_nid2obj (NID_id_smime_aa_msgSigDigest), -3, V_ASN1_OCTET_STRING); if (!msig) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_MSGSIGDIGEST); goto err; } if (!cms_msgSigDigest(osi, dig, &diglen)) { ERR_raise(ERR_LIB_CMS, CMS_R_MSGSIGDIGEST_ERROR); goto err; } if (diglen != (unsigned int)msig->length) { ERR_raise(ERR_LIB_CMS, CMS_R_MSGSIGDIGEST_WRONG_LENGTH); goto err; } if (memcmp(dig, msig->data, diglen)) { ERR_raise(ERR_LIB_CMS, CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE); goto err; } /* Compare content types */ octype = CMS_signed_get0_data_by_OBJ(osi, OBJ_nid2obj(NID_pkcs9_contentType), -3, V_ASN1_OBJECT); if (!octype) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_CONTENT_TYPE); goto err; } /* Compare details in receipt request */ if (OBJ_cmp(octype, rct->contentType)) { ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_TYPE_MISMATCH); goto err; } /* Get original receipt request details */ if (CMS_get1_ReceiptRequest(osi, &rr) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_RECEIPT_REQUEST); goto err; } if (ASN1_STRING_cmp(rr->signedContentIdentifier, rct->signedContentIdentifier)) { ERR_raise(ERR_LIB_CMS, CMS_R_CONTENTIDENTIFIER_MISMATCH); goto err; } r = 1; err: CMS_ReceiptRequest_free(rr); M_ASN1_free_of(rct, CMS_Receipt); return r; } /* * Encode a Receipt into an OCTET STRING read for including into content of a * SignedData ContentInfo. */ ASN1_OCTET_STRING *ossl_cms_encode_Receipt(CMS_SignerInfo *si) { CMS_Receipt rct; CMS_ReceiptRequest *rr = NULL; ASN1_OBJECT *ctype; ASN1_OCTET_STRING *os = NULL; /* Get original receipt request */ /* Get original receipt request details */ if (CMS_get1_ReceiptRequest(si, &rr) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_RECEIPT_REQUEST); goto err; } /* Get original content type */ ctype = CMS_signed_get0_data_by_OBJ(si, OBJ_nid2obj(NID_pkcs9_contentType), -3, V_ASN1_OBJECT); if (!ctype) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_CONTENT_TYPE); goto err; } rct.version = 1; rct.contentType = ctype; rct.signedContentIdentifier = rr->signedContentIdentifier; rct.originatorSignatureValue = si->signature; os = ASN1_item_pack(&rct, ASN1_ITEM_rptr(CMS_Receipt), NULL); err: CMS_ReceiptRequest_free(rr); return os; }
11,821
27.147619
78
c
openssl
openssl-master/crypto/cms/cms_io.c
/* * Copyright 2008-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/asn1t.h> #include <openssl/x509.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/cms.h> #include "cms_local.h" /* unfortunately cannot constify BIO_new_NDEF() due to this and PKCS7_stream() */ int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms) { ASN1_OCTET_STRING **pos; pos = CMS_get0_content(cms); if (pos == NULL) return 0; if (*pos == NULL) *pos = ASN1_OCTET_STRING_new(); if (*pos != NULL) { (*pos)->flags |= ASN1_STRING_FLAG_NDEF; (*pos)->flags &= ~ASN1_STRING_FLAG_CONT; *boundary = &(*pos)->data; return 1; } ERR_raise(ERR_LIB_CMS, ERR_R_CMS_LIB); return 0; } CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms) { CMS_ContentInfo *ci; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms == NULL ? NULL : *cms); ci = ASN1_item_d2i_bio_ex(ASN1_ITEM_rptr(CMS_ContentInfo), bp, cms, ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx)); if (ci != NULL) { ERR_set_mark(); ossl_cms_resolve_libctx(ci); ERR_pop_to_mark(); } return ci; } int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms) { return ASN1_item_i2d_bio(ASN1_ITEM_rptr(CMS_ContentInfo), bp, cms); } IMPLEMENT_PEM_rw(CMS, CMS_ContentInfo, PEM_STRING_CMS, CMS_ContentInfo) BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms) { return BIO_new_NDEF(out, (ASN1_VALUE *)cms, ASN1_ITEM_rptr(CMS_ContentInfo)); } /* CMS wrappers round generalised stream and MIME routines */ int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags) { return i2d_ASN1_bio_stream(out, (ASN1_VALUE *)cms, in, flags, ASN1_ITEM_rptr(CMS_ContentInfo)); } int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags) { return PEM_write_bio_ASN1_stream(out, (ASN1_VALUE *)cms, in, flags, "CMS", ASN1_ITEM_rptr(CMS_ContentInfo)); } int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags) { STACK_OF(X509_ALGOR) *mdalgs; int ctype_nid = OBJ_obj2nid(cms->contentType); int econt_nid = OBJ_obj2nid(CMS_get0_eContentType(cms)); const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms); if (ctype_nid == NID_pkcs7_signed) mdalgs = cms->d.signedData->digestAlgorithms; else mdalgs = NULL; return SMIME_write_ASN1_ex(bio, (ASN1_VALUE *)cms, data, flags, ctype_nid, econt_nid, mdalgs, ASN1_ITEM_rptr(CMS_ContentInfo), ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx)); } CMS_ContentInfo *SMIME_read_CMS_ex(BIO *bio, int flags, BIO **bcont, CMS_ContentInfo **cms) { CMS_ContentInfo *ci; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(cms == NULL ? NULL : *cms); ci = (CMS_ContentInfo *)SMIME_read_ASN1_ex(bio, flags, bcont, ASN1_ITEM_rptr(CMS_ContentInfo), (ASN1_VALUE **)cms, ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx)); if (ci != NULL) { ERR_set_mark(); ossl_cms_resolve_libctx(ci); ERR_pop_to_mark(); } return ci; } CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont) { return SMIME_read_CMS_ex(bio, 0, bcont, NULL); }
3,991
31.455285
81
c
openssl
openssl-master/crypto/cms/cms_kari.c
/* * Copyright 2013-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * Low level key APIs (DH etc) are deprecated for public use, but still ok for * internal use. */ #include "internal/deprecated.h" #include "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include <openssl/cms.h> #include <openssl/aes.h> #include "cms_local.h" #include "crypto/asn1.h" /* Key Agreement Recipient Info (KARI) routines */ int CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo *ri, X509_ALGOR **palg, ASN1_OCTET_STRING **pukm) { if (ri->type != CMS_RECIPINFO_AGREE) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT); return 0; } if (palg) *palg = ri->d.kari->keyEncryptionAlgorithm; if (pukm) *pukm = ri->d.kari->ukm; return 1; } /* Retrieve recipient encrypted keys from a kari */ STACK_OF(CMS_RecipientEncryptedKey) *CMS_RecipientInfo_kari_get0_reks(CMS_RecipientInfo *ri) { if (ri->type != CMS_RECIPINFO_AGREE) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT); return NULL; } return ri->d.kari->recipientEncryptedKeys; } int CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo *ri, X509_ALGOR **pubalg, ASN1_BIT_STRING **pubkey, ASN1_OCTET_STRING **keyid, X509_NAME **issuer, ASN1_INTEGER **sno) { CMS_OriginatorIdentifierOrKey *oik; if (ri->type != CMS_RECIPINFO_AGREE) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT); return 0; } oik = ri->d.kari->originator; if (issuer) *issuer = NULL; if (sno) *sno = NULL; if (keyid) *keyid = NULL; if (pubalg) *pubalg = NULL; if (pubkey) *pubkey = NULL; if (oik->type == CMS_OIK_ISSUER_SERIAL) { if (issuer) *issuer = oik->d.issuerAndSerialNumber->issuer; if (sno) *sno = oik->d.issuerAndSerialNumber->serialNumber; } else if (oik->type == CMS_OIK_KEYIDENTIFIER) { if (keyid) *keyid = oik->d.subjectKeyIdentifier; } else if (oik->type == CMS_OIK_PUBKEY) { if (pubalg) *pubalg = oik->d.originatorKey->algorithm; if (pubkey) *pubkey = oik->d.originatorKey->publicKey; } else return 0; return 1; } int CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo *ri, X509 *cert) { CMS_OriginatorIdentifierOrKey *oik; if (ri->type != CMS_RECIPINFO_AGREE) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT); return -2; } oik = ri->d.kari->originator; if (oik->type == CMS_OIK_ISSUER_SERIAL) return ossl_cms_ias_cert_cmp(oik->d.issuerAndSerialNumber, cert); else if (oik->type == CMS_OIK_KEYIDENTIFIER) return ossl_cms_keyid_cert_cmp(oik->d.subjectKeyIdentifier, cert); return -1; } int CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey *rek, ASN1_OCTET_STRING **keyid, ASN1_GENERALIZEDTIME **tm, CMS_OtherKeyAttribute **other, X509_NAME **issuer, ASN1_INTEGER **sno) { CMS_KeyAgreeRecipientIdentifier *rid = rek->rid; if (rid->type == CMS_REK_ISSUER_SERIAL) { if (issuer) *issuer = rid->d.issuerAndSerialNumber->issuer; if (sno) *sno = rid->d.issuerAndSerialNumber->serialNumber; if (keyid) *keyid = NULL; if (tm) *tm = NULL; if (other) *other = NULL; } else if (rid->type == CMS_REK_KEYIDENTIFIER) { if (keyid) *keyid = rid->d.rKeyId->subjectKeyIdentifier; if (tm) *tm = rid->d.rKeyId->date; if (other) *other = rid->d.rKeyId->other; if (issuer) *issuer = NULL; if (sno) *sno = NULL; } else return 0; return 1; } int CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey *rek, X509 *cert) { CMS_KeyAgreeRecipientIdentifier *rid = rek->rid; if (rid->type == CMS_REK_ISSUER_SERIAL) return ossl_cms_ias_cert_cmp(rid->d.issuerAndSerialNumber, cert); else if (rid->type == CMS_REK_KEYIDENTIFIER) return ossl_cms_keyid_cert_cmp(rid->d.rKeyId->subjectKeyIdentifier, cert); else return -1; } int CMS_RecipientInfo_kari_set0_pkey_and_peer(CMS_RecipientInfo *ri, EVP_PKEY *pk, X509 *peer) { EVP_PKEY_CTX *pctx; CMS_KeyAgreeRecipientInfo *kari = ri->d.kari; EVP_PKEY_CTX_free(kari->pctx); kari->pctx = NULL; if (pk == NULL) return 1; pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(kari->cms_ctx), pk, ossl_cms_ctx_get0_propq(kari->cms_ctx)); if (pctx == NULL || EVP_PKEY_derive_init(pctx) <= 0) goto err; if (peer != NULL) { EVP_PKEY *pub_pkey = X509_get0_pubkey(peer); if (EVP_PKEY_derive_set_peer(pctx, pub_pkey) <= 0) goto err; } kari->pctx = pctx; return 1; err: EVP_PKEY_CTX_free(pctx); return 0; } int CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pk) { return CMS_RecipientInfo_kari_set0_pkey_and_peer(ri, pk, NULL); } EVP_CIPHER_CTX *CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo *ri) { if (ri->type == CMS_RECIPINFO_AGREE) return ri->d.kari->ctx; return NULL; } /* * Derive KEK and decrypt/encrypt with it to produce either the original CEK * or the encrypted CEK. */ static int cms_kek_cipher(unsigned char **pout, size_t *poutlen, const unsigned char *in, size_t inlen, CMS_KeyAgreeRecipientInfo *kari, int enc) { /* Key encryption key */ unsigned char kek[EVP_MAX_KEY_LENGTH]; size_t keklen; int rv = 0; unsigned char *out = NULL; int outlen; keklen = EVP_CIPHER_CTX_get_key_length(kari->ctx); if (keklen > EVP_MAX_KEY_LENGTH) return 0; /* Derive KEK */ if (EVP_PKEY_derive(kari->pctx, kek, &keklen) <= 0) goto err; /* Set KEK in context */ if (!EVP_CipherInit_ex(kari->ctx, NULL, NULL, kek, NULL, enc)) goto err; /* obtain output length of ciphered key */ if (!EVP_CipherUpdate(kari->ctx, NULL, &outlen, in, inlen)) goto err; out = OPENSSL_malloc(outlen); if (out == NULL) goto err; if (!EVP_CipherUpdate(kari->ctx, out, &outlen, in, inlen)) goto err; *pout = out; *poutlen = (size_t)outlen; rv = 1; err: OPENSSL_cleanse(kek, keklen); if (!rv) OPENSSL_free(out); EVP_CIPHER_CTX_reset(kari->ctx); /* FIXME: WHY IS kari->pctx freed here? /RL */ EVP_PKEY_CTX_free(kari->pctx); kari->pctx = NULL; return rv; } int CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri, CMS_RecipientEncryptedKey *rek) { int rv = 0; unsigned char *enckey = NULL, *cek = NULL; size_t enckeylen; size_t ceklen; CMS_EncryptedContentInfo *ec; enckeylen = rek->encryptedKey->length; enckey = rek->encryptedKey->data; /* Setup all parameters to derive KEK */ if (!ossl_cms_env_asn1_ctrl(ri, 1)) goto err; /* Attempt to decrypt CEK */ if (!cms_kek_cipher(&cek, &ceklen, enckey, enckeylen, ri->d.kari, 0)) goto err; ec = ossl_cms_get0_env_enc_content(cms); OPENSSL_clear_free(ec->key, ec->keylen); ec->key = cek; ec->keylen = ceklen; cek = NULL; rv = 1; err: OPENSSL_free(cek); return rv; } /* Create ephemeral key and initialise context based on it */ static int cms_kari_create_ephemeral_key(CMS_KeyAgreeRecipientInfo *kari, EVP_PKEY *pk) { EVP_PKEY_CTX *pctx = NULL; EVP_PKEY *ekey = NULL; int rv = 0; const CMS_CTX *ctx = kari->cms_ctx; OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx); const char *propq = ossl_cms_ctx_get0_propq(ctx); pctx = EVP_PKEY_CTX_new_from_pkey(libctx, pk, propq); if (pctx == NULL) goto err; if (EVP_PKEY_keygen_init(pctx) <= 0) goto err; if (EVP_PKEY_keygen(pctx, &ekey) <= 0) goto err; EVP_PKEY_CTX_free(pctx); pctx = EVP_PKEY_CTX_new_from_pkey(libctx, ekey, propq); if (pctx == NULL) goto err; if (EVP_PKEY_derive_init(pctx) <= 0) goto err; kari->pctx = pctx; rv = 1; err: if (!rv) EVP_PKEY_CTX_free(pctx); EVP_PKEY_free(ekey); return rv; } /* Set originator private key and initialise context based on it */ static int cms_kari_set_originator_private_key(CMS_KeyAgreeRecipientInfo *kari, EVP_PKEY *originatorPrivKey ) { EVP_PKEY_CTX *pctx = NULL; int rv = 0; const CMS_CTX *ctx = kari->cms_ctx; pctx = EVP_PKEY_CTX_new_from_pkey(ossl_cms_ctx_get0_libctx(ctx), originatorPrivKey, ossl_cms_ctx_get0_propq(ctx)); if (pctx == NULL) goto err; if (EVP_PKEY_derive_init(pctx) <= 0) goto err; kari->pctx = pctx; rv = 1; err: if (rv == 0) EVP_PKEY_CTX_free(pctx); return rv; } /* Initialise a kari based on passed certificate and key */ int ossl_cms_RecipientInfo_kari_init(CMS_RecipientInfo *ri, X509 *recip, EVP_PKEY *recipPubKey, X509 *originator, EVP_PKEY *originatorPrivKey, unsigned int flags, const CMS_CTX *ctx) { CMS_KeyAgreeRecipientInfo *kari; CMS_RecipientEncryptedKey *rek = NULL; ri->d.kari = M_ASN1_new_of(CMS_KeyAgreeRecipientInfo); if (ri->d.kari == NULL) return 0; ri->type = CMS_RECIPINFO_AGREE; kari = ri->d.kari; kari->version = 3; kari->cms_ctx = ctx; rek = M_ASN1_new_of(CMS_RecipientEncryptedKey); if (rek == NULL) return 0; if (!sk_CMS_RecipientEncryptedKey_push(kari->recipientEncryptedKeys, rek)) { M_ASN1_free_of(rek, CMS_RecipientEncryptedKey); return 0; } if (flags & CMS_USE_KEYID) { rek->rid->type = CMS_REK_KEYIDENTIFIER; rek->rid->d.rKeyId = M_ASN1_new_of(CMS_RecipientKeyIdentifier); if (rek->rid->d.rKeyId == NULL) return 0; if (!ossl_cms_set1_keyid(&rek->rid->d.rKeyId->subjectKeyIdentifier, recip)) return 0; } else { rek->rid->type = CMS_REK_ISSUER_SERIAL; if (!ossl_cms_set1_ias(&rek->rid->d.issuerAndSerialNumber, recip)) return 0; } if (originatorPrivKey == NULL && originator == NULL) { /* Create ephemeral key */ if (!cms_kari_create_ephemeral_key(kari, recipPubKey)) return 0; } else { /* Use originator key */ CMS_OriginatorIdentifierOrKey *oik = ri->d.kari->originator; if (originatorPrivKey == NULL || originator == NULL) return 0; if (flags & CMS_USE_ORIGINATOR_KEYID) { oik->type = CMS_OIK_KEYIDENTIFIER; oik->d.subjectKeyIdentifier = ASN1_OCTET_STRING_new(); if (oik->d.subjectKeyIdentifier == NULL) return 0; if (!ossl_cms_set1_keyid(&oik->d.subjectKeyIdentifier, originator)) return 0; } else { oik->type = CMS_REK_ISSUER_SERIAL; if (!ossl_cms_set1_ias(&oik->d.issuerAndSerialNumber, originator)) return 0; } if (!cms_kari_set_originator_private_key(kari, originatorPrivKey)) return 0; } EVP_PKEY_up_ref(recipPubKey); rek->pkey = recipPubKey; return 1; } static int cms_wrap_init(CMS_KeyAgreeRecipientInfo *kari, const EVP_CIPHER *cipher) { const CMS_CTX *cms_ctx = kari->cms_ctx; EVP_CIPHER_CTX *ctx = kari->ctx; const EVP_CIPHER *kekcipher; EVP_CIPHER *fetched_kekcipher; const char *kekcipher_name; int keylen; int ret; /* If a suitable wrap algorithm is already set nothing to do */ kekcipher = EVP_CIPHER_CTX_get0_cipher(ctx); if (kekcipher != NULL) { if (EVP_CIPHER_CTX_get_mode(ctx) != EVP_CIPH_WRAP_MODE) return 0; return 1; } if (cipher == NULL) return 0; keylen = EVP_CIPHER_get_key_length(cipher); if ((EVP_CIPHER_get_flags(cipher) & EVP_CIPH_FLAG_GET_WRAP_CIPHER) != 0) { ret = EVP_CIPHER_meth_get_ctrl(cipher)(NULL, EVP_CTRL_GET_WRAP_CIPHER, 0, &kekcipher); if (ret <= 0) return 0; if (kekcipher != NULL) { if (EVP_CIPHER_get_mode(kekcipher) != EVP_CIPH_WRAP_MODE) return 0; kekcipher_name = EVP_CIPHER_get0_name(kekcipher); goto enc; } } /* * Pick a cipher based on content encryption cipher. If it is DES3 use * DES3 wrap otherwise use AES wrap similar to key size. */ #ifndef OPENSSL_NO_DES if (EVP_CIPHER_get_type(cipher) == NID_des_ede3_cbc) kekcipher_name = SN_id_smime_alg_CMS3DESwrap; else #endif if (keylen <= 16) kekcipher_name = SN_id_aes128_wrap; else if (keylen <= 24) kekcipher_name = SN_id_aes192_wrap; else kekcipher_name = SN_id_aes256_wrap; enc: fetched_kekcipher = EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(cms_ctx), kekcipher_name, ossl_cms_ctx_get0_propq(cms_ctx)); if (fetched_kekcipher == NULL) return 0; ret = EVP_EncryptInit_ex(ctx, fetched_kekcipher, NULL, NULL, NULL); EVP_CIPHER_free(fetched_kekcipher); return ret; } /* Encrypt content key in key agreement recipient info */ int ossl_cms_RecipientInfo_kari_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri) { CMS_KeyAgreeRecipientInfo *kari; CMS_EncryptedContentInfo *ec; CMS_RecipientEncryptedKey *rek; STACK_OF(CMS_RecipientEncryptedKey) *reks; int i; if (ri->type != CMS_RECIPINFO_AGREE) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_KEY_AGREEMENT); return 0; } kari = ri->d.kari; reks = kari->recipientEncryptedKeys; ec = ossl_cms_get0_env_enc_content(cms); /* Initialise wrap algorithm parameters */ if (!cms_wrap_init(kari, ec->cipher)) return 0; /* * If no originator key set up initialise for ephemeral key the public key * ASN1 structure will set the actual public key value. */ if (kari->originator->type == -1) { CMS_OriginatorIdentifierOrKey *oik = kari->originator; oik->type = CMS_OIK_PUBKEY; oik->d.originatorKey = M_ASN1_new_of(CMS_OriginatorPublicKey); if (!oik->d.originatorKey) return 0; } /* Initialise KDF algorithm */ if (!ossl_cms_env_asn1_ctrl(ri, 0)) return 0; /* For each rek, derive KEK, encrypt CEK */ for (i = 0; i < sk_CMS_RecipientEncryptedKey_num(reks); i++) { unsigned char *enckey; size_t enckeylen; rek = sk_CMS_RecipientEncryptedKey_value(reks, i); if (EVP_PKEY_derive_set_peer(kari->pctx, rek->pkey) <= 0) return 0; if (!cms_kek_cipher(&enckey, &enckeylen, ec->key, ec->keylen, kari, 1)) return 0; ASN1_STRING_set0(rek->encryptedKey, enckey, enckeylen); } return 1; }
16,372
30.246183
83
c
openssl
openssl-master/crypto/cms/cms_lib.c
/* * Copyright 2008-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/asn1t.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include <openssl/pem.h> #include <openssl/bio.h> #include <openssl/asn1.h> #include <openssl/cms.h> #include "internal/sizes.h" #include "crypto/x509.h" #include "cms_local.h" static STACK_OF(CMS_CertificateChoices) **cms_get0_certificate_choices(CMS_ContentInfo *cms); IMPLEMENT_ASN1_PRINT_FUNCTION(CMS_ContentInfo) CMS_ContentInfo *d2i_CMS_ContentInfo(CMS_ContentInfo **a, const unsigned char **in, long len) { CMS_ContentInfo *ci; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(a == NULL ? NULL : *a); ci = (CMS_ContentInfo *)ASN1_item_d2i_ex((ASN1_VALUE **)a, in, len, (CMS_ContentInfo_it()), ossl_cms_ctx_get0_libctx(ctx), ossl_cms_ctx_get0_propq(ctx)); if (ci != NULL) { ERR_set_mark(); ossl_cms_resolve_libctx(ci); ERR_pop_to_mark(); } return ci; } int i2d_CMS_ContentInfo(const CMS_ContentInfo *a, unsigned char **out) { return ASN1_item_i2d((const ASN1_VALUE *)a, out, (CMS_ContentInfo_it())); } CMS_ContentInfo *CMS_ContentInfo_new_ex(OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *ci; ci = (CMS_ContentInfo *)ASN1_item_new_ex(ASN1_ITEM_rptr(CMS_ContentInfo), libctx, propq); if (ci != NULL) { ci->ctx.libctx = libctx; ci->ctx.propq = NULL; if (propq != NULL) { ci->ctx.propq = OPENSSL_strdup(propq); if (ci->ctx.propq == NULL) { CMS_ContentInfo_free(ci); ci = NULL; } } } return ci; } CMS_ContentInfo *CMS_ContentInfo_new(void) { return CMS_ContentInfo_new_ex(NULL, NULL); } void CMS_ContentInfo_free(CMS_ContentInfo *cms) { if (cms != NULL) { CMS_EncryptedContentInfo *ec = ossl_cms_get0_env_enc_content(cms); if (ec != NULL) OPENSSL_clear_free(ec->key, ec->keylen); OPENSSL_free(cms->ctx.propq); ASN1_item_free((ASN1_VALUE *)cms, ASN1_ITEM_rptr(CMS_ContentInfo)); } } const CMS_CTX *ossl_cms_get0_cmsctx(const CMS_ContentInfo *cms) { return cms != NULL ? &cms->ctx : NULL; } OSSL_LIB_CTX *ossl_cms_ctx_get0_libctx(const CMS_CTX *ctx) { return ctx != NULL ? ctx->libctx : NULL; } const char *ossl_cms_ctx_get0_propq(const CMS_CTX *ctx) { return ctx != NULL ? ctx->propq : NULL; } void ossl_cms_resolve_libctx(CMS_ContentInfo *ci) { int i; CMS_CertificateChoices *cch; STACK_OF(CMS_CertificateChoices) **pcerts; const CMS_CTX *ctx = ossl_cms_get0_cmsctx(ci); OSSL_LIB_CTX *libctx = ossl_cms_ctx_get0_libctx(ctx); const char *propq = ossl_cms_ctx_get0_propq(ctx); ossl_cms_SignerInfos_set_cmsctx(ci); ossl_cms_RecipientInfos_set_cmsctx(ci); pcerts = cms_get0_certificate_choices(ci); if (pcerts != NULL) { for (i = 0; i < sk_CMS_CertificateChoices_num(*pcerts); i++) { cch = sk_CMS_CertificateChoices_value(*pcerts, i); if (cch->type == CMS_CERTCHOICE_CERT) ossl_x509_set0_libctx(cch->d.certificate, libctx, propq); } } } const ASN1_OBJECT *CMS_get0_type(const CMS_ContentInfo *cms) { return cms->contentType; } CMS_ContentInfo *ossl_cms_Data_create(OSSL_LIB_CTX *libctx, const char *propq) { CMS_ContentInfo *cms = CMS_ContentInfo_new_ex(libctx, propq); if (cms != NULL) { cms->contentType = OBJ_nid2obj(NID_pkcs7_data); /* Never detached */ CMS_set_detached(cms, 0); } return cms; } BIO *ossl_cms_content_bio(CMS_ContentInfo *cms) { ASN1_OCTET_STRING **pos = CMS_get0_content(cms); if (pos == NULL) return NULL; /* If content detached data goes nowhere: create NULL BIO */ if (*pos == NULL) return BIO_new(BIO_s_null()); /* * If content not detached and created return memory BIO */ if (*pos == NULL || ((*pos)->flags == ASN1_STRING_FLAG_CONT)) return BIO_new(BIO_s_mem()); /* Else content was read in: return read only BIO for it */ return BIO_new_mem_buf((*pos)->data, (*pos)->length); } BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont) { BIO *cmsbio, *cont; if (icont) cont = icont; else cont = ossl_cms_content_bio(cms); if (!cont) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_CONTENT); return NULL; } switch (OBJ_obj2nid(cms->contentType)) { case NID_pkcs7_data: return cont; case NID_pkcs7_signed: cmsbio = ossl_cms_SignedData_init_bio(cms); break; case NID_pkcs7_digest: cmsbio = ossl_cms_DigestedData_init_bio(cms); break; #ifndef OPENSSL_NO_ZLIB case NID_id_smime_ct_compressedData: cmsbio = ossl_cms_CompressedData_init_bio(cms); break; #endif case NID_pkcs7_encrypted: cmsbio = ossl_cms_EncryptedData_init_bio(cms); break; case NID_pkcs7_enveloped: cmsbio = ossl_cms_EnvelopedData_init_bio(cms); break; case NID_id_smime_ct_authEnvelopedData: cmsbio = ossl_cms_AuthEnvelopedData_init_bio(cms); break; default: ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_TYPE); goto err; } if (cmsbio) return BIO_push(cmsbio, cont); err: if (!icont) BIO_free(cont); return NULL; } /* unfortunately cannot constify SMIME_write_ASN1() due to this function */ int CMS_dataFinal(CMS_ContentInfo *cms, BIO *cmsbio) { return ossl_cms_DataFinal(cms, cmsbio, NULL, 0); } int ossl_cms_DataFinal(CMS_ContentInfo *cms, BIO *cmsbio, const unsigned char *precomp_md, unsigned int precomp_mdlen) { ASN1_OCTET_STRING **pos = CMS_get0_content(cms); if (pos == NULL) return 0; /* If embedded content find memory BIO and set content */ if (*pos && ((*pos)->flags & ASN1_STRING_FLAG_CONT)) { BIO *mbio; unsigned char *cont; long contlen; mbio = BIO_find_type(cmsbio, BIO_TYPE_MEM); if (!mbio) { ERR_raise(ERR_LIB_CMS, CMS_R_CONTENT_NOT_FOUND); return 0; } contlen = BIO_get_mem_data(mbio, &cont); /* Set bio as read only so its content can't be clobbered */ BIO_set_flags(mbio, BIO_FLAGS_MEM_RDONLY); BIO_set_mem_eof_return(mbio, 0); ASN1_STRING_set0(*pos, cont, contlen); (*pos)->flags &= ~ASN1_STRING_FLAG_CONT; } switch (OBJ_obj2nid(cms->contentType)) { case NID_pkcs7_data: case NID_pkcs7_encrypted: case NID_id_smime_ct_compressedData: /* Nothing to do */ return 1; case NID_pkcs7_enveloped: return ossl_cms_EnvelopedData_final(cms, cmsbio); case NID_id_smime_ct_authEnvelopedData: return ossl_cms_AuthEnvelopedData_final(cms, cmsbio); case NID_pkcs7_signed: return ossl_cms_SignedData_final(cms, cmsbio, precomp_md, precomp_mdlen); case NID_pkcs7_digest: return ossl_cms_DigestedData_do_final(cms, cmsbio, 0); default: ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_TYPE); return 0; } } /* * Return an OCTET STRING pointer to content. This allows it to be accessed * or set later. */ ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms) { switch (OBJ_obj2nid(cms->contentType)) { case NID_pkcs7_data: return &cms->d.data; case NID_pkcs7_signed: return &cms->d.signedData->encapContentInfo->eContent; case NID_pkcs7_enveloped: return &cms->d.envelopedData->encryptedContentInfo->encryptedContent; case NID_pkcs7_digest: return &cms->d.digestedData->encapContentInfo->eContent; case NID_pkcs7_encrypted: return &cms->d.encryptedData->encryptedContentInfo->encryptedContent; case NID_id_smime_ct_authEnvelopedData: return &cms->d.authEnvelopedData->authEncryptedContentInfo ->encryptedContent; case NID_id_smime_ct_authData: return &cms->d.authenticatedData->encapContentInfo->eContent; case NID_id_smime_ct_compressedData: return &cms->d.compressedData->encapContentInfo->eContent; default: if (cms->d.other->type == V_ASN1_OCTET_STRING) return &cms->d.other->value.octet_string; ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_CONTENT_TYPE); return NULL; } } /* * Return an ASN1_OBJECT pointer to content type. This allows it to be * accessed or set later. */ static ASN1_OBJECT **cms_get0_econtent_type(CMS_ContentInfo *cms) { switch (OBJ_obj2nid(cms->contentType)) { case NID_pkcs7_signed: return &cms->d.signedData->encapContentInfo->eContentType; case NID_pkcs7_enveloped: return &cms->d.envelopedData->encryptedContentInfo->contentType; case NID_pkcs7_digest: return &cms->d.digestedData->encapContentInfo->eContentType; case NID_pkcs7_encrypted: return &cms->d.encryptedData->encryptedContentInfo->contentType; case NID_id_smime_ct_authEnvelopedData: return &cms->d.authEnvelopedData->authEncryptedContentInfo ->contentType; case NID_id_smime_ct_authData: return &cms->d.authenticatedData->encapContentInfo->eContentType; case NID_id_smime_ct_compressedData: return &cms->d.compressedData->encapContentInfo->eContentType; default: ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_CONTENT_TYPE); return NULL; } } const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms) { ASN1_OBJECT **petype; petype = cms_get0_econtent_type(cms); if (petype) return *petype; return NULL; } int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid) { ASN1_OBJECT **petype, *etype; petype = cms_get0_econtent_type(cms); if (petype == NULL) return 0; if (oid == NULL) return 1; etype = OBJ_dup(oid); if (etype == NULL) return 0; ASN1_OBJECT_free(*petype); *petype = etype; return 1; } int CMS_is_detached(CMS_ContentInfo *cms) { ASN1_OCTET_STRING **pos; pos = CMS_get0_content(cms); if (pos == NULL) return -1; if (*pos != NULL) return 0; return 1; } int CMS_set_detached(CMS_ContentInfo *cms, int detached) { ASN1_OCTET_STRING **pos; pos = CMS_get0_content(cms); if (pos == NULL) return 0; if (detached) { ASN1_OCTET_STRING_free(*pos); *pos = NULL; return 1; } if (*pos == NULL) *pos = ASN1_OCTET_STRING_new(); if (*pos != NULL) { /* * NB: special flag to show content is created and not read in. */ (*pos)->flags |= ASN1_STRING_FLAG_CONT; return 1; } ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); return 0; } /* Create a digest BIO from an X509_ALGOR structure */ BIO *ossl_cms_DigestAlgorithm_init_bio(X509_ALGOR *digestAlgorithm, const CMS_CTX *ctx) { BIO *mdbio = NULL; const ASN1_OBJECT *digestoid; const EVP_MD *digest = NULL; EVP_MD *fetched_digest = NULL; char alg[OSSL_MAX_NAME_SIZE]; X509_ALGOR_get0(&digestoid, NULL, NULL, digestAlgorithm); OBJ_obj2txt(alg, sizeof(alg), digestoid, 0); (void)ERR_set_mark(); fetched_digest = EVP_MD_fetch(ossl_cms_ctx_get0_libctx(ctx), alg, ossl_cms_ctx_get0_propq(ctx)); if (fetched_digest != NULL) digest = fetched_digest; else digest = EVP_get_digestbyobj(digestoid); if (digest == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_DIGEST_ALGORITHM); goto err; } (void)ERR_pop_to_mark(); mdbio = BIO_new(BIO_f_md()); if (mdbio == NULL || BIO_set_md(mdbio, digest) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_MD_BIO_INIT_ERROR); goto err; } EVP_MD_free(fetched_digest); return mdbio; err: EVP_MD_free(fetched_digest); BIO_free(mdbio); return NULL; } /* Locate a message digest content from a BIO chain based on SignerInfo */ int ossl_cms_DigestAlgorithm_find_ctx(EVP_MD_CTX *mctx, BIO *chain, X509_ALGOR *mdalg) { int nid; const ASN1_OBJECT *mdoid; X509_ALGOR_get0(&mdoid, NULL, NULL, mdalg); nid = OBJ_obj2nid(mdoid); /* Look for digest type to match signature */ for (;;) { EVP_MD_CTX *mtmp; chain = BIO_find_type(chain, BIO_TYPE_MD); if (chain == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_MATCHING_DIGEST); return 0; } BIO_get_md_ctx(chain, &mtmp); if (EVP_MD_CTX_get_type(mtmp) == nid /* * Workaround for broken implementations that use signature * algorithm OID instead of digest. */ || EVP_MD_get_pkey_type(EVP_MD_CTX_get0_md(mtmp)) == nid) return EVP_MD_CTX_copy_ex(mctx, mtmp); chain = BIO_next(chain); } } static STACK_OF(CMS_CertificateChoices) **cms_get0_certificate_choices(CMS_ContentInfo *cms) { switch (OBJ_obj2nid(cms->contentType)) { case NID_pkcs7_signed: return &cms->d.signedData->certificates; case NID_pkcs7_enveloped: if (cms->d.envelopedData->originatorInfo == NULL) return NULL; return &cms->d.envelopedData->originatorInfo->certificates; case NID_id_smime_ct_authEnvelopedData: if (cms->d.authEnvelopedData->originatorInfo == NULL) return NULL; return &cms->d.authEnvelopedData->originatorInfo->certificates; default: ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_CONTENT_TYPE); return NULL; } } CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms) { STACK_OF(CMS_CertificateChoices) **pcerts; CMS_CertificateChoices *cch; pcerts = cms_get0_certificate_choices(cms); if (pcerts == NULL) return NULL; if (*pcerts == NULL) *pcerts = sk_CMS_CertificateChoices_new_null(); if (*pcerts == NULL) return NULL; cch = M_ASN1_new_of(CMS_CertificateChoices); if (!cch) return NULL; if (!sk_CMS_CertificateChoices_push(*pcerts, cch)) { M_ASN1_free_of(cch, CMS_CertificateChoices); return NULL; } return cch; } int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert) { CMS_CertificateChoices *cch; STACK_OF(CMS_CertificateChoices) **pcerts; int i; pcerts = cms_get0_certificate_choices(cms); if (pcerts == NULL) return 0; for (i = 0; i < sk_CMS_CertificateChoices_num(*pcerts); i++) { cch = sk_CMS_CertificateChoices_value(*pcerts, i); if (cch->type == CMS_CERTCHOICE_CERT) { if (X509_cmp(cch->d.certificate, cert) == 0) { X509_free(cert); return 1; /* cert already present */ } } } cch = CMS_add0_CertificateChoices(cms); if (!cch) return 0; cch->type = CMS_CERTCHOICE_CERT; cch->d.certificate = cert; return 1; } int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert) { if (!X509_up_ref(cert)) return 0; if (CMS_add0_cert(cms, cert)) return 1; X509_free(cert); return 0; } static STACK_OF(CMS_RevocationInfoChoice) **cms_get0_revocation_choices(CMS_ContentInfo *cms) { switch (OBJ_obj2nid(cms->contentType)) { case NID_pkcs7_signed: return &cms->d.signedData->crls; case NID_pkcs7_enveloped: if (cms->d.envelopedData->originatorInfo == NULL) return NULL; return &cms->d.envelopedData->originatorInfo->crls; case NID_id_smime_ct_authEnvelopedData: if (cms->d.authEnvelopedData->originatorInfo == NULL) return NULL; return &cms->d.authEnvelopedData->originatorInfo->crls; default: ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_CONTENT_TYPE); return NULL; } } CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms) { STACK_OF(CMS_RevocationInfoChoice) **pcrls; CMS_RevocationInfoChoice *rch; pcrls = cms_get0_revocation_choices(cms); if (pcrls == NULL) return NULL; if (*pcrls == NULL) *pcrls = sk_CMS_RevocationInfoChoice_new_null(); if (*pcrls == NULL) return NULL; rch = M_ASN1_new_of(CMS_RevocationInfoChoice); if (rch == NULL) return NULL; if (!sk_CMS_RevocationInfoChoice_push(*pcrls, rch)) { M_ASN1_free_of(rch, CMS_RevocationInfoChoice); return NULL; } return rch; } int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl) { CMS_RevocationInfoChoice *rch = CMS_add0_RevocationInfoChoice(cms); if (rch == NULL) return 0; rch->type = CMS_REVCHOICE_CRL; rch->d.crl = crl; return 1; } int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl) { if (!X509_CRL_up_ref(crl)) return 0; if (CMS_add0_crl(cms, crl)) return 1; X509_CRL_free(crl); return 0; } STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms) { STACK_OF(X509) *certs = NULL; CMS_CertificateChoices *cch; STACK_OF(CMS_CertificateChoices) **pcerts; int i; pcerts = cms_get0_certificate_choices(cms); if (pcerts == NULL) return NULL; for (i = 0; i < sk_CMS_CertificateChoices_num(*pcerts); i++) { cch = sk_CMS_CertificateChoices_value(*pcerts, i); if (cch->type == 0) { if (!ossl_x509_add_cert_new(&certs, cch->d.certificate, X509_ADD_FLAG_UP_REF)) { OSSL_STACK_OF_X509_free(certs); return NULL; } } } return certs; } STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms) { STACK_OF(X509_CRL) *crls = NULL; STACK_OF(CMS_RevocationInfoChoice) **pcrls; CMS_RevocationInfoChoice *rch; int i; pcrls = cms_get0_revocation_choices(cms); if (pcrls == NULL) return NULL; for (i = 0; i < sk_CMS_RevocationInfoChoice_num(*pcrls); i++) { rch = sk_CMS_RevocationInfoChoice_value(*pcrls, i); if (rch->type == 0) { if (crls == NULL) { if ((crls = sk_X509_CRL_new_null()) == NULL) return NULL; } if (!sk_X509_CRL_push(crls, rch->d.crl) || !X509_CRL_up_ref(rch->d.crl)) { sk_X509_CRL_pop_free(crls, X509_CRL_free); return NULL; } } } return crls; } int ossl_cms_ias_cert_cmp(CMS_IssuerAndSerialNumber *ias, X509 *cert) { int ret; ret = X509_NAME_cmp(ias->issuer, X509_get_issuer_name(cert)); if (ret) return ret; return ASN1_INTEGER_cmp(ias->serialNumber, X509_get0_serialNumber(cert)); } int ossl_cms_keyid_cert_cmp(ASN1_OCTET_STRING *keyid, X509 *cert) { const ASN1_OCTET_STRING *cert_keyid = X509_get0_subject_key_id(cert); if (cert_keyid == NULL) return -1; return ASN1_OCTET_STRING_cmp(keyid, cert_keyid); } int ossl_cms_set1_ias(CMS_IssuerAndSerialNumber **pias, X509 *cert) { CMS_IssuerAndSerialNumber *ias; ias = M_ASN1_new_of(CMS_IssuerAndSerialNumber); if (!ias) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } if (!X509_NAME_set(&ias->issuer, X509_get_issuer_name(cert))) { ERR_raise(ERR_LIB_CMS, ERR_R_X509_LIB); goto err; } if (!ASN1_STRING_copy(ias->serialNumber, X509_get0_serialNumber(cert))) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } M_ASN1_free_of(*pias, CMS_IssuerAndSerialNumber); *pias = ias; return 1; err: M_ASN1_free_of(ias, CMS_IssuerAndSerialNumber); return 0; } int ossl_cms_set1_keyid(ASN1_OCTET_STRING **pkeyid, X509 *cert) { ASN1_OCTET_STRING *keyid = NULL; const ASN1_OCTET_STRING *cert_keyid; cert_keyid = X509_get0_subject_key_id(cert); if (cert_keyid == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_CERTIFICATE_HAS_NO_KEYID); return 0; } keyid = ASN1_STRING_dup(cert_keyid); if (!keyid) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); return 0; } ASN1_OCTET_STRING_free(*pkeyid); *pkeyid = keyid; return 1; }
20,834
26.891566
81
c
openssl
openssl-master/crypto/cms/cms_local.h
/* * Copyright 2008-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifndef OSSL_CRYPTO_CMS_LOCAL_H # define OSSL_CRYPTO_CMS_LOCAL_H # include <openssl/x509.h> /* * Cryptographic message syntax (CMS) structures: taken from RFC3852 */ /* Forward references */ typedef struct CMS_IssuerAndSerialNumber_st CMS_IssuerAndSerialNumber; typedef struct CMS_EncapsulatedContentInfo_st CMS_EncapsulatedContentInfo; typedef struct CMS_SignerIdentifier_st CMS_SignerIdentifier; typedef struct CMS_OtherRevocationInfoFormat_st CMS_OtherRevocationInfoFormat; typedef struct CMS_OriginatorInfo_st CMS_OriginatorInfo; typedef struct CMS_EncryptedContentInfo_st CMS_EncryptedContentInfo; typedef struct CMS_DigestedData_st CMS_DigestedData; typedef struct CMS_EncryptedData_st CMS_EncryptedData; typedef struct CMS_AuthenticatedData_st CMS_AuthenticatedData; typedef struct CMS_AuthEnvelopedData_st CMS_AuthEnvelopedData; typedef struct CMS_CompressedData_st CMS_CompressedData; typedef struct CMS_OtherCertificateFormat_st CMS_OtherCertificateFormat; typedef struct CMS_KeyTransRecipientInfo_st CMS_KeyTransRecipientInfo; typedef struct CMS_OriginatorPublicKey_st CMS_OriginatorPublicKey; typedef struct CMS_OriginatorIdentifierOrKey_st CMS_OriginatorIdentifierOrKey; typedef struct CMS_KeyAgreeRecipientInfo_st CMS_KeyAgreeRecipientInfo; typedef struct CMS_RecipientKeyIdentifier_st CMS_RecipientKeyIdentifier; typedef struct CMS_KeyAgreeRecipientIdentifier_st CMS_KeyAgreeRecipientIdentifier; typedef struct CMS_KEKIdentifier_st CMS_KEKIdentifier; typedef struct CMS_KEKRecipientInfo_st CMS_KEKRecipientInfo; typedef struct CMS_PasswordRecipientInfo_st CMS_PasswordRecipientInfo; typedef struct CMS_OtherRecipientInfo_st CMS_OtherRecipientInfo; typedef struct CMS_ReceiptsFrom_st CMS_ReceiptsFrom; typedef struct CMS_CTX_st CMS_CTX; struct CMS_CTX_st { OSSL_LIB_CTX *libctx; char *propq; }; struct CMS_ContentInfo_st { ASN1_OBJECT *contentType; union { ASN1_OCTET_STRING *data; CMS_SignedData *signedData; CMS_EnvelopedData *envelopedData; CMS_DigestedData *digestedData; CMS_EncryptedData *encryptedData; CMS_AuthEnvelopedData *authEnvelopedData; CMS_AuthenticatedData *authenticatedData; CMS_CompressedData *compressedData; ASN1_TYPE *other; /* Other types ... */ void *otherData; } d; CMS_CTX ctx; }; DEFINE_STACK_OF(CMS_CertificateChoices) struct CMS_SignedData_st { int32_t version; STACK_OF(X509_ALGOR) *digestAlgorithms; CMS_EncapsulatedContentInfo *encapContentInfo; STACK_OF(CMS_CertificateChoices) *certificates; STACK_OF(CMS_RevocationInfoChoice) *crls; STACK_OF(CMS_SignerInfo) *signerInfos; }; struct CMS_EncapsulatedContentInfo_st { ASN1_OBJECT *eContentType; ASN1_OCTET_STRING *eContent; /* Set to 1 if incomplete structure only part set up */ int partial; }; struct CMS_SignerInfo_st { int32_t version; CMS_SignerIdentifier *sid; X509_ALGOR *digestAlgorithm; STACK_OF(X509_ATTRIBUTE) *signedAttrs; X509_ALGOR *signatureAlgorithm; ASN1_OCTET_STRING *signature; STACK_OF(X509_ATTRIBUTE) *unsignedAttrs; /* Signing certificate and key */ X509 *signer; EVP_PKEY *pkey; /* Digest and public key context for alternative parameters */ EVP_MD_CTX *mctx; EVP_PKEY_CTX *pctx; const CMS_CTX *cms_ctx; }; struct CMS_SignerIdentifier_st { int type; union { CMS_IssuerAndSerialNumber *issuerAndSerialNumber; ASN1_OCTET_STRING *subjectKeyIdentifier; } d; }; struct CMS_EnvelopedData_st { int32_t version; CMS_OriginatorInfo *originatorInfo; STACK_OF(CMS_RecipientInfo) *recipientInfos; CMS_EncryptedContentInfo *encryptedContentInfo; STACK_OF(X509_ATTRIBUTE) *unprotectedAttrs; }; struct CMS_OriginatorInfo_st { STACK_OF(CMS_CertificateChoices) *certificates; STACK_OF(CMS_RevocationInfoChoice) *crls; }; struct CMS_EncryptedContentInfo_st { ASN1_OBJECT *contentType; X509_ALGOR *contentEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedContent; /* Content encryption algorithm, key and tag */ const EVP_CIPHER *cipher; unsigned char *key; size_t keylen; unsigned char *tag; size_t taglen; /* Set to 1 if we are debugging decrypt and don't fake keys for MMA */ int debug; /* Set to 1 if we have no cert and need extra safety measures for MMA */ int havenocert; }; struct CMS_RecipientInfo_st { int type; union { CMS_KeyTransRecipientInfo *ktri; CMS_KeyAgreeRecipientInfo *kari; CMS_KEKRecipientInfo *kekri; CMS_PasswordRecipientInfo *pwri; CMS_OtherRecipientInfo *ori; } d; }; typedef CMS_SignerIdentifier CMS_RecipientIdentifier; struct CMS_KeyTransRecipientInfo_st { int32_t version; CMS_RecipientIdentifier *rid; X509_ALGOR *keyEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedKey; /* Recipient Key and cert */ X509 *recip; EVP_PKEY *pkey; /* Public key context for this operation */ EVP_PKEY_CTX *pctx; const CMS_CTX *cms_ctx; }; struct CMS_KeyAgreeRecipientInfo_st { int32_t version; CMS_OriginatorIdentifierOrKey *originator; ASN1_OCTET_STRING *ukm; X509_ALGOR *keyEncryptionAlgorithm; STACK_OF(CMS_RecipientEncryptedKey) *recipientEncryptedKeys; /* Public key context associated with current operation */ EVP_PKEY_CTX *pctx; /* Cipher context for CEK wrapping */ EVP_CIPHER_CTX *ctx; const CMS_CTX *cms_ctx; }; struct CMS_OriginatorIdentifierOrKey_st { int type; union { CMS_IssuerAndSerialNumber *issuerAndSerialNumber; ASN1_OCTET_STRING *subjectKeyIdentifier; CMS_OriginatorPublicKey *originatorKey; } d; }; struct CMS_OriginatorPublicKey_st { X509_ALGOR *algorithm; ASN1_BIT_STRING *publicKey; }; struct CMS_RecipientEncryptedKey_st { CMS_KeyAgreeRecipientIdentifier *rid; ASN1_OCTET_STRING *encryptedKey; /* Public key associated with this recipient */ EVP_PKEY *pkey; }; struct CMS_KeyAgreeRecipientIdentifier_st { int type; union { CMS_IssuerAndSerialNumber *issuerAndSerialNumber; CMS_RecipientKeyIdentifier *rKeyId; } d; }; struct CMS_RecipientKeyIdentifier_st { ASN1_OCTET_STRING *subjectKeyIdentifier; ASN1_GENERALIZEDTIME *date; CMS_OtherKeyAttribute *other; }; struct CMS_KEKRecipientInfo_st { int32_t version; CMS_KEKIdentifier *kekid; X509_ALGOR *keyEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedKey; /* Extra info: symmetric key to use */ unsigned char *key; size_t keylen; const CMS_CTX *cms_ctx; }; struct CMS_KEKIdentifier_st { ASN1_OCTET_STRING *keyIdentifier; ASN1_GENERALIZEDTIME *date; CMS_OtherKeyAttribute *other; }; struct CMS_PasswordRecipientInfo_st { int32_t version; X509_ALGOR *keyDerivationAlgorithm; X509_ALGOR *keyEncryptionAlgorithm; ASN1_OCTET_STRING *encryptedKey; /* Extra info: password to use */ unsigned char *pass; size_t passlen; const CMS_CTX *cms_ctx; }; struct CMS_OtherRecipientInfo_st { ASN1_OBJECT *oriType; ASN1_TYPE *oriValue; }; struct CMS_DigestedData_st { int32_t version; X509_ALGOR *digestAlgorithm; CMS_EncapsulatedContentInfo *encapContentInfo; ASN1_OCTET_STRING *digest; }; struct CMS_EncryptedData_st { int32_t version; CMS_EncryptedContentInfo *encryptedContentInfo; STACK_OF(X509_ATTRIBUTE) *unprotectedAttrs; }; struct CMS_AuthenticatedData_st { int32_t version; CMS_OriginatorInfo *originatorInfo; STACK_OF(CMS_RecipientInfo) *recipientInfos; X509_ALGOR *macAlgorithm; X509_ALGOR *digestAlgorithm; CMS_EncapsulatedContentInfo *encapContentInfo; STACK_OF(X509_ATTRIBUTE) *authAttrs; ASN1_OCTET_STRING *mac; STACK_OF(X509_ATTRIBUTE) *unauthAttrs; }; struct CMS_AuthEnvelopedData_st { int32_t version; CMS_OriginatorInfo *originatorInfo; STACK_OF(CMS_RecipientInfo) *recipientInfos; CMS_EncryptedContentInfo *authEncryptedContentInfo; STACK_OF(X509_ATTRIBUTE) *authAttrs; ASN1_OCTET_STRING *mac; STACK_OF(X509_ATTRIBUTE) *unauthAttrs; }; struct CMS_CompressedData_st { int32_t version; X509_ALGOR *compressionAlgorithm; STACK_OF(CMS_RecipientInfo) *recipientInfos; CMS_EncapsulatedContentInfo *encapContentInfo; }; struct CMS_RevocationInfoChoice_st { int type; union { X509_CRL *crl; CMS_OtherRevocationInfoFormat *other; } d; }; # define CMS_REVCHOICE_CRL 0 # define CMS_REVCHOICE_OTHER 1 struct CMS_OtherRevocationInfoFormat_st { ASN1_OBJECT *otherRevInfoFormat; ASN1_TYPE *otherRevInfo; }; struct CMS_CertificateChoices { int type; union { X509 *certificate; ASN1_STRING *extendedCertificate; /* Obsolete */ ASN1_STRING *v1AttrCert; /* Left encoded for now */ ASN1_STRING *v2AttrCert; /* Left encoded for now */ CMS_OtherCertificateFormat *other; } d; }; # define CMS_CERTCHOICE_CERT 0 # define CMS_CERTCHOICE_EXCERT 1 # define CMS_CERTCHOICE_V1ACERT 2 # define CMS_CERTCHOICE_V2ACERT 3 # define CMS_CERTCHOICE_OTHER 4 struct CMS_OtherCertificateFormat_st { ASN1_OBJECT *otherCertFormat; ASN1_TYPE *otherCert; }; /* * This is also defined in pkcs7.h but we duplicate it to allow the CMS code * to be independent of PKCS#7 */ struct CMS_IssuerAndSerialNumber_st { X509_NAME *issuer; ASN1_INTEGER *serialNumber; }; struct CMS_OtherKeyAttribute_st { ASN1_OBJECT *keyAttrId; ASN1_TYPE *keyAttr; }; /* ESS structures */ struct CMS_ReceiptRequest_st { ASN1_OCTET_STRING *signedContentIdentifier; CMS_ReceiptsFrom *receiptsFrom; STACK_OF(GENERAL_NAMES) *receiptsTo; }; struct CMS_ReceiptsFrom_st { int type; union { int32_t allOrFirstTier; STACK_OF(GENERAL_NAMES) *receiptList; } d; }; struct CMS_Receipt_st { int32_t version; ASN1_OBJECT *contentType; ASN1_OCTET_STRING *signedContentIdentifier; ASN1_OCTET_STRING *originatorSignatureValue; }; DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo) DECLARE_ASN1_ITEM(CMS_SignerInfo) DECLARE_ASN1_ITEM(CMS_IssuerAndSerialNumber) DECLARE_ASN1_ITEM(CMS_Attributes_Sign) DECLARE_ASN1_ITEM(CMS_Attributes_Verify) DECLARE_ASN1_ITEM(CMS_RecipientInfo) DECLARE_ASN1_ITEM(CMS_PasswordRecipientInfo) DECLARE_ASN1_ALLOC_FUNCTIONS(CMS_IssuerAndSerialNumber) # define CMS_SIGNERINFO_ISSUER_SERIAL 0 # define CMS_SIGNERINFO_KEYIDENTIFIER 1 # define CMS_RECIPINFO_ISSUER_SERIAL 0 # define CMS_RECIPINFO_KEYIDENTIFIER 1 # define CMS_REK_ISSUER_SERIAL 0 # define CMS_REK_KEYIDENTIFIER 1 # define CMS_OIK_ISSUER_SERIAL 0 # define CMS_OIK_KEYIDENTIFIER 1 # define CMS_OIK_PUBKEY 2 BIO *ossl_cms_content_bio(CMS_ContentInfo *cms); const CMS_CTX *ossl_cms_get0_cmsctx(const CMS_ContentInfo *cms); OSSL_LIB_CTX *ossl_cms_ctx_get0_libctx(const CMS_CTX *ctx); const char *ossl_cms_ctx_get0_propq(const CMS_CTX *ctx); void ossl_cms_resolve_libctx(CMS_ContentInfo *ci); CMS_ContentInfo *ossl_cms_Data_create(OSSL_LIB_CTX *ctx, const char *propq); int ossl_cms_DataFinal(CMS_ContentInfo *cms, BIO *cmsbio, const unsigned char *precomp_md, unsigned int precomp_mdlen); CMS_ContentInfo *ossl_cms_DigestedData_create(const EVP_MD *md, OSSL_LIB_CTX *libctx, const char *propq); BIO *ossl_cms_DigestedData_init_bio(const CMS_ContentInfo *cms); int ossl_cms_DigestedData_do_final(const CMS_ContentInfo *cms, BIO *chain, int verify); BIO *ossl_cms_SignedData_init_bio(CMS_ContentInfo *cms); int ossl_cms_SignedData_final(CMS_ContentInfo *cms, BIO *chain, const unsigned char *precomp_md, unsigned int precomp_mdlen); int ossl_cms_set1_SignerIdentifier(CMS_SignerIdentifier *sid, X509 *cert, int type, const CMS_CTX *ctx); int ossl_cms_SignerIdentifier_get0_signer_id(CMS_SignerIdentifier *sid, ASN1_OCTET_STRING **keyid, X509_NAME **issuer, ASN1_INTEGER **sno); int ossl_cms_SignerIdentifier_cert_cmp(CMS_SignerIdentifier *sid, X509 *cert); CMS_ContentInfo *ossl_cms_CompressedData_create(int comp_nid, OSSL_LIB_CTX *libctx, const char *propq); BIO *ossl_cms_CompressedData_init_bio(const CMS_ContentInfo *cms); BIO *ossl_cms_DigestAlgorithm_init_bio(X509_ALGOR *digestAlgorithm, const CMS_CTX *ctx); int ossl_cms_DigestAlgorithm_find_ctx(EVP_MD_CTX *mctx, BIO *chain, X509_ALGOR *mdalg); int ossl_cms_ias_cert_cmp(CMS_IssuerAndSerialNumber *ias, X509 *cert); int ossl_cms_keyid_cert_cmp(ASN1_OCTET_STRING *keyid, X509 *cert); int ossl_cms_set1_ias(CMS_IssuerAndSerialNumber **pias, X509 *cert); int ossl_cms_set1_keyid(ASN1_OCTET_STRING **pkeyid, X509 *cert); BIO *ossl_cms_EncryptedContent_init_bio(CMS_EncryptedContentInfo *ec, const CMS_CTX *ctx); BIO *ossl_cms_EncryptedData_init_bio(const CMS_ContentInfo *cms); int ossl_cms_EncryptedContent_init(CMS_EncryptedContentInfo *ec, const EVP_CIPHER *cipher, const unsigned char *key, size_t keylen, const CMS_CTX *ctx); int ossl_cms_Receipt_verify(CMS_ContentInfo *cms, CMS_ContentInfo *req_cms); int ossl_cms_msgSigDigest_add1(CMS_SignerInfo *dest, CMS_SignerInfo *src); ASN1_OCTET_STRING *ossl_cms_encode_Receipt(CMS_SignerInfo *si); BIO *ossl_cms_EnvelopedData_init_bio(CMS_ContentInfo *cms); int ossl_cms_EnvelopedData_final(CMS_ContentInfo *cms, BIO *chain); BIO *ossl_cms_AuthEnvelopedData_init_bio(CMS_ContentInfo *cms); int ossl_cms_AuthEnvelopedData_final(CMS_ContentInfo *cms, BIO *cmsbio); CMS_EnvelopedData *ossl_cms_get0_enveloped(CMS_ContentInfo *cms); CMS_AuthEnvelopedData *ossl_cms_get0_auth_enveloped(CMS_ContentInfo *cms); CMS_EncryptedContentInfo *ossl_cms_get0_env_enc_content(const CMS_ContentInfo *cms); /* RecipientInfo routines */ int ossl_cms_env_asn1_ctrl(CMS_RecipientInfo *ri, int cmd); int ossl_cms_pkey_get_ri_type(EVP_PKEY *pk); int ossl_cms_pkey_is_ri_type_supported(EVP_PKEY *pk, int ri_type); void ossl_cms_RecipientInfos_set_cmsctx(CMS_ContentInfo *cms); /* KARI routines */ int ossl_cms_RecipientInfo_kari_init(CMS_RecipientInfo *ri, X509 *recip, EVP_PKEY *recipPubKey, X509 *originator, EVP_PKEY *originatorPrivKey, unsigned int flags, const CMS_CTX *ctx); int ossl_cms_RecipientInfo_kari_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri); /* PWRI routines */ int ossl_cms_RecipientInfo_pwri_crypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri, int en_de); /* SignerInfo routines */ int ossl_cms_si_check_attributes(const CMS_SignerInfo *si); void ossl_cms_SignerInfos_set_cmsctx(CMS_ContentInfo *cms); /* ESS routines */ int ossl_cms_check_signing_certs(const CMS_SignerInfo *si, const STACK_OF(X509) *chain); int ossl_cms_dh_envelope(CMS_RecipientInfo *ri, int decrypt); int ossl_cms_ecdh_envelope(CMS_RecipientInfo *ri, int decrypt); int ossl_cms_rsa_envelope(CMS_RecipientInfo *ri, int decrypt); int ossl_cms_rsa_sign(CMS_SignerInfo *si, int verify); DECLARE_ASN1_ITEM(CMS_CertificateChoices) DECLARE_ASN1_ITEM(CMS_DigestedData) DECLARE_ASN1_ITEM(CMS_EncryptedData) DECLARE_ASN1_ITEM(CMS_EnvelopedData) DECLARE_ASN1_ITEM(CMS_AuthEnvelopedData) DECLARE_ASN1_ITEM(CMS_KEKRecipientInfo) DECLARE_ASN1_ITEM(CMS_KeyAgreeRecipientInfo) DECLARE_ASN1_ITEM(CMS_KeyTransRecipientInfo) DECLARE_ASN1_ITEM(CMS_OriginatorPublicKey) DECLARE_ASN1_ITEM(CMS_OtherKeyAttribute) DECLARE_ASN1_ITEM(CMS_Receipt) DECLARE_ASN1_ITEM(CMS_ReceiptRequest) DECLARE_ASN1_ITEM(CMS_RecipientEncryptedKey) DECLARE_ASN1_ITEM(CMS_RecipientKeyIdentifier) DECLARE_ASN1_ITEM(CMS_RevocationInfoChoice) DECLARE_ASN1_ITEM(CMS_SignedData) DECLARE_ASN1_ITEM(CMS_CompressedData) #endif
16,985
32.56917
84
h
openssl
openssl-master/crypto/cms/cms_pwri.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 "internal/cryptlib.h" #include <openssl/asn1t.h> #include <openssl/pem.h> #include <openssl/x509v3.h> #include <openssl/err.h> #include <openssl/cms.h> #include <openssl/rand.h> #include <openssl/aes.h> #include "internal/sizes.h" #include "crypto/asn1.h" #include "cms_local.h" int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri, unsigned char *pass, ossl_ssize_t passlen) { CMS_PasswordRecipientInfo *pwri; if (ri->type != CMS_RECIPINFO_PASS) { ERR_raise(ERR_LIB_CMS, CMS_R_NOT_PWRI); return 0; } pwri = ri->d.pwri; pwri->pass = pass; if (pass && passlen < 0) passlen = strlen((char *)pass); pwri->passlen = passlen; return 1; } CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms, int iter, int wrap_nid, int pbe_nid, unsigned char *pass, ossl_ssize_t passlen, const EVP_CIPHER *kekciph) { STACK_OF(CMS_RecipientInfo) *ris; CMS_RecipientInfo *ri = NULL; CMS_EncryptedContentInfo *ec; CMS_PasswordRecipientInfo *pwri; EVP_CIPHER_CTX *ctx = NULL; X509_ALGOR *encalg = NULL; unsigned char iv[EVP_MAX_IV_LENGTH]; int ivlen; const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms); ec = ossl_cms_get0_env_enc_content(cms); if (ec == NULL) return NULL; ris = CMS_get0_RecipientInfos(cms); if (ris == NULL) return NULL; if (wrap_nid <= 0) wrap_nid = NID_id_alg_PWRI_KEK; if (pbe_nid <= 0) pbe_nid = NID_id_pbkdf2; /* Get from enveloped data */ if (kekciph == NULL) kekciph = ec->cipher; if (kekciph == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_CIPHER); return NULL; } if (wrap_nid != NID_id_alg_PWRI_KEK) { ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM); return NULL; } /* Setup algorithm identifier for cipher */ encalg = X509_ALGOR_new(); if (encalg == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } ctx = EVP_CIPHER_CTX_new(); if (ctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } if (EVP_EncryptInit_ex(ctx, kekciph, NULL, NULL, NULL) <= 0) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } ivlen = EVP_CIPHER_CTX_get_iv_length(ctx); if (ivlen < 0) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } if (ivlen > 0) { if (RAND_bytes_ex(ossl_cms_ctx_get0_libctx(cms_ctx), iv, ivlen, 0) <= 0) goto err; if (EVP_EncryptInit_ex(ctx, NULL, NULL, NULL, iv) <= 0) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } encalg->parameter = ASN1_TYPE_new(); if (!encalg->parameter) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } if (EVP_CIPHER_param_to_asn1(ctx, encalg->parameter) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR); goto err; } } encalg->algorithm = OBJ_nid2obj(EVP_CIPHER_CTX_get_type(ctx)); EVP_CIPHER_CTX_free(ctx); ctx = NULL; /* Initialize recipient info */ ri = M_ASN1_new_of(CMS_RecipientInfo); if (ri == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } ri->d.pwri = M_ASN1_new_of(CMS_PasswordRecipientInfo); if (ri->d.pwri == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } ri->type = CMS_RECIPINFO_PASS; pwri = ri->d.pwri; pwri->cms_ctx = cms_ctx; /* Since this is overwritten, free up empty structure already there */ X509_ALGOR_free(pwri->keyEncryptionAlgorithm); pwri->keyEncryptionAlgorithm = X509_ALGOR_new(); if (pwri->keyEncryptionAlgorithm == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } pwri->keyEncryptionAlgorithm->algorithm = OBJ_nid2obj(wrap_nid); pwri->keyEncryptionAlgorithm->parameter = ASN1_TYPE_new(); if (pwri->keyEncryptionAlgorithm->parameter == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } if (!ASN1_item_pack(encalg, ASN1_ITEM_rptr(X509_ALGOR), &pwri->keyEncryptionAlgorithm->parameter-> value.sequence)) { ERR_raise(ERR_LIB_CMS, ERR_R_ASN1_LIB); goto err; } pwri->keyEncryptionAlgorithm->parameter->type = V_ASN1_SEQUENCE; X509_ALGOR_free(encalg); encalg = NULL; /* Setup PBE algorithm */ pwri->keyDerivationAlgorithm = PKCS5_pbkdf2_set(iter, NULL, 0, -1, -1); if (pwri->keyDerivationAlgorithm == NULL) goto err; CMS_RecipientInfo_set0_password(ri, pass, passlen); pwri->version = 0; if (!sk_CMS_RecipientInfo_push(ris, ri)) { ERR_raise(ERR_LIB_CMS, ERR_R_CRYPTO_LIB); goto err; } return ri; err: EVP_CIPHER_CTX_free(ctx); if (ri) M_ASN1_free_of(ri, CMS_RecipientInfo); X509_ALGOR_free(encalg); return NULL; } /* * This is an implementation of the key wrapping mechanism in RFC3211, at * some point this should go into EVP. */ static int kek_unwrap_key(unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen, EVP_CIPHER_CTX *ctx) { size_t blocklen = EVP_CIPHER_CTX_get_block_size(ctx); unsigned char *tmp; int outl, rv = 0; if (inlen < 2 * blocklen) { /* too small */ return 0; } if (inlen % blocklen) { /* Invalid size */ return 0; } if ((tmp = OPENSSL_malloc(inlen)) == NULL) return 0; /* setup IV by decrypting last two blocks */ if (!EVP_DecryptUpdate(ctx, tmp + inlen - 2 * blocklen, &outl, in + inlen - 2 * blocklen, blocklen * 2) /* * Do a decrypt of last decrypted block to set IV to correct value * output it to start of buffer so we don't corrupt decrypted block * this works because buffer is at least two block lengths long. */ || !EVP_DecryptUpdate(ctx, tmp, &outl, tmp + inlen - blocklen, blocklen) /* Can now decrypt first n - 1 blocks */ || !EVP_DecryptUpdate(ctx, tmp, &outl, in, inlen - blocklen) /* Reset IV to original value */ || !EVP_DecryptInit_ex(ctx, NULL, NULL, NULL, NULL) /* Decrypt again */ || !EVP_DecryptUpdate(ctx, tmp, &outl, tmp, inlen)) goto err; /* Check check bytes */ if (((tmp[1] ^ tmp[4]) & (tmp[2] ^ tmp[5]) & (tmp[3] ^ tmp[6])) != 0xff) { /* Check byte failure */ goto err; } if (inlen < (size_t)(tmp[0] - 4)) { /* Invalid length value */ goto err; } *outlen = (size_t)tmp[0]; memcpy(out, tmp + 4, *outlen); rv = 1; err: OPENSSL_clear_free(tmp, inlen); return rv; } static int kek_wrap_key(unsigned char *out, size_t *outlen, const unsigned char *in, size_t inlen, EVP_CIPHER_CTX *ctx, const CMS_CTX *cms_ctx) { size_t blocklen = EVP_CIPHER_CTX_get_block_size(ctx); size_t olen; int dummy; /* * First decide length of output buffer: need header and round up to * multiple of block length. */ olen = (inlen + 4 + blocklen - 1) / blocklen; olen *= blocklen; if (olen < 2 * blocklen) { /* Key too small */ return 0; } if (inlen > 0xFF) { /* Key too large */ return 0; } if (out) { /* Set header */ out[0] = (unsigned char)inlen; out[1] = in[0] ^ 0xFF; out[2] = in[1] ^ 0xFF; out[3] = in[2] ^ 0xFF; memcpy(out + 4, in, inlen); /* Add random padding to end */ if (olen > inlen + 4 && RAND_bytes_ex(ossl_cms_ctx_get0_libctx(cms_ctx), out + 4 + inlen, olen - 4 - inlen, 0) <= 0) return 0; /* Encrypt twice */ if (!EVP_EncryptUpdate(ctx, out, &dummy, out, olen) || !EVP_EncryptUpdate(ctx, out, &dummy, out, olen)) return 0; } *outlen = olen; return 1; } /* Encrypt/Decrypt content key in PWRI recipient info */ int ossl_cms_RecipientInfo_pwri_crypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri, int en_de) { CMS_EncryptedContentInfo *ec; CMS_PasswordRecipientInfo *pwri; int r = 0; X509_ALGOR *algtmp, *kekalg = NULL; EVP_CIPHER_CTX *kekctx = NULL; char name[OSSL_MAX_NAME_SIZE]; EVP_CIPHER *kekcipher; unsigned char *key = NULL; size_t keylen; const CMS_CTX *cms_ctx = ossl_cms_get0_cmsctx(cms); ec = ossl_cms_get0_env_enc_content(cms); pwri = ri->d.pwri; if (pwri->pass == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_NO_PASSWORD); return 0; } algtmp = pwri->keyEncryptionAlgorithm; if (!algtmp || OBJ_obj2nid(algtmp->algorithm) != NID_id_alg_PWRI_KEK) { ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM); return 0; } kekalg = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(X509_ALGOR), algtmp->parameter); if (kekalg == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER); return 0; } OBJ_obj2txt(name, sizeof(name), kekalg->algorithm, 0); kekcipher = EVP_CIPHER_fetch(ossl_cms_ctx_get0_libctx(cms_ctx), name, ossl_cms_ctx_get0_propq(cms_ctx)); if (kekcipher == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_UNKNOWN_CIPHER); goto err; } kekctx = EVP_CIPHER_CTX_new(); if (kekctx == NULL) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } /* Fixup cipher based on AlgorithmIdentifier to set IV etc */ if (!EVP_CipherInit_ex(kekctx, kekcipher, NULL, NULL, NULL, en_de)) goto err; EVP_CIPHER_CTX_set_padding(kekctx, 0); if (EVP_CIPHER_asn1_to_param(kekctx, kekalg->parameter) <= 0) { ERR_raise(ERR_LIB_CMS, CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR); goto err; } algtmp = pwri->keyDerivationAlgorithm; /* Finish password based key derivation to setup key in "ctx" */ if (EVP_PBE_CipherInit(algtmp->algorithm, (char *)pwri->pass, pwri->passlen, algtmp->parameter, kekctx, en_de) < 0) { ERR_raise(ERR_LIB_CMS, ERR_R_EVP_LIB); goto err; } /* Finally wrap/unwrap the key */ if (en_de) { if (!kek_wrap_key(NULL, &keylen, ec->key, ec->keylen, kekctx, cms_ctx)) goto err; key = OPENSSL_malloc(keylen); if (key == NULL) goto err; if (!kek_wrap_key(key, &keylen, ec->key, ec->keylen, kekctx, cms_ctx)) goto err; pwri->encryptedKey->data = key; pwri->encryptedKey->length = keylen; } else { key = OPENSSL_malloc(pwri->encryptedKey->length); if (key == NULL) goto err; if (!kek_unwrap_key(key, &keylen, pwri->encryptedKey->data, pwri->encryptedKey->length, kekctx)) { ERR_raise(ERR_LIB_CMS, CMS_R_UNWRAP_FAILURE); goto err; } OPENSSL_clear_free(ec->key, ec->keylen); ec->key = key; ec->keylen = keylen; } r = 1; err: EVP_CIPHER_free(kekcipher); EVP_CIPHER_CTX_free(kekctx); if (!r) OPENSSL_free(key); X509_ALGOR_free(kekalg); return r; }
12,262
28.478365
80
c
openssl
openssl-master/crypto/cms/cms_rsa.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 <assert.h> #include <openssl/cms.h> #include <openssl/err.h> #include <openssl/core_names.h> #include "crypto/asn1.h" #include "crypto/rsa.h" #include "crypto/evp.h" #include "cms_local.h" static RSA_OAEP_PARAMS *rsa_oaep_decode(const X509_ALGOR *alg) { RSA_OAEP_PARAMS *oaep; oaep = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(RSA_OAEP_PARAMS), alg->parameter); if (oaep == NULL) return NULL; if (oaep->maskGenFunc != NULL) { oaep->maskHash = ossl_x509_algor_mgf1_decode(oaep->maskGenFunc); if (oaep->maskHash == NULL) { RSA_OAEP_PARAMS_free(oaep); return NULL; } } return oaep; } static int rsa_cms_decrypt(CMS_RecipientInfo *ri) { EVP_PKEY_CTX *pkctx; X509_ALGOR *cmsalg; int nid; int rv = -1; unsigned char *label = NULL; int labellen = 0; const EVP_MD *mgf1md = NULL, *md = NULL; RSA_OAEP_PARAMS *oaep; pkctx = CMS_RecipientInfo_get0_pkey_ctx(ri); if (pkctx == NULL) return 0; if (!CMS_RecipientInfo_ktri_get0_algs(ri, NULL, NULL, &cmsalg)) return -1; nid = OBJ_obj2nid(cmsalg->algorithm); if (nid == NID_rsaEncryption) return 1; if (nid != NID_rsaesOaep) { ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_ENCRYPTION_TYPE); return -1; } /* Decode OAEP parameters */ oaep = rsa_oaep_decode(cmsalg); if (oaep == NULL) { ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_OAEP_PARAMETERS); goto err; } mgf1md = ossl_x509_algor_get_md(oaep->maskHash); if (mgf1md == NULL) goto err; md = ossl_x509_algor_get_md(oaep->hashFunc); if (md == NULL) goto err; if (oaep->pSourceFunc != NULL) { X509_ALGOR *plab = oaep->pSourceFunc; if (OBJ_obj2nid(plab->algorithm) != NID_pSpecified) { ERR_raise(ERR_LIB_CMS, CMS_R_UNSUPPORTED_LABEL_SOURCE); goto err; } if (plab->parameter->type != V_ASN1_OCTET_STRING) { ERR_raise(ERR_LIB_CMS, CMS_R_INVALID_LABEL); goto err; } label = plab->parameter->value.octet_string->data; /* Stop label being freed when OAEP parameters are freed */ plab->parameter->value.octet_string->data = NULL; labellen = plab->parameter->value.octet_string->length; } if (EVP_PKEY_CTX_set_rsa_padding(pkctx, RSA_PKCS1_OAEP_PADDING) <= 0) goto err; if (EVP_PKEY_CTX_set_rsa_oaep_md(pkctx, md) <= 0) goto err; if (EVP_PKEY_CTX_set_rsa_mgf1_md(pkctx, mgf1md) <= 0) goto err; if (label != NULL && EVP_PKEY_CTX_set0_rsa_oaep_label(pkctx, label, labellen) <= 0) goto err; /* Carry on */ rv = 1; err: RSA_OAEP_PARAMS_free(oaep); return rv; } static int rsa_cms_encrypt(CMS_RecipientInfo *ri) { const EVP_MD *md, *mgf1md; RSA_OAEP_PARAMS *oaep = NULL; ASN1_STRING *os = NULL; X509_ALGOR *alg; EVP_PKEY_CTX *pkctx = CMS_RecipientInfo_get0_pkey_ctx(ri); int pad_mode = RSA_PKCS1_PADDING, rv = 0, labellen; unsigned char *label; if (CMS_RecipientInfo_ktri_get0_algs(ri, NULL, NULL, &alg) <= 0) return 0; if (pkctx != NULL) { if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0) return 0; } if (pad_mode == RSA_PKCS1_PADDING) return X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, NULL); /* Not supported */ if (pad_mode != RSA_PKCS1_OAEP_PADDING) return 0; if (EVP_PKEY_CTX_get_rsa_oaep_md(pkctx, &md) <= 0) goto err; if (EVP_PKEY_CTX_get_rsa_mgf1_md(pkctx, &mgf1md) <= 0) goto err; labellen = EVP_PKEY_CTX_get0_rsa_oaep_label(pkctx, &label); if (labellen < 0) goto err; oaep = RSA_OAEP_PARAMS_new(); if (oaep == NULL) goto err; if (!ossl_x509_algor_new_from_md(&oaep->hashFunc, md)) goto err; if (!ossl_x509_algor_md_to_mgf1(&oaep->maskGenFunc, mgf1md)) goto err; if (labellen > 0) { ASN1_OCTET_STRING *los = ASN1_OCTET_STRING_new(); if (los == NULL) goto err; if (!ASN1_OCTET_STRING_set(los, label, labellen)) { ASN1_OCTET_STRING_free(los); goto err; } oaep->pSourceFunc = ossl_X509_ALGOR_from_nid(NID_pSpecified, V_ASN1_OCTET_STRING, los); if (oaep->pSourceFunc == NULL) goto err; } /* create string with pss parameter encoding. */ if (!ASN1_item_pack(oaep, ASN1_ITEM_rptr(RSA_OAEP_PARAMS), &os)) goto err; if (!X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaesOaep), V_ASN1_SEQUENCE, os)) goto err; os = NULL; rv = 1; err: RSA_OAEP_PARAMS_free(oaep); ASN1_STRING_free(os); return rv; } int ossl_cms_rsa_envelope(CMS_RecipientInfo *ri, int decrypt) { assert(decrypt == 0 || decrypt == 1); if (decrypt == 1) return rsa_cms_decrypt(ri); if (decrypt == 0) return rsa_cms_encrypt(ri); ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); return 0; } static int rsa_cms_sign(CMS_SignerInfo *si) { int pad_mode = RSA_PKCS1_PADDING; X509_ALGOR *alg; EVP_PKEY_CTX *pkctx = CMS_SignerInfo_get0_pkey_ctx(si); unsigned char aid[128]; const unsigned char *pp = aid; size_t aid_len = 0; OSSL_PARAM params[2]; CMS_SignerInfo_get0_algs(si, NULL, NULL, NULL, &alg); if (pkctx != NULL) { if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0) return 0; } if (pad_mode == RSA_PKCS1_PADDING) return X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, NULL); /* We don't support it */ if (pad_mode != RSA_PKCS1_PSS_PADDING) return 0; if (evp_pkey_ctx_is_legacy(pkctx)) { /* No provider -> we cannot query it for algorithm ID. */ ASN1_STRING *os = NULL; os = ossl_rsa_ctx_to_pss_string(pkctx); if (os == NULL) return 0; return X509_ALGOR_set0(alg, OBJ_nid2obj(EVP_PKEY_RSA_PSS), V_ASN1_SEQUENCE, os); } params[0] = OSSL_PARAM_construct_octet_string( OSSL_SIGNATURE_PARAM_ALGORITHM_ID, aid, sizeof(aid)); params[1] = OSSL_PARAM_construct_end(); if (EVP_PKEY_CTX_get_params(pkctx, params) <= 0) return 0; if ((aid_len = params[0].return_size) == 0) return 0; if (d2i_X509_ALGOR(&alg, &pp, aid_len) == NULL) return 0; return 1; } static int rsa_cms_verify(CMS_SignerInfo *si) { int nid, nid2; X509_ALGOR *alg; EVP_PKEY_CTX *pkctx = CMS_SignerInfo_get0_pkey_ctx(si); EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(pkctx); CMS_SignerInfo_get0_algs(si, NULL, NULL, NULL, &alg); nid = OBJ_obj2nid(alg->algorithm); if (nid == EVP_PKEY_RSA_PSS) return ossl_rsa_pss_to_ctx(NULL, pkctx, alg, NULL) > 0; /* Only PSS allowed for PSS keys */ if (EVP_PKEY_is_a(pkey, "RSA-PSS")) { ERR_raise(ERR_LIB_RSA, RSA_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE); return 0; } if (nid == NID_rsaEncryption) return 1; /* Workaround for some implementation that use a signature OID */ if (OBJ_find_sigid_algs(nid, NULL, &nid2)) { if (nid2 == NID_rsaEncryption) return 1; } return 0; } int ossl_cms_rsa_sign(CMS_SignerInfo *si, int verify) { assert(verify == 0 || verify == 1); if (verify == 1) return rsa_cms_verify(si); if (verify == 0) return rsa_cms_sign(si); ERR_raise(ERR_LIB_CMS, CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE); return 0; }
8,090
28.421818
88
c
openssl
openssl-master/crypto/comp/c_zlib.c
/* * Copyright 1998-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 <stdlib.h> #include <string.h> #include <openssl/objects.h> #include "internal/comp.h" #include <openssl/err.h> #include "crypto/cryptlib.h" #include "internal/bio.h" #include "internal/thread_once.h" #include "comp_local.h" COMP_METHOD *COMP_zlib(void); #ifdef OPENSSL_NO_ZLIB # undef ZLIB_SHARED #else # include <zlib.h> static int zlib_stateful_init(COMP_CTX *ctx); static void zlib_stateful_finish(COMP_CTX *ctx); static ossl_ssize_t zlib_stateful_compress_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen); static ossl_ssize_t zlib_stateful_expand_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen); /* memory allocations functions for zlib initialisation */ static void *zlib_zalloc(void *opaque, unsigned int no, unsigned int size) { void *p; p = OPENSSL_zalloc(no * size); return p; } static void zlib_zfree(void *opaque, void *address) { OPENSSL_free(address); } static COMP_METHOD zlib_stateful_method = { NID_zlib_compression, LN_zlib_compression, zlib_stateful_init, zlib_stateful_finish, zlib_stateful_compress_block, zlib_stateful_expand_block }; /* * When OpenSSL is built on Windows, we do not want to require that * the ZLIB.DLL be available in order for the OpenSSL DLLs to * work. Therefore, all ZLIB routines are loaded at run time * and we do not link to a .LIB file when ZLIB_SHARED is set. */ # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) # include <windows.h> # endif /* !(OPENSSL_SYS_WINDOWS || * OPENSSL_SYS_WIN32) */ # ifdef ZLIB_SHARED # include "internal/dso.h" /* Function pointers */ typedef int (*compress_ft) (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen); typedef int (*uncompress_ft) (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen); typedef int (*inflateEnd_ft) (z_streamp strm); typedef int (*inflate_ft) (z_streamp strm, int flush); typedef int (*inflateInit__ft) (z_streamp strm, const char *version, int stream_size); typedef int (*deflateEnd_ft) (z_streamp strm); typedef int (*deflate_ft) (z_streamp strm, int flush); typedef int (*deflateInit__ft) (z_streamp strm, int level, const char *version, int stream_size); typedef const char *(*zError__ft) (int err); static compress_ft p_compress = NULL; static uncompress_ft p_uncompress = NULL; static inflateEnd_ft p_inflateEnd = NULL; static inflate_ft p_inflate = NULL; static inflateInit__ft p_inflateInit_ = NULL; static deflateEnd_ft p_deflateEnd = NULL; static deflate_ft p_deflate = NULL; static deflateInit__ft p_deflateInit_ = NULL; static zError__ft p_zError = NULL; static DSO *zlib_dso = NULL; # define compress p_compress # define uncompress p_uncompress # define inflateEnd p_inflateEnd # define inflate p_inflate # define inflateInit_ p_inflateInit_ # define deflateEnd p_deflateEnd # define deflate p_deflate # define deflateInit_ p_deflateInit_ # define zError p_zError # endif /* ZLIB_SHARED */ struct zlib_state { z_stream istream; z_stream ostream; }; static int zlib_stateful_init(COMP_CTX *ctx) { int err; struct zlib_state *state = OPENSSL_zalloc(sizeof(*state)); if (state == NULL) goto err; state->istream.zalloc = zlib_zalloc; state->istream.zfree = zlib_zfree; state->istream.opaque = Z_NULL; state->istream.next_in = Z_NULL; state->istream.next_out = Z_NULL; err = inflateInit_(&state->istream, ZLIB_VERSION, sizeof(z_stream)); if (err != Z_OK) goto err; state->ostream.zalloc = zlib_zalloc; state->ostream.zfree = zlib_zfree; state->ostream.opaque = Z_NULL; state->ostream.next_in = Z_NULL; state->ostream.next_out = Z_NULL; err = deflateInit_(&state->ostream, Z_DEFAULT_COMPRESSION, ZLIB_VERSION, sizeof(z_stream)); if (err != Z_OK) goto err; ctx->data = state; return 1; err: OPENSSL_free(state); return 0; } static void zlib_stateful_finish(COMP_CTX *ctx) { struct zlib_state *state = ctx->data; inflateEnd(&state->istream); deflateEnd(&state->ostream); OPENSSL_free(state); } static ossl_ssize_t zlib_stateful_compress_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { int err = Z_OK; struct zlib_state *state = ctx->data; if (state == NULL) return -1; state->ostream.next_in = in; state->ostream.avail_in = ilen; state->ostream.next_out = out; state->ostream.avail_out = olen; if (ilen > 0) err = deflate(&state->ostream, Z_SYNC_FLUSH); if (err != Z_OK) return -1; if (state->ostream.avail_out > olen) return -1; return (ossl_ssize_t)(olen - state->ostream.avail_out); } static ossl_ssize_t zlib_stateful_expand_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { int err = Z_OK; struct zlib_state *state = ctx->data; if (state == NULL) return 0; state->istream.next_in = in; state->istream.avail_in = ilen; state->istream.next_out = out; state->istream.avail_out = olen; if (ilen > 0) err = inflate(&state->istream, Z_SYNC_FLUSH); if (err != Z_OK) return -1; if (state->istream.avail_out > olen) return -1; return (ossl_ssize_t)(olen - state->istream.avail_out); } /* ONESHOT COMPRESSION/DECOMPRESSION */ static int zlib_oneshot_init(COMP_CTX *ctx) { return 1; } static void zlib_oneshot_finish(COMP_CTX *ctx) { } static ossl_ssize_t zlib_oneshot_compress_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { uLongf out_size; if (ilen == 0) return 0; /* zlib's uLongf defined as unsigned long FAR */ if (olen > ULONG_MAX) return -1; out_size = (uLongf)olen; if (compress(out, &out_size, in, ilen) != Z_OK) return -1; if (out_size > OSSL_SSIZE_MAX) return -1; return (ossl_ssize_t)out_size; } static ossl_ssize_t zlib_oneshot_expand_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { uLongf out_size; if (ilen == 0) return 0; /* zlib's uLongf defined as unsigned long FAR */ if (olen > ULONG_MAX) return -1; out_size = (uLongf)olen; if (uncompress(out, &out_size, in, ilen) != Z_OK) return -1; if (out_size > OSSL_SSIZE_MAX) return -1; return (ossl_ssize_t)out_size; } static COMP_METHOD zlib_oneshot_method = { NID_zlib_compression, LN_zlib_compression, zlib_oneshot_init, zlib_oneshot_finish, zlib_oneshot_compress_block, zlib_oneshot_expand_block }; static CRYPTO_ONCE zlib_once = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_comp_zlib_init) { # ifdef ZLIB_SHARED /* LIBZ may be externally defined, and we should respect that value */ # ifndef LIBZ # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) # define LIBZ "ZLIB1" # elif defined(OPENSSL_SYS_VMS) # define LIBZ "LIBZ" # else # define LIBZ "z" # endif # endif zlib_dso = DSO_load(NULL, LIBZ, NULL, 0); if (zlib_dso != NULL) { p_compress = (compress_ft) DSO_bind_func(zlib_dso, "compress"); p_uncompress = (compress_ft) DSO_bind_func(zlib_dso, "uncompress"); p_inflateEnd = (inflateEnd_ft) DSO_bind_func(zlib_dso, "inflateEnd"); p_inflate = (inflate_ft) DSO_bind_func(zlib_dso, "inflate"); p_inflateInit_ = (inflateInit__ft) DSO_bind_func(zlib_dso, "inflateInit_"); p_deflateEnd = (deflateEnd_ft) DSO_bind_func(zlib_dso, "deflateEnd"); p_deflate = (deflate_ft) DSO_bind_func(zlib_dso, "deflate"); p_deflateInit_ = (deflateInit__ft) DSO_bind_func(zlib_dso, "deflateInit_"); p_zError = (zError__ft) DSO_bind_func(zlib_dso, "zError"); if (p_compress == NULL || p_uncompress == NULL || p_inflateEnd == NULL || p_inflate == NULL || p_inflateInit_ == NULL || p_deflateEnd == NULL || p_deflate == NULL || p_deflateInit_ == NULL || p_zError == NULL) { ossl_comp_zlib_cleanup(); return 0; } } # endif return 1; } #endif COMP_METHOD *COMP_zlib(void) { COMP_METHOD *meth = NULL; #ifndef OPENSSL_NO_ZLIB if (RUN_ONCE(&zlib_once, ossl_comp_zlib_init)) meth = &zlib_stateful_method; #endif return meth; } COMP_METHOD *COMP_zlib_oneshot(void) { COMP_METHOD *meth = NULL; #ifndef OPENSSL_NO_ZLIB if (RUN_ONCE(&zlib_once, ossl_comp_zlib_init)) meth = &zlib_oneshot_method; #endif return meth; } /* Also called from OPENSSL_cleanup() */ void ossl_comp_zlib_cleanup(void) { #ifdef ZLIB_SHARED DSO_free(zlib_dso); zlib_dso = NULL; #endif } #ifndef OPENSSL_NO_ZLIB /* Zlib based compression/decompression filter BIO */ typedef struct { unsigned char *ibuf; /* Input buffer */ int ibufsize; /* Buffer size */ z_stream zin; /* Input decompress context */ unsigned char *obuf; /* Output buffer */ int obufsize; /* Output buffer size */ unsigned char *optr; /* Position in output buffer */ int ocount; /* Amount of data in output buffer */ int odone; /* deflate EOF */ int comp_level; /* Compression level to use */ z_stream zout; /* Output compression context */ } BIO_ZLIB_CTX; # define ZLIB_DEFAULT_BUFSIZE 1024 static int bio_zlib_new(BIO *bi); static int bio_zlib_free(BIO *bi); static int bio_zlib_read(BIO *b, char *out, int outl); static int bio_zlib_write(BIO *b, const char *in, int inl); static long bio_zlib_ctrl(BIO *b, int cmd, long num, void *ptr); static long bio_zlib_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp); static const BIO_METHOD bio_meth_zlib = { BIO_TYPE_COMP, "zlib", bwrite_conv, bio_zlib_write, bread_conv, bio_zlib_read, NULL, /* bio_zlib_puts, */ NULL, /* bio_zlib_gets, */ bio_zlib_ctrl, bio_zlib_new, bio_zlib_free, bio_zlib_callback_ctrl }; #endif const BIO_METHOD *BIO_f_zlib(void) { #ifndef OPENSSL_NO_ZLIB if (RUN_ONCE(&zlib_once, ossl_comp_zlib_init)) return &bio_meth_zlib; #endif return NULL; } #ifndef OPENSSL_NO_ZLIB static int bio_zlib_new(BIO *bi) { BIO_ZLIB_CTX *ctx; # ifdef ZLIB_SHARED if (!RUN_ONCE(&zlib_once, ossl_comp_zlib_init)) { ERR_raise(ERR_LIB_COMP, COMP_R_ZLIB_NOT_SUPPORTED); return 0; } # endif ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) return 0; ctx->ibufsize = ZLIB_DEFAULT_BUFSIZE; ctx->obufsize = ZLIB_DEFAULT_BUFSIZE; ctx->zin.zalloc = Z_NULL; ctx->zin.zfree = Z_NULL; ctx->zout.zalloc = Z_NULL; ctx->zout.zfree = Z_NULL; ctx->comp_level = Z_DEFAULT_COMPRESSION; BIO_set_init(bi, 1); BIO_set_data(bi, ctx); return 1; } static int bio_zlib_free(BIO *bi) { BIO_ZLIB_CTX *ctx; if (!bi) return 0; ctx = BIO_get_data(bi); if (ctx->ibuf) { /* Destroy decompress context */ inflateEnd(&ctx->zin); OPENSSL_free(ctx->ibuf); } if (ctx->obuf) { /* Destroy compress context */ deflateEnd(&ctx->zout); OPENSSL_free(ctx->obuf); } OPENSSL_free(ctx); BIO_set_data(bi, NULL); BIO_set_init(bi, 0); return 1; } static int bio_zlib_read(BIO *b, char *out, int outl) { BIO_ZLIB_CTX *ctx; int ret; z_stream *zin; BIO *next = BIO_next(b); if (!out || !outl) return 0; ctx = BIO_get_data(b); zin = &ctx->zin; BIO_clear_retry_flags(b); if (!ctx->ibuf) { ctx->ibuf = OPENSSL_malloc(ctx->ibufsize); if (ctx->ibuf == NULL) return 0; if ((ret = inflateInit(zin)) != Z_OK) { ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_INFLATE_ERROR, "zlib error: %s", zError(ret)); return 0; } zin->next_in = ctx->ibuf; zin->avail_in = 0; } /* Copy output data directly to supplied buffer */ zin->next_out = (unsigned char *)out; zin->avail_out = (unsigned int)outl; for (;;) { /* Decompress while data available */ while (zin->avail_in) { ret = inflate(zin, 0); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_INFLATE_ERROR, "zlib error: %s", zError(ret)); return 0; } /* If EOF or we've read everything then return */ if ((ret == Z_STREAM_END) || !zin->avail_out) return outl - zin->avail_out; } /* * No data in input buffer try to read some in, if an error then * return the total data read. */ ret = BIO_read(next, ctx->ibuf, ctx->ibufsize); if (ret <= 0) { /* Total data read */ int tot = outl - zin->avail_out; BIO_copy_next_retry(b); if (ret < 0) return (tot > 0) ? tot : ret; return tot; } zin->avail_in = ret; zin->next_in = ctx->ibuf; } } static int bio_zlib_write(BIO *b, const char *in, int inl) { BIO_ZLIB_CTX *ctx; int ret; z_stream *zout; BIO *next = BIO_next(b); if (!in || !inl) return 0; ctx = BIO_get_data(b); if (ctx->odone) return 0; zout = &ctx->zout; BIO_clear_retry_flags(b); if (!ctx->obuf) { ctx->obuf = OPENSSL_malloc(ctx->obufsize); /* Need error here */ if (ctx->obuf == NULL) return 0; ctx->optr = ctx->obuf; ctx->ocount = 0; if ((ret = deflateInit(zout, ctx->comp_level)) != Z_OK) { ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_DEFLATE_ERROR, "zlib error: %s", zError(ret)); return 0; } zout->next_out = ctx->obuf; zout->avail_out = ctx->obufsize; } /* Obtain input data directly from supplied buffer */ zout->next_in = (void *)in; zout->avail_in = inl; for (;;) { /* If data in output buffer write it first */ while (ctx->ocount) { ret = BIO_write(next, ctx->optr, ctx->ocount); if (ret <= 0) { /* Total data written */ int tot = inl - zout->avail_in; BIO_copy_next_retry(b); if (ret < 0) return (tot > 0) ? tot : ret; return tot; } ctx->optr += ret; ctx->ocount -= ret; } /* Have we consumed all supplied data? */ if (!zout->avail_in) return inl; /* Compress some more */ /* Reset buffer */ ctx->optr = ctx->obuf; zout->next_out = ctx->obuf; zout->avail_out = ctx->obufsize; /* Compress some more */ ret = deflate(zout, 0); if (ret != Z_OK) { ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_DEFLATE_ERROR, "zlib error: %s", zError(ret)); return 0; } ctx->ocount = ctx->obufsize - zout->avail_out; } } static int bio_zlib_flush(BIO *b) { BIO_ZLIB_CTX *ctx; int ret; z_stream *zout; BIO *next = BIO_next(b); ctx = BIO_get_data(b); /* If no data written or already flush show success */ if (!ctx->obuf || (ctx->odone && !ctx->ocount)) return 1; zout = &ctx->zout; BIO_clear_retry_flags(b); /* No more input data */ zout->next_in = NULL; zout->avail_in = 0; for (;;) { /* If data in output buffer write it first */ while (ctx->ocount) { ret = BIO_write(next, ctx->optr, ctx->ocount); if (ret <= 0) { BIO_copy_next_retry(b); return ret; } ctx->optr += ret; ctx->ocount -= ret; } if (ctx->odone) return 1; /* Compress some more */ /* Reset buffer */ ctx->optr = ctx->obuf; zout->next_out = ctx->obuf; zout->avail_out = ctx->obufsize; /* Compress some more */ ret = deflate(zout, Z_FINISH); if (ret == Z_STREAM_END) ctx->odone = 1; else if (ret != Z_OK) { ERR_raise_data(ERR_LIB_COMP, COMP_R_ZLIB_DEFLATE_ERROR, "zlib error: %s", zError(ret)); return 0; } ctx->ocount = ctx->obufsize - zout->avail_out; } } static long bio_zlib_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO_ZLIB_CTX *ctx; int ret, *ip; int ibs, obs; BIO *next = BIO_next(b); if (next == NULL) return 0; ctx = BIO_get_data(b); switch (cmd) { case BIO_CTRL_RESET: ctx->ocount = 0; ctx->odone = 0; ret = 1; break; case BIO_CTRL_FLUSH: ret = bio_zlib_flush(b); if (ret > 0) ret = BIO_flush(next); break; case BIO_C_SET_BUFF_SIZE: ibs = -1; obs = -1; if (ptr != NULL) { ip = ptr; if (*ip == 0) ibs = (int)num; else obs = (int)num; } else { ibs = (int)num; obs = ibs; } if (ibs != -1) { OPENSSL_free(ctx->ibuf); ctx->ibuf = NULL; ctx->ibufsize = ibs; } if (obs != -1) { OPENSSL_free(ctx->obuf); ctx->obuf = NULL; ctx->obufsize = obs; } ret = 1; break; case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_WPENDING: if (ctx->obuf == NULL) return 0; if (ctx->odone) { ret = ctx->ocount; } else { ret = ctx->ocount; if (ret == 0) /* Unknown amount pending but we are not finished */ ret = 1; } if (ret == 0) ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_PENDING: ret = ctx->zin.avail_in; if (ret == 0) ret = BIO_ctrl(next, cmd, num, ptr); break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static long bio_zlib_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_callback_ctrl(next, cmd, fp); } #endif
20,101
26.842105
83
c
openssl
openssl-master/crypto/comp/c_zstd.c
/* * Copyright 1998-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 * * Uses zstd compression library from https://github.com/facebook/zstd * Requires version 1.4.x (latest as of this writing is 1.4.5) * Using custom free functions require static linking, so that is disabled when * using the shared library. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/objects.h> #include "internal/comp.h" #include <openssl/err.h> #include "crypto/cryptlib.h" #include "internal/bio.h" #include "internal/thread_once.h" #include "comp_local.h" COMP_METHOD *COMP_zstd(void); #ifdef OPENSSL_NO_ZSTD # undef ZSTD_SHARED #else # ifndef ZSTD_SHARED # define ZSTD_STATIC_LINKING_ONLY # endif # include <zstd.h> /* Note: There is also a linux zstd.h file in the kernel source */ # ifndef ZSTD_H_235446 # error Wrong (i.e. linux) zstd.h included. # endif # if ZSTD_VERSION_MAJOR != 1 && ZSTD_VERSION_MINOR < 4 # error Expecting version 1.4 or greater of ZSTD # endif # ifndef ZSTD_SHARED /* memory allocations functions for zstd initialisation */ static void *zstd_alloc(void *opaque, size_t size) { return OPENSSL_zalloc(size); } static void zstd_free(void *opaque, void *address) { OPENSSL_free(address); } static ZSTD_customMem zstd_mem_funcs = { zstd_alloc, zstd_free, NULL }; # endif /* * When OpenSSL is built on Windows, we do not want to require that * the LIBZSTD.DLL be available in order for the OpenSSL DLLs to * work. Therefore, all ZSTD routines are loaded at run time * and we do not link to a .LIB file when ZSTD_SHARED is set. */ # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) # include <windows.h> # endif # ifdef ZSTD_SHARED # include "internal/dso.h" /* Function pointers */ typedef ZSTD_CStream* (*createCStream_ft)(void); typedef size_t (*initCStream_ft)(ZSTD_CStream*, int); typedef size_t (*freeCStream_ft)(ZSTD_CStream*); typedef size_t (*compressStream2_ft)(ZSTD_CCtx*, ZSTD_outBuffer*, ZSTD_inBuffer*, ZSTD_EndDirective); typedef size_t (*flushStream_ft)(ZSTD_CStream*, ZSTD_outBuffer*); typedef size_t (*endStream_ft)(ZSTD_CStream*, ZSTD_outBuffer*); typedef size_t (*compress_ft)(void*, size_t, const void*, size_t, int); typedef ZSTD_DStream* (*createDStream_ft)(void); typedef size_t (*initDStream_ft)(ZSTD_DStream*); typedef size_t (*freeDStream_ft)(ZSTD_DStream*); typedef size_t (*decompressStream_ft)(ZSTD_DStream*, ZSTD_outBuffer*, ZSTD_inBuffer*); typedef size_t (*decompress_ft)(void*, size_t, const void*, size_t); typedef unsigned (*isError_ft)(size_t); typedef const char* (*getErrorName_ft)(size_t); typedef size_t (*DStreamInSize_ft)(void); typedef size_t (*CStreamInSize_ft)(void); static createCStream_ft p_createCStream = NULL; static initCStream_ft p_initCStream = NULL; static freeCStream_ft p_freeCStream = NULL; static compressStream2_ft p_compressStream2 = NULL; static flushStream_ft p_flushStream = NULL; static endStream_ft p_endStream = NULL; static compress_ft p_compress = NULL; static createDStream_ft p_createDStream = NULL; static initDStream_ft p_initDStream = NULL; static freeDStream_ft p_freeDStream = NULL; static decompressStream_ft p_decompressStream = NULL; static decompress_ft p_decompress = NULL; static isError_ft p_isError = NULL; static getErrorName_ft p_getErrorName = NULL; static DStreamInSize_ft p_DStreamInSize = NULL; static CStreamInSize_ft p_CStreamInSize = NULL; static DSO *zstd_dso = NULL; # define ZSTD_createCStream p_createCStream # define ZSTD_initCStream p_initCStream # define ZSTD_freeCStream p_freeCStream # define ZSTD_compressStream2 p_compressStream2 # define ZSTD_flushStream p_flushStream # define ZSTD_endStream p_endStream # define ZSTD_compress p_compress # define ZSTD_createDStream p_createDStream # define ZSTD_initDStream p_initDStream # define ZSTD_freeDStream p_freeDStream # define ZSTD_decompressStream p_decompressStream # define ZSTD_decompress p_decompress # define ZSTD_isError p_isError # define ZSTD_getErrorName p_getErrorName # define ZSTD_DStreamInSize p_DStreamInSize # define ZSTD_CStreamInSize p_CStreamInSize # endif /* ifdef ZSTD_SHARED */ struct zstd_state { ZSTD_CStream *compressor; ZSTD_DStream *decompressor; }; static int zstd_stateful_init(COMP_CTX *ctx) { struct zstd_state *state = OPENSSL_zalloc(sizeof(*state)); if (state == NULL) return 0; # ifdef ZSTD_SHARED state->compressor = ZSTD_createCStream(); # else state->compressor = ZSTD_createCStream_advanced(zstd_mem_funcs); # endif if (state->compressor == NULL) goto err; ZSTD_initCStream(state->compressor, ZSTD_CLEVEL_DEFAULT); # ifdef ZSTD_SHARED state->decompressor = ZSTD_createDStream(); # else state->decompressor = ZSTD_createDStream_advanced(zstd_mem_funcs); # endif if (state->decompressor == NULL) goto err; ZSTD_initDStream(state->decompressor); ctx->data = state; return 1; err: ZSTD_freeCStream(state->compressor); ZSTD_freeDStream(state->decompressor); OPENSSL_free(state); return 0; } static void zstd_stateful_finish(COMP_CTX *ctx) { struct zstd_state *state = ctx->data; if (state != NULL) { ZSTD_freeCStream(state->compressor); ZSTD_freeDStream(state->decompressor); OPENSSL_free(state); ctx->data = NULL; } } static ossl_ssize_t zstd_stateful_compress_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { ZSTD_inBuffer inbuf; ZSTD_outBuffer outbuf; size_t ret; ossl_ssize_t fret; struct zstd_state *state = ctx->data; inbuf.src = in; inbuf.size = ilen; inbuf.pos = 0; outbuf.dst = out; outbuf.size = olen; outbuf.pos = 0; if (state == NULL) return -1; /* If input length is zero, end the stream/frame ? */ if (ilen == 0) { ret = ZSTD_endStream(state->compressor, &outbuf); if (ZSTD_isError(ret)) return -1; goto end; } /* * The finish API does not provide a final output buffer, * so each compress operation has to be ended, if all * the input data can't be accepted, or there is more output, * this has to be considered an error, since there is no more * output buffer space. */ do { ret = ZSTD_compressStream2(state->compressor, &outbuf, &inbuf, ZSTD_e_continue); if (ZSTD_isError(ret)) return -1; /* do I need to check for ret == 0 ? */ } while (inbuf.pos < inbuf.size); /* Did not consume all the data */ if (inbuf.pos < inbuf.size) return -1; ret = ZSTD_flushStream(state->compressor, &outbuf); if (ZSTD_isError(ret)) return -1; end: if (outbuf.pos > OSSL_SSIZE_MAX) return -1; fret = (ossl_ssize_t)outbuf.pos; if (fret < 0) return -1; return fret; } static ossl_ssize_t zstd_stateful_expand_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { ZSTD_inBuffer inbuf; ZSTD_outBuffer outbuf; size_t ret; ossl_ssize_t fret; struct zstd_state *state = ctx->data; inbuf.src = in; inbuf.size = ilen; inbuf.pos = 0; outbuf.dst = out; outbuf.size = olen; outbuf.pos = 0; if (state == NULL) return -1; if (ilen == 0) return 0; do { ret = ZSTD_decompressStream(state->decompressor, &outbuf, &inbuf); if (ZSTD_isError(ret)) return -1; /* If we completed a frame, and there's more data, try again */ } while (ret == 0 && inbuf.pos < inbuf.size); /* Did not consume all the data */ if (inbuf.pos < inbuf.size) return -1; if (outbuf.pos > OSSL_SSIZE_MAX) return -1; fret = (ossl_ssize_t)outbuf.pos; if (fret < 0) return -1; return fret; } static COMP_METHOD zstd_stateful_method = { NID_zstd, LN_zstd, zstd_stateful_init, zstd_stateful_finish, zstd_stateful_compress_block, zstd_stateful_expand_block }; static int zstd_oneshot_init(COMP_CTX *ctx) { return 1; } static void zstd_oneshot_finish(COMP_CTX *ctx) { } static ossl_ssize_t zstd_oneshot_compress_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { size_t out_size; ossl_ssize_t ret; if (ilen == 0) return 0; /* Note: uses STDLIB memory allocators */ out_size = ZSTD_compress(out, olen, in, ilen, ZSTD_CLEVEL_DEFAULT); if (ZSTD_isError(out_size)) return -1; if (out_size > OSSL_SSIZE_MAX) return -1; ret = (ossl_ssize_t)out_size; if (ret < 0) return -1; return ret; } static ossl_ssize_t zstd_oneshot_expand_block(COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen) { size_t out_size; ossl_ssize_t ret; if (ilen == 0) return 0; /* Note: uses STDLIB memory allocators */ out_size = ZSTD_decompress(out, olen, in, ilen); if (ZSTD_isError(out_size)) return -1; if (out_size > OSSL_SSIZE_MAX) return -1; ret = (ossl_ssize_t)out_size; if (ret < 0) return -1; return ret; } static COMP_METHOD zstd_oneshot_method = { NID_zstd, LN_zstd, zstd_oneshot_init, zstd_oneshot_finish, zstd_oneshot_compress_block, zstd_oneshot_expand_block }; static CRYPTO_ONCE zstd_once = CRYPTO_ONCE_STATIC_INIT; DEFINE_RUN_ONCE_STATIC(ossl_comp_zstd_init) { # ifdef ZSTD_SHARED # if defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_WIN32) # define LIBZSTD "LIBZSTD" # else # define LIBZSTD "zstd" # endif zstd_dso = DSO_load(NULL, LIBZSTD, NULL, 0); if (zstd_dso != NULL) { p_createCStream = (createCStream_ft)DSO_bind_func(zstd_dso, "ZSTD_createCStream"); p_initCStream = (initCStream_ft)DSO_bind_func(zstd_dso, "ZSTD_initCStream"); p_freeCStream = (freeCStream_ft)DSO_bind_func(zstd_dso, "ZSTD_freeCStream"); p_compressStream2 = (compressStream2_ft)DSO_bind_func(zstd_dso, "ZSTD_compressStream2"); p_flushStream = (flushStream_ft)DSO_bind_func(zstd_dso, "ZSTD_flushStream"); p_endStream = (endStream_ft)DSO_bind_func(zstd_dso, "ZSTD_endStream"); p_compress = (compress_ft)DSO_bind_func(zstd_dso, "ZSTD_compress"); p_createDStream = (createDStream_ft)DSO_bind_func(zstd_dso, "ZSTD_createDStream"); p_initDStream = (initDStream_ft)DSO_bind_func(zstd_dso, "ZSTD_initDStream"); p_freeDStream = (freeDStream_ft)DSO_bind_func(zstd_dso, "ZSTD_freeDStream"); p_decompressStream = (decompressStream_ft)DSO_bind_func(zstd_dso, "ZSTD_decompressStream"); p_decompress = (decompress_ft)DSO_bind_func(zstd_dso, "ZSTD_decompress"); p_isError = (isError_ft)DSO_bind_func(zstd_dso, "ZSTD_isError"); p_getErrorName = (getErrorName_ft)DSO_bind_func(zstd_dso, "ZSTD_getErrorName"); p_DStreamInSize = (DStreamInSize_ft)DSO_bind_func(zstd_dso, "ZSTD_DStreamInSize"); p_CStreamInSize = (CStreamInSize_ft)DSO_bind_func(zstd_dso, "ZSTD_CStreamInSize"); } if (p_createCStream == NULL || p_initCStream == NULL || p_freeCStream == NULL || p_compressStream2 == NULL || p_flushStream == NULL || p_endStream == NULL || p_compress == NULL || p_createDStream == NULL || p_initDStream == NULL || p_freeDStream == NULL || p_decompressStream == NULL || p_decompress == NULL || p_isError == NULL || p_getErrorName == NULL || p_DStreamInSize == NULL || p_CStreamInSize == NULL) { ossl_comp_zstd_cleanup(); return 0; } # endif return 1; } #endif /* ifndef ZSTD / else */ COMP_METHOD *COMP_zstd(void) { COMP_METHOD *meth = NULL; #ifndef OPENSSL_NO_ZSTD if (RUN_ONCE(&zstd_once, ossl_comp_zstd_init)) meth = &zstd_stateful_method; #endif return meth; } COMP_METHOD *COMP_zstd_oneshot(void) { COMP_METHOD *meth = NULL; #ifndef OPENSSL_NO_ZSTD if (RUN_ONCE(&zstd_once, ossl_comp_zstd_init)) meth = &zstd_oneshot_method; #endif return meth; } /* Also called from OPENSSL_cleanup() */ void ossl_comp_zstd_cleanup(void) { #ifdef ZSTD_SHARED DSO_free(zstd_dso); zstd_dso = NULL; p_createCStream = NULL; p_initCStream = NULL; p_freeCStream = NULL; p_compressStream2 = NULL; p_flushStream = NULL; p_endStream = NULL; p_compress = NULL; p_createDStream = NULL; p_initDStream = NULL; p_freeDStream = NULL; p_decompressStream = NULL; p_decompress = NULL; p_isError = NULL; p_getErrorName = NULL; p_DStreamInSize = NULL; p_CStreamInSize = NULL; #endif } #ifndef OPENSSL_NO_ZSTD /* Zstd-based compression/decompression filter BIO */ typedef struct { struct { /* input structure */ ZSTD_DStream *state; ZSTD_inBuffer inbuf; /* has const src */ size_t bufsize; void* buffer; } decompress; struct { /* output structure */ ZSTD_CStream *state; ZSTD_outBuffer outbuf; size_t bufsize; size_t write_pos; } compress; } BIO_ZSTD_CTX; # define ZSTD_DEFAULT_BUFSIZE 1024 static int bio_zstd_new(BIO *bi); static int bio_zstd_free(BIO *bi); static int bio_zstd_read(BIO *b, char *out, int outl); static int bio_zstd_write(BIO *b, const char *in, int inl); static long bio_zstd_ctrl(BIO *b, int cmd, long num, void *ptr); static long bio_zstd_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp); static const BIO_METHOD bio_meth_zstd = { BIO_TYPE_COMP, "zstd", /* TODO: Convert to new style write function */ bwrite_conv, bio_zstd_write, /* TODO: Convert to new style read function */ bread_conv, bio_zstd_read, NULL, /* bio_zstd_puts, */ NULL, /* bio_zstd_gets, */ bio_zstd_ctrl, bio_zstd_new, bio_zstd_free, bio_zstd_callback_ctrl }; #endif const BIO_METHOD *BIO_f_zstd(void) { #ifndef OPENSSL_NO_ZSTD if (RUN_ONCE(&zstd_once, ossl_comp_zstd_init)) return &bio_meth_zstd; #endif return NULL; } #ifndef OPENSSL_NO_ZSTD static int bio_zstd_new(BIO *bi) { BIO_ZSTD_CTX *ctx; # ifdef ZSTD_SHARED (void)COMP_zstd(); if (zstd_dso == NULL) { ERR_raise(ERR_LIB_COMP, COMP_R_ZSTD_NOT_SUPPORTED); return 0; } # endif ctx = OPENSSL_zalloc(sizeof(*ctx)); if (ctx == NULL) { ERR_raise(ERR_LIB_COMP, ERR_R_MALLOC_FAILURE); return 0; } # ifdef ZSTD_SHARED ctx->decompress.state = ZSTD_createDStream(); # else ctx->decompress.state = ZSTD_createDStream_advanced(zstd_mem_funcs); # endif if (ctx->decompress.state == NULL) goto err; ZSTD_initDStream(ctx->decompress.state); ctx->decompress.bufsize = ZSTD_DStreamInSize(); # ifdef ZSTD_SHARED ctx->compress.state = ZSTD_createCStream(); # else ctx->compress.state = ZSTD_createCStream_advanced(zstd_mem_funcs); # endif if (ctx->compress.state == NULL) goto err; ZSTD_initCStream(ctx->compress.state, ZSTD_CLEVEL_DEFAULT); ctx->compress.bufsize = ZSTD_CStreamInSize(); BIO_set_init(bi, 1); BIO_set_data(bi, ctx); return 1; err: ERR_raise(ERR_LIB_COMP, ERR_R_MALLOC_FAILURE); ZSTD_freeDStream(ctx->decompress.state); ZSTD_freeCStream(ctx->compress.state); OPENSSL_free(ctx); return 0; } static int bio_zstd_free(BIO *bi) { BIO_ZSTD_CTX *ctx; if (bi == NULL) return 0; ctx = BIO_get_data(bi); if (ctx != NULL) { ZSTD_freeDStream(ctx->decompress.state); OPENSSL_free(ctx->decompress.buffer); ZSTD_freeCStream(ctx->compress.state); OPENSSL_free(ctx->compress.outbuf.dst); OPENSSL_free(ctx); } BIO_set_data(bi, NULL); BIO_set_init(bi, 0); return 1; } static int bio_zstd_read(BIO *b, char *out, int outl) { BIO_ZSTD_CTX *ctx; size_t zret; int ret; ZSTD_outBuffer outBuf; BIO *next = BIO_next(b); if (out == NULL || outl <= 0) return 0; ctx = BIO_get_data(b); BIO_clear_retry_flags(b); if (ctx->decompress.buffer == NULL) { ctx->decompress.buffer = OPENSSL_malloc(ctx->decompress.bufsize); if (ctx->decompress.buffer == NULL) { ERR_raise(ERR_LIB_COMP, ERR_R_MALLOC_FAILURE); return 0; } ctx->decompress.inbuf.src = ctx->decompress.buffer; ctx->decompress.inbuf.size = 0; ctx->decompress.inbuf.pos = 0; } /* Copy output data directly to supplied buffer */ outBuf.dst = out; outBuf.size = (size_t)outl; outBuf.pos = 0; for (;;) { /* Decompress while data available */ do { zret = ZSTD_decompressStream(ctx->decompress.state, &outBuf, &ctx->decompress.inbuf); if (ZSTD_isError(zret)) { ERR_raise(ERR_LIB_COMP, COMP_R_ZSTD_DECOMPRESS_ERROR); ERR_add_error_data(1, ZSTD_getErrorName(zret)); return -1; } /* No more output space */ if (outBuf.pos == outBuf.size) return outBuf.pos; } while (ctx->decompress.inbuf.pos < ctx->decompress.inbuf.size); /* * No data in input buffer try to read some in, if an error then * return the total data read. */ ret = BIO_read(next, ctx->decompress.buffer, ctx->decompress.bufsize); if (ret <= 0) { BIO_copy_next_retry(b); if (ret < 0 && outBuf.pos == 0) return ret; return outBuf.pos; } ctx->decompress.inbuf.size = ret; ctx->decompress.inbuf.pos = 0; } } static int bio_zstd_write(BIO *b, const char *in, int inl) { BIO_ZSTD_CTX *ctx; size_t zret; ZSTD_inBuffer inBuf; int ret; int done = 0; BIO *next = BIO_next(b); if (in == NULL || inl <= 0) return 0; ctx = BIO_get_data(b); BIO_clear_retry_flags(b); if (ctx->compress.outbuf.dst == NULL) { ctx->compress.outbuf.dst = OPENSSL_malloc(ctx->compress.bufsize); if (ctx->compress.outbuf.dst == NULL) { ERR_raise(ERR_LIB_COMP, ERR_R_MALLOC_FAILURE); return 0; } ctx->compress.outbuf.size = ctx->compress.bufsize; ctx->compress.outbuf.pos = 0; ctx->compress.write_pos = 0; } /* Obtain input data directly from supplied buffer */ inBuf.src = in; inBuf.size = inl; inBuf.pos = 0; for (;;) { /* If data in output buffer write it first */ while (ctx->compress.write_pos < ctx->compress.outbuf.pos) { ret = BIO_write(next, (unsigned char*)ctx->compress.outbuf.dst + ctx->compress.write_pos, ctx->compress.outbuf.pos - ctx->compress.write_pos); if (ret <= 0) { BIO_copy_next_retry(b); if (ret < 0 && inBuf.pos == 0) return ret; return inBuf.pos; } ctx->compress.write_pos += ret; } /* Have we consumed all supplied data? */ if (done) return inBuf.pos; /* Reset buffer */ ctx->compress.outbuf.pos = 0; ctx->compress.outbuf.size = ctx->compress.bufsize; ctx->compress.write_pos = 0; /* Compress some more */ zret = ZSTD_compressStream2(ctx->compress.state, &ctx->compress.outbuf, &inBuf, ZSTD_e_end); if (ZSTD_isError(zret)) { ERR_raise(ERR_LIB_COMP, COMP_R_ZSTD_COMPRESS_ERROR); ERR_add_error_data(1, ZSTD_getErrorName(zret)); return 0; } else if (zret == 0) { done = 1; } } } static int bio_zstd_flush(BIO *b) { BIO_ZSTD_CTX *ctx; size_t zret; int ret; BIO *next = BIO_next(b); ctx = BIO_get_data(b); /* If no data written or already flush show success */ if (ctx->compress.outbuf.dst == NULL) return 1; BIO_clear_retry_flags(b); /* No more input data */ ctx->compress.outbuf.pos = 0; ctx->compress.outbuf.size = ctx->compress.bufsize; ctx->compress.write_pos = 0; for (;;) { /* If data in output buffer write it first */ while (ctx->compress.write_pos < ctx->compress.outbuf.pos) { ret = BIO_write(next, (unsigned char*)ctx->compress.outbuf.dst + ctx->compress.write_pos, ctx->compress.outbuf.pos - ctx->compress.write_pos); if (ret <= 0) { BIO_copy_next_retry(b); return ret; } ctx->compress.write_pos += ret; } /* Reset buffer */ ctx->compress.outbuf.pos = 0; ctx->compress.outbuf.size = ctx->compress.bufsize; ctx->compress.write_pos = 0; /* Compress some more */ zret = ZSTD_flushStream(ctx->compress.state, &ctx->compress.outbuf); if (ZSTD_isError(zret)) { ERR_raise(ERR_LIB_COMP, COMP_R_ZSTD_DECODE_ERROR); ERR_add_error_data(1, ZSTD_getErrorName(zret)); return 0; } if (zret == 0) return 1; } } static long bio_zstd_ctrl(BIO *b, int cmd, long num, void *ptr) { BIO_ZSTD_CTX *ctx; int ret = 0, *ip; size_t ibs, obs; unsigned char *tmp; BIO *next = BIO_next(b); if (next == NULL) return 0; ctx = BIO_get_data(b); switch (cmd) { case BIO_CTRL_RESET: ctx->compress.write_pos = 0; ctx->compress.bufsize = 0; ret = 1; break; case BIO_CTRL_FLUSH: ret = bio_zstd_flush(b); if (ret > 0) ret = BIO_flush(next); break; case BIO_C_SET_BUFF_SIZE: ibs = ctx->decompress.bufsize; obs = ctx->compress.bufsize; if (ptr != NULL) { ip = ptr; if (*ip == 0) ibs = (size_t)num; else obs = (size_t)num; } else { obs = ibs = (size_t)num; } if (ibs > 0 && ibs != ctx->decompress.bufsize) { if (ctx->decompress.buffer != NULL) { tmp = OPENSSL_realloc(ctx->decompress.buffer, ibs); if (tmp == NULL) return 0; if (ctx->decompress.inbuf.src == ctx->decompress.buffer) ctx->decompress.inbuf.src = tmp; ctx->decompress.buffer = tmp; } ctx->decompress.bufsize = ibs; } if (obs > 0 && obs != ctx->compress.bufsize) { if (ctx->compress.outbuf.dst != NULL) { tmp = OPENSSL_realloc(ctx->compress.outbuf.dst, obs); if (tmp == NULL) return 0; ctx->compress.outbuf.dst = tmp; } ctx->compress.bufsize = obs; } ret = 1; break; case BIO_C_DO_STATE_MACHINE: BIO_clear_retry_flags(b); ret = BIO_ctrl(next, cmd, num, ptr); BIO_copy_next_retry(b); break; case BIO_CTRL_WPENDING: if (ctx->compress.outbuf.pos < ctx->compress.outbuf.size) ret = 1; else ret = BIO_ctrl(next, cmd, num, ptr); break; case BIO_CTRL_PENDING: if (ctx->decompress.inbuf.pos < ctx->decompress.inbuf.size) ret = 1; else ret = BIO_ctrl(next, cmd, num, ptr); break; default: ret = BIO_ctrl(next, cmd, num, ptr); break; } return ret; } static long bio_zstd_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp) { BIO *next = BIO_next(b); if (next == NULL) return 0; return BIO_callback_ctrl(next, cmd, fp); } #endif
24,402
27.913507
101
c
openssl
openssl-master/crypto/comp/comp_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/comperr.h> #include "crypto/comperr.h" #ifndef OPENSSL_NO_COMP # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA COMP_str_reasons[] = { {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_BROTLI_DECODE_ERROR), "brotli decode error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_BROTLI_ENCODE_ERROR), "brotli encode error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_BROTLI_NOT_SUPPORTED), "brotli not supported"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZLIB_DEFLATE_ERROR), "zlib deflate error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZLIB_INFLATE_ERROR), "zlib inflate error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZLIB_NOT_SUPPORTED), "zlib not supported"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZSTD_COMPRESS_ERROR), "zstd compress error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZSTD_DECODE_ERROR), "zstd decode error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZSTD_DECOMPRESS_ERROR), "zstd decompress error"}, {ERR_PACK(ERR_LIB_COMP, 0, COMP_R_ZSTD_NOT_SUPPORTED), "zstd not supported"}, {0, NULL} }; # endif int ossl_err_load_COMP_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(COMP_str_reasons[0].error) == NULL) ERR_load_strings_const(COMP_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
1,706
30.036364
79
c
openssl
openssl-master/crypto/comp/comp_lib.c
/* * Copyright 1998-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <openssl/objects.h> #include <openssl/comp.h> #include <openssl/err.h> #include "comp_local.h" COMP_CTX *COMP_CTX_new(COMP_METHOD *meth) { COMP_CTX *ret; if (meth == NULL) return NULL; if ((ret = OPENSSL_zalloc(sizeof(*ret))) == NULL) return NULL; ret->meth = meth; if ((ret->meth->init != NULL) && !ret->meth->init(ret)) { OPENSSL_free(ret); ret = NULL; } return ret; } const COMP_METHOD *COMP_CTX_get_method(const COMP_CTX *ctx) { return ctx->meth; } int COMP_get_type(const COMP_METHOD *meth) { if (meth == NULL) return NID_undef; return meth->type; } const char *COMP_get_name(const COMP_METHOD *meth) { if (meth == NULL) return NULL; return meth->name; } void COMP_CTX_free(COMP_CTX *ctx) { if (ctx == NULL) return; if (ctx->meth->finish != NULL) ctx->meth->finish(ctx); OPENSSL_free(ctx); } int COMP_compress_block(COMP_CTX *ctx, unsigned char *out, int olen, unsigned char *in, int ilen) { int ret; if (ctx->meth->compress == NULL) { return -1; } ret = ctx->meth->compress(ctx, out, olen, in, ilen); if (ret > 0) { ctx->compress_in += ilen; ctx->compress_out += ret; } return ret; } int COMP_expand_block(COMP_CTX *ctx, unsigned char *out, int olen, unsigned char *in, int ilen) { int ret; if (ctx->meth->expand == NULL) { return -1; } ret = ctx->meth->expand(ctx, out, olen, in, ilen); if (ret > 0) { ctx->expand_in += ilen; ctx->expand_out += ret; } return ret; } int COMP_CTX_get_type(const COMP_CTX* comp) { return comp->meth ? comp->meth->type : NID_undef; }
2,166
20.888889
74
c
openssl
openssl-master/crypto/comp/comp_local.h
/* * Copyright 2015-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 comp_method_st { int type; /* NID for compression library */ const char *name; /* A text string to identify the library */ int (*init) (COMP_CTX *ctx); void (*finish) (COMP_CTX *ctx); ossl_ssize_t (*compress) (COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen); ossl_ssize_t (*expand) (COMP_CTX *ctx, unsigned char *out, size_t olen, unsigned char *in, size_t ilen); }; struct comp_ctx_st { struct comp_method_st *meth; unsigned long compress_in; unsigned long compress_out; unsigned long expand_in; unsigned long expand_out; void* data; };
1,105
34.677419
75
h
openssl
openssl-master/crypto/conf/conf_api.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 */ /* Part of the code in here was originally in conf.c, which is now removed */ #include "internal/e_os.h" #include "internal/cryptlib.h" #include <stdlib.h> #include <string.h> #include <openssl/conf.h> #include <openssl/conf_api.h> #include "conf_local.h" static void value_free_hash(const CONF_VALUE *a, LHASH_OF(CONF_VALUE) *conf); static void value_free_stack_doall(CONF_VALUE *a); CONF_VALUE *_CONF_get_section(const CONF *conf, const char *section) { CONF_VALUE vv; if (conf == NULL || section == NULL) return NULL; vv.name = NULL; vv.section = (char *)section; return conf->data != NULL ? lh_CONF_VALUE_retrieve(conf->data, &vv) : NULL; } STACK_OF(CONF_VALUE) *_CONF_get_section_values(const CONF *conf, const char *section) { CONF_VALUE *v; v = _CONF_get_section(conf, section); if (v == NULL) return NULL; return ((STACK_OF(CONF_VALUE) *)v->value); } int _CONF_add_string(CONF *conf, CONF_VALUE *section, CONF_VALUE *value) { CONF_VALUE *v = NULL; STACK_OF(CONF_VALUE) *ts; ts = (STACK_OF(CONF_VALUE) *)section->value; value->section = section->section; if (!sk_CONF_VALUE_push(ts, value)) return 0; v = lh_CONF_VALUE_insert(conf->data, value); if (v != NULL) { (void)sk_CONF_VALUE_delete_ptr(ts, v); OPENSSL_free(v->name); OPENSSL_free(v->value); OPENSSL_free(v); } return 1; } char *_CONF_get_string(const CONF *conf, const char *section, const char *name) { CONF_VALUE *v, vv; char *p; if (name == NULL) return NULL; if (conf == NULL) return ossl_safe_getenv(name); if (conf->data == NULL) return NULL; if (section != NULL) { vv.name = (char *)name; vv.section = (char *)section; v = lh_CONF_VALUE_retrieve(conf->data, &vv); if (v != NULL) return v->value; if (strcmp(section, "ENV") == 0) { p = ossl_safe_getenv(name); if (p != NULL) return p; } } vv.section = "default"; vv.name = (char *)name; v = lh_CONF_VALUE_retrieve(conf->data, &vv); if (v == NULL) return NULL; return v->value; } static unsigned long conf_value_hash(const CONF_VALUE *v) { return (OPENSSL_LH_strhash(v->section) << 2) ^ OPENSSL_LH_strhash(v->name); } static int conf_value_cmp(const CONF_VALUE *a, const CONF_VALUE *b) { int i; if (a->section != b->section) { i = strcmp(a->section, b->section); if (i != 0) return i; } if (a->name != NULL && b->name != NULL) return strcmp(a->name, b->name); if (a->name == b->name) return 0; return (a->name == NULL) ? -1 : 1; } int _CONF_new_data(CONF *conf) { if (conf == NULL) return 0; if (conf->data == NULL) { conf->data = lh_CONF_VALUE_new(conf_value_hash, conf_value_cmp); if (conf->data == NULL) return 0; } return 1; } typedef LHASH_OF(CONF_VALUE) LH_CONF_VALUE; IMPLEMENT_LHASH_DOALL_ARG_CONST(CONF_VALUE, LH_CONF_VALUE); void _CONF_free_data(CONF *conf) { if (conf == NULL) return; OPENSSL_free(conf->includedir); if (conf->data == NULL) return; /* evil thing to make sure the 'OPENSSL_free()' works as expected */ lh_CONF_VALUE_set_down_load(conf->data, 0); lh_CONF_VALUE_doall_LH_CONF_VALUE(conf->data, value_free_hash, conf->data); /* * We now have only 'section' entries in the hash table. Due to problems * with */ lh_CONF_VALUE_doall(conf->data, value_free_stack_doall); lh_CONF_VALUE_free(conf->data); } static void value_free_hash(const CONF_VALUE *a, LHASH_OF(CONF_VALUE) *conf) { if (a->name != NULL) (void)lh_CONF_VALUE_delete(conf, a); } static void value_free_stack_doall(CONF_VALUE *a) { CONF_VALUE *vv; STACK_OF(CONF_VALUE) *sk; int i; if (a->name != NULL) return; sk = (STACK_OF(CONF_VALUE) *)a->value; for (i = sk_CONF_VALUE_num(sk) - 1; i >= 0; i--) { vv = sk_CONF_VALUE_value(sk, i); OPENSSL_free(vv->value); OPENSSL_free(vv->name); OPENSSL_free(vv); } sk_CONF_VALUE_free(sk); OPENSSL_free(a->section); OPENSSL_free(a); } CONF_VALUE *_CONF_new_section(CONF *conf, const char *section) { STACK_OF(CONF_VALUE) *sk = NULL; int i; CONF_VALUE *v = NULL, *vv; if ((sk = sk_CONF_VALUE_new_null()) == NULL) goto err; if ((v = OPENSSL_malloc(sizeof(*v))) == NULL) goto err; i = strlen(section) + 1; if ((v->section = OPENSSL_malloc(i)) == NULL) goto err; memcpy(v->section, section, i); v->name = NULL; v->value = (char *)sk; vv = lh_CONF_VALUE_insert(conf->data, v); if (vv != NULL || lh_CONF_VALUE_error(conf->data) > 0) goto err; return v; err: sk_CONF_VALUE_free(sk); if (v != NULL) OPENSSL_free(v->section); OPENSSL_free(v); return NULL; }
5,429
24.255814
79
c
openssl
openssl-master/crypto/conf/conf_def.h
/* * WARNING: do not edit! * Generated by crypto/conf/keysets.pl * * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved. * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #define CONF_NUMBER 1 #define CONF_UPPER 2 #define CONF_LOWER 4 #define CONF_UNDER 256 #define CONF_PUNCT 512 #define CONF_WS 16 #define CONF_ESC 32 #define CONF_QUOTE 64 #define CONF_DQUOTE 1024 #define CONF_COMMENT 128 #define CONF_FCOMMENT 2048 #define CONF_DOLLAR 4096 #define CONF_EOF 8 #define CONF_ALPHA (CONF_UPPER|CONF_LOWER) #define CONF_ALNUM (CONF_ALPHA|CONF_NUMBER|CONF_UNDER) #define CONF_ALNUM_PUNCT (CONF_ALPHA|CONF_NUMBER|CONF_UNDER|CONF_PUNCT) #define IS_COMMENT(conf,c) is_keytype(conf, c, CONF_COMMENT) #define IS_FCOMMENT(conf,c) is_keytype(conf, c, CONF_FCOMMENT) #define IS_EOF(conf,c) is_keytype(conf, c, CONF_EOF) #define IS_ESC(conf,c) is_keytype(conf, c, CONF_ESC) #define IS_NUMBER(conf,c) is_keytype(conf, c, CONF_NUMBER) #define IS_WS(conf,c) is_keytype(conf, c, CONF_WS) #define IS_ALNUM(conf,c) is_keytype(conf, c, CONF_ALNUM) #define IS_ALNUM_PUNCT(conf,c) is_keytype(conf, c, CONF_ALNUM_PUNCT) #define IS_QUOTE(conf,c) is_keytype(conf, c, CONF_QUOTE) #define IS_DQUOTE(conf,c) is_keytype(conf, c, CONF_DQUOTE) #define IS_DOLLAR(conf,c) is_keytype(conf, c, CONF_DOLLAR) static const unsigned short CONF_type_default[128] = { 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0010, 0x0010, 0x0000, 0x0000, 0x0010, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0010, 0x0200, 0x0040, 0x0080, 0x1000, 0x0200, 0x0200, 0x0040, 0x0000, 0x0000, 0x0200, 0x0200, 0x0200, 0x0200, 0x0200, 0x0200, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0200, 0x0000, 0x0000, 0x0000, 0x0200, 0x0200, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0000, 0x0020, 0x0000, 0x0200, 0x0100, 0x0040, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0000, 0x0200, 0x0000, 0x0200, 0x0000, }; #ifndef OPENSSL_NO_DEPRECATED_3_0 static const unsigned short CONF_type_win32[128] = { 0x0008, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0010, 0x0010, 0x0000, 0x0000, 0x0010, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0010, 0x0200, 0x0400, 0x0000, 0x1000, 0x0200, 0x0200, 0x0000, 0x0000, 0x0000, 0x0200, 0x0200, 0x0200, 0x0200, 0x0200, 0x0200, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0001, 0x0000, 0x0A00, 0x0000, 0x0000, 0x0000, 0x0200, 0x0200, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0002, 0x0000, 0x0000, 0x0000, 0x0200, 0x0100, 0x0000, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0004, 0x0000, 0x0200, 0x0000, 0x0200, 0x0000, }; #endif
4,003
48.432099
74
h
openssl
openssl-master/crypto/conf/conf_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/conferr.h> #include "crypto/conferr.h" #ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA CONF_str_reasons[] = { {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_ERROR_LOADING_DSO), "error loading dso"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_INVALID_PRAGMA), "invalid pragma"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_LIST_CANNOT_BE_NULL), "list cannot be null"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_MANDATORY_BRACES_IN_VARIABLE_EXPANSION), "mandatory braces in variable expansion"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_MISSING_CLOSE_SQUARE_BRACKET), "missing close square bracket"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_MISSING_EQUAL_SIGN), "missing equal sign"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_MISSING_INIT_FUNCTION), "missing init function"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_MODULE_INITIALIZATION_ERROR), "module initialization error"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NO_CLOSE_BRACE), "no close brace"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NO_CONF), "no conf"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NO_CONF_OR_ENVIRONMENT_VARIABLE), "no conf or environment variable"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NO_SECTION), "no section"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NO_SUCH_FILE), "no such file"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NO_VALUE), "no value"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_NUMBER_TOO_LARGE), "number too large"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_OPENSSL_CONF_REFERENCES_MISSING_SECTION), "openssl conf references missing section"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_RECURSIVE_DIRECTORY_INCLUDE), "recursive directory include"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_RELATIVE_PATH), "relative path"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_SSL_COMMAND_SECTION_EMPTY), "ssl command section empty"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_SSL_COMMAND_SECTION_NOT_FOUND), "ssl command section not found"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_SSL_SECTION_EMPTY), "ssl section empty"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_SSL_SECTION_NOT_FOUND), "ssl section not found"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_UNABLE_TO_CREATE_NEW_SECTION), "unable to create new section"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_UNKNOWN_MODULE_NAME), "unknown module name"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_VARIABLE_EXPANSION_TOO_LONG), "variable expansion too long"}, {ERR_PACK(ERR_LIB_CONF, 0, CONF_R_VARIABLE_HAS_NO_VALUE), "variable has no value"}, {0, NULL} }; #endif int ossl_err_load_CONF_strings(void) { #ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(CONF_str_reasons[0].error) == NULL) ERR_load_strings_const(CONF_str_reasons); #endif return 1; }
3,119
41.739726
79
c
openssl
openssl-master/crypto/conf/conf_lib.c
/* * Copyright 2000-2022 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include "internal/e_os.h" #include <stdio.h> #include <string.h> #include "internal/conf.h" #include "crypto/ctype.h" #include <openssl/crypto.h> #include <openssl/err.h> #include <openssl/conf.h> #include <openssl/conf_api.h> #include "conf_local.h" #include <openssl/lhash.h> static CONF_METHOD *default_CONF_method = NULL; /* Init a 'CONF' structure from an old LHASH */ void CONF_set_nconf(CONF *conf, LHASH_OF(CONF_VALUE) *hash) { if (default_CONF_method == NULL) default_CONF_method = NCONF_default(); default_CONF_method->init(conf); conf->data = hash; } /* * The following section contains the "CONF classic" functions, rewritten in * terms of the new CONF interface. */ int CONF_set_default_method(CONF_METHOD *meth) { default_CONF_method = meth; return 1; } LHASH_OF(CONF_VALUE) *CONF_load(LHASH_OF(CONF_VALUE) *conf, const char *file, long *eline) { LHASH_OF(CONF_VALUE) *ltmp; BIO *in = NULL; #ifdef OPENSSL_SYS_VMS in = BIO_new_file(file, "r"); #else in = BIO_new_file(file, "rb"); #endif if (in == NULL) { ERR_raise(ERR_LIB_CONF, ERR_R_SYS_LIB); return NULL; } ltmp = CONF_load_bio(conf, in, eline); BIO_free(in); return ltmp; } #ifndef OPENSSL_NO_STDIO LHASH_OF(CONF_VALUE) *CONF_load_fp(LHASH_OF(CONF_VALUE) *conf, FILE *fp, long *eline) { BIO *btmp; LHASH_OF(CONF_VALUE) *ltmp; if ((btmp = BIO_new_fp(fp, BIO_NOCLOSE)) == NULL) { ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB); return NULL; } ltmp = CONF_load_bio(conf, btmp, eline); BIO_free(btmp); return ltmp; } #endif LHASH_OF(CONF_VALUE) *CONF_load_bio(LHASH_OF(CONF_VALUE) *conf, BIO *bp, long *eline) { CONF ctmp; int ret; CONF_set_nconf(&ctmp, conf); ret = NCONF_load_bio(&ctmp, bp, eline); if (ret) return ctmp.data; return NULL; } STACK_OF(CONF_VALUE) *CONF_get_section(LHASH_OF(CONF_VALUE) *conf, const char *section) { if (conf == NULL) { return NULL; } else { CONF ctmp; CONF_set_nconf(&ctmp, conf); return NCONF_get_section(&ctmp, section); } } char *CONF_get_string(LHASH_OF(CONF_VALUE) *conf, const char *group, const char *name) { if (conf == NULL) { return NCONF_get_string(NULL, group, name); } else { CONF ctmp; CONF_set_nconf(&ctmp, conf); return NCONF_get_string(&ctmp, group, name); } } long CONF_get_number(LHASH_OF(CONF_VALUE) *conf, const char *group, const char *name) { int status; long result = 0; ERR_set_mark(); if (conf == NULL) { status = NCONF_get_number_e(NULL, group, name, &result); } else { CONF ctmp; CONF_set_nconf(&ctmp, conf); status = NCONF_get_number_e(&ctmp, group, name, &result); } ERR_pop_to_mark(); return status == 0 ? 0L : result; } void CONF_free(LHASH_OF(CONF_VALUE) *conf) { CONF ctmp; CONF_set_nconf(&ctmp, conf); NCONF_free_data(&ctmp); } #ifndef OPENSSL_NO_STDIO int CONF_dump_fp(LHASH_OF(CONF_VALUE) *conf, FILE *out) { BIO *btmp; int ret; if ((btmp = BIO_new_fp(out, BIO_NOCLOSE)) == NULL) { ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB); return 0; } ret = CONF_dump_bio(conf, btmp); BIO_free(btmp); return ret; } #endif int CONF_dump_bio(LHASH_OF(CONF_VALUE) *conf, BIO *out) { CONF ctmp; CONF_set_nconf(&ctmp, conf); return NCONF_dump_bio(&ctmp, out); } /* * The following section contains the "New CONF" functions. They are * completely centralised around a new CONF structure that may contain * basically anything, but at least a method pointer and a table of data. * These functions are also written in terms of the bridge functions used by * the "CONF classic" functions, for consistency. */ CONF *NCONF_new_ex(OSSL_LIB_CTX *libctx, CONF_METHOD *meth) { CONF *ret; if (meth == NULL) meth = NCONF_default(); ret = meth->create(meth); if (ret == NULL) { ERR_raise(ERR_LIB_CONF, ERR_R_CONF_LIB); return NULL; } ret->libctx = libctx; return ret; } CONF *NCONF_new(CONF_METHOD *meth) { return NCONF_new_ex(NULL, meth); } void NCONF_free(CONF *conf) { if (conf == NULL) return; conf->meth->destroy(conf); } void NCONF_free_data(CONF *conf) { if (conf == NULL) return; conf->meth->destroy_data(conf); } OSSL_LIB_CTX *NCONF_get0_libctx(const CONF *conf) { return conf->libctx; } typedef STACK_OF(OPENSSL_CSTRING) SECTION_NAMES; IMPLEMENT_LHASH_DOALL_ARG_CONST(CONF_VALUE, SECTION_NAMES); static void collect_section_name(const CONF_VALUE *v, SECTION_NAMES *names) { /* A section is a CONF_VALUE with name == NULL */ if (v->name == NULL) sk_OPENSSL_CSTRING_push(names, v->section); } static int section_name_cmp(OPENSSL_CSTRING const *a, OPENSSL_CSTRING const *b) { return strcmp(*a, *b); } STACK_OF(OPENSSL_CSTRING) *NCONF_get_section_names(const CONF *cnf) { SECTION_NAMES *names; if ((names = sk_OPENSSL_CSTRING_new(section_name_cmp)) == NULL) return NULL; lh_CONF_VALUE_doall_SECTION_NAMES(cnf->data, collect_section_name, names); sk_OPENSSL_CSTRING_sort(names); return names; } int NCONF_load(CONF *conf, const char *file, long *eline) { if (conf == NULL) { ERR_raise(ERR_LIB_CONF, CONF_R_NO_CONF); return 0; } return conf->meth->load(conf, file, eline); } #ifndef OPENSSL_NO_STDIO int NCONF_load_fp(CONF *conf, FILE *fp, long *eline) { BIO *btmp; int ret; if ((btmp = BIO_new_fp(fp, BIO_NOCLOSE)) == NULL) { ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB); return 0; } ret = NCONF_load_bio(conf, btmp, eline); BIO_free(btmp); return ret; } #endif int NCONF_load_bio(CONF *conf, BIO *bp, long *eline) { if (conf == NULL) { ERR_raise(ERR_LIB_CONF, CONF_R_NO_CONF); return 0; } return conf->meth->load_bio(conf, bp, eline); } STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf, const char *section) { if (conf == NULL) { ERR_raise(ERR_LIB_CONF, CONF_R_NO_CONF); return NULL; } if (section == NULL) { ERR_raise(ERR_LIB_CONF, CONF_R_NO_SECTION); return NULL; } return _CONF_get_section_values(conf, section); } char *NCONF_get_string(const CONF *conf, const char *group, const char *name) { char *s = _CONF_get_string(conf, group, name); /* * Since we may get a value from an environment variable even if conf is * NULL, let's check the value first */ if (s) return s; if (conf == NULL) { ERR_raise(ERR_LIB_CONF, CONF_R_NO_CONF_OR_ENVIRONMENT_VARIABLE); return NULL; } ERR_raise_data(ERR_LIB_CONF, CONF_R_NO_VALUE, "group=%s name=%s", group, name); return NULL; } static int default_is_number(const CONF *conf, char c) { return ossl_isdigit(c); } static int default_to_int(const CONF *conf, char c) { return (int)(c - '0'); } int NCONF_get_number_e(const CONF *conf, const char *group, const char *name, long *result) { char *str; long res; int (*is_number)(const CONF *, char) = &default_is_number; int (*to_int)(const CONF *, char) = &default_to_int; if (result == NULL) { ERR_raise(ERR_LIB_CONF, ERR_R_PASSED_NULL_PARAMETER); return 0; } str = NCONF_get_string(conf, group, name); if (str == NULL) return 0; if (conf != NULL) { if (conf->meth->is_number != NULL) is_number = conf->meth->is_number; if (conf->meth->to_int != NULL) to_int = conf->meth->to_int; } for (res = 0; is_number(conf, *str); str++) { const int d = to_int(conf, *str); if (res > (LONG_MAX - d) / 10L) { ERR_raise(ERR_LIB_CONF, CONF_R_NUMBER_TOO_LARGE); return 0; } res = res * 10 + d; } *result = res; return 1; } long _CONF_get_number(const CONF *conf, const char *section, const char *name) { int status; long result = 0; ERR_set_mark(); status = NCONF_get_number_e(conf, section, name, &result); ERR_pop_to_mark(); return status == 0 ? 0L : result; } #ifndef OPENSSL_NO_STDIO int NCONF_dump_fp(const CONF *conf, FILE *out) { BIO *btmp; int ret; if ((btmp = BIO_new_fp(out, BIO_NOCLOSE)) == NULL) { ERR_raise(ERR_LIB_CONF, ERR_R_BUF_LIB); return 0; } ret = NCONF_dump_bio(conf, btmp); BIO_free(btmp); return ret; } #endif int NCONF_dump_bio(const CONF *conf, BIO *out) { if (conf == NULL) { ERR_raise(ERR_LIB_CONF, CONF_R_NO_CONF); return 0; } return conf->meth->dump(conf, out); } /* * These routines call the C malloc/free, to avoid intermixing with * OpenSSL function pointers before the library is initialized. */ OPENSSL_INIT_SETTINGS *OPENSSL_INIT_new(void) { OPENSSL_INIT_SETTINGS *ret = malloc(sizeof(*ret)); if (ret == NULL) return NULL; memset(ret, 0, sizeof(*ret)); ret->flags = DEFAULT_CONF_MFLAGS; return ret; } #ifndef OPENSSL_NO_STDIO int OPENSSL_INIT_set_config_filename(OPENSSL_INIT_SETTINGS *settings, const char *filename) { char *newfilename = NULL; if (filename != NULL) { newfilename = strdup(filename); if (newfilename == NULL) return 0; } free(settings->filename); settings->filename = newfilename; return 1; } void OPENSSL_INIT_set_config_file_flags(OPENSSL_INIT_SETTINGS *settings, unsigned long flags) { settings->flags = flags; } int OPENSSL_INIT_set_config_appname(OPENSSL_INIT_SETTINGS *settings, const char *appname) { char *newappname = NULL; if (appname != NULL) { newappname = strdup(appname); if (newappname == NULL) return 0; } free(settings->appname); settings->appname = newappname; return 1; } #endif void OPENSSL_INIT_free(OPENSSL_INIT_SETTINGS *settings) { free(settings->filename); free(settings->appname); free(settings); }
10,807
21.946921
79
c
openssl
openssl-master/crypto/conf/conf_mall.c
/* * Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include <stdio.h> #include <openssl/crypto.h> #include "internal/cryptlib.h" #include <openssl/conf.h> #include <openssl/x509.h> #include <openssl/asn1.h> #include <openssl/engine.h> #include "internal/provider.h" #include "crypto/rand.h" #include "conf_local.h" /* Load all OpenSSL builtin modules */ void OPENSSL_load_builtin_modules(void) { /* Add builtin modules here */ ASN1_add_oid_module(); ASN1_add_stable_module(); #ifndef OPENSSL_NO_ENGINE ENGINE_add_conf_module(); #endif EVP_add_alg_module(); ossl_config_add_ssl_module(); ossl_provider_add_conf_module(); ossl_random_add_conf_module(); }
1,059
26.179487
74
c
openssl
openssl-master/crypto/conf/conf_mod.c
/* * Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* We need to use some engine deprecated APIs */ #define OPENSSL_SUPPRESS_DEPRECATED #include "internal/cryptlib.h" #include <stdio.h> #include <ctype.h> #include <openssl/crypto.h> #include "internal/conf.h" #include <openssl/conf_api.h> #include "internal/dso.h" #include "internal/thread_once.h" #include <openssl/x509.h> #include <openssl/trace.h> #include <openssl/engine.h> #include "conf_local.h" DEFINE_STACK_OF(CONF_MODULE) DEFINE_STACK_OF(CONF_IMODULE) #define DSO_mod_init_name "OPENSSL_init" #define DSO_mod_finish_name "OPENSSL_finish" /* * This structure contains a data about supported modules. entries in this * table correspond to either dynamic or static modules. */ struct conf_module_st { /* DSO of this module or NULL if static */ DSO *dso; /* Name of the module */ char *name; /* Init function */ conf_init_func *init; /* Finish function */ conf_finish_func *finish; /* Number of successfully initialized modules */ int links; void *usr_data; }; /* * This structure contains information about modules that have been * successfully initialized. There may be more than one entry for a given * module. */ struct conf_imodule_st { CONF_MODULE *pmod; char *name; char *value; unsigned long flags; void *usr_data; }; static CRYPTO_ONCE init_module_list_lock = CRYPTO_ONCE_STATIC_INIT; static CRYPTO_RWLOCK *module_list_lock = NULL; static STACK_OF(CONF_MODULE) *supported_modules = NULL; /* protected by lock */ static STACK_OF(CONF_IMODULE) *initialized_modules = NULL; /* protected by lock */ static CRYPTO_ONCE load_builtin_modules = CRYPTO_ONCE_STATIC_INIT; static void module_free(CONF_MODULE *md); static void module_finish(CONF_IMODULE *imod); static int module_run(const CONF *cnf, const char *name, const char *value, unsigned long flags); static CONF_MODULE *module_add(DSO *dso, const char *name, conf_init_func *ifunc, conf_finish_func *ffunc); static CONF_MODULE *module_find(const char *name); static int module_init(CONF_MODULE *pmod, const char *name, const char *value, const CONF *cnf); static CONF_MODULE *module_load_dso(const CONF *cnf, const char *name, const char *value); static int conf_modules_finish_int(void); static void module_lists_free(void) { CRYPTO_THREAD_lock_free(module_list_lock); module_list_lock = NULL; sk_CONF_MODULE_free(supported_modules); supported_modules = NULL; sk_CONF_IMODULE_free(initialized_modules); initialized_modules = NULL; } DEFINE_RUN_ONCE_STATIC(do_init_module_list_lock) { module_list_lock = CRYPTO_THREAD_lock_new(); if (module_list_lock == NULL) { ERR_raise(ERR_LIB_CONF, ERR_R_CRYPTO_LIB); return 0; } return 1; } static int conf_diagnostics(const CONF *cnf) { return _CONF_get_number(cnf, NULL, "config_diagnostics") != 0; } /* Main function: load modules from a CONF structure */ int CONF_modules_load(const CONF *cnf, const char *appname, unsigned long flags) { STACK_OF(CONF_VALUE) *values; CONF_VALUE *vl; char *vsection = NULL; int ret, i; if (!cnf) return 1; if (conf_diagnostics(cnf)) flags &= ~(CONF_MFLAGS_IGNORE_ERRORS | CONF_MFLAGS_IGNORE_RETURN_CODES | CONF_MFLAGS_SILENT | CONF_MFLAGS_IGNORE_MISSING_FILE); ERR_set_mark(); if (appname) vsection = NCONF_get_string(cnf, NULL, appname); if (!appname || (!vsection && (flags & CONF_MFLAGS_DEFAULT_SECTION))) vsection = NCONF_get_string(cnf, NULL, "openssl_conf"); if (!vsection) { ERR_pop_to_mark(); return 1; } OSSL_TRACE1(CONF, "Configuration in section %s\n", vsection); values = NCONF_get_section(cnf, vsection); if (values == NULL) { if (!(flags & CONF_MFLAGS_SILENT)) { ERR_clear_last_mark(); ERR_raise_data(ERR_LIB_CONF, CONF_R_OPENSSL_CONF_REFERENCES_MISSING_SECTION, "openssl_conf=%s", vsection); } else { ERR_pop_to_mark(); } return 0; } ERR_pop_to_mark(); for (i = 0; i < sk_CONF_VALUE_num(values); i++) { vl = sk_CONF_VALUE_value(values, i); ERR_set_mark(); ret = module_run(cnf, vl->name, vl->value, flags); OSSL_TRACE3(CONF, "Running module %s (%s) returned %d\n", vl->name, vl->value, ret); if (ret <= 0) if (!(flags & CONF_MFLAGS_IGNORE_ERRORS)) { ERR_clear_last_mark(); return ret; } ERR_pop_to_mark(); } return 1; } int CONF_modules_load_file_ex(OSSL_LIB_CTX *libctx, const char *filename, const char *appname, unsigned long flags) { char *file = NULL; CONF *conf = NULL; int ret = 0, diagnostics = 0; ERR_set_mark(); if (filename == NULL) { file = CONF_get1_default_config_file(); if (file == NULL) goto err; if (*file == '\0') { /* Do not try to load an empty file name but do not error out */ ret = 1; goto err; } } else { file = (char *)filename; } conf = NCONF_new_ex(libctx, NULL); if (conf == NULL) goto err; if (NCONF_load(conf, file, NULL) <= 0) { if ((flags & CONF_MFLAGS_IGNORE_MISSING_FILE) && (ERR_GET_REASON(ERR_peek_last_error()) == CONF_R_NO_SUCH_FILE)) { ret = 1; } goto err; } ret = CONF_modules_load(conf, appname, flags); diagnostics = conf_diagnostics(conf); err: if (filename == NULL) OPENSSL_free(file); NCONF_free(conf); if ((flags & CONF_MFLAGS_IGNORE_RETURN_CODES) != 0 && !diagnostics) ret = 1; if (ret > 0) ERR_pop_to_mark(); else ERR_clear_last_mark(); return ret; } int CONF_modules_load_file(const char *filename, const char *appname, unsigned long flags) { return CONF_modules_load_file_ex(NULL, filename, appname, flags); } DEFINE_RUN_ONCE_STATIC(do_load_builtin_modules) { OPENSSL_load_builtin_modules(); #ifndef OPENSSL_NO_ENGINE /* Need to load ENGINEs */ ENGINE_load_builtin_engines(); #endif return 1; } static int module_run(const CONF *cnf, const char *name, const char *value, unsigned long flags) { CONF_MODULE *md; int ret; if (!RUN_ONCE(&load_builtin_modules, do_load_builtin_modules)) return -1; md = module_find(name); /* Module not found: try to load DSO */ if (!md && !(flags & CONF_MFLAGS_NO_DSO)) md = module_load_dso(cnf, name, value); if (!md) { if (!(flags & CONF_MFLAGS_SILENT)) { ERR_raise_data(ERR_LIB_CONF, CONF_R_UNKNOWN_MODULE_NAME, "module=%s", name); } return -1; } ret = module_init(md, name, value, cnf); if (ret <= 0) { if (!(flags & CONF_MFLAGS_SILENT)) ERR_raise_data(ERR_LIB_CONF, CONF_R_MODULE_INITIALIZATION_ERROR, "module=%s, value=%s retcode=%-8d", name, value, ret); } return ret; } /* Load a module from a DSO */ static CONF_MODULE *module_load_dso(const CONF *cnf, const char *name, const char *value) { DSO *dso = NULL; conf_init_func *ifunc; conf_finish_func *ffunc; const char *path = NULL; int errcode = 0; CONF_MODULE *md; /* Look for alternative path in module section */ path = _CONF_get_string(cnf, value, "path"); if (path == NULL) { path = name; } dso = DSO_load(NULL, path, NULL, 0); if (dso == NULL) { errcode = CONF_R_ERROR_LOADING_DSO; goto err; } ifunc = (conf_init_func *)DSO_bind_func(dso, DSO_mod_init_name); if (ifunc == NULL) { errcode = CONF_R_MISSING_INIT_FUNCTION; goto err; } ffunc = (conf_finish_func *)DSO_bind_func(dso, DSO_mod_finish_name); /* All OK, add module */ md = module_add(dso, name, ifunc, ffunc); if (md == NULL) goto err; return md; err: DSO_free(dso); ERR_raise_data(ERR_LIB_CONF, errcode, "module=%s, path=%s", name, path); return NULL; } /* add module to list */ static CONF_MODULE *module_add(DSO *dso, const char *name, conf_init_func *ifunc, conf_finish_func *ffunc) { CONF_MODULE *tmod = NULL; if (!RUN_ONCE(&init_module_list_lock, do_init_module_list_lock)) return NULL; if (!CRYPTO_THREAD_write_lock(module_list_lock)) return NULL; if (supported_modules == NULL) supported_modules = sk_CONF_MODULE_new_null(); if (supported_modules == NULL) goto err; if ((tmod = OPENSSL_zalloc(sizeof(*tmod))) == NULL) goto err; tmod->dso = dso; tmod->name = OPENSSL_strdup(name); tmod->init = ifunc; tmod->finish = ffunc; if (tmod->name == NULL) goto err; if (!sk_CONF_MODULE_push(supported_modules, tmod)) goto err; CRYPTO_THREAD_unlock(module_list_lock); return tmod; err: CRYPTO_THREAD_unlock(module_list_lock); if (tmod != NULL) { OPENSSL_free(tmod->name); OPENSSL_free(tmod); } return NULL; } /* * Find a module from the list. We allow module names of the form * modname.XXXX to just search for modname to allow the same module to be * initialized more than once. */ static CONF_MODULE *module_find(const char *name) { CONF_MODULE *tmod; int i, nchar; char *p; p = strrchr(name, '.'); if (p) nchar = p - name; else nchar = strlen(name); if (!RUN_ONCE(&init_module_list_lock, do_init_module_list_lock)) return NULL; if (!CRYPTO_THREAD_read_lock(module_list_lock)) return NULL; for (i = 0; i < sk_CONF_MODULE_num(supported_modules); i++) { tmod = sk_CONF_MODULE_value(supported_modules, i); if (strncmp(tmod->name, name, nchar) == 0) { CRYPTO_THREAD_unlock(module_list_lock); return tmod; } } CRYPTO_THREAD_unlock(module_list_lock); return NULL; } /* initialize a module */ static int module_init(CONF_MODULE *pmod, const char *name, const char *value, const CONF *cnf) { int ret = 1; int init_called = 0; CONF_IMODULE *imod = NULL; /* Otherwise add initialized module to list */ imod = OPENSSL_malloc(sizeof(*imod)); if (imod == NULL) goto err; imod->pmod = pmod; imod->name = OPENSSL_strdup(name); imod->value = OPENSSL_strdup(value); imod->usr_data = NULL; if (!imod->name || !imod->value) goto memerr; /* Try to initialize module */ if (pmod->init) { ret = pmod->init(imod, cnf); init_called = 1; /* Error occurred, exit */ if (ret <= 0) goto err; } if (!RUN_ONCE(&init_module_list_lock, do_init_module_list_lock)) goto err; if (!CRYPTO_THREAD_write_lock(module_list_lock)) goto err; if (initialized_modules == NULL) { initialized_modules = sk_CONF_IMODULE_new_null(); if (initialized_modules == NULL) { CRYPTO_THREAD_unlock(module_list_lock); ERR_raise(ERR_LIB_CONF, ERR_R_CRYPTO_LIB); goto err; } } if (!sk_CONF_IMODULE_push(initialized_modules, imod)) { CRYPTO_THREAD_unlock(module_list_lock); ERR_raise(ERR_LIB_CONF, ERR_R_CRYPTO_LIB); goto err; } pmod->links++; CRYPTO_THREAD_unlock(module_list_lock); return ret; err: /* We've started the module so we'd better finish it */ if (pmod->finish && init_called) pmod->finish(imod); memerr: if (imod) { OPENSSL_free(imod->name); OPENSSL_free(imod->value); OPENSSL_free(imod); } return -1; } /* * Unload any dynamic modules that have a link count of zero: i.e. have no * active initialized modules. If 'all' is set then all modules are unloaded * including static ones. */ void CONF_modules_unload(int all) { int i; CONF_MODULE *md; if (!conf_modules_finish_int()) /* also inits module list lock */ return; if (!CRYPTO_THREAD_write_lock(module_list_lock)) return; /* unload modules in reverse order */ for (i = sk_CONF_MODULE_num(supported_modules) - 1; i >= 0; i--) { md = sk_CONF_MODULE_value(supported_modules, i); /* If static or in use and 'all' not set ignore it */ if (((md->links > 0) || !md->dso) && !all) continue; /* Since we're working in reverse this is OK */ (void)sk_CONF_MODULE_delete(supported_modules, i); module_free(md); } if (sk_CONF_MODULE_num(supported_modules) == 0) { sk_CONF_MODULE_free(supported_modules); supported_modules = NULL; } CRYPTO_THREAD_unlock(module_list_lock); } /* unload a single module */ static void module_free(CONF_MODULE *md) { DSO_free(md->dso); OPENSSL_free(md->name); OPENSSL_free(md); } /* finish and free up all modules instances */ static int conf_modules_finish_int(void) { CONF_IMODULE *imod; if (!RUN_ONCE(&init_module_list_lock, do_init_module_list_lock)) return 0; /* If module_list_lock is NULL here it means we were already unloaded */ if (module_list_lock == NULL || !CRYPTO_THREAD_write_lock(module_list_lock)) return 0; while (sk_CONF_IMODULE_num(initialized_modules) > 0) { imod = sk_CONF_IMODULE_pop(initialized_modules); module_finish(imod); } sk_CONF_IMODULE_free(initialized_modules); initialized_modules = NULL; CRYPTO_THREAD_unlock(module_list_lock); return 1; } void CONF_modules_finish(void) { conf_modules_finish_int(); } /* finish a module instance */ static void module_finish(CONF_IMODULE *imod) { if (!imod) return; if (imod->pmod->finish) imod->pmod->finish(imod); imod->pmod->links--; OPENSSL_free(imod->name); OPENSSL_free(imod->value); OPENSSL_free(imod); } /* Add a static module to OpenSSL */ int CONF_module_add(const char *name, conf_init_func *ifunc, conf_finish_func *ffunc) { if (module_add(NULL, name, ifunc, ffunc)) return 1; else return 0; } void ossl_config_modules_free(void) { CONF_modules_unload(1); /* calls CONF_modules_finish */ module_lists_free(); } /* Utility functions */ const char *CONF_imodule_get_name(const CONF_IMODULE *md) { return md->name; } const char *CONF_imodule_get_value(const CONF_IMODULE *md) { return md->value; } void *CONF_imodule_get_usr_data(const CONF_IMODULE *md) { return md->usr_data; } void CONF_imodule_set_usr_data(CONF_IMODULE *md, void *usr_data) { md->usr_data = usr_data; } CONF_MODULE *CONF_imodule_get_module(const CONF_IMODULE *md) { return md->pmod; } unsigned long CONF_imodule_get_flags(const CONF_IMODULE *md) { return md->flags; } void CONF_imodule_set_flags(CONF_IMODULE *md, unsigned long flags) { md->flags = flags; } void *CONF_module_get_usr_data(CONF_MODULE *pmod) { return pmod->usr_data; } void CONF_module_set_usr_data(CONF_MODULE *pmod, void *usr_data) { pmod->usr_data = usr_data; } /* Return default config file name */ char *CONF_get1_default_config_file(void) { const char *t; char *file, *sep = ""; size_t size; if ((file = ossl_safe_getenv("OPENSSL_CONF")) != NULL) return OPENSSL_strdup(file); t = X509_get_default_cert_area(); #ifndef OPENSSL_SYS_VMS sep = "/"; #endif size = strlen(t) + strlen(sep) + strlen(OPENSSL_CONF) + 1; file = OPENSSL_malloc(size); if (file == NULL) return NULL; BIO_snprintf(file, size, "%s%s%s", t, sep, OPENSSL_CONF); return file; } /* * This function takes a list separated by 'sep' and calls the callback * function giving the start and length of each member optionally stripping * leading and trailing whitespace. This can be used to parse comma separated * lists for example. */ int CONF_parse_list(const char *list_, int sep, int nospc, int (*list_cb) (const char *elem, int len, void *usr), void *arg) { int ret; const char *lstart, *tmpend, *p; if (list_ == NULL) { ERR_raise(ERR_LIB_CONF, CONF_R_LIST_CANNOT_BE_NULL); return 0; } lstart = list_; for (;;) { if (nospc) { while (*lstart && isspace((unsigned char)*lstart)) lstart++; } p = strchr(lstart, sep); if (p == lstart || *lstart == '\0') ret = list_cb(NULL, 0, arg); else { if (p) tmpend = p - 1; else tmpend = lstart + strlen(lstart) - 1; if (nospc) { while (isspace((unsigned char)*tmpend)) tmpend--; } ret = list_cb(lstart, tmpend - lstart + 1, arg); } if (ret <= 0) return ret; if (p == NULL) return 1; lstart = p + 1; } }
17,832
24.548711
82
c
openssl
openssl-master/crypto/conf/conf_sap.c
/* * Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> #include <openssl/crypto.h> #include "internal/cryptlib.h" #include "internal/conf.h" #include "conf_local.h" #include <openssl/x509.h> #include <openssl/asn1.h> #include <openssl/engine.h> #if defined(_WIN32) && !defined(__BORLANDC__) # define strdup _strdup #endif /* * This is the automatic configuration loader: it is called automatically by * OpenSSL when any of a number of standard initialisation functions are * called, unless this is overridden by calling OPENSSL_no_config() */ static int openssl_configured = 0; #ifndef OPENSSL_NO_DEPRECATED_1_1_0 void OPENSSL_config(const char *appname) { OPENSSL_INIT_SETTINGS settings; memset(&settings, 0, sizeof(settings)); if (appname != NULL) settings.appname = strdup(appname); settings.flags = DEFAULT_CONF_MFLAGS; OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CONFIG, &settings); } #endif int ossl_config_int(const OPENSSL_INIT_SETTINGS *settings) { int ret = 0; #if defined(OPENSSL_INIT_DEBUG) || !defined(OPENSSL_SYS_UEFI) const char *filename; const char *appname; unsigned long flags; #endif if (openssl_configured) return 1; #if defined(OPENSSL_INIT_DEBUG) || !defined(OPENSSL_SYS_UEFI) filename = settings ? settings->filename : NULL; appname = settings ? settings->appname : NULL; flags = settings ? settings->flags : DEFAULT_CONF_MFLAGS; #endif #ifdef OPENSSL_INIT_DEBUG fprintf(stderr, "OPENSSL_INIT: ossl_config_int(%s, %s, %lu)\n", filename, appname, flags); #endif #ifndef OPENSSL_SYS_UEFI ret = CONF_modules_load_file(filename, appname, flags); #else ret = 1; #endif openssl_configured = 1; return ret; } void ossl_no_config_int(void) { openssl_configured = 1; }
2,098
25.2375
76
c
openssl
openssl-master/crypto/conf/conf_ssl.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 <stdio.h> #include <string.h> #include <openssl/conf.h> #include <openssl/err.h> #include "internal/sslconf.h" #include "conf_local.h" /* * SSL library configuration module placeholder. We load it here but defer * all decisions about its contents to libssl. */ struct ssl_conf_name_st { /* Name of this set of commands */ char *name; /* List of commands */ SSL_CONF_CMD *cmds; /* Number of commands */ size_t cmd_count; }; struct ssl_conf_cmd_st { /* Command */ char *cmd; /* Argument */ char *arg; }; static struct ssl_conf_name_st *ssl_names; static size_t ssl_names_count; static void ssl_module_free(CONF_IMODULE *md) { size_t i, j; if (ssl_names == NULL) return; for (i = 0; i < ssl_names_count; i++) { struct ssl_conf_name_st *tname = ssl_names + i; OPENSSL_free(tname->name); for (j = 0; j < tname->cmd_count; j++) { OPENSSL_free(tname->cmds[j].cmd); OPENSSL_free(tname->cmds[j].arg); } OPENSSL_free(tname->cmds); } OPENSSL_free(ssl_names); ssl_names = NULL; ssl_names_count = 0; } static int ssl_module_init(CONF_IMODULE *md, const CONF *cnf) { size_t i, j, cnt; int rv = 0; const char *ssl_conf_section; STACK_OF(CONF_VALUE) *cmd_lists; ssl_conf_section = CONF_imodule_get_value(md); cmd_lists = NCONF_get_section(cnf, ssl_conf_section); if (sk_CONF_VALUE_num(cmd_lists) <= 0) { int rcode = cmd_lists == NULL ? CONF_R_SSL_SECTION_NOT_FOUND : CONF_R_SSL_SECTION_EMPTY; ERR_raise_data(ERR_LIB_CONF, rcode, "section=%s", ssl_conf_section); goto err; } cnt = sk_CONF_VALUE_num(cmd_lists); ssl_module_free(md); ssl_names = OPENSSL_zalloc(sizeof(*ssl_names) * cnt); if (ssl_names == NULL) goto err; ssl_names_count = cnt; for (i = 0; i < ssl_names_count; i++) { struct ssl_conf_name_st *ssl_name = ssl_names + i; CONF_VALUE *sect = sk_CONF_VALUE_value(cmd_lists, (int)i); STACK_OF(CONF_VALUE) *cmds = NCONF_get_section(cnf, sect->value); if (sk_CONF_VALUE_num(cmds) <= 0) { int rcode = cmds == NULL ? CONF_R_SSL_COMMAND_SECTION_NOT_FOUND : CONF_R_SSL_COMMAND_SECTION_EMPTY; ERR_raise_data(ERR_LIB_CONF, rcode, "name=%s, value=%s", sect->name, sect->value); goto err; } ssl_name->name = OPENSSL_strdup(sect->name); if (ssl_name->name == NULL) goto err; cnt = sk_CONF_VALUE_num(cmds); ssl_name->cmds = OPENSSL_zalloc(cnt * sizeof(struct ssl_conf_cmd_st)); if (ssl_name->cmds == NULL) goto err; ssl_name->cmd_count = cnt; for (j = 0; j < cnt; j++) { const char *name; CONF_VALUE *cmd_conf = sk_CONF_VALUE_value(cmds, (int)j); struct ssl_conf_cmd_st *cmd = ssl_name->cmds + j; /* Skip any initial dot in name */ name = strchr(cmd_conf->name, '.'); if (name != NULL) name++; else name = cmd_conf->name; cmd->cmd = OPENSSL_strdup(name); cmd->arg = OPENSSL_strdup(cmd_conf->value); if (cmd->cmd == NULL || cmd->arg == NULL) goto err; } } rv = 1; err: if (rv == 0) ssl_module_free(md); return rv; } /* * Returns the set of commands with index |idx| previously searched for via * conf_ssl_name_find. Also stores the name of the set of commands in |*name| * and the number of commands in the set in |*cnt|. */ const SSL_CONF_CMD *conf_ssl_get(size_t idx, const char **name, size_t *cnt) { *name = ssl_names[idx].name; *cnt = ssl_names[idx].cmd_count; return ssl_names[idx].cmds; } /* * Search for the named set of commands given in |name|. On success return the * index for the command set in |*idx|. * Returns 1 on success or 0 on failure. */ int conf_ssl_name_find(const char *name, size_t *idx) { size_t i; const struct ssl_conf_name_st *nm; if (name == NULL) return 0; for (i = 0, nm = ssl_names; i < ssl_names_count; i++, nm++) { if (strcmp(nm->name, name) == 0) { *idx = i; return 1; } } return 0; } /* * Given a command set |cmd|, return details on the command at index |idx| which * must be less than the number of commands in the set (as returned by * conf_ssl_get). The name of the command will be returned in |*cmdstr| and the * argument is returned in |*arg|. */ void conf_ssl_get_cmd(const SSL_CONF_CMD *cmd, size_t idx, char **cmdstr, char **arg) { *cmdstr = cmd[idx].cmd; *arg = cmd[idx].arg; } void ossl_config_add_ssl_module(void) { CONF_module_add("ssl_conf", ssl_module_init, ssl_module_free); }
5,302
27.978142
80
c
openssl
openssl-master/crypto/crmf/crmf_asn.c
/*- * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * CRMF implementation by Martin Peylo, Miikka Viljanen, and David von Oheimb. */ #include <openssl/asn1t.h> #include "crmf_local.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/crmf.h> ASN1_SEQUENCE(OSSL_CRMF_PRIVATEKEYINFO) = { ASN1_SIMPLE(OSSL_CRMF_PRIVATEKEYINFO, version, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CRMF_PRIVATEKEYINFO, privateKeyAlgorithm, X509_ALGOR), ASN1_SIMPLE(OSSL_CRMF_PRIVATEKEYINFO, privateKey, ASN1_OCTET_STRING), ASN1_IMP_SET_OF_OPT(OSSL_CRMF_PRIVATEKEYINFO, attributes, X509_ATTRIBUTE, 0) } ASN1_SEQUENCE_END(OSSL_CRMF_PRIVATEKEYINFO) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_PRIVATEKEYINFO) ASN1_CHOICE(OSSL_CRMF_ENCKEYWITHID_IDENTIFIER) = { ASN1_SIMPLE(OSSL_CRMF_ENCKEYWITHID_IDENTIFIER, value.string, ASN1_UTF8STRING), ASN1_SIMPLE(OSSL_CRMF_ENCKEYWITHID_IDENTIFIER, value.generalName, GENERAL_NAME) } ASN1_CHOICE_END(OSSL_CRMF_ENCKEYWITHID_IDENTIFIER) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_ENCKEYWITHID_IDENTIFIER) ASN1_SEQUENCE(OSSL_CRMF_ENCKEYWITHID) = { ASN1_SIMPLE(OSSL_CRMF_ENCKEYWITHID, privateKey, OSSL_CRMF_PRIVATEKEYINFO), ASN1_OPT(OSSL_CRMF_ENCKEYWITHID, identifier, OSSL_CRMF_ENCKEYWITHID_IDENTIFIER) } ASN1_SEQUENCE_END(OSSL_CRMF_ENCKEYWITHID) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_ENCKEYWITHID) ASN1_SEQUENCE(OSSL_CRMF_CERTID) = { ASN1_SIMPLE(OSSL_CRMF_CERTID, issuer, GENERAL_NAME), ASN1_SIMPLE(OSSL_CRMF_CERTID, serialNumber, ASN1_INTEGER) } ASN1_SEQUENCE_END(OSSL_CRMF_CERTID) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_CERTID) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CRMF_CERTID) ASN1_SEQUENCE(OSSL_CRMF_ENCRYPTEDVALUE) = { ASN1_IMP_OPT(OSSL_CRMF_ENCRYPTEDVALUE, intendedAlg, X509_ALGOR, 0), ASN1_IMP_OPT(OSSL_CRMF_ENCRYPTEDVALUE, symmAlg, X509_ALGOR, 1), ASN1_IMP_OPT(OSSL_CRMF_ENCRYPTEDVALUE, encSymmKey, ASN1_BIT_STRING, 2), ASN1_IMP_OPT(OSSL_CRMF_ENCRYPTEDVALUE, keyAlg, X509_ALGOR, 3), ASN1_IMP_OPT(OSSL_CRMF_ENCRYPTEDVALUE, valueHint, ASN1_OCTET_STRING, 4), ASN1_SIMPLE(OSSL_CRMF_ENCRYPTEDVALUE, encValue, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(OSSL_CRMF_ENCRYPTEDVALUE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_ENCRYPTEDVALUE) ASN1_SEQUENCE(OSSL_CRMF_SINGLEPUBINFO) = { ASN1_SIMPLE(OSSL_CRMF_SINGLEPUBINFO, pubMethod, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CRMF_SINGLEPUBINFO, pubLocation, GENERAL_NAME) } ASN1_SEQUENCE_END(OSSL_CRMF_SINGLEPUBINFO) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_SINGLEPUBINFO) ASN1_SEQUENCE(OSSL_CRMF_PKIPUBLICATIONINFO) = { ASN1_SIMPLE(OSSL_CRMF_PKIPUBLICATIONINFO, action, ASN1_INTEGER), ASN1_SEQUENCE_OF_OPT(OSSL_CRMF_PKIPUBLICATIONINFO, pubInfos, OSSL_CRMF_SINGLEPUBINFO) } ASN1_SEQUENCE_END(OSSL_CRMF_PKIPUBLICATIONINFO) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_PKIPUBLICATIONINFO) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CRMF_PKIPUBLICATIONINFO) ASN1_SEQUENCE(OSSL_CRMF_PKMACVALUE) = { ASN1_SIMPLE(OSSL_CRMF_PKMACVALUE, algId, X509_ALGOR), ASN1_SIMPLE(OSSL_CRMF_PKMACVALUE, value, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(OSSL_CRMF_PKMACVALUE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_PKMACVALUE) ASN1_CHOICE(OSSL_CRMF_POPOPRIVKEY) = { ASN1_IMP(OSSL_CRMF_POPOPRIVKEY, value.thisMessage, ASN1_BIT_STRING, 0), ASN1_IMP(OSSL_CRMF_POPOPRIVKEY, value.subsequentMessage, ASN1_INTEGER, 1), ASN1_IMP(OSSL_CRMF_POPOPRIVKEY, value.dhMAC, ASN1_BIT_STRING, 2), ASN1_IMP(OSSL_CRMF_POPOPRIVKEY, value.agreeMAC, OSSL_CRMF_PKMACVALUE, 3), ASN1_IMP(OSSL_CRMF_POPOPRIVKEY, value.encryptedKey, ASN1_NULL, 4), /* When supported, ASN1_NULL needs to be replaced by CMS_ENVELOPEDDATA */ } ASN1_CHOICE_END(OSSL_CRMF_POPOPRIVKEY) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_POPOPRIVKEY) ASN1_SEQUENCE(OSSL_CRMF_PBMPARAMETER) = { ASN1_SIMPLE(OSSL_CRMF_PBMPARAMETER, salt, ASN1_OCTET_STRING), ASN1_SIMPLE(OSSL_CRMF_PBMPARAMETER, owf, X509_ALGOR), ASN1_SIMPLE(OSSL_CRMF_PBMPARAMETER, iterationCount, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CRMF_PBMPARAMETER, mac, X509_ALGOR) } ASN1_SEQUENCE_END(OSSL_CRMF_PBMPARAMETER) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_PBMPARAMETER) ASN1_CHOICE(OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO) = { ASN1_EXP(OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO, value.sender, GENERAL_NAME, 0), ASN1_SIMPLE(OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO, value.publicKeyMAC, OSSL_CRMF_PKMACVALUE) } ASN1_CHOICE_END(OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO) ASN1_SEQUENCE(OSSL_CRMF_POPOSIGNINGKEYINPUT) = { ASN1_SIMPLE(OSSL_CRMF_POPOSIGNINGKEYINPUT, authInfo, OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO), ASN1_SIMPLE(OSSL_CRMF_POPOSIGNINGKEYINPUT, publicKey, X509_PUBKEY) } ASN1_SEQUENCE_END(OSSL_CRMF_POPOSIGNINGKEYINPUT) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_POPOSIGNINGKEYINPUT) ASN1_SEQUENCE(OSSL_CRMF_POPOSIGNINGKEY) = { ASN1_IMP_OPT(OSSL_CRMF_POPOSIGNINGKEY, poposkInput, OSSL_CRMF_POPOSIGNINGKEYINPUT, 0), ASN1_SIMPLE(OSSL_CRMF_POPOSIGNINGKEY, algorithmIdentifier, X509_ALGOR), ASN1_SIMPLE(OSSL_CRMF_POPOSIGNINGKEY, signature, ASN1_BIT_STRING) } ASN1_SEQUENCE_END(OSSL_CRMF_POPOSIGNINGKEY) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_POPOSIGNINGKEY) ASN1_CHOICE(OSSL_CRMF_POPO) = { ASN1_IMP(OSSL_CRMF_POPO, value.raVerified, ASN1_NULL, 0), ASN1_IMP(OSSL_CRMF_POPO, value.signature, OSSL_CRMF_POPOSIGNINGKEY, 1), ASN1_EXP(OSSL_CRMF_POPO, value.keyEncipherment, OSSL_CRMF_POPOPRIVKEY, 2), ASN1_EXP(OSSL_CRMF_POPO, value.keyAgreement, OSSL_CRMF_POPOPRIVKEY, 3) } ASN1_CHOICE_END(OSSL_CRMF_POPO) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_POPO) ASN1_ADB_TEMPLATE(attributetypeandvalue_default) = ASN1_OPT(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.other, ASN1_ANY); ASN1_ADB(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) = { ADB_ENTRY(NID_id_regCtrl_regToken, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.regToken, ASN1_UTF8STRING)), ADB_ENTRY(NID_id_regCtrl_authenticator, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.authenticator, ASN1_UTF8STRING)), ADB_ENTRY(NID_id_regCtrl_pkiPublicationInfo, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.pkiPublicationInfo, OSSL_CRMF_PKIPUBLICATIONINFO)), ADB_ENTRY(NID_id_regCtrl_oldCertID, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.oldCertID, OSSL_CRMF_CERTID)), ADB_ENTRY(NID_id_regCtrl_protocolEncrKey, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.protocolEncrKey, X509_PUBKEY)), ADB_ENTRY(NID_id_regInfo_utf8Pairs, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.utf8Pairs, ASN1_UTF8STRING)), ADB_ENTRY(NID_id_regInfo_certReq, ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, value.certReq, OSSL_CRMF_CERTREQUEST)), } ASN1_ADB_END(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, 0, type, 0, &attributetypeandvalue_default_tt, NULL); ASN1_SEQUENCE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) = { ASN1_SIMPLE(OSSL_CRMF_ATTRIBUTETYPEANDVALUE, type, ASN1_OBJECT), ASN1_ADB_OBJECT(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) } ASN1_SEQUENCE_END(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) ASN1_SEQUENCE(OSSL_CRMF_OPTIONALVALIDITY) = { ASN1_EXP_OPT(OSSL_CRMF_OPTIONALVALIDITY, notBefore, ASN1_TIME, 0), ASN1_EXP_OPT(OSSL_CRMF_OPTIONALVALIDITY, notAfter, ASN1_TIME, 1) } ASN1_SEQUENCE_END(OSSL_CRMF_OPTIONALVALIDITY) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_OPTIONALVALIDITY) ASN1_SEQUENCE(OSSL_CRMF_CERTTEMPLATE) = { ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, version, ASN1_INTEGER, 0), /* * serialNumber MUST be omitted. This field is assigned by the CA * during certificate creation. */ ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, serialNumber, ASN1_INTEGER, 1), /* * signingAlg MUST be omitted. This field is assigned by the CA * during certificate creation. */ ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, signingAlg, X509_ALGOR, 2), ASN1_EXP_OPT(OSSL_CRMF_CERTTEMPLATE, issuer, X509_NAME, 3), ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, validity, OSSL_CRMF_OPTIONALVALIDITY, 4), ASN1_EXP_OPT(OSSL_CRMF_CERTTEMPLATE, subject, X509_NAME, 5), ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, publicKey, X509_PUBKEY, 6), /* issuerUID is deprecated in version 2 */ ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, issuerUID, ASN1_BIT_STRING, 7), /* subjectUID is deprecated in version 2 */ ASN1_IMP_OPT(OSSL_CRMF_CERTTEMPLATE, subjectUID, ASN1_BIT_STRING, 8), ASN1_IMP_SEQUENCE_OF_OPT(OSSL_CRMF_CERTTEMPLATE, extensions, X509_EXTENSION, 9), } ASN1_SEQUENCE_END(OSSL_CRMF_CERTTEMPLATE) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_CERTTEMPLATE) ASN1_SEQUENCE(OSSL_CRMF_CERTREQUEST) = { ASN1_SIMPLE(OSSL_CRMF_CERTREQUEST, certReqId, ASN1_INTEGER), ASN1_SIMPLE(OSSL_CRMF_CERTREQUEST, certTemplate, OSSL_CRMF_CERTTEMPLATE), ASN1_SEQUENCE_OF_OPT(OSSL_CRMF_CERTREQUEST, controls, OSSL_CRMF_ATTRIBUTETYPEANDVALUE) } ASN1_SEQUENCE_END(OSSL_CRMF_CERTREQUEST) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_CERTREQUEST) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CRMF_CERTREQUEST) ASN1_SEQUENCE(OSSL_CRMF_MSG) = { ASN1_SIMPLE(OSSL_CRMF_MSG, certReq, OSSL_CRMF_CERTREQUEST), ASN1_OPT(OSSL_CRMF_MSG, popo, OSSL_CRMF_POPO), ASN1_SEQUENCE_OF_OPT(OSSL_CRMF_MSG, regInfo, OSSL_CRMF_ATTRIBUTETYPEANDVALUE) } ASN1_SEQUENCE_END(OSSL_CRMF_MSG) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_MSG) IMPLEMENT_ASN1_DUP_FUNCTION(OSSL_CRMF_MSG) ASN1_ITEM_TEMPLATE(OSSL_CRMF_MSGS) = ASN1_EX_TEMPLATE_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, OSSL_CRMF_MSGS, OSSL_CRMF_MSG) ASN1_ITEM_TEMPLATE_END(OSSL_CRMF_MSGS) IMPLEMENT_ASN1_FUNCTIONS(OSSL_CRMF_MSGS)
10,429
46.19457
80
c
openssl
openssl-master/crypto/crmf/crmf_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/crmferr.h> #include "crypto/crmferr.h" #ifndef OPENSSL_NO_CRMF # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA CRMF_str_reasons[] = { {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_BAD_PBM_ITERATIONCOUNT), "bad pbm iterationcount"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_CRMFERROR), "crmferror"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_ERROR), "error"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_ERROR_DECODING_CERTIFICATE), "error decoding certificate"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_ERROR_DECRYPTING_CERTIFICATE), "error decrypting certificate"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_ERROR_DECRYPTING_SYMMETRIC_KEY), "error decrypting symmetric key"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_FAILURE_OBTAINING_RANDOM), "failure obtaining random"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_ITERATIONCOUNT_BELOW_100), "iterationcount below 100"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_MALFORMED_IV), "malformed iv"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_NULL_ARGUMENT), "null argument"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_POPOSKINPUT_NOT_SUPPORTED), "poposkinput not supported"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_POPO_INCONSISTENT_PUBLIC_KEY), "popo inconsistent public key"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_POPO_MISSING), "popo missing"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_POPO_MISSING_PUBLIC_KEY), "popo missing public key"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_POPO_MISSING_SUBJECT), "popo missing subject"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_POPO_RAVERIFIED_NOT_ACCEPTED), "popo raverified not accepted"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_SETTING_MAC_ALGOR_FAILURE), "setting mac algor failure"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_SETTING_OWF_ALGOR_FAILURE), "setting owf algor failure"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_UNSUPPORTED_ALGORITHM), "unsupported algorithm"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_UNSUPPORTED_CIPHER), "unsupported cipher"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_UNSUPPORTED_METHOD_FOR_CREATING_POPO), "unsupported method for creating popo"}, {ERR_PACK(ERR_LIB_CRMF, 0, CRMF_R_UNSUPPORTED_POPO_METHOD), "unsupported popo method"}, {0, NULL} }; # endif int ossl_err_load_CRMF_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(CRMF_str_reasons[0].error) == NULL) ERR_load_strings_const(CRMF_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
2,870
37.28
76
c
openssl
openssl-master/crypto/crmf/crmf_lib.c
/*- * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2018 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * CRMF implementation by Martin Peylo, Miikka Viljanen, and David von Oheimb. */ /* * This file contains the functions that handle the individual items inside * the CRMF structures */ /* * NAMING * * The 0 functions use the supplied structure pointer directly in the parent and * it will be freed up when the parent is freed. * * The 1 functions use a copy of the supplied structure pointer (or in some * cases increases its link count) in the parent and so both should be freed up. */ #include <openssl/asn1t.h> #include "crmf_local.h" #include "internal/sizes.h" #include "crypto/evp.h" #include "crypto/x509.h" /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/crmf.h> #include <openssl/err.h> #include <openssl/evp.h> /*- * atyp = Attribute Type * valt = Value Type * ctrlinf = "regCtrl" or "regInfo" */ #define IMPLEMENT_CRMF_CTRL_FUNC(atyp, valt, ctrlinf) \ valt *OSSL_CRMF_MSG_get0_##ctrlinf##_##atyp(const OSSL_CRMF_MSG *msg) \ { \ int i; \ STACK_OF(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) *controls; \ OSSL_CRMF_ATTRIBUTETYPEANDVALUE *atav = NULL; \ \ if (msg == NULL || msg->certReq == NULL) \ return NULL; \ controls = msg->certReq->controls; \ for (i = 0; i < sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_num(controls); i++) { \ atav = sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_value(controls, i); \ if (OBJ_obj2nid(atav->type) == NID_id_##ctrlinf##_##atyp) \ return atav->value.atyp; \ } \ return NULL; \ } \ \ int OSSL_CRMF_MSG_set1_##ctrlinf##_##atyp(OSSL_CRMF_MSG *msg, const valt *in) \ { \ OSSL_CRMF_ATTRIBUTETYPEANDVALUE *atav = NULL; \ \ if (msg == NULL || in == NULL) \ goto err; \ if ((atav = OSSL_CRMF_ATTRIBUTETYPEANDVALUE_new()) == NULL) \ goto err; \ if ((atav->type = OBJ_nid2obj(NID_id_##ctrlinf##_##atyp)) == NULL) \ goto err; \ if ((atav->value.atyp = valt##_dup(in)) == NULL) \ goto err; \ if (!OSSL_CRMF_MSG_push0_##ctrlinf(msg, atav)) \ goto err; \ return 1; \ err: \ OSSL_CRMF_ATTRIBUTETYPEANDVALUE_free(atav); \ return 0; \ } /*- * Pushes the given control attribute into the controls stack of a CertRequest * (section 6) * returns 1 on success, 0 on error */ static int OSSL_CRMF_MSG_push0_regCtrl(OSSL_CRMF_MSG *crm, OSSL_CRMF_ATTRIBUTETYPEANDVALUE *ctrl) { int new = 0; if (crm == NULL || crm->certReq == NULL || ctrl == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (crm->certReq->controls == NULL) { crm->certReq->controls = sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_new_null(); if (crm->certReq->controls == NULL) goto err; new = 1; } if (!sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_push(crm->certReq->controls, ctrl)) goto err; return 1; err: if (new != 0) { sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_free(crm->certReq->controls); crm->certReq->controls = NULL; } return 0; } /* id-regCtrl-regToken Control (section 6.1) */ IMPLEMENT_CRMF_CTRL_FUNC(regToken, ASN1_STRING, regCtrl) /* id-regCtrl-authenticator Control (section 6.2) */ #define ASN1_UTF8STRING_dup ASN1_STRING_dup IMPLEMENT_CRMF_CTRL_FUNC(authenticator, ASN1_UTF8STRING, regCtrl) int OSSL_CRMF_MSG_set0_SinglePubInfo(OSSL_CRMF_SINGLEPUBINFO *spi, int method, GENERAL_NAME *nm) { if (spi == NULL || method < OSSL_CRMF_PUB_METHOD_DONTCARE || method > OSSL_CRMF_PUB_METHOD_LDAP) { ERR_raise(ERR_LIB_CRMF, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } if (!ASN1_INTEGER_set(spi->pubMethod, method)) return 0; GENERAL_NAME_free(spi->pubLocation); spi->pubLocation = nm; return 1; } int OSSL_CRMF_MSG_PKIPublicationInfo_push0_SinglePubInfo(OSSL_CRMF_PKIPUBLICATIONINFO *pi, OSSL_CRMF_SINGLEPUBINFO *spi) { if (pi == NULL || spi == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (pi->pubInfos == NULL) pi->pubInfos = sk_OSSL_CRMF_SINGLEPUBINFO_new_null(); if (pi->pubInfos == NULL) return 0; return sk_OSSL_CRMF_SINGLEPUBINFO_push(pi->pubInfos, spi); } int OSSL_CRMF_MSG_set_PKIPublicationInfo_action(OSSL_CRMF_PKIPUBLICATIONINFO *pi, int action) { if (pi == NULL || action < OSSL_CRMF_PUB_ACTION_DONTPUBLISH || action > OSSL_CRMF_PUB_ACTION_PLEASEPUBLISH) { ERR_raise(ERR_LIB_CRMF, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } return ASN1_INTEGER_set(pi->action, action); } /* id-regCtrl-pkiPublicationInfo Control (section 6.3) */ IMPLEMENT_CRMF_CTRL_FUNC(pkiPublicationInfo, OSSL_CRMF_PKIPUBLICATIONINFO, regCtrl) /* id-regCtrl-oldCertID Control (section 6.5) from the given */ IMPLEMENT_CRMF_CTRL_FUNC(oldCertID, OSSL_CRMF_CERTID, regCtrl) OSSL_CRMF_CERTID *OSSL_CRMF_CERTID_gen(const X509_NAME *issuer, const ASN1_INTEGER *serial) { OSSL_CRMF_CERTID *cid = NULL; if (issuer == NULL || serial == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return NULL; } if ((cid = OSSL_CRMF_CERTID_new()) == NULL) goto err; if (!X509_NAME_set(&cid->issuer->d.directoryName, issuer)) goto err; cid->issuer->type = GEN_DIRNAME; ASN1_INTEGER_free(cid->serialNumber); if ((cid->serialNumber = ASN1_INTEGER_dup(serial)) == NULL) goto err; return cid; err: OSSL_CRMF_CERTID_free(cid); return NULL; } /* * id-regCtrl-protocolEncrKey Control (section 6.6) */ IMPLEMENT_CRMF_CTRL_FUNC(protocolEncrKey, X509_PUBKEY, regCtrl) /*- * Pushes the attribute given in regInfo in to the CertReqMsg->regInfo stack. * (section 7) * returns 1 on success, 0 on error */ static int OSSL_CRMF_MSG_push0_regInfo(OSSL_CRMF_MSG *crm, OSSL_CRMF_ATTRIBUTETYPEANDVALUE *ri) { STACK_OF(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) *info = NULL; if (crm == NULL || ri == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (crm->regInfo == NULL) crm->regInfo = info = sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_new_null(); if (crm->regInfo == NULL) goto err; if (!sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_push(crm->regInfo, ri)) goto err; return 1; err: if (info != NULL) crm->regInfo = NULL; sk_OSSL_CRMF_ATTRIBUTETYPEANDVALUE_free(info); return 0; } /* id-regInfo-utf8Pairs to regInfo (section 7.1) */ IMPLEMENT_CRMF_CTRL_FUNC(utf8Pairs, ASN1_UTF8STRING, regInfo) /* id-regInfo-certReq to regInfo (section 7.2) */ IMPLEMENT_CRMF_CTRL_FUNC(certReq, OSSL_CRMF_CERTREQUEST, regInfo) /* retrieves the certificate template of crm */ OSSL_CRMF_CERTTEMPLATE *OSSL_CRMF_MSG_get0_tmpl(const OSSL_CRMF_MSG *crm) { if (crm == NULL || crm->certReq == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return NULL; } return crm->certReq->certTemplate; } int OSSL_CRMF_MSG_set0_validity(OSSL_CRMF_MSG *crm, ASN1_TIME *notBefore, ASN1_TIME *notAfter) { OSSL_CRMF_OPTIONALVALIDITY *vld; OSSL_CRMF_CERTTEMPLATE *tmpl = OSSL_CRMF_MSG_get0_tmpl(crm); if (tmpl == NULL) { /* also crm == NULL implies this */ ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if ((vld = OSSL_CRMF_OPTIONALVALIDITY_new()) == NULL) return 0; vld->notBefore = notBefore; vld->notAfter = notAfter; tmpl->validity = vld; return 1; } int OSSL_CRMF_MSG_set_certReqId(OSSL_CRMF_MSG *crm, int rid) { if (crm == NULL || crm->certReq == NULL || crm->certReq->certReqId == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } return ASN1_INTEGER_set(crm->certReq->certReqId, rid); } /* get ASN.1 encoded integer, return -1 on error */ static int crmf_asn1_get_int(const ASN1_INTEGER *a) { int64_t res; if (!ASN1_INTEGER_get_int64(&res, a)) { ERR_raise(ERR_LIB_CRMF, ASN1_R_INVALID_NUMBER); return -1; } if (res < INT_MIN) { ERR_raise(ERR_LIB_CRMF, ASN1_R_TOO_SMALL); return -1; } if (res > INT_MAX) { ERR_raise(ERR_LIB_CRMF, ASN1_R_TOO_LARGE); return -1; } return (int)res; } int OSSL_CRMF_MSG_get_certReqId(const OSSL_CRMF_MSG *crm) { if (crm == NULL || /* not really needed: */ crm->certReq == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return -1; } return crmf_asn1_get_int(crm->certReq->certReqId); } int OSSL_CRMF_MSG_set0_extensions(OSSL_CRMF_MSG *crm, X509_EXTENSIONS *exts) { OSSL_CRMF_CERTTEMPLATE *tmpl = OSSL_CRMF_MSG_get0_tmpl(crm); if (tmpl == NULL) { /* also crm == NULL implies this */ ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (sk_X509_EXTENSION_num(exts) == 0) { sk_X509_EXTENSION_free(exts); exts = NULL; /* do not include empty extensions list */ } sk_X509_EXTENSION_pop_free(tmpl->extensions, X509_EXTENSION_free); tmpl->extensions = exts; return 1; } int OSSL_CRMF_MSG_push0_extension(OSSL_CRMF_MSG *crm, X509_EXTENSION *ext) { int new = 0; OSSL_CRMF_CERTTEMPLATE *tmpl = OSSL_CRMF_MSG_get0_tmpl(crm); if (tmpl == NULL || ext == NULL) { /* also crm == NULL implies this */ ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (tmpl->extensions == NULL) { if ((tmpl->extensions = sk_X509_EXTENSION_new_null()) == NULL) goto err; new = 1; } if (!sk_X509_EXTENSION_push(tmpl->extensions, ext)) goto err; return 1; err: if (new != 0) { sk_X509_EXTENSION_free(tmpl->extensions); tmpl->extensions = NULL; } return 0; } static int create_popo_signature(OSSL_CRMF_POPOSIGNINGKEY *ps, const OSSL_CRMF_CERTREQUEST *cr, EVP_PKEY *pkey, const EVP_MD *digest, OSSL_LIB_CTX *libctx, const char *propq) { char name[80] = ""; EVP_PKEY *pub; if (ps == NULL || cr == NULL || pkey == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } pub = X509_PUBKEY_get0(cr->certTemplate->publicKey); if (!ossl_x509_check_private_key(pub, pkey)) return 0; if (ps->poposkInput != NULL) { /* We do not support cases 1+2 defined in RFC 4211, section 4.1 */ ERR_raise(ERR_LIB_CRMF, CRMF_R_POPOSKINPUT_NOT_SUPPORTED); return 0; } if (EVP_PKEY_get_default_digest_name(pkey, name, sizeof(name)) > 0 && strcmp(name, "UNDEF") == 0) /* at least for Ed25519, Ed448 */ digest = NULL; return ASN1_item_sign_ex(ASN1_ITEM_rptr(OSSL_CRMF_CERTREQUEST), ps->algorithmIdentifier, NULL, ps->signature, cr, NULL, pkey, digest, libctx, propq); } int OSSL_CRMF_MSG_create_popo(int meth, OSSL_CRMF_MSG *crm, EVP_PKEY *pkey, const EVP_MD *digest, OSSL_LIB_CTX *libctx, const char *propq) { OSSL_CRMF_POPO *pp = NULL; ASN1_INTEGER *tag = NULL; if (crm == NULL || (meth == OSSL_CRMF_POPO_SIGNATURE && pkey == NULL)) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (meth == OSSL_CRMF_POPO_NONE) goto end; if ((pp = OSSL_CRMF_POPO_new()) == NULL) goto err; pp->type = meth; switch (meth) { case OSSL_CRMF_POPO_RAVERIFIED: if ((pp->value.raVerified = ASN1_NULL_new()) == NULL) goto err; break; case OSSL_CRMF_POPO_SIGNATURE: { OSSL_CRMF_POPOSIGNINGKEY *ps = OSSL_CRMF_POPOSIGNINGKEY_new(); if (ps == NULL) goto err; if (!create_popo_signature(ps, crm->certReq, pkey, digest, libctx, propq)) { OSSL_CRMF_POPOSIGNINGKEY_free(ps); goto err; } pp->value.signature = ps; } break; case OSSL_CRMF_POPO_KEYENC: if ((pp->value.keyEncipherment = OSSL_CRMF_POPOPRIVKEY_new()) == NULL) goto err; tag = ASN1_INTEGER_new(); pp->value.keyEncipherment->type = OSSL_CRMF_POPOPRIVKEY_SUBSEQUENTMESSAGE; pp->value.keyEncipherment->value.subsequentMessage = tag; if (tag == NULL || !ASN1_INTEGER_set(tag, OSSL_CRMF_SUBSEQUENTMESSAGE_ENCRCERT)) goto err; break; default: ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_METHOD_FOR_CREATING_POPO); goto err; } end: OSSL_CRMF_POPO_free(crm->popo); crm->popo = pp; return 1; err: OSSL_CRMF_POPO_free(pp); return 0; } /* verifies the Proof-of-Possession of the request with the given rid in reqs */ int OSSL_CRMF_MSGS_verify_popo(const OSSL_CRMF_MSGS *reqs, int rid, int acceptRAVerified, OSSL_LIB_CTX *libctx, const char *propq) { OSSL_CRMF_MSG *req = NULL; X509_PUBKEY *pubkey = NULL; OSSL_CRMF_POPOSIGNINGKEY *sig = NULL; const ASN1_ITEM *it; void *asn; if (reqs == NULL || (req = sk_OSSL_CRMF_MSG_value(reqs, rid)) == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (req->popo == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_MISSING); return 0; } switch (req->popo->type) { case OSSL_CRMF_POPO_RAVERIFIED: if (!acceptRAVerified) { ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_RAVERIFIED_NOT_ACCEPTED); return 0; } break; case OSSL_CRMF_POPO_SIGNATURE: pubkey = req->certReq->certTemplate->publicKey; if (pubkey == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_MISSING_PUBLIC_KEY); return 0; } sig = req->popo->value.signature; if (sig->poposkInput != NULL) { /* * According to RFC 4211: publicKey contains a copy of * the public key from the certificate template. This MUST be * exactly the same value as contained in the certificate template. */ if (sig->poposkInput->publicKey == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_MISSING_PUBLIC_KEY); return 0; } if (X509_PUBKEY_eq(pubkey, sig->poposkInput->publicKey) != 1) { ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_INCONSISTENT_PUBLIC_KEY); return 0; } /* * Should check at this point the contents of the authInfo sub-field * as requested in FR #19807 according to RFC 4211 section 4.1. */ it = ASN1_ITEM_rptr(OSSL_CRMF_POPOSIGNINGKEYINPUT); asn = sig->poposkInput; } else { if (req->certReq->certTemplate->subject == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_POPO_MISSING_SUBJECT); return 0; } it = ASN1_ITEM_rptr(OSSL_CRMF_CERTREQUEST); asn = req->certReq; } if (ASN1_item_verify_ex(it, sig->algorithmIdentifier, sig->signature, asn, NULL, X509_PUBKEY_get0(pubkey), libctx, propq) < 1) return 0; break; case OSSL_CRMF_POPO_KEYENC: /* * When OSSL_CMP_certrep_new() supports encrypted certs, * should return 1 if the type of req->popo->value.keyEncipherment * is OSSL_CRMF_POPOPRIVKEY_SUBSEQUENTMESSAGE and * its value.subsequentMessage == OSSL_CRMF_SUBSEQUENTMESSAGE_ENCRCERT */ case OSSL_CRMF_POPO_KEYAGREE: default: ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_POPO_METHOD); return 0; } return 1; } X509_PUBKEY *OSSL_CRMF_CERTTEMPLATE_get0_publicKey(const OSSL_CRMF_CERTTEMPLATE *tmpl) { return tmpl != NULL ? tmpl->publicKey : NULL; } const ASN1_INTEGER *OSSL_CRMF_CERTTEMPLATE_get0_serialNumber(const OSSL_CRMF_CERTTEMPLATE *tmpl) { return tmpl != NULL ? tmpl->serialNumber : NULL; } const X509_NAME *OSSL_CRMF_CERTTEMPLATE_get0_subject(const OSSL_CRMF_CERTTEMPLATE *tmpl) { return tmpl != NULL ? tmpl->subject : NULL; } const X509_NAME *OSSL_CRMF_CERTTEMPLATE_get0_issuer(const OSSL_CRMF_CERTTEMPLATE *tmpl) { return tmpl != NULL ? tmpl->issuer : NULL; } X509_EXTENSIONS *OSSL_CRMF_CERTTEMPLATE_get0_extensions(const OSSL_CRMF_CERTTEMPLATE *tmpl) { return tmpl != NULL ? tmpl->extensions : NULL; } const X509_NAME *OSSL_CRMF_CERTID_get0_issuer(const OSSL_CRMF_CERTID *cid) { return cid != NULL && cid->issuer->type == GEN_DIRNAME ? cid->issuer->d.directoryName : NULL; } const ASN1_INTEGER *OSSL_CRMF_CERTID_get0_serialNumber(const OSSL_CRMF_CERTID *cid) { return cid != NULL ? cid->serialNumber : NULL; } /*- * Fill in the certificate template |tmpl|. * Any other NULL argument will leave the respective field unchanged. */ int OSSL_CRMF_CERTTEMPLATE_fill(OSSL_CRMF_CERTTEMPLATE *tmpl, EVP_PKEY *pubkey, const X509_NAME *subject, const X509_NAME *issuer, const ASN1_INTEGER *serial) { if (tmpl == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return 0; } if (subject != NULL && !X509_NAME_set((X509_NAME **)&tmpl->subject, subject)) return 0; if (issuer != NULL && !X509_NAME_set((X509_NAME **)&tmpl->issuer, issuer)) return 0; if (serial != NULL) { ASN1_INTEGER_free(tmpl->serialNumber); if ((tmpl->serialNumber = ASN1_INTEGER_dup(serial)) == NULL) return 0; } if (pubkey != NULL && !X509_PUBKEY_set(&tmpl->publicKey, pubkey)) return 0; return 1; } /*- * Decrypts the certificate in the given encryptedValue using private key pkey. * This is needed for the indirect PoP method as in RFC 4210 section 5.2.8.2. * * returns a pointer to the decrypted certificate * returns NULL on error or if no certificate available */ X509 *OSSL_CRMF_ENCRYPTEDVALUE_get1_encCert(const OSSL_CRMF_ENCRYPTEDVALUE *ecert, OSSL_LIB_CTX *libctx, const char *propq, EVP_PKEY *pkey) { X509 *cert = NULL; /* decrypted certificate */ EVP_CIPHER_CTX *evp_ctx = NULL; /* context for symmetric encryption */ unsigned char *ek = NULL; /* decrypted symmetric encryption key */ size_t eksize = 0; /* size of decrypted symmetric encryption key */ EVP_CIPHER *cipher = NULL; /* used cipher */ int cikeysize = 0; /* key size from cipher */ unsigned char *iv = NULL; /* initial vector for symmetric encryption */ unsigned char *outbuf = NULL; /* decryption output buffer */ const unsigned char *p = NULL; /* needed for decoding ASN1 */ int n, outlen = 0; EVP_PKEY_CTX *pkctx = NULL; /* private key context */ char name[OSSL_MAX_NAME_SIZE]; if (ecert == NULL || ecert->symmAlg == NULL || ecert->encSymmKey == NULL || ecert->encValue == NULL || pkey == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); return NULL; } /* select symmetric cipher based on algorithm given in message */ OBJ_obj2txt(name, sizeof(name), ecert->symmAlg->algorithm, 0); (void)ERR_set_mark(); cipher = EVP_CIPHER_fetch(NULL, name, NULL); if (cipher == NULL) cipher = (EVP_CIPHER *)EVP_get_cipherbyname(name); if (cipher == NULL) { (void)ERR_clear_last_mark(); ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_CIPHER); goto end; } (void)ERR_pop_to_mark(); cikeysize = EVP_CIPHER_get_key_length(cipher); /* first the symmetric key needs to be decrypted */ pkctx = EVP_PKEY_CTX_new_from_pkey(libctx, pkey, propq); if (pkctx == NULL || EVP_PKEY_decrypt_init(pkctx) <= 0 || evp_pkey_decrypt_alloc(pkctx, &ek, &eksize, (size_t)cikeysize, ecert->encSymmKey->data, ecert->encSymmKey->length) <= 0) goto end; if ((iv = OPENSSL_malloc(EVP_CIPHER_get_iv_length(cipher))) == NULL) goto end; if (ASN1_TYPE_get_octetstring(ecert->symmAlg->parameter, iv, EVP_CIPHER_get_iv_length(cipher)) != EVP_CIPHER_get_iv_length(cipher)) { ERR_raise(ERR_LIB_CRMF, CRMF_R_MALFORMED_IV); goto end; } /* * d2i_X509 changes the given pointer, so use p for decoding the message and * keep the original pointer in outbuf so the memory can be freed later */ if ((p = outbuf = OPENSSL_malloc(ecert->encValue->length + EVP_CIPHER_get_block_size(cipher))) == NULL || (evp_ctx = EVP_CIPHER_CTX_new()) == NULL) goto end; EVP_CIPHER_CTX_set_padding(evp_ctx, 0); if (!EVP_DecryptInit(evp_ctx, cipher, ek, iv) || !EVP_DecryptUpdate(evp_ctx, outbuf, &outlen, ecert->encValue->data, ecert->encValue->length) || !EVP_DecryptFinal(evp_ctx, outbuf + outlen, &n)) { ERR_raise(ERR_LIB_CRMF, CRMF_R_ERROR_DECRYPTING_CERTIFICATE); goto end; } outlen += n; /* convert decrypted certificate from DER to internal ASN.1 structure */ if ((cert = X509_new_ex(libctx, propq)) == NULL) goto end; if (d2i_X509(&cert, &p, outlen) == NULL) ERR_raise(ERR_LIB_CRMF, CRMF_R_ERROR_DECODING_CERTIFICATE); end: EVP_PKEY_CTX_free(pkctx); OPENSSL_free(outbuf); EVP_CIPHER_CTX_free(evp_ctx); EVP_CIPHER_free(cipher); OPENSSL_clear_free(ek, eksize); OPENSSL_free(iv); return cert; }
24,223
32.974755
86
c
openssl
openssl-master/crypto/crmf/crmf_local.h
/*- * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * CRMF implementation by Martin Peylo, Miikka Viljanen, and David von Oheimb. */ #ifndef OSSL_CRYPTO_CRMF_LOCAL_H # define OSSL_CRYPTO_CRMF_LOCAL_H # include <openssl/crmf.h> # include <openssl/err.h> /* explicit #includes not strictly needed since implied by the above: */ # include <openssl/types.h> # include <openssl/safestack.h> # include <openssl/x509.h> # include <openssl/x509v3.h> /*- * EncryptedValue ::= SEQUENCE { * intendedAlg [0] AlgorithmIdentifier OPTIONAL, * -- the intended algorithm for which the value will be used * symmAlg [1] AlgorithmIdentifier OPTIONAL, * -- the symmetric algorithm used to encrypt the value * encSymmKey [2] BIT STRING OPTIONAL, * -- the (encrypted) symmetric key used to encrypt the value * keyAlg [3] AlgorithmIdentifier OPTIONAL, * -- algorithm used to encrypt the symmetric key * valueHint [4] OCTET STRING OPTIONAL, * -- a brief description or identifier of the encValue content * -- (may be meaningful only to the sending entity, and * -- used only if EncryptedValue might be re-examined * -- by the sending entity in the future) * encValue BIT STRING * -- the encrypted value itself * } */ struct ossl_crmf_encryptedvalue_st { X509_ALGOR *intendedAlg; /* 0 */ X509_ALGOR *symmAlg; /* 1 */ ASN1_BIT_STRING *encSymmKey; /* 2 */ X509_ALGOR *keyAlg; /* 3 */ ASN1_OCTET_STRING *valueHint; /* 4 */ ASN1_BIT_STRING *encValue; } /* OSSL_CRMF_ENCRYPTEDVALUE */; /*- * Attributes ::= SET OF Attribute * => X509_ATTRIBUTE * * PrivateKeyInfo ::= SEQUENCE { * version INTEGER, * privateKeyAlgorithm AlgorithmIdentifier, * privateKey OCTET STRING, * attributes [0] IMPLICIT Attributes OPTIONAL * } */ typedef struct ossl_crmf_privatekeyinfo_st { ASN1_INTEGER *version; X509_ALGOR *privateKeyAlgorithm; ASN1_OCTET_STRING *privateKey; STACK_OF(X509_ATTRIBUTE) *attributes; /* [ 0 ] */ } OSSL_CRMF_PRIVATEKEYINFO; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_PRIVATEKEYINFO) /*- * section 4.2.1 Private Key Info Content Type * id-ct-encKeyWithID OBJECT IDENTIFIER ::= {id-ct 21} * * EncKeyWithID ::= SEQUENCE { * privateKey PrivateKeyInfo, * identifier CHOICE { * string UTF8String, * generalName GeneralName * } OPTIONAL * } */ typedef struct ossl_crmf_enckeywithid_identifier_st { int type; union { ASN1_UTF8STRING *string; GENERAL_NAME *generalName; } value; } OSSL_CRMF_ENCKEYWITHID_IDENTIFIER; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_ENCKEYWITHID_IDENTIFIER) typedef struct ossl_crmf_enckeywithid_st { OSSL_CRMF_PRIVATEKEYINFO *privateKey; /* [0] */ OSSL_CRMF_ENCKEYWITHID_IDENTIFIER *identifier; } OSSL_CRMF_ENCKEYWITHID; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_ENCKEYWITHID) /*- * CertId ::= SEQUENCE { * issuer GeneralName, * serialNumber INTEGER * } */ struct ossl_crmf_certid_st { GENERAL_NAME *issuer; ASN1_INTEGER *serialNumber; } /* OSSL_CRMF_CERTID */; /*- * SinglePubInfo ::= SEQUENCE { * pubMethod INTEGER { * dontCare (0), * x500 (1), * web (2), * ldap (3) }, * pubLocation GeneralName OPTIONAL * } */ struct ossl_crmf_singlepubinfo_st { ASN1_INTEGER *pubMethod; GENERAL_NAME *pubLocation; } /* OSSL_CRMF_SINGLEPUBINFO */; DEFINE_STACK_OF(OSSL_CRMF_SINGLEPUBINFO) typedef STACK_OF(OSSL_CRMF_SINGLEPUBINFO) OSSL_CRMF_PUBINFOS; /*- * PKIPublicationInfo ::= SEQUENCE { * action INTEGER { * dontPublish (0), * pleasePublish (1) }, * pubInfos SEQUENCE SIZE (1..MAX) OF SinglePubInfo OPTIONAL * -- pubInfos MUST NOT be present if action is "dontPublish" * -- (if action is "pleasePublish" and pubInfos is omitted, * -- "dontCare" is assumed) * } */ struct ossl_crmf_pkipublicationinfo_st { ASN1_INTEGER *action; OSSL_CRMF_PUBINFOS *pubInfos; } /* OSSL_CRMF_PKIPUBLICATIONINFO */; DECLARE_ASN1_DUP_FUNCTION(OSSL_CRMF_PKIPUBLICATIONINFO) /*- * PKMACValue ::= SEQUENCE { * algId AlgorithmIdentifier, * -- algorithm value shall be PasswordBasedMac {1 2 840 113533 7 66 13} * -- parameter value is PBMParameter * value BIT STRING * } */ typedef struct ossl_crmf_pkmacvalue_st { X509_ALGOR *algId; ASN1_BIT_STRING *value; } OSSL_CRMF_PKMACVALUE; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_PKMACVALUE) /*- * SubsequentMessage ::= INTEGER { * encrCert (0), * -- requests that resulting certificate be encrypted for the * -- end entity (following which, POP will be proven in a * -- confirmation message) * challengeResp (1) * -- requests that CA engage in challenge-response exchange with * -- end entity in order to prove private key possession * } * * POPOPrivKey ::= CHOICE { * thisMessage [0] BIT STRING, -- Deprecated * -- possession is proven in this message (which contains the private * -- key itself (encrypted for the CA)) * subsequentMessage [1] SubsequentMessage, * -- possession will be proven in a subsequent message * dhMAC [2] BIT STRING, -- Deprecated * agreeMAC [3] PKMACValue, * encryptedKey [4] EnvelopedData * } */ typedef struct ossl_crmf_popoprivkey_st { int type; union { ASN1_BIT_STRING *thisMessage; /* 0 */ /* Deprecated */ ASN1_INTEGER *subsequentMessage; /* 1 */ ASN1_BIT_STRING *dhMAC; /* 2 */ /* Deprecated */ OSSL_CRMF_PKMACVALUE *agreeMAC; /* 3 */ ASN1_NULL *encryptedKey; /* 4 */ /* When supported, ASN1_NULL needs to be replaced by CMS_ENVELOPEDDATA */ } value; } OSSL_CRMF_POPOPRIVKEY; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_POPOPRIVKEY) /*- * PBMParameter ::= SEQUENCE { * salt OCTET STRING, * owf AlgorithmIdentifier, * -- AlgId for a One-Way Function (SHA-1 recommended) * iterationCount INTEGER, * -- number of times the OWF is applied * mac AlgorithmIdentifier * -- the MAC AlgId (e.g., DES-MAC, Triple-DES-MAC [PKCS11], * -- or HMAC [HMAC, RFC2202]) * } */ struct ossl_crmf_pbmparameter_st { ASN1_OCTET_STRING *salt; X509_ALGOR *owf; ASN1_INTEGER *iterationCount; X509_ALGOR *mac; } /* OSSL_CRMF_PBMPARAMETER */; # define OSSL_CRMF_PBM_MAX_ITERATION_COUNT 100000 /* if too large allows DoS */ /*- * POPOSigningKeyInput ::= SEQUENCE { * authInfo CHOICE { * sender [0] GeneralName, * -- used only if an authenticated identity has been * -- established for the sender (e.g., a DN from a * -- previously-issued and currently-valid certificate) * publicKeyMAC PKMACValue }, * -- used if no authenticated GeneralName currently exists for * -- the sender; publicKeyMAC contains a password-based MAC * -- on the DER-encoded value of publicKey * publicKey SubjectPublicKeyInfo -- from CertTemplate * } */ typedef struct ossl_crmf_poposigningkeyinput_authinfo_st { int type; union { /* 0 */ GENERAL_NAME *sender; /* 1 */ OSSL_CRMF_PKMACVALUE *publicKeyMAC; } value; } OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO) typedef struct ossl_crmf_poposigningkeyinput_st { OSSL_CRMF_POPOSIGNINGKEYINPUT_AUTHINFO *authInfo; X509_PUBKEY *publicKey; } OSSL_CRMF_POPOSIGNINGKEYINPUT; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_POPOSIGNINGKEYINPUT) /*- * POPOSigningKey ::= SEQUENCE { * poposkInput [0] POPOSigningKeyInput OPTIONAL, * algorithmIdentifier AlgorithmIdentifier, * signature BIT STRING * } */ struct ossl_crmf_poposigningkey_st { OSSL_CRMF_POPOSIGNINGKEYINPUT *poposkInput; X509_ALGOR *algorithmIdentifier; ASN1_BIT_STRING *signature; } /* OSSL_CRMF_POPOSIGNINGKEY */; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_POPOSIGNINGKEY) /*- * ProofOfPossession ::= CHOICE { * raVerified [0] NULL, * -- used if the RA has already verified that the requester is in * -- possession of the private key * signature [1] POPOSigningKey, * keyEncipherment [2] POPOPrivKey, * keyAgreement [3] POPOPrivKey * } */ typedef struct ossl_crmf_popo_st { int type; union { ASN1_NULL *raVerified; /* 0 */ OSSL_CRMF_POPOSIGNINGKEY *signature; /* 1 */ OSSL_CRMF_POPOPRIVKEY *keyEncipherment; /* 2 */ OSSL_CRMF_POPOPRIVKEY *keyAgreement; /* 3 */ } value; } OSSL_CRMF_POPO; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_POPO) /*- * OptionalValidity ::= SEQUENCE { * notBefore [0] Time OPTIONAL, * notAfter [1] Time OPTIONAL -- at least one MUST be present * } */ struct ossl_crmf_optionalvalidity_st { /* 0 */ ASN1_TIME *notBefore; /* 1 */ ASN1_TIME *notAfter; } /* OSSL_CRMF_OPTIONALVALIDITY */; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_OPTIONALVALIDITY) /*- * CertTemplate ::= SEQUENCE { * version [0] Version OPTIONAL, * serialNumber [1] INTEGER OPTIONAL, * signingAlg [2] AlgorithmIdentifier OPTIONAL, * issuer [3] Name OPTIONAL, * validity [4] OptionalValidity OPTIONAL, * subject [5] Name OPTIONAL, * publicKey [6] SubjectPublicKeyInfo OPTIONAL, * issuerUID [7] UniqueIdentifier OPTIONAL, * subjectUID [8] UniqueIdentifier OPTIONAL, * extensions [9] Extensions OPTIONAL * } */ struct ossl_crmf_certtemplate_st { ASN1_INTEGER *version; ASN1_INTEGER *serialNumber; /* serialNumber MUST be omitted */ /* This field is assigned by the CA during certificate creation */ X509_ALGOR *signingAlg; /* signingAlg MUST be omitted */ /* This field is assigned by the CA during certificate creation */ const X509_NAME *issuer; OSSL_CRMF_OPTIONALVALIDITY *validity; const X509_NAME *subject; X509_PUBKEY *publicKey; ASN1_BIT_STRING *issuerUID; /* deprecated in version 2 */ /* According to rfc 3280: UniqueIdentifier ::= BIT STRING */ ASN1_BIT_STRING *subjectUID; /* deprecated in version 2 */ /* Could be X509_EXTENSION*S*, but that's only cosmetic */ STACK_OF(X509_EXTENSION) *extensions; } /* OSSL_CRMF_CERTTEMPLATE */; /*- * CertRequest ::= SEQUENCE { * certReqId INTEGER, -- ID for matching request and reply * certTemplate CertTemplate, -- Selected fields of cert to be issued * controls Controls OPTIONAL -- Attributes affecting issuance * } */ struct ossl_crmf_certrequest_st { ASN1_INTEGER *certReqId; OSSL_CRMF_CERTTEMPLATE *certTemplate; STACK_OF(OSSL_CRMF_ATTRIBUTETYPEANDVALUE /* Controls expanded */) *controls; } /* OSSL_CRMF_CERTREQUEST */; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_CERTREQUEST) DECLARE_ASN1_DUP_FUNCTION(OSSL_CRMF_CERTREQUEST) struct ossl_crmf_attributetypeandvalue_st { ASN1_OBJECT *type; union { /* NID_id_regCtrl_regToken */ ASN1_UTF8STRING *regToken; /* NID_id_regCtrl_authenticator */ ASN1_UTF8STRING *authenticator; /* NID_id_regCtrl_pkiPublicationInfo */ OSSL_CRMF_PKIPUBLICATIONINFO *pkiPublicationInfo; /* NID_id_regCtrl_oldCertID */ OSSL_CRMF_CERTID *oldCertID; /* NID_id_regCtrl_protocolEncrKey */ X509_PUBKEY *protocolEncrKey; /* NID_id_regInfo_utf8Pairs */ ASN1_UTF8STRING *utf8Pairs; /* NID_id_regInfo_certReq */ OSSL_CRMF_CERTREQUEST *certReq; ASN1_TYPE *other; } value; } /* OSSL_CRMF_ATTRIBUTETYPEANDVALUE */; DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) DEFINE_STACK_OF(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) DECLARE_ASN1_DUP_FUNCTION(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) /*- * CertReqMessages ::= SEQUENCE SIZE (1..MAX) OF CertReqMsg * CertReqMsg ::= SEQUENCE { * certReq CertRequest, * popo ProofOfPossession OPTIONAL, * -- content depends upon key type * regInfo SEQUENCE SIZE(1..MAX) OF AttributeTypeAndValue OPTIONAL * } */ struct ossl_crmf_msg_st { OSSL_CRMF_CERTREQUEST *certReq; /* 0 */ OSSL_CRMF_POPO *popo; /* 1 */ STACK_OF(OSSL_CRMF_ATTRIBUTETYPEANDVALUE) *regInfo; } /* OSSL_CRMF_MSG */; #endif
13,056
32.826425
81
h
openssl
openssl-master/crypto/crmf/crmf_pbm.c
/*- * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved. * Copyright Nokia 2007-2019 * Copyright Siemens AG 2015-2019 * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html * * CRMF implementation by Martin Peylo, Miikka Viljanen, and David von Oheimb. */ #include <string.h> #include <openssl/rand.h> #include <openssl/evp.h> #include <openssl/hmac.h> /* explicit #includes not strictly needed since implied by the above: */ #include <openssl/asn1t.h> #include <openssl/crmf.h> #include <openssl/err.h> #include <openssl/params.h> #include <openssl/core_names.h> #include "internal/sizes.h" #include "crmf_local.h" /*- * creates and initializes OSSL_CRMF_PBMPARAMETER (section 4.4) * |slen| SHOULD be at least 8 (16 is common) * |owfnid| e.g., NID_sha256 * |itercnt| MUST be >= 100 (e.g., 500) and <= OSSL_CRMF_PBM_MAX_ITERATION_COUNT * |macnid| e.g., NID_hmac_sha1 * returns pointer to OSSL_CRMF_PBMPARAMETER on success, NULL on error */ OSSL_CRMF_PBMPARAMETER *OSSL_CRMF_pbmp_new(OSSL_LIB_CTX *libctx, size_t slen, int owfnid, size_t itercnt, int macnid) { OSSL_CRMF_PBMPARAMETER *pbm = NULL; unsigned char *salt = NULL; if ((pbm = OSSL_CRMF_PBMPARAMETER_new()) == NULL) goto err; /* * salt contains a randomly generated value used in computing the key * of the MAC process. The salt SHOULD be at least 8 octets (64 * bits) long. */ if ((salt = OPENSSL_malloc(slen)) == NULL) goto err; if (RAND_bytes_ex(libctx, salt, slen, 0) <= 0) { ERR_raise(ERR_LIB_CRMF, CRMF_R_FAILURE_OBTAINING_RANDOM); goto err; } if (!ASN1_OCTET_STRING_set(pbm->salt, salt, (int)slen)) goto err; /* * owf identifies the hash algorithm and associated parameters used to * compute the key used in the MAC process. All implementations MUST * support SHA-1. */ if (!X509_ALGOR_set0(pbm->owf, OBJ_nid2obj(owfnid), V_ASN1_UNDEF, NULL)) { ERR_raise(ERR_LIB_CRMF, CRMF_R_SETTING_OWF_ALGOR_FAILURE); goto err; } /* * iterationCount identifies the number of times the hash is applied * during the key computation process. The iterationCount MUST be a * minimum of 100. Many people suggest using values as high as 1000 * iterations as the minimum value. The trade off here is between * protection of the password from attacks and the time spent by the * server processing all of the different iterations in deriving * passwords. Hashing is generally considered a cheap operation but * this may not be true with all hash functions in the future. */ if (itercnt < 100) { ERR_raise(ERR_LIB_CRMF, CRMF_R_ITERATIONCOUNT_BELOW_100); goto err; } if (itercnt > OSSL_CRMF_PBM_MAX_ITERATION_COUNT) { ERR_raise(ERR_LIB_CRMF, CRMF_R_BAD_PBM_ITERATIONCOUNT); goto err; } if (!ASN1_INTEGER_set(pbm->iterationCount, itercnt)) { ERR_raise(ERR_LIB_CRMF, CRMF_R_CRMFERROR); goto err; } /* * mac identifies the algorithm and associated parameters of the MAC * function to be used. All implementations MUST support HMAC-SHA1 [HMAC]. * All implementations SHOULD support DES-MAC and Triple-DES-MAC [PKCS11]. */ if (!X509_ALGOR_set0(pbm->mac, OBJ_nid2obj(macnid), V_ASN1_UNDEF, NULL)) { ERR_raise(ERR_LIB_CRMF, CRMF_R_SETTING_MAC_ALGOR_FAILURE); goto err; } OPENSSL_free(salt); return pbm; err: OPENSSL_free(salt); OSSL_CRMF_PBMPARAMETER_free(pbm); return NULL; } /*- * calculates the PBM based on the settings of the given OSSL_CRMF_PBMPARAMETER * |pbmp| identifies the algorithms, salt to use * |msg| message to apply the PBM for * |msglen| length of the message * |sec| key to use * |seclen| length of the key * |out| pointer to the computed mac, will be set on success * |outlen| if not NULL, will set variable to the length of the mac on success * returns 1 on success, 0 on error */ /* could be combined with other MAC calculations in the library */ int OSSL_CRMF_pbm_new(OSSL_LIB_CTX *libctx, const char *propq, const OSSL_CRMF_PBMPARAMETER *pbmp, const unsigned char *msg, size_t msglen, const unsigned char *sec, size_t seclen, unsigned char **out, size_t *outlen) { int mac_nid, hmac_md_nid = NID_undef; char mdname[OSSL_MAX_NAME_SIZE]; char hmac_mdname[OSSL_MAX_NAME_SIZE]; EVP_MD *owf = NULL; EVP_MD_CTX *ctx = NULL; unsigned char basekey[EVP_MAX_MD_SIZE]; unsigned int bklen = EVP_MAX_MD_SIZE; int64_t iterations; unsigned char *mac_res = 0; int ok = 0; if (out == NULL || pbmp == NULL || pbmp->mac == NULL || pbmp->mac->algorithm == NULL || msg == NULL || sec == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_NULL_ARGUMENT); goto err; } if ((mac_res = OPENSSL_malloc(EVP_MAX_MD_SIZE)) == NULL) goto err; /* * owf identifies the hash algorithm and associated parameters used to * compute the key used in the MAC process. All implementations MUST * support SHA-1. */ OBJ_obj2txt(mdname, sizeof(mdname), pbmp->owf->algorithm, 0); if ((owf = EVP_MD_fetch(libctx, mdname, propq)) == NULL) { ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_ALGORITHM); goto err; } if ((ctx = EVP_MD_CTX_new()) == NULL) goto err; /* compute the basekey of the salted secret */ if (!EVP_DigestInit_ex(ctx, owf, NULL)) goto err; /* first the secret */ if (!EVP_DigestUpdate(ctx, sec, seclen)) goto err; /* then the salt */ if (!EVP_DigestUpdate(ctx, pbmp->salt->data, pbmp->salt->length)) goto err; if (!EVP_DigestFinal_ex(ctx, basekey, &bklen)) goto err; if (!ASN1_INTEGER_get_int64(&iterations, pbmp->iterationCount) || iterations < 100 /* min from RFC */ || iterations > OSSL_CRMF_PBM_MAX_ITERATION_COUNT) { ERR_raise(ERR_LIB_CRMF, CRMF_R_BAD_PBM_ITERATIONCOUNT); goto err; } /* the first iteration was already done above */ while (--iterations > 0) { if (!EVP_DigestInit_ex(ctx, owf, NULL)) goto err; if (!EVP_DigestUpdate(ctx, basekey, bklen)) goto err; if (!EVP_DigestFinal_ex(ctx, basekey, &bklen)) goto err; } /* * mac identifies the algorithm and associated parameters of the MAC * function to be used. All implementations MUST support HMAC-SHA1 [HMAC]. * All implementations SHOULD support DES-MAC and Triple-DES-MAC [PKCS11]. */ mac_nid = OBJ_obj2nid(pbmp->mac->algorithm); if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, mac_nid, NULL, &hmac_md_nid, NULL) || OBJ_obj2txt(hmac_mdname, sizeof(hmac_mdname), OBJ_nid2obj(hmac_md_nid), 0) <= 0) { ERR_raise(ERR_LIB_CRMF, CRMF_R_UNSUPPORTED_ALGORITHM); goto err; } /* could be generalized to allow non-HMAC: */ if (EVP_Q_mac(libctx, "HMAC", propq, hmac_mdname, NULL, basekey, bklen, msg, msglen, mac_res, EVP_MAX_MD_SIZE, outlen) == NULL) goto err; ok = 1; err: OPENSSL_cleanse(basekey, bklen); EVP_MD_free(owf); EVP_MD_CTX_free(ctx); if (ok == 1) { *out = mac_res; return 1; } OPENSSL_free(mac_res); if (pbmp != NULL && pbmp->mac != NULL) { char buf[128]; if (OBJ_obj2txt(buf, sizeof(buf), pbmp->mac->algorithm, 0)) ERR_add_error_data(1, buf); } return 0; }
7,940
32.935897
80
c
openssl
openssl-master/crypto/ct/ct_b64.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 */ #include <limits.h> #include <string.h> #include <openssl/ct.h> #include <openssl/err.h> #include <openssl/evp.h> #include "ct_local.h" /* * Decodes the base64 string |in| into |out|. * A new string will be malloc'd and assigned to |out|. This will be owned by * the caller. Do not provide a pre-allocated string in |out|. */ static int ct_base64_decode(const char *in, unsigned char **out) { size_t inlen = strlen(in); int outlen, i; unsigned char *outbuf = NULL; if (inlen == 0) { *out = NULL; return 0; } outlen = (inlen / 4) * 3; outbuf = OPENSSL_malloc(outlen); if (outbuf == NULL) goto err; outlen = EVP_DecodeBlock(outbuf, (unsigned char *)in, inlen); if (outlen < 0) { ERR_raise(ERR_LIB_CT, CT_R_BASE64_DECODE_ERROR); goto err; } /* Subtract padding bytes from |outlen|. Any more than 2 is malformed. */ i = 0; while (in[--inlen] == '=') { --outlen; if (++i > 2) goto err; } *out = outbuf; return outlen; err: OPENSSL_free(outbuf); return -1; } SCT *SCT_new_from_base64(unsigned char version, const char *logid_base64, ct_log_entry_type_t entry_type, uint64_t timestamp, const char *extensions_base64, const char *signature_base64) { SCT *sct = SCT_new(); unsigned char *dec = NULL; const unsigned char* p = NULL; int declen; if (sct == NULL) { ERR_raise(ERR_LIB_CT, ERR_R_CT_LIB); return NULL; } /* * RFC6962 section 4.1 says we "MUST NOT expect this to be 0", but we * can only construct SCT versions that have been defined. */ if (!SCT_set_version(sct, version)) { ERR_raise(ERR_LIB_CT, CT_R_SCT_UNSUPPORTED_VERSION); goto err; } declen = ct_base64_decode(logid_base64, &dec); if (declen < 0) { ERR_raise(ERR_LIB_CT, X509_R_BASE64_DECODE_ERROR); goto err; } if (!SCT_set0_log_id(sct, dec, declen)) goto err; dec = NULL; declen = ct_base64_decode(extensions_base64, &dec); if (declen < 0) { ERR_raise(ERR_LIB_CT, X509_R_BASE64_DECODE_ERROR); goto err; } SCT_set0_extensions(sct, dec, declen); dec = NULL; declen = ct_base64_decode(signature_base64, &dec); if (declen < 0) { ERR_raise(ERR_LIB_CT, X509_R_BASE64_DECODE_ERROR); goto err; } p = dec; if (o2i_SCT_signature(sct, &p, declen) <= 0) goto err; OPENSSL_free(dec); dec = NULL; SCT_set_timestamp(sct, timestamp); if (!SCT_set_log_entry_type(sct, entry_type)) goto err; return sct; err: OPENSSL_free(dec); SCT_free(sct); return NULL; } /* * Allocate, build and returns a new |ct_log| from input |pkey_base64| * It returns 1 on success, * 0 on decoding failure, or invalid parameter if any * -1 on internal (malloc) failure */ int CTLOG_new_from_base64_ex(CTLOG **ct_log, const char *pkey_base64, const char *name, OSSL_LIB_CTX *libctx, const char *propq) { unsigned char *pkey_der = NULL; int pkey_der_len; const unsigned char *p; EVP_PKEY *pkey = NULL; if (ct_log == NULL) { ERR_raise(ERR_LIB_CT, ERR_R_PASSED_INVALID_ARGUMENT); return 0; } pkey_der_len = ct_base64_decode(pkey_base64, &pkey_der); if (pkey_der_len < 0) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID_KEY); return 0; } p = pkey_der; pkey = d2i_PUBKEY_ex(NULL, &p, pkey_der_len, libctx, propq); OPENSSL_free(pkey_der); if (pkey == NULL) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID_KEY); return 0; } *ct_log = CTLOG_new_ex(pkey, name, libctx, propq); if (*ct_log == NULL) { EVP_PKEY_free(pkey); return 0; } return 1; } int CTLOG_new_from_base64(CTLOG **ct_log, const char *pkey_base64, const char *name) { return CTLOG_new_from_base64_ex(ct_log, pkey_base64, name, NULL, NULL); }
4,473
24.565714
78
c
openssl
openssl-master/crypto/ct/ct_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/cterr.h> #include "crypto/cterr.h" #ifndef OPENSSL_NO_CT # ifndef OPENSSL_NO_ERR static const ERR_STRING_DATA CT_str_reasons[] = { {ERR_PACK(ERR_LIB_CT, 0, CT_R_BASE64_DECODE_ERROR), "base64 decode error"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_INVALID_LOG_ID_LENGTH), "invalid log id length"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_CONF_INVALID), "log conf invalid"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_CONF_INVALID_KEY), "log conf invalid key"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_CONF_MISSING_DESCRIPTION), "log conf missing description"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_CONF_MISSING_KEY), "log conf missing key"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_LOG_KEY_INVALID), "log key invalid"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_FUTURE_TIMESTAMP), "sct future timestamp"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_INVALID), "sct invalid"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_INVALID_SIGNATURE), "sct invalid signature"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_LIST_INVALID), "sct list invalid"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_LOG_ID_MISMATCH), "sct log id mismatch"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_NOT_SET), "sct not set"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_SCT_UNSUPPORTED_VERSION), "sct unsupported version"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_UNRECOGNIZED_SIGNATURE_NID), "unrecognized signature nid"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_UNSUPPORTED_ENTRY_TYPE), "unsupported entry type"}, {ERR_PACK(ERR_LIB_CT, 0, CT_R_UNSUPPORTED_VERSION), "unsupported version"}, {0, NULL} }; # endif int ossl_err_load_CT_strings(void) { # ifndef OPENSSL_NO_ERR if (ERR_reason_error_string(CT_str_reasons[0].error) == NULL) ERR_load_strings_const(CT_str_reasons); # endif return 1; } #else NON_EMPTY_TRANSLATION_UNIT #endif
2,226
34.919355
79
c
openssl
openssl-master/crypto/ct/ct_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 <stddef.h> #include <openssl/ct.h> #include <openssl/evp.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #include <openssl/safestack.h> /* * From RFC6962: opaque SerializedSCT<1..2^16-1>; struct { SerializedSCT * sct_list <1..2^16-1>; } SignedCertificateTimestampList; */ # define MAX_SCT_SIZE 65535 # define MAX_SCT_LIST_SIZE MAX_SCT_SIZE /* * Macros to read and write integers in network-byte order. */ #define n2s(c,s) ((s=(((unsigned int)((c)[0]))<< 8)| \ (((unsigned int)((c)[1])) )),c+=2) #define s2n(s,c) ((c[0]=(unsigned char)(((s)>> 8)&0xff), \ c[1]=(unsigned char)(((s) )&0xff)),c+=2) #define l2n3(l,c) ((c[0]=(unsigned char)(((l)>>16)&0xff), \ c[1]=(unsigned char)(((l)>> 8)&0xff), \ c[2]=(unsigned char)(((l) )&0xff)),c+=3) #define n2l8(c,l) (l =((uint64_t)(*((c)++)))<<56, \ l|=((uint64_t)(*((c)++)))<<48, \ l|=((uint64_t)(*((c)++)))<<40, \ l|=((uint64_t)(*((c)++)))<<32, \ l|=((uint64_t)(*((c)++)))<<24, \ l|=((uint64_t)(*((c)++)))<<16, \ l|=((uint64_t)(*((c)++)))<< 8, \ l|=((uint64_t)(*((c)++)))) #define l2n8(l,c) (*((c)++)=(unsigned char)(((l)>>56)&0xff), \ *((c)++)=(unsigned char)(((l)>>48)&0xff), \ *((c)++)=(unsigned char)(((l)>>40)&0xff), \ *((c)++)=(unsigned char)(((l)>>32)&0xff), \ *((c)++)=(unsigned char)(((l)>>24)&0xff), \ *((c)++)=(unsigned char)(((l)>>16)&0xff), \ *((c)++)=(unsigned char)(((l)>> 8)&0xff), \ *((c)++)=(unsigned char)(((l) )&0xff)) /* Signed Certificate Timestamp */ struct sct_st { sct_version_t version; /* If version is not SCT_VERSION_V1, this contains the encoded SCT */ unsigned char *sct; size_t sct_len; /* If version is SCT_VERSION_V1, fields below contain components of the SCT */ unsigned char *log_id; size_t log_id_len; /* * Note, we cannot distinguish between an unset timestamp, and one * that is set to 0. However since CT didn't exist in 1970, no real * SCT should ever be set as such. */ uint64_t timestamp; unsigned char *ext; size_t ext_len; unsigned char hash_alg; unsigned char sig_alg; unsigned char *sig; size_t sig_len; /* Log entry type */ ct_log_entry_type_t entry_type; /* Where this SCT was found, e.g. certificate, OCSP response, etc. */ sct_source_t source; /* The result of the last attempt to validate this SCT. */ sct_validation_status_t validation_status; }; /* Miscellaneous data that is useful when verifying an SCT */ struct sct_ctx_st { /* Public key */ EVP_PKEY *pkey; /* Hash of public key */ unsigned char *pkeyhash; size_t pkeyhashlen; /* For pre-certificate: issuer public key hash */ unsigned char *ihash; size_t ihashlen; /* certificate encoding */ unsigned char *certder; size_t certderlen; /* pre-certificate encoding */ unsigned char *preder; size_t prederlen; /* milliseconds since epoch (to check that the SCT isn't from the future) */ uint64_t epoch_time_in_ms; OSSL_LIB_CTX *libctx; char *propq; }; /* Context when evaluating whether a Certificate Transparency policy is met */ struct ct_policy_eval_ctx_st { X509 *cert; X509 *issuer; CTLOG_STORE *log_store; /* milliseconds since epoch (to check that SCTs aren't from the future) */ uint64_t epoch_time_in_ms; OSSL_LIB_CTX *libctx; char *propq; }; /* * Creates a new context for verifying an SCT. */ SCT_CTX *SCT_CTX_new(OSSL_LIB_CTX *ctx, const char *propq); /* * Deletes an SCT verification context. */ void SCT_CTX_free(SCT_CTX *sctx); /* * Sets the certificate that the SCT was created for. * If *cert does not have a poison extension, presigner must be NULL. * If *cert does not have a poison extension, it may have a single SCT * (NID_ct_precert_scts) extension. * If either *cert or *presigner have an AKID (NID_authority_key_identifier) * extension, both must have one. * Returns 1 on success, 0 on failure. */ __owur int SCT_CTX_set1_cert(SCT_CTX *sctx, X509 *cert, X509 *presigner); /* * Sets the issuer of the certificate that the SCT was created for. * This is just a convenience method to save extracting the public key and * calling SCT_CTX_set1_issuer_pubkey(). * Issuer must not be NULL. * Returns 1 on success, 0 on failure. */ __owur int SCT_CTX_set1_issuer(SCT_CTX *sctx, const X509 *issuer); /* * Sets the public key of the issuer of the certificate that the SCT was created * for. * The public key must not be NULL. * Returns 1 on success, 0 on failure. */ __owur int SCT_CTX_set1_issuer_pubkey(SCT_CTX *sctx, X509_PUBKEY *pubkey); /* * Sets the public key of the CT log that the SCT is from. * Returns 1 on success, 0 on failure. */ __owur int SCT_CTX_set1_pubkey(SCT_CTX *sctx, X509_PUBKEY *pubkey); /* * Sets the time to evaluate the SCT against, in milliseconds since the Unix * epoch. If the SCT's timestamp is after this time, it will be interpreted as * having been issued in the future. RFC6962 states that "TLS clients MUST * reject SCTs whose timestamp is in the future", so an SCT will not validate * in this case. */ void SCT_CTX_set_time(SCT_CTX *sctx, uint64_t time_in_ms); /* * Verifies an SCT with the given context. * Returns 1 if the SCT verifies successfully; any other value indicates * failure. See EVP_DigestVerifyFinal() for the meaning of those values. */ __owur int SCT_CTX_verify(const SCT_CTX *sctx, const SCT *sct); /* * Does this SCT have the minimum fields populated to be usable? * Returns 1 if so, 0 otherwise. */ __owur int SCT_is_complete(const SCT *sct); /* * Does this SCT have the signature-related fields populated? * Returns 1 if so, 0 otherwise. * This checks that the signature and hash algorithms are set to supported * values and that the signature field is set. */ __owur int SCT_signature_is_complete(const SCT *sct); /* * Serialize (to TLS format) an |sct| signature and write it to |out|. * If |out| is null, no signature will be output but the length will be returned. * If |out| points to a null pointer, a string will be allocated to hold the * TLS-format signature. It is the responsibility of the caller to free it. * If |out| points to an allocated string, the signature will be written to it. * The length of the signature in TLS format will be returned. */ __owur int i2o_SCT_signature(const SCT *sct, unsigned char **out); /* * Parses an SCT signature in TLS format and populates the |sct| with it. * |in| should be a pointer to a string containing the TLS-format signature. * |in| will be advanced to the end of the signature if parsing succeeds. * |len| should be the length of the signature in |in|. * Returns the number of bytes parsed, or a negative integer if an error occurs. * If an error occurs, the SCT's signature NID may be updated whilst the * signature field itself remains unset. */ __owur int o2i_SCT_signature(SCT *sct, const unsigned char **in, size_t len); /* * Handlers for Certificate Transparency X509v3/OCSP extensions */ extern const X509V3_EXT_METHOD ossl_v3_ct_scts[3];
7,873
35.119266
82
h
openssl
openssl-master/crypto/ct/ct_log.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 */ #include <stdlib.h> #include <string.h> #include <openssl/conf.h> #include <openssl/ct.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/safestack.h> #include "internal/cryptlib.h" /* * Information about a CT log server. */ struct ctlog_st { OSSL_LIB_CTX *libctx; char *propq; char *name; uint8_t log_id[CT_V1_HASHLEN]; EVP_PKEY *public_key; }; /* * A store for multiple CTLOG instances. * It takes ownership of any CTLOG instances added to it. */ struct ctlog_store_st { OSSL_LIB_CTX *libctx; char *propq; STACK_OF(CTLOG) *logs; }; /* The context when loading a CT log list from a CONF file. */ typedef struct ctlog_store_load_ctx_st { CTLOG_STORE *log_store; CONF *conf; size_t invalid_log_entries; } CTLOG_STORE_LOAD_CTX; /* * Creates an empty context for loading a CT log store. * It should be populated before use. */ static CTLOG_STORE_LOAD_CTX *ctlog_store_load_ctx_new(void); /* * Deletes a CT log store load context. * Does not delete any of the fields. */ static void ctlog_store_load_ctx_free(CTLOG_STORE_LOAD_CTX* ctx); static CTLOG_STORE_LOAD_CTX *ctlog_store_load_ctx_new(void) { CTLOG_STORE_LOAD_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx)); return ctx; } static void ctlog_store_load_ctx_free(CTLOG_STORE_LOAD_CTX* ctx) { OPENSSL_free(ctx); } /* Converts a log's public key into a SHA256 log ID */ static int ct_v1_log_id_from_pkey(CTLOG *log, EVP_PKEY *pkey) { int ret = 0; unsigned char *pkey_der = NULL; int pkey_der_len = i2d_PUBKEY(pkey, &pkey_der); unsigned int len; EVP_MD *sha256 = NULL; if (pkey_der_len <= 0) { ERR_raise(ERR_LIB_CT, CT_R_LOG_KEY_INVALID); goto err; } sha256 = EVP_MD_fetch(log->libctx, "SHA2-256", log->propq); if (sha256 == NULL) { ERR_raise(ERR_LIB_CT, ERR_R_EVP_LIB); goto err; } ret = EVP_Digest(pkey_der, pkey_der_len, log->log_id, &len, sha256, NULL); err: EVP_MD_free(sha256); OPENSSL_free(pkey_der); return ret; } CTLOG_STORE *CTLOG_STORE_new_ex(OSSL_LIB_CTX *libctx, const char *propq) { CTLOG_STORE *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->libctx = libctx; if (propq != NULL) { ret->propq = OPENSSL_strdup(propq); if (ret->propq == NULL) goto err; } ret->logs = sk_CTLOG_new_null(); if (ret->logs == NULL) { ERR_raise(ERR_LIB_CT, ERR_R_CRYPTO_LIB); goto err; } return ret; err: CTLOG_STORE_free(ret); return NULL; } CTLOG_STORE *CTLOG_STORE_new(void) { return CTLOG_STORE_new_ex(NULL, NULL); } void CTLOG_STORE_free(CTLOG_STORE *store) { if (store != NULL) { OPENSSL_free(store->propq); sk_CTLOG_pop_free(store->logs, CTLOG_free); OPENSSL_free(store); } } static int ctlog_new_from_conf(CTLOG_STORE *store, CTLOG **ct_log, const CONF *conf, const char *section) { const char *description = NCONF_get_string(conf, section, "description"); char *pkey_base64; if (description == NULL) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_MISSING_DESCRIPTION); return 0; } pkey_base64 = NCONF_get_string(conf, section, "key"); if (pkey_base64 == NULL) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_MISSING_KEY); return 0; } return CTLOG_new_from_base64_ex(ct_log, pkey_base64, description, store->libctx, store->propq); } int CTLOG_STORE_load_default_file(CTLOG_STORE *store) { const char *fpath = ossl_safe_getenv(CTLOG_FILE_EVP); if (fpath == NULL) fpath = CTLOG_FILE; return CTLOG_STORE_load_file(store, fpath); } /* * Called by CONF_parse_list, which stops if this returns <= 0, * Otherwise, one bad log entry would stop loading of any of * the following log entries. * It may stop parsing and returns -1 on any internal (malloc) error. */ static int ctlog_store_load_log(const char *log_name, int log_name_len, void *arg) { CTLOG_STORE_LOAD_CTX *load_ctx = arg; CTLOG *ct_log = NULL; /* log_name may not be null-terminated, so fix that before using it */ char *tmp; int ret = 0; /* log_name will be NULL for empty list entries */ if (log_name == NULL) return 1; tmp = OPENSSL_strndup(log_name, log_name_len); if (tmp == NULL) return -1; ret = ctlog_new_from_conf(load_ctx->log_store, &ct_log, load_ctx->conf, tmp); OPENSSL_free(tmp); if (ret < 0) { /* Propagate any internal error */ return ret; } if (ret == 0) { /* If we can't load this log, record that fact and skip it */ ++load_ctx->invalid_log_entries; return 1; } if (!sk_CTLOG_push(load_ctx->log_store->logs, ct_log)) { CTLOG_free(ct_log); ERR_raise(ERR_LIB_CT, ERR_R_CRYPTO_LIB); return -1; } return 1; } int CTLOG_STORE_load_file(CTLOG_STORE *store, const char *file) { int ret = 0; char *enabled_logs; CTLOG_STORE_LOAD_CTX* load_ctx = ctlog_store_load_ctx_new(); if (load_ctx == NULL) return 0; load_ctx->log_store = store; load_ctx->conf = NCONF_new(NULL); if (load_ctx->conf == NULL) goto end; if (NCONF_load(load_ctx->conf, file, NULL) <= 0) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID); goto end; } enabled_logs = NCONF_get_string(load_ctx->conf, NULL, "enabled_logs"); if (enabled_logs == NULL) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID); goto end; } if (!CONF_parse_list(enabled_logs, ',', 1, ctlog_store_load_log, load_ctx) || load_ctx->invalid_log_entries > 0) { ERR_raise(ERR_LIB_CT, CT_R_LOG_CONF_INVALID); goto end; } ret = 1; end: NCONF_free(load_ctx->conf); ctlog_store_load_ctx_free(load_ctx); return ret; } /* * Initialize a new CTLOG object. * Takes ownership of the public key. * Copies the name. */ CTLOG *CTLOG_new_ex(EVP_PKEY *public_key, const char *name, OSSL_LIB_CTX *libctx, const char *propq) { CTLOG *ret = OPENSSL_zalloc(sizeof(*ret)); if (ret == NULL) return NULL; ret->libctx = libctx; if (propq != NULL) { ret->propq = OPENSSL_strdup(propq); if (ret->propq == NULL) goto err; } ret->name = OPENSSL_strdup(name); if (ret->name == NULL) goto err; if (ct_v1_log_id_from_pkey(ret, public_key) != 1) goto err; ret->public_key = public_key; return ret; err: CTLOG_free(ret); return NULL; } CTLOG *CTLOG_new(EVP_PKEY *public_key, const char *name) { return CTLOG_new_ex(public_key, name, NULL, NULL); } /* Frees CT log and associated structures */ void CTLOG_free(CTLOG *log) { if (log != NULL) { OPENSSL_free(log->name); EVP_PKEY_free(log->public_key); OPENSSL_free(log->propq); OPENSSL_free(log); } } const char *CTLOG_get0_name(const CTLOG *log) { return log->name; } void CTLOG_get0_log_id(const CTLOG *log, const uint8_t **log_id, size_t *log_id_len) { *log_id = log->log_id; *log_id_len = CT_V1_HASHLEN; } EVP_PKEY *CTLOG_get0_public_key(const CTLOG *log) { return log->public_key; } /* * Given a log ID, finds the matching log. * Returns NULL if no match found. */ const CTLOG *CTLOG_STORE_get0_log_by_id(const CTLOG_STORE *store, const uint8_t *log_id, size_t log_id_len) { int i; for (i = 0; i < sk_CTLOG_num(store->logs); ++i) { const CTLOG *log = sk_CTLOG_value(store->logs, i); if (memcmp(log->log_id, log_id, log_id_len) == 0) return log; } return NULL; }
8,251
23.486647
81
c
openssl
openssl-master/crypto/ct/ct_oct.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifdef OPENSSL_NO_CT # error "CT is disabled" #endif #include <limits.h> #include <string.h> #include <openssl/asn1.h> #include <openssl/buffer.h> #include <openssl/ct.h> #include <openssl/err.h> #include "ct_local.h" int o2i_SCT_signature(SCT *sct, const unsigned char **in, size_t len) { size_t siglen; size_t len_remaining = len; const unsigned char *p; if (sct->version != SCT_VERSION_V1) { ERR_raise(ERR_LIB_CT, CT_R_UNSUPPORTED_VERSION); return -1; } /* * digitally-signed struct header: (1 byte) Hash algorithm (1 byte) * Signature algorithm (2 bytes + ?) Signature * * This explicitly rejects empty signatures: they're invalid for * all supported algorithms. */ if (len <= 4) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID_SIGNATURE); return -1; } p = *in; /* Get hash and signature algorithm */ sct->hash_alg = *p++; sct->sig_alg = *p++; if (SCT_get_signature_nid(sct) == NID_undef) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID_SIGNATURE); return -1; } /* Retrieve signature and check it is consistent with the buffer length */ n2s(p, siglen); len_remaining -= (p - *in); if (siglen > len_remaining) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID_SIGNATURE); return -1; } if (SCT_set1_signature(sct, p, siglen) != 1) return -1; len_remaining -= siglen; *in = p + siglen; return len - len_remaining; } SCT *o2i_SCT(SCT **psct, const unsigned char **in, size_t len) { SCT *sct = NULL; const unsigned char *p; if (len == 0 || len > MAX_SCT_SIZE) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID); goto err; } if ((sct = SCT_new()) == NULL) goto err; p = *in; sct->version = *p; if (sct->version == SCT_VERSION_V1) { int sig_len; size_t len2; /*- * Fixed-length header: * struct { * Version sct_version; (1 byte) * log_id id; (32 bytes) * uint64 timestamp; (8 bytes) * CtExtensions extensions; (2 bytes + ?) * } */ if (len < 43) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID); goto err; } len -= 43; p++; sct->log_id = OPENSSL_memdup(p, CT_V1_HASHLEN); if (sct->log_id == NULL) goto err; sct->log_id_len = CT_V1_HASHLEN; p += CT_V1_HASHLEN; n2l8(p, sct->timestamp); n2s(p, len2); if (len < len2) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID); goto err; } if (len2 > 0) { sct->ext = OPENSSL_memdup(p, len2); if (sct->ext == NULL) goto err; } sct->ext_len = len2; p += len2; len -= len2; sig_len = o2i_SCT_signature(sct, &p, len); if (sig_len <= 0) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID); goto err; } len -= sig_len; *in = p + len; } else { /* If not V1 just cache encoding */ sct->sct = OPENSSL_memdup(p, len); if (sct->sct == NULL) goto err; sct->sct_len = len; *in = p + len; } if (psct != NULL) { SCT_free(*psct); *psct = sct; } return sct; err: SCT_free(sct); return NULL; } int i2o_SCT_signature(const SCT *sct, unsigned char **out) { size_t len; unsigned char *p = NULL, *pstart = NULL; if (!SCT_signature_is_complete(sct)) { ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID_SIGNATURE); goto err; } if (sct->version != SCT_VERSION_V1) { ERR_raise(ERR_LIB_CT, CT_R_UNSUPPORTED_VERSION); goto err; } /* * (1 byte) Hash algorithm * (1 byte) Signature algorithm * (2 bytes + ?) Signature */ len = 4 + sct->sig_len; if (out != NULL) { if (*out != NULL) { p = *out; *out += len; } else { pstart = p = OPENSSL_malloc(len); if (p == NULL) goto err; *out = p; } *p++ = sct->hash_alg; *p++ = sct->sig_alg; s2n(sct->sig_len, p); memcpy(p, sct->sig, sct->sig_len); } return len; err: OPENSSL_free(pstart); return -1; } int i2o_SCT(const SCT *sct, unsigned char **out) { size_t len; unsigned char *p = NULL, *pstart = NULL; if (!SCT_is_complete(sct)) { ERR_raise(ERR_LIB_CT, CT_R_SCT_NOT_SET); goto err; } /* * Fixed-length header: struct { (1 byte) Version sct_version; (32 bytes) * log_id id; (8 bytes) uint64 timestamp; (2 bytes + ?) CtExtensions * extensions; (1 byte) Hash algorithm (1 byte) Signature algorithm (2 * bytes + ?) Signature */ if (sct->version == SCT_VERSION_V1) len = 43 + sct->ext_len + 4 + sct->sig_len; else len = sct->sct_len; if (out == NULL) return len; if (*out != NULL) { p = *out; *out += len; } else { pstart = p = OPENSSL_malloc(len); if (p == NULL) goto err; *out = p; } if (sct->version == SCT_VERSION_V1) { *p++ = sct->version; memcpy(p, sct->log_id, CT_V1_HASHLEN); p += CT_V1_HASHLEN; l2n8(sct->timestamp, p); s2n(sct->ext_len, p); if (sct->ext_len > 0) { memcpy(p, sct->ext, sct->ext_len); p += sct->ext_len; } if (i2o_SCT_signature(sct, &p) <= 0) goto err; } else { memcpy(p, sct->sct, len); } return len; err: OPENSSL_free(pstart); return -1; } STACK_OF(SCT) *o2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp, size_t len) { STACK_OF(SCT) *sk = NULL; size_t list_len, sct_len; if (len < 2 || len > MAX_SCT_LIST_SIZE) { ERR_raise(ERR_LIB_CT, CT_R_SCT_LIST_INVALID); return NULL; } n2s(*pp, list_len); if (list_len != len - 2) { ERR_raise(ERR_LIB_CT, CT_R_SCT_LIST_INVALID); return NULL; } if (a == NULL || *a == NULL) { sk = sk_SCT_new_null(); if (sk == NULL) return NULL; } else { SCT *sct; /* Use the given stack, but empty it first. */ sk = *a; while ((sct = sk_SCT_pop(sk)) != NULL) SCT_free(sct); } while (list_len > 0) { SCT *sct; if (list_len < 2) { ERR_raise(ERR_LIB_CT, CT_R_SCT_LIST_INVALID); goto err; } n2s(*pp, sct_len); list_len -= 2; if (sct_len == 0 || sct_len > list_len) { ERR_raise(ERR_LIB_CT, CT_R_SCT_LIST_INVALID); goto err; } list_len -= sct_len; if ((sct = o2i_SCT(NULL, pp, sct_len)) == NULL) goto err; if (!sk_SCT_push(sk, sct)) { SCT_free(sct); goto err; } } if (a != NULL && *a == NULL) *a = sk; return sk; err: if (a == NULL || *a == NULL) SCT_LIST_free(sk); return NULL; } int i2o_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **pp) { int len, sct_len, i, is_pp_new = 0; size_t len2; unsigned char *p = NULL, *p2; if (pp != NULL) { if (*pp == NULL) { if ((len = i2o_SCT_LIST(a, NULL)) == -1) { ERR_raise(ERR_LIB_CT, CT_R_SCT_LIST_INVALID); return -1; } if ((*pp = OPENSSL_malloc(len)) == NULL) return -1; is_pp_new = 1; } p = *pp + 2; } len2 = 2; for (i = 0; i < sk_SCT_num(a); i++) { if (pp != NULL) { p2 = p; p += 2; if ((sct_len = i2o_SCT(sk_SCT_value(a, i), &p)) == -1) goto err; s2n(sct_len, p2); } else { if ((sct_len = i2o_SCT(sk_SCT_value(a, i), NULL)) == -1) goto err; } len2 += 2 + sct_len; } if (len2 > MAX_SCT_LIST_SIZE) goto err; if (pp != NULL) { p = *pp; s2n(len2 - 2, p); if (!is_pp_new) *pp += len2; } return len2; err: if (is_pp_new) { OPENSSL_free(*pp); *pp = NULL; } return -1; } STACK_OF(SCT) *d2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp, long len) { ASN1_OCTET_STRING *oct = NULL; STACK_OF(SCT) *sk = NULL; const unsigned char *p; p = *pp; if (d2i_ASN1_OCTET_STRING(&oct, &p, len) == NULL) return NULL; p = oct->data; if ((sk = o2i_SCT_LIST(a, &p, oct->length)) != NULL) *pp += len; ASN1_OCTET_STRING_free(oct); return sk; } int i2d_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **out) { ASN1_OCTET_STRING oct; int len; oct.data = NULL; if ((oct.length = i2o_SCT_LIST(a, &oct.data)) == -1) return -1; len = i2d_ASN1_OCTET_STRING(&oct, out); OPENSSL_free(oct.data); return len; }
9,514
22.669154
78
c
openssl
openssl-master/crypto/ct/ct_policy.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifdef OPENSSL_NO_CT # error "CT is disabled" #endif #include <openssl/ct.h> #include <openssl/err.h> #include "internal/time.h" #include "ct_local.h" /* * Number of seconds in the future that an SCT timestamp can be, by default, * without being considered invalid. This is added to time() when setting a * default value for CT_POLICY_EVAL_CTX.epoch_time_in_ms. * It can be overridden by calling CT_POLICY_EVAL_CTX_set_time(). */ static const time_t SCT_CLOCK_DRIFT_TOLERANCE = 300; CT_POLICY_EVAL_CTX *CT_POLICY_EVAL_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq) { CT_POLICY_EVAL_CTX *ctx = OPENSSL_zalloc(sizeof(CT_POLICY_EVAL_CTX)); OSSL_TIME now; if (ctx == NULL) return NULL; ctx->libctx = libctx; if (propq != NULL) { ctx->propq = OPENSSL_strdup(propq); if (ctx->propq == NULL) { OPENSSL_free(ctx); return NULL; } } now = ossl_time_add(ossl_time_now(), ossl_seconds2time(SCT_CLOCK_DRIFT_TOLERANCE)); ctx->epoch_time_in_ms = ossl_time2ms(now); return ctx; } CT_POLICY_EVAL_CTX *CT_POLICY_EVAL_CTX_new(void) { return CT_POLICY_EVAL_CTX_new_ex(NULL, NULL); } void CT_POLICY_EVAL_CTX_free(CT_POLICY_EVAL_CTX *ctx) { if (ctx == NULL) return; X509_free(ctx->cert); X509_free(ctx->issuer); OPENSSL_free(ctx->propq); OPENSSL_free(ctx); } int CT_POLICY_EVAL_CTX_set1_cert(CT_POLICY_EVAL_CTX *ctx, X509 *cert) { if (!X509_up_ref(cert)) return 0; ctx->cert = cert; return 1; } int CT_POLICY_EVAL_CTX_set1_issuer(CT_POLICY_EVAL_CTX *ctx, X509 *issuer) { if (!X509_up_ref(issuer)) return 0; ctx->issuer = issuer; return 1; } void CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(CT_POLICY_EVAL_CTX *ctx, CTLOG_STORE *log_store) { ctx->log_store = log_store; } void CT_POLICY_EVAL_CTX_set_time(CT_POLICY_EVAL_CTX *ctx, uint64_t time_in_ms) { ctx->epoch_time_in_ms = time_in_ms; } X509* CT_POLICY_EVAL_CTX_get0_cert(const CT_POLICY_EVAL_CTX *ctx) { return ctx->cert; } X509* CT_POLICY_EVAL_CTX_get0_issuer(const CT_POLICY_EVAL_CTX *ctx) { return ctx->issuer; } const CTLOG_STORE *CT_POLICY_EVAL_CTX_get0_log_store(const CT_POLICY_EVAL_CTX *ctx) { return ctx->log_store; } uint64_t CT_POLICY_EVAL_CTX_get_time(const CT_POLICY_EVAL_CTX *ctx) { return ctx->epoch_time_in_ms; }
2,829
23.824561
83
c
openssl
openssl-master/crypto/ct/ct_prn.c
/* * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifdef OPENSSL_NO_CT # error "CT is disabled" #endif #include <openssl/asn1.h> #include <openssl/bio.h> #include "ct_local.h" static void SCT_signature_algorithms_print(const SCT *sct, BIO *out) { int nid = SCT_get_signature_nid(sct); if (nid == NID_undef) BIO_printf(out, "%02X%02X", sct->hash_alg, sct->sig_alg); else BIO_printf(out, "%s", OBJ_nid2ln(nid)); } static void timestamp_print(uint64_t timestamp, BIO *out) { ASN1_GENERALIZEDTIME *gen = ASN1_GENERALIZEDTIME_new(); char genstr[20]; if (gen == NULL) return; ASN1_GENERALIZEDTIME_adj(gen, (time_t)0, (int)(timestamp / 86400000), (timestamp % 86400000) / 1000); /* * Note GeneralizedTime from ASN1_GENERALIZETIME_adj is always 15 * characters long with a final Z. Update it with fractional seconds. */ BIO_snprintf(genstr, sizeof(genstr), "%.14s.%03dZ", ASN1_STRING_get0_data(gen), (unsigned int)(timestamp % 1000)); if (ASN1_GENERALIZEDTIME_set_string(gen, genstr)) ASN1_GENERALIZEDTIME_print(out, gen); ASN1_GENERALIZEDTIME_free(gen); } const char *SCT_validation_status_string(const SCT *sct) { switch (SCT_get_validation_status(sct)) { case SCT_VALIDATION_STATUS_NOT_SET: return "not set"; case SCT_VALIDATION_STATUS_UNKNOWN_VERSION: return "unknown version"; case SCT_VALIDATION_STATUS_UNKNOWN_LOG: return "unknown log"; case SCT_VALIDATION_STATUS_UNVERIFIED: return "unverified"; case SCT_VALIDATION_STATUS_INVALID: return "invalid"; case SCT_VALIDATION_STATUS_VALID: return "valid"; } return "unknown status"; } void SCT_print(const SCT *sct, BIO *out, int indent, const CTLOG_STORE *log_store) { const CTLOG *log = NULL; if (log_store != NULL) { log = CTLOG_STORE_get0_log_by_id(log_store, sct->log_id, sct->log_id_len); } BIO_printf(out, "%*sSigned Certificate Timestamp:", indent, ""); BIO_printf(out, "\n%*sVersion : ", indent + 4, ""); if (sct->version != SCT_VERSION_V1) { BIO_printf(out, "unknown\n%*s", indent + 16, ""); BIO_hex_string(out, indent + 16, 16, sct->sct, sct->sct_len); return; } BIO_printf(out, "v1 (0x0)"); if (log != NULL) { BIO_printf(out, "\n%*sLog : %s", indent + 4, "", CTLOG_get0_name(log)); } BIO_printf(out, "\n%*sLog ID : ", indent + 4, ""); BIO_hex_string(out, indent + 16, 16, sct->log_id, sct->log_id_len); BIO_printf(out, "\n%*sTimestamp : ", indent + 4, ""); timestamp_print(sct->timestamp, out); BIO_printf(out, "\n%*sExtensions: ", indent + 4, ""); if (sct->ext_len == 0) BIO_printf(out, "none"); else BIO_hex_string(out, indent + 16, 16, sct->ext, sct->ext_len); BIO_printf(out, "\n%*sSignature : ", indent + 4, ""); SCT_signature_algorithms_print(sct, out); BIO_printf(out, "\n%*s ", indent + 4, ""); BIO_hex_string(out, indent + 16, 16, sct->sig, sct->sig_len); } void SCT_LIST_print(const STACK_OF(SCT) *sct_list, BIO *out, int indent, const char *separator, const CTLOG_STORE *log_store) { int sct_count = sk_SCT_num(sct_list); int i; for (i = 0; i < sct_count; ++i) { SCT *sct = sk_SCT_value(sct_list, i); SCT_print(sct, out, indent, log_store); if (i < sk_SCT_num(sct_list) - 1) BIO_printf(out, "%s", separator); } }
3,947
29.84375
79
c
openssl
openssl-master/crypto/ct/ct_sct.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 */ #ifdef OPENSSL_NO_CT # error "CT disabled" #endif #include <openssl/ct.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/tls1.h> #include <openssl/x509.h> #include "ct_local.h" SCT *SCT_new(void) { SCT *sct = OPENSSL_zalloc(sizeof(*sct)); if (sct == NULL) return NULL; sct->entry_type = CT_LOG_ENTRY_TYPE_NOT_SET; sct->version = SCT_VERSION_NOT_SET; return sct; } void SCT_free(SCT *sct) { if (sct == NULL) return; OPENSSL_free(sct->log_id); OPENSSL_free(sct->ext); OPENSSL_free(sct->sig); OPENSSL_free(sct->sct); OPENSSL_free(sct); } void SCT_LIST_free(STACK_OF(SCT) *a) { sk_SCT_pop_free(a, SCT_free); } int SCT_set_version(SCT *sct, sct_version_t version) { if (version != SCT_VERSION_V1) { ERR_raise(ERR_LIB_CT, CT_R_UNSUPPORTED_VERSION); return 0; } sct->version = version; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; return 1; } int SCT_set_log_entry_type(SCT *sct, ct_log_entry_type_t entry_type) { sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; switch (entry_type) { case CT_LOG_ENTRY_TYPE_X509: case CT_LOG_ENTRY_TYPE_PRECERT: sct->entry_type = entry_type; return 1; case CT_LOG_ENTRY_TYPE_NOT_SET: break; } ERR_raise(ERR_LIB_CT, CT_R_UNSUPPORTED_ENTRY_TYPE); return 0; } int SCT_set0_log_id(SCT *sct, unsigned char *log_id, size_t log_id_len) { if (sct->version == SCT_VERSION_V1 && log_id_len != CT_V1_HASHLEN) { ERR_raise(ERR_LIB_CT, CT_R_INVALID_LOG_ID_LENGTH); return 0; } OPENSSL_free(sct->log_id); sct->log_id = log_id; sct->log_id_len = log_id_len; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; return 1; } int SCT_set1_log_id(SCT *sct, const unsigned char *log_id, size_t log_id_len) { if (sct->version == SCT_VERSION_V1 && log_id_len != CT_V1_HASHLEN) { ERR_raise(ERR_LIB_CT, CT_R_INVALID_LOG_ID_LENGTH); return 0; } OPENSSL_free(sct->log_id); sct->log_id = NULL; sct->log_id_len = 0; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; if (log_id != NULL && log_id_len > 0) { sct->log_id = OPENSSL_memdup(log_id, log_id_len); if (sct->log_id == NULL) return 0; sct->log_id_len = log_id_len; } return 1; } void SCT_set_timestamp(SCT *sct, uint64_t timestamp) { sct->timestamp = timestamp; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; } int SCT_set_signature_nid(SCT *sct, int nid) { switch (nid) { case NID_sha256WithRSAEncryption: sct->hash_alg = TLSEXT_hash_sha256; sct->sig_alg = TLSEXT_signature_rsa; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; return 1; case NID_ecdsa_with_SHA256: sct->hash_alg = TLSEXT_hash_sha256; sct->sig_alg = TLSEXT_signature_ecdsa; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; return 1; default: ERR_raise(ERR_LIB_CT, CT_R_UNRECOGNIZED_SIGNATURE_NID); return 0; } } void SCT_set0_extensions(SCT *sct, unsigned char *ext, size_t ext_len) { OPENSSL_free(sct->ext); sct->ext = ext; sct->ext_len = ext_len; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; } int SCT_set1_extensions(SCT *sct, const unsigned char *ext, size_t ext_len) { OPENSSL_free(sct->ext); sct->ext = NULL; sct->ext_len = 0; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; if (ext != NULL && ext_len > 0) { sct->ext = OPENSSL_memdup(ext, ext_len); if (sct->ext == NULL) return 0; sct->ext_len = ext_len; } return 1; } void SCT_set0_signature(SCT *sct, unsigned char *sig, size_t sig_len) { OPENSSL_free(sct->sig); sct->sig = sig; sct->sig_len = sig_len; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; } int SCT_set1_signature(SCT *sct, const unsigned char *sig, size_t sig_len) { OPENSSL_free(sct->sig); sct->sig = NULL; sct->sig_len = 0; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; if (sig != NULL && sig_len > 0) { sct->sig = OPENSSL_memdup(sig, sig_len); if (sct->sig == NULL) return 0; sct->sig_len = sig_len; } return 1; } sct_version_t SCT_get_version(const SCT *sct) { return sct->version; } ct_log_entry_type_t SCT_get_log_entry_type(const SCT *sct) { return sct->entry_type; } size_t SCT_get0_log_id(const SCT *sct, unsigned char **log_id) { *log_id = sct->log_id; return sct->log_id_len; } uint64_t SCT_get_timestamp(const SCT *sct) { return sct->timestamp; } int SCT_get_signature_nid(const SCT *sct) { if (sct->version == SCT_VERSION_V1) { if (sct->hash_alg == TLSEXT_hash_sha256) { switch (sct->sig_alg) { case TLSEXT_signature_ecdsa: return NID_ecdsa_with_SHA256; case TLSEXT_signature_rsa: return NID_sha256WithRSAEncryption; default: return NID_undef; } } } return NID_undef; } size_t SCT_get0_extensions(const SCT *sct, unsigned char **ext) { *ext = sct->ext; return sct->ext_len; } size_t SCT_get0_signature(const SCT *sct, unsigned char **sig) { *sig = sct->sig; return sct->sig_len; } int SCT_is_complete(const SCT *sct) { switch (sct->version) { case SCT_VERSION_NOT_SET: return 0; case SCT_VERSION_V1: return sct->log_id != NULL && SCT_signature_is_complete(sct); default: return sct->sct != NULL; /* Just need cached encoding */ } } int SCT_signature_is_complete(const SCT *sct) { return SCT_get_signature_nid(sct) != NID_undef && sct->sig != NULL && sct->sig_len > 0; } sct_source_t SCT_get_source(const SCT *sct) { return sct->source; } int SCT_set_source(SCT *sct, sct_source_t source) { sct->source = source; sct->validation_status = SCT_VALIDATION_STATUS_NOT_SET; switch (source) { case SCT_SOURCE_TLS_EXTENSION: case SCT_SOURCE_OCSP_STAPLED_RESPONSE: return SCT_set_log_entry_type(sct, CT_LOG_ENTRY_TYPE_X509); case SCT_SOURCE_X509V3_EXTENSION: return SCT_set_log_entry_type(sct, CT_LOG_ENTRY_TYPE_PRECERT); case SCT_SOURCE_UNKNOWN: break; } /* if we aren't sure, leave the log entry type alone */ return 1; } sct_validation_status_t SCT_get_validation_status(const SCT *sct) { return sct->validation_status; } int SCT_validate(SCT *sct, const CT_POLICY_EVAL_CTX *ctx) { int is_sct_valid = -1; SCT_CTX *sctx = NULL; X509_PUBKEY *pub = NULL, *log_pkey = NULL; const CTLOG *log; /* * With an unrecognized SCT version we don't know what such an SCT means, * let alone validate one. So we return validation failure (0). */ if (sct->version != SCT_VERSION_V1) { sct->validation_status = SCT_VALIDATION_STATUS_UNKNOWN_VERSION; return 0; } log = CTLOG_STORE_get0_log_by_id(ctx->log_store, sct->log_id, sct->log_id_len); /* Similarly, an SCT from an unknown log also cannot be validated. */ if (log == NULL) { sct->validation_status = SCT_VALIDATION_STATUS_UNKNOWN_LOG; return 0; } sctx = SCT_CTX_new(ctx->libctx, ctx->propq); if (sctx == NULL) goto err; if (X509_PUBKEY_set(&log_pkey, CTLOG_get0_public_key(log)) != 1) goto err; if (SCT_CTX_set1_pubkey(sctx, log_pkey) != 1) goto err; if (SCT_get_log_entry_type(sct) == CT_LOG_ENTRY_TYPE_PRECERT) { EVP_PKEY *issuer_pkey; if (ctx->issuer == NULL) { sct->validation_status = SCT_VALIDATION_STATUS_UNVERIFIED; goto end; } issuer_pkey = X509_get0_pubkey(ctx->issuer); if (X509_PUBKEY_set(&pub, issuer_pkey) != 1) goto err; if (SCT_CTX_set1_issuer_pubkey(sctx, pub) != 1) goto err; } SCT_CTX_set_time(sctx, ctx->epoch_time_in_ms); /* * XXX: Potential for optimization. This repeats some idempotent heavy * lifting on the certificate for each candidate SCT, and appears to not * use any information in the SCT itself, only the certificate is * processed. So it may make more sense to do this just once, perhaps * associated with the shared (by all SCTs) policy eval ctx. * * XXX: Failure here is global (SCT independent) and represents either an * issue with the certificate (e.g. duplicate extensions) or an out of * memory condition. When the certificate is incompatible with CT, we just * mark the SCTs invalid, rather than report a failure to determine the * validation status. That way, callbacks that want to do "soft" SCT * processing will not abort handshakes with false positive internal * errors. Since the function does not distinguish between certificate * issues (peer's fault) and internal problems (out fault) the safe thing * to do is to report a validation failure and let the callback or * application decide what to do. */ if (SCT_CTX_set1_cert(sctx, ctx->cert, NULL) != 1) sct->validation_status = SCT_VALIDATION_STATUS_UNVERIFIED; else sct->validation_status = SCT_CTX_verify(sctx, sct) == 1 ? SCT_VALIDATION_STATUS_VALID : SCT_VALIDATION_STATUS_INVALID; end: is_sct_valid = sct->validation_status == SCT_VALIDATION_STATUS_VALID; err: X509_PUBKEY_free(pub); X509_PUBKEY_free(log_pkey); SCT_CTX_free(sctx); return is_sct_valid; } int SCT_LIST_validate(const STACK_OF(SCT) *scts, CT_POLICY_EVAL_CTX *ctx) { int are_scts_valid = 1; int sct_count = scts != NULL ? sk_SCT_num(scts) : 0; int i; for (i = 0; i < sct_count; ++i) { int is_sct_valid = -1; SCT *sct = sk_SCT_value(scts, i); if (sct == NULL) continue; is_sct_valid = SCT_validate(sct, ctx); if (is_sct_valid < 0) return is_sct_valid; are_scts_valid &= is_sct_valid; } return are_scts_valid; }
10,549
26.120823
79
c
openssl
openssl-master/crypto/ct/ct_sct_ctx.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 */ #ifdef OPENSSL_NO_CT # error "CT is disabled" #endif #include <stddef.h> #include <string.h> #include <openssl/err.h> #include <openssl/obj_mac.h> #include <openssl/x509.h> #include "ct_local.h" SCT_CTX *SCT_CTX_new(OSSL_LIB_CTX *libctx, const char *propq) { SCT_CTX *sctx = OPENSSL_zalloc(sizeof(*sctx)); if (sctx == NULL) return NULL; sctx->libctx = libctx; if (propq != NULL) { sctx->propq = OPENSSL_strdup(propq); if (sctx->propq == NULL) { OPENSSL_free(sctx); return NULL; } } return sctx; } void SCT_CTX_free(SCT_CTX *sctx) { if (sctx == NULL) return; EVP_PKEY_free(sctx->pkey); OPENSSL_free(sctx->pkeyhash); OPENSSL_free(sctx->ihash); OPENSSL_free(sctx->certder); OPENSSL_free(sctx->preder); OPENSSL_free(sctx->propq); OPENSSL_free(sctx); } /* * Finds the index of the first extension with the given NID in cert. * If there is more than one extension with that NID, *is_duplicated is set to * 1, otherwise 0 (unless it is NULL). */ static int ct_x509_get_ext(X509 *cert, int nid, int *is_duplicated) { int ret = X509_get_ext_by_NID(cert, nid, -1); if (is_duplicated != NULL) *is_duplicated = ret >= 0 && X509_get_ext_by_NID(cert, nid, ret) >= 0; return ret; } /* * Modifies a certificate by deleting extensions and copying the issuer and * AKID from the presigner certificate, if necessary. * Returns 1 on success, 0 otherwise. */ __owur static int ct_x509_cert_fixup(X509 *cert, X509 *presigner) { int preidx, certidx; int pre_akid_ext_is_dup, cert_akid_ext_is_dup; if (presigner == NULL) return 1; preidx = ct_x509_get_ext(presigner, NID_authority_key_identifier, &pre_akid_ext_is_dup); certidx = ct_x509_get_ext(cert, NID_authority_key_identifier, &cert_akid_ext_is_dup); /* An error occurred whilst searching for the extension */ if (preidx < -1 || certidx < -1) return 0; /* Invalid certificate if they contain duplicate extensions */ if (pre_akid_ext_is_dup || cert_akid_ext_is_dup) return 0; /* AKID must be present in both certificate or absent in both */ if (preidx >= 0 && certidx == -1) return 0; if (preidx == -1 && certidx >= 0) return 0; /* Copy issuer name */ if (!X509_set_issuer_name(cert, X509_get_issuer_name(presigner))) return 0; if (preidx != -1) { /* Retrieve and copy AKID encoding */ X509_EXTENSION *preext = X509_get_ext(presigner, preidx); X509_EXTENSION *certext = X509_get_ext(cert, certidx); ASN1_OCTET_STRING *preextdata; /* Should never happen */ if (preext == NULL || certext == NULL) return 0; preextdata = X509_EXTENSION_get_data(preext); if (preextdata == NULL || !X509_EXTENSION_set_data(certext, preextdata)) return 0; } return 1; } int SCT_CTX_set1_cert(SCT_CTX *sctx, X509 *cert, X509 *presigner) { unsigned char *certder = NULL, *preder = NULL; X509 *pretmp = NULL; int certderlen = 0, prederlen = 0; int idx = -1; int poison_ext_is_dup, sct_ext_is_dup; int poison_idx = ct_x509_get_ext(cert, NID_ct_precert_poison, &poison_ext_is_dup); /* Duplicate poison extensions are present - error */ if (poison_ext_is_dup) goto err; /* If *cert doesn't have a poison extension, it isn't a precert */ if (poison_idx == -1) { /* cert isn't a precert, so we shouldn't have a presigner */ if (presigner != NULL) goto err; certderlen = i2d_X509(cert, &certder); if (certderlen < 0) goto err; } /* See if cert has a precert SCTs extension */ idx = ct_x509_get_ext(cert, NID_ct_precert_scts, &sct_ext_is_dup); /* Duplicate SCT extensions are present - error */ if (sct_ext_is_dup) goto err; if (idx >= 0 && poison_idx >= 0) { /* * cert can't both contain SCTs (i.e. have an SCT extension) and be a * precert (i.e. have a poison extension). */ goto err; } if (idx == -1) { idx = poison_idx; } /* * If either a poison or SCT extension is present, remove it before encoding * cert. This, along with ct_x509_cert_fixup(), gets a TBSCertificate (see * RFC5280) from cert, which is what the CT log signed when it produced the * SCT. */ if (idx >= 0) { /* Take a copy of certificate so we don't modify passed version */ pretmp = X509_dup(cert); if (pretmp == NULL) goto err; X509_EXTENSION_free(X509_delete_ext(pretmp, idx)); if (!ct_x509_cert_fixup(pretmp, presigner)) goto err; prederlen = i2d_re_X509_tbs(pretmp, &preder); if (prederlen <= 0) goto err; } X509_free(pretmp); OPENSSL_free(sctx->certder); sctx->certder = certder; sctx->certderlen = certderlen; OPENSSL_free(sctx->preder); sctx->preder = preder; sctx->prederlen = prederlen; return 1; err: OPENSSL_free(certder); OPENSSL_free(preder); X509_free(pretmp); return 0; } __owur static int ct_public_key_hash(SCT_CTX *sctx, X509_PUBKEY *pkey, unsigned char **hash, size_t *hash_len) { int ret = 0; unsigned char *md = NULL, *der = NULL; int der_len; unsigned int md_len; EVP_MD *sha256 = EVP_MD_fetch(sctx->libctx, "SHA2-256", sctx->propq); if (sha256 == NULL) goto err; /* Reuse buffer if possible */ if (*hash != NULL && *hash_len >= SHA256_DIGEST_LENGTH) { md = *hash; } else { md = OPENSSL_malloc(SHA256_DIGEST_LENGTH); if (md == NULL) goto err; } /* Calculate key hash */ der_len = i2d_X509_PUBKEY(pkey, &der); if (der_len <= 0) goto err; if (!EVP_Digest(der, der_len, md, &md_len, sha256, NULL)) goto err; if (md != *hash) { OPENSSL_free(*hash); *hash = md; *hash_len = SHA256_DIGEST_LENGTH; } md = NULL; ret = 1; err: EVP_MD_free(sha256); OPENSSL_free(md); OPENSSL_free(der); return ret; } int SCT_CTX_set1_issuer(SCT_CTX *sctx, const X509 *issuer) { return SCT_CTX_set1_issuer_pubkey(sctx, X509_get_X509_PUBKEY(issuer)); } int SCT_CTX_set1_issuer_pubkey(SCT_CTX *sctx, X509_PUBKEY *pubkey) { return ct_public_key_hash(sctx, pubkey, &sctx->ihash, &sctx->ihashlen); } int SCT_CTX_set1_pubkey(SCT_CTX *sctx, X509_PUBKEY *pubkey) { EVP_PKEY *pkey = X509_PUBKEY_get(pubkey); if (pkey == NULL) return 0; if (!ct_public_key_hash(sctx, pubkey, &sctx->pkeyhash, &sctx->pkeyhashlen)) { EVP_PKEY_free(pkey); return 0; } EVP_PKEY_free(sctx->pkey); sctx->pkey = pkey; return 1; } void SCT_CTX_set_time(SCT_CTX *sctx, uint64_t time_in_ms) { sctx->epoch_time_in_ms = time_in_ms; }
7,415
25.869565
86
c
openssl
openssl-master/crypto/ct/ct_vfy.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 */ #include <string.h> #include <openssl/ct.h> #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/x509.h> #include "ct_local.h" typedef enum sct_signature_type_t { SIGNATURE_TYPE_NOT_SET = -1, SIGNATURE_TYPE_CERT_TIMESTAMP, SIGNATURE_TYPE_TREE_HASH } SCT_SIGNATURE_TYPE; /* * Update encoding for SCT signature verification/generation to supplied * EVP_MD_CTX. */ static int sct_ctx_update(EVP_MD_CTX *ctx, const SCT_CTX *sctx, const SCT *sct) { unsigned char tmpbuf[12]; unsigned char *p, *der; size_t derlen; /*+ * digitally-signed struct { * (1 byte) Version sct_version; * (1 byte) SignatureType signature_type = certificate_timestamp; * (8 bytes) uint64 timestamp; * (2 bytes) LogEntryType entry_type; * (? bytes) select(entry_type) { * case x509_entry: ASN.1Cert; * case precert_entry: PreCert; * } signed_entry; * (2 bytes + sct->ext_len) CtExtensions extensions; * } */ if (sct->entry_type == CT_LOG_ENTRY_TYPE_NOT_SET) return 0; if (sct->entry_type == CT_LOG_ENTRY_TYPE_PRECERT && sctx->ihash == NULL) return 0; p = tmpbuf; *p++ = sct->version; *p++ = SIGNATURE_TYPE_CERT_TIMESTAMP; l2n8(sct->timestamp, p); s2n(sct->entry_type, p); if (!EVP_DigestUpdate(ctx, tmpbuf, p - tmpbuf)) return 0; if (sct->entry_type == CT_LOG_ENTRY_TYPE_X509) { der = sctx->certder; derlen = sctx->certderlen; } else { if (!EVP_DigestUpdate(ctx, sctx->ihash, sctx->ihashlen)) return 0; der = sctx->preder; derlen = sctx->prederlen; } /* If no encoding available, fatal error */ if (der == NULL) return 0; /* Include length first */ p = tmpbuf; l2n3(derlen, p); if (!EVP_DigestUpdate(ctx, tmpbuf, 3)) return 0; if (!EVP_DigestUpdate(ctx, der, derlen)) return 0; /* Add any extensions */ p = tmpbuf; s2n(sct->ext_len, p); if (!EVP_DigestUpdate(ctx, tmpbuf, 2)) return 0; if (sct->ext_len && !EVP_DigestUpdate(ctx, sct->ext, sct->ext_len)) return 0; return 1; } int SCT_CTX_verify(const SCT_CTX *sctx, const SCT *sct) { EVP_MD_CTX *ctx = NULL; int ret = 0; if (!SCT_is_complete(sct) || sctx->pkey == NULL || sct->entry_type == CT_LOG_ENTRY_TYPE_NOT_SET || (sct->entry_type == CT_LOG_ENTRY_TYPE_PRECERT && sctx->ihash == NULL)) { ERR_raise(ERR_LIB_CT, CT_R_SCT_NOT_SET); return 0; } if (sct->version != SCT_VERSION_V1) { ERR_raise(ERR_LIB_CT, CT_R_SCT_UNSUPPORTED_VERSION); return 0; } if (sct->log_id_len != sctx->pkeyhashlen || memcmp(sct->log_id, sctx->pkeyhash, sctx->pkeyhashlen) != 0) { ERR_raise(ERR_LIB_CT, CT_R_SCT_LOG_ID_MISMATCH); return 0; } if (sct->timestamp > sctx->epoch_time_in_ms) { ERR_raise(ERR_LIB_CT, CT_R_SCT_FUTURE_TIMESTAMP); return 0; } ctx = EVP_MD_CTX_new(); if (ctx == NULL) goto end; if (!EVP_DigestVerifyInit_ex(ctx, NULL, "SHA2-256", sctx->libctx, sctx->propq, sctx->pkey, NULL)) goto end; if (!sct_ctx_update(ctx, sctx, sct)) goto end; /* Verify signature */ ret = EVP_DigestVerifyFinal(ctx, sct->sig, sct->sig_len); /* If ret < 0 some other error: fall through without setting error */ if (ret == 0) ERR_raise(ERR_LIB_CT, CT_R_SCT_INVALID_SIGNATURE); end: EVP_MD_CTX_free(ctx); return ret; }
3,937
26.732394
80
c
openssl
openssl-master/crypto/ct/ct_x509v3.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 */ #ifdef OPENSSL_NO_CT # error "CT is disabled" #endif #include "ct_local.h" static char *i2s_poison(const X509V3_EXT_METHOD *method, void *val) { return OPENSSL_strdup("NULL"); } static void *s2i_poison(const X509V3_EXT_METHOD *method, X509V3_CTX *ctx, const char *str) { return ASN1_NULL_new(); } static int i2r_SCT_LIST(X509V3_EXT_METHOD *method, STACK_OF(SCT) *sct_list, BIO *out, int indent) { SCT_LIST_print(sct_list, out, indent, "\n", NULL); return 1; } static int set_sct_list_source(STACK_OF(SCT) *s, sct_source_t source) { if (s != NULL) { int i; for (i = 0; i < sk_SCT_num(s); i++) { int res = SCT_set_source(sk_SCT_value(s, i), source); if (res != 1) { return 0; } } } return 1; } static STACK_OF(SCT) *x509_ext_d2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp, long len) { STACK_OF(SCT) *s = d2i_SCT_LIST(a, pp, len); if (set_sct_list_source(s, SCT_SOURCE_X509V3_EXTENSION) != 1) { SCT_LIST_free(s); *a = NULL; return NULL; } return s; } static STACK_OF(SCT) *ocsp_ext_d2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp, long len) { STACK_OF(SCT) *s = d2i_SCT_LIST(a, pp, len); if (set_sct_list_source(s, SCT_SOURCE_OCSP_STAPLED_RESPONSE) != 1) { SCT_LIST_free(s); *a = NULL; return NULL; } return s; } /* Handlers for X509v3/OCSP Certificate Transparency extensions */ const X509V3_EXT_METHOD ossl_v3_ct_scts[3] = { /* X509v3 extension in certificates that contains SCTs */ { NID_ct_precert_scts, 0, NULL, NULL, (X509V3_EXT_FREE)SCT_LIST_free, (X509V3_EXT_D2I)x509_ext_d2i_SCT_LIST, (X509V3_EXT_I2D)i2d_SCT_LIST, NULL, NULL, NULL, NULL, (X509V3_EXT_I2R)i2r_SCT_LIST, NULL, NULL }, /* X509v3 extension to mark a certificate as a pre-certificate */ { NID_ct_precert_poison, 0, ASN1_ITEM_ref(ASN1_NULL), NULL, NULL, NULL, NULL, i2s_poison, s2i_poison, NULL, NULL, NULL, NULL, NULL }, /* OCSP extension that contains SCTs */ { NID_ct_cert_scts, 0, NULL, 0, (X509V3_EXT_FREE)SCT_LIST_free, (X509V3_EXT_D2I)ocsp_ext_d2i_SCT_LIST, (X509V3_EXT_I2D)i2d_SCT_LIST, NULL, NULL, NULL, NULL, (X509V3_EXT_I2R)i2r_SCT_LIST, NULL, NULL }, };
2,878
26.419048
90
c
openssl
openssl-master/crypto/des/cbc_cksm.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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "des_local.h" DES_LONG DES_cbc_cksum(const unsigned char *in, DES_cblock *output, long length, DES_key_schedule *schedule, const_DES_cblock *ivec) { register DES_LONG tout0, tout1, tin0, tin1; register long l = length; DES_LONG tin[2]; unsigned char *out = &(*output)[0]; const unsigned char *iv = &(*ivec)[0]; c2l(iv, tout0); c2l(iv, tout1); for (; l > 0; l -= 8) { if (l >= 8) { c2l(in, tin0); c2l(in, tin1); } else c2ln(in, tin0, tin1, l); tin0 ^= tout0; tin[0] = tin0; tin1 ^= tout1; tin[1] = tin1; DES_encrypt1((DES_LONG *)tin, schedule, DES_ENCRYPT); tout0 = tin[0]; tout1 = tin[1]; } if (out != NULL) { l2c(tout0, out); l2c(tout1, out); } tout0 = tin0 = tin1 = tin[0] = tin[1] = 0; /* * Transform the data in tout1 so that it will match the return value * that the MIT Kerberos mit_des_cbc_cksum API returns. */ tout1 = ((tout1 >> 24L) & 0x000000FF) | ((tout1 >> 8L) & 0x0000FF00) | ((tout1 << 8L) & 0x00FF0000) | ((tout1 << 24L) & 0xFF000000); return tout1; }
1,714
27.583333
78
c
openssl
openssl-master/crypto/des/cbc_enc.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #define CBC_ENC_C__DONT_UPDATE_IV #include "ncbc_enc.c" /* des_cbc_encrypt */
554
28.210526
78
c
openssl
openssl-master/crypto/des/cfb64ede.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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "des_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 DES_ede3_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, DES_key_schedule *ks1, DES_key_schedule *ks2, DES_key_schedule *ks3, DES_cblock *ivec, int *num, int enc) { register DES_LONG v0, v1; register long l = length; register int n = *num; DES_LONG ti[2]; unsigned char *iv, c, cc; iv = &(*ivec)[0]; if (enc) { while (l--) { if (n == 0) { c2l(iv, v0); c2l(iv, v1); ti[0] = v0; ti[1] = v1; DES_encrypt3(ti, ks1, ks2, ks3); v0 = ti[0]; v1 = ti[1]; iv = &(*ivec)[0]; l2c(v0, iv); l2c(v1, iv); iv = &(*ivec)[0]; } c = *(in++) ^ iv[n]; *(out++) = c; iv[n] = c; n = (n + 1) & 0x07; } } else { while (l--) { if (n == 0) { c2l(iv, v0); c2l(iv, v1); ti[0] = v0; ti[1] = v1; DES_encrypt3(ti, ks1, ks2, ks3); v0 = ti[0]; v1 = ti[1]; iv = &(*ivec)[0]; l2c(v0, iv); l2c(v1, iv); iv = &(*ivec)[0]; } cc = *(in++); c = iv[n]; iv[n] = cc; *(out++) = c ^ cc; n = (n + 1) & 0x07; } } v0 = v1 = ti[0] = ti[1] = c = cc = 0; *num = n; } /* * This is compatible with the single key CFB-r for DES, even thought that's * not what EVP needs. */ void DES_ede3_cfb_encrypt(const unsigned char *in, unsigned char *out, int numbits, long length, DES_key_schedule *ks1, DES_key_schedule *ks2, DES_key_schedule *ks3, DES_cblock *ivec, int enc) { register DES_LONG d0, d1, v0, v1; register unsigned long l = length, n = ((unsigned int)numbits + 7) / 8; register int num = numbits, i; DES_LONG ti[2]; unsigned char *iv; unsigned char ovec[16]; if (num > 64) return; iv = &(*ivec)[0]; c2l(iv, v0); c2l(iv, v1); if (enc) { while (l >= n) { l -= n; ti[0] = v0; ti[1] = v1; DES_encrypt3(ti, ks1, ks2, ks3); c2ln(in, d0, d1, n); in += n; d0 ^= ti[0]; d1 ^= ti[1]; l2cn(d0, d1, out, n); out += n; /* * 30-08-94 - eay - changed because l>>32 and l<<32 are bad under * gcc :-( */ if (num == 32) { v0 = v1; v1 = d0; } else if (num == 64) { v0 = d0; v1 = d1; } else { iv = &ovec[0]; l2c(v0, iv); l2c(v1, iv); l2c(d0, iv); l2c(d1, iv); /* shift ovec left most of the bits... */ memmove(ovec, ovec + num / 8, 8 + (num % 8 ? 1 : 0)); /* now the remaining bits */ if (num % 8 != 0) for (i = 0; i < 8; ++i) { ovec[i] <<= num % 8; ovec[i] |= ovec[i + 1] >> (8 - num % 8); } iv = &ovec[0]; c2l(iv, v0); c2l(iv, v1); } } } else { while (l >= n) { l -= n; ti[0] = v0; ti[1] = v1; DES_encrypt3(ti, ks1, ks2, ks3); c2ln(in, d0, d1, n); in += n; /* * 30-08-94 - eay - changed because l>>32 and l<<32 are bad under * gcc :-( */ if (num == 32) { v0 = v1; v1 = d0; } else if (num == 64) { v0 = d0; v1 = d1; } else { iv = &ovec[0]; l2c(v0, iv); l2c(v1, iv); l2c(d0, iv); l2c(d1, iv); /* shift ovec left most of the bits... */ memmove(ovec, ovec + num / 8, 8 + (num % 8 ? 1 : 0)); /* now the remaining bits */ if (num % 8 != 0) for (i = 0; i < 8; ++i) { ovec[i] <<= num % 8; ovec[i] |= ovec[i + 1] >> (8 - num % 8); } iv = &ovec[0]; c2l(iv, v0); c2l(iv, v1); } d0 ^= ti[0]; d1 ^= ti[1]; l2cn(d0, d1, out, n); out += n; } } iv = &(*ivec)[0]; l2c(v0, iv); l2c(v1, iv); v0 = v1 = d0 = d1 = ti[0] = ti[1] = 0; }
5,646
27.811224
78
c
openssl
openssl-master/crypto/des/cfb64enc.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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "des_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 DES_cfb64_encrypt(const unsigned char *in, unsigned char *out, long length, DES_key_schedule *schedule, DES_cblock *ivec, int *num, int enc) { register DES_LONG v0, v1; register long l = length; register int n = *num; DES_LONG ti[2]; unsigned char *iv, c, cc; iv = &(*ivec)[0]; if (enc) { while (l--) { if (n == 0) { c2l(iv, v0); ti[0] = v0; c2l(iv, v1); ti[1] = v1; DES_encrypt1(ti, schedule, DES_ENCRYPT); iv = &(*ivec)[0]; v0 = ti[0]; l2c(v0, iv); v0 = ti[1]; l2c(v0, iv); iv = &(*ivec)[0]; } c = *(in++) ^ iv[n]; *(out++) = c; iv[n] = c; n = (n + 1) & 0x07; } } else { while (l--) { if (n == 0) { c2l(iv, v0); ti[0] = v0; c2l(iv, v1); ti[1] = v1; DES_encrypt1(ti, schedule, DES_ENCRYPT); iv = &(*ivec)[0]; v0 = ti[0]; l2c(v0, iv); v0 = ti[1]; l2c(v0, iv); iv = &(*ivec)[0]; } cc = *(in++); c = iv[n]; iv[n] = cc; *(out++) = c ^ cc; n = (n + 1) & 0x07; } } v0 = v1 = ti[0] = ti[1] = c = cc = 0; *num = n; }
2,224
26.8125
78
c
openssl
openssl-master/crypto/des/cfb_enc.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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "internal/e_os.h" #include "des_local.h" #include <assert.h> /* * The input and output are loaded in multiples of 8 bits. What this means is * that if you hame numbits=12 and length=2 the first 12 bits will be * retrieved from the first byte and half the second. The second 12 bits * will come from the 3rd and half the 4th byte. */ /* * Until Aug 1 2003 this function did not correctly implement CFB-r, so it * will not be compatible with any encryption prior to that date. Ben. */ void DES_cfb_encrypt(const unsigned char *in, unsigned char *out, int numbits, long length, DES_key_schedule *schedule, DES_cblock *ivec, int enc) { register DES_LONG d0, d1, v0, v1; register unsigned long l = length; register int num = numbits / 8, n = (numbits + 7) / 8, i, rem = numbits % 8; DES_LONG ti[2]; unsigned char *iv; #ifndef L_ENDIAN unsigned char ovec[16]; #else unsigned int sh[4]; unsigned char *ovec = (unsigned char *)sh; /* I kind of count that compiler optimizes away this assertion, */ assert(sizeof(sh[0]) == 4); /* as this holds true for all, */ /* but 16-bit platforms... */ #endif if (numbits <= 0 || numbits > 64) return; iv = &(*ivec)[0]; c2l(iv, v0); c2l(iv, v1); if (enc) { while (l >= (unsigned long)n) { l -= n; ti[0] = v0; ti[1] = v1; DES_encrypt1((DES_LONG *)ti, schedule, DES_ENCRYPT); c2ln(in, d0, d1, n); in += n; d0 ^= ti[0]; d1 ^= ti[1]; l2cn(d0, d1, out, n); out += n; /* * 30-08-94 - eay - changed because l>>32 and l<<32 are bad under * gcc :-( */ if (numbits == 32) { v0 = v1; v1 = d0; } else if (numbits == 64) { v0 = d0; v1 = d1; } else { #ifndef L_ENDIAN iv = &ovec[0]; l2c(v0, iv); l2c(v1, iv); l2c(d0, iv); l2c(d1, iv); #else sh[0] = v0, sh[1] = v1, sh[2] = d0, sh[3] = d1; #endif if (rem == 0) memmove(ovec, ovec + num, 8); else for (i = 0; i < 8; ++i) ovec[i] = ovec[i + num] << rem | ovec[i + num + 1] >> (8 - rem); #ifdef L_ENDIAN v0 = sh[0], v1 = sh[1]; #else iv = &ovec[0]; c2l(iv, v0); c2l(iv, v1); #endif } } } else { while (l >= (unsigned long)n) { l -= n; ti[0] = v0; ti[1] = v1; DES_encrypt1((DES_LONG *)ti, schedule, DES_ENCRYPT); c2ln(in, d0, d1, n); in += n; /* * 30-08-94 - eay - changed because l>>32 and l<<32 are bad under * gcc :-( */ if (numbits == 32) { v0 = v1; v1 = d0; } else if (numbits == 64) { v0 = d0; v1 = d1; } else { #ifndef L_ENDIAN iv = &ovec[0]; l2c(v0, iv); l2c(v1, iv); l2c(d0, iv); l2c(d1, iv); #else sh[0] = v0, sh[1] = v1, sh[2] = d0, sh[3] = d1; #endif if (rem == 0) memmove(ovec, ovec + num, 8); else for (i = 0; i < 8; ++i) ovec[i] = ovec[i + num] << rem | ovec[i + num + 1] >> (8 - rem); #ifdef L_ENDIAN v0 = sh[0], v1 = sh[1]; #else iv = &ovec[0]; c2l(iv, v0); c2l(iv, v1); #endif } d0 ^= ti[0]; d1 ^= ti[1]; l2cn(d0, d1, out, n); out += n; } } iv = &(*ivec)[0]; l2c(v0, iv); l2c(v1, iv); v0 = v1 = d0 = d1 = ti[0] = ti[1] = 0; }
4,608
28.356688
78
c
openssl
openssl-master/crypto/des/des_enc.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/crypto.h> #include "des_local.h" #include "spr.h" void DES_encrypt1(DES_LONG *data, DES_key_schedule *ks, int enc) { register DES_LONG l, r, t, u; register DES_LONG *s; r = data[0]; l = data[1]; IP(r, l); /* * Things have been modified so that the initial rotate is done outside * the loop. This required the DES_SPtrans values in sp.h to be rotated * 1 bit to the right. One perl script later and things have a 5% speed * up on a sparc2. Thanks to Richard Outerbridge for pointing this out. */ /* clear the top bits on machines with 8byte longs */ /* shift left by 2 */ r = ROTATE(r, 29) & 0xffffffffL; l = ROTATE(l, 29) & 0xffffffffL; s = ks->ks->deslong; /* * I don't know if it is worth the effort of loop unrolling the inner * loop */ if (enc) { D_ENCRYPT(l, r, 0); /* 1 */ D_ENCRYPT(r, l, 2); /* 2 */ D_ENCRYPT(l, r, 4); /* 3 */ D_ENCRYPT(r, l, 6); /* 4 */ D_ENCRYPT(l, r, 8); /* 5 */ D_ENCRYPT(r, l, 10); /* 6 */ D_ENCRYPT(l, r, 12); /* 7 */ D_ENCRYPT(r, l, 14); /* 8 */ D_ENCRYPT(l, r, 16); /* 9 */ D_ENCRYPT(r, l, 18); /* 10 */ D_ENCRYPT(l, r, 20); /* 11 */ D_ENCRYPT(r, l, 22); /* 12 */ D_ENCRYPT(l, r, 24); /* 13 */ D_ENCRYPT(r, l, 26); /* 14 */ D_ENCRYPT(l, r, 28); /* 15 */ D_ENCRYPT(r, l, 30); /* 16 */ } else { D_ENCRYPT(l, r, 30); /* 16 */ D_ENCRYPT(r, l, 28); /* 15 */ D_ENCRYPT(l, r, 26); /* 14 */ D_ENCRYPT(r, l, 24); /* 13 */ D_ENCRYPT(l, r, 22); /* 12 */ D_ENCRYPT(r, l, 20); /* 11 */ D_ENCRYPT(l, r, 18); /* 10 */ D_ENCRYPT(r, l, 16); /* 9 */ D_ENCRYPT(l, r, 14); /* 8 */ D_ENCRYPT(r, l, 12); /* 7 */ D_ENCRYPT(l, r, 10); /* 6 */ D_ENCRYPT(r, l, 8); /* 5 */ D_ENCRYPT(l, r, 6); /* 4 */ D_ENCRYPT(r, l, 4); /* 3 */ D_ENCRYPT(l, r, 2); /* 2 */ D_ENCRYPT(r, l, 0); /* 1 */ } /* rotate and clear the top bits on machines with 8byte longs */ l = ROTATE(l, 3) & 0xffffffffL; r = ROTATE(r, 3) & 0xffffffffL; FP(r, l); data[0] = l; data[1] = r; l = r = t = u = 0; } void DES_encrypt2(DES_LONG *data, DES_key_schedule *ks, int enc) { register DES_LONG l, r, t, u; register DES_LONG *s; r = data[0]; l = data[1]; /* * Things have been modified so that the initial rotate is done outside * the loop. This required the DES_SPtrans values in sp.h to be rotated * 1 bit to the right. One perl script later and things have a 5% speed * up on a sparc2. Thanks to Richard Outerbridge for pointing this out. */ /* clear the top bits on machines with 8byte longs */ r = ROTATE(r, 29) & 0xffffffffL; l = ROTATE(l, 29) & 0xffffffffL; s = ks->ks->deslong; /* * I don't know if it is worth the effort of loop unrolling the inner * loop */ if (enc) { D_ENCRYPT(l, r, 0); /* 1 */ D_ENCRYPT(r, l, 2); /* 2 */ D_ENCRYPT(l, r, 4); /* 3 */ D_ENCRYPT(r, l, 6); /* 4 */ D_ENCRYPT(l, r, 8); /* 5 */ D_ENCRYPT(r, l, 10); /* 6 */ D_ENCRYPT(l, r, 12); /* 7 */ D_ENCRYPT(r, l, 14); /* 8 */ D_ENCRYPT(l, r, 16); /* 9 */ D_ENCRYPT(r, l, 18); /* 10 */ D_ENCRYPT(l, r, 20); /* 11 */ D_ENCRYPT(r, l, 22); /* 12 */ D_ENCRYPT(l, r, 24); /* 13 */ D_ENCRYPT(r, l, 26); /* 14 */ D_ENCRYPT(l, r, 28); /* 15 */ D_ENCRYPT(r, l, 30); /* 16 */ } else { D_ENCRYPT(l, r, 30); /* 16 */ D_ENCRYPT(r, l, 28); /* 15 */ D_ENCRYPT(l, r, 26); /* 14 */ D_ENCRYPT(r, l, 24); /* 13 */ D_ENCRYPT(l, r, 22); /* 12 */ D_ENCRYPT(r, l, 20); /* 11 */ D_ENCRYPT(l, r, 18); /* 10 */ D_ENCRYPT(r, l, 16); /* 9 */ D_ENCRYPT(l, r, 14); /* 8 */ D_ENCRYPT(r, l, 12); /* 7 */ D_ENCRYPT(l, r, 10); /* 6 */ D_ENCRYPT(r, l, 8); /* 5 */ D_ENCRYPT(l, r, 6); /* 4 */ D_ENCRYPT(r, l, 4); /* 3 */ D_ENCRYPT(l, r, 2); /* 2 */ D_ENCRYPT(r, l, 0); /* 1 */ } /* rotate and clear the top bits on machines with 8byte longs */ data[0] = ROTATE(l, 3) & 0xffffffffL; data[1] = ROTATE(r, 3) & 0xffffffffL; l = r = t = u = 0; } void DES_encrypt3(DES_LONG *data, DES_key_schedule *ks1, DES_key_schedule *ks2, DES_key_schedule *ks3) { register DES_LONG l, r; l = data[0]; r = data[1]; IP(l, r); data[0] = l; data[1] = r; DES_encrypt2((DES_LONG *)data, ks1, DES_ENCRYPT); DES_encrypt2((DES_LONG *)data, ks2, DES_DECRYPT); DES_encrypt2((DES_LONG *)data, ks3, DES_ENCRYPT); l = data[0]; r = data[1]; FP(r, l); data[0] = l; data[1] = r; } void DES_decrypt3(DES_LONG *data, DES_key_schedule *ks1, DES_key_schedule *ks2, DES_key_schedule *ks3) { register DES_LONG l, r; l = data[0]; r = data[1]; IP(l, r); data[0] = l; data[1] = r; DES_encrypt2((DES_LONG *)data, ks3, DES_DECRYPT); DES_encrypt2((DES_LONG *)data, ks2, DES_ENCRYPT); DES_encrypt2((DES_LONG *)data, ks1, DES_DECRYPT); l = data[0]; r = data[1]; FP(r, l); data[0] = l; data[1] = r; } #ifndef DES_DEFAULT_OPTIONS # undef CBC_ENC_C__DONT_UPDATE_IV # include "ncbc_enc.c" /* DES_ncbc_encrypt */ void DES_ede3_cbc_encrypt(const unsigned char *input, unsigned char *output, long length, DES_key_schedule *ks1, DES_key_schedule *ks2, DES_key_schedule *ks3, DES_cblock *ivec, int enc) { register DES_LONG tin0, tin1; register DES_LONG tout0, tout1, xor0, xor1; register const unsigned char *in; unsigned char *out; register long l = length; DES_LONG tin[2]; unsigned char *iv; in = input; out = output; iv = &(*ivec)[0]; if (enc) { c2l(iv, tout0); c2l(iv, tout1); for (l -= 8; l >= 0; l -= 8) { c2l(in, tin0); c2l(in, tin1); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; DES_encrypt3((DES_LONG *)tin, ks1, ks2, ks3); tout0 = tin[0]; tout1 = tin[1]; l2c(tout0, out); l2c(tout1, out); } if (l != -8) { c2ln(in, tin0, tin1, l + 8); tin0 ^= tout0; tin1 ^= tout1; tin[0] = tin0; tin[1] = tin1; DES_encrypt3((DES_LONG *)tin, ks1, ks2, ks3); tout0 = tin[0]; tout1 = tin[1]; l2c(tout0, out); l2c(tout1, out); } iv = &(*ivec)[0]; l2c(tout0, iv); l2c(tout1, iv); } else { register DES_LONG t0, t1; c2l(iv, xor0); c2l(iv, xor1); for (l -= 8; l >= 0; l -= 8) { c2l(in, tin0); c2l(in, tin1); t0 = tin0; t1 = tin1; tin[0] = tin0; tin[1] = tin1; DES_decrypt3((DES_LONG *)tin, ks1, ks2, ks3); tout0 = tin[0]; tout1 = tin[1]; tout0 ^= xor0; tout1 ^= xor1; l2c(tout0, out); l2c(tout1, out); xor0 = t0; xor1 = t1; } if (l != -8) { c2l(in, tin0); c2l(in, tin1); t0 = tin0; t1 = tin1; tin[0] = tin0; tin[1] = tin1; DES_decrypt3((DES_LONG *)tin, ks1, ks2, ks3); tout0 = tin[0]; tout1 = tin[1]; tout0 ^= xor0; tout1 ^= xor1; l2cn(tout0, tout1, out, l + 8); xor0 = t0; xor1 = t1; } iv = &(*ivec)[0]; l2c(xor0, iv); l2c(xor1, iv); } tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; tin[0] = tin[1] = 0; } #endif /* DES_DEFAULT_OPTIONS */
8,847
27.915033
78
c
openssl
openssl-master/crypto/des/ecb3_enc.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "des_local.h" void DES_ecb3_encrypt(const_DES_cblock *input, DES_cblock *output, DES_key_schedule *ks1, DES_key_schedule *ks2, DES_key_schedule *ks3, int enc) { register DES_LONG l0, l1; DES_LONG ll[2]; const unsigned char *in = &(*input)[0]; unsigned char *out = &(*output)[0]; c2l(in, l0); c2l(in, l1); ll[0] = l0; ll[1] = l1; if (enc) DES_encrypt3(ll, ks1, ks2, ks3); else DES_decrypt3(ll, ks1, ks2, ks3); l0 = ll[0]; l1 = ll[1]; l2c(l0, out); l2c(l1, out); }
1,055
25.4
78
c
openssl
openssl-master/crypto/des/ecb_enc.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "des_local.h" #include <openssl/opensslv.h> #include <openssl/bio.h> const char *DES_options(void) { static int init = 1; static char buf[12]; if (init) { if (sizeof(DES_LONG) != sizeof(long)) OPENSSL_strlcpy(buf, "des(int)", sizeof(buf)); else OPENSSL_strlcpy(buf, "des(long)", sizeof(buf)); init = 0; } return buf; } void DES_ecb_encrypt(const_DES_cblock *input, DES_cblock *output, DES_key_schedule *ks, int enc) { register DES_LONG l; DES_LONG ll[2]; const unsigned char *in = &(*input)[0]; unsigned char *out = &(*output)[0]; c2l(in, l); ll[0] = l; c2l(in, l); ll[1] = l; DES_encrypt1(ll, ks, enc); l = ll[0]; l2c(l, out); l = ll[1]; l2c(l, out); l = ll[0] = ll[1] = 0; }
1,301
22.672727
78
c
openssl
openssl-master/crypto/des/fcrypt.c
/* * Copyright 1998-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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" /* NOCW */ #include <stdio.h> #ifdef _OSD_POSIX # ifndef CHARSET_EBCDIC # define CHARSET_EBCDIC 1 # endif #endif #ifdef CHARSET_EBCDIC # include <openssl/ebcdic.h> #endif #include <openssl/crypto.h> #include "des_local.h" /* * Added more values to handle illegal salt values the way normal crypt() * implementations do. */ static const unsigned char con_salt[128] = { 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9, 0xDA, 0xDB, 0xDC, 0xDD, 0xDE, 0xDF, 0xE0, 0xE1, 0xE2, 0xE3, 0xE4, 0xE5, 0xE6, 0xE7, 0xE8, 0xE9, 0xEA, 0xEB, 0xEC, 0xED, 0xEE, 0xEF, 0xF0, 0xF1, 0xF2, 0xF3, 0xF4, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, }; static const unsigned char cov_2char[64] = { 0x2E, 0x2F, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A }; char *DES_crypt(const char *buf, const char *salt) { static char buff[14]; #ifndef CHARSET_EBCDIC return DES_fcrypt(buf, salt, buff); #else char e_salt[2 + 1]; char e_buf[32 + 1]; /* replace 32 by 8 ? */ char *ret; if (salt[0] == '\0' || salt[1] == '\0') return NULL; /* Copy salt, convert to ASCII. */ e_salt[0] = salt[0]; e_salt[1] = salt[1]; e_salt[2] = '\0'; ebcdic2ascii(e_salt, e_salt, sizeof(e_salt)); /* Convert password to ASCII. */ OPENSSL_strlcpy(e_buf, buf, sizeof(e_buf)); ebcdic2ascii(e_buf, e_buf, sizeof(e_buf)); /* Encrypt it (from/to ASCII); if it worked, convert back. */ ret = DES_fcrypt(e_buf, e_salt, buff); if (ret != NULL) ascii2ebcdic(ret, ret, strlen(ret)); return ret; #endif } char *DES_fcrypt(const char *buf, const char *salt, char *ret) { unsigned int i, j, x, y; DES_LONG Eswap0, Eswap1; DES_LONG out[2], ll; DES_cblock key; DES_key_schedule ks; unsigned char bb[9]; unsigned char *b = bb; unsigned char c, u; x = ret[0] = salt[0]; if (x == 0 || x >= sizeof(con_salt)) return NULL; Eswap0 = con_salt[x] << 2; x = ret[1] = salt[1]; if (x == 0 || x >= sizeof(con_salt)) return NULL; Eswap1 = con_salt[x] << 6; /* * EAY r=strlen(buf); r=(r+7)/8; */ for (i = 0; i < 8; i++) { c = *(buf++); if (!c) break; key[i] = (c << 1); } for (; i < 8; i++) key[i] = 0; DES_set_key_unchecked(&key, &ks); fcrypt_body(&(out[0]), &ks, Eswap0, Eswap1); ll = out[0]; l2c(ll, b); ll = out[1]; l2c(ll, b); y = 0; u = 0x80; bb[8] = 0; for (i = 2; i < 13; i++) { c = 0; for (j = 0; j < 6; j++) { c <<= 1; if (bb[y] & u) c |= 1; u >>= 1; if (!u) { y++; u = 0x80; } } ret[i] = cov_2char[c]; } ret[13] = '\0'; return ret; }
4,207
25.974359
78
c
openssl
openssl-master/crypto/des/fcrypt_b.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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <stdio.h> #define DES_FCRYPT #include "des_local.h" #undef DES_FCRYPT #undef PERM_OP #define PERM_OP(a,b,t,n,m) ((t)=((((a)>>(n))^(b))&(m)),\ (b)^=(t),\ (a)^=((t)<<(n))) #undef HPERM_OP #define HPERM_OP(a,t,n,m) ((t)=((((a)<<(16-(n)))^(a))&(m)),\ (a)=(a)^(t)^(t>>(16-(n))))\ void fcrypt_body(DES_LONG *out, DES_key_schedule *ks, DES_LONG Eswap0, DES_LONG Eswap1) { register DES_LONG l, r, t, u; register DES_LONG *s; register int j; register DES_LONG E0, E1; l = 0; r = 0; s = (DES_LONG *)ks; E0 = Eswap0; E1 = Eswap1; for (j = 0; j < 25; j++) { D_ENCRYPT(l, r, 0); /* 1 */ D_ENCRYPT(r, l, 2); /* 2 */ D_ENCRYPT(l, r, 4); /* 3 */ D_ENCRYPT(r, l, 6); /* 4 */ D_ENCRYPT(l, r, 8); /* 5 */ D_ENCRYPT(r, l, 10); /* 6 */ D_ENCRYPT(l, r, 12); /* 7 */ D_ENCRYPT(r, l, 14); /* 8 */ D_ENCRYPT(l, r, 16); /* 9 */ D_ENCRYPT(r, l, 18); /* 10 */ D_ENCRYPT(l, r, 20); /* 11 */ D_ENCRYPT(r, l, 22); /* 12 */ D_ENCRYPT(l, r, 24); /* 13 */ D_ENCRYPT(r, l, 26); /* 14 */ D_ENCRYPT(l, r, 28); /* 15 */ D_ENCRYPT(r, l, 30); /* 16 */ t = l; l = r; r = t; } l = ROTATE(l, 3) & 0xffffffffL; r = ROTATE(r, 3) & 0xffffffffL; PERM_OP(l, r, t, 1, 0x55555555L); PERM_OP(r, l, t, 8, 0x00ff00ffL); PERM_OP(l, r, t, 2, 0x33333333L); PERM_OP(r, l, t, 16, 0x0000ffffL); PERM_OP(l, r, t, 4, 0x0f0f0f0fL); out[0] = r; out[1] = l; }
2,109
25.708861
78
c
openssl
openssl-master/crypto/des/ncbc_enc.c
/* * Copyright 1998-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 */ /*- * #included by: * cbc_enc.c (DES_cbc_encrypt) * des_enc.c (DES_ncbc_encrypt) */ #include "des_local.h" #ifdef CBC_ENC_C__DONT_UPDATE_IV void DES_cbc_encrypt(const unsigned char *in, unsigned char *out, long length, DES_key_schedule *_schedule, DES_cblock *ivec, int enc) #else void DES_ncbc_encrypt(const unsigned char *in, unsigned char *out, long length, DES_key_schedule *_schedule, DES_cblock *ivec, int enc) #endif { register DES_LONG tin0, tin1; register DES_LONG tout0, tout1, xor0, xor1; register long l = length; DES_LONG tin[2]; unsigned char *iv; iv = &(*ivec)[0]; if (enc) { c2l(iv, tout0); c2l(iv, tout1); for (l -= 8; l >= 0; l -= 8) { c2l(in, tin0); c2l(in, tin1); tin0 ^= tout0; tin[0] = tin0; tin1 ^= tout1; tin[1] = tin1; DES_encrypt1((DES_LONG *)tin, _schedule, DES_ENCRYPT); tout0 = tin[0]; l2c(tout0, out); tout1 = tin[1]; l2c(tout1, out); } if (l != -8) { c2ln(in, tin0, tin1, l + 8); tin0 ^= tout0; tin[0] = tin0; tin1 ^= tout1; tin[1] = tin1; DES_encrypt1((DES_LONG *)tin, _schedule, DES_ENCRYPT); tout0 = tin[0]; l2c(tout0, out); tout1 = tin[1]; l2c(tout1, out); } #ifndef CBC_ENC_C__DONT_UPDATE_IV iv = &(*ivec)[0]; l2c(tout0, iv); l2c(tout1, iv); #endif } else { c2l(iv, xor0); c2l(iv, xor1); for (l -= 8; l >= 0; l -= 8) { c2l(in, tin0); tin[0] = tin0; c2l(in, tin1); tin[1] = tin1; DES_encrypt1((DES_LONG *)tin, _schedule, DES_DECRYPT); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2c(tout0, out); l2c(tout1, out); xor0 = tin0; xor1 = tin1; } if (l != -8) { c2l(in, tin0); tin[0] = tin0; c2l(in, tin1); tin[1] = tin1; DES_encrypt1((DES_LONG *)tin, _schedule, DES_DECRYPT); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; l2cn(tout0, tout1, out, l + 8); #ifndef CBC_ENC_C__DONT_UPDATE_IV xor0 = tin0; xor1 = tin1; #endif } #ifndef CBC_ENC_C__DONT_UPDATE_IV iv = &(*ivec)[0]; l2c(xor0, iv); l2c(xor1, iv); #endif } tin0 = tin1 = tout0 = tout1 = xor0 = xor1 = 0; tin[0] = tin[1] = 0; }
3,026
27.28972
78
c
openssl
openssl-master/crypto/des/ofb64ede.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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "des_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 DES_ede3_ofb64_encrypt(register const unsigned char *in, register unsigned char *out, long length, DES_key_schedule *k1, DES_key_schedule *k2, DES_key_schedule *k3, DES_cblock *ivec, int *num) { register DES_LONG v0, v1; register int n = *num; register long l = length; DES_cblock d; register char *dp; DES_LONG ti[2]; unsigned char *iv; int save = 0; iv = &(*ivec)[0]; c2l(iv, v0); c2l(iv, v1); ti[0] = v0; ti[1] = v1; dp = (char *)d; l2c(v0, dp); l2c(v1, dp); while (l--) { if (n == 0) { /* ti[0]=v0; */ /* ti[1]=v1; */ DES_encrypt3(ti, k1, k2, k3); v0 = ti[0]; v1 = ti[1]; dp = (char *)d; l2c(v0, dp); l2c(v1, dp); save++; } *(out++) = *(in++) ^ d[n]; n = (n + 1) & 0x07; } if (save) { iv = &(*ivec)[0]; l2c(v0, iv); l2c(v1, iv); } v0 = v1 = ti[0] = ti[1] = 0; *num = n; }
1,796
25.043478
78
c
openssl
openssl-master/crypto/des/ofb64enc.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 */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "des_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 DES_ofb64_encrypt(register const unsigned char *in, register unsigned char *out, long length, DES_key_schedule *schedule, DES_cblock *ivec, int *num) { register DES_LONG v0, v1, t; register int n = *num; register long l = length; DES_cblock d; register unsigned char *dp; DES_LONG ti[2]; unsigned char *iv; int save = 0; iv = &(*ivec)[0]; c2l(iv, v0); c2l(iv, v1); ti[0] = v0; ti[1] = v1; dp = d; l2c(v0, dp); l2c(v1, dp); while (l--) { if (n == 0) { DES_encrypt1(ti, schedule, DES_ENCRYPT); dp = d; t = ti[0]; l2c(t, dp); t = ti[1]; l2c(t, dp); save++; } *(out++) = *(in++) ^ d[n]; n = (n + 1) & 0x07; } if (save) { v0 = ti[0]; v1 = ti[1]; iv = &(*ivec)[0]; l2c(v0, iv); l2c(v1, iv); } t = v0 = v1 = ti[0] = ti[1] = 0; *num = n; }
1,705
24.462687
78
c
openssl
openssl-master/crypto/des/ofb_enc.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "des_local.h" /* * The input and output are loaded in multiples of 8 bits. What this means is * that if you have numbits=12 and length=2 the first 12 bits will be * retrieved from the first byte and half the second. The second 12 bits * will come from the 3rd and half the 4th byte. */ void DES_ofb_encrypt(const unsigned char *in, unsigned char *out, int numbits, long length, DES_key_schedule *schedule, DES_cblock *ivec) { register DES_LONG d0, d1, vv0, vv1, v0, v1, n = (numbits + 7) / 8; register DES_LONG mask0, mask1; register long l = length; register int num = numbits; DES_LONG ti[2]; unsigned char *iv; if (num > 64) return; if (num > 32) { mask0 = 0xffffffffL; if (num >= 64) mask1 = mask0; else mask1 = (1L << (num - 32)) - 1; } else { if (num == 32) mask0 = 0xffffffffL; else mask0 = (1L << num) - 1; mask1 = 0x00000000L; } iv = &(*ivec)[0]; c2l(iv, v0); c2l(iv, v1); ti[0] = v0; ti[1] = v1; while (l-- > 0) { ti[0] = v0; ti[1] = v1; DES_encrypt1((DES_LONG *)ti, schedule, DES_ENCRYPT); vv0 = ti[0]; vv1 = ti[1]; c2ln(in, d0, d1, n); in += n; d0 = (d0 ^ vv0) & mask0; d1 = (d1 ^ vv1) & mask1; l2cn(d0, d1, out, n); out += n; if (num == 32) { v0 = v1; v1 = vv0; } else if (num == 64) { v0 = vv0; v1 = vv1; } else if (num > 32) { /* && num != 64 */ v0 = ((v1 >> (num - 32)) | (vv0 << (64 - num))) & 0xffffffffL; v1 = ((vv0 >> (num - 32)) | (vv1 << (64 - num))) & 0xffffffffL; } else { /* num < 32 */ v0 = ((v0 >> num) | (v1 << (32 - num))) & 0xffffffffL; v1 = ((v1 >> num) | (vv0 << (32 - num))) & 0xffffffffL; } } iv = &(*ivec)[0]; l2c(v0, iv); l2c(v1, iv); v0 = v1 = d0 = d1 = ti[0] = ti[1] = vv0 = vv1 = 0; }
2,579
27.988764
78
c
openssl
openssl-master/crypto/des/pcbc_enc.c
/* * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "des_local.h" void DES_pcbc_encrypt(const unsigned char *input, unsigned char *output, long length, DES_key_schedule *schedule, DES_cblock *ivec, int enc) { register DES_LONG sin0, sin1, xor0, xor1, tout0, tout1; DES_LONG tin[2]; const unsigned char *in; unsigned char *out, *iv; in = input; out = output; iv = &(*ivec)[0]; if (enc) { c2l(iv, xor0); c2l(iv, xor1); for (; length > 0; length -= 8) { if (length >= 8) { c2l(in, sin0); c2l(in, sin1); } else c2ln(in, sin0, sin1, length); tin[0] = sin0 ^ xor0; tin[1] = sin1 ^ xor1; DES_encrypt1((DES_LONG *)tin, schedule, DES_ENCRYPT); tout0 = tin[0]; tout1 = tin[1]; xor0 = sin0 ^ tout0; xor1 = sin1 ^ tout1; l2c(tout0, out); l2c(tout1, out); } } else { c2l(iv, xor0); c2l(iv, xor1); for (; length > 0; length -= 8) { c2l(in, sin0); c2l(in, sin1); tin[0] = sin0; tin[1] = sin1; DES_encrypt1((DES_LONG *)tin, schedule, DES_DECRYPT); tout0 = tin[0] ^ xor0; tout1 = tin[1] ^ xor1; if (length >= 8) { l2c(tout0, out); l2c(tout1, out); } else l2cn(tout0, tout1, out, length); xor0 = tout0 ^ sin0; xor1 = tout1 ^ sin1; } } tin[0] = tin[1] = 0; sin0 = sin1 = xor0 = xor1 = tout0 = tout1 = 0; }
2,128
28.164384
78
c
openssl
openssl-master/crypto/des/qud_cksm.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 */ /* * From "Message Authentication" R.R. Jueneman, S.M. Matyas, C.H. Meyer IEEE * Communications Magazine Sept 1985 Vol. 23 No. 9 p 29-40 This module in * only based on the code in this paper and is almost definitely not the same * as the MIT implementation. */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include "des_local.h" #define Q_B0(a) (((DES_LONG)(a))) #define Q_B1(a) (((DES_LONG)(a))<<8) #define Q_B2(a) (((DES_LONG)(a))<<16) #define Q_B3(a) (((DES_LONG)(a))<<24) /* used to scramble things a bit */ /* Got the value MIT uses via brute force :-) 2/10/90 eay */ #define NOISE ((DES_LONG)83653421L) DES_LONG DES_quad_cksum(const unsigned char *input, DES_cblock output[], long length, int out_count, DES_cblock *seed) { DES_LONG z0, z1, t0, t1; int i; long l; const unsigned char *cp; DES_LONG *lp; if (out_count < 1) out_count = 1; lp = (DES_LONG *)&(output[0])[0]; z0 = Q_B0((*seed)[0]) | Q_B1((*seed)[1]) | Q_B2((*seed)[2]) | Q_B3((*seed)[3]); z1 = Q_B0((*seed)[4]) | Q_B1((*seed)[5]) | Q_B2((*seed)[6]) | Q_B3((*seed)[7]); for (i = 0; ((i < 4) && (i < out_count)); i++) { cp = input; l = length; while (l > 0) { if (l > 1) { t0 = (DES_LONG)(*(cp++)); t0 |= (DES_LONG)Q_B1(*(cp++)); l--; } else t0 = (DES_LONG)(*(cp++)); l--; /* add */ t0 += z0; t0 &= 0xffffffffL; t1 = z1; /* square, well sort of square */ z0 = ((((t0 * t0) & 0xffffffffL) + ((t1 * t1) & 0xffffffffL)) & 0xffffffffL) % 0x7fffffffL; z1 = ((t0 * ((t1 + NOISE) & 0xffffffffL)) & 0xffffffffL) % 0x7fffffffL; } if (lp != NULL) { /* * The MIT library assumes that the checksum is composed of * 2*out_count 32 bit ints */ *lp++ = z0; *lp++ = z1; } } return z0; }
2,508
28.869048
78
c
openssl
openssl-master/crypto/des/rand_key.c
/* * Copyright 1998-2020 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/des.h> #include <openssl/rand.h> int DES_random_key(DES_cblock *ret) { do { if (RAND_priv_bytes((unsigned char *)ret, sizeof(DES_cblock)) != 1) return 0; } while (DES_is_weak_key(ret)); DES_set_odd_parity(ret); return 1; }
743
25.571429
78
c
openssl
openssl-master/crypto/des/set_key.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 */ /*- * set_key.c v 1.4 eay 24/9/91 * 1.4 Speed up by 400% :-) * 1.3 added register declarations. * 1.2 unrolled make_key_sched a bit more * 1.1 added norm_expand_bits * 1.0 First working version */ /* * DES low level APIs are deprecated for public use, but still ok for internal * use. */ #include "internal/deprecated.h" #include <openssl/crypto.h> #include "internal/constant_time.h" #include "internal/nelem.h" #include "des_local.h" static const unsigned char odd_parity[256] = { 1, 1, 2, 2, 4, 4, 7, 7, 8, 8, 11, 11, 13, 13, 14, 14, 16, 16, 19, 19, 21, 21, 22, 22, 25, 25, 26, 26, 28, 28, 31, 31, 32, 32, 35, 35, 37, 37, 38, 38, 41, 41, 42, 42, 44, 44, 47, 47, 49, 49, 50, 50, 52, 52, 55, 55, 56, 56, 59, 59, 61, 61, 62, 62, 64, 64, 67, 67, 69, 69, 70, 70, 73, 73, 74, 74, 76, 76, 79, 79, 81, 81, 82, 82, 84, 84, 87, 87, 88, 88, 91, 91, 93, 93, 94, 94, 97, 97, 98, 98, 100, 100, 103, 103, 104, 104, 107, 107, 109, 109, 110, 110, 112, 112, 115, 115, 117, 117, 118, 118, 121, 121, 122, 122, 124, 124, 127, 127, 128, 128, 131, 131, 133, 133, 134, 134, 137, 137, 138, 138, 140, 140, 143, 143, 145, 145, 146, 146, 148, 148, 151, 151, 152, 152, 155, 155, 157, 157, 158, 158, 161, 161, 162, 162, 164, 164, 167, 167, 168, 168, 171, 171, 173, 173, 174, 174, 176, 176, 179, 179, 181, 181, 182, 182, 185, 185, 186, 186, 188, 188, 191, 191, 193, 193, 194, 194, 196, 196, 199, 199, 200, 200, 203, 203, 205, 205, 206, 206, 208, 208, 211, 211, 213, 213, 214, 214, 217, 217, 218, 218, 220, 220, 223, 223, 224, 224, 227, 227, 229, 229, 230, 230, 233, 233, 234, 234, 236, 236, 239, 239, 241, 241, 242, 242, 244, 244, 247, 247, 248, 248, 251, 251, 253, 253, 254, 254 }; void DES_set_odd_parity(DES_cblock *key) { unsigned int i; for (i = 0; i < DES_KEY_SZ; i++) (*key)[i] = odd_parity[(*key)[i]]; } /* * Check that a key has the correct parity. * Return 1 if parity is okay and 0 if not. */ int DES_check_key_parity(const_DES_cblock *key) { unsigned int i; unsigned char res = 0377, b; for (i = 0; i < DES_KEY_SZ; i++) { b = (*key)[i]; b ^= b >> 4; b ^= b >> 2; b ^= b >> 1; res &= constant_time_eq_8(b & 1, 1); } return (int)(res & 1); } /*- * Weak and semi weak keys as taken from * %A D.W. Davies * %A W.L. Price * %T Security for Computer Networks * %I John Wiley & Sons * %D 1984 */ static const DES_cblock weak_keys[] = { /* weak keys */ {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, {0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE}, {0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E}, {0xE0, 0xE0, 0xE0, 0xE0, 0xF1, 0xF1, 0xF1, 0xF1}, /* semi-weak keys */ {0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE}, {0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01}, {0x1F, 0xE0, 0x1F, 0xE0, 0x0E, 0xF1, 0x0E, 0xF1}, {0xE0, 0x1F, 0xE0, 0x1F, 0xF1, 0x0E, 0xF1, 0x0E}, {0x01, 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1}, {0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1, 0x01}, {0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E, 0xFE}, {0xFE, 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E}, {0x01, 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E}, {0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E, 0x01}, {0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE}, {0xFE, 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1} }; /* * Check for weak keys. * Return 1 if the key is weak and 0 otherwise. */ int DES_is_weak_key(const_DES_cblock *key) { unsigned int i, res = 0; int j; for (i = 0; i < OSSL_NELEM(weak_keys); i++) { j = CRYPTO_memcmp(weak_keys[i], key, sizeof(DES_cblock)); res |= constant_time_is_zero((unsigned int)j); } return (int)(res & 1); } /*- * NOW DEFINED IN des_local.h * See ecb_encrypt.c for a pseudo description of these macros. * #define PERM_OP(a,b,t,n,m) ((t)=((((a)>>(n))^(b))&(m)),\ * (b)^=(t),\ * (a)=((a)^((t)<<(n)))) */ #define HPERM_OP(a,t,n,m) ((t)=((((a)<<(16-(n)))^(a))&(m)),\ (a)=(a)^(t)^(t>>(16-(n)))) static const DES_LONG des_skb[8][64] = { { /* for C bits (numbered as per FIPS 46) 1 2 3 4 5 6 */ 0x00000000L, 0x00000010L, 0x20000000L, 0x20000010L, 0x00010000L, 0x00010010L, 0x20010000L, 0x20010010L, 0x00000800L, 0x00000810L, 0x20000800L, 0x20000810L, 0x00010800L, 0x00010810L, 0x20010800L, 0x20010810L, 0x00000020L, 0x00000030L, 0x20000020L, 0x20000030L, 0x00010020L, 0x00010030L, 0x20010020L, 0x20010030L, 0x00000820L, 0x00000830L, 0x20000820L, 0x20000830L, 0x00010820L, 0x00010830L, 0x20010820L, 0x20010830L, 0x00080000L, 0x00080010L, 0x20080000L, 0x20080010L, 0x00090000L, 0x00090010L, 0x20090000L, 0x20090010L, 0x00080800L, 0x00080810L, 0x20080800L, 0x20080810L, 0x00090800L, 0x00090810L, 0x20090800L, 0x20090810L, 0x00080020L, 0x00080030L, 0x20080020L, 0x20080030L, 0x00090020L, 0x00090030L, 0x20090020L, 0x20090030L, 0x00080820L, 0x00080830L, 0x20080820L, 0x20080830L, 0x00090820L, 0x00090830L, 0x20090820L, 0x20090830L, }, { /* for C bits (numbered as per FIPS 46) 7 8 10 11 12 13 */ 0x00000000L, 0x02000000L, 0x00002000L, 0x02002000L, 0x00200000L, 0x02200000L, 0x00202000L, 0x02202000L, 0x00000004L, 0x02000004L, 0x00002004L, 0x02002004L, 0x00200004L, 0x02200004L, 0x00202004L, 0x02202004L, 0x00000400L, 0x02000400L, 0x00002400L, 0x02002400L, 0x00200400L, 0x02200400L, 0x00202400L, 0x02202400L, 0x00000404L, 0x02000404L, 0x00002404L, 0x02002404L, 0x00200404L, 0x02200404L, 0x00202404L, 0x02202404L, 0x10000000L, 0x12000000L, 0x10002000L, 0x12002000L, 0x10200000L, 0x12200000L, 0x10202000L, 0x12202000L, 0x10000004L, 0x12000004L, 0x10002004L, 0x12002004L, 0x10200004L, 0x12200004L, 0x10202004L, 0x12202004L, 0x10000400L, 0x12000400L, 0x10002400L, 0x12002400L, 0x10200400L, 0x12200400L, 0x10202400L, 0x12202400L, 0x10000404L, 0x12000404L, 0x10002404L, 0x12002404L, 0x10200404L, 0x12200404L, 0x10202404L, 0x12202404L, }, { /* for C bits (numbered as per FIPS 46) 14 15 16 17 19 20 */ 0x00000000L, 0x00000001L, 0x00040000L, 0x00040001L, 0x01000000L, 0x01000001L, 0x01040000L, 0x01040001L, 0x00000002L, 0x00000003L, 0x00040002L, 0x00040003L, 0x01000002L, 0x01000003L, 0x01040002L, 0x01040003L, 0x00000200L, 0x00000201L, 0x00040200L, 0x00040201L, 0x01000200L, 0x01000201L, 0x01040200L, 0x01040201L, 0x00000202L, 0x00000203L, 0x00040202L, 0x00040203L, 0x01000202L, 0x01000203L, 0x01040202L, 0x01040203L, 0x08000000L, 0x08000001L, 0x08040000L, 0x08040001L, 0x09000000L, 0x09000001L, 0x09040000L, 0x09040001L, 0x08000002L, 0x08000003L, 0x08040002L, 0x08040003L, 0x09000002L, 0x09000003L, 0x09040002L, 0x09040003L, 0x08000200L, 0x08000201L, 0x08040200L, 0x08040201L, 0x09000200L, 0x09000201L, 0x09040200L, 0x09040201L, 0x08000202L, 0x08000203L, 0x08040202L, 0x08040203L, 0x09000202L, 0x09000203L, 0x09040202L, 0x09040203L, }, { /* for C bits (numbered as per FIPS 46) 21 23 24 26 27 28 */ 0x00000000L, 0x00100000L, 0x00000100L, 0x00100100L, 0x00000008L, 0x00100008L, 0x00000108L, 0x00100108L, 0x00001000L, 0x00101000L, 0x00001100L, 0x00101100L, 0x00001008L, 0x00101008L, 0x00001108L, 0x00101108L, 0x04000000L, 0x04100000L, 0x04000100L, 0x04100100L, 0x04000008L, 0x04100008L, 0x04000108L, 0x04100108L, 0x04001000L, 0x04101000L, 0x04001100L, 0x04101100L, 0x04001008L, 0x04101008L, 0x04001108L, 0x04101108L, 0x00020000L, 0x00120000L, 0x00020100L, 0x00120100L, 0x00020008L, 0x00120008L, 0x00020108L, 0x00120108L, 0x00021000L, 0x00121000L, 0x00021100L, 0x00121100L, 0x00021008L, 0x00121008L, 0x00021108L, 0x00121108L, 0x04020000L, 0x04120000L, 0x04020100L, 0x04120100L, 0x04020008L, 0x04120008L, 0x04020108L, 0x04120108L, 0x04021000L, 0x04121000L, 0x04021100L, 0x04121100L, 0x04021008L, 0x04121008L, 0x04021108L, 0x04121108L, }, { /* for D bits (numbered as per FIPS 46) 1 2 3 4 5 6 */ 0x00000000L, 0x10000000L, 0x00010000L, 0x10010000L, 0x00000004L, 0x10000004L, 0x00010004L, 0x10010004L, 0x20000000L, 0x30000000L, 0x20010000L, 0x30010000L, 0x20000004L, 0x30000004L, 0x20010004L, 0x30010004L, 0x00100000L, 0x10100000L, 0x00110000L, 0x10110000L, 0x00100004L, 0x10100004L, 0x00110004L, 0x10110004L, 0x20100000L, 0x30100000L, 0x20110000L, 0x30110000L, 0x20100004L, 0x30100004L, 0x20110004L, 0x30110004L, 0x00001000L, 0x10001000L, 0x00011000L, 0x10011000L, 0x00001004L, 0x10001004L, 0x00011004L, 0x10011004L, 0x20001000L, 0x30001000L, 0x20011000L, 0x30011000L, 0x20001004L, 0x30001004L, 0x20011004L, 0x30011004L, 0x00101000L, 0x10101000L, 0x00111000L, 0x10111000L, 0x00101004L, 0x10101004L, 0x00111004L, 0x10111004L, 0x20101000L, 0x30101000L, 0x20111000L, 0x30111000L, 0x20101004L, 0x30101004L, 0x20111004L, 0x30111004L, }, { /* for D bits (numbered as per FIPS 46) 8 9 11 12 13 14 */ 0x00000000L, 0x08000000L, 0x00000008L, 0x08000008L, 0x00000400L, 0x08000400L, 0x00000408L, 0x08000408L, 0x00020000L, 0x08020000L, 0x00020008L, 0x08020008L, 0x00020400L, 0x08020400L, 0x00020408L, 0x08020408L, 0x00000001L, 0x08000001L, 0x00000009L, 0x08000009L, 0x00000401L, 0x08000401L, 0x00000409L, 0x08000409L, 0x00020001L, 0x08020001L, 0x00020009L, 0x08020009L, 0x00020401L, 0x08020401L, 0x00020409L, 0x08020409L, 0x02000000L, 0x0A000000L, 0x02000008L, 0x0A000008L, 0x02000400L, 0x0A000400L, 0x02000408L, 0x0A000408L, 0x02020000L, 0x0A020000L, 0x02020008L, 0x0A020008L, 0x02020400L, 0x0A020400L, 0x02020408L, 0x0A020408L, 0x02000001L, 0x0A000001L, 0x02000009L, 0x0A000009L, 0x02000401L, 0x0A000401L, 0x02000409L, 0x0A000409L, 0x02020001L, 0x0A020001L, 0x02020009L, 0x0A020009L, 0x02020401L, 0x0A020401L, 0x02020409L, 0x0A020409L, }, { /* for D bits (numbered as per FIPS 46) 16 17 18 19 20 21 */ 0x00000000L, 0x00000100L, 0x00080000L, 0x00080100L, 0x01000000L, 0x01000100L, 0x01080000L, 0x01080100L, 0x00000010L, 0x00000110L, 0x00080010L, 0x00080110L, 0x01000010L, 0x01000110L, 0x01080010L, 0x01080110L, 0x00200000L, 0x00200100L, 0x00280000L, 0x00280100L, 0x01200000L, 0x01200100L, 0x01280000L, 0x01280100L, 0x00200010L, 0x00200110L, 0x00280010L, 0x00280110L, 0x01200010L, 0x01200110L, 0x01280010L, 0x01280110L, 0x00000200L, 0x00000300L, 0x00080200L, 0x00080300L, 0x01000200L, 0x01000300L, 0x01080200L, 0x01080300L, 0x00000210L, 0x00000310L, 0x00080210L, 0x00080310L, 0x01000210L, 0x01000310L, 0x01080210L, 0x01080310L, 0x00200200L, 0x00200300L, 0x00280200L, 0x00280300L, 0x01200200L, 0x01200300L, 0x01280200L, 0x01280300L, 0x00200210L, 0x00200310L, 0x00280210L, 0x00280310L, 0x01200210L, 0x01200310L, 0x01280210L, 0x01280310L, }, { /* for D bits (numbered as per FIPS 46) 22 23 24 25 27 28 */ 0x00000000L, 0x04000000L, 0x00040000L, 0x04040000L, 0x00000002L, 0x04000002L, 0x00040002L, 0x04040002L, 0x00002000L, 0x04002000L, 0x00042000L, 0x04042000L, 0x00002002L, 0x04002002L, 0x00042002L, 0x04042002L, 0x00000020L, 0x04000020L, 0x00040020L, 0x04040020L, 0x00000022L, 0x04000022L, 0x00040022L, 0x04040022L, 0x00002020L, 0x04002020L, 0x00042020L, 0x04042020L, 0x00002022L, 0x04002022L, 0x00042022L, 0x04042022L, 0x00000800L, 0x04000800L, 0x00040800L, 0x04040800L, 0x00000802L, 0x04000802L, 0x00040802L, 0x04040802L, 0x00002800L, 0x04002800L, 0x00042800L, 0x04042800L, 0x00002802L, 0x04002802L, 0x00042802L, 0x04042802L, 0x00000820L, 0x04000820L, 0x00040820L, 0x04040820L, 0x00000822L, 0x04000822L, 0x00040822L, 0x04040822L, 0x00002820L, 0x04002820L, 0x00042820L, 0x04042820L, 0x00002822L, 0x04002822L, 0x00042822L, 0x04042822L, } }; /* Return values as DES_set_key_checked() but always set the key */ int DES_set_key(const_DES_cblock *key, DES_key_schedule *schedule) { int ret = 0; if (!DES_check_key_parity(key)) ret = -1; if (DES_is_weak_key(key)) ret = -2; DES_set_key_unchecked(key, schedule); return ret; } /*- * return 0 if key parity is odd (correct), * return -1 if key parity error, * return -2 if illegal weak key. */ int DES_set_key_checked(const_DES_cblock *key, DES_key_schedule *schedule) { if (!DES_check_key_parity(key)) return -1; if (DES_is_weak_key(key)) return -2; DES_set_key_unchecked(key, schedule); return 0; } void DES_set_key_unchecked(const_DES_cblock *key, DES_key_schedule *schedule) { static const int shifts2[16] = { 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0 }; register DES_LONG c, d, t, s, t2; register const unsigned char *in; register DES_LONG *k; register int i; #ifdef OPENBSD_DEV_CRYPTO memcpy(schedule->key, key, sizeof(schedule->key)); schedule->session = NULL; #endif k = &schedule->ks->deslong[0]; in = &(*key)[0]; c2l(in, c); c2l(in, d); /* * do PC1 in 47 simple operations. Thanks to John Fletcher * for the inspiration. */ PERM_OP(d, c, t, 4, 0x0f0f0f0fL); HPERM_OP(c, t, -2, 0xcccc0000L); HPERM_OP(d, t, -2, 0xcccc0000L); PERM_OP(d, c, t, 1, 0x55555555L); PERM_OP(c, d, t, 8, 0x00ff00ffL); PERM_OP(d, c, t, 1, 0x55555555L); d = (((d & 0x000000ffL) << 16L) | (d & 0x0000ff00L) | ((d & 0x00ff0000L) >> 16L) | ((c & 0xf0000000L) >> 4L)); c &= 0x0fffffffL; for (i = 0; i < ITERATIONS; i++) { if (shifts2[i]) { c = ((c >> 2L) | (c << 26L)); d = ((d >> 2L) | (d << 26L)); } else { c = ((c >> 1L) | (c << 27L)); d = ((d >> 1L) | (d << 27L)); } c &= 0x0fffffffL; d &= 0x0fffffffL; /* * could be a few less shifts but I am to lazy at this point in time * to investigate */ s = des_skb[0][(c) & 0x3f] | des_skb[1][((c >> 6L) & 0x03) | ((c >> 7L) & 0x3c)] | des_skb[2][((c >> 13L) & 0x0f) | ((c >> 14L) & 0x30)] | des_skb[3][((c >> 20L) & 0x01) | ((c >> 21L) & 0x06) | ((c >> 22L) & 0x38)]; t = des_skb[4][(d) & 0x3f] | des_skb[5][((d >> 7L) & 0x03) | ((d >> 8L) & 0x3c)] | des_skb[6][(d >> 15L) & 0x3f] | des_skb[7][((d >> 21L) & 0x0f) | ((d >> 22L) & 0x30)]; /* table contained 0213 4657 */ t2 = ((t << 16L) | (s & 0x0000ffffL)) & 0xffffffffL; *(k++) = ROTATE(t2, 30) & 0xffffffffL; t2 = ((s >> 16L) | (t & 0xffff0000L)); *(k++) = ROTATE(t2, 26) & 0xffffffffL; } } int DES_key_sched(const_DES_cblock *key, DES_key_schedule *schedule) { return DES_set_key(key, schedule); }
15,377
37.931646
78
c