blob: a89cc5bb2161b008d7858b786e899a33affc61d6 [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 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
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
21#include <iostream>
22
David Zeuthene0c40892021-01-08 12:54:11 -050023#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070024#include <openssl/evp.h>
25#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027
28#include <cutils/properties.h>
29
David Drysdale4dc01072021-04-01 12:17:35 +010030#include <android/binder_manager.h>
31
32#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080033#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070034
Shawn Willden08a7e432020-12-11 13:05:27 +000035#include <keymint_support/key_param_output.h>
36#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
38#include "KeyMintAidlTestBase.h"
39
Janis Danisevskis24c04702020-12-16 18:28:39 -080040using aidl::android::hardware::security::keymint::AuthorizationSet;
41using aidl::android::hardware::security::keymint::KeyCharacteristics;
42using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070043
Selene Huang31ab4042020-04-29 04:22:39 -070044namespace std {
45
Janis Danisevskis24c04702020-12-16 18:28:39 -080046using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070047
48template <>
49struct std::equal_to<KeyCharacteristics> {
50 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070051 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070052
Shawn Willden7f424372021-01-10 18:06:50 -070053 // this isn't very efficient. Oh, well.
54 AuthorizationSet a_auths(a.authorizations);
55 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070056
Shawn Willden7f424372021-01-10 18:06:50 -070057 a_auths.Sort();
58 b_auths.Sort();
59
60 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070061 }
62};
63
64} // namespace std
65
Janis Danisevskis24c04702020-12-16 18:28:39 -080066namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000067
Selene Huang31ab4042020-04-29 04:22:39 -070068namespace {
69
70template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000071bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
72 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070073 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080074 if (auto p = authorizationValue(ttag, param)) {
75 return *p == expected_value;
76 }
77 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070078 });
79 return (it != set.end());
80}
81
82template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000083bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070084 auto it = std::find_if(set.begin(), set.end(),
85 [&](const KeyParameter& param) { return param.tag == tag; });
86 return (it != set.end());
87}
88
89constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
90 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
91 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
92 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
93 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
94 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
95 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
96 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
97 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
98 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
99 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
100 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
101 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
102 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
103 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
105
106string hex2str(string a) {
107 string b;
108 size_t num = a.size() / 2;
109 b.resize(num);
110 for (size_t i = 0; i < num; i++) {
111 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
112 }
113 return b;
114}
115
116string rsa_key =
117 hex2str("30820275020100300d06092a864886f70d01010105000482025f3082025b"
118 "02010002818100c6095409047d8634812d5a218176e45c41d60a75b13901"
119 "f234226cffe776521c5a77b9e389417b71c0b6a44d13afe4e4a2805d46c9"
120 "da2935adb1ff0c1f24ea06e62b20d776430a4d435157233c6f916783c30e"
121 "310fcbd89b85c2d56771169785ac12bca244abda72bfb19fc44d27c81e1d"
122 "92de284f4061edfd99280745ea6d2502030100010281801be0f04d9cae37"
123 "18691f035338308e91564b55899ffb5084d2460e6630257e05b3ceab0297"
124 "2dfabcd6ce5f6ee2589eb67911ed0fac16e43a444b8c861e544a05933657"
125 "72f8baf6b22fc9e3c5f1024b063ac080a7b2234cf8aee8f6c47bbf4fd3ac"
126 "e7240290bef16c0b3f7f3cdd64ce3ab5912cf6e32f39ab188358afcccd80"
127 "81024100e4b49ef50f765d3b24dde01aceaaf130f2c76670a91a61ae08af"
128 "497b4a82be6dee8fcdd5e3f7ba1cfb1f0c926b88f88c92bfab137fba2285"
129 "227b83c342ff7c55024100ddabb5839c4c7f6bf3d4183231f005b31aa58a"
130 "ffdda5c79e4cce217f6bc930dbe563d480706c24e9ebfcab28a6cdefd324"
131 "b77e1bf7251b709092c24ff501fd91024023d4340eda3445d8cd26c14411"
132 "da6fdca63c1ccd4b80a98ad52b78cc8ad8beb2842c1d280405bc2f6c1bea"
133 "214a1d742ab996b35b63a82a5e470fa88dbf823cdd02401b7b57449ad30d"
134 "1518249a5f56bb98294d4b6ac12ffc86940497a5a5837a6cf946262b4945"
135 "26d328c11e1126380fde04c24f916dec250892db09a6d77cdba351024077"
136 "62cd8f4d050da56bd591adb515d24d7ccd32cca0d05f866d583514bd7324"
137 "d5f33645e8ed8b4a1cb3cc4a1d67987399f2a09f5b3fb68c88d5e5d90ac3"
138 "3492d6");
139
Selene Huange5727e62021-04-13 22:41:20 -0700140/*
141 * DER-encoded PKCS#8 format RSA key. Generated using:
142 *
143 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
144 */
145string rsa_2048_key =
146 hex2str("308204BD020100300D06092A864886F70D0101010500048204A7308204A3"
147 "0201000282010100BEBC342B56D443B1299F9A6A7056E80A897E318476A5"
148 "A18029E63B2ED739A61791D339F58DC763D9D14911F2EDEC383DEE11F631"
149 "9B44510E7A3ECD9B79B97382E49500ACF8117DC89CAF0E621F77756554A2"
150 "FD4664BFE7AB8B59AB48340DBFA27B93B5A81F6ECDEB02D0759307128DF3"
151 "E3BAD4055C8B840216DFAA5700670E6C5126F0962FCB70FF308F25049164"
152 "CCF76CC2DA66A7DD9A81A714C2809D69186133D29D84568E892B6FFBF319"
153 "9BDB14383EE224407F190358F111A949552ABA6714227D1BD7F6B20DD0CB"
154 "88F9467B719339F33BFF35B3870B3F62204E4286B0948EA348B524544B5F"
155 "9838F29EE643B079EEF8A713B220D7806924CDF7295070C5020301000102"
156 "82010069F377F35F2F584EF075353CCD1CA99738DB3DBC7C7FF35F9366CE"
157 "176DFD1B135AB10030344ABF5FBECF1D4659FDEF1C0FC430834BE1BE3911"
158 "951377BB3D563A2EA9CA8F4AD9C48A8CE6FD516A735C662686C7B4B3C09A"
159 "7B8354133E6F93F790D59EAEB92E84C9A4339302CCE28FDF04CCCAFA7DE3"
160 "F3A827D4F6F7D38E68B0EC6AB706645BF074A4E4090D06FB163124365FD5"
161 "EE7A20D350E9958CC30D91326E1B292E9EF5DB408EC42DAF737D20149704"
162 "D0A678A0FB5B5446863B099228A352D604BA8091A164D01D5AB05397C71E"
163 "AD20BE2A08FC528FE442817809C787FEE4AB97F97B9130D022153EDC6EB6"
164 "CBE7B0F8E3473F2E901209B5DB10F93604DB0102818100E83C0998214941"
165 "EA4F9293F1B77E2E99E6CF305FAF358238E126124FEAF2EB9724B2EA7B78"
166 "E6032343821A80E55D1D88FB12D220C3F41A56142FEC85796D1917F1E8C7"
167 "74F142B67D3D6E7B7E6B4383E94DB5929089DBB346D5BDAB40CC2D96EE04"
168 "09475E175C63BF78CFD744136740838127EA723FF3FE7FA368C1311B4A4E"
169 "0502818100D240FCC0F5D7715CDE21CB2DC86EA146132EA3B06F61FF2AF5"
170 "4BF38473F59DADCCE32B5F4CC32DD0BA6F509347B4B5B1B58C39F95E4798"
171 "CCBB43E83D0119ACF532F359CA743C85199F0286610E200997D731291717"
172 "9AC9B67558773212EC961E8BCE7A3CC809BC5486A96E4B0E6AF394D94E06"
173 "6A0900B7B70E82A44FB30053C102818100AD15DA1CBD6A492B66851BA8C3"
174 "16D38AB700E2CFDDD926A658003513C54BAA152B30021D667D20078F500F"
175 "8AD3E7F3945D74A891ED1A28EAD0FEEAEC8C14A8E834CF46A13D1378C99D"
176 "18940823CFDD27EC5810D59339E0C34198AC638E09C87CBB1B634A9864AE"
177 "9F4D5EB2D53514F67B4CAEC048C8AB849A02E397618F3271350281801FA2"
178 "C1A5331880A92D8F3E281C617108BF38244F16E352E69ED417C7153F9EC3"
179 "18F211839C643DCF8B4DD67CE2AC312E95178D5D952F06B1BF779F491692"
180 "4B70F582A23F11304E02A5E7565AE22A35E74FECC8B6FDC93F92A1A37703"
181 "E4CF0E63783BD02EB716A7ECBBFA606B10B74D01579522E7EF84D91FC522"
182 "292108D902C1028180796FE3825F9DCC85DF22D58690065D93898ACD65C0"
183 "87BEA8DA3A63BF4549B795E2CD0E3BE08CDEBD9FCF1720D9CDC5070D74F4"
184 "0DED8E1102C52152A31B6165F83A6722AECFCC35A493D7634664B888A08D"
185 "3EB034F12EA28BFEE346E205D334827F778B16ED40872BD29FCB36536B6E"
186 "93FFB06778696B4A9D81BB0A9423E63DE5");
187
Selene Huang31ab4042020-04-29 04:22:39 -0700188string ec_256_key =
189 hex2str("308187020100301306072a8648ce3d020106082a8648ce3d030107046d30"
190 "6b0201010420737c2ecd7b8d1940bf2930aa9b4ed3ff941eed09366bc032"
191 "99986481f3a4d859a14403420004bf85d7720d07c25461683bc648b4778a"
192 "9a14dd8a024e3bdd8c7ddd9ab2b528bbc7aa1b51f14ebbbb0bd0ce21bcc4"
193 "1c6eb00083cf3376d11fd44949e0b2183bfe");
194
195string ec_521_key =
196 hex2str("3081EE020100301006072A8648CE3D020106052B810400230481D63081D3"
197 "02010104420011458C586DB5DAA92AFAB03F4FE46AA9D9C3CE9A9B7A006A"
198 "8384BEC4C78E8E9D18D7D08B5BCFA0E53C75B064AD51C449BAE0258D54B9"
199 "4B1E885DED08ED4FB25CE9A1818903818600040149EC11C6DF0FA122C6A9"
200 "AFD9754A4FA9513A627CA329E349535A5629875A8ADFBE27DCB932C05198"
201 "6377108D054C28C6F39B6F2C9AF81802F9F326B842FF2E5F3C00AB7635CF"
202 "B36157FC0882D574A10D839C1A0C049DC5E0D775E2EE50671A208431BB45"
203 "E78E70BEFE930DB34818EE4D5C26259F5C6B8E28A652950F9F88D7B4B2C9"
204 "D9");
205
206string ec_256_key_rfc5915 =
207 hex2str("308193020100301306072a8648ce3d020106082a8648ce3d030107047930"
208 "770201010420782370a8c8ce5537baadd04dcff079c8158cfa9c67b818b3"
209 "8e8d21c9fa750c1da00a06082a8648ce3d030107a14403420004e2cc561e"
210 "e701da0ad0ef0d176bb0c919d42e79c393fdc1bd6c4010d85cf2cf8e68c9"
211 "05464666f98dad4f01573ba81078b3428570a439ba3229fbc026c550682f");
212
213string ec_256_key_sec1 =
214 hex2str("308187020100301306072a8648ce3d020106082a8648ce3d030107046d30"
215 "6b0201010420782370a8c8ce5537baadd04dcff079c8158cfa9c67b818b3"
216 "8e8d21c9fa750c1da14403420004e2cc561ee701da0ad0ef0d176bb0c919"
217 "d42e79c393fdc1bd6c4010d85cf2cf8e68c905464666f98dad4f01573ba8"
218 "1078b3428570a439ba3229fbc026c550682f");
219
220struct RSA_Delete {
221 void operator()(RSA* p) { RSA_free(p); }
222};
223
Selene Huang31ab4042020-04-29 04:22:39 -0700224std::string make_string(const uint8_t* data, size_t length) {
225 return std::string(reinterpret_cast<const char*>(data), length);
226}
227
228template <size_t N>
229std::string make_string(const uint8_t (&a)[N]) {
230 return make_string(a, N);
231}
232
233class AidlBuf : public vector<uint8_t> {
234 typedef vector<uint8_t> super;
235
236 public:
237 AidlBuf() {}
238 AidlBuf(const super& other) : super(other) {}
239 AidlBuf(super&& other) : super(std::move(other)) {}
240 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
241
242 AidlBuf& operator=(const super& other) {
243 super::operator=(other);
244 return *this;
245 }
246
247 AidlBuf& operator=(super&& other) {
248 super::operator=(std::move(other));
249 return *this;
250 }
251
252 AidlBuf& operator=(const string& other) {
253 resize(other.size());
254 for (size_t i = 0; i < other.size(); ++i) {
255 (*this)[i] = static_cast<uint8_t>(other[i]);
256 }
257 return *this;
258 }
259
260 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
261};
262
David Drysdale4dc01072021-04-01 12:17:35 +0100263string device_suffix(const string& name) {
264 size_t pos = name.find('/');
265 if (pos == string::npos) {
266 return name;
267 }
268 return name.substr(pos + 1);
269}
270
271bool matching_rp_instance(const string& km_name,
272 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
273 string km_suffix = device_suffix(km_name);
274
275 vector<string> rp_names =
276 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
277 for (const string& rp_name : rp_names) {
278 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
279 // KeyMint instance, assume they match.
280 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
281 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
282 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
283 return true;
284 }
285 }
286 return false;
287}
288
Selene Huang31ab4042020-04-29 04:22:39 -0700289} // namespace
290
291class NewKeyGenerationTest : public KeyMintAidlTestBase {
292 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700293 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Selene Huang31ab4042020-04-29 04:22:39 -0700294 // TODO(swillden): Distinguish which params should be in which auth list.
295
Shawn Willden7f424372021-01-10 18:06:50 -0700296 AuthorizationSet auths;
297 for (auto& entry : keyCharacteristics) {
298 auths.push_back(AuthorizationSet(entry.authorizations));
299 }
Selene Huang31ab4042020-04-29 04:22:39 -0700300
301 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
302 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
303 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
304
Shawn Willden7f424372021-01-10 18:06:50 -0700305 // Verify that App data and ROT are NOT included.
Selene Huang31ab4042020-04-29 04:22:39 -0700306 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
Selene Huang31ab4042020-04-29 04:22:39 -0700307 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
308
309 // Check that some unexpected tags/values are NOT present.
310 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
311 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
312 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
313
Shawn Willden7f424372021-01-10 18:06:50 -0700314 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
315 ASSERT_TRUE(os_ver);
316 EXPECT_EQ(*os_ver, os_version());
Selene Huang31ab4042020-04-29 04:22:39 -0700317
Shawn Willden7f424372021-01-10 18:06:50 -0700318 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
319 ASSERT_TRUE(os_pl);
320 EXPECT_EQ(*os_pl, os_patch_level());
Selene Huang31ab4042020-04-29 04:22:39 -0700321 }
322};
323
324/*
325 * NewKeyGenerationTest.Rsa
326 *
327 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
328 * have correct characteristics.
329 */
330TEST_P(NewKeyGenerationTest, Rsa) {
331 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
332 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700333 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700334 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
335 .RsaSigningKey(key_size, 65537)
336 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800337 .Padding(PaddingMode::NONE)
338 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700339 &key_blob, &key_characteristics));
340
341 ASSERT_GT(key_blob.size(), 0U);
342 CheckBaseParams(key_characteristics);
343
Shawn Willden7f424372021-01-10 18:06:50 -0700344 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700345
346 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
347 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
348 << "Key size " << key_size << "missing";
349 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
350
351 CheckedDeleteKey(&key_blob);
352 }
353}
354
355/*
Qi Wud22ec842020-11-26 13:27:53 +0800356 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700357 *
358 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
359 * have correct characteristics.
360 */
361TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700362 auto challenge = "hello";
363 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700364
Selene Huang6e46f142021-04-20 19:20:11 -0700365 auto subject = "cert subj 2";
366 vector<uint8_t> subject_der(make_name_from_str(subject));
367
368 uint64_t serial_int = 66;
369 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
370
Selene Huang4f64c222021-04-13 19:54:36 -0700371 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700372 vector<uint8_t> key_blob;
373 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700374 ASSERT_EQ(ErrorCode::OK,
375 GenerateKey(AuthorizationSetBuilder()
376 .RsaSigningKey(key_size, 65537)
377 .Digest(Digest::NONE)
378 .Padding(PaddingMode::NONE)
379 .AttestationChallenge(challenge)
380 .AttestationApplicationId(app_id)
381 .Authorization(TAG_NO_AUTH_REQUIRED)
382 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
383 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
384 .SetDefaultValidity(),
385 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700386
387 ASSERT_GT(key_blob.size(), 0U);
388 CheckBaseParams(key_characteristics);
389
390 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
391
392 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
393 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
394 << "Key size " << key_size << "missing";
395 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
396
Selene Huang6e46f142021-04-20 19:20:11 -0700397 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700398 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700399 ASSERT_GT(cert_chain_.size(), 0);
400
401 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
402 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
403 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
404 sw_enforced, hw_enforced, SecLevel(),
405 cert_chain_[0].encodedCertificate));
406
407 CheckedDeleteKey(&key_blob);
408 }
409}
410
411/*
David Drysdale4dc01072021-04-01 12:17:35 +0100412 * NewKeyGenerationTest.RsaWithRpkAttestation
413 *
414 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
415 * that has been generated using an associate IRemotelyProvisionedComponent.
416 */
417TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
418 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
419 // instance.
420 std::shared_ptr<IRemotelyProvisionedComponent> rp;
421 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
422 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
423
424 // Generate a P-256 keypair to use as an attestation key.
425 MacedPublicKey macedPubKey;
426 std::vector<uint8_t> privateKeyBlob;
427 auto status =
428 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
429 ASSERT_TRUE(status.isOk());
430 vector<uint8_t> coseKeyData;
431 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
432
433 AttestationKey attestation_key;
434 attestation_key.keyBlob = std::move(privateKeyBlob);
435 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
436
437 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
438 auto challenge = "hello";
439 auto app_id = "foo";
440
441 vector<uint8_t> key_blob;
442 vector<KeyCharacteristics> key_characteristics;
443 ASSERT_EQ(ErrorCode::OK,
444 GenerateKey(AuthorizationSetBuilder()
445 .RsaSigningKey(key_size, 65537)
446 .Digest(Digest::NONE)
447 .Padding(PaddingMode::NONE)
448 .AttestationChallenge(challenge)
449 .AttestationApplicationId(app_id)
450 .Authorization(TAG_NO_AUTH_REQUIRED)
451 .SetDefaultValidity(),
452 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
453
454 ASSERT_GT(key_blob.size(), 0U);
455 CheckBaseParams(key_characteristics);
456
457 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
458
459 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
460 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
461 << "Key size " << key_size << "missing";
462 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
463
464 // Attestation by itself is not valid (last entry is not self-signed).
465 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
466
467 // The signature over the attested key should correspond to the P256 public key.
468 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
469 ASSERT_TRUE(key_cert.get());
470 EVP_PKEY_Ptr signing_pubkey;
471 p256_pub_key(coseKeyData, &signing_pubkey);
472 ASSERT_TRUE(signing_pubkey.get());
473
474 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
475 << "Verification of attested certificate failed "
476 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
477
478 CheckedDeleteKey(&key_blob);
479 }
480}
481
482/*
Selene Huang4f64c222021-04-13 19:54:36 -0700483 * NewKeyGenerationTest.RsaEncryptionWithAttestation
484 *
485 * Verifies that keymint attestation for RSA encryption keys with challenge and
486 * app id is also successful.
487 */
488TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
489 auto key_size = 2048;
490 auto challenge = "hello";
491 auto app_id = "foo";
492
Selene Huang6e46f142021-04-20 19:20:11 -0700493 auto subject = "subj 2";
494 vector<uint8_t> subject_der(make_name_from_str(subject));
495
496 uint64_t serial_int = 111166;
497 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
498
Selene Huang4f64c222021-04-13 19:54:36 -0700499 vector<uint8_t> key_blob;
500 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700501 ASSERT_EQ(ErrorCode::OK,
502 GenerateKey(AuthorizationSetBuilder()
503 .RsaEncryptionKey(key_size, 65537)
504 .Padding(PaddingMode::NONE)
505 .AttestationChallenge(challenge)
506 .AttestationApplicationId(app_id)
507 .Authorization(TAG_NO_AUTH_REQUIRED)
508 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
509 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
510 .SetDefaultValidity(),
511 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700512
513 ASSERT_GT(key_blob.size(), 0U);
514 AuthorizationSet auths;
515 for (auto& entry : key_characteristics) {
516 auths.push_back(AuthorizationSet(entry.authorizations));
517 }
518
519 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
520 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
521
522 // Verify that App data and ROT are NOT included.
523 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
524 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
525
526 // Check that some unexpected tags/values are NOT present.
527 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
528 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
529
530 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
531
532 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
533 ASSERT_TRUE(os_ver);
534 EXPECT_EQ(*os_ver, os_version());
535
536 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
537
538 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
539 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
540 << "Key size " << key_size << "missing";
541 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
542
Selene Huang6e46f142021-04-20 19:20:11 -0700543 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700544 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
545 ASSERT_GT(cert_chain_.size(), 0);
546
547 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
548 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
549 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
550 sw_enforced, hw_enforced, SecLevel(),
551 cert_chain_[0].encodedCertificate));
552
553 CheckedDeleteKey(&key_blob);
554}
555
556/*
557 * NewKeyGenerationTest.RsaWithSelfSign
558 *
559 * Verifies that attesting to RSA key generation is successful, and returns
560 * self signed certificate if no challenge is provided. And signing etc
561 * works as expected.
562 */
563TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -0700564 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
565 vector<uint8_t> subject_der(make_name_from_str(subject));
566
567 uint64_t serial_int = 0;
568 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
569
Selene Huang4f64c222021-04-13 19:54:36 -0700570 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
571 vector<uint8_t> key_blob;
572 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700573 ASSERT_EQ(ErrorCode::OK,
574 GenerateKey(AuthorizationSetBuilder()
575 .RsaSigningKey(key_size, 65537)
576 .Digest(Digest::NONE)
577 .Padding(PaddingMode::NONE)
578 .Authorization(TAG_NO_AUTH_REQUIRED)
579 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
580 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
581 .SetDefaultValidity(),
582 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700583
584 ASSERT_GT(key_blob.size(), 0U);
585 CheckBaseParams(key_characteristics);
586
587 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
588
589 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
590 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
591 << "Key size " << key_size << "missing";
592 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
593
Selene Huang6e46f142021-04-20 19:20:11 -0700594 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700595 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
596 ASSERT_EQ(cert_chain_.size(), 1);
597
598 CheckedDeleteKey(&key_blob);
599 }
600}
601
602/*
603 * NewKeyGenerationTest.RsaWithAttestationMissAppId
604 *
605 * Verifies that attesting to RSA checks for missing app ID.
606 */
607TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
608 auto challenge = "hello";
609 vector<uint8_t> key_blob;
610 vector<KeyCharacteristics> key_characteristics;
611
612 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
613 GenerateKey(AuthorizationSetBuilder()
614 .RsaSigningKey(2048, 65537)
615 .Digest(Digest::NONE)
616 .Padding(PaddingMode::NONE)
617 .AttestationChallenge(challenge)
618 .Authorization(TAG_NO_AUTH_REQUIRED)
619 .SetDefaultValidity(),
620 &key_blob, &key_characteristics));
621}
622
623/*
624 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
625 *
626 * Verifies that attesting to RSA ignores app id if challenge is missing.
627 */
628TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
629 auto key_size = 2048;
630 auto app_id = "foo";
631
Selene Huang6e46f142021-04-20 19:20:11 -0700632 auto subject = "cert subj 2";
633 vector<uint8_t> subject_der(make_name_from_str(subject));
634
635 uint64_t serial_int = 1;
636 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
637
Selene Huang4f64c222021-04-13 19:54:36 -0700638 vector<uint8_t> key_blob;
639 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700640 ASSERT_EQ(ErrorCode::OK,
641 GenerateKey(AuthorizationSetBuilder()
642 .RsaSigningKey(key_size, 65537)
643 .Digest(Digest::NONE)
644 .Padding(PaddingMode::NONE)
645 .AttestationApplicationId(app_id)
646 .Authorization(TAG_NO_AUTH_REQUIRED)
647 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
648 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
649 .SetDefaultValidity(),
650 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700651
652 ASSERT_GT(key_blob.size(), 0U);
653 CheckBaseParams(key_characteristics);
654
655 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
656
657 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
658 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
659 << "Key size " << key_size << "missing";
660 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
661
Selene Huang6e46f142021-04-20 19:20:11 -0700662 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700663 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
664 ASSERT_EQ(cert_chain_.size(), 1);
665
666 CheckedDeleteKey(&key_blob);
667}
668
669/*
Qi Wud22ec842020-11-26 13:27:53 +0800670 * NewKeyGenerationTest.LimitedUsageRsa
671 *
672 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
673 * resulting keys have correct characteristics.
674 */
675TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
676 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
677 vector<uint8_t> key_blob;
678 vector<KeyCharacteristics> key_characteristics;
679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
680 .RsaSigningKey(key_size, 65537)
681 .Digest(Digest::NONE)
682 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800683 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
684 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +0800685 &key_blob, &key_characteristics));
686
687 ASSERT_GT(key_blob.size(), 0U);
688 CheckBaseParams(key_characteristics);
689
690 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
691
692 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
693 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
694 << "Key size " << key_size << "missing";
695 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
696
697 // Check the usage count limit tag appears in the authorizations.
698 AuthorizationSet auths;
699 for (auto& entry : key_characteristics) {
700 auths.push_back(AuthorizationSet(entry.authorizations));
701 }
702 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
703 << "key usage count limit " << 1U << " missing";
704
705 CheckedDeleteKey(&key_blob);
706 }
707}
708
709/*
Qi Wubeefae42021-01-28 23:16:37 +0800710 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
711 *
712 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
713 * resulting keys have correct characteristics and attestation.
714 */
715TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700716 auto challenge = "hello";
717 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +0800718
Selene Huang6e46f142021-04-20 19:20:11 -0700719 auto subject = "cert subj 2";
720 vector<uint8_t> subject_der(make_name_from_str(subject));
721
722 uint64_t serial_int = 66;
723 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
724
Selene Huang4f64c222021-04-13 19:54:36 -0700725 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +0800726 vector<uint8_t> key_blob;
727 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700728 ASSERT_EQ(ErrorCode::OK,
729 GenerateKey(AuthorizationSetBuilder()
730 .RsaSigningKey(key_size, 65537)
731 .Digest(Digest::NONE)
732 .Padding(PaddingMode::NONE)
733 .AttestationChallenge(challenge)
734 .AttestationApplicationId(app_id)
735 .Authorization(TAG_NO_AUTH_REQUIRED)
736 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
737 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
738 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
739 .SetDefaultValidity(),
740 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +0800741
742 ASSERT_GT(key_blob.size(), 0U);
743 CheckBaseParams(key_characteristics);
744
745 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
746
747 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
748 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
749 << "Key size " << key_size << "missing";
750 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
751
752 // Check the usage count limit tag appears in the authorizations.
753 AuthorizationSet auths;
754 for (auto& entry : key_characteristics) {
755 auths.push_back(AuthorizationSet(entry.authorizations));
756 }
757 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
758 << "key usage count limit " << 1U << " missing";
759
760 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -0700761 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +0800762 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -0700763 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +0800764
765 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
766 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
767 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
768 sw_enforced, hw_enforced, SecLevel(),
769 cert_chain_[0].encodedCertificate));
770
771 CheckedDeleteKey(&key_blob);
772 }
773}
774
775/*
Selene Huang31ab4042020-04-29 04:22:39 -0700776 * NewKeyGenerationTest.NoInvalidRsaSizes
777 *
778 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
779 */
780TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
781 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
782 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700783 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700784 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
785 GenerateKey(AuthorizationSetBuilder()
786 .RsaSigningKey(key_size, 65537)
787 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800788 .Padding(PaddingMode::NONE)
789 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700790 &key_blob, &key_characteristics));
791 }
792}
793
794/*
795 * NewKeyGenerationTest.RsaNoDefaultSize
796 *
797 * Verifies that failing to specify a key size for RSA key generation returns
798 * UNSUPPORTED_KEY_SIZE.
799 */
800TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
801 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
802 GenerateKey(AuthorizationSetBuilder()
803 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
804 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800805 .SigningKey()
806 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700807}
808
809/*
810 * NewKeyGenerationTest.Ecdsa
811 *
812 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
813 * have correct characteristics.
814 */
815TEST_P(NewKeyGenerationTest, Ecdsa) {
816 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
817 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700818 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -0800819 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
820 .EcdsaSigningKey(key_size)
821 .Digest(Digest::NONE)
822 .SetDefaultValidity(),
823 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -0700824 ASSERT_GT(key_blob.size(), 0U);
825 CheckBaseParams(key_characteristics);
826
Shawn Willden7f424372021-01-10 18:06:50 -0700827 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700828
829 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
830 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
831 << "Key size " << key_size << "missing";
832
833 CheckedDeleteKey(&key_blob);
834 }
835}
836
837/*
Selene Huang4f64c222021-04-13 19:54:36 -0700838 * NewKeyGenerationTest.EcdsaAttestation
839 *
840 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
841 * an attestation will be generated.
842 */
843TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
844 auto challenge = "hello";
845 auto app_id = "foo";
846
Selene Huang6e46f142021-04-20 19:20:11 -0700847 auto subject = "cert subj 2";
848 vector<uint8_t> subject_der(make_name_from_str(subject));
849
850 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
851 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
852
Selene Huang4f64c222021-04-13 19:54:36 -0700853 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
854 vector<uint8_t> key_blob;
855 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700856 ASSERT_EQ(ErrorCode::OK,
857 GenerateKey(AuthorizationSetBuilder()
858 .Authorization(TAG_NO_AUTH_REQUIRED)
859 .EcdsaSigningKey(key_size)
860 .Digest(Digest::NONE)
861 .AttestationChallenge(challenge)
862 .AttestationApplicationId(app_id)
863 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
864 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
865 .SetDefaultValidity(),
866 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700867 ASSERT_GT(key_blob.size(), 0U);
868 CheckBaseParams(key_characteristics);
869
870 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
871
872 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
873 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
874 << "Key size " << key_size << "missing";
875
876 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
877 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -0700878 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700879
880 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
881 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
882 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
883 sw_enforced, hw_enforced, SecLevel(),
884 cert_chain_[0].encodedCertificate));
885
886 CheckedDeleteKey(&key_blob);
887 }
888}
889
890/*
891 * NewKeyGenerationTest.EcdsaSelfSignAttestation
892 *
893 * Verifies that if no challenge is provided to an Ecdsa key generation, then
894 * the key will generate a self signed attestation.
895 */
896TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -0700897 auto subject = "cert subj 2";
898 vector<uint8_t> subject_der(make_name_from_str(subject));
899
900 uint64_t serial_int = 0x123456FFF1234;
901 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
902
Selene Huang4f64c222021-04-13 19:54:36 -0700903 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
904 vector<uint8_t> key_blob;
905 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700906 ASSERT_EQ(ErrorCode::OK,
907 GenerateKey(AuthorizationSetBuilder()
908 .EcdsaSigningKey(key_size)
909 .Digest(Digest::NONE)
910 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
911 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
912 .SetDefaultValidity(),
913 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -0700914 ASSERT_GT(key_blob.size(), 0U);
915 CheckBaseParams(key_characteristics);
916
917 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
918
919 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
920 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
921 << "Key size " << key_size << "missing";
922
923 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -0700924 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -0700925 ASSERT_EQ(cert_chain_.size(), 1);
926
927 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
928 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
929
930 CheckedDeleteKey(&key_blob);
931 }
932}
933
934/*
935 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
936 *
937 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
938 * app id must also be provided or else it will fail.
939 */
940TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
941 auto challenge = "hello";
942 vector<uint8_t> key_blob;
943 vector<KeyCharacteristics> key_characteristics;
944
945 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
946 GenerateKey(AuthorizationSetBuilder()
947 .EcdsaSigningKey(EcCurve::P_256)
948 .Digest(Digest::NONE)
949 .AttestationChallenge(challenge)
950 .SetDefaultValidity(),
951 &key_blob, &key_characteristics));
952}
953
954/*
955 * NewKeyGenerationTest.EcdsaIgnoreAppId
956 *
957 * Verifies that if no challenge is provided to the Ecdsa key generation, then
958 * any appid will be ignored, and keymint will generate a self sign certificate.
959 */
960TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
961 auto app_id = "foo";
962
963 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
964 vector<uint8_t> key_blob;
965 vector<KeyCharacteristics> key_characteristics;
966 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
967 .EcdsaSigningKey(key_size)
968 .Digest(Digest::NONE)
969 .AttestationApplicationId(app_id)
970 .SetDefaultValidity(),
971 &key_blob, &key_characteristics));
972
973 ASSERT_GT(key_blob.size(), 0U);
974 CheckBaseParams(key_characteristics);
975
976 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
977
978 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
979 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
980 << "Key size " << key_size << "missing";
981
982 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
983 ASSERT_EQ(cert_chain_.size(), 1);
984
985 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
986 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
987
988 CheckedDeleteKey(&key_blob);
989 }
990}
991
992/*
993 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
994 *
995 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
996 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
997 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
998 * to specify how many following bytes will be used to encode the length.
999 */
1000TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1001 auto challenge = "hello";
1002 auto key_size = 256;
1003 std::vector<uint32_t> app_id_lengths{143, 258};
1004
1005 for (uint32_t length : app_id_lengths) {
1006 const string app_id(length, 'a');
1007 vector<uint8_t> key_blob;
1008 vector<KeyCharacteristics> key_characteristics;
1009 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1010 .Authorization(TAG_NO_AUTH_REQUIRED)
1011 .EcdsaSigningKey(key_size)
1012 .Digest(Digest::NONE)
1013 .AttestationChallenge(challenge)
1014 .AttestationApplicationId(app_id)
1015 .SetDefaultValidity(),
1016 &key_blob, &key_characteristics));
1017 ASSERT_GT(key_blob.size(), 0U);
1018 CheckBaseParams(key_characteristics);
1019
1020 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1021
1022 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1023 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1024 << "Key size " << key_size << "missing";
1025
1026 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1027 ASSERT_GT(cert_chain_.size(), 0);
1028
1029 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1030 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1031 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1032 sw_enforced, hw_enforced, SecLevel(),
1033 cert_chain_[0].encodedCertificate));
1034
1035 CheckedDeleteKey(&key_blob);
1036 }
1037}
1038
1039/*
Qi Wud22ec842020-11-26 13:27:53 +08001040 * NewKeyGenerationTest.LimitedUsageEcdsa
1041 *
1042 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1043 * resulting keys have correct characteristics.
1044 */
1045TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
1046 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1047 vector<uint8_t> key_blob;
1048 vector<KeyCharacteristics> key_characteristics;
1049 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1050 .EcdsaSigningKey(key_size)
1051 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001052 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1053 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001054 &key_blob, &key_characteristics));
1055
1056 ASSERT_GT(key_blob.size(), 0U);
1057 CheckBaseParams(key_characteristics);
1058
1059 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1060
1061 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1062 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1063 << "Key size " << key_size << "missing";
1064
1065 // Check the usage count limit tag appears in the authorizations.
1066 AuthorizationSet auths;
1067 for (auto& entry : key_characteristics) {
1068 auths.push_back(AuthorizationSet(entry.authorizations));
1069 }
1070 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1071 << "key usage count limit " << 1U << " missing";
1072
1073 CheckedDeleteKey(&key_blob);
1074 }
1075}
1076
1077/*
Selene Huang31ab4042020-04-29 04:22:39 -07001078 * NewKeyGenerationTest.EcdsaDefaultSize
1079 *
1080 * Verifies that failing to specify a key size for EC key generation returns
1081 * UNSUPPORTED_KEY_SIZE.
1082 */
1083TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1084 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1085 GenerateKey(AuthorizationSetBuilder()
1086 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1087 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001088 .Digest(Digest::NONE)
1089 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001090}
1091
1092/*
1093 * NewKeyGenerationTest.EcdsaInvalidSize
1094 *
1095 * Verifies that specifying an invalid key size for EC key generation returns
1096 * UNSUPPORTED_KEY_SIZE.
1097 */
1098TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
1099 for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
1100 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001101 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001102 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1103 .EcdsaSigningKey(key_size)
1104 .Digest(Digest::NONE)
1105 .SetDefaultValidity(),
1106 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001107 }
1108
Janis Danisevskis164bb872021-02-09 11:30:25 -08001109 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
1110 .EcdsaSigningKey(190)
1111 .Digest(Digest::NONE)
1112 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001113}
1114
1115/*
1116 * NewKeyGenerationTest.EcdsaMismatchKeySize
1117 *
1118 * Verifies that specifying mismatched key size and curve for EC key generation returns
1119 * INVALID_ARGUMENT.
1120 */
1121TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1122 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1123
1124 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
1125 GenerateKey(AuthorizationSetBuilder()
1126 .EcdsaSigningKey(224)
1127 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001128 .Digest(Digest::NONE)
1129 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001130}
1131
1132/*
1133 * NewKeyGenerationTest.EcdsaAllValidSizes
1134 *
1135 * Verifies that keymint supports all required EC key sizes.
1136 */
1137TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
1138 auto valid_sizes = ValidKeySizes(Algorithm::EC);
1139 for (size_t size : valid_sizes) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001140 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1141 .EcdsaSigningKey(size)
1142 .Digest(Digest::NONE)
1143 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001144 << "Failed to generate size: " << size;
1145 CheckedDeleteKey();
1146 }
1147}
1148
1149/*
1150 * NewKeyGenerationTest.EcdsaInvalidCurves
1151 *
1152 * Verifies that keymint does not support any curve designated as unsupported.
1153 */
1154TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1155 Digest digest;
1156 if (SecLevel() == SecurityLevel::STRONGBOX) {
1157 digest = Digest::SHA_2_256;
1158 } else {
1159 digest = Digest::SHA_2_512;
1160 }
1161 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001162 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1163 .EcdsaSigningKey(curve)
1164 .Digest(digest)
1165 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001166 << "Failed to generate key on curve: " << curve;
1167 CheckedDeleteKey();
1168 }
1169}
1170
1171/*
1172 * NewKeyGenerationTest.Hmac
1173 *
1174 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1175 * characteristics.
1176 */
1177TEST_P(NewKeyGenerationTest, Hmac) {
1178 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1179 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001180 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001181 constexpr size_t key_size = 128;
1182 ASSERT_EQ(ErrorCode::OK,
1183 GenerateKey(
1184 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1185 TAG_MIN_MAC_LENGTH, 128),
1186 &key_blob, &key_characteristics));
1187
1188 ASSERT_GT(key_blob.size(), 0U);
1189 CheckBaseParams(key_characteristics);
1190
Shawn Willden7f424372021-01-10 18:06:50 -07001191 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1192 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1193 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1194 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001195
1196 CheckedDeleteKey(&key_blob);
1197 }
1198}
1199
1200/*
Selene Huang4f64c222021-04-13 19:54:36 -07001201 * NewKeyGenerationTest.HmacNoAttestation
1202 *
1203 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1204 * and app id are provided.
1205 */
1206TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1207 auto challenge = "hello";
1208 auto app_id = "foo";
1209
1210 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1211 vector<uint8_t> key_blob;
1212 vector<KeyCharacteristics> key_characteristics;
1213 constexpr size_t key_size = 128;
1214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1215 .HmacKey(key_size)
1216 .Digest(digest)
1217 .AttestationChallenge(challenge)
1218 .AttestationApplicationId(app_id)
1219 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1220 &key_blob, &key_characteristics));
1221
1222 ASSERT_GT(key_blob.size(), 0U);
1223 ASSERT_EQ(cert_chain_.size(), 0);
1224 CheckBaseParams(key_characteristics);
1225
1226 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1227 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1228 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1229 << "Key size " << key_size << "missing";
1230
1231 CheckedDeleteKey(&key_blob);
1232 }
1233}
1234
1235/*
Qi Wud22ec842020-11-26 13:27:53 +08001236 * NewKeyGenerationTest.LimitedUsageHmac
1237 *
1238 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1239 * resulting keys have correct characteristics.
1240 */
1241TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1242 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1243 vector<uint8_t> key_blob;
1244 vector<KeyCharacteristics> key_characteristics;
1245 constexpr size_t key_size = 128;
1246 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1247 .HmacKey(key_size)
1248 .Digest(digest)
1249 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1250 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1251 &key_blob, &key_characteristics));
1252
1253 ASSERT_GT(key_blob.size(), 0U);
1254 CheckBaseParams(key_characteristics);
1255
1256 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1257 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1258 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1259 << "Key size " << key_size << "missing";
1260
1261 // Check the usage count limit tag appears in the authorizations.
1262 AuthorizationSet auths;
1263 for (auto& entry : key_characteristics) {
1264 auths.push_back(AuthorizationSet(entry.authorizations));
1265 }
1266 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1267 << "key usage count limit " << 1U << " missing";
1268
1269 CheckedDeleteKey(&key_blob);
1270 }
1271}
1272
1273/*
Selene Huang31ab4042020-04-29 04:22:39 -07001274 * NewKeyGenerationTest.HmacCheckKeySizes
1275 *
1276 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1277 */
1278TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1279 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1280 if (key_size < 64 || key_size % 8 != 0) {
1281 // To keep this test from being very slow, we only test a random fraction of
1282 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1283 // them, we expect to run ~40 of them in each run.
1284 if (key_size % 8 == 0 || random() % 10 == 0) {
1285 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1286 GenerateKey(AuthorizationSetBuilder()
1287 .HmacKey(key_size)
1288 .Digest(Digest::SHA_2_256)
1289 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1290 << "HMAC key size " << key_size << " invalid";
1291 }
1292 } else {
1293 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1294 .HmacKey(key_size)
1295 .Digest(Digest::SHA_2_256)
1296 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1297 << "Failed to generate HMAC key of size " << key_size;
1298 CheckedDeleteKey();
1299 }
1300 }
1301}
1302
1303/*
1304 * NewKeyGenerationTest.HmacCheckMinMacLengths
1305 *
1306 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
1307 * test is probabilistic in order to keep the runtime down, but any failure prints out the
1308 * specific MAC length that failed, so reproducing a failed run will be easy.
1309 */
1310TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
1311 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
1312 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
1313 // To keep this test from being very long, we only test a random fraction of
1314 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
1315 // we expect to run ~17 of them in each run.
1316 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
1317 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
1318 GenerateKey(AuthorizationSetBuilder()
1319 .HmacKey(128)
1320 .Digest(Digest::SHA_2_256)
1321 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1322 << "HMAC min mac length " << min_mac_length << " invalid.";
1323 }
1324 } else {
1325 EXPECT_EQ(ErrorCode::OK,
1326 GenerateKey(AuthorizationSetBuilder()
1327 .HmacKey(128)
1328 .Digest(Digest::SHA_2_256)
1329 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
1330 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
1331 CheckedDeleteKey();
1332 }
1333 }
1334}
1335
1336/*
1337 * NewKeyGenerationTest.HmacMultipleDigests
1338 *
1339 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
1340 */
1341TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
1342 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1343
1344 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1345 GenerateKey(AuthorizationSetBuilder()
1346 .HmacKey(128)
1347 .Digest(Digest::SHA1)
1348 .Digest(Digest::SHA_2_256)
1349 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1350}
1351
1352/*
1353 * NewKeyGenerationTest.HmacDigestNone
1354 *
1355 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
1356 */
1357TEST_P(NewKeyGenerationTest, HmacDigestNone) {
1358 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1359 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
1360 128)));
1361
1362 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1363 GenerateKey(AuthorizationSetBuilder()
1364 .HmacKey(128)
1365 .Digest(Digest::NONE)
1366 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1367}
1368
Selene Huang4f64c222021-04-13 19:54:36 -07001369/*
1370 * NewKeyGenerationTest.AesNoAttestation
1371 *
1372 * Verifies that attestation parameters to AES keys are ignored and generateKey
1373 * will succeed.
1374 */
1375TEST_P(NewKeyGenerationTest, AesNoAttestation) {
1376 auto challenge = "hello";
1377 auto app_id = "foo";
1378
1379 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1380 .Authorization(TAG_NO_AUTH_REQUIRED)
1381 .AesEncryptionKey(128)
1382 .EcbMode()
1383 .Padding(PaddingMode::PKCS7)
1384 .AttestationChallenge(challenge)
1385 .AttestationApplicationId(app_id)));
1386
1387 ASSERT_EQ(cert_chain_.size(), 0);
1388}
1389
1390/*
1391 * NewKeyGenerationTest.TripleDesNoAttestation
1392 *
1393 * Verifies that attesting parameters to 3DES keys are ignored and generate key
1394 * will be successful. No attestation should be generated.
1395 */
1396TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
1397 auto challenge = "hello";
1398 auto app_id = "foo";
1399
1400 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1401 .TripleDesEncryptionKey(168)
1402 .BlockMode(BlockMode::ECB)
1403 .Authorization(TAG_NO_AUTH_REQUIRED)
1404 .Padding(PaddingMode::NONE)
1405 .AttestationChallenge(challenge)
1406 .AttestationApplicationId(app_id)));
1407 ASSERT_EQ(cert_chain_.size(), 0);
1408}
1409
Selene Huang31ab4042020-04-29 04:22:39 -07001410INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
1411
1412typedef KeyMintAidlTestBase SigningOperationsTest;
1413
1414/*
1415 * SigningOperationsTest.RsaSuccess
1416 *
1417 * Verifies that raw RSA signature operations succeed.
1418 */
1419TEST_P(SigningOperationsTest, RsaSuccess) {
1420 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1421 .RsaSigningKey(2048, 65537)
1422 .Digest(Digest::NONE)
1423 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001424 .Authorization(TAG_NO_AUTH_REQUIRED)
1425 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001426 string message = "12345678901234567890123456789012";
1427 string signature = SignMessage(
1428 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1429}
1430
1431/*
1432 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
1433 *
Shawn Willden7f424372021-01-10 18:06:50 -07001434 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07001435 */
1436TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
1437 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1438 .Authorization(TAG_NO_AUTH_REQUIRED)
1439 .RsaSigningKey(2048, 65537)
1440 .Digest(Digest::NONE)
1441 .Padding(PaddingMode::NONE)
1442 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08001443 .Authorization(TAG_APPLICATION_DATA, "appdata")
1444 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001445 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1446 Begin(KeyPurpose::SIGN,
1447 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1448 AbortIfNeeded();
1449 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1450 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1451 .Digest(Digest::NONE)
1452 .Padding(PaddingMode::NONE)
1453 .Authorization(TAG_APPLICATION_ID, "clientid")));
1454 AbortIfNeeded();
1455 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1456 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1457 .Digest(Digest::NONE)
1458 .Padding(PaddingMode::NONE)
1459 .Authorization(TAG_APPLICATION_DATA, "appdata")));
1460 AbortIfNeeded();
1461 EXPECT_EQ(ErrorCode::OK,
1462 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1463 .Digest(Digest::NONE)
1464 .Padding(PaddingMode::NONE)
1465 .Authorization(TAG_APPLICATION_DATA, "appdata")
1466 .Authorization(TAG_APPLICATION_ID, "clientid")));
1467 AbortIfNeeded();
1468}
1469
1470/*
1471 * SigningOperationsTest.RsaPssSha256Success
1472 *
1473 * Verifies that RSA-PSS signature operations succeed.
1474 */
1475TEST_P(SigningOperationsTest, RsaPssSha256Success) {
1476 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1477 .RsaSigningKey(2048, 65537)
1478 .Digest(Digest::SHA_2_256)
1479 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001480 .Authorization(TAG_NO_AUTH_REQUIRED)
1481 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001482 // Use large message, which won't work without digesting.
1483 string message(1024, 'a');
1484 string signature = SignMessage(
1485 message,
1486 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
1487}
1488
1489/*
1490 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
1491 *
1492 * Verifies that keymint rejects signature operations that specify a padding mode when the key
1493 * supports only unpadded operations.
1494 */
1495TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
1496 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1497 .RsaSigningKey(2048, 65537)
1498 .Digest(Digest::NONE)
1499 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001500 .Padding(PaddingMode::NONE)
1501 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001502 string message = "12345678901234567890123456789012";
1503 string signature;
1504
1505 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
1506 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1507 .Digest(Digest::NONE)
1508 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1509}
1510
1511/*
1512 * SigningOperationsTest.NoUserConfirmation
1513 *
1514 * Verifies that keymint rejects signing operations for keys with
1515 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
1516 * presented.
1517 */
1518TEST_P(SigningOperationsTest, NoUserConfirmation) {
1519 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001520 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1521 .RsaSigningKey(1024, 65537)
1522 .Digest(Digest::NONE)
1523 .Padding(PaddingMode::NONE)
1524 .Authorization(TAG_NO_AUTH_REQUIRED)
1525 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1526 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001527
1528 const string message = "12345678901234567890123456789012";
1529 EXPECT_EQ(ErrorCode::OK,
1530 Begin(KeyPurpose::SIGN,
1531 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1532 string signature;
1533 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
1534}
1535
1536/*
1537 * SigningOperationsTest.RsaPkcs1Sha256Success
1538 *
1539 * Verifies that digested RSA-PKCS1 signature operations succeed.
1540 */
1541TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
1542 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1543 .RsaSigningKey(2048, 65537)
1544 .Digest(Digest::SHA_2_256)
1545 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001546 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1547 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001548 string message(1024, 'a');
1549 string signature = SignMessage(message, AuthorizationSetBuilder()
1550 .Digest(Digest::SHA_2_256)
1551 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1552}
1553
1554/*
1555 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
1556 *
1557 * Verifies that undigested RSA-PKCS1 signature operations succeed.
1558 */
1559TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
1560 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1561 .RsaSigningKey(2048, 65537)
1562 .Digest(Digest::NONE)
1563 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001564 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1565 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001566 string message(53, 'a');
1567 string signature = SignMessage(message, AuthorizationSetBuilder()
1568 .Digest(Digest::NONE)
1569 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1570}
1571
1572/*
1573 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
1574 *
1575 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
1576 * given a too-long message.
1577 */
1578TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
1579 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1580 .RsaSigningKey(2048, 65537)
1581 .Digest(Digest::NONE)
1582 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001583 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1584 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001585 string message(257, 'a');
1586
1587 EXPECT_EQ(ErrorCode::OK,
1588 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1589 .Digest(Digest::NONE)
1590 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1591 string signature;
1592 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
1593}
1594
1595/*
1596 * SigningOperationsTest.RsaPssSha512TooSmallKey
1597 *
1598 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
1599 * used with a key that is too small for the message.
1600 *
1601 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
1602 * keymint specification requires that salt_size == digest_size, so the message will be
1603 * digest_size * 2 +
1604 * 16. Such a message can only be signed by a given key if the key is at least that size. This
1605 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
1606 * for a 1024-bit key.
1607 */
1608TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
1609 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1610 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1611 .RsaSigningKey(1024, 65537)
1612 .Digest(Digest::SHA_2_512)
1613 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001614 .Padding(PaddingMode::RSA_PSS)
1615 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001616 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1617 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1618 .Digest(Digest::SHA_2_512)
1619 .Padding(PaddingMode::RSA_PSS)));
1620}
1621
1622/*
1623 * SigningOperationsTest.RsaNoPaddingTooLong
1624 *
1625 * Verifies that raw RSA signature operations fail with the correct error code when
1626 * given a too-long message.
1627 */
1628TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
1629 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1630 .RsaSigningKey(2048, 65537)
1631 .Digest(Digest::NONE)
1632 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001633 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1634 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001635 // One byte too long
1636 string message(2048 / 8 + 1, 'a');
1637 ASSERT_EQ(ErrorCode::OK,
1638 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1639 .Digest(Digest::NONE)
1640 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1641 string result;
1642 ErrorCode finish_error_code = Finish(message, &result);
1643 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1644 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1645
1646 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
1647 message = string(128 * 1024, 'a');
1648 ASSERT_EQ(ErrorCode::OK,
1649 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1650 .Digest(Digest::NONE)
1651 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1652 finish_error_code = Finish(message, &result);
1653 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1654 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1655}
1656
1657/*
1658 * SigningOperationsTest.RsaAbort
1659 *
1660 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
1661 * test, but the behavior should be algorithm and purpose-independent.
1662 */
1663TEST_P(SigningOperationsTest, RsaAbort) {
1664 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1665 .RsaSigningKey(2048, 65537)
1666 .Digest(Digest::NONE)
1667 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001668 .Padding(PaddingMode::NONE)
1669 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001670
1671 ASSERT_EQ(ErrorCode::OK,
1672 Begin(KeyPurpose::SIGN,
1673 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1674 EXPECT_EQ(ErrorCode::OK, Abort());
1675
1676 // Another abort should fail
1677 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
1678
1679 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08001680 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07001681}
1682
1683/*
1684 * SigningOperationsTest.RsaUnsupportedPadding
1685 *
1686 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
1687 * with a padding mode inappropriate for RSA.
1688 */
1689TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
1690 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1691 .RsaSigningKey(2048, 65537)
1692 .Authorization(TAG_NO_AUTH_REQUIRED)
1693 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001694 .Padding(PaddingMode::PKCS7)
1695 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001696 ASSERT_EQ(
1697 ErrorCode::UNSUPPORTED_PADDING_MODE,
1698 Begin(KeyPurpose::SIGN,
1699 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
1700}
1701
1702/*
1703 * SigningOperationsTest.RsaPssNoDigest
1704 *
1705 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
1706 */
1707TEST_P(SigningOperationsTest, RsaNoDigest) {
1708 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1709 .RsaSigningKey(2048, 65537)
1710 .Authorization(TAG_NO_AUTH_REQUIRED)
1711 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001712 .Padding(PaddingMode::RSA_PSS)
1713 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001714 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1715 Begin(KeyPurpose::SIGN,
1716 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
1717
1718 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1719 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
1720}
1721
1722/*
1723 * SigningOperationsTest.RsaPssNoDigest
1724 *
1725 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
1726 * supported in some cases (as validated in other tests), but a mode must be specified.
1727 */
1728TEST_P(SigningOperationsTest, RsaNoPadding) {
1729 // Padding must be specified
1730 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1731 .RsaKey(2048, 65537)
1732 .Authorization(TAG_NO_AUTH_REQUIRED)
1733 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001734 .Digest(Digest::NONE)
1735 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001736 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
1737 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1738}
1739
1740/*
1741 * SigningOperationsTest.RsaShortMessage
1742 *
1743 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
1744 */
1745TEST_P(SigningOperationsTest, RsaTooShortMessage) {
1746 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1747 .Authorization(TAG_NO_AUTH_REQUIRED)
1748 .RsaSigningKey(2048, 65537)
1749 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001750 .Padding(PaddingMode::NONE)
1751 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001752
1753 // Barely shorter
1754 string message(2048 / 8 - 1, 'a');
1755 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1756
1757 // Much shorter
1758 message = "a";
1759 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1760}
1761
1762/*
1763 * SigningOperationsTest.RsaSignWithEncryptionKey
1764 *
1765 * Verifies that RSA encryption keys cannot be used to sign.
1766 */
1767TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
1768 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1769 .Authorization(TAG_NO_AUTH_REQUIRED)
1770 .RsaEncryptionKey(2048, 65537)
1771 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001772 .Padding(PaddingMode::NONE)
1773 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001774 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
1775 Begin(KeyPurpose::SIGN,
1776 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1777}
1778
1779/*
1780 * SigningOperationsTest.RsaSignTooLargeMessage
1781 *
1782 * Verifies that attempting a raw signature of a message which is the same length as the key,
1783 * but numerically larger than the public modulus, fails with the correct error.
1784 */
1785TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
1786 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1787 .Authorization(TAG_NO_AUTH_REQUIRED)
1788 .RsaSigningKey(2048, 65537)
1789 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001790 .Padding(PaddingMode::NONE)
1791 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001792
1793 // Largest possible message will always be larger than the public modulus.
1794 string message(2048 / 8, static_cast<char>(0xff));
1795 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1796 .Authorization(TAG_NO_AUTH_REQUIRED)
1797 .Digest(Digest::NONE)
1798 .Padding(PaddingMode::NONE)));
1799 string signature;
1800 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
1801}
1802
1803/*
1804 * SigningOperationsTest.EcdsaAllSizesAndHashes
1805 *
1806 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
1807 */
1808TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
1809 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1810 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
1811 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1812 .Authorization(TAG_NO_AUTH_REQUIRED)
1813 .EcdsaSigningKey(key_size)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001814 .Digest(digest)
1815 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07001816 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
1817 << " and digest " << digest;
1818 if (error != ErrorCode::OK) continue;
1819
1820 string message(1024, 'a');
1821 if (digest == Digest::NONE) message.resize(key_size / 8);
1822 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
1823 CheckedDeleteKey();
1824 }
1825 }
1826}
1827
1828/*
1829 * SigningOperationsTest.EcdsaAllCurves
1830 *
1831 * Verifies that ECDSA operations succeed with all possible curves.
1832 */
1833TEST_P(SigningOperationsTest, EcdsaAllCurves) {
1834 for (auto curve : ValidCurves()) {
1835 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1836 .Authorization(TAG_NO_AUTH_REQUIRED)
1837 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001838 .Digest(Digest::SHA_2_256)
1839 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07001840 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
1841 if (error != ErrorCode::OK) continue;
1842
1843 string message(1024, 'a');
1844 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1845 CheckedDeleteKey();
1846 }
1847}
1848
1849/*
1850 * SigningOperationsTest.EcdsaNoDigestHugeData
1851 *
1852 * Verifies that ECDSA operations support very large messages, even without digesting. This
1853 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
1854 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
1855 * the framework.
1856 */
1857TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
1858 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1859 .Authorization(TAG_NO_AUTH_REQUIRED)
1860 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001861 .Digest(Digest::NONE)
1862 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001863 string message(1 * 1024, 'a');
1864 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
1865}
1866
1867/*
1868 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
1869 *
1870 * Verifies that using an EC key requires the correct app ID/data.
1871 */
1872TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
1873 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1874 .Authorization(TAG_NO_AUTH_REQUIRED)
1875 .EcdsaSigningKey(256)
1876 .Digest(Digest::NONE)
1877 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08001878 .Authorization(TAG_APPLICATION_DATA, "appdata")
1879 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001880 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1881 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1882 AbortIfNeeded();
1883 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1884 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1885 .Digest(Digest::NONE)
1886 .Authorization(TAG_APPLICATION_ID, "clientid")));
1887 AbortIfNeeded();
1888 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1889 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1890 .Digest(Digest::NONE)
1891 .Authorization(TAG_APPLICATION_DATA, "appdata")));
1892 AbortIfNeeded();
1893 EXPECT_EQ(ErrorCode::OK,
1894 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1895 .Digest(Digest::NONE)
1896 .Authorization(TAG_APPLICATION_DATA, "appdata")
1897 .Authorization(TAG_APPLICATION_ID, "clientid")));
1898 AbortIfNeeded();
1899}
1900
1901/*
1902 * SigningOperationsTest.AesEcbSign
1903 *
1904 * Verifies that attempts to use AES keys to sign fail in the correct way.
1905 */
1906TEST_P(SigningOperationsTest, AesEcbSign) {
1907 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1908 .Authorization(TAG_NO_AUTH_REQUIRED)
1909 .SigningKey()
1910 .AesEncryptionKey(128)
1911 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
1912
1913 AuthorizationSet out_params;
1914 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1915 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
1916 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1917 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
1918}
1919
1920/*
1921 * SigningOperationsTest.HmacAllDigests
1922 *
1923 * Verifies that HMAC works with all digests.
1924 */
1925TEST_P(SigningOperationsTest, HmacAllDigests) {
1926 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
1927 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1928 .Authorization(TAG_NO_AUTH_REQUIRED)
1929 .HmacKey(128)
1930 .Digest(digest)
1931 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
1932 << "Failed to create HMAC key with digest " << digest;
1933 string message = "12345678901234567890123456789012";
1934 string signature = MacMessage(message, digest, 160);
1935 EXPECT_EQ(160U / 8U, signature.size())
1936 << "Failed to sign with HMAC key with digest " << digest;
1937 CheckedDeleteKey();
1938 }
1939}
1940
1941/*
1942 * SigningOperationsTest.HmacSha256TooLargeMacLength
1943 *
1944 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
1945 * digest size.
1946 */
1947TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
1948 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1949 .Authorization(TAG_NO_AUTH_REQUIRED)
1950 .HmacKey(128)
1951 .Digest(Digest::SHA_2_256)
1952 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1953 AuthorizationSet output_params;
1954 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
1955 AuthorizationSetBuilder()
1956 .Digest(Digest::SHA_2_256)
1957 .Authorization(TAG_MAC_LENGTH, 264),
1958 &output_params));
1959}
1960
1961/*
1962 * SigningOperationsTest.HmacSha256TooSmallMacLength
1963 *
1964 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
1965 * specified minimum MAC length.
1966 */
1967TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
1968 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1969 .Authorization(TAG_NO_AUTH_REQUIRED)
1970 .HmacKey(128)
1971 .Digest(Digest::SHA_2_256)
1972 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1973 AuthorizationSet output_params;
1974 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
1975 AuthorizationSetBuilder()
1976 .Digest(Digest::SHA_2_256)
1977 .Authorization(TAG_MAC_LENGTH, 120),
1978 &output_params));
1979}
1980
1981/*
1982 * SigningOperationsTest.HmacRfc4231TestCase3
1983 *
1984 * Validates against the test vectors from RFC 4231 test case 3.
1985 */
1986TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
1987 string key(20, 0xaa);
1988 string message(50, 0xdd);
1989 uint8_t sha_224_expected[] = {
1990 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
1991 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
1992 };
1993 uint8_t sha_256_expected[] = {
1994 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
1995 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
1996 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
1997 };
1998 uint8_t sha_384_expected[] = {
1999 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2000 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2001 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2002 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2003 };
2004 uint8_t sha_512_expected[] = {
2005 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2006 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2007 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2008 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2009 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2010 };
2011
2012 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2013 if (SecLevel() != SecurityLevel::STRONGBOX) {
2014 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2015 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2016 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2017 }
2018}
2019
2020/*
2021 * SigningOperationsTest.HmacRfc4231TestCase5
2022 *
2023 * Validates against the test vectors from RFC 4231 test case 5.
2024 */
2025TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2026 string key(20, 0x0c);
2027 string message = "Test With Truncation";
2028
2029 uint8_t sha_224_expected[] = {
2030 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2031 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2032 };
2033 uint8_t sha_256_expected[] = {
2034 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2035 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2036 };
2037 uint8_t sha_384_expected[] = {
2038 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2039 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2040 };
2041 uint8_t sha_512_expected[] = {
2042 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2043 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2044 };
2045
2046 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2047 if (SecLevel() != SecurityLevel::STRONGBOX) {
2048 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2049 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2050 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2051 }
2052}
2053
2054INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2055
2056typedef KeyMintAidlTestBase VerificationOperationsTest;
2057
2058/*
2059 * VerificationOperationsTest.RsaSuccess
2060 *
2061 * Verifies that a simple RSA signature/verification sequence succeeds.
2062 */
2063TEST_P(VerificationOperationsTest, RsaSuccess) {
2064 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2065 .Authorization(TAG_NO_AUTH_REQUIRED)
2066 .RsaSigningKey(2048, 65537)
2067 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002068 .Padding(PaddingMode::NONE)
2069 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002070 string message = "12345678901234567890123456789012";
2071 string signature = SignMessage(
2072 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2073 VerifyMessage(message, signature,
2074 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2075}
2076
2077/*
2078 * VerificationOperationsTest.RsaSuccess
2079 *
2080 * Verifies RSA signature/verification for all padding modes and digests.
2081 */
2082TEST_P(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
2083 auto authorizations = AuthorizationSetBuilder()
2084 .Authorization(TAG_NO_AUTH_REQUIRED)
2085 .RsaSigningKey(2048, 65537)
2086 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2087 .Padding(PaddingMode::NONE)
2088 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002089 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2090 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002091
2092 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2093
2094 string message(128, 'a');
2095 string corrupt_message(message);
2096 ++corrupt_message[corrupt_message.size() / 2];
2097
2098 for (auto padding :
2099 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2100 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2101 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2102 // Digesting only makes sense with padding.
2103 continue;
2104 }
2105
2106 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2107 // PSS requires digesting.
2108 continue;
2109 }
2110
2111 string signature =
2112 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2113 VerifyMessage(message, signature,
2114 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2115
2116 /* TODO(seleneh) add exportkey tests back later when we have decided on
2117 * the new api.
2118 if (digest != Digest::NONE) {
2119 // Verify with OpenSSL.
2120 vector<uint8_t> pubkey;
2121 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
2122
2123 const uint8_t* p = pubkey.data();
2124 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2125 ASSERT_TRUE(pkey.get());
2126
2127 EVP_MD_CTX digest_ctx;
2128 EVP_MD_CTX_init(&digest_ctx);
2129 EVP_PKEY_CTX* pkey_ctx;
2130 const EVP_MD* md = openssl_digest(digest);
2131 ASSERT_NE(md, nullptr);
2132 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2133 nullptr, pkey.get()));
2134
2135 switch (padding) {
2136 case PaddingMode::RSA_PSS:
2137 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx,
2138 RSA_PKCS1_PSS_PADDING), 0); EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx,
2139 EVP_MD_size(md)), 0); break; case PaddingMode::RSA_PKCS1_1_5_SIGN:
2140 // PKCS1 is the default; don't need to set anything.
2141 break;
2142 default:
2143 FAIL();
2144 break;
2145 }
2146
2147 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2148 message.size())); EXPECT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
2149 reinterpret_cast<const
2150 uint8_t*>(signature.data()), signature.size())); EVP_MD_CTX_cleanup(&digest_ctx);
2151 }
2152 */
2153
2154 // Corrupt signature shouldn't verify.
2155 string corrupt_signature(signature);
2156 ++corrupt_signature[corrupt_signature.size() / 2];
2157
2158 EXPECT_EQ(ErrorCode::OK,
2159 Begin(KeyPurpose::VERIFY,
2160 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2161 string result;
2162 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
2163
2164 // Corrupt message shouldn't verify
2165 EXPECT_EQ(ErrorCode::OK,
2166 Begin(KeyPurpose::VERIFY,
2167 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
2168 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
2169 }
2170 }
2171}
2172
2173/*
2174 * VerificationOperationsTest.RsaSuccess
2175 *
2176 * Verifies ECDSA signature/verification for all digests and curves.
2177 */
2178TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
2179 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2180
2181 string message = "1234567890";
2182 string corrupt_message = "2234567890";
2183 for (auto curve : ValidCurves()) {
2184 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2185 .Authorization(TAG_NO_AUTH_REQUIRED)
2186 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002187 .Digest(digests)
2188 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002189 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2190 if (error != ErrorCode::OK) {
2191 continue;
2192 }
2193
2194 for (auto digest : digests) {
2195 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2196 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2197
2198 /* TODO(seleneh) add exportkey tests back later when we have decided on
2199 * the new api.
2200
2201 // Verify with OpenSSL
2202 if (digest != Digest::NONE) {
2203 vector<uint8_t> pubkey;
2204 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
2205 << curve << ' ' << digest;
2206
2207 const uint8_t* p = pubkey.data();
2208 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
2209 ASSERT_TRUE(pkey.get());
2210
2211 EVP_MD_CTX digest_ctx;
2212 EVP_MD_CTX_init(&digest_ctx);
2213 EVP_PKEY_CTX* pkey_ctx;
2214 const EVP_MD* md = openssl_digest(digest);
2215
2216 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
2217 nullptr, pkey.get()))
2218 << curve << ' ' << digest;
2219
2220 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
2221 message.size()))
2222 << curve << ' ' << digest;
2223
2224 EXPECT_EQ(1,
2225 EVP_DigestVerifyFinal(&digest_ctx,
2226 reinterpret_cast<const
2227 uint8_t*>(signature.data()), signature.size()))
2228 << curve << ' ' << digest;
2229
2230 EVP_MD_CTX_cleanup(&digest_ctx);
2231 }
2232 */
2233 // Corrupt signature shouldn't verify.
2234 string corrupt_signature(signature);
2235 ++corrupt_signature[corrupt_signature.size() / 2];
2236
2237 EXPECT_EQ(ErrorCode::OK,
2238 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2239 << curve << ' ' << digest;
2240
2241 string result;
2242 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
2243 << curve << ' ' << digest;
2244
2245 // Corrupt message shouldn't verify
2246 EXPECT_EQ(ErrorCode::OK,
2247 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
2248 << curve << ' ' << digest;
2249
2250 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
2251 << curve << ' ' << digest;
2252 }
2253
2254 auto rc = DeleteKey();
2255 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2256 }
2257}
2258
2259/*
2260 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2261 *
2262 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2263 */
2264TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2265 string key_material = "HelloThisIsAKey";
2266
2267 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002268 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002269 EXPECT_EQ(ErrorCode::OK,
2270 ImportKey(AuthorizationSetBuilder()
2271 .Authorization(TAG_NO_AUTH_REQUIRED)
2272 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2273 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2274 .Digest(Digest::SHA_2_256)
2275 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2276 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2277 EXPECT_EQ(ErrorCode::OK,
2278 ImportKey(AuthorizationSetBuilder()
2279 .Authorization(TAG_NO_AUTH_REQUIRED)
2280 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2281 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2282 .Digest(Digest::SHA_2_256)
2283 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2284 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2285
2286 string message = "This is a message.";
2287 string signature = SignMessage(
2288 signing_key, message,
2289 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2290
2291 // Signing key should not work.
2292 AuthorizationSet out_params;
2293 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2294 Begin(KeyPurpose::VERIFY, signing_key,
2295 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2296
2297 // Verification key should work.
2298 VerifyMessage(verification_key, message, signature,
2299 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2300
2301 CheckedDeleteKey(&signing_key);
2302 CheckedDeleteKey(&verification_key);
2303}
2304
2305INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2306
2307typedef KeyMintAidlTestBase ExportKeyTest;
2308
2309/*
2310 * ExportKeyTest.RsaUnsupportedKeyFormat
2311 *
2312 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2313 */
2314// TODO(seleneh) add ExportKey to GenerateKey
2315// check result
2316
2317class ImportKeyTest : public KeyMintAidlTestBase {
2318 public:
2319 template <TagType tag_type, Tag tag, typename ValueT>
2320 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2321 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002322 for (auto& entry : key_characteristics_) {
2323 if (entry.securityLevel == SecLevel()) {
2324 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2325 << "Tag " << tag << " with value " << expected
2326 << " not found at security level" << entry.securityLevel;
2327 } else {
2328 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2329 << "Tag " << tag << " found at security level " << entry.securityLevel;
2330 }
Selene Huang31ab4042020-04-29 04:22:39 -07002331 }
2332 }
2333
2334 void CheckOrigin() {
2335 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07002336 // Origin isn't a crypto param, but it always lives with them.
2337 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07002338 }
2339};
2340
2341/*
2342 * ImportKeyTest.RsaSuccess
2343 *
2344 * Verifies that importing and using an RSA key pair works correctly.
2345 */
2346TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07002347 uint32_t key_size;
2348 string key;
2349
2350 if (SecLevel() == SecurityLevel::STRONGBOX) {
2351 key_size = 2048;
2352 key = rsa_2048_key;
2353 } else {
2354 key_size = 1024;
2355 key = rsa_key;
2356 }
2357
Selene Huang31ab4042020-04-29 04:22:39 -07002358 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2359 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07002360 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07002361 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002362 .Padding(PaddingMode::RSA_PSS)
2363 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07002364 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07002365
2366 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07002367 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002368 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
2369 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2370 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
2371 CheckOrigin();
2372
2373 string message(1024 / 8, 'a');
2374 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
2375 string signature = SignMessage(message, params);
2376 VerifyMessage(message, signature, params);
2377}
2378
2379/*
2380 * ImportKeyTest.RsaKeySizeMismatch
2381 *
2382 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
2383 * correct way.
2384 */
2385TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
2386 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2387 ImportKey(AuthorizationSetBuilder()
2388 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
2389 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002390 .Padding(PaddingMode::NONE)
2391 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002392 KeyFormat::PKCS8, rsa_key));
2393}
2394
2395/*
2396 * ImportKeyTest.RsaPublicExponentMismatch
2397 *
2398 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
2399 * fails in the correct way.
2400 */
2401TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
2402 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2403 ImportKey(AuthorizationSetBuilder()
2404 .RsaSigningKey(1024, 3 /* Doesn't match key */)
2405 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002406 .Padding(PaddingMode::NONE)
2407 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002408 KeyFormat::PKCS8, rsa_key));
2409}
2410
2411/*
2412 * ImportKeyTest.EcdsaSuccess
2413 *
2414 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
2415 */
2416TEST_P(ImportKeyTest, EcdsaSuccess) {
2417 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2418 .Authorization(TAG_NO_AUTH_REQUIRED)
2419 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002420 .Digest(Digest::SHA_2_256)
2421 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002422 KeyFormat::PKCS8, ec_256_key));
2423
2424 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2425 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2426 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2427 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2428
2429 CheckOrigin();
2430
2431 string message(32, 'a');
2432 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2433 string signature = SignMessage(message, params);
2434 VerifyMessage(message, signature, params);
2435}
2436
2437/*
2438 * ImportKeyTest.EcdsaP256RFC5915Success
2439 *
2440 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
2441 * correctly.
2442 */
2443TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
2444 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2445 .Authorization(TAG_NO_AUTH_REQUIRED)
2446 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002447 .Digest(Digest::SHA_2_256)
2448 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002449 KeyFormat::PKCS8, ec_256_key_rfc5915));
2450
2451 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2452 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2453 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2454 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2455
2456 CheckOrigin();
2457
2458 string message(32, 'a');
2459 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2460 string signature = SignMessage(message, params);
2461 VerifyMessage(message, signature, params);
2462}
2463
2464/*
2465 * ImportKeyTest.EcdsaP256SEC1Success
2466 *
2467 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
2468 */
2469TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
2470 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2471 .Authorization(TAG_NO_AUTH_REQUIRED)
2472 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002473 .Digest(Digest::SHA_2_256)
2474 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002475 KeyFormat::PKCS8, ec_256_key_sec1));
2476
2477 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2478 CheckCryptoParam(TAG_KEY_SIZE, 256U);
2479 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2480 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
2481
2482 CheckOrigin();
2483
2484 string message(32, 'a');
2485 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2486 string signature = SignMessage(message, params);
2487 VerifyMessage(message, signature, params);
2488}
2489
2490/*
2491 * ImportKeyTest.Ecdsa521Success
2492 *
2493 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
2494 */
2495TEST_P(ImportKeyTest, Ecdsa521Success) {
2496 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2497 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2498 .Authorization(TAG_NO_AUTH_REQUIRED)
2499 .EcdsaSigningKey(521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002500 .Digest(Digest::SHA_2_256)
2501 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002502 KeyFormat::PKCS8, ec_521_key));
2503
2504 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2505 CheckCryptoParam(TAG_KEY_SIZE, 521U);
2506 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2507 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
2508 CheckOrigin();
2509
2510 string message(32, 'a');
2511 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2512 string signature = SignMessage(message, params);
2513 VerifyMessage(message, signature, params);
2514}
2515
2516/*
2517 * ImportKeyTest.EcdsaSizeMismatch
2518 *
2519 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
2520 * correct way.
2521 */
2522TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
2523 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2524 ImportKey(AuthorizationSetBuilder()
2525 .EcdsaSigningKey(224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002526 .Digest(Digest::NONE)
2527 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002528 KeyFormat::PKCS8, ec_256_key));
2529}
2530
2531/*
2532 * ImportKeyTest.EcdsaCurveMismatch
2533 *
2534 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
2535 * the correct way.
2536 */
2537TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
2538 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2539 ImportKey(AuthorizationSetBuilder()
2540 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002541 .Digest(Digest::NONE)
2542 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002543 KeyFormat::PKCS8, ec_256_key));
2544}
2545
2546/*
2547 * ImportKeyTest.AesSuccess
2548 *
2549 * Verifies that importing and using an AES key works.
2550 */
2551TEST_P(ImportKeyTest, AesSuccess) {
2552 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2553 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2554 .Authorization(TAG_NO_AUTH_REQUIRED)
2555 .AesEncryptionKey(key.size() * 8)
2556 .EcbMode()
2557 .Padding(PaddingMode::PKCS7),
2558 KeyFormat::RAW, key));
2559
2560 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
2561 CheckCryptoParam(TAG_KEY_SIZE, 128U);
2562 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
2563 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
2564 CheckOrigin();
2565
2566 string message = "Hello World!";
2567 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2568 string ciphertext = EncryptMessage(message, params);
2569 string plaintext = DecryptMessage(ciphertext, params);
2570 EXPECT_EQ(message, plaintext);
2571}
2572
2573/*
2574 * ImportKeyTest.AesSuccess
2575 *
2576 * Verifies that importing and using an HMAC key works.
2577 */
2578TEST_P(ImportKeyTest, HmacKeySuccess) {
2579 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2580 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2581 .Authorization(TAG_NO_AUTH_REQUIRED)
2582 .HmacKey(key.size() * 8)
2583 .Digest(Digest::SHA_2_256)
2584 .Authorization(TAG_MIN_MAC_LENGTH, 256),
2585 KeyFormat::RAW, key));
2586
2587 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
2588 CheckCryptoParam(TAG_KEY_SIZE, 128U);
2589 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2590 CheckOrigin();
2591
2592 string message = "Hello World!";
2593 string signature = MacMessage(message, Digest::SHA_2_256, 256);
2594 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2595}
2596
2597INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
2598
2599auto wrapped_key = hex2str(
2600 "3082017902010004820100934bf94e2aa28a3f83c9f79297250262fbe3276b5a1c91159bbfa3ef8957aac8"
2601 "4b59b30b455a79c2973480823d8b3863c3deef4a8e243590268d80e18751a0e130f67ce6a1ace9f79b95e0"
2602 "97474febc981195b1d13a69086c0863f66a7b7fdb48792227b1ac5e2489febdf087ab5486483033a6f001c"
2603 "a5d1ec1e27f5c30f4cec2642074a39ae68aee552e196627a8e3d867e67a8c01b11e75f13cca0a97ab668b5"
2604 "0cda07a8ecb7cd8e3dd7009c9636534f6f239cffe1fc8daa466f78b676c7119efb96bce4e69ca2a25d0b34"
2605 "ed9c3ff999b801597d5220e307eaa5bee507fb94d1fa69f9e519b2de315bac92c36f2ea1fa1df4478c0dde"
2606 "deae8c70e0233cd098040cd796b02c370f1fa4cc0124f1302e0201033029a1083106020100020101a20302"
2607 "0120a30402020100a4053103020101a6053103020140bf83770205000420ccd540855f833a5e1480bfd2d3"
2608 "6faf3aeee15df5beabe2691bc82dde2a7aa910041064c9f689c60ff6223ab6e6999e0eb6e5");
2609
2610auto wrapped_key_masked = hex2str(
2611 "3082017902010004820100aad93ed5924f283b4bb5526fbe7a1412f9d9749ec30db9062b29e574a8546f33"
2612 "c88732452f5b8e6a391ee76c39ed1712c61d8df6213dec1cffbc17a8c6d04c7b30893d8daa9b2015213e21"
2613 "946821553207f8f9931c4caba23ed3bee28b36947e47f10e0a5c3dc51c988a628daad3e5e1f4005e79c2d5"
2614 "a96c284b4b8d7e4948f331e5b85dd5a236f85579f3ea1d1b848487470bdb0ab4f81a12bee42c99fe0df4be"
2615 "e3759453e69ad1d68a809ce06b949f7694a990429b2fe81e066ff43e56a21602db70757922a4bcc23ab89f"
2616 "1e35da77586775f423e519c2ea394caf48a28d0c8020f1dcf6b3a68ec246f615ae96dae9a079b1f6eb9590"
2617 "33c1af5c125fd94168040c6d9721d08589581ab49204a3302e0201033029a1083106020100020101a20302"
2618 "0120a30402020100a4053103020101a6053103020140bf83770205000420a61c6e247e25b3e6e69aa78eb0"
2619 "3c2d4ac20d1f99a9a024a76f35c8e2cab9b68d04102560c70109ae67c030f00b98b512a670");
2620
2621auto wrapping_key = hex2str(
2622 "308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100aec367931d"
2623 "8900ce56b0067f7d70e1fc653f3f34d194c1fed50018fb43db937b06e673a837313d56b1c725150a3fef86"
2624 "acbddc41bb759c2854eae32d35841efb5c18d82bc90a1cb5c1d55adf245b02911f0b7cda88c421ff0ebafe"
2625 "7c0d23be312d7bd5921ffaea1347c157406fef718f682643e4e5d33c6703d61c0cf7ac0bf4645c11f5c137"
2626 "4c3886427411c449796792e0bef75dec858a2123c36753e02a95a96d7c454b504de385a642e0dfc3e60ac3"
2627 "a7ee4991d0d48b0172a95f9536f02ba13cecccb92b727db5c27e5b2f5cec09600b286af5cf14c42024c61d"
2628 "dfe71c2a8d7458f185234cb00e01d282f10f8fc6721d2aed3f4833cca2bd8fa62821dd5502030100010282"
2629 "0100431447b6251908112b1ee76f99f3711a52b6630960046c2de70de188d833f8b8b91e4d785caeeeaf4f"
2630 "0f74414e2cda40641f7fe24f14c67a88959bdb27766df9e710b630a03adc683b5d2c43080e52bee71e9eae"
2631 "b6de297a5fea1072070d181c822bccff087d63c940ba8a45f670feb29fb4484d1c95e6d2579ba02aae0a00"
2632 "900c3ebf490e3d2cd7ee8d0e20c536e4dc5a5097272888cddd7e91f228b1c4d7474c55b8fcd618c4a957bb"
2633 "ddd5ad7407cc312d8d98a5caf7e08f4a0d6b45bb41c652659d5a5ba05b663737a8696281865ba20fbdd7f8"
2634 "51e6c56e8cbe0ddbbf24dc03b2d2cb4c3d540fb0af52e034a2d06698b128e5f101e3b51a34f8d8b4f86181"
2635 "02818100de392e18d682c829266cc3454e1d6166242f32d9a1d10577753e904ea7d08bff841be5bac82a16"
2636 "4c5970007047b8c517db8f8f84e37bd5988561bdf503d4dc2bdb38f885434ae42c355f725c9a60f91f0788"
2637 "e1f1a97223b524b5357fdf72e2f696bab7d78e32bf92ba8e1864eab1229e91346130748a6e3c124f9149d7"
2638 "1c743502818100c95387c0f9d35f137b57d0d65c397c5e21cc251e47008ed62a542409c8b6b6ac7f8967b3"
2639 "863ca645fcce49582a9aa17349db6c4a95affdae0dae612e1afac99ed39a2d934c880440aed8832f984316"
2640 "3a47f27f392199dc1202f9a0f9bd08308007cb1e4e7f58309366a7de25f7c3c9b880677c068e1be936e812"
2641 "88815252a8a102818057ff8ca1895080b2cae486ef0adfd791fb0235c0b8b36cd6c136e52e4085f4ea5a06"
2642 "3212a4f105a3764743e53281988aba073f6e0027298e1c4378556e0efca0e14ece1af76ad0b030f27af6f0"
2643 "ab35fb73a060d8b1a0e142fa2647e93b32e36d8282ae0a4de50ab7afe85500a16f43a64719d6e2b9439823"
2644 "719cd08bcd03178102818100ba73b0bb28e3f81e9bd1c568713b101241acc607976c4ddccc90e65b6556ca"
2645 "31516058f92b6e09f3b160ff0e374ec40d78ae4d4979fde6ac06a1a400c61dd31254186af30b22c10582a8"
2646 "a43e34fe949c5f3b9755bae7baa7b7b7a6bd03b38cef55c86885fc6c1978b9cee7ef33da507c9df6b9277c"
2647 "ff1e6aaa5d57aca528466102818100c931617c77829dfb1270502be9195c8f2830885f57dba869536811e6"
2648 "864236d0c4736a0008a145af36b8357a7c3d139966d04c4e00934ea1aede3bb6b8ec841dc95e3f579751e2"
2649 "bfdfe27ae778983f959356210723287b0affcc9f727044d48c373f1babde0724fa17a4fd4da0902c7c9b9b"
2650 "f27ba61be6ad02dfddda8f4e6822");
2651
2652string zero_masking_key =
2653 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
2654string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
2655
2656class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
2657
2658TEST_P(ImportWrappedKeyTest, Success) {
2659 auto wrapping_key_desc = AuthorizationSetBuilder()
2660 .RsaEncryptionKey(2048, 65537)
2661 .Digest(Digest::SHA_2_256)
2662 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002663 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
2664 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002665
2666 ASSERT_EQ(ErrorCode::OK,
2667 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
2668 AuthorizationSetBuilder()
2669 .Digest(Digest::SHA_2_256)
2670 .Padding(PaddingMode::RSA_OAEP)));
2671
2672 string message = "Hello World!";
2673 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2674 string ciphertext = EncryptMessage(message, params);
2675 string plaintext = DecryptMessage(ciphertext, params);
2676 EXPECT_EQ(message, plaintext);
2677}
2678
2679TEST_P(ImportWrappedKeyTest, SuccessMasked) {
2680 auto wrapping_key_desc = AuthorizationSetBuilder()
2681 .RsaEncryptionKey(2048, 65537)
2682 .Digest(Digest::SHA_2_256)
2683 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002684 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
2685 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002686
2687 ASSERT_EQ(ErrorCode::OK,
2688 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
2689 AuthorizationSetBuilder()
2690 .Digest(Digest::SHA_2_256)
2691 .Padding(PaddingMode::RSA_OAEP)));
2692}
2693
2694TEST_P(ImportWrappedKeyTest, WrongMask) {
2695 auto wrapping_key_desc = AuthorizationSetBuilder()
2696 .RsaEncryptionKey(2048, 65537)
2697 .Digest(Digest::SHA_2_256)
2698 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002699 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
2700 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002701
2702 ASSERT_EQ(
2703 ErrorCode::VERIFICATION_FAILED,
2704 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
2705 AuthorizationSetBuilder()
2706 .Digest(Digest::SHA_2_256)
2707 .Padding(PaddingMode::RSA_OAEP)));
2708}
2709
2710TEST_P(ImportWrappedKeyTest, WrongPurpose) {
2711 auto wrapping_key_desc = AuthorizationSetBuilder()
2712 .RsaEncryptionKey(2048, 65537)
2713 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002714 .Padding(PaddingMode::RSA_OAEP)
2715 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002716
2717 ASSERT_EQ(
2718 ErrorCode::INCOMPATIBLE_PURPOSE,
2719 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
2720 AuthorizationSetBuilder()
2721 .Digest(Digest::SHA_2_256)
2722 .Padding(PaddingMode::RSA_OAEP)));
2723}
2724
2725INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
2726
2727typedef KeyMintAidlTestBase EncryptionOperationsTest;
2728
2729/*
2730 * EncryptionOperationsTest.RsaNoPaddingSuccess
2731 *
2732 * Verifies that raw RSA encryption works.
2733 */
2734TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
2735 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2736 .Authorization(TAG_NO_AUTH_REQUIRED)
2737 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002738 .Padding(PaddingMode::NONE)
2739 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002740
2741 string message = string(2048 / 8, 'a');
2742 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2743 string ciphertext1 = EncryptMessage(message, params);
2744 EXPECT_EQ(2048U / 8, ciphertext1.size());
2745
2746 string ciphertext2 = EncryptMessage(message, params);
2747 EXPECT_EQ(2048U / 8, ciphertext2.size());
2748
2749 // Unpadded RSA is deterministic
2750 EXPECT_EQ(ciphertext1, ciphertext2);
2751}
2752
2753/*
2754 * EncryptionOperationsTest.RsaNoPaddingShortMessage
2755 *
2756 * Verifies that raw RSA encryption of short messages works.
2757 */
2758TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
2759 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2760 .Authorization(TAG_NO_AUTH_REQUIRED)
2761 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002762 .Padding(PaddingMode::NONE)
2763 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002764
2765 string message = "1";
2766 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2767
2768 string ciphertext = EncryptMessage(message, params);
2769 EXPECT_EQ(2048U / 8, ciphertext.size());
2770
2771 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
2772 string plaintext = DecryptMessage(ciphertext, params);
2773
2774 EXPECT_EQ(expected_plaintext, plaintext);
2775
2776 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
2777 message = static_cast<char>(1);
2778 ciphertext = EncryptMessage(message, params);
2779 EXPECT_EQ(2048U / 8, ciphertext.size());
2780 EXPECT_EQ(ciphertext, string(2048U / 8 - 1, 0) + message);
2781}
2782
2783/*
2784 * EncryptionOperationsTest.RsaNoPaddingTooLong
2785 *
2786 * Verifies that raw RSA encryption of too-long messages fails in the expected way.
2787 */
2788TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
2789 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2790 .Authorization(TAG_NO_AUTH_REQUIRED)
2791 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002792 .Padding(PaddingMode::NONE)
2793 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002794
2795 string message(2048 / 8 + 1, 'a');
2796
2797 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2798 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2799
2800 string result;
2801 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
2802}
2803
2804/*
2805 * EncryptionOperationsTest.RsaNoPaddingTooLarge
2806 *
2807 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected
2808 * way.
2809 */
2810// TODO(seleneh) add RsaNoPaddingTooLarge test back after decided and implemented new
2811// version of ExportKey inside generateKey
2812
2813/*
2814 * EncryptionOperationsTest.RsaOaepSuccess
2815 *
2816 * Verifies that RSA-OAEP encryption operations work, with all digests.
2817 */
2818TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
2819 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
2820
2821 size_t key_size = 2048; // Need largish key for SHA-512 test.
2822 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2823 .Authorization(TAG_NO_AUTH_REQUIRED)
2824 .RsaEncryptionKey(key_size, 65537)
2825 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002826 .Digest(digests)
2827 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002828
2829 string message = "Hello";
2830
2831 for (auto digest : digests) {
2832 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
2833 string ciphertext1 = EncryptMessage(message, params);
2834 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
2835 EXPECT_EQ(key_size / 8, ciphertext1.size());
2836
2837 string ciphertext2 = EncryptMessage(message, params);
2838 EXPECT_EQ(key_size / 8, ciphertext2.size());
2839
2840 // OAEP randomizes padding so every result should be different (with astronomically high
2841 // probability).
2842 EXPECT_NE(ciphertext1, ciphertext2);
2843
2844 string plaintext1 = DecryptMessage(ciphertext1, params);
2845 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
2846 string plaintext2 = DecryptMessage(ciphertext2, params);
2847 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
2848
2849 // Decrypting corrupted ciphertext should fail.
2850 size_t offset_to_corrupt = random() % ciphertext1.size();
2851 char corrupt_byte;
2852 do {
2853 corrupt_byte = static_cast<char>(random() % 256);
2854 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2855 ciphertext1[offset_to_corrupt] = corrupt_byte;
2856
2857 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2858 string result;
2859 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2860 EXPECT_EQ(0U, result.size());
2861 }
2862}
2863
2864/*
2865 * EncryptionOperationsTest.RsaOaepInvalidDigest
2866 *
2867 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2868 * without a digest.
2869 */
2870TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
2871 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2872 .Authorization(TAG_NO_AUTH_REQUIRED)
2873 .RsaEncryptionKey(2048, 65537)
2874 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002875 .Digest(Digest::NONE)
2876 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002877 string message = "Hello World!";
2878
2879 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
2880 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2881}
2882
2883/*
2884 * EncryptionOperationsTest.RsaOaepInvalidDigest
2885 *
2886 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt
2887 * with a different digest than was used to encrypt.
2888 */
2889TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
2890 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2891
2892 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2893 .Authorization(TAG_NO_AUTH_REQUIRED)
2894 .RsaEncryptionKey(1024, 65537)
2895 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002896 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
2897 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002898 string message = "Hello World!";
2899 string ciphertext = EncryptMessage(
2900 message,
2901 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
2902
2903 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
2904 .Digest(Digest::SHA_2_256)
2905 .Padding(PaddingMode::RSA_OAEP)));
2906 string result;
2907 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
2908 EXPECT_EQ(0U, result.size());
2909}
2910
2911/*
2912 * EncryptionOperationsTest.RsaOaepTooLarge
2913 *
2914 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
2915 * too-large message.
2916 */
2917TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
2918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2919 .Authorization(TAG_NO_AUTH_REQUIRED)
2920 .RsaEncryptionKey(2048, 65537)
2921 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002922 .Digest(Digest::SHA_2_256)
2923 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002924 constexpr size_t digest_size = 256 /* SHA_2_256 */ / 8;
2925 constexpr size_t oaep_overhead = 2 * digest_size + 2;
2926 string message(2048 / 8 - oaep_overhead + 1, 'a');
2927 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
2928 .Padding(PaddingMode::RSA_OAEP)
2929 .Digest(Digest::SHA_2_256)));
2930 string result;
2931 ErrorCode error = Finish(message, &result);
2932 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2933 EXPECT_EQ(0U, result.size());
2934}
2935
2936/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002937 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
2938 *
2939 * Verifies that RSA-OAEP encryption operations work, with all SHA 256 digests and all type of MGF1
2940 * digests.
2941 */
2942TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
2943 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
2944
2945 size_t key_size = 2048; // Need largish key for SHA-512 test.
2946 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2947 .OaepMGFDigest(digests)
2948 .Authorization(TAG_NO_AUTH_REQUIRED)
2949 .RsaEncryptionKey(key_size, 65537)
2950 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002951 .Digest(Digest::SHA_2_256)
2952 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002953
2954 string message = "Hello";
2955
2956 for (auto digest : digests) {
2957 auto params = AuthorizationSetBuilder()
2958 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
2959 .Digest(Digest::SHA_2_256)
2960 .Padding(PaddingMode::RSA_OAEP);
2961 string ciphertext1 = EncryptMessage(message, params);
2962 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
2963 EXPECT_EQ(key_size / 8, ciphertext1.size());
2964
2965 string ciphertext2 = EncryptMessage(message, params);
2966 EXPECT_EQ(key_size / 8, ciphertext2.size());
2967
2968 // OAEP randomizes padding so every result should be different (with astronomically high
2969 // probability).
2970 EXPECT_NE(ciphertext1, ciphertext2);
2971
2972 string plaintext1 = DecryptMessage(ciphertext1, params);
2973 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
2974 string plaintext2 = DecryptMessage(ciphertext2, params);
2975 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
2976
2977 // Decrypting corrupted ciphertext should fail.
2978 size_t offset_to_corrupt = random() % ciphertext1.size();
2979 char corrupt_byte;
2980 do {
2981 corrupt_byte = static_cast<char>(random() % 256);
2982 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2983 ciphertext1[offset_to_corrupt] = corrupt_byte;
2984
2985 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2986 string result;
2987 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2988 EXPECT_EQ(0U, result.size());
2989 }
2990}
2991
2992/*
2993 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
2994 *
2995 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2996 * with incompatible MGF digest.
2997 */
2998TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
2999 ASSERT_EQ(ErrorCode::OK,
3000 GenerateKey(AuthorizationSetBuilder()
3001 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3002 .Authorization(TAG_NO_AUTH_REQUIRED)
3003 .RsaEncryptionKey(2048, 65537)
3004 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003005 .Digest(Digest::SHA_2_256)
3006 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003007 string message = "Hello World!";
3008
3009 auto params = AuthorizationSetBuilder()
3010 .Padding(PaddingMode::RSA_OAEP)
3011 .Digest(Digest::SHA_2_256)
3012 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
3013 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3014}
3015
3016/*
3017 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
3018 *
3019 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
3020 * with unsupported MGF digest.
3021 */
3022TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
3023 ASSERT_EQ(ErrorCode::OK,
3024 GenerateKey(AuthorizationSetBuilder()
3025 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3026 .Authorization(TAG_NO_AUTH_REQUIRED)
3027 .RsaEncryptionKey(2048, 65537)
3028 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003029 .Digest(Digest::SHA_2_256)
3030 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003031 string message = "Hello World!";
3032
3033 auto params = AuthorizationSetBuilder()
3034 .Padding(PaddingMode::RSA_OAEP)
3035 .Digest(Digest::SHA_2_256)
3036 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
3037 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
3038}
3039
3040/*
Selene Huang31ab4042020-04-29 04:22:39 -07003041 * EncryptionOperationsTest.RsaPkcs1Success
3042 *
3043 * Verifies that RSA PKCS encryption/decrypts works.
3044 */
3045TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
3046 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3047 .Authorization(TAG_NO_AUTH_REQUIRED)
3048 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003049 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
3050 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003051
3052 string message = "Hello World!";
3053 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
3054 string ciphertext1 = EncryptMessage(message, params);
3055 EXPECT_EQ(2048U / 8, ciphertext1.size());
3056
3057 string ciphertext2 = EncryptMessage(message, params);
3058 EXPECT_EQ(2048U / 8, ciphertext2.size());
3059
3060 // PKCS1 v1.5 randomizes padding so every result should be different.
3061 EXPECT_NE(ciphertext1, ciphertext2);
3062
3063 string plaintext = DecryptMessage(ciphertext1, params);
3064 EXPECT_EQ(message, plaintext);
3065
3066 // Decrypting corrupted ciphertext should fail.
3067 size_t offset_to_corrupt = random() % ciphertext1.size();
3068 char corrupt_byte;
3069 do {
3070 corrupt_byte = static_cast<char>(random() % 256);
3071 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3072 ciphertext1[offset_to_corrupt] = corrupt_byte;
3073
3074 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3075 string result;
3076 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3077 EXPECT_EQ(0U, result.size());
3078}
3079
3080/*
3081 * EncryptionOperationsTest.RsaPkcs1TooLarge
3082 *
3083 * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large.
3084 */
3085TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
3086 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3087 .Authorization(TAG_NO_AUTH_REQUIRED)
3088 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003089 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
3090 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003091 string message(2048 / 8 - 10, 'a');
3092
3093 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
3094 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3095 string result;
3096 ErrorCode error = Finish(message, &result);
3097 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
3098 EXPECT_EQ(0U, result.size());
3099}
3100
3101/*
3102 * EncryptionOperationsTest.EcdsaEncrypt
3103 *
3104 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
3105 */
3106TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
3107 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3108 .Authorization(TAG_NO_AUTH_REQUIRED)
3109 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003110 .Digest(Digest::NONE)
3111 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003112 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3113 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
3114 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
3115}
3116
3117/*
3118 * EncryptionOperationsTest.HmacEncrypt
3119 *
3120 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
3121 */
3122TEST_P(EncryptionOperationsTest, HmacEncrypt) {
3123 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3124 .Authorization(TAG_NO_AUTH_REQUIRED)
3125 .HmacKey(128)
3126 .Digest(Digest::SHA_2_256)
3127 .Padding(PaddingMode::NONE)
3128 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3129 auto params = AuthorizationSetBuilder()
3130 .Digest(Digest::SHA_2_256)
3131 .Padding(PaddingMode::NONE)
3132 .Authorization(TAG_MAC_LENGTH, 128);
3133 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
3134 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
3135}
3136
3137/*
3138 * EncryptionOperationsTest.AesEcbRoundTripSuccess
3139 *
3140 * Verifies that AES ECB mode works.
3141 */
3142TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
3143 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3144 .Authorization(TAG_NO_AUTH_REQUIRED)
3145 .AesEncryptionKey(128)
3146 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3147 .Padding(PaddingMode::NONE)));
3148
3149 ASSERT_GT(key_blob_.size(), 0U);
3150 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3151
3152 // Two-block message.
3153 string message = "12345678901234567890123456789012";
3154 string ciphertext1 = EncryptMessage(message, params);
3155 EXPECT_EQ(message.size(), ciphertext1.size());
3156
3157 string ciphertext2 = EncryptMessage(string(message), params);
3158 EXPECT_EQ(message.size(), ciphertext2.size());
3159
3160 // ECB is deterministic.
3161 EXPECT_EQ(ciphertext1, ciphertext2);
3162
3163 string plaintext = DecryptMessage(ciphertext1, params);
3164 EXPECT_EQ(message, plaintext);
3165}
3166
3167/*
3168 * EncryptionOperationsTest.AesEcbRoundTripSuccess
3169 *
3170 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
3171 */
3172TEST_P(EncryptionOperationsTest, AesWrongMode) {
3173 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3174 .Authorization(TAG_NO_AUTH_REQUIRED)
3175 .AesEncryptionKey(128)
3176 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3177 .Padding(PaddingMode::NONE)));
3178
3179 ASSERT_GT(key_blob_.size(), 0U);
3180
3181 // Two-block message.
3182 string message = "12345678901234567890123456789012";
3183 EXPECT_EQ(
3184 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
3185 Begin(KeyPurpose::ENCRYPT,
3186 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
3187}
3188
3189/*
3190 * EncryptionOperationsTest.AesWrongPurpose
3191 *
3192 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
3193 * specified.
3194 */
3195TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
3196 auto err = GenerateKey(AuthorizationSetBuilder()
3197 .Authorization(TAG_NO_AUTH_REQUIRED)
3198 .AesKey(128)
3199 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
3200 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3201 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3202 .Padding(PaddingMode::NONE));
3203 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
3204 ASSERT_GT(key_blob_.size(), 0U);
3205
3206 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3207 .BlockMode(BlockMode::GCM)
3208 .Padding(PaddingMode::NONE)
3209 .Authorization(TAG_MAC_LENGTH, 128));
3210 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
3211
3212 CheckedDeleteKey();
3213
3214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3215 .Authorization(TAG_NO_AUTH_REQUIRED)
3216 .AesKey(128)
3217 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
3218 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3219 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3220 .Padding(PaddingMode::NONE)));
3221
3222 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
3223 .BlockMode(BlockMode::GCM)
3224 .Padding(PaddingMode::NONE)
3225 .Authorization(TAG_MAC_LENGTH, 128));
3226 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
3227}
3228
3229/*
3230 * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize
3231 *
3232 * Verifies that AES encryption fails in the correct way when provided an input that is not a
3233 * multiple of the block size and no padding is specified.
3234 */
3235TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
3236 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3237 .Authorization(TAG_NO_AUTH_REQUIRED)
3238 .AesEncryptionKey(128)
3239 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3240 .Padding(PaddingMode::NONE)));
3241 // Message is slightly shorter than two blocks.
3242 string message(16 * 2 - 1, 'a');
3243
3244 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3245 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
3246 string ciphertext;
3247 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
3248 EXPECT_EQ(0U, ciphertext.size());
3249}
3250
3251/*
3252 * EncryptionOperationsTest.AesEcbPkcs7Padding
3253 *
3254 * Verifies that AES PKCS7 padding works for any message length.
3255 */
3256TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
3257 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3258 .Authorization(TAG_NO_AUTH_REQUIRED)
3259 .AesEncryptionKey(128)
3260 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3261 .Padding(PaddingMode::PKCS7)));
3262
3263 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3264
3265 // Try various message lengths; all should work.
3266 for (size_t i = 0; i < 32; ++i) {
3267 string message(i, 'a');
3268 string ciphertext = EncryptMessage(message, params);
3269 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
3270 string plaintext = DecryptMessage(ciphertext, params);
3271 EXPECT_EQ(message, plaintext);
3272 }
3273}
3274
3275/*
3276 * EncryptionOperationsTest.AesEcbWrongPadding
3277 *
3278 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
3279 * specified.
3280 */
3281TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
3282 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3283 .Authorization(TAG_NO_AUTH_REQUIRED)
3284 .AesEncryptionKey(128)
3285 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3286 .Padding(PaddingMode::NONE)));
3287
3288 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3289
3290 // Try various message lengths; all should fail
3291 for (size_t i = 0; i < 32; ++i) {
3292 string message(i, 'a');
3293 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3294 }
3295}
3296
3297/*
3298 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
3299 *
3300 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
3301 */
3302TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
3303 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3304 .Authorization(TAG_NO_AUTH_REQUIRED)
3305 .AesEncryptionKey(128)
3306 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
3307 .Padding(PaddingMode::PKCS7)));
3308
3309 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3310
3311 string message = "a";
3312 string ciphertext = EncryptMessage(message, params);
3313 EXPECT_EQ(16U, ciphertext.size());
3314 EXPECT_NE(ciphertext, message);
3315 ++ciphertext[ciphertext.size() / 2];
3316
3317 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3318 string plaintext;
3319 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
3320}
3321
3322vector<uint8_t> CopyIv(const AuthorizationSet& set) {
3323 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003324 EXPECT_TRUE(iv);
3325 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07003326}
3327
3328/*
3329 * EncryptionOperationsTest.AesCtrRoundTripSuccess
3330 *
3331 * Verifies that AES CTR mode works.
3332 */
3333TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
3334 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3335 .Authorization(TAG_NO_AUTH_REQUIRED)
3336 .AesEncryptionKey(128)
3337 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3338 .Padding(PaddingMode::NONE)));
3339
3340 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3341
3342 string message = "123";
3343 AuthorizationSet out_params;
3344 string ciphertext1 = EncryptMessage(message, params, &out_params);
3345 vector<uint8_t> iv1 = CopyIv(out_params);
3346 EXPECT_EQ(16U, iv1.size());
3347
3348 EXPECT_EQ(message.size(), ciphertext1.size());
3349
3350 out_params.Clear();
3351 string ciphertext2 = EncryptMessage(message, params, &out_params);
3352 vector<uint8_t> iv2 = CopyIv(out_params);
3353 EXPECT_EQ(16U, iv2.size());
3354
3355 // IVs should be random, so ciphertexts should differ.
3356 EXPECT_NE(ciphertext1, ciphertext2);
3357
3358 auto params_iv1 =
3359 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
3360 auto params_iv2 =
3361 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
3362
3363 string plaintext = DecryptMessage(ciphertext1, params_iv1);
3364 EXPECT_EQ(message, plaintext);
3365 plaintext = DecryptMessage(ciphertext2, params_iv2);
3366 EXPECT_EQ(message, plaintext);
3367
3368 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
3369 plaintext = DecryptMessage(ciphertext1, params_iv2);
3370 EXPECT_NE(message, plaintext);
3371 plaintext = DecryptMessage(ciphertext2, params_iv1);
3372 EXPECT_NE(message, plaintext);
3373}
3374
3375/*
3376 * EncryptionOperationsTest.AesIncremental
3377 *
3378 * Verifies that AES works, all modes, when provided data in various size increments.
3379 */
3380TEST_P(EncryptionOperationsTest, AesIncremental) {
3381 auto block_modes = {
3382 BlockMode::ECB,
3383 BlockMode::CBC,
3384 BlockMode::CTR,
3385 BlockMode::GCM,
3386 };
3387
3388 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3389 .Authorization(TAG_NO_AUTH_REQUIRED)
3390 .AesEncryptionKey(128)
3391 .BlockMode(block_modes)
3392 .Padding(PaddingMode::NONE)
3393 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3394
3395 for (int increment = 1; increment <= 240; ++increment) {
3396 for (auto block_mode : block_modes) {
3397 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07003398 auto params =
3399 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
3400 if (block_mode == BlockMode::GCM) {
3401 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
3402 }
Selene Huang31ab4042020-04-29 04:22:39 -07003403
3404 AuthorizationSet output_params;
3405 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
3406
3407 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07003408 string to_send;
3409 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07003410 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003411 }
Shawn Willden92d79c02021-02-19 07:31:55 -07003412 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
3413 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07003414
3415 switch (block_mode) {
3416 case BlockMode::GCM:
3417 EXPECT_EQ(message.size() + 16, ciphertext.size());
3418 break;
3419 case BlockMode::CTR:
3420 EXPECT_EQ(message.size(), ciphertext.size());
3421 break;
3422 case BlockMode::CBC:
3423 case BlockMode::ECB:
3424 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
3425 break;
3426 }
3427
3428 auto iv = output_params.GetTagValue(TAG_NONCE);
3429 switch (block_mode) {
3430 case BlockMode::CBC:
3431 case BlockMode::GCM:
3432 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003433 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
3434 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
3435 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003436 break;
3437
3438 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003439 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07003440 break;
3441 }
3442
3443 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
3444 << "Decrypt begin() failed for block mode " << block_mode;
3445
3446 string plaintext;
3447 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07003448 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003449 }
3450 ErrorCode error = Finish(to_send, &plaintext);
3451 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
3452 << " and increment " << increment;
3453 if (error == ErrorCode::OK) {
3454 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
3455 << block_mode << " and increment " << increment;
3456 }
3457 }
3458 }
3459}
3460
3461struct AesCtrSp80038aTestVector {
3462 const char* key;
3463 const char* nonce;
3464 const char* plaintext;
3465 const char* ciphertext;
3466};
3467
3468// These test vectors are taken from
3469// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
3470static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
3471 // AES-128
3472 {
3473 "2b7e151628aed2a6abf7158809cf4f3c",
3474 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3475 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3476 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3477 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
3478 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
3479 },
3480 // AES-192
3481 {
3482 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
3483 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3484 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3485 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3486 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
3487 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
3488 },
3489 // AES-256
3490 {
3491 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
3492 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3493 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3494 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3495 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
3496 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
3497 },
3498};
3499
3500/*
3501 * EncryptionOperationsTest.AesCtrSp80038aTestVector
3502 *
3503 * Verifies AES CTR implementation against SP800-38A test vectors.
3504 */
3505TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
3506 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
3507 for (size_t i = 0; i < 3; i++) {
3508 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
3509 const string key = hex2str(test.key);
3510 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
3511 InvalidSizes.end())
3512 continue;
3513 const string nonce = hex2str(test.nonce);
3514 const string plaintext = hex2str(test.plaintext);
3515 const string ciphertext = hex2str(test.ciphertext);
3516 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
3517 }
3518}
3519
3520/*
3521 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
3522 *
3523 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
3524 */
3525TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
3526 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3527 .Authorization(TAG_NO_AUTH_REQUIRED)
3528 .AesEncryptionKey(128)
3529 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3530 .Padding(PaddingMode::PKCS7)));
3531 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3532 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3533}
3534
3535/*
3536 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3537 *
3538 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
3539 */
3540TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
3541 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3542 .Authorization(TAG_NO_AUTH_REQUIRED)
3543 .AesEncryptionKey(128)
3544 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3545 .Authorization(TAG_CALLER_NONCE)
3546 .Padding(PaddingMode::NONE)));
3547
3548 auto params = AuthorizationSetBuilder()
3549 .BlockMode(BlockMode::CTR)
3550 .Padding(PaddingMode::NONE)
3551 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
3552 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3553
3554 params = AuthorizationSetBuilder()
3555 .BlockMode(BlockMode::CTR)
3556 .Padding(PaddingMode::NONE)
3557 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
3558 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3559
3560 params = AuthorizationSetBuilder()
3561 .BlockMode(BlockMode::CTR)
3562 .Padding(PaddingMode::NONE)
3563 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
3564 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3565}
3566
3567/*
3568 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3569 *
3570 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
3571 */
3572TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
3573 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3574 .Authorization(TAG_NO_AUTH_REQUIRED)
3575 .AesEncryptionKey(128)
3576 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3577 .Padding(PaddingMode::NONE)));
3578 // Two-block message.
3579 string message = "12345678901234567890123456789012";
3580 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3581 AuthorizationSet out_params;
3582 string ciphertext1 = EncryptMessage(message, params, &out_params);
3583 vector<uint8_t> iv1 = CopyIv(out_params);
3584 EXPECT_EQ(message.size(), ciphertext1.size());
3585
3586 out_params.Clear();
3587
3588 string ciphertext2 = EncryptMessage(message, params, &out_params);
3589 vector<uint8_t> iv2 = CopyIv(out_params);
3590 EXPECT_EQ(message.size(), ciphertext2.size());
3591
3592 // IVs should be random, so ciphertexts should differ.
3593 EXPECT_NE(ciphertext1, ciphertext2);
3594
3595 params.push_back(TAG_NONCE, iv1);
3596 string plaintext = DecryptMessage(ciphertext1, params);
3597 EXPECT_EQ(message, plaintext);
3598}
3599
3600/*
3601 * EncryptionOperationsTest.AesCallerNonce
3602 *
3603 * Verifies that AES caller-provided nonces work correctly.
3604 */
3605TEST_P(EncryptionOperationsTest, AesCallerNonce) {
3606 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3607 .Authorization(TAG_NO_AUTH_REQUIRED)
3608 .AesEncryptionKey(128)
3609 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3610 .Authorization(TAG_CALLER_NONCE)
3611 .Padding(PaddingMode::NONE)));
3612
3613 string message = "12345678901234567890123456789012";
3614
3615 // Don't specify nonce, should get a random one.
3616 AuthorizationSetBuilder params =
3617 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3618 AuthorizationSet out_params;
3619 string ciphertext = EncryptMessage(message, params, &out_params);
3620 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003621 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07003622
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003623 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003624 string plaintext = DecryptMessage(ciphertext, params);
3625 EXPECT_EQ(message, plaintext);
3626
3627 // Now specify a nonce, should also work.
3628 params = AuthorizationSetBuilder()
3629 .BlockMode(BlockMode::CBC)
3630 .Padding(PaddingMode::NONE)
3631 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
3632 out_params.Clear();
3633 ciphertext = EncryptMessage(message, params, &out_params);
3634
3635 // Decrypt with correct nonce.
3636 plaintext = DecryptMessage(ciphertext, params);
3637 EXPECT_EQ(message, plaintext);
3638
3639 // Try with wrong nonce.
3640 params = AuthorizationSetBuilder()
3641 .BlockMode(BlockMode::CBC)
3642 .Padding(PaddingMode::NONE)
3643 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
3644 plaintext = DecryptMessage(ciphertext, params);
3645 EXPECT_NE(message, plaintext);
3646}
3647
3648/*
3649 * EncryptionOperationsTest.AesCallerNonceProhibited
3650 *
3651 * Verifies that caller-provided nonces are not permitted when not specified in the key
3652 * authorizations.
3653 */
3654TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
3655 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3656 .Authorization(TAG_NO_AUTH_REQUIRED)
3657 .AesEncryptionKey(128)
3658 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3659 .Padding(PaddingMode::NONE)));
3660
3661 string message = "12345678901234567890123456789012";
3662
3663 // Don't specify nonce, should get a random one.
3664 AuthorizationSetBuilder params =
3665 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3666 AuthorizationSet out_params;
3667 string ciphertext = EncryptMessage(message, params, &out_params);
3668 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003669 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07003670
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003671 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003672 string plaintext = DecryptMessage(ciphertext, params);
3673 EXPECT_EQ(message, plaintext);
3674
3675 // Now specify a nonce, should fail
3676 params = AuthorizationSetBuilder()
3677 .BlockMode(BlockMode::CBC)
3678 .Padding(PaddingMode::NONE)
3679 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
3680 out_params.Clear();
3681 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
3682}
3683
3684/*
3685 * EncryptionOperationsTest.AesGcmRoundTripSuccess
3686 *
3687 * Verifies that AES GCM mode works.
3688 */
3689TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
3690 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3691 .Authorization(TAG_NO_AUTH_REQUIRED)
3692 .AesEncryptionKey(128)
3693 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3694 .Padding(PaddingMode::NONE)
3695 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3696
3697 string aad = "foobar";
3698 string message = "123456789012345678901234567890123456";
3699
3700 auto begin_params = AuthorizationSetBuilder()
3701 .BlockMode(BlockMode::GCM)
3702 .Padding(PaddingMode::NONE)
3703 .Authorization(TAG_MAC_LENGTH, 128);
3704
Selene Huang31ab4042020-04-29 04:22:39 -07003705 // Encrypt
3706 AuthorizationSet begin_out_params;
3707 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3708 << "Begin encrypt";
3709 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003710 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
3711 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003712 ASSERT_EQ(ciphertext.length(), message.length() + 16);
3713
3714 // Grab nonce
3715 begin_params.push_back(begin_out_params);
3716
3717 // Decrypt.
3718 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07003719 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003720 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003721 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003722 EXPECT_EQ(message.length(), plaintext.length());
3723 EXPECT_EQ(message, plaintext);
3724}
3725
3726/*
3727 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
3728 *
3729 * Verifies that AES GCM mode works, even when there's a long delay
3730 * between operations.
3731 */
3732TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
3733 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3734 .Authorization(TAG_NO_AUTH_REQUIRED)
3735 .AesEncryptionKey(128)
3736 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3737 .Padding(PaddingMode::NONE)
3738 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3739
3740 string aad = "foobar";
3741 string message = "123456789012345678901234567890123456";
3742
3743 auto begin_params = AuthorizationSetBuilder()
3744 .BlockMode(BlockMode::GCM)
3745 .Padding(PaddingMode::NONE)
3746 .Authorization(TAG_MAC_LENGTH, 128);
3747
Selene Huang31ab4042020-04-29 04:22:39 -07003748 // Encrypt
3749 AuthorizationSet begin_out_params;
3750 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3751 << "Begin encrypt";
3752 string ciphertext;
3753 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07003754 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003755 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07003756 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003757
3758 ASSERT_EQ(ciphertext.length(), message.length() + 16);
3759
3760 // Grab nonce
3761 begin_params.push_back(begin_out_params);
3762
3763 // Decrypt.
3764 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
3765 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003766 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003767 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07003768 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003769 sleep(5);
3770 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
3771 EXPECT_EQ(message.length(), plaintext.length());
3772 EXPECT_EQ(message, plaintext);
3773}
3774
3775/*
3776 * EncryptionOperationsTest.AesGcmDifferentNonces
3777 *
3778 * Verifies that encrypting the same data with different nonces produces different outputs.
3779 */
3780TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
3781 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3782 .Authorization(TAG_NO_AUTH_REQUIRED)
3783 .AesEncryptionKey(128)
3784 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3785 .Padding(PaddingMode::NONE)
3786 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3787 .Authorization(TAG_CALLER_NONCE)));
3788
3789 string aad = "foobar";
3790 string message = "123456789012345678901234567890123456";
3791 string nonce1 = "000000000000";
3792 string nonce2 = "111111111111";
3793 string nonce3 = "222222222222";
3794
3795 string ciphertext1 =
3796 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
3797 string ciphertext2 =
3798 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
3799 string ciphertext3 =
3800 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
3801
3802 ASSERT_NE(ciphertext1, ciphertext2);
3803 ASSERT_NE(ciphertext1, ciphertext3);
3804 ASSERT_NE(ciphertext2, ciphertext3);
3805}
3806
3807/*
3808 * EncryptionOperationsTest.AesGcmTooShortTag
3809 *
3810 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
3811 */
3812TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
3813 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3814 .Authorization(TAG_NO_AUTH_REQUIRED)
3815 .AesEncryptionKey(128)
3816 .BlockMode(BlockMode::GCM)
3817 .Padding(PaddingMode::NONE)
3818 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3819 string message = "123456789012345678901234567890123456";
3820 auto params = AuthorizationSetBuilder()
3821 .BlockMode(BlockMode::GCM)
3822 .Padding(PaddingMode::NONE)
3823 .Authorization(TAG_MAC_LENGTH, 96);
3824
3825 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
3826}
3827
3828/*
3829 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
3830 *
3831 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
3832 */
3833TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
3834 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3835 .Authorization(TAG_NO_AUTH_REQUIRED)
3836 .AesEncryptionKey(128)
3837 .BlockMode(BlockMode::GCM)
3838 .Padding(PaddingMode::NONE)
3839 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3840 string aad = "foobar";
3841 string message = "123456789012345678901234567890123456";
3842 auto params = AuthorizationSetBuilder()
3843 .BlockMode(BlockMode::GCM)
3844 .Padding(PaddingMode::NONE)
3845 .Authorization(TAG_MAC_LENGTH, 128);
3846
Selene Huang31ab4042020-04-29 04:22:39 -07003847 // Encrypt
3848 AuthorizationSet begin_out_params;
3849 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3850 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003851 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07003852
3853 AuthorizationSet finish_out_params;
3854 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003855 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
3856 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003857
3858 params = AuthorizationSetBuilder()
3859 .Authorizations(begin_out_params)
3860 .BlockMode(BlockMode::GCM)
3861 .Padding(PaddingMode::NONE)
3862 .Authorization(TAG_MAC_LENGTH, 96);
3863
3864 // Decrypt.
3865 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
3866}
3867
3868/*
3869 * EncryptionOperationsTest.AesGcmCorruptKey
3870 *
3871 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
3872 */
3873TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
3874 const uint8_t nonce_bytes[] = {
3875 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
3876 };
3877 string nonce = make_string(nonce_bytes);
3878 const uint8_t ciphertext_bytes[] = {
3879 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
3880 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
3881 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
3882 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
3883 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
3884 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
3885 };
3886 string ciphertext = make_string(ciphertext_bytes);
3887
3888 auto params = AuthorizationSetBuilder()
3889 .BlockMode(BlockMode::GCM)
3890 .Padding(PaddingMode::NONE)
3891 .Authorization(TAG_MAC_LENGTH, 128)
3892 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
3893
3894 auto import_params = AuthorizationSetBuilder()
3895 .Authorization(TAG_NO_AUTH_REQUIRED)
3896 .AesEncryptionKey(128)
3897 .BlockMode(BlockMode::GCM)
3898 .Padding(PaddingMode::NONE)
3899 .Authorization(TAG_CALLER_NONCE)
3900 .Authorization(TAG_MIN_MAC_LENGTH, 128);
3901
3902 // Import correct key and decrypt
3903 const uint8_t key_bytes[] = {
3904 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
3905 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
3906 };
3907 string key = make_string(key_bytes);
3908 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3909 string plaintext = DecryptMessage(ciphertext, params);
3910 CheckedDeleteKey();
3911
3912 // Corrupt key and attempt to decrypt
3913 key[0] = 0;
3914 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3915 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3916 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
3917 CheckedDeleteKey();
3918}
3919
3920/*
3921 * EncryptionOperationsTest.AesGcmAadNoData
3922 *
3923 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
3924 * encrypt.
3925 */
3926TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
3927 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3928 .Authorization(TAG_NO_AUTH_REQUIRED)
3929 .AesEncryptionKey(128)
3930 .BlockMode(BlockMode::GCM)
3931 .Padding(PaddingMode::NONE)
3932 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3933
3934 string aad = "1234567890123456";
3935 auto params = AuthorizationSetBuilder()
3936 .BlockMode(BlockMode::GCM)
3937 .Padding(PaddingMode::NONE)
3938 .Authorization(TAG_MAC_LENGTH, 128);
3939
Selene Huang31ab4042020-04-29 04:22:39 -07003940 // Encrypt
3941 AuthorizationSet begin_out_params;
3942 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3943 string ciphertext;
3944 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07003945 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
3946 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003947 EXPECT_TRUE(finish_out_params.empty());
3948
3949 // Grab nonce
3950 params.push_back(begin_out_params);
3951
3952 // Decrypt.
3953 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003954 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003955 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003956 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003957
3958 EXPECT_TRUE(finish_out_params.empty());
3959
3960 EXPECT_EQ("", plaintext);
3961}
3962
3963/*
3964 * EncryptionOperationsTest.AesGcmMultiPartAad
3965 *
3966 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
3967 * chunks.
3968 */
3969TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
3970 const size_t tag_bits = 128;
3971 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3972 .Authorization(TAG_NO_AUTH_REQUIRED)
3973 .AesEncryptionKey(128)
3974 .BlockMode(BlockMode::GCM)
3975 .Padding(PaddingMode::NONE)
3976 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3977
3978 string message = "123456789012345678901234567890123456";
3979 auto begin_params = AuthorizationSetBuilder()
3980 .BlockMode(BlockMode::GCM)
3981 .Padding(PaddingMode::NONE)
3982 .Authorization(TAG_MAC_LENGTH, tag_bits);
3983 AuthorizationSet begin_out_params;
3984
Selene Huang31ab4042020-04-29 04:22:39 -07003985 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3986
3987 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07003988 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
3989 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07003990 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003991 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
3992 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003993
Selene Huang31ab4042020-04-29 04:22:39 -07003994 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07003995 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003996
3997 // Grab nonce.
3998 begin_params.push_back(begin_out_params);
3999
4000 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004001 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004002 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004003 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004004 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004005 EXPECT_EQ(message, plaintext);
4006}
4007
4008/*
4009 * EncryptionOperationsTest.AesGcmAadOutOfOrder
4010 *
4011 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
4012 */
4013TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
4014 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4015 .Authorization(TAG_NO_AUTH_REQUIRED)
4016 .AesEncryptionKey(128)
4017 .BlockMode(BlockMode::GCM)
4018 .Padding(PaddingMode::NONE)
4019 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4020
4021 string message = "123456789012345678901234567890123456";
4022 auto begin_params = AuthorizationSetBuilder()
4023 .BlockMode(BlockMode::GCM)
4024 .Padding(PaddingMode::NONE)
4025 .Authorization(TAG_MAC_LENGTH, 128);
4026 AuthorizationSet begin_out_params;
4027
Selene Huang31ab4042020-04-29 04:22:39 -07004028 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
4029
Shawn Willden92d79c02021-02-19 07:31:55 -07004030 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004031 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004032 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
4033 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004034
Shawn Willden92d79c02021-02-19 07:31:55 -07004035 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07004036}
4037
4038/*
4039 * EncryptionOperationsTest.AesGcmBadAad
4040 *
4041 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
4042 */
4043TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
4044 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4045 .Authorization(TAG_NO_AUTH_REQUIRED)
4046 .AesEncryptionKey(128)
4047 .BlockMode(BlockMode::GCM)
4048 .Padding(PaddingMode::NONE)
4049 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4050
4051 string message = "12345678901234567890123456789012";
4052 auto begin_params = AuthorizationSetBuilder()
4053 .BlockMode(BlockMode::GCM)
4054 .Padding(PaddingMode::NONE)
4055 .Authorization(TAG_MAC_LENGTH, 128);
4056
Selene Huang31ab4042020-04-29 04:22:39 -07004057 // Encrypt
4058 AuthorizationSet begin_out_params;
4059 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004060 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004061 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004062 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004063
4064 // Grab nonce
4065 begin_params.push_back(begin_out_params);
4066
Selene Huang31ab4042020-04-29 04:22:39 -07004067 // Decrypt.
4068 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004069 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07004070 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004071 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004072}
4073
4074/*
4075 * EncryptionOperationsTest.AesGcmWrongNonce
4076 *
4077 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
4078 */
4079TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
4080 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4081 .Authorization(TAG_NO_AUTH_REQUIRED)
4082 .AesEncryptionKey(128)
4083 .BlockMode(BlockMode::GCM)
4084 .Padding(PaddingMode::NONE)
4085 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4086
4087 string message = "12345678901234567890123456789012";
4088 auto begin_params = AuthorizationSetBuilder()
4089 .BlockMode(BlockMode::GCM)
4090 .Padding(PaddingMode::NONE)
4091 .Authorization(TAG_MAC_LENGTH, 128);
4092
Selene Huang31ab4042020-04-29 04:22:39 -07004093 // Encrypt
4094 AuthorizationSet begin_out_params;
4095 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004096 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004097 string ciphertext;
4098 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004099 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004100
4101 // Wrong nonce
4102 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
4103
4104 // Decrypt.
4105 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004106 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07004107 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004108 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004109
4110 // With wrong nonce, should have gotten garbage plaintext (or none).
4111 EXPECT_NE(message, plaintext);
4112}
4113
4114/*
4115 * EncryptionOperationsTest.AesGcmCorruptTag
4116 *
4117 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
4118 */
4119TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
4120 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4121 .Authorization(TAG_NO_AUTH_REQUIRED)
4122 .AesEncryptionKey(128)
4123 .BlockMode(BlockMode::GCM)
4124 .Padding(PaddingMode::NONE)
4125 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4126
4127 string aad = "1234567890123456";
4128 string message = "123456789012345678901234567890123456";
4129
4130 auto params = AuthorizationSetBuilder()
4131 .BlockMode(BlockMode::GCM)
4132 .Padding(PaddingMode::NONE)
4133 .Authorization(TAG_MAC_LENGTH, 128);
4134
Selene Huang31ab4042020-04-29 04:22:39 -07004135 // Encrypt
4136 AuthorizationSet begin_out_params;
4137 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004138 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004139 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004140 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004141
4142 // Corrupt tag
4143 ++(*ciphertext.rbegin());
4144
4145 // Grab nonce
4146 params.push_back(begin_out_params);
4147
4148 // Decrypt.
4149 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07004150 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004151 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004152 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004153}
4154
4155/*
4156 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
4157 *
4158 * Verifies that 3DES is basically functional.
4159 */
4160TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
4161 auto auths = AuthorizationSetBuilder()
4162 .TripleDesEncryptionKey(168)
4163 .BlockMode(BlockMode::ECB)
4164 .Authorization(TAG_NO_AUTH_REQUIRED)
4165 .Padding(PaddingMode::NONE);
4166
4167 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
4168 // Two-block message.
4169 string message = "1234567890123456";
4170 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4171 string ciphertext1 = EncryptMessage(message, inParams);
4172 EXPECT_EQ(message.size(), ciphertext1.size());
4173
4174 string ciphertext2 = EncryptMessage(string(message), inParams);
4175 EXPECT_EQ(message.size(), ciphertext2.size());
4176
4177 // ECB is deterministic.
4178 EXPECT_EQ(ciphertext1, ciphertext2);
4179
4180 string plaintext = DecryptMessage(ciphertext1, inParams);
4181 EXPECT_EQ(message, plaintext);
4182}
4183
4184/*
4185 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
4186 *
4187 * Verifies that CBC keys reject ECB usage.
4188 */
4189TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
4190 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4191 .TripleDesEncryptionKey(168)
4192 .BlockMode(BlockMode::CBC)
4193 .Authorization(TAG_NO_AUTH_REQUIRED)
4194 .Padding(PaddingMode::NONE)));
4195
4196 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4197 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
4198}
4199
4200/*
4201 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
4202 *
4203 * Tests ECB mode with PKCS#7 padding, various message sizes.
4204 */
4205TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
4206 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4207 .TripleDesEncryptionKey(168)
4208 .BlockMode(BlockMode::ECB)
4209 .Authorization(TAG_NO_AUTH_REQUIRED)
4210 .Padding(PaddingMode::PKCS7)));
4211
4212 for (size_t i = 0; i < 32; ++i) {
4213 string message(i, 'a');
4214 auto inParams =
4215 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4216 string ciphertext = EncryptMessage(message, inParams);
4217 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
4218 string plaintext = DecryptMessage(ciphertext, inParams);
4219 EXPECT_EQ(message, plaintext);
4220 }
4221}
4222
4223/*
4224 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
4225 *
4226 * Verifies that keys configured for no padding reject PKCS7 padding
4227 */
4228TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
4229 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4230 .TripleDesEncryptionKey(168)
4231 .BlockMode(BlockMode::ECB)
4232 .Authorization(TAG_NO_AUTH_REQUIRED)
4233 .Padding(PaddingMode::NONE)));
4234 for (size_t i = 0; i < 32; ++i) {
4235 auto inParams =
4236 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4237 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
4238 }
4239}
4240
4241/*
4242 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
4243 *
4244 * Verifies that corrupted padding is detected.
4245 */
4246TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
4247 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4248 .TripleDesEncryptionKey(168)
4249 .BlockMode(BlockMode::ECB)
4250 .Authorization(TAG_NO_AUTH_REQUIRED)
4251 .Padding(PaddingMode::PKCS7)));
4252
4253 string message = "a";
4254 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
4255 EXPECT_EQ(8U, ciphertext.size());
4256 EXPECT_NE(ciphertext, message);
4257 ++ciphertext[ciphertext.size() / 2];
4258
4259 AuthorizationSetBuilder begin_params;
4260 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
4261 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
4262 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4263 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004264 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004265 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4266}
4267
4268struct TripleDesTestVector {
4269 const char* name;
4270 const KeyPurpose purpose;
4271 const BlockMode block_mode;
4272 const PaddingMode padding_mode;
4273 const char* key;
4274 const char* iv;
4275 const char* input;
4276 const char* output;
4277};
4278
4279// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
4280// of the NIST vectors are multiples of the block size.
4281static const TripleDesTestVector kTripleDesTestVectors[] = {
4282 {
4283 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
4284 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
4285 "", // IV
4286 "329d86bdf1bc5af4", // input
4287 "d946c2756d78633f", // output
4288 },
4289 {
4290 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
4291 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
4292 "", // IV
4293 "6b1540781b01ce1997adae102dbf3c5b", // input
4294 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
4295 },
4296 {
4297 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
4298 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
4299 "", // IV
4300 "6daad94ce08acfe7", // input
4301 "660e7d32dcc90e79", // output
4302 },
4303 {
4304 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
4305 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
4306 "", // IV
4307 "e9653a0a1f05d31b9acd12d73aa9879d", // input
4308 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
4309 },
4310 {
4311 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
4312 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
4313 "43f791134c5647ba", // IV
4314 "dcc153cef81d6f24", // input
4315 "92538bd8af18d3ba", // output
4316 },
4317 {
4318 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
4319 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4320 "c2e999cb6249023c", // IV
4321 "c689aee38a301bb316da75db36f110b5", // input
4322 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
4323 },
4324 {
4325 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
4326 PaddingMode::PKCS7,
4327 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4328 "c2e999cb6249023c", // IV
4329 "c689aee38a301bb316da75db36f110b500", // input
4330 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
4331 },
4332 {
4333 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
4334 PaddingMode::PKCS7,
4335 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
4336 "c2e999cb6249023c", // IV
4337 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
4338 "c689aee38a301bb316da75db36f110b500", // output
4339 },
4340 {
4341 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
4342 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
4343 "41746c7e442d3681", // IV
4344 "c53a7b0ec40600fe", // input
4345 "d4f00eb455de1034", // output
4346 },
4347 {
4348 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
4349 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
4350 "3982bc02c3727d45", // IV
4351 "6006f10adef52991fcc777a1238bbb65", // input
4352 "edae09288e9e3bc05746d872b48e3b29", // output
4353 },
4354};
4355
4356/*
4357 * EncryptionOperationsTest.TripleDesTestVector
4358 *
4359 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
4360 */
4361TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
4362 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
4363 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
4364 SCOPED_TRACE(test->name);
4365 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
4366 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
4367 hex2str(test->output));
4368 }
4369}
4370
4371/*
4372 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
4373 *
4374 * Validates CBC mode functionality.
4375 */
4376TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
4377 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4378 .TripleDesEncryptionKey(168)
4379 .BlockMode(BlockMode::CBC)
4380 .Authorization(TAG_NO_AUTH_REQUIRED)
4381 .Padding(PaddingMode::NONE)));
4382
4383 ASSERT_GT(key_blob_.size(), 0U);
4384
4385 // Two-block message.
4386 string message = "1234567890123456";
4387 vector<uint8_t> iv1;
4388 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
4389 EXPECT_EQ(message.size(), ciphertext1.size());
4390
4391 vector<uint8_t> iv2;
4392 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
4393 EXPECT_EQ(message.size(), ciphertext2.size());
4394
4395 // IVs should be random, so ciphertexts should differ.
4396 EXPECT_NE(iv1, iv2);
4397 EXPECT_NE(ciphertext1, ciphertext2);
4398
4399 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
4400 EXPECT_EQ(message, plaintext);
4401}
4402
4403/*
4404 * EncryptionOperationsTest.TripleDesCallerIv
4405 *
4406 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
4407 */
4408TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
4409 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4410 .TripleDesEncryptionKey(168)
4411 .BlockMode(BlockMode::CBC)
4412 .Authorization(TAG_NO_AUTH_REQUIRED)
4413 .Authorization(TAG_CALLER_NONCE)
4414 .Padding(PaddingMode::NONE)));
4415 string message = "1234567890123456";
4416 vector<uint8_t> iv;
4417 // Don't specify IV, should get a random one.
4418 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
4419 EXPECT_EQ(message.size(), ciphertext1.size());
4420 EXPECT_EQ(8U, iv.size());
4421
4422 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
4423 EXPECT_EQ(message, plaintext);
4424
4425 // Now specify an IV, should also work.
4426 iv = AidlBuf("abcdefgh");
4427 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
4428
4429 // Decrypt with correct IV.
4430 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
4431 EXPECT_EQ(message, plaintext);
4432
4433 // Now try with wrong IV.
4434 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
4435 EXPECT_NE(message, plaintext);
4436}
4437
4438/*
4439 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
4440 *
4441 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVS.
4442 */
4443TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
4444 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4445 .TripleDesEncryptionKey(168)
4446 .BlockMode(BlockMode::CBC)
4447 .Authorization(TAG_NO_AUTH_REQUIRED)
4448 .Padding(PaddingMode::NONE)));
4449
4450 string message = "12345678901234567890123456789012";
4451 vector<uint8_t> iv;
4452 // Don't specify nonce, should get a random one.
4453 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
4454 EXPECT_EQ(message.size(), ciphertext1.size());
4455 EXPECT_EQ(8U, iv.size());
4456
4457 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
4458 EXPECT_EQ(message, plaintext);
4459
4460 // Now specify a nonce, should fail.
4461 auto input_params = AuthorizationSetBuilder()
4462 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
4463 .BlockMode(BlockMode::CBC)
4464 .Padding(PaddingMode::NONE);
4465 AuthorizationSet output_params;
4466 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
4467 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4468}
4469
4470/*
4471 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
4472 *
4473 * Verifies that 3DES ECB-only keys do not allow CBC usage.
4474 */
4475TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
4476 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4477 .TripleDesEncryptionKey(168)
4478 .BlockMode(BlockMode::ECB)
4479 .Authorization(TAG_NO_AUTH_REQUIRED)
4480 .Padding(PaddingMode::NONE)));
4481 // Two-block message.
4482 string message = "1234567890123456";
4483 auto begin_params =
4484 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4485 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4486}
4487
4488/*
4489 * EncryptionOperationsTest.TripleDesCbcNoPaddingWrongInputSize
4490 *
4491 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
4492 */
4493TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingWrongInputSize) {
4494 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4495 .TripleDesEncryptionKey(168)
4496 .BlockMode(BlockMode::CBC)
4497 .Authorization(TAG_NO_AUTH_REQUIRED)
4498 .Padding(PaddingMode::NONE)));
4499 // Message is slightly shorter than two blocks.
4500 string message = "123456789012345";
4501
4502 auto begin_params =
4503 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4504 AuthorizationSet output_params;
4505 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
4506 string ciphertext;
4507 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
4508}
4509
4510/*
4511 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
4512 *
4513 * Verifies that PKCS7 padding works correctly in CBC mode.
4514 */
4515TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
4516 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4517 .TripleDesEncryptionKey(168)
4518 .BlockMode(BlockMode::CBC)
4519 .Authorization(TAG_NO_AUTH_REQUIRED)
4520 .Padding(PaddingMode::PKCS7)));
4521
4522 // Try various message lengths; all should work.
4523 for (size_t i = 0; i < 32; ++i) {
4524 string message(i, 'a');
4525 vector<uint8_t> iv;
4526 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4527 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
4528 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
4529 EXPECT_EQ(message, plaintext);
4530 }
4531}
4532
4533/*
4534 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
4535 *
4536 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
4537 */
4538TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
4539 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4540 .TripleDesEncryptionKey(168)
4541 .BlockMode(BlockMode::CBC)
4542 .Authorization(TAG_NO_AUTH_REQUIRED)
4543 .Padding(PaddingMode::NONE)));
4544
4545 // Try various message lengths; all should fail.
4546 for (size_t i = 0; i < 32; ++i) {
4547 auto begin_params =
4548 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
4549 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4550 }
4551}
4552
4553/*
4554 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
4555 *
4556 * Verifies that corrupted PKCS7 padding is rejected during decryption.
4557 */
4558TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
4559 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4560 .TripleDesEncryptionKey(168)
4561 .BlockMode(BlockMode::CBC)
4562 .Authorization(TAG_NO_AUTH_REQUIRED)
4563 .Padding(PaddingMode::PKCS7)));
4564
4565 string message = "a";
4566 vector<uint8_t> iv;
4567 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4568 EXPECT_EQ(8U, ciphertext.size());
4569 EXPECT_NE(ciphertext, message);
4570 ++ciphertext[ciphertext.size() / 2];
4571
4572 auto begin_params = AuthorizationSetBuilder()
4573 .BlockMode(BlockMode::CBC)
4574 .Padding(PaddingMode::PKCS7)
4575 .Authorization(TAG_NONCE, iv);
4576 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4577 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004578 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004579 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4580}
4581
4582/*
4583 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
4584 *
4585 * Verifies that 3DES CBC works with many different input sizes.
4586 */
4587TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
4588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4589 .TripleDesEncryptionKey(168)
4590 .BlockMode(BlockMode::CBC)
4591 .Authorization(TAG_NO_AUTH_REQUIRED)
4592 .Padding(PaddingMode::NONE)));
4593
4594 int increment = 7;
4595 string message(240, 'a');
4596 AuthorizationSet input_params =
4597 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4598 AuthorizationSet output_params;
4599 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4600
4601 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004602 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07004603 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004604 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
4605 EXPECT_EQ(message.size(), ciphertext.size());
4606
4607 // Move TAG_NONCE into input_params
4608 input_params = output_params;
4609 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
4610 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
4611 output_params.Clear();
4612
4613 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
4614 string plaintext;
4615 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07004616 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004617 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
4618 EXPECT_EQ(ciphertext.size(), plaintext.size());
4619 EXPECT_EQ(message, plaintext);
4620}
4621
4622INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
4623
4624typedef KeyMintAidlTestBase MaxOperationsTest;
4625
4626/*
4627 * MaxOperationsTest.TestLimitAes
4628 *
4629 * Verifies that the max uses per boot tag works correctly with AES keys.
4630 */
4631TEST_P(MaxOperationsTest, TestLimitAes) {
4632 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4633
4634 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4635 .Authorization(TAG_NO_AUTH_REQUIRED)
4636 .AesEncryptionKey(128)
4637 .EcbMode()
4638 .Padding(PaddingMode::NONE)
4639 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
4640
4641 string message = "1234567890123456";
4642
4643 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4644
4645 EncryptMessage(message, params);
4646 EncryptMessage(message, params);
4647 EncryptMessage(message, params);
4648
4649 // Fourth time should fail.
4650 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
4651}
4652
4653/*
Qi Wud22ec842020-11-26 13:27:53 +08004654 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07004655 *
4656 * Verifies that the max uses per boot tag works correctly with RSA keys.
4657 */
4658TEST_P(MaxOperationsTest, TestLimitRsa) {
4659 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4660
4661 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4662 .Authorization(TAG_NO_AUTH_REQUIRED)
4663 .RsaSigningKey(1024, 65537)
4664 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08004665 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
4666 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004667
4668 string message = "1234567890123456";
4669
4670 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4671
4672 SignMessage(message, params);
4673 SignMessage(message, params);
4674 SignMessage(message, params);
4675
4676 // Fourth time should fail.
4677 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
4678}
4679
4680INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
4681
Qi Wud22ec842020-11-26 13:27:53 +08004682typedef KeyMintAidlTestBase UsageCountLimitTest;
4683
4684/*
Qi Wubeefae42021-01-28 23:16:37 +08004685 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08004686 *
Qi Wubeefae42021-01-28 23:16:37 +08004687 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08004688 */
Qi Wubeefae42021-01-28 23:16:37 +08004689TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08004690 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4691
4692 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4693 .Authorization(TAG_NO_AUTH_REQUIRED)
4694 .AesEncryptionKey(128)
4695 .EcbMode()
4696 .Padding(PaddingMode::NONE)
4697 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
4698
4699 // Check the usage count limit tag appears in the authorizations.
4700 AuthorizationSet auths;
4701 for (auto& entry : key_characteristics_) {
4702 auths.push_back(AuthorizationSet(entry.authorizations));
4703 }
4704 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
4705 << "key usage count limit " << 1U << " missing";
4706
4707 string message = "1234567890123456";
4708 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4709
Qi Wubeefae42021-01-28 23:16:37 +08004710 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4711 AuthorizationSet keystore_auths =
4712 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4713
Qi Wud22ec842020-11-26 13:27:53 +08004714 // First usage of AES key should work.
4715 EncryptMessage(message, params);
4716
Qi Wud22ec842020-11-26 13:27:53 +08004717 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
4718 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4719 // must be invalidated from secure storage (such as RPMB partition).
4720 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
4721 } else {
Qi Wubeefae42021-01-28 23:16:37 +08004722 // Usage count limit tag is enforced by keystore, keymint does nothing.
4723 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08004724 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
4725 }
4726}
4727
4728/*
Qi Wubeefae42021-01-28 23:16:37 +08004729 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08004730 *
Qi Wubeefae42021-01-28 23:16:37 +08004731 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08004732 */
Qi Wubeefae42021-01-28 23:16:37 +08004733TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
4734 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4735
4736 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4737 .Authorization(TAG_NO_AUTH_REQUIRED)
4738 .AesEncryptionKey(128)
4739 .EcbMode()
4740 .Padding(PaddingMode::NONE)
4741 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
4742
4743 // Check the usage count limit tag appears in the authorizations.
4744 AuthorizationSet auths;
4745 for (auto& entry : key_characteristics_) {
4746 auths.push_back(AuthorizationSet(entry.authorizations));
4747 }
4748 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
4749 << "key usage count limit " << 3U << " missing";
4750
4751 string message = "1234567890123456";
4752 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4753
4754 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4755 AuthorizationSet keystore_auths =
4756 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4757
4758 EncryptMessage(message, params);
4759 EncryptMessage(message, params);
4760 EncryptMessage(message, params);
4761
4762 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
4763 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4764 // must be invalidated from secure storage (such as RPMB partition).
4765 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
4766 } else {
4767 // Usage count limit tag is enforced by keystore, keymint does nothing.
4768 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
4769 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
4770 }
4771}
4772
4773/*
4774 * UsageCountLimitTest.TestSingleUseRsa
4775 *
4776 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
4777 */
4778TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08004779 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4780
4781 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4782 .Authorization(TAG_NO_AUTH_REQUIRED)
4783 .RsaSigningKey(1024, 65537)
4784 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08004785 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
4786 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08004787
4788 // Check the usage count limit tag appears in the authorizations.
4789 AuthorizationSet auths;
4790 for (auto& entry : key_characteristics_) {
4791 auths.push_back(AuthorizationSet(entry.authorizations));
4792 }
4793 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
4794 << "key usage count limit " << 1U << " missing";
4795
4796 string message = "1234567890123456";
4797 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4798
Qi Wubeefae42021-01-28 23:16:37 +08004799 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4800 AuthorizationSet keystore_auths =
4801 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4802
Qi Wud22ec842020-11-26 13:27:53 +08004803 // First usage of RSA key should work.
4804 SignMessage(message, params);
4805
Qi Wud22ec842020-11-26 13:27:53 +08004806 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
4807 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4808 // must be invalidated from secure storage (such as RPMB partition).
4809 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
4810 } else {
Qi Wubeefae42021-01-28 23:16:37 +08004811 // Usage count limit tag is enforced by keystore, keymint does nothing.
4812 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
4813 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
4814 }
4815}
4816
4817/*
4818 * UsageCountLimitTest.TestLimitUseRsa
4819 *
4820 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
4821 */
4822TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
4823 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4824
4825 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4826 .Authorization(TAG_NO_AUTH_REQUIRED)
4827 .RsaSigningKey(1024, 65537)
4828 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08004829 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
4830 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08004831
4832 // Check the usage count limit tag appears in the authorizations.
4833 AuthorizationSet auths;
4834 for (auto& entry : key_characteristics_) {
4835 auths.push_back(AuthorizationSet(entry.authorizations));
4836 }
4837 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
4838 << "key usage count limit " << 3U << " missing";
4839
4840 string message = "1234567890123456";
4841 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4842
4843 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4844 AuthorizationSet keystore_auths =
4845 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4846
4847 SignMessage(message, params);
4848 SignMessage(message, params);
4849 SignMessage(message, params);
4850
4851 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
4852 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4853 // must be invalidated from secure storage (such as RPMB partition).
4854 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
4855 } else {
4856 // Usage count limit tag is enforced by keystore, keymint does nothing.
4857 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08004858 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
4859 }
4860}
4861
Qi Wu8e727f72021-02-11 02:49:33 +08004862/*
4863 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
4864 *
4865 * Verifies that when rollback resistance is supported by the KeyMint implementation with
4866 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
4867 * in hardware.
4868 */
4869TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
4870 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4871
4872 auto error = GenerateKey(AuthorizationSetBuilder()
4873 .RsaSigningKey(2048, 65537)
4874 .Digest(Digest::NONE)
4875 .Padding(PaddingMode::NONE)
4876 .Authorization(TAG_NO_AUTH_REQUIRED)
4877 .Authorization(TAG_ROLLBACK_RESISTANCE)
4878 .SetDefaultValidity());
4879 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4880
4881 if (error == ErrorCode::OK) {
4882 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
4883 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
4884 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4885 ASSERT_EQ(ErrorCode::OK, DeleteKey());
4886
4887 // The KeyMint should also enforce single use key in hardware when it supports rollback
4888 // resistance.
4889 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4890 .Authorization(TAG_NO_AUTH_REQUIRED)
4891 .RsaSigningKey(1024, 65537)
4892 .NoDigestOrPadding()
4893 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
4894 .SetDefaultValidity()));
4895
4896 // Check the usage count limit tag appears in the hardware authorizations.
4897 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4898 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
4899 << "key usage count limit " << 1U << " missing";
4900
4901 string message = "1234567890123456";
4902 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4903
4904 // First usage of RSA key should work.
4905 SignMessage(message, params);
4906
4907 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4908 // must be invalidated from secure storage (such as RPMB partition).
4909 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
4910 }
4911}
4912
Qi Wud22ec842020-11-26 13:27:53 +08004913INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
4914
Selene Huang31ab4042020-04-29 04:22:39 -07004915typedef KeyMintAidlTestBase AddEntropyTest;
4916
4917/*
4918 * AddEntropyTest.AddEntropy
4919 *
4920 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
4921 * is actually added.
4922 */
4923TEST_P(AddEntropyTest, AddEntropy) {
4924 string data = "foo";
4925 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
4926}
4927
4928/*
4929 * AddEntropyTest.AddEmptyEntropy
4930 *
4931 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
4932 */
4933TEST_P(AddEntropyTest, AddEmptyEntropy) {
4934 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
4935}
4936
4937/*
4938 * AddEntropyTest.AddLargeEntropy
4939 *
4940 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
4941 */
4942TEST_P(AddEntropyTest, AddLargeEntropy) {
4943 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
4944}
4945
4946INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
4947
Selene Huang31ab4042020-04-29 04:22:39 -07004948typedef KeyMintAidlTestBase KeyDeletionTest;
4949
4950/**
4951 * KeyDeletionTest.DeleteKey
4952 *
4953 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
4954 * valid key blob.
4955 */
4956TEST_P(KeyDeletionTest, DeleteKey) {
4957 auto error = GenerateKey(AuthorizationSetBuilder()
4958 .RsaSigningKey(2048, 65537)
4959 .Digest(Digest::NONE)
4960 .Padding(PaddingMode::NONE)
4961 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08004962 .Authorization(TAG_ROLLBACK_RESISTANCE)
4963 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07004964 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4965
4966 // Delete must work if rollback protection is implemented
4967 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07004968 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07004969 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4970
4971 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
4972
4973 string message = "12345678901234567890123456789012";
4974 AuthorizationSet begin_out_params;
4975 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
4976 Begin(KeyPurpose::SIGN, key_blob_,
4977 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
4978 &begin_out_params));
4979 AbortIfNeeded();
4980 key_blob_ = AidlBuf();
4981 }
4982}
4983
4984/**
4985 * KeyDeletionTest.DeleteInvalidKey
4986 *
4987 * This test checks that the HAL excepts invalid key blobs..
4988 */
4989TEST_P(KeyDeletionTest, DeleteInvalidKey) {
4990 // Generate key just to check if rollback protection is implemented
4991 auto error = GenerateKey(AuthorizationSetBuilder()
4992 .RsaSigningKey(2048, 65537)
4993 .Digest(Digest::NONE)
4994 .Padding(PaddingMode::NONE)
4995 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08004996 .Authorization(TAG_ROLLBACK_RESISTANCE)
4997 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07004998 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4999
5000 // Delete must work if rollback protection is implemented
5001 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07005002 AuthorizationSet enforced(SecLevelAuthorizations());
5003 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005004
5005 // Delete the key we don't care about the result at this point.
5006 DeleteKey();
5007
5008 // Now create an invalid key blob and delete it.
5009 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
5010
5011 ASSERT_EQ(ErrorCode::OK, DeleteKey());
5012 }
5013}
5014
5015/**
5016 * KeyDeletionTest.DeleteAllKeys
5017 *
5018 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
5019 *
5020 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
5021 * FBE/FDE encryption keys, which means that the device will not even boot until after the
5022 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
5023 * been provisioned. Use this test only on dedicated testing devices that have no valuable
5024 * credentials stored in Keystore/Keymint.
5025 */
5026TEST_P(KeyDeletionTest, DeleteAllKeys) {
5027 if (!arm_deleteAllKeys) return;
5028 auto error = GenerateKey(AuthorizationSetBuilder()
5029 .RsaSigningKey(2048, 65537)
5030 .Digest(Digest::NONE)
5031 .Padding(PaddingMode::NONE)
5032 .Authorization(TAG_NO_AUTH_REQUIRED)
5033 .Authorization(TAG_ROLLBACK_RESISTANCE));
5034 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
5035
5036 // Delete must work if rollback protection is implemented
5037 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07005038 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07005039 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
5040
5041 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
5042
5043 string message = "12345678901234567890123456789012";
5044 AuthorizationSet begin_out_params;
5045
5046 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
5047 Begin(KeyPurpose::SIGN, key_blob_,
5048 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
5049 &begin_out_params));
5050 AbortIfNeeded();
5051 key_blob_ = AidlBuf();
5052 }
5053}
5054
5055INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
5056
5057using UpgradeKeyTest = KeyMintAidlTestBase;
5058
5059/*
5060 * UpgradeKeyTest.UpgradeKey
5061 *
5062 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
5063 */
5064TEST_P(UpgradeKeyTest, UpgradeKey) {
5065 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5066 .AesEncryptionKey(128)
5067 .Padding(PaddingMode::NONE)
5068 .Authorization(TAG_NO_AUTH_REQUIRED)));
5069
5070 auto result = UpgradeKey(key_blob_);
5071
5072 // Key doesn't need upgrading. Should get okay, but no new key blob.
5073 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
5074}
5075
5076INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
5077
5078using ClearOperationsTest = KeyMintAidlTestBase;
5079
5080/*
5081 * ClearSlotsTest.TooManyOperations
5082 *
5083 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
5084 * operations are started without being finished or aborted. Also verifies
5085 * that aborting the operations clears the operations.
5086 *
5087 */
5088TEST_P(ClearOperationsTest, TooManyOperations) {
5089 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5090 .Authorization(TAG_NO_AUTH_REQUIRED)
5091 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005092 .Padding(PaddingMode::NONE)
5093 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005094
5095 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5096 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08005097 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07005098 AuthorizationSet out_params;
5099 ErrorCode result;
5100 size_t i;
5101
5102 for (i = 0; i < max_operations; i++) {
5103 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
5104 if (ErrorCode::OK != result) {
5105 break;
5106 }
5107 }
5108 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
5109 // Try again just in case there's a weird overflow bug
5110 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
5111 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
5112 for (size_t j = 0; j < i; j++) {
5113 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
5114 << "Aboort failed for i = " << j << std::endl;
5115 }
5116 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
5117 AbortIfNeeded();
5118}
5119
5120INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
5121
5122typedef KeyMintAidlTestBase TransportLimitTest;
5123
5124/*
5125 * TransportLimitTest.FinishInput
5126 *
5127 * Verifies that passing input data to finish succeeds as expected.
5128 */
5129TEST_P(TransportLimitTest, LargeFinishInput) {
5130 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5131 .Authorization(TAG_NO_AUTH_REQUIRED)
5132 .AesEncryptionKey(128)
5133 .BlockMode(BlockMode::ECB)
5134 .Padding(PaddingMode::NONE)));
5135
5136 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
5137 auto cipher_params =
5138 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5139
5140 AuthorizationSet out_params;
5141 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
5142
5143 string plain_message = std::string(1 << msg_size, 'x');
5144 string encrypted_message;
5145 auto rc = Finish(plain_message, &encrypted_message);
5146
5147 EXPECT_EQ(ErrorCode::OK, rc);
5148 EXPECT_EQ(plain_message.size(), encrypted_message.size())
5149 << "Encrypt finish returned OK, but did not consume all of the given input";
5150 cipher_params.push_back(out_params);
5151
5152 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
5153
5154 string decrypted_message;
5155 rc = Finish(encrypted_message, &decrypted_message);
5156 EXPECT_EQ(ErrorCode::OK, rc);
5157 EXPECT_EQ(plain_message.size(), decrypted_message.size())
5158 << "Decrypt finish returned OK, did not consume all of the given input";
5159 }
5160}
5161
5162INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
5163
David Zeuthene0c40892021-01-08 12:54:11 -05005164typedef KeyMintAidlTestBase KeyAgreementTest;
5165
5166int CurveToOpenSslCurveName(EcCurve curve) {
5167 switch (curve) {
5168 case EcCurve::P_224:
5169 return NID_secp224r1;
5170 case EcCurve::P_256:
5171 return NID_X9_62_prime256v1;
5172 case EcCurve::P_384:
5173 return NID_secp384r1;
5174 case EcCurve::P_521:
5175 return NID_secp521r1;
5176 }
5177}
5178
5179/*
5180 * KeyAgreementTest.Ecdh
5181 *
5182 * Verifies that ECDH works for all curves
5183 */
5184TEST_P(KeyAgreementTest, Ecdh) {
5185 // Because it's possible to use this API with keys on different curves, we
5186 // check all N^2 combinations where N is the number of supported
5187 // curves.
5188 //
5189 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
5190 // lot more curves we can be smart about things and just pick |otherCurve| so
5191 // it's not |curve| and that way we end up with only 2*N runs
5192 //
5193 for (auto curve : ValidCurves()) {
5194 for (auto localCurve : ValidCurves()) {
5195 // Generate EC key locally (with access to private key material)
5196 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
5197 int curveName = CurveToOpenSslCurveName(localCurve);
5198 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
5199 ASSERT_NE(group, nullptr);
5200 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
5201 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
5202 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
5203 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
5204
5205 // Get encoded form of the public part of the locally generated key...
5206 unsigned char* p = nullptr;
5207 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
5208 ASSERT_GT(encodedPublicKeySize, 0);
5209 vector<uint8_t> encodedPublicKey(
5210 reinterpret_cast<const uint8_t*>(p),
5211 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
5212 OPENSSL_free(p);
5213
5214 // Generate EC key in KeyMint (only access to public key material)
5215 vector<uint8_t> challenge = {0x41, 0x42};
5216 EXPECT_EQ(
5217 ErrorCode::OK,
5218 GenerateKey(AuthorizationSetBuilder()
5219 .Authorization(TAG_NO_AUTH_REQUIRED)
5220 .Authorization(TAG_EC_CURVE, curve)
5221 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
5222 .Authorization(TAG_ALGORITHM, Algorithm::EC)
5223 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08005224 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
5225 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05005226 << "Failed to generate key";
5227 ASSERT_GT(cert_chain_.size(), 0);
5228 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
5229 ASSERT_NE(kmKeyCert, nullptr);
5230 // Check that keyAgreement (bit 4) is set in KeyUsage
5231 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
5232 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
5233 ASSERT_NE(kmPkey, nullptr);
5234 if (dump_Attestations) {
5235 for (size_t n = 0; n < cert_chain_.size(); n++) {
5236 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
5237 }
5238 }
5239
5240 // Now that we have the two keys, we ask KeyMint to perform ECDH...
5241 if (curve != localCurve) {
5242 // If the keys are using different curves KeyMint should fail with
5243 // ErrorCode:INVALID_ARGUMENT. Check that.
5244 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
5245 string ZabFromKeyMintStr;
5246 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
5247 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
5248 &ZabFromKeyMintStr));
5249
5250 } else {
5251 // Otherwise if the keys are using the same curve, it should work.
5252 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
5253 string ZabFromKeyMintStr;
5254 EXPECT_EQ(ErrorCode::OK,
5255 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
5256 &ZabFromKeyMintStr));
5257 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
5258
5259 // Perform local ECDH between the two keys so we can check if we get the same Zab..
5260 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
5261 ASSERT_NE(ctx, nullptr);
5262 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
5263 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
5264 size_t ZabFromTestLen = 0;
5265 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
5266 vector<uint8_t> ZabFromTest;
5267 ZabFromTest.resize(ZabFromTestLen);
5268 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
5269
5270 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
5271 }
5272
5273 CheckedDeleteKey();
5274 }
5275 }
5276}
5277
5278INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
5279
Shawn Willdend659c7c2021-02-19 14:51:51 -07005280using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005281
5282TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
5283 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5284 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
5285
5286 CheckedDeleteKey(&aesKeyData.blob);
5287 CheckedDeleteKey(&hmacKeyData.blob);
5288 CheckedDeleteKey(&rsaKeyData.blob);
5289 CheckedDeleteKey(&ecdsaKeyData.blob);
5290}
5291
5292// This is a more comprenhensive test, but it can only be run on a machine which is still in early
5293// boot stage, which no proper Android device is by the time we can run VTS. To use this,
5294// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
5295// early boot, so you'll have to reboot between runs.
5296TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
5297 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5298 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
5299 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
5300 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5301 EXPECT_TRUE(
5302 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5303 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5304 EXPECT_TRUE(
5305 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
5306
5307 // Should be able to use keys, since early boot has not ended
5308 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
5309 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
5310 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
5311 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
5312
5313 // End early boot
5314 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
5315 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
5316
5317 // Should not be able to use already-created keys.
5318 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
5319 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
5320 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
5321 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
5322
5323 CheckedDeleteKey(&aesKeyData.blob);
5324 CheckedDeleteKey(&hmacKeyData.blob);
5325 CheckedDeleteKey(&rsaKeyData.blob);
5326 CheckedDeleteKey(&ecdsaKeyData.blob);
5327
5328 // Should not be able to create new keys
5329 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
5330 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
5331
5332 CheckedDeleteKey(&aesKeyData.blob);
5333 CheckedDeleteKey(&hmacKeyData.blob);
5334 CheckedDeleteKey(&rsaKeyData.blob);
5335 CheckedDeleteKey(&ecdsaKeyData.blob);
5336}
Shawn Willdend659c7c2021-02-19 14:51:51 -07005337
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005338INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
5339
Shawn Willdend659c7c2021-02-19 14:51:51 -07005340using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005341
5342// This may be a problematic test. It can't be run repeatedly without unlocking the device in
5343// between runs... and on most test devices there are no enrolled credentials so it can't be
5344// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
5345// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
5346// a manual test process, which includes unlocking between runs, which is why it's included here.
5347// Well, that and the fact that it's the only test we can do without also making calls into the
5348// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
5349// implications might be, so that may or may not be a solution.
5350TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
5351 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
5352 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
5353
5354 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
5355 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
5356 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
5357 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
5358
5359 ErrorCode rc = GetReturnErrorCode(
5360 keyMint().deviceLocked(false /* passwordOnly */, {} /* verificationToken */));
5361 ASSERT_EQ(ErrorCode::OK, rc);
5362 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
5363 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
5364 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
5365 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
5366
5367 CheckedDeleteKey(&aesKeyData.blob);
5368 CheckedDeleteKey(&hmacKeyData.blob);
5369 CheckedDeleteKey(&rsaKeyData.blob);
5370 CheckedDeleteKey(&ecdsaKeyData.blob);
5371}
Shawn Willdend659c7c2021-02-19 14:51:51 -07005372
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00005373INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
5374
Janis Danisevskis24c04702020-12-16 18:28:39 -08005375} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07005376
5377int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07005378 std::cout << "Testing ";
5379 auto halInstances =
5380 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
5381 std::cout << "HAL instances:\n";
5382 for (auto& entry : halInstances) {
5383 std::cout << " " << entry << '\n';
5384 }
5385
Selene Huang31ab4042020-04-29 04:22:39 -07005386 ::testing::InitGoogleTest(&argc, argv);
5387 for (int i = 1; i < argc; ++i) {
5388 if (argv[i][0] == '-') {
5389 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07005390 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
5391 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07005392 }
5393 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07005394 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
5395 dump_Attestations = true;
5396 } else {
5397 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07005398 }
5399 }
5400 }
Shawn Willden08a7e432020-12-11 13:05:27 +00005401 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07005402}