2cd7b970a2e8a2ba33ad8d264c2fce2df6af7303
[openssl.git] / test / ecdsatest.c
1 /*
2  * Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 /*
12  * Low level APIs are deprecated for public use, but still ok for internal use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <openssl/opensslconf.h> /* To see if OPENSSL_NO_EC is defined */
17 #include "testutil.h"
18
19 #ifndef OPENSSL_NO_EC
20
21 # include <openssl/evp.h>
22 # include <openssl/bn.h>
23 # include <openssl/ec.h>
24 # include <openssl/rand.h>
25 # include "internal/nelem.h"
26 # include "ecdsatest.h"
27
28 static fake_random_generate_cb fbytes;
29
30 static const char *numbers[2];
31 static size_t crv_len = 0;
32 static EC_builtin_curve *curves = NULL;
33 static OSSL_PROVIDER *fake_rand = NULL;
34
35 static int fbytes(unsigned char *buf, size_t num, ossl_unused const char *name,
36                   EVP_RAND_CTX *ctx)
37 {
38     int ret = 0;
39     static int fbytes_counter = 0;
40     BIGNUM *tmp = NULL;
41
42     fake_rand_set_callback(ctx, NULL);
43
44     if (!TEST_ptr(tmp = BN_new())
45         || !TEST_int_lt(fbytes_counter, OSSL_NELEM(numbers))
46         || !TEST_true(BN_hex2bn(&tmp, numbers[fbytes_counter]))
47         /* tmp might need leading zeros so pad it out */
48         || !TEST_int_le(BN_num_bytes(tmp), num)
49         || !TEST_true(BN_bn2binpad(tmp, buf, num)))
50         goto err;
51
52     fbytes_counter = (fbytes_counter + 1) % OSSL_NELEM(numbers);
53     ret = 1;
54  err:
55     BN_free(tmp);
56     return ret;
57 }
58
59 /*-
60  * This function hijacks the RNG to feed it the chosen ECDSA key and nonce.
61  * The ECDSA KATs are from:
62  * - the X9.62 draft (4)
63  * - NIST CAVP (720)
64  *
65  * It uses the low-level ECDSA_sign_setup instead of EVP to control the RNG.
66  * NB: This is not how applications should use ECDSA; this is only for testing.
67  *
68  * Tests the library can successfully:
69  * - generate public keys that matches those KATs
70  * - create ECDSA signatures that match those KATs
71  * - accept those signatures as valid
72  */
73 static int x9_62_tests(int n)
74 {
75     int nid, md_nid, ret = 0;
76     const char *r_in = NULL, *s_in = NULL, *tbs = NULL;
77     unsigned char *pbuf = NULL, *qbuf = NULL, *message = NULL;
78     unsigned char digest[EVP_MAX_MD_SIZE];
79     unsigned int dgst_len = 0;
80     long q_len, msg_len = 0;
81     size_t p_len;
82     EVP_MD_CTX *mctx = NULL;
83     EC_KEY *key = NULL;
84     ECDSA_SIG *signature = NULL;
85     BIGNUM *r = NULL, *s = NULL;
86     BIGNUM *kinv = NULL, *rp = NULL;
87     const BIGNUM *sig_r = NULL, *sig_s = NULL;
88
89     nid = ecdsa_cavs_kats[n].nid;
90     md_nid = ecdsa_cavs_kats[n].md_nid;
91     r_in = ecdsa_cavs_kats[n].r;
92     s_in = ecdsa_cavs_kats[n].s;
93     tbs = ecdsa_cavs_kats[n].msg;
94     numbers[0] = ecdsa_cavs_kats[n].d;
95     numbers[1] = ecdsa_cavs_kats[n].k;
96
97     TEST_info("ECDSA KATs for curve %s", OBJ_nid2sn(nid));
98
99 #ifdef FIPS_MODULE
100     if (EC_curve_nid2nist(nid) == NULL)
101         return TEST_skip("skip non approved curves");
102 #endif /* FIPS_MODULE */
103
104     if (!TEST_ptr(mctx = EVP_MD_CTX_new())
105         /* get the message digest */
106         || !TEST_ptr(message = OPENSSL_hexstr2buf(tbs, &msg_len))
107         || !TEST_true(EVP_DigestInit_ex(mctx, EVP_get_digestbynid(md_nid), NULL))
108         || !TEST_true(EVP_DigestUpdate(mctx, message, msg_len))
109         || !TEST_true(EVP_DigestFinal_ex(mctx, digest, &dgst_len))
110         /* create the key */
111         || !TEST_ptr(key = EC_KEY_new_by_curve_name(nid))
112         /* load KAT variables */
113         || !TEST_ptr(r = BN_new())
114         || !TEST_ptr(s = BN_new())
115         || !TEST_true(BN_hex2bn(&r, r_in))
116         || !TEST_true(BN_hex2bn(&s, s_in)))
117         goto err;
118
119     /* public key must match KAT */
120     fake_rand_set_callback(RAND_get0_private(NULL), &fbytes);
121     if (!TEST_true(EC_KEY_generate_key(key))
122         || !TEST_true(p_len = EC_KEY_key2buf(key, POINT_CONVERSION_UNCOMPRESSED,
123                                              &pbuf, NULL))
124         || !TEST_ptr(qbuf = OPENSSL_hexstr2buf(ecdsa_cavs_kats[n].Q, &q_len))
125         || !TEST_int_eq(q_len, p_len)
126         || !TEST_mem_eq(qbuf, q_len, pbuf, p_len))
127         goto err;
128
129     /* create the signature via ECDSA_sign_setup to avoid use of ECDSA nonces */
130     fake_rand_set_callback(RAND_get0_private(NULL), &fbytes);
131     if (!TEST_true(ECDSA_sign_setup(key, NULL, &kinv, &rp))
132         || !TEST_ptr(signature = ECDSA_do_sign_ex(digest, dgst_len,
133                                                   kinv, rp, key))
134         /* verify the signature */
135         || !TEST_int_eq(ECDSA_do_verify(digest, dgst_len, signature, key), 1))
136         goto err;
137
138     /* compare the created signature with the expected signature */
139     ECDSA_SIG_get0(signature, &sig_r, &sig_s);
140     if (!TEST_BN_eq(sig_r, r)
141         || !TEST_BN_eq(sig_s, s))
142         goto err;
143
144     ret = 1;
145
146  err:
147     OPENSSL_free(message);
148     OPENSSL_free(pbuf);
149     OPENSSL_free(qbuf);
150     EC_KEY_free(key);
151     ECDSA_SIG_free(signature);
152     BN_free(r);
153     BN_free(s);
154     EVP_MD_CTX_free(mctx);
155     BN_clear_free(kinv);
156     BN_clear_free(rp);
157     return ret;
158 }
159
160 /*-
161  * Positive and negative ECDSA testing through EVP interface:
162  * - EVP_DigestSign (this is the one-shot version)
163  * - EVP_DigestVerify
164  *
165  * Tests the library can successfully:
166  * - create a key
167  * - create a signature
168  * - accept that signature
169  * - reject that signature with a different public key
170  * - reject that signature if its length is not correct
171  * - reject that signature after modifying the message
172  * - accept that signature after un-modifying the message
173  * - reject that signature after modifying the signature
174  * - accept that signature after un-modifying the signature
175  */
176 static int set_sm2_id(EVP_MD_CTX *mctx, EVP_PKEY *pkey)
177 {
178     /* With the SM2 key type, the SM2 ID is mandatory */
179     static const char sm2_id[] = { 1, 2, 3, 4, 'l', 'e', 't', 't', 'e', 'r' };
180     EVP_PKEY_CTX *pctx;
181
182     if (!TEST_ptr(pctx = EVP_MD_CTX_pkey_ctx(mctx))
183         || !TEST_int_gt(EVP_PKEY_CTX_set1_id(pctx, sm2_id, sizeof(sm2_id)), 0))
184         return 0;
185     return 1;
186 }
187
188 static int test_builtin(int n, int as)
189 {
190     EC_KEY *eckey_neg = NULL, *eckey = NULL;
191     unsigned char dirt, offset, tbs[128];
192     unsigned char *sig = NULL;
193     EVP_PKEY *pkey_neg = NULL, *pkey = NULL, *dup_pk = NULL;
194     EVP_MD_CTX *mctx = NULL;
195     size_t sig_len;
196     int nid, ret = 0;
197     int temp;
198
199     nid = curves[n].nid;
200
201     /* skip built-in curves where ord(G) is not prime */
202     if (nid == NID_ipsec4 || nid == NID_ipsec3) {
203         TEST_info("skipped: ECDSA unsupported for curve %s", OBJ_nid2sn(nid));
204         return 1;
205     }
206
207     /*
208      * skip SM2 curve if 'as' is equal to EVP_PKEY_EC or, skip all curves
209      * except SM2 curve if 'as' is equal to EVP_PKEY_SM2
210      */
211     if (nid == NID_sm2 && as == EVP_PKEY_EC) {
212         TEST_info("skipped: EC key type unsupported for curve %s",
213                   OBJ_nid2sn(nid));
214         return 1;
215     } else if (nid != NID_sm2 && as == EVP_PKEY_SM2) {
216         TEST_info("skipped: SM2 key type unsupported for curve %s",
217                   OBJ_nid2sn(nid));
218         return 1;
219     }
220
221     TEST_info("testing ECDSA for curve %s as %s key type", OBJ_nid2sn(nid),
222               as == EVP_PKEY_EC ? "EC" : "SM2");
223
224     if (!TEST_ptr(mctx = EVP_MD_CTX_new())
225         /* get some random message data */
226         || !TEST_true(RAND_bytes(tbs, sizeof(tbs)))
227         /* real key */
228         || !TEST_ptr(eckey = EC_KEY_new_by_curve_name(nid))
229         || !TEST_true(EC_KEY_generate_key(eckey))
230         || !TEST_ptr(pkey = EVP_PKEY_new())
231         || !TEST_true(EVP_PKEY_assign_EC_KEY(pkey, eckey))
232         /* fake key for negative testing */
233         || !TEST_ptr(eckey_neg = EC_KEY_new_by_curve_name(nid))
234         || !TEST_true(EC_KEY_generate_key(eckey_neg))
235         || !TEST_ptr(pkey_neg = EVP_PKEY_new())
236         || !TEST_false(EVP_PKEY_assign_EC_KEY(pkey_neg, NULL))
237         || !TEST_true(EVP_PKEY_assign_EC_KEY(pkey_neg, eckey_neg)))
238         goto err;
239
240     if (!TEST_ptr(dup_pk = EVP_PKEY_dup(pkey))
241         || !TEST_int_eq(EVP_PKEY_eq(pkey, dup_pk), 1))
242         goto err;
243
244     temp = ECDSA_size(eckey);
245
246     /*
247      * |as| indicates how we want to treat the key, i.e. what sort of
248      * computation we want to do with it.  The two choices are the key
249      * types EVP_PKEY_EC and EVP_PKEY_SM2.  It's perfectly possible to
250      * switch back and forth between those two key types, regardless of
251      * curve, even though the default is to have EVP_PKEY_SM2 for the
252      * SM2 curve and EVP_PKEY_EC for all other curves.
253      */
254     if (!TEST_true(EVP_PKEY_set_alias_type(pkey, as))
255         || !TEST_true(EVP_PKEY_set_alias_type(pkey_neg, as)))
256             goto err;
257
258     if (!TEST_int_ge(temp, 0)
259         || !TEST_ptr(sig = OPENSSL_malloc(sig_len = (size_t)temp))
260         /* create a signature */
261         || !TEST_true(EVP_DigestSignInit(mctx, NULL, NULL, NULL, pkey))
262         || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
263         || !TEST_true(EVP_DigestSign(mctx, sig, &sig_len, tbs, sizeof(tbs)))
264         || !TEST_int_le(sig_len, ECDSA_size(eckey))
265         || !TEST_true(EVP_MD_CTX_reset(mctx))
266         /* negative test, verify with wrong key, 0 return */
267         || !TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey_neg))
268         || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey_neg))
269         || !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 0)
270         || !TEST_true(EVP_MD_CTX_reset(mctx))
271         /* negative test, verify with wrong signature length, -1 return */
272         || !TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
273         || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
274         || !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len - 1, tbs, sizeof(tbs)), -1)
275         || !TEST_true(EVP_MD_CTX_reset(mctx))
276         /* positive test, verify with correct key, 1 return */
277         || !TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
278         || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
279         || !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1)
280         || !TEST_true(EVP_MD_CTX_reset(mctx)))
281         goto err;
282
283     /* muck with the message, test it fails with 0 return */
284     tbs[0] ^= 1;
285     if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
286         || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
287         || !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 0)
288         || !TEST_true(EVP_MD_CTX_reset(mctx)))
289         goto err;
290     /* un-muck and test it verifies */
291     tbs[0] ^= 1;
292     if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
293         || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
294         || !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1)
295         || !TEST_true(EVP_MD_CTX_reset(mctx)))
296         goto err;
297
298     /*-
299      * Muck with the ECDSA signature. The DER encoding is one of:
300      * - 30 LL 02 ..
301      * - 30 81 LL 02 ..
302      *
303      * - Sometimes this mucks with the high level DER sequence wrapper:
304      *   in that case, DER-parsing of the whole signature should fail.
305      *
306      * - Sometimes this mucks with the DER-encoding of ECDSA.r:
307      *   in that case, DER-parsing of ECDSA.r should fail.
308      *
309      * - Sometimes this mucks with the DER-encoding of ECDSA.s:
310      *   in that case, DER-parsing of ECDSA.s should fail.
311      *
312      * - Sometimes this mucks with ECDSA.r:
313      *   in that case, the signature verification should fail.
314      *
315      * - Sometimes this mucks with ECDSA.s:
316      *   in that case, the signature verification should fail.
317      *
318      * The usual case is changing the integer value of ECDSA.r or ECDSA.s.
319      * Because the ratio of DER overhead to signature bytes is small.
320      * So most of the time it will be one of the last two cases.
321      *
322      * In any case, EVP_PKEY_verify should not return 1 for valid.
323      */
324     offset = tbs[0] % sig_len;
325     dirt = tbs[1] ? tbs[1] : 1;
326     sig[offset] ^= dirt;
327     if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
328         || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
329         || !TEST_int_ne(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1)
330         || !TEST_true(EVP_MD_CTX_reset(mctx)))
331         goto err;
332     /* un-muck and test it verifies */
333     sig[offset] ^= dirt;
334     if (!TEST_true(EVP_DigestVerifyInit(mctx, NULL, NULL, NULL, pkey))
335         || (as == EVP_PKEY_SM2 && !set_sm2_id(mctx, pkey))
336         || !TEST_int_eq(EVP_DigestVerify(mctx, sig, sig_len, tbs, sizeof(tbs)), 1)
337         || !TEST_true(EVP_MD_CTX_reset(mctx)))
338         goto err;
339
340     ret = 1;
341  err:
342     EVP_PKEY_free(pkey);
343     EVP_PKEY_free(pkey_neg);
344     EVP_PKEY_free(dup_pk);
345     EVP_MD_CTX_free(mctx);
346     OPENSSL_free(sig);
347     return ret;
348 }
349
350 static int test_builtin_as_ec(int n)
351 {
352     return test_builtin(n, EVP_PKEY_EC);
353 }
354
355 # ifndef OPENSSL_NO_SM2
356 static int test_builtin_as_sm2(int n)
357 {
358     return test_builtin(n, EVP_PKEY_SM2);
359 }
360 # endif
361 #endif /* OPENSSL_NO_EC */
362
363 int setup_tests(void)
364 {
365 #ifdef OPENSSL_NO_EC
366     TEST_note("Elliptic curves are disabled.");
367 #else
368     fake_rand = fake_rand_start(NULL);
369     if (fake_rand == NULL)
370         return 0;
371
372     /* get a list of all internal curves */
373     crv_len = EC_get_builtin_curves(NULL, 0);
374     if (!TEST_ptr(curves = OPENSSL_malloc(sizeof(*curves) * crv_len))
375         || !TEST_true(EC_get_builtin_curves(curves, crv_len))) {
376         fake_rand_finish(fake_rand);
377         return 0;
378     }
379     ADD_ALL_TESTS(test_builtin_as_ec, crv_len);
380 # ifndef OPENSSL_NO_SM2
381     ADD_ALL_TESTS(test_builtin_as_sm2, crv_len);
382 # endif
383     ADD_ALL_TESTS(x9_62_tests, OSSL_NELEM(ecdsa_cavs_kats));
384 #endif
385     return 1;
386 }
387
388 void cleanup_tests(void)
389 {
390 #ifndef OPENSSL_NO_EC
391     fake_rand_finish(fake_rand);
392     OPENSSL_free(curves);
393 #endif
394 }