EC only uses approved curves in FIPS mode.
[openssl.git] / crypto / ec / ec_check.c
1 /*
2  * Copyright 2002-2019 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "ec_lcl.h"
11 #include <openssl/err.h>
12
13 int EC_GROUP_check_named_curve(const EC_GROUP *group, int nist_only)
14 {
15     int nid;
16
17     nid = ec_curve_nid_from_params(group);
18     if (nid > 0 && nist_only && EC_curve_nid2nist(nid) == NULL)
19         nid = NID_undef;
20     return nid;
21 }
22
23 int EC_GROUP_check(const EC_GROUP *group, BN_CTX *ctx)
24 {
25 #ifdef FIPS_MODE
26     /*
27     * ECC domain parameter validation.
28     * See SP800-56A R3 5.5.2 "Assurances of Domain-Parameter Validity" Part 1b.
29     */
30     return EC_GROUP_check_named_curve(group, 1) >= 0 ? 1 : 0;
31 #else
32     int ret = 0;
33     const BIGNUM *order;
34     BN_CTX *new_ctx = NULL;
35     EC_POINT *point = NULL;
36
37     if (group == NULL || group->meth == NULL) {
38         ECerr(EC_F_EC_GROUP_CHECK, ERR_R_PASSED_NULL_PARAMETER);
39         return 0;
40     }
41
42     /* Custom curves assumed to be correct */
43     if ((group->meth->flags & EC_FLAGS_CUSTOM_CURVE) != 0)
44         return 1;
45
46     if (ctx == NULL) {
47         ctx = new_ctx = BN_CTX_new();
48         if (ctx == NULL) {
49             ECerr(EC_F_EC_GROUP_CHECK, ERR_R_MALLOC_FAILURE);
50             goto err;
51         }
52     }
53
54     /* check the discriminant */
55     if (!EC_GROUP_check_discriminant(group, ctx)) {
56         ECerr(EC_F_EC_GROUP_CHECK, EC_R_DISCRIMINANT_IS_ZERO);
57         goto err;
58     }
59
60     /* check the generator */
61     if (group->generator == NULL) {
62         ECerr(EC_F_EC_GROUP_CHECK, EC_R_UNDEFINED_GENERATOR);
63         goto err;
64     }
65     if (EC_POINT_is_on_curve(group, group->generator, ctx) <= 0) {
66         ECerr(EC_F_EC_GROUP_CHECK, EC_R_POINT_IS_NOT_ON_CURVE);
67         goto err;
68     }
69
70     /* check the order of the generator */
71     if ((point = EC_POINT_new(group)) == NULL)
72         goto err;
73     order = EC_GROUP_get0_order(group);
74     if (order == NULL)
75         goto err;
76     if (BN_is_zero(order)) {
77         ECerr(EC_F_EC_GROUP_CHECK, EC_R_UNDEFINED_ORDER);
78         goto err;
79     }
80
81     if (!EC_POINT_mul(group, point, order, NULL, NULL, ctx))
82         goto err;
83     if (!EC_POINT_is_at_infinity(group, point)) {
84         ECerr(EC_F_EC_GROUP_CHECK, EC_R_INVALID_GROUP_ORDER);
85         goto err;
86     }
87
88     ret = 1;
89
90  err:
91     BN_CTX_free(new_ctx);
92     EC_POINT_free(point);
93     return ret;
94 #endif /* FIPS_MODE */
95 }