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 static const keymaster_ec_curve_t kEcCurves[] = {KM_EC_CURVE_P_224, KM_EC_CURVE_P_256,
33                                                  KM_EC_CURVE_P_384, KM_EC_CURVE_P_521};
34 
35 /**
36  * SharedKey just tests that the basic key exchange identity holds: that both
37  * parties end up with the same key.
38  */
TEST(NistCurveKeyExchange,SharedKey)39 TEST(NistCurveKeyExchange, SharedKey) {
40     for (auto& curve : kEcCurves) {
41         AuthorizationSet kex_description(
42             AuthorizationSetBuilder().Authorization(TAG_EC_CURVE, curve));
43         for (size_t j = 0; j < 5; j++) {
44             NistCurveKeyExchange* alice_keyex = NistCurveKeyExchange::GenerateKeyExchange(curve);
45             NistCurveKeyExchange* bob_keyex = NistCurveKeyExchange::GenerateKeyExchange(curve);
46 
47             ASSERT_TRUE(alice_keyex != nullptr);
48             ASSERT_TRUE(bob_keyex != nullptr);
49 
50             Buffer alice_public_value;
51             ASSERT_TRUE(alice_keyex->public_value(&alice_public_value));
52             Buffer bob_public_value;
53             ASSERT_TRUE(bob_keyex->public_value(&bob_public_value));
54 
55             Buffer alice_shared, bob_shared;
56             ASSERT_TRUE(alice_keyex->CalculateSharedKey(bob_public_value, &alice_shared));
57             ASSERT_TRUE(bob_keyex->CalculateSharedKey(alice_public_value, &bob_shared));
58             EXPECT_EQ(alice_shared.available_read(), bob_shared.available_read());
59             EXPECT_EQ(0, memcmp(alice_shared.peek_read(), bob_shared.peek_read(),
60                                 alice_shared.available_read()));
61         }
62     }
63 }
64 
65 /*
66  * This test tries a key agreement with a false public key (i.e. with
67  * a point not on the curve.)
68  * The expected result of such a protocol should be that the
69  * key agreement fails and returns an error.
70  */
71 static const char* kInvalidPublicKeys[] = {
72     "04"  // uncompressed public key
73     "deadbeef7f56584c5cc632ca65640db91b6bacce3a4df6b42ce7cc838833d287"
74     "db71e509e3fd9b060ddb20ba5c51dcc5948d46fbf640dfe0441782cab85fa4ac",
75 };
76 
TEST(NistCurveKeyExchange,InvalidPublicKey)77 TEST(NistCurveKeyExchange, InvalidPublicKey) {
78     for (auto& curve : kEcCurves) {
79         AuthorizationSet kex_description(
80             AuthorizationSetBuilder().Authorization(TAG_EC_CURVE, curve));
81         KeyExchange* key_exchange = NistCurveKeyExchange::GenerateKeyExchange(curve);
82         ASSERT_TRUE(key_exchange != nullptr);
83 
84         string peer_public_key = hex2str(kInvalidPublicKeys[0]);
85         Buffer computed_shared_secret;
86         ASSERT_FALSE(key_exchange->CalculateSharedKey(
87             reinterpret_cast<const uint8_t*>(peer_public_key.data()), peer_public_key.size(),
88             &computed_shared_secret));
89     }
90 }
91 
92 /**
93  * Test that key exchange fails when peer public key is the point at infinity.
94  */
TEST(NistCurveKeyExchange,TestInfinity)95 TEST(NistCurveKeyExchange, TestInfinity) {
96     for (auto& curve : kEcCurves) {
97         /* Obtain the point at infinity */
98         EC_GROUP* group = ec_get_group(curve);
99         EC_POINT* point_at_infinity = EC_POINT_new(group);
100         EC_POINT_set_to_infinity(group, point_at_infinity);
101         EXPECT_EQ(1, EC_POINT_is_on_curve(group, point_at_infinity, nullptr));
102         size_t field_len_in_bits;
103         ec_get_group_size(group, &field_len_in_bits);
104         size_t field_len = (field_len_in_bits + 7) / 8;
105         size_t public_key_len = (field_len * 2) + 1;
106         uint8_t* public_key = new uint8_t[public_key_len];
107         public_key_len = EC_POINT_point2oct(group, point_at_infinity, POINT_CONVERSION_UNCOMPRESSED,
108                                             public_key, public_key_len, nullptr /* ctx */);
109 
110         /* Perform the key exchange */
111         AuthorizationSet kex_description(
112             AuthorizationSetBuilder().Authorization(TAG_EC_CURVE, curve));
113         NistCurveKeyExchange* key_exchange = NistCurveKeyExchange::GenerateKeyExchange(curve);
114         ASSERT_TRUE(key_exchange != nullptr);
115         Buffer computed_shared_secret;
116         /* It should fail */
117         ASSERT_FALSE(key_exchange->CalculateSharedKey(reinterpret_cast<const uint8_t*>(public_key),
118                                                       public_key_len, &computed_shared_secret));
119 
120         /* Explicitly test that ECDH_compute_key fails when the public key is the point at infinity
121          */
122         UniquePtr<uint8_t[]> result(new uint8_t[field_len]);
123         EXPECT_EQ(-1 /* error */, ECDH_compute_key(result.get(), field_len, point_at_infinity,
124                                                    key_exchange->private_key(), nullptr /* kdf */));
125     }
126 }
127 
128 /* Test vectors for P-256, downloaded from NIST. */
129 struct NistCurveTest {
130     const keymaster_ec_curve_t curve;
131     const char* peer_public_key;
132     const char* my_private_key;
133     const char* shared_secret;
134 };
135 
136 static const NistCurveTest kNistCurveTests[] = {
137     {
138         KM_EC_CURVE_P_256,
139         "04"  // uncompressed public key
140         "700c48f77f56584c5cc632ca65640db91b6bacce3a4df6b42ce7cc838833d287"
141         "db71e509e3fd9b060ddb20ba5c51dcc5948d46fbf640dfe0441782cab85fa4ac",
142         // https://tools.ietf.org/html/rfc5915
143         "30770201010420"  // DER-encodeded EC private key header
144         "7d7dc5f71eb29ddaf80d6214632eeae03d9058af1fb6d22ed80badb62bc1a534"  // private key
145         "a00a06082a8648ce3d030107a144034200"  // DER-encoded curve OID,
146         "04"
147         "ead218590119e8876b29146ff89ca61770c4edbbf97d38ce385ed281d8a6b230"
148         "28af61281fd35e2fa7002523acc85a429cb06ee6648325389f59edfce1405141",
149         "46fc62106420ff012e54a434fbdd2d25ccc5852060561e68040dd7778997bd7b",
150     },
151     {
152         KM_EC_CURVE_P_256,
153         "04"
154         "809f04289c64348c01515eb03d5ce7ac1a8cb9498f5caa50197e58d43a86a7ae"
155         "b29d84e811197f25eba8f5194092cb6ff440e26d4421011372461f579271cda3",
156         // https://tools.ietf.org/html/rfc5915
157         "30770201010420"  // DER-encodeded EC private key header
158         "38f65d6dce47676044d58ce5139582d568f64bb16098d179dbab07741dd5caf5"  // private key
159         "a00a06082a8648ce3d030107a144034200"  // DER-encoded curve OID,
160         "04"
161         "119f2f047902782ab0c9e27a54aff5eb9b964829ca99c06b02ddba95b0a3f6d0"
162         "8f52b726664cac366fc98ac7a012b2682cbd962e5acb544671d41b9445704d1d",
163         "057d636096cb80b67a8c038c890e887d1adfa4195e9b3ce241c8a778c59cda67",
164     },
165     {
166         KM_EC_CURVE_P_256,
167         "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