/* Provenance: openssl/openssl DH_check (fixed). * repo: openssl/openssl * commit: 8780a896543a654e757db1b9396383f9d8095528 * parent: fe824ce0c5d51e7e7cf36c31db6c49c1c0c04a25 * commit_url: https://github.com/openssl/openssl/commit/8780a896543a654e757db1b9396383f9d8095528 * cve: CVE-2023-3446 * license: Apache-2.0 * function: DH_check * relpath: crypto/dh/dh_check.c */ int DH_check(const DH *dh, int *ret) { int ok = 0, r; BN_CTX *ctx = NULL; BIGNUM *t1 = NULL, *t2 = NULL; /* Don't do any checks at all with an excessively large modulus */ if (BN_num_bits(dh->p) > OPENSSL_DH_CHECK_MAX_MODULUS_BITS) { DHerr(DH_F_DH_CHECK, DH_R_MODULUS_TOO_LARGE); return 0; } if (!DH_check_params(dh, ret)) return 0; ctx = BN_CTX_new(); if (ctx == NULL) goto err; BN_CTX_start(ctx); t1 = BN_CTX_get(ctx); t2 = BN_CTX_get(ctx); if (t2 == NULL) goto err; if (dh->q) { if (BN_cmp(dh->g, BN_value_one()) <= 0) *ret |= DH_NOT_SUITABLE_GENERATOR; else if (BN_cmp(dh->g, dh->p) >= 0) *ret |= DH_NOT_SUITABLE_GENERATOR; else { /* Check g^q == 1 mod p */ if (!BN_mod_exp(t1, dh->g, dh->q, dh->p, ctx)) goto err; if (!BN_is_one(t1)) *ret |= DH_NOT_SUITABLE_GENERATOR; } r = BN_is_prime_ex(dh->q, DH_NUMBER_ITERATIONS_FOR_PRIME, ctx, NULL); if (r < 0) goto err; if (!r) *ret |= DH_CHECK_Q_NOT_PRIME; /* Check p == 1 mod q i.e. q divides p - 1 */ if (!BN_div(t1, t2, dh->p, dh->q, ctx)) goto err; if (!BN_is_one(t2)) *ret |= DH_CHECK_INVALID_Q_VALUE; if (dh->j && BN_cmp(dh->j, t1)) *ret |= DH_CHECK_INVALID_J_VALUE; } r = BN_is_prime_ex(dh->p, DH_NUMBER_ITERATIONS_FOR_PRIME, ctx, NULL); if (r < 0) goto err; if (!r) *ret |= DH_CHECK_P_NOT_PRIME; else if (!dh->q) { if (!BN_rshift1(t1, dh->p)) goto err; r = BN_is_prime_ex(t1, DH_NUMBER_ITERATIONS_FOR_PRIME, ctx, NULL); if (r < 0) goto err; if (!r) *ret |= DH_CHECK_P_NOT_SAFE_PRIME; } ok = 1; err: BN_CTX_end(ctx); BN_CTX_free(ctx); return ok; }