1/*
2 * Copyright 2017-2021 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#include <stdio.h>
11#include <stdlib.h>
12#include <string.h>
13
14#include <openssl/bio.h>
15#include <openssl/evp.h>
16#include <openssl/bn.h>
17#include <openssl/crypto.h>
18#include <openssl/err.h>
19#include <openssl/rand.h>
20#include "testutil.h"
21
22#ifndef OPENSSL_NO_SM2
23
24# include "crypto/sm2.h"
25
26static RAND_METHOD fake_rand;
27static const RAND_METHOD *saved_rand;
28
29static uint8_t *fake_rand_bytes = NULL;
30static size_t fake_rand_bytes_offset = 0;
31static size_t fake_rand_size = 0;
32
33static int get_faked_bytes(unsigned char *buf, int num)
34{
35    if (fake_rand_bytes == NULL)
36        return saved_rand->bytes(buf, num);
37
38    if (!TEST_size_t_gt(fake_rand_size, 0))
39        return 0;
40
41    while (num-- > 0) {
42        if (fake_rand_bytes_offset >= fake_rand_size)
43            fake_rand_bytes_offset = 0;
44        *buf++ = fake_rand_bytes[fake_rand_bytes_offset++];
45    }
46
47    return 1;
48}
49
50static int start_fake_rand(const char *hex_bytes)
51{
52    /* save old rand method */
53    if (!TEST_ptr(saved_rand = RAND_get_rand_method()))
54        return 0;
55
56    fake_rand = *saved_rand;
57    /* use own random function */
58    fake_rand.bytes = get_faked_bytes;
59
60    fake_rand_bytes = OPENSSL_hexstr2buf(hex_bytes, NULL);
61    fake_rand_bytes_offset = 0;
62    fake_rand_size = strlen(hex_bytes) / 2;
63
64    /* set new RAND_METHOD */
65    if (!TEST_true(RAND_set_rand_method(&fake_rand)))
66        return 0;
67    return 1;
68}
69
70static int restore_rand(void)
71{
72    OPENSSL_free(fake_rand_bytes);
73    fake_rand_bytes = NULL;
74    fake_rand_bytes_offset = 0;
75    if (!TEST_true(RAND_set_rand_method(saved_rand)))
76        return 0;
77    return 1;
78}
79
80static EC_GROUP *create_EC_group(const char *p_hex, const char *a_hex,
81                                 const char *b_hex, const char *x_hex,
82                                 const char *y_hex, const char *order_hex,
83                                 const char *cof_hex)
84{
85    BIGNUM *p = NULL;
86    BIGNUM *a = NULL;
87    BIGNUM *b = NULL;
88    BIGNUM *g_x = NULL;
89    BIGNUM *g_y = NULL;
90    BIGNUM *order = NULL;
91    BIGNUM *cof = NULL;
92    EC_POINT *generator = NULL;
93    EC_GROUP *group = NULL;
94    int ok = 0;
95
96    if (!TEST_true(BN_hex2bn(&p, p_hex))
97            || !TEST_true(BN_hex2bn(&a, a_hex))
98            || !TEST_true(BN_hex2bn(&b, b_hex)))
99        goto done;
100
101    group = EC_GROUP_new_curve_GFp(p, a, b, NULL);
102    if (!TEST_ptr(group))
103        goto done;
104
105    generator = EC_POINT_new(group);
106    if (!TEST_ptr(generator))
107        goto done;
108
109    if (!TEST_true(BN_hex2bn(&g_x, x_hex))
110            || !TEST_true(BN_hex2bn(&g_y, y_hex))
111            || !TEST_true(EC_POINT_set_affine_coordinates(group, generator, g_x,
112                                                          g_y, NULL)))
113        goto done;
114
115    if (!TEST_true(BN_hex2bn(&order, order_hex))
116            || !TEST_true(BN_hex2bn(&cof, cof_hex))
117            || !TEST_true(EC_GROUP_set_generator(group, generator, order, cof)))
118        goto done;
119
120    ok = 1;
121done:
122    BN_free(p);
123    BN_free(a);
124    BN_free(b);
125    BN_free(g_x);
126    BN_free(g_y);
127    EC_POINT_free(generator);
128    BN_free(order);
129    BN_free(cof);
130    if (!ok) {
131        EC_GROUP_free(group);
132        group = NULL;
133    }
134
135    return group;
136}
137
138static int test_sm2_crypt(const EC_GROUP *group,
139                          const EVP_MD *digest,
140                          const char *privkey_hex,
141                          const char *message,
142                          const char *k_hex, const char *ctext_hex)
143{
144    const size_t msg_len = strlen(message);
145    BIGNUM *priv = NULL;
146    EC_KEY *key = NULL;
147    EC_POINT *pt = NULL;
148    unsigned char *expected = OPENSSL_hexstr2buf(ctext_hex, NULL);
149    size_t ctext_len = 0;
150    size_t ptext_len = 0;
151    uint8_t *ctext = NULL;
152    uint8_t *recovered = NULL;
153    size_t recovered_len = msg_len;
154    int rc = 0;
155
156    if (!TEST_ptr(expected)
157            || !TEST_true(BN_hex2bn(&priv, privkey_hex)))
158        goto done;
159
160    key = EC_KEY_new();
161    if (!TEST_ptr(key)
162            || !TEST_true(EC_KEY_set_group(key, group))
163            || !TEST_true(EC_KEY_set_private_key(key, priv)))
164        goto done;
165
166    pt = EC_POINT_new(group);
167    if (!TEST_ptr(pt)
168            || !TEST_true(EC_POINT_mul(group, pt, priv, NULL, NULL, NULL))
169            || !TEST_true(EC_KEY_set_public_key(key, pt))
170            || !TEST_true(sm2_ciphertext_size(key, digest, msg_len, &ctext_len)))
171        goto done;
172
173    ctext = OPENSSL_zalloc(ctext_len);
174    if (!TEST_ptr(ctext))
175        goto done;
176
177    start_fake_rand(k_hex);
178    if (!TEST_true(sm2_encrypt(key, digest, (const uint8_t *)message, msg_len,
179                               ctext, &ctext_len))) {
180        restore_rand();
181        goto done;
182    }
183    restore_rand();
184
185    if (!TEST_mem_eq(ctext, ctext_len, expected, ctext_len))
186        goto done;
187
188    if (!TEST_true(sm2_plaintext_size(ctext, ctext_len, &ptext_len))
189            || !TEST_int_eq(ptext_len, msg_len))
190        goto done;
191
192    recovered = OPENSSL_zalloc(ptext_len);
193    if (!TEST_ptr(recovered)
194            || !TEST_true(sm2_decrypt(key, digest, ctext, ctext_len, recovered, &recovered_len))
195            || !TEST_int_eq(recovered_len, msg_len)
196            || !TEST_mem_eq(recovered, recovered_len, message, msg_len))
197        goto done;
198
199    rc = 1;
200 done:
201    BN_free(priv);
202    EC_POINT_free(pt);
203    OPENSSL_free(ctext);
204    OPENSSL_free(recovered);
205    OPENSSL_free(expected);
206    EC_KEY_free(key);
207    return rc;
208}
209
210static int sm2_crypt_test(void)
211{
212    int testresult = 0;
213    EC_GROUP *gm_group = NULL;
214    EC_GROUP *test_group =
215        create_EC_group
216        ("8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3",
217         "787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498",
218         "63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A",
219         "421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D",
220         "0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2",
221         "8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7",
222         "1");
223
224    if (!TEST_ptr(test_group))
225        goto done;
226
227    if (!test_sm2_crypt(
228            test_group,
229            EVP_sm3(),
230            "1649AB77A00637BD5E2EFE283FBF353534AA7F7CB89463F208DDBC2920BB0DA0",
231            "encryption standard",
232            "004C62EEFD6ECFC2B95B92FD6C3D9575148AFA17425546D49018E5388D49DD7B4F"
233            "0092e8ff62146873c258557548500ab2df2a365e0609ab67640a1f6d57d7b17820"
234            "008349312695a3e1d2f46905f39a766487f2432e95d6be0cb009fe8c69fd8825a7",
235            "307B0220245C26FB68B1DDDDB12C4B6BF9F2B6D5FE60A383B0D18D1C4144ABF1"
236            "7F6252E7022076CB9264C2A7E88E52B19903FDC47378F605E36811F5C07423A2"
237            "4B84400F01B804209C3D7360C30156FAB7C80A0276712DA9D8094A634B766D3A"
238            "285E07480653426D0413650053A89B41C418B0C3AAD00D886C00286467"))
239        goto done;
240
241    /* Same test as above except using SHA-256 instead of SM3 */
242    if (!test_sm2_crypt(
243            test_group,
244            EVP_sha256(),
245            "1649AB77A00637BD5E2EFE283FBF353534AA7F7CB89463F208DDBC2920BB0DA0",
246            "encryption standard",
247            "004C62EEFD6ECFC2B95B92FD6C3D9575148AFA17425546D49018E5388D49DD7B4F"
248            "003da18008784352192d70f22c26c243174a447ba272fec64163dd4742bae8bc98"
249            "00df17605cf304e9dd1dfeb90c015e93b393a6f046792f790a6fa4228af67d9588",
250            "307B0220245C26FB68B1DDDDB12C4B6BF9F2B6D5FE60A383B0D18D1C4144ABF17F"
251            "6252E7022076CB9264C2A7E88E52B19903FDC47378F605E36811F5C07423A24B84"
252            "400F01B80420BE89139D07853100EFA763F60CBE30099EA3DF7F8F364F9D10A5E9"
253            "88E3C5AAFC0413229E6C9AEE2BB92CAD649FE2C035689785DA33"))
254        goto done;
255
256    /* From Annex C in both GM/T0003.5-2012 and GB/T 32918.5-2016.*/
257    gm_group = create_EC_group(
258         "fffffffeffffffffffffffffffffffffffffffff00000000ffffffffffffffff",
259         "fffffffeffffffffffffffffffffffffffffffff00000000fffffffffffffffc",
260         "28e9fa9e9d9f5e344d5a9e4bcf6509a7f39789f515ab8f92ddbcbd414d940e93",
261         "32c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7",
262         "bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0",
263         "fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123",
264         "1");
265
266    if (!TEST_ptr(gm_group))
267        goto done;
268
269    if (!test_sm2_crypt(
270            gm_group,
271            EVP_sm3(),
272            /* privkey (from which the encrypting public key is derived) */
273            "3945208F7B2144B13F36E38AC6D39F95889393692860B51A42FB81EF4DF7C5B8",
274            /* plaintext message */
275            "encryption standard",
276            /* ephemeral nonce k */
277            "59276E27D506861A16680F3AD9C02DCCEF3CC1FA3CDBE4CE6D54B80DEAC1BC21",
278            /*
279             * expected ciphertext, the field values are from GM/T 0003.5-2012
280             * (Annex C), but serialized following the ASN.1 format specified
281             * in GM/T 0009-2012 (Sec. 7.2).
282             */
283            "307C" /* SEQUENCE, 0x7c bytes */
284              "0220" /* INTEGER, 0x20 bytes */
285                "04EBFC718E8D1798620432268E77FEB6415E2EDE0E073C0F4F640ECD2E149A73"
286              "0221" /* INTEGER, 0x21 bytes */
287                "00" /* leading 00 due to DER for pos. int with topmost bit set */
288                "E858F9D81E5430A57B36DAAB8F950A3C64E6EE6A63094D99283AFF767E124DF0"
289              "0420" /* OCTET STRING, 0x20 bytes */
290                "59983C18F809E262923C53AEC295D30383B54E39D609D160AFCB1908D0BD8766"
291              "0413" /* OCTET STRING, 0x13 bytes */
292                "21886CA989CA9C7D58087307CA93092D651EFA"))
293        goto done;
294
295    testresult = 1;
296 done:
297    EC_GROUP_free(test_group);
298    EC_GROUP_free(gm_group);
299
300    return testresult;
301}
302
303static int test_sm2_sign(const EC_GROUP *group,
304                         const char *userid,
305                         const char *privkey_hex,
306                         const char *message,
307                         const char *k_hex,
308                         const char *r_hex,
309                         const char *s_hex)
310{
311    const size_t msg_len = strlen(message);
312    int ok = 0;
313    BIGNUM *priv = NULL;
314    EC_POINT *pt = NULL;
315    EC_KEY *key = NULL;
316    ECDSA_SIG *sig = NULL;
317    const BIGNUM *sig_r = NULL;
318    const BIGNUM *sig_s = NULL;
319    BIGNUM *r = NULL;
320    BIGNUM *s = NULL;
321
322    if (!TEST_true(BN_hex2bn(&priv, privkey_hex)))
323        goto done;
324
325    key = EC_KEY_new();
326    if (!TEST_ptr(key)
327            || !TEST_true(EC_KEY_set_group(key, group))
328            || !TEST_true(EC_KEY_set_private_key(key, priv)))
329        goto done;
330
331    pt = EC_POINT_new(group);
332    if (!TEST_ptr(pt)
333            || !TEST_true(EC_POINT_mul(group, pt, priv, NULL, NULL, NULL))
334            || !TEST_true(EC_KEY_set_public_key(key, pt)))
335        goto done;
336
337    start_fake_rand(k_hex);
338    sig = sm2_do_sign(key, EVP_sm3(), (const uint8_t *)userid, strlen(userid),
339                      (const uint8_t *)message, msg_len);
340    if (!TEST_ptr(sig)) {
341        restore_rand();
342        goto done;
343    }
344    restore_rand();
345
346    ECDSA_SIG_get0(sig, &sig_r, &sig_s);
347
348    if (!TEST_true(BN_hex2bn(&r, r_hex))
349            || !TEST_true(BN_hex2bn(&s, s_hex))
350            || !TEST_BN_eq(r, sig_r)
351            || !TEST_BN_eq(s, sig_s))
352        goto done;
353
354    ok = sm2_do_verify(key, EVP_sm3(), sig, (const uint8_t *)userid,
355                       strlen(userid), (const uint8_t *)message, msg_len);
356
357    /* We goto done whether this passes or fails */
358    TEST_true(ok);
359
360 done:
361    ECDSA_SIG_free(sig);
362    EC_POINT_free(pt);
363    EC_KEY_free(key);
364    BN_free(priv);
365    BN_free(r);
366    BN_free(s);
367
368    return ok;
369}
370
371static int sm2_sig_test(void)
372{
373    int testresult = 0;
374    /* From draft-shen-sm2-ecdsa-02 */
375    EC_GROUP *test_group =
376        create_EC_group
377        ("8542D69E4C044F18E8B92435BF6FF7DE457283915C45517D722EDB8B08F1DFC3",
378         "787968B4FA32C3FD2417842E73BBFEFF2F3C848B6831D7E0EC65228B3937E498",
379         "63E4C6D3B23B0C849CF84241484BFE48F61D59A5B16BA06E6E12D1DA27C5249A",
380         "421DEBD61B62EAB6746434EBC3CC315E32220B3BADD50BDC4C4E6C147FEDD43D",
381         "0680512BCBB42C07D47349D2153B70C4E5D7FDFCBFA36EA1A85841B9E46E09A2",
382         "8542D69E4C044F18E8B92435BF6FF7DD297720630485628D5AE74EE7C32E79B7",
383         "1");
384
385    if (!TEST_ptr(test_group))
386        goto done;
387
388    if (!TEST_true(test_sm2_sign(
389                        test_group,
390                        "ALICE123@YAHOO.COM",
391                        "128B2FA8BD433C6C068C8D803DFF79792A519A55171B1B650C23661D15897263",
392                        "message digest",
393                        "006CB28D99385C175C94F94E934817663FC176D925DD72B727260DBAAE1FB2F96F"
394                        "007c47811054c6f99613a578eb8453706ccb96384fe7df5c171671e760bfa8be3a",
395                        "40F1EC59F793D9F49E09DCEF49130D4194F79FB1EED2CAA55BACDB49C4E755D1",
396                        "6FC6DAC32C5D5CF10C77DFB20F7C2EB667A457872FB09EC56327A67EC7DEEBE7")))
397        goto done;
398
399    testresult = 1;
400
401 done:
402    EC_GROUP_free(test_group);
403
404    return testresult;
405}
406
407#endif
408
409int setup_tests(void)
410{
411#ifdef OPENSSL_NO_SM2
412    TEST_note("SM2 is disabled.");
413#else
414    ADD_TEST(sm2_crypt_test);
415    ADD_TEST(sm2_sig_test);
416#endif
417    return 1;
418}
419