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