1 /*
2  * Copyright 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <keymaster/km_openssl/nist_curve_key_exchange.h>
18 
19 #include <gtest/gtest.h>
20 #include <openssl/evp.h>
21 
22 #include <hardware/keymaster_defs.h>
23 #include <keymaster/android_keymaster_utils.h>
24 
25 #include "android_keymaster_test_utils.h"
26 
27 using std::string;
28 
29 namespace keymaster {
30 namespace test {
31 
32 StdoutLogger logger;
33 
34 static const keymaster_ec_curve_t kEcCurves[] = {KM_EC_CURVE_P_224, KM_EC_CURVE_P_256,
35                                                  KM_EC_CURVE_P_384, KM_EC_CURVE_P_521};
36 
37 /**
38  * SharedKey just tests that the basic key exchange identity holds: that both
39  * parties end up with the same key.
40  */
TEST(NistCurveKeyExchange,SharedKey)41 TEST(NistCurveKeyExchange, SharedKey) {
42     for (auto& curve : kEcCurves) {
43         AuthorizationSet kex_description(
44             AuthorizationSetBuilder().Authorization(TAG_EC_CURVE, curve));
45         for (size_t j = 0; j < 5; j++) {
46             NistCurveKeyExchange* alice_keyex = NistCurveKeyExchange::GenerateKeyExchange(curve);
47             NistCurveKeyExchange* bob_keyex = NistCurveKeyExchange::GenerateKeyExchange(curve);
48 
49             ASSERT_TRUE(alice_keyex != nullptr);
50             ASSERT_TRUE(bob_keyex != nullptr);
51 
52             Buffer alice_public_value;
53             ASSERT_TRUE(alice_keyex->public_value(&alice_public_value));
54             Buffer bob_public_value;
55             ASSERT_TRUE(bob_keyex->public_value(&bob_public_value));
56 
57             Buffer alice_shared, bob_shared;
58             ASSERT_TRUE(alice_keyex->CalculateSharedKey(bob_public_value, &alice_shared));
59             ASSERT_TRUE(bob_keyex->CalculateSharedKey(alice_public_value, &bob_shared));
60             EXPECT_EQ(alice_shared.available_read(), bob_shared.available_read());
61             EXPECT_EQ(0, memcmp(alice_shared.peek_read(), bob_shared.peek_read(),
62                                 alice_shared.available_read()));
63         }
64     }
65 }
66 
67 /*
68  * This test tries a key agreement with a false public key (i.e. with
69  * a point not on the curve.)
70  * The expected result of such a protocol should be that the
71  * key agreement fails and returns an error.
72 */
73 static const char* kInvalidPublicKeys[] = {
74     "04"  // uncompressed public key
75     "deadbeef7f56584c5cc632ca65640db91b6bacce3a4df6b42ce7cc838833d287"
76     "db71e509e3fd9b060ddb20ba5c51dcc5948d46fbf640dfe0441782cab85fa4ac",
77 };
78 
TEST(NistCurveKeyExchange,InvalidPublicKey)79 TEST(NistCurveKeyExchange, InvalidPublicKey) {
80     for (auto& curve : kEcCurves) {
81         AuthorizationSet kex_description(
82             AuthorizationSetBuilder().Authorization(TAG_EC_CURVE, curve));
83         KeyExchange* key_exchange = NistCurveKeyExchange::GenerateKeyExchange(curve);
84         ASSERT_TRUE(key_exchange != nullptr);
85 
86         string peer_public_key = hex2str(kInvalidPublicKeys[0]);
87         Buffer computed_shared_secret;
88         ASSERT_FALSE(key_exchange->CalculateSharedKey(
89             reinterpret_cast<const uint8_t*>(peer_public_key.data()), peer_public_key.size(),
90             &computed_shared_secret));
91     }
92 }
93 
94 /**
95  * Test that key exchange fails when peer public key is the point at infinity.
96  */
TEST(NistCurveKeyExchange,TestInfinity)97 TEST(NistCurveKeyExchange, TestInfinity) {
98     for (auto& curve : kEcCurves) {
99         /* Obtain the point at infinity */
100         EC_GROUP* group = ec_get_group(curve);
101         EC_POINT* point_at_infinity = EC_POINT_new(group);
102         EC_POINT_set_to_infinity(group, point_at_infinity);
103         EXPECT_EQ(1, EC_POINT_is_on_curve(group, point_at_infinity, nullptr));
104         size_t field_len_in_bits;
105         ec_get_group_size(group, &field_len_in_bits);
106         size_t field_len = (field_len_in_bits + 7) / 8;
107         size_t public_key_len = (field_len * 2) + 1;
108         uint8_t* public_key = new uint8_t[public_key_len];
109         public_key_len = EC_POINT_point2oct(group, point_at_infinity, POINT_CONVERSION_UNCOMPRESSED,
110                                             public_key, public_key_len, nullptr /* ctx */);
111 
112         /* Perform the key exchange */
113         AuthorizationSet kex_description(
114             AuthorizationSetBuilder().Authorization(TAG_EC_CURVE, curve));
115         NistCurveKeyExchange* key_exchange = NistCurveKeyExchange::GenerateKeyExchange(curve);
116         ASSERT_TRUE(key_exchange != nullptr);
117         Buffer computed_shared_secret;
118         /* It should fail */
119         ASSERT_FALSE(key_exchange->CalculateSharedKey(reinterpret_cast<const uint8_t*>(public_key),
120                                                       public_key_len, &computed_shared_secret));
121 
122         /* Explicitly test that ECDH_compute_key fails when the public key is the point at infinity
123          */
124         UniquePtr<uint8_t[]> result(new uint8_t[field_len]);
125         EXPECT_EQ(-1 /* error */, ECDH_compute_key(result.get(), field_len, point_at_infinity,
126                                                    key_exchange->private_key(), nullptr /* kdf */));
127     }
128 }
129 
130 /* Test vectors for P-256, downloaded from NIST. */
131 struct NistCurveTest {
132     const keymaster_ec_curve_t curve;
133     const char* peer_public_key;
134     const char* my_private_key;
135     const char* shared_secret;
136 };
137 
138 static const NistCurveTest kNistCurveTests[] = {
139     {
140         KM_EC_CURVE_P_256,
141         "04"  // uncompressed public key
142         "700c48f77f56584c5cc632ca65640db91b6bacce3a4df6b42ce7cc838833d287"
143         "db71e509e3fd9b060ddb20ba5c51dcc5948d46fbf640dfe0441782cab85fa4ac",
144         // https://tools.ietf.org/html/rfc5915
145         "30770201010420"  // DER-encodeded EC private key header
146         "7d7dc5f71eb29ddaf80d6214632eeae03d9058af1fb6d22ed80badb62bc1a534"  // private key
147         "a00a06082a8648ce3d030107a144034200"  // DER-encoded curve OID,
148         "04"
149         "ead218590119e8876b29146ff89ca61770c4edbbf97d38ce385ed281d8a6b230"
150         "28af61281fd35e2fa7002523acc85a429cb06ee6648325389f59edfce1405141",
151         "46fc62106420ff012e54a434fbdd2d25ccc5852060561e68040dd7778997bd7b",
152     },
153     {
154         KM_EC_CURVE_P_256, "04"
155                            "809f04289c64348c01515eb03d5ce7ac1a8cb9498f5caa50197e58d43a86a7ae"
156                            "b29d84e811197f25eba8f5194092cb6ff440e26d4421011372461f579271cda3",
157         // https://tools.ietf.org/html/rfc5915
158         "30770201010420"  // DER-encodeded EC private key header
159         "38f65d6dce47676044d58ce5139582d568f64bb16098d179dbab07741dd5caf5"  // private key
160         "a00a06082a8648ce3d030107a144034200"  // DER-encoded curve OID,
161         "04"
162         "119f2f047902782ab0c9e27a54aff5eb9b964829ca99c06b02ddba95b0a3f6d0"
163         "8f52b726664cac366fc98ac7a012b2682cbd962e5acb544671d41b9445704d1d",
164         "057d636096cb80b67a8c038c890e887d1adfa4195e9b3ce241c8a778c59cda67",
165     },
166     {
167         KM_EC_CURVE_P_256, "04"
168                            "df3989b9fa55495719b3cf46dccd28b5153f7808191dd518eff0c3cff2b705ed"
169                            "422294ff46003429d739a33206c8752552c8ba54a270defc06e221e0feaf6ac4",
170         // https://tools.ietf.org/html/rfc5915
171         "30770201010420"  // DER-encodeded EC private key header
172         "207c43a79bfee03db6f4b944f53d2fb76cc49ef1c9c4d34d51b6c65c4db6932d"  // private key
173         "a00a06082a8648ce3d030107a144034200"  // DER-encoded curve OID,
174         "04"
175         "24277c33f450462dcb3d4801d57b9ced05188f16c28eda873258048cd1607e0d"
176         "c4789753e2b1f63b32ff014ec42cd6a69fac81dfe6d0d6fd4af372ae27c46f88",
177         "96441259534b80f6aee3d287a6bb17b5094dd4277d9e294f8fe73e48bf2a0024",
178     },
179 };
180 
181 /**
182  * Test that key exchange works with NIST test vectors.
183  */
TEST(NistCurveKeyExchange,NistTestVectors)184 TEST(NistCurveKeyExchange, NistTestVectors) {
185     for (auto& test : kNistCurveTests) {
186         string private_key = hex2str(test.my_private_key);
187         string shared_secret = hex2str(test.shared_secret);
188 
189         const uint8_t* private_key_data = reinterpret_cast<const uint8_t*>(private_key.data());
190         UniquePtr<EC_KEY, EC_KEY_Delete> ec_key(
191             d2i_ECPrivateKey(nullptr, &private_key_data, private_key.size()));
192         ASSERT_TRUE(ec_key.get() && EC_KEY_check_key(ec_key.get()));
193 
194         keymaster_error_t error;
195         NistCurveKeyExchange* key_exchange = new NistCurveKeyExchange(ec_key.release(), &error);
196         EXPECT_EQ(KM_ERROR_OK, error);
197         ASSERT_TRUE(key_exchange != nullptr);
198 
199         Buffer computed_shared_secret;
200         string peer_public_key = hex2str(test.peer_public_key);
201         ASSERT_TRUE(key_exchange->CalculateSharedKey(
202             reinterpret_cast<const uint8_t*>(peer_public_key.data()), peer_public_key.size(),
203             &computed_shared_secret));
204         EXPECT_EQ(shared_secret.size(), computed_shared_secret.available_read());
205         EXPECT_EQ(0, memcmp(shared_secret.data(), computed_shared_secret.peek_read(),
206                             shared_secret.size()));
207 
208         for (size_t i = 0; i < peer_public_key.size(); i++) {
209             // randomly flip some bits in the peer public key to make it invalid
210             peer_public_key[i] ^= 0xff;
211             ASSERT_FALSE(key_exchange->CalculateSharedKey(
212                 reinterpret_cast<const uint8_t*>(peer_public_key.data()), peer_public_key.size(),
213                 &computed_shared_secret));
214         }
215     }
216 }
217 
218 }  // namespace test
219 }  // namespace keymaster
220