Fix a warning about an uninit var
[openssl.git] / test / ecdsatest.c
1 /*
2  * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 /* ====================================================================
11  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
12  *
13  * Portions of the attached software ("Contribution") are developed by
14  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
15  *
16  * The Contribution is licensed pursuant to the OpenSSL open source
17  * license provided above.
18  *
19  * The elliptic curve binary polynomial software is originally written by
20  * Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems Laboratories.
21  *
22  */
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27
28 #include <openssl/opensslconf.h> /* To see if OPENSSL_NO_EC is defined */
29
30 #ifdef OPENSSL_NO_EC
31 int main(int argc, char *argv[])
32 {
33     puts("Elliptic curves are disabled.");
34     return 0;
35 }
36 #else
37
38 # include <openssl/crypto.h>
39 # include <openssl/bio.h>
40 # include <openssl/evp.h>
41 # include <openssl/bn.h>
42 # include <openssl/ec.h>
43 # ifndef OPENSSL_NO_ENGINE
44 #  include <openssl/engine.h>
45 # endif
46 # include <openssl/err.h>
47 # include <openssl/rand.h>
48
49 static const char rnd_seed[] = "string to make the random number generator "
50     "think it has entropy";
51
52 /* declaration of the test functions */
53 int x9_62_tests(BIO *);
54 int x9_62_test_internal(BIO *out, int nid, const char *r, const char *s);
55 int test_builtin(BIO *);
56
57 /* functions to change the RAND_METHOD */
58 int change_rand(void);
59 int restore_rand(void);
60 int fbytes(unsigned char *buf, int num);
61
62 static RAND_METHOD fake_rand;
63 static const RAND_METHOD *old_rand;
64
65 int change_rand(void)
66 {
67     /* save old rand method */
68     if ((old_rand = RAND_get_rand_method()) == NULL)
69         return 0;
70
71     fake_rand.seed = old_rand->seed;
72     fake_rand.cleanup = old_rand->cleanup;
73     fake_rand.add = old_rand->add;
74     fake_rand.status = old_rand->status;
75     /* use own random function */
76     fake_rand.bytes = fbytes;
77     fake_rand.pseudorand = old_rand->bytes;
78     /* set new RAND_METHOD */
79     if (!RAND_set_rand_method(&fake_rand))
80         return 0;
81     return 1;
82 }
83
84 int restore_rand(void)
85 {
86     if (!RAND_set_rand_method(old_rand))
87         return 0;
88     else
89         return 1;
90 }
91
92 static int fbytes_counter = 0, use_fake = 0;
93 static const char *numbers[8] = {
94     "651056770906015076056810763456358567190100156695615665659",
95     "6140507067065001063065065565667405560006161556565665656654",
96     "8763001015071075675010661307616710783570106710677817767166"
97         "71676178726717",
98     "7000000175690566466555057817571571075705015757757057795755"
99         "55657156756655",
100     "1275552191113212300012030439187146164646146646466749494799",
101     "1542725565216523985789236956265265265235675811949404040041",
102     "1456427555219115346513212300075341203043918714616464614664"
103         "64667494947990",
104     "1712787255652165239672857892369562652652652356758119494040"
105         "40041670216363"
106 };
107
108 int fbytes(unsigned char *buf, int num)
109 {
110     int ret;
111     BIGNUM *tmp = NULL;
112
113     if (use_fake == 0)
114         return old_rand->bytes(buf, num);
115
116     use_fake = 0;
117
118     if (fbytes_counter >= 8)
119         return 0;
120     tmp = BN_new();
121     if (!tmp)
122         return 0;
123     if (!BN_dec2bn(&tmp, numbers[fbytes_counter])) {
124         BN_free(tmp);
125         return 0;
126     }
127     fbytes_counter++;
128     if (num != BN_num_bytes(tmp) || !BN_bn2bin(tmp, buf))
129         ret = 0;
130     else
131         ret = 1;
132     BN_free(tmp);
133     return ret;
134 }
135
136 /* some tests from the X9.62 draft */
137 int x9_62_test_internal(BIO *out, int nid, const char *r_in, const char *s_in)
138 {
139     int ret = 0;
140     const char message[] = "abc";
141     unsigned char digest[20];
142     unsigned int dgst_len = 0;
143     EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
144     EC_KEY *key = NULL;
145     ECDSA_SIG *signature = NULL;
146     BIGNUM *r = NULL, *s = NULL;
147     BIGNUM *kinv = NULL, *rp = NULL;
148     const BIGNUM *sig_r, *sig_s;
149
150     if (md_ctx == NULL)
151         goto x962_int_err;
152
153     /* get the message digest */
154     if (!EVP_DigestInit(md_ctx, EVP_sha1())
155         || !EVP_DigestUpdate(md_ctx, (const void *)message, 3)
156         || !EVP_DigestFinal(md_ctx, digest, &dgst_len))
157         goto x962_int_err;
158
159     BIO_printf(out, "testing %s: ", OBJ_nid2sn(nid));
160     /* create the key */
161     if ((key = EC_KEY_new_by_curve_name(nid)) == NULL)
162         goto x962_int_err;
163     use_fake = 1;
164     if (!EC_KEY_generate_key(key))
165         goto x962_int_err;
166     BIO_printf(out, ".");
167     (void)BIO_flush(out);
168     /* create the signature */
169     use_fake = 1;
170     /* Use ECDSA_sign_setup to avoid use of ECDSA nonces */
171     if (!ECDSA_sign_setup(key, NULL, &kinv, &rp))
172         goto x962_int_err;
173     signature = ECDSA_do_sign_ex(digest, 20, kinv, rp, key);
174     if (signature == NULL)
175         goto x962_int_err;
176     BIO_printf(out, ".");
177     (void)BIO_flush(out);
178     /* compare the created signature with the expected signature */
179     if ((r = BN_new()) == NULL || (s = BN_new()) == NULL)
180         goto x962_int_err;
181     if (!BN_dec2bn(&r, r_in) || !BN_dec2bn(&s, s_in))
182         goto x962_int_err;
183     ECDSA_SIG_get0(signature, &sig_r, &sig_s);
184     if (BN_cmp(sig_r, r) || BN_cmp(sig_s, s))
185         goto x962_int_err;
186     BIO_printf(out, ".");
187     (void)BIO_flush(out);
188     /* verify the signature */
189     if (ECDSA_do_verify(digest, 20, signature, key) != 1)
190         goto x962_int_err;
191     BIO_printf(out, ".");
192     (void)BIO_flush(out);
193
194     BIO_printf(out, " ok\n");
195     ret = 1;
196  x962_int_err:
197     if (!ret)
198         BIO_printf(out, " failed\n");
199     EC_KEY_free(key);
200     ECDSA_SIG_free(signature);
201     BN_free(r);
202     BN_free(s);
203     EVP_MD_CTX_free(md_ctx);
204     BN_clear_free(kinv);
205     BN_clear_free(rp);
206     return ret;
207 }
208
209 int x9_62_tests(BIO *out)
210 {
211     int ret = 0;
212
213     BIO_printf(out, "some tests from X9.62:\n");
214
215     /* set own rand method */
216     if (!change_rand())
217         goto x962_err;
218
219     if (!x9_62_test_internal(out, NID_X9_62_prime192v1,
220                              "3342403536405981729393488334694600415596881826869351677613",
221                              "5735822328888155254683894997897571951568553642892029982342"))
222         goto x962_err;
223     if (!x9_62_test_internal(out, NID_X9_62_prime239v1,
224                              "3086361431751678114926225473006680188549593787585317781474"
225                              "62058306432176",
226                              "3238135532097973577080787768312505059318910517550078427819"
227                              "78505179448783"))
228         goto x962_err;
229 # ifndef OPENSSL_NO_EC2M
230     if (!x9_62_test_internal(out, NID_X9_62_c2tnb191v1,
231                              "87194383164871543355722284926904419997237591535066528048",
232                              "308992691965804947361541664549085895292153777025772063598"))
233         goto x962_err;
234     if (!x9_62_test_internal(out, NID_X9_62_c2tnb239v1,
235                              "2159633321041961198501834003903461262881815148684178964245"
236                              "5876922391552",
237                              "1970303740007316867383349976549972270528498040721988191026"
238                              "49413465737174"))
239         goto x962_err;
240 # endif
241     ret = 1;
242  x962_err:
243     if (!restore_rand())
244         ret = 0;
245     return ret;
246 }
247
248 int test_builtin(BIO *out)
249 {
250     EC_builtin_curve *curves = NULL;
251     size_t crv_len = 0, n = 0;
252     EC_KEY *eckey = NULL, *wrong_eckey = NULL;
253     EC_GROUP *group;
254     ECDSA_SIG *ecdsa_sig = NULL, *modified_sig = NULL;
255     unsigned char digest[20], wrong_digest[20];
256     unsigned char *signature = NULL;
257     const unsigned char *sig_ptr;
258     unsigned char *sig_ptr2;
259     unsigned char *raw_buf = NULL;
260     const BIGNUM *sig_r, *sig_s;
261     BIGNUM *modified_r = NULL, *modified_s = NULL;
262     BIGNUM *unmodified_r = NULL, *unmodified_s = NULL;
263     unsigned int sig_len, degree, r_len, s_len, bn_len, buf_len;
264     int nid, ret = 0;
265
266     /* fill digest values with some random data */
267     if (RAND_bytes(digest, 20) <= 0 || RAND_bytes(wrong_digest, 20) <= 0) {
268         BIO_printf(out, "ERROR: unable to get random data\n");
269         goto builtin_err;
270     }
271
272     /*
273      * create and verify a ecdsa signature with every available curve (with )
274      */
275     BIO_printf(out, "\ntesting ECDSA_sign() and ECDSA_verify() "
276                "with some internal curves:\n");
277
278     /* get a list of all internal curves */
279     crv_len = EC_get_builtin_curves(NULL, 0);
280     curves = OPENSSL_malloc(sizeof(*curves) * crv_len);
281     if (curves == NULL) {
282         BIO_printf(out, "malloc error\n");
283         goto builtin_err;
284     }
285
286     if (!EC_get_builtin_curves(curves, crv_len)) {
287         BIO_printf(out, "unable to get internal curves\n");
288         goto builtin_err;
289     }
290
291     /* now create and verify a signature for every curve */
292     for (n = 0; n < crv_len; n++) {
293         unsigned char dirt, offset;
294
295         nid = curves[n].nid;
296         if (nid == NID_ipsec4 || nid == NID_X25519)
297             continue;
298         /* create new ecdsa key (== EC_KEY) */
299         if ((eckey = EC_KEY_new()) == NULL)
300             goto builtin_err;
301         group = EC_GROUP_new_by_curve_name(nid);
302         if (group == NULL)
303             goto builtin_err;
304         if (EC_KEY_set_group(eckey, group) == 0)
305             goto builtin_err;
306         EC_GROUP_free(group);
307         degree = EC_GROUP_get_degree(EC_KEY_get0_group(eckey));
308         if (degree < 160) {
309             /* drop the curve */
310             EC_KEY_free(eckey);
311             eckey = NULL;
312             continue;
313         }
314         BIO_printf(out, "%s: ", OBJ_nid2sn(nid));
315         /* create key */
316         if (!EC_KEY_generate_key(eckey)) {
317             BIO_printf(out, " failed\n");
318             goto builtin_err;
319         }
320         /* create second key */
321         if ((wrong_eckey = EC_KEY_new()) == NULL)
322             goto builtin_err;
323         group = EC_GROUP_new_by_curve_name(nid);
324         if (group == NULL)
325             goto builtin_err;
326         if (EC_KEY_set_group(wrong_eckey, group) == 0)
327             goto builtin_err;
328         EC_GROUP_free(group);
329         if (!EC_KEY_generate_key(wrong_eckey)) {
330             BIO_printf(out, " failed\n");
331             goto builtin_err;
332         }
333
334         BIO_printf(out, ".");
335         (void)BIO_flush(out);
336         /* check key */
337         if (!EC_KEY_check_key(eckey)) {
338             BIO_printf(out, " failed\n");
339             goto builtin_err;
340         }
341         BIO_printf(out, ".");
342         (void)BIO_flush(out);
343         /* create signature */
344         sig_len = ECDSA_size(eckey);
345         if ((signature = OPENSSL_malloc(sig_len)) == NULL)
346             goto builtin_err;
347         if (!ECDSA_sign(0, digest, 20, signature, &sig_len, eckey)) {
348             BIO_printf(out, " failed\n");
349             goto builtin_err;
350         }
351         BIO_printf(out, ".");
352         (void)BIO_flush(out);
353         /* verify signature */
354         if (ECDSA_verify(0, digest, 20, signature, sig_len, eckey) != 1) {
355             BIO_printf(out, " failed\n");
356             goto builtin_err;
357         }
358         BIO_printf(out, ".");
359         (void)BIO_flush(out);
360         /* verify signature with the wrong key */
361         if (ECDSA_verify(0, digest, 20, signature, sig_len, wrong_eckey) == 1) {
362             BIO_printf(out, " failed\n");
363             goto builtin_err;
364         }
365         BIO_printf(out, ".");
366         (void)BIO_flush(out);
367         /* wrong digest */
368         if (ECDSA_verify(0, wrong_digest, 20, signature, sig_len, eckey) == 1) {
369             BIO_printf(out, " failed\n");
370             goto builtin_err;
371         }
372         BIO_printf(out, ".");
373         (void)BIO_flush(out);
374         /* wrong length */
375         if (ECDSA_verify(0, digest, 20, signature, sig_len - 1, eckey) == 1) {
376             BIO_printf(out, " failed\n");
377             goto builtin_err;
378         }
379         BIO_printf(out, ".");
380         (void)BIO_flush(out);
381
382         /*
383          * Modify a single byte of the signature: to ensure we don't garble
384          * the ASN1 structure, we read the raw signature and modify a byte in
385          * one of the bignums directly.
386          */
387         sig_ptr = signature;
388         if ((ecdsa_sig = d2i_ECDSA_SIG(NULL, &sig_ptr, sig_len)) == NULL) {
389             BIO_printf(out, " failed\n");
390             goto builtin_err;
391         }
392
393         ECDSA_SIG_get0(ecdsa_sig, &sig_r, &sig_s);
394
395         /* Store the two BIGNUMs in raw_buf. */
396         r_len = BN_num_bytes(sig_r);
397         s_len = BN_num_bytes(sig_s);
398         bn_len = (degree + 7) / 8;
399         if ((r_len > bn_len) || (s_len > bn_len)) {
400             BIO_printf(out, " failed\n");
401             goto builtin_err;
402         }
403         buf_len = 2 * bn_len;
404         if ((raw_buf = OPENSSL_zalloc(buf_len)) == NULL)
405             goto builtin_err;
406         BN_bn2bin(sig_r, raw_buf + bn_len - r_len);
407         BN_bn2bin(sig_s, raw_buf + buf_len - s_len);
408
409         /* Modify a single byte in the buffer. */
410         offset = raw_buf[10] % buf_len;
411         dirt = raw_buf[11] ? raw_buf[11] : 1;
412         raw_buf[offset] ^= dirt;
413         /* Now read the BIGNUMs back in from raw_buf. */
414         modified_sig = ECDSA_SIG_new();
415         if (modified_sig == NULL)
416             goto builtin_err;
417         if (((modified_r = BN_bin2bn(raw_buf, bn_len, NULL)) == NULL)
418             || ((modified_s = BN_bin2bn(raw_buf + bn_len, bn_len, NULL)) == NULL)
419             || !ECDSA_SIG_set0(modified_sig, modified_r, modified_s)) {
420             BN_free(modified_r);
421             BN_free(modified_s);
422             goto builtin_err;
423         }
424         sig_ptr2 = signature;
425         sig_len = i2d_ECDSA_SIG(modified_sig, &sig_ptr2);
426         if (ECDSA_verify(0, digest, 20, signature, sig_len, eckey) == 1) {
427             BIO_printf(out, " failed\n");
428             goto builtin_err;
429         }
430         /*
431          * Sanity check: undo the modification and verify signature.
432          */
433         raw_buf[offset] ^= dirt;
434         if (((unmodified_r = BN_bin2bn(raw_buf, bn_len, NULL)) == NULL)
435             || ((unmodified_s = BN_bin2bn(raw_buf + bn_len, bn_len, NULL)) == NULL)
436             || !ECDSA_SIG_set0(modified_sig, unmodified_r, unmodified_s)) {
437             BN_free(unmodified_r);
438             BN_free(unmodified_s);
439             goto builtin_err;
440         }
441
442         sig_ptr2 = signature;
443         sig_len = i2d_ECDSA_SIG(modified_sig, &sig_ptr2);
444         if (ECDSA_verify(0, digest, 20, signature, sig_len, eckey) != 1) {
445             BIO_printf(out, " failed\n");
446             goto builtin_err;
447         }
448         BIO_printf(out, ".");
449         (void)BIO_flush(out);
450
451         BIO_printf(out, " ok\n");
452         /* cleanup */
453         /* clean bogus errors */
454         ERR_clear_error();
455         OPENSSL_free(signature);
456         signature = NULL;
457         EC_KEY_free(eckey);
458         eckey = NULL;
459         EC_KEY_free(wrong_eckey);
460         wrong_eckey = NULL;
461         ECDSA_SIG_free(ecdsa_sig);
462         ecdsa_sig = NULL;
463         ECDSA_SIG_free(modified_sig);
464         modified_sig = NULL;
465         OPENSSL_free(raw_buf);
466         raw_buf = NULL;
467     }
468
469     ret = 1;
470  builtin_err:
471     EC_KEY_free(eckey);
472     EC_KEY_free(wrong_eckey);
473     ECDSA_SIG_free(ecdsa_sig);
474     ECDSA_SIG_free(modified_sig);
475     OPENSSL_free(signature);
476     OPENSSL_free(raw_buf);
477     OPENSSL_free(curves);
478
479     return ret;
480 }
481
482 int main(void)
483 {
484     int ret = 1;
485     BIO *out;
486     char *p;
487
488     out = BIO_new_fp(stdout, BIO_NOCLOSE | BIO_FP_TEXT);
489
490     p = getenv("OPENSSL_DEBUG_MEMORY");
491     if (p != NULL && strcmp(p, "on") == 0)
492         CRYPTO_set_mem_debug(1);
493
494     /* initialize the prng */
495     RAND_seed(rnd_seed, sizeof(rnd_seed));
496
497     /* the tests */
498     if (!x9_62_tests(out))
499         goto err;
500     if (!test_builtin(out))
501         goto err;
502
503     ret = 0;
504  err:
505     if (ret)
506         BIO_printf(out, "\nECDSA test failed\n");
507     else
508         BIO_printf(out, "\nECDSA test passed\n");
509     if (ret)
510         ERR_print_errors(out);
511
512 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
513     if (CRYPTO_mem_leaks(out) <= 0)
514         ret = 1;
515 #endif
516     BIO_free(out);
517     return ret;
518 }
519 #endif