blob: 2d28845b0bebbe0743bbbe598e1176ead1a63748 [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) {
362 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
363 auto challenge = "hello";
364 auto app_id = "foo";
365
366 vector<uint8_t> key_blob;
367 vector<KeyCharacteristics> key_characteristics;
368 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
369 .RsaSigningKey(key_size, 65537)
370 .Digest(Digest::NONE)
371 .Padding(PaddingMode::NONE)
372 .AttestationChallenge(challenge)
373 .AttestationApplicationId(app_id)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800374 .Authorization(TAG_NO_AUTH_REQUIRED)
375 .SetDefaultValidity(),
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700376 &key_blob, &key_characteristics));
377
378 ASSERT_GT(key_blob.size(), 0U);
379 CheckBaseParams(key_characteristics);
380
381 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
382
383 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
384 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
385 << "Key size " << key_size << "missing";
386 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
387
Shawn Willden7c130392020-12-21 09:58:22 -0700388 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700389 ASSERT_GT(cert_chain_.size(), 0);
390
391 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
392 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
393 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
394 sw_enforced, hw_enforced, SecLevel(),
395 cert_chain_[0].encodedCertificate));
396
397 CheckedDeleteKey(&key_blob);
398 }
399}
400
401/*
David Drysdale4dc01072021-04-01 12:17:35 +0100402 * NewKeyGenerationTest.RsaWithRpkAttestation
403 *
404 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
405 * that has been generated using an associate IRemotelyProvisionedComponent.
406 */
407TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
408 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
409 // instance.
410 std::shared_ptr<IRemotelyProvisionedComponent> rp;
411 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
412 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
413
414 // Generate a P-256 keypair to use as an attestation key.
415 MacedPublicKey macedPubKey;
416 std::vector<uint8_t> privateKeyBlob;
417 auto status =
418 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
419 ASSERT_TRUE(status.isOk());
420 vector<uint8_t> coseKeyData;
421 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
422
423 AttestationKey attestation_key;
424 attestation_key.keyBlob = std::move(privateKeyBlob);
425 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
426
427 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
428 auto challenge = "hello";
429 auto app_id = "foo";
430
431 vector<uint8_t> key_blob;
432 vector<KeyCharacteristics> key_characteristics;
433 ASSERT_EQ(ErrorCode::OK,
434 GenerateKey(AuthorizationSetBuilder()
435 .RsaSigningKey(key_size, 65537)
436 .Digest(Digest::NONE)
437 .Padding(PaddingMode::NONE)
438 .AttestationChallenge(challenge)
439 .AttestationApplicationId(app_id)
440 .Authorization(TAG_NO_AUTH_REQUIRED)
441 .SetDefaultValidity(),
442 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
443
444 ASSERT_GT(key_blob.size(), 0U);
445 CheckBaseParams(key_characteristics);
446
447 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
448
449 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
450 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
451 << "Key size " << key_size << "missing";
452 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
453
454 // Attestation by itself is not valid (last entry is not self-signed).
455 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
456
457 // The signature over the attested key should correspond to the P256 public key.
458 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
459 ASSERT_TRUE(key_cert.get());
460 EVP_PKEY_Ptr signing_pubkey;
461 p256_pub_key(coseKeyData, &signing_pubkey);
462 ASSERT_TRUE(signing_pubkey.get());
463
464 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
465 << "Verification of attested certificate failed "
466 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
467
468 CheckedDeleteKey(&key_blob);
469 }
470}
471
472/*
Qi Wud22ec842020-11-26 13:27:53 +0800473 * NewKeyGenerationTest.LimitedUsageRsa
474 *
475 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
476 * resulting keys have correct characteristics.
477 */
478TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
479 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
480 vector<uint8_t> key_blob;
481 vector<KeyCharacteristics> key_characteristics;
482 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
483 .RsaSigningKey(key_size, 65537)
484 .Digest(Digest::NONE)
485 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800486 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
487 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +0800488 &key_blob, &key_characteristics));
489
490 ASSERT_GT(key_blob.size(), 0U);
491 CheckBaseParams(key_characteristics);
492
493 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
494
495 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
496 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
497 << "Key size " << key_size << "missing";
498 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
499
500 // Check the usage count limit tag appears in the authorizations.
501 AuthorizationSet auths;
502 for (auto& entry : key_characteristics) {
503 auths.push_back(AuthorizationSet(entry.authorizations));
504 }
505 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
506 << "key usage count limit " << 1U << " missing";
507
508 CheckedDeleteKey(&key_blob);
509 }
510}
511
512/*
Qi Wubeefae42021-01-28 23:16:37 +0800513 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
514 *
515 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
516 * resulting keys have correct characteristics and attestation.
517 */
518TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
519 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
520 auto challenge = "hello";
521 auto app_id = "foo";
522
523 vector<uint8_t> key_blob;
524 vector<KeyCharacteristics> key_characteristics;
525 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
526 .RsaSigningKey(key_size, 65537)
527 .Digest(Digest::NONE)
528 .Padding(PaddingMode::NONE)
529 .AttestationChallenge(challenge)
530 .AttestationApplicationId(app_id)
531 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800532 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
533 .SetDefaultValidity(),
Qi Wubeefae42021-01-28 23:16:37 +0800534 &key_blob, &key_characteristics));
535
536 ASSERT_GT(key_blob.size(), 0U);
537 CheckBaseParams(key_characteristics);
538
539 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
540
541 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
542 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
543 << "Key size " << key_size << "missing";
544 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
545
546 // Check the usage count limit tag appears in the authorizations.
547 AuthorizationSet auths;
548 for (auto& entry : key_characteristics) {
549 auths.push_back(AuthorizationSet(entry.authorizations));
550 }
551 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
552 << "key usage count limit " << 1U << " missing";
553
554 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -0700555 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +0800556 ASSERT_GT(cert_chain_.size(), 0);
557
558 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
559 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
560 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
561 sw_enforced, hw_enforced, SecLevel(),
562 cert_chain_[0].encodedCertificate));
563
564 CheckedDeleteKey(&key_blob);
565 }
566}
567
568/*
Selene Huang31ab4042020-04-29 04:22:39 -0700569 * NewKeyGenerationTest.NoInvalidRsaSizes
570 *
571 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
572 */
573TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
574 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
575 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700576 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700577 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
578 GenerateKey(AuthorizationSetBuilder()
579 .RsaSigningKey(key_size, 65537)
580 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800581 .Padding(PaddingMode::NONE)
582 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700583 &key_blob, &key_characteristics));
584 }
585}
586
587/*
588 * NewKeyGenerationTest.RsaNoDefaultSize
589 *
590 * Verifies that failing to specify a key size for RSA key generation returns
591 * UNSUPPORTED_KEY_SIZE.
592 */
593TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
594 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
595 GenerateKey(AuthorizationSetBuilder()
596 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
597 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800598 .SigningKey()
599 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700600}
601
602/*
603 * NewKeyGenerationTest.Ecdsa
604 *
605 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
606 * have correct characteristics.
607 */
608TEST_P(NewKeyGenerationTest, Ecdsa) {
609 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
610 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700611 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -0800612 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
613 .EcdsaSigningKey(key_size)
614 .Digest(Digest::NONE)
615 .SetDefaultValidity(),
616 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -0700617 ASSERT_GT(key_blob.size(), 0U);
618 CheckBaseParams(key_characteristics);
619
Shawn Willden7f424372021-01-10 18:06:50 -0700620 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700621
622 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
623 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
624 << "Key size " << key_size << "missing";
625
626 CheckedDeleteKey(&key_blob);
627 }
628}
629
630/*
Qi Wud22ec842020-11-26 13:27:53 +0800631 * NewKeyGenerationTest.LimitedUsageEcdsa
632 *
633 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
634 * resulting keys have correct characteristics.
635 */
636TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
637 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
638 vector<uint8_t> key_blob;
639 vector<KeyCharacteristics> key_characteristics;
640 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
641 .EcdsaSigningKey(key_size)
642 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800643 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
644 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +0800645 &key_blob, &key_characteristics));
646
647 ASSERT_GT(key_blob.size(), 0U);
648 CheckBaseParams(key_characteristics);
649
650 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
651
652 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
653 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
654 << "Key size " << key_size << "missing";
655
656 // Check the usage count limit tag appears in the authorizations.
657 AuthorizationSet auths;
658 for (auto& entry : key_characteristics) {
659 auths.push_back(AuthorizationSet(entry.authorizations));
660 }
661 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
662 << "key usage count limit " << 1U << " missing";
663
664 CheckedDeleteKey(&key_blob);
665 }
666}
667
668/*
Selene Huang31ab4042020-04-29 04:22:39 -0700669 * NewKeyGenerationTest.EcdsaDefaultSize
670 *
671 * Verifies that failing to specify a key size for EC key generation returns
672 * UNSUPPORTED_KEY_SIZE.
673 */
674TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
675 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
676 GenerateKey(AuthorizationSetBuilder()
677 .Authorization(TAG_ALGORITHM, Algorithm::EC)
678 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -0800679 .Digest(Digest::NONE)
680 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700681}
682
683/*
684 * NewKeyGenerationTest.EcdsaInvalidSize
685 *
686 * Verifies that specifying an invalid key size for EC key generation returns
687 * UNSUPPORTED_KEY_SIZE.
688 */
689TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
690 for (auto key_size : InvalidKeySizes(Algorithm::EC)) {
691 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700692 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -0800693 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
694 .EcdsaSigningKey(key_size)
695 .Digest(Digest::NONE)
696 .SetDefaultValidity(),
697 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -0700698 }
699
Janis Danisevskis164bb872021-02-09 11:30:25 -0800700 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
701 .EcdsaSigningKey(190)
702 .Digest(Digest::NONE)
703 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700704}
705
706/*
707 * NewKeyGenerationTest.EcdsaMismatchKeySize
708 *
709 * Verifies that specifying mismatched key size and curve for EC key generation returns
710 * INVALID_ARGUMENT.
711 */
712TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
713 if (SecLevel() == SecurityLevel::STRONGBOX) return;
714
715 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT,
716 GenerateKey(AuthorizationSetBuilder()
717 .EcdsaSigningKey(224)
718 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800719 .Digest(Digest::NONE)
720 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700721}
722
723/*
724 * NewKeyGenerationTest.EcdsaAllValidSizes
725 *
726 * Verifies that keymint supports all required EC key sizes.
727 */
728TEST_P(NewKeyGenerationTest, EcdsaAllValidSizes) {
729 auto valid_sizes = ValidKeySizes(Algorithm::EC);
730 for (size_t size : valid_sizes) {
Janis Danisevskis164bb872021-02-09 11:30:25 -0800731 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
732 .EcdsaSigningKey(size)
733 .Digest(Digest::NONE)
734 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -0700735 << "Failed to generate size: " << size;
736 CheckedDeleteKey();
737 }
738}
739
740/*
741 * NewKeyGenerationTest.EcdsaInvalidCurves
742 *
743 * Verifies that keymint does not support any curve designated as unsupported.
744 */
745TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
746 Digest digest;
747 if (SecLevel() == SecurityLevel::STRONGBOX) {
748 digest = Digest::SHA_2_256;
749 } else {
750 digest = Digest::SHA_2_512;
751 }
752 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -0800753 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
754 .EcdsaSigningKey(curve)
755 .Digest(digest)
756 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -0700757 << "Failed to generate key on curve: " << curve;
758 CheckedDeleteKey();
759 }
760}
761
762/*
763 * NewKeyGenerationTest.Hmac
764 *
765 * Verifies that keymint supports all required digests, and that the resulting keys have correct
766 * characteristics.
767 */
768TEST_P(NewKeyGenerationTest, Hmac) {
769 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
770 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700771 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700772 constexpr size_t key_size = 128;
773 ASSERT_EQ(ErrorCode::OK,
774 GenerateKey(
775 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
776 TAG_MIN_MAC_LENGTH, 128),
777 &key_blob, &key_characteristics));
778
779 ASSERT_GT(key_blob.size(), 0U);
780 CheckBaseParams(key_characteristics);
781
Shawn Willden7f424372021-01-10 18:06:50 -0700782 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
783 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
784 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
785 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -0700786
787 CheckedDeleteKey(&key_blob);
788 }
789}
790
791/*
Qi Wud22ec842020-11-26 13:27:53 +0800792 * NewKeyGenerationTest.LimitedUsageHmac
793 *
794 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
795 * resulting keys have correct characteristics.
796 */
797TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
798 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
799 vector<uint8_t> key_blob;
800 vector<KeyCharacteristics> key_characteristics;
801 constexpr size_t key_size = 128;
802 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
803 .HmacKey(key_size)
804 .Digest(digest)
805 .Authorization(TAG_MIN_MAC_LENGTH, 128)
806 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
807 &key_blob, &key_characteristics));
808
809 ASSERT_GT(key_blob.size(), 0U);
810 CheckBaseParams(key_characteristics);
811
812 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
813 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
814 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
815 << "Key size " << key_size << "missing";
816
817 // Check the usage count limit tag appears in the authorizations.
818 AuthorizationSet auths;
819 for (auto& entry : key_characteristics) {
820 auths.push_back(AuthorizationSet(entry.authorizations));
821 }
822 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
823 << "key usage count limit " << 1U << " missing";
824
825 CheckedDeleteKey(&key_blob);
826 }
827}
828
829/*
Selene Huang31ab4042020-04-29 04:22:39 -0700830 * NewKeyGenerationTest.HmacCheckKeySizes
831 *
832 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
833 */
834TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
835 for (size_t key_size = 0; key_size <= 512; ++key_size) {
836 if (key_size < 64 || key_size % 8 != 0) {
837 // To keep this test from being very slow, we only test a random fraction of
838 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
839 // them, we expect to run ~40 of them in each run.
840 if (key_size % 8 == 0 || random() % 10 == 0) {
841 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
842 GenerateKey(AuthorizationSetBuilder()
843 .HmacKey(key_size)
844 .Digest(Digest::SHA_2_256)
845 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
846 << "HMAC key size " << key_size << " invalid";
847 }
848 } else {
849 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
850 .HmacKey(key_size)
851 .Digest(Digest::SHA_2_256)
852 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
853 << "Failed to generate HMAC key of size " << key_size;
854 CheckedDeleteKey();
855 }
856 }
857}
858
859/*
860 * NewKeyGenerationTest.HmacCheckMinMacLengths
861 *
862 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
863 * test is probabilistic in order to keep the runtime down, but any failure prints out the
864 * specific MAC length that failed, so reproducing a failed run will be easy.
865 */
866TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
867 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
868 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
869 // To keep this test from being very long, we only test a random fraction of
870 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
871 // we expect to run ~17 of them in each run.
872 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
873 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
874 GenerateKey(AuthorizationSetBuilder()
875 .HmacKey(128)
876 .Digest(Digest::SHA_2_256)
877 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
878 << "HMAC min mac length " << min_mac_length << " invalid.";
879 }
880 } else {
881 EXPECT_EQ(ErrorCode::OK,
882 GenerateKey(AuthorizationSetBuilder()
883 .HmacKey(128)
884 .Digest(Digest::SHA_2_256)
885 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
886 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
887 CheckedDeleteKey();
888 }
889 }
890}
891
892/*
893 * NewKeyGenerationTest.HmacMultipleDigests
894 *
895 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
896 */
897TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
898 if (SecLevel() == SecurityLevel::STRONGBOX) return;
899
900 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
901 GenerateKey(AuthorizationSetBuilder()
902 .HmacKey(128)
903 .Digest(Digest::SHA1)
904 .Digest(Digest::SHA_2_256)
905 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
906}
907
908/*
909 * NewKeyGenerationTest.HmacDigestNone
910 *
911 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
912 */
913TEST_P(NewKeyGenerationTest, HmacDigestNone) {
914 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
915 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
916 128)));
917
918 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
919 GenerateKey(AuthorizationSetBuilder()
920 .HmacKey(128)
921 .Digest(Digest::NONE)
922 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
923}
924
925INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
926
927typedef KeyMintAidlTestBase SigningOperationsTest;
928
929/*
930 * SigningOperationsTest.RsaSuccess
931 *
932 * Verifies that raw RSA signature operations succeed.
933 */
934TEST_P(SigningOperationsTest, RsaSuccess) {
935 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
936 .RsaSigningKey(2048, 65537)
937 .Digest(Digest::NONE)
938 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800939 .Authorization(TAG_NO_AUTH_REQUIRED)
940 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700941 string message = "12345678901234567890123456789012";
942 string signature = SignMessage(
943 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
944}
945
946/*
947 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
948 *
Shawn Willden7f424372021-01-10 18:06:50 -0700949 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -0700950 */
951TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
952 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
953 .Authorization(TAG_NO_AUTH_REQUIRED)
954 .RsaSigningKey(2048, 65537)
955 .Digest(Digest::NONE)
956 .Padding(PaddingMode::NONE)
957 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -0800958 .Authorization(TAG_APPLICATION_DATA, "appdata")
959 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700960 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
961 Begin(KeyPurpose::SIGN,
962 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
963 AbortIfNeeded();
964 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
965 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
966 .Digest(Digest::NONE)
967 .Padding(PaddingMode::NONE)
968 .Authorization(TAG_APPLICATION_ID, "clientid")));
969 AbortIfNeeded();
970 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
971 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
972 .Digest(Digest::NONE)
973 .Padding(PaddingMode::NONE)
974 .Authorization(TAG_APPLICATION_DATA, "appdata")));
975 AbortIfNeeded();
976 EXPECT_EQ(ErrorCode::OK,
977 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
978 .Digest(Digest::NONE)
979 .Padding(PaddingMode::NONE)
980 .Authorization(TAG_APPLICATION_DATA, "appdata")
981 .Authorization(TAG_APPLICATION_ID, "clientid")));
982 AbortIfNeeded();
983}
984
985/*
986 * SigningOperationsTest.RsaPssSha256Success
987 *
988 * Verifies that RSA-PSS signature operations succeed.
989 */
990TEST_P(SigningOperationsTest, RsaPssSha256Success) {
991 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
992 .RsaSigningKey(2048, 65537)
993 .Digest(Digest::SHA_2_256)
994 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800995 .Authorization(TAG_NO_AUTH_REQUIRED)
996 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -0700997 // Use large message, which won't work without digesting.
998 string message(1024, 'a');
999 string signature = SignMessage(
1000 message,
1001 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
1002}
1003
1004/*
1005 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
1006 *
1007 * Verifies that keymint rejects signature operations that specify a padding mode when the key
1008 * supports only unpadded operations.
1009 */
1010TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
1011 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1012 .RsaSigningKey(2048, 65537)
1013 .Digest(Digest::NONE)
1014 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001015 .Padding(PaddingMode::NONE)
1016 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001017 string message = "12345678901234567890123456789012";
1018 string signature;
1019
1020 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
1021 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1022 .Digest(Digest::NONE)
1023 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1024}
1025
1026/*
1027 * SigningOperationsTest.NoUserConfirmation
1028 *
1029 * Verifies that keymint rejects signing operations for keys with
1030 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
1031 * presented.
1032 */
1033TEST_P(SigningOperationsTest, NoUserConfirmation) {
1034 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001035 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1036 .RsaSigningKey(1024, 65537)
1037 .Digest(Digest::NONE)
1038 .Padding(PaddingMode::NONE)
1039 .Authorization(TAG_NO_AUTH_REQUIRED)
1040 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1041 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001042
1043 const string message = "12345678901234567890123456789012";
1044 EXPECT_EQ(ErrorCode::OK,
1045 Begin(KeyPurpose::SIGN,
1046 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1047 string signature;
1048 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
1049}
1050
1051/*
1052 * SigningOperationsTest.RsaPkcs1Sha256Success
1053 *
1054 * Verifies that digested RSA-PKCS1 signature operations succeed.
1055 */
1056TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
1057 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1058 .RsaSigningKey(2048, 65537)
1059 .Digest(Digest::SHA_2_256)
1060 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001061 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1062 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001063 string message(1024, 'a');
1064 string signature = SignMessage(message, AuthorizationSetBuilder()
1065 .Digest(Digest::SHA_2_256)
1066 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1067}
1068
1069/*
1070 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
1071 *
1072 * Verifies that undigested RSA-PKCS1 signature operations succeed.
1073 */
1074TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
1075 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1076 .RsaSigningKey(2048, 65537)
1077 .Digest(Digest::NONE)
1078 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001079 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1080 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001081 string message(53, 'a');
1082 string signature = SignMessage(message, AuthorizationSetBuilder()
1083 .Digest(Digest::NONE)
1084 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
1085}
1086
1087/*
1088 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
1089 *
1090 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
1091 * given a too-long message.
1092 */
1093TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
1094 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1095 .RsaSigningKey(2048, 65537)
1096 .Digest(Digest::NONE)
1097 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001098 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1099 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001100 string message(257, 'a');
1101
1102 EXPECT_EQ(ErrorCode::OK,
1103 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1104 .Digest(Digest::NONE)
1105 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1106 string signature;
1107 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
1108}
1109
1110/*
1111 * SigningOperationsTest.RsaPssSha512TooSmallKey
1112 *
1113 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
1114 * used with a key that is too small for the message.
1115 *
1116 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
1117 * keymint specification requires that salt_size == digest_size, so the message will be
1118 * digest_size * 2 +
1119 * 16. Such a message can only be signed by a given key if the key is at least that size. This
1120 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
1121 * for a 1024-bit key.
1122 */
1123TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
1124 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1125 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1126 .RsaSigningKey(1024, 65537)
1127 .Digest(Digest::SHA_2_512)
1128 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001129 .Padding(PaddingMode::RSA_PSS)
1130 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001131 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1132 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1133 .Digest(Digest::SHA_2_512)
1134 .Padding(PaddingMode::RSA_PSS)));
1135}
1136
1137/*
1138 * SigningOperationsTest.RsaNoPaddingTooLong
1139 *
1140 * Verifies that raw RSA signature operations fail with the correct error code when
1141 * given a too-long message.
1142 */
1143TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
1144 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1145 .RsaSigningKey(2048, 65537)
1146 .Digest(Digest::NONE)
1147 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001148 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1149 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001150 // One byte too long
1151 string message(2048 / 8 + 1, 'a');
1152 ASSERT_EQ(ErrorCode::OK,
1153 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1154 .Digest(Digest::NONE)
1155 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1156 string result;
1157 ErrorCode finish_error_code = Finish(message, &result);
1158 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1159 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1160
1161 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
1162 message = string(128 * 1024, 'a');
1163 ASSERT_EQ(ErrorCode::OK,
1164 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1165 .Digest(Digest::NONE)
1166 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
1167 finish_error_code = Finish(message, &result);
1168 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
1169 finish_error_code == ErrorCode::INVALID_ARGUMENT);
1170}
1171
1172/*
1173 * SigningOperationsTest.RsaAbort
1174 *
1175 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
1176 * test, but the behavior should be algorithm and purpose-independent.
1177 */
1178TEST_P(SigningOperationsTest, RsaAbort) {
1179 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1180 .RsaSigningKey(2048, 65537)
1181 .Digest(Digest::NONE)
1182 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001183 .Padding(PaddingMode::NONE)
1184 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001185
1186 ASSERT_EQ(ErrorCode::OK,
1187 Begin(KeyPurpose::SIGN,
1188 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1189 EXPECT_EQ(ErrorCode::OK, Abort());
1190
1191 // Another abort should fail
1192 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
1193
1194 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08001195 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07001196}
1197
1198/*
1199 * SigningOperationsTest.RsaUnsupportedPadding
1200 *
1201 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
1202 * with a padding mode inappropriate for RSA.
1203 */
1204TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
1205 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1206 .RsaSigningKey(2048, 65537)
1207 .Authorization(TAG_NO_AUTH_REQUIRED)
1208 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001209 .Padding(PaddingMode::PKCS7)
1210 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001211 ASSERT_EQ(
1212 ErrorCode::UNSUPPORTED_PADDING_MODE,
1213 Begin(KeyPurpose::SIGN,
1214 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
1215}
1216
1217/*
1218 * SigningOperationsTest.RsaPssNoDigest
1219 *
1220 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
1221 */
1222TEST_P(SigningOperationsTest, RsaNoDigest) {
1223 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1224 .RsaSigningKey(2048, 65537)
1225 .Authorization(TAG_NO_AUTH_REQUIRED)
1226 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001227 .Padding(PaddingMode::RSA_PSS)
1228 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001229 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
1230 Begin(KeyPurpose::SIGN,
1231 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
1232
1233 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
1234 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
1235}
1236
1237/*
1238 * SigningOperationsTest.RsaPssNoDigest
1239 *
1240 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
1241 * supported in some cases (as validated in other tests), but a mode must be specified.
1242 */
1243TEST_P(SigningOperationsTest, RsaNoPadding) {
1244 // Padding must be specified
1245 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1246 .RsaKey(2048, 65537)
1247 .Authorization(TAG_NO_AUTH_REQUIRED)
1248 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001249 .Digest(Digest::NONE)
1250 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001251 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
1252 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1253}
1254
1255/*
1256 * SigningOperationsTest.RsaShortMessage
1257 *
1258 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
1259 */
1260TEST_P(SigningOperationsTest, RsaTooShortMessage) {
1261 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1262 .Authorization(TAG_NO_AUTH_REQUIRED)
1263 .RsaSigningKey(2048, 65537)
1264 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001265 .Padding(PaddingMode::NONE)
1266 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001267
1268 // Barely shorter
1269 string message(2048 / 8 - 1, 'a');
1270 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1271
1272 // Much shorter
1273 message = "a";
1274 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1275}
1276
1277/*
1278 * SigningOperationsTest.RsaSignWithEncryptionKey
1279 *
1280 * Verifies that RSA encryption keys cannot be used to sign.
1281 */
1282TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
1283 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1284 .Authorization(TAG_NO_AUTH_REQUIRED)
1285 .RsaEncryptionKey(2048, 65537)
1286 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001287 .Padding(PaddingMode::NONE)
1288 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001289 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
1290 Begin(KeyPurpose::SIGN,
1291 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
1292}
1293
1294/*
1295 * SigningOperationsTest.RsaSignTooLargeMessage
1296 *
1297 * Verifies that attempting a raw signature of a message which is the same length as the key,
1298 * but numerically larger than the public modulus, fails with the correct error.
1299 */
1300TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
1301 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1302 .Authorization(TAG_NO_AUTH_REQUIRED)
1303 .RsaSigningKey(2048, 65537)
1304 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001305 .Padding(PaddingMode::NONE)
1306 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001307
1308 // Largest possible message will always be larger than the public modulus.
1309 string message(2048 / 8, static_cast<char>(0xff));
1310 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1311 .Authorization(TAG_NO_AUTH_REQUIRED)
1312 .Digest(Digest::NONE)
1313 .Padding(PaddingMode::NONE)));
1314 string signature;
1315 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
1316}
1317
1318/*
1319 * SigningOperationsTest.EcdsaAllSizesAndHashes
1320 *
1321 * Verifies that ECDSA operations succeed with all possible key sizes and hashes.
1322 */
1323TEST_P(SigningOperationsTest, EcdsaAllSizesAndHashes) {
1324 for (auto key_size : ValidKeySizes(Algorithm::EC)) {
1325 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
1326 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1327 .Authorization(TAG_NO_AUTH_REQUIRED)
1328 .EcdsaSigningKey(key_size)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001329 .Digest(digest)
1330 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07001331 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with size " << key_size
1332 << " and digest " << digest;
1333 if (error != ErrorCode::OK) continue;
1334
1335 string message(1024, 'a');
1336 if (digest == Digest::NONE) message.resize(key_size / 8);
1337 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
1338 CheckedDeleteKey();
1339 }
1340 }
1341}
1342
1343/*
1344 * SigningOperationsTest.EcdsaAllCurves
1345 *
1346 * Verifies that ECDSA operations succeed with all possible curves.
1347 */
1348TEST_P(SigningOperationsTest, EcdsaAllCurves) {
1349 for (auto curve : ValidCurves()) {
1350 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1351 .Authorization(TAG_NO_AUTH_REQUIRED)
1352 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001353 .Digest(Digest::SHA_2_256)
1354 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07001355 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
1356 if (error != ErrorCode::OK) continue;
1357
1358 string message(1024, 'a');
1359 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1360 CheckedDeleteKey();
1361 }
1362}
1363
1364/*
1365 * SigningOperationsTest.EcdsaNoDigestHugeData
1366 *
1367 * Verifies that ECDSA operations support very large messages, even without digesting. This
1368 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
1369 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
1370 * the framework.
1371 */
1372TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
1373 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1374 .Authorization(TAG_NO_AUTH_REQUIRED)
1375 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001376 .Digest(Digest::NONE)
1377 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001378 string message(1 * 1024, 'a');
1379 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
1380}
1381
1382/*
1383 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
1384 *
1385 * Verifies that using an EC key requires the correct app ID/data.
1386 */
1387TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
1388 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1389 .Authorization(TAG_NO_AUTH_REQUIRED)
1390 .EcdsaSigningKey(256)
1391 .Digest(Digest::NONE)
1392 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08001393 .Authorization(TAG_APPLICATION_DATA, "appdata")
1394 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001395 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1396 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
1397 AbortIfNeeded();
1398 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1399 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1400 .Digest(Digest::NONE)
1401 .Authorization(TAG_APPLICATION_ID, "clientid")));
1402 AbortIfNeeded();
1403 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
1404 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1405 .Digest(Digest::NONE)
1406 .Authorization(TAG_APPLICATION_DATA, "appdata")));
1407 AbortIfNeeded();
1408 EXPECT_EQ(ErrorCode::OK,
1409 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
1410 .Digest(Digest::NONE)
1411 .Authorization(TAG_APPLICATION_DATA, "appdata")
1412 .Authorization(TAG_APPLICATION_ID, "clientid")));
1413 AbortIfNeeded();
1414}
1415
1416/*
1417 * SigningOperationsTest.AesEcbSign
1418 *
1419 * Verifies that attempts to use AES keys to sign fail in the correct way.
1420 */
1421TEST_P(SigningOperationsTest, AesEcbSign) {
1422 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1423 .Authorization(TAG_NO_AUTH_REQUIRED)
1424 .SigningKey()
1425 .AesEncryptionKey(128)
1426 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
1427
1428 AuthorizationSet out_params;
1429 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1430 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
1431 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
1432 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
1433}
1434
1435/*
1436 * SigningOperationsTest.HmacAllDigests
1437 *
1438 * Verifies that HMAC works with all digests.
1439 */
1440TEST_P(SigningOperationsTest, HmacAllDigests) {
1441 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
1442 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1443 .Authorization(TAG_NO_AUTH_REQUIRED)
1444 .HmacKey(128)
1445 .Digest(digest)
1446 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
1447 << "Failed to create HMAC key with digest " << digest;
1448 string message = "12345678901234567890123456789012";
1449 string signature = MacMessage(message, digest, 160);
1450 EXPECT_EQ(160U / 8U, signature.size())
1451 << "Failed to sign with HMAC key with digest " << digest;
1452 CheckedDeleteKey();
1453 }
1454}
1455
1456/*
1457 * SigningOperationsTest.HmacSha256TooLargeMacLength
1458 *
1459 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
1460 * digest size.
1461 */
1462TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
1463 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1464 .Authorization(TAG_NO_AUTH_REQUIRED)
1465 .HmacKey(128)
1466 .Digest(Digest::SHA_2_256)
1467 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
1468 AuthorizationSet output_params;
1469 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
1470 AuthorizationSetBuilder()
1471 .Digest(Digest::SHA_2_256)
1472 .Authorization(TAG_MAC_LENGTH, 264),
1473 &output_params));
1474}
1475
1476/*
1477 * SigningOperationsTest.HmacSha256TooSmallMacLength
1478 *
1479 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
1480 * specified minimum MAC length.
1481 */
1482TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
1483 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1484 .Authorization(TAG_NO_AUTH_REQUIRED)
1485 .HmacKey(128)
1486 .Digest(Digest::SHA_2_256)
1487 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
1488 AuthorizationSet output_params;
1489 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
1490 AuthorizationSetBuilder()
1491 .Digest(Digest::SHA_2_256)
1492 .Authorization(TAG_MAC_LENGTH, 120),
1493 &output_params));
1494}
1495
1496/*
1497 * SigningOperationsTest.HmacRfc4231TestCase3
1498 *
1499 * Validates against the test vectors from RFC 4231 test case 3.
1500 */
1501TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
1502 string key(20, 0xaa);
1503 string message(50, 0xdd);
1504 uint8_t sha_224_expected[] = {
1505 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
1506 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
1507 };
1508 uint8_t sha_256_expected[] = {
1509 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
1510 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
1511 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
1512 };
1513 uint8_t sha_384_expected[] = {
1514 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
1515 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
1516 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
1517 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
1518 };
1519 uint8_t sha_512_expected[] = {
1520 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
1521 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
1522 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
1523 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
1524 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
1525 };
1526
1527 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1528 if (SecLevel() != SecurityLevel::STRONGBOX) {
1529 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1530 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1531 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1532 }
1533}
1534
1535/*
1536 * SigningOperationsTest.HmacRfc4231TestCase5
1537 *
1538 * Validates against the test vectors from RFC 4231 test case 5.
1539 */
1540TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
1541 string key(20, 0x0c);
1542 string message = "Test With Truncation";
1543
1544 uint8_t sha_224_expected[] = {
1545 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
1546 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
1547 };
1548 uint8_t sha_256_expected[] = {
1549 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
1550 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
1551 };
1552 uint8_t sha_384_expected[] = {
1553 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
1554 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
1555 };
1556 uint8_t sha_512_expected[] = {
1557 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
1558 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
1559 };
1560
1561 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
1562 if (SecLevel() != SecurityLevel::STRONGBOX) {
1563 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
1564 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
1565 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
1566 }
1567}
1568
1569INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
1570
1571typedef KeyMintAidlTestBase VerificationOperationsTest;
1572
1573/*
1574 * VerificationOperationsTest.RsaSuccess
1575 *
1576 * Verifies that a simple RSA signature/verification sequence succeeds.
1577 */
1578TEST_P(VerificationOperationsTest, RsaSuccess) {
1579 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1580 .Authorization(TAG_NO_AUTH_REQUIRED)
1581 .RsaSigningKey(2048, 65537)
1582 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001583 .Padding(PaddingMode::NONE)
1584 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001585 string message = "12345678901234567890123456789012";
1586 string signature = SignMessage(
1587 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1588 VerifyMessage(message, signature,
1589 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
1590}
1591
1592/*
1593 * VerificationOperationsTest.RsaSuccess
1594 *
1595 * Verifies RSA signature/verification for all padding modes and digests.
1596 */
1597TEST_P(VerificationOperationsTest, RsaAllPaddingsAndDigests) {
1598 auto authorizations = AuthorizationSetBuilder()
1599 .Authorization(TAG_NO_AUTH_REQUIRED)
1600 .RsaSigningKey(2048, 65537)
1601 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
1602 .Padding(PaddingMode::NONE)
1603 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001604 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
1605 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07001606
1607 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
1608
1609 string message(128, 'a');
1610 string corrupt_message(message);
1611 ++corrupt_message[corrupt_message.size() / 2];
1612
1613 for (auto padding :
1614 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
1615 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
1616 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
1617 // Digesting only makes sense with padding.
1618 continue;
1619 }
1620
1621 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
1622 // PSS requires digesting.
1623 continue;
1624 }
1625
1626 string signature =
1627 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
1628 VerifyMessage(message, signature,
1629 AuthorizationSetBuilder().Digest(digest).Padding(padding));
1630
1631 /* TODO(seleneh) add exportkey tests back later when we have decided on
1632 * the new api.
1633 if (digest != Digest::NONE) {
1634 // Verify with OpenSSL.
1635 vector<uint8_t> pubkey;
1636 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey));
1637
1638 const uint8_t* p = pubkey.data();
1639 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
1640 ASSERT_TRUE(pkey.get());
1641
1642 EVP_MD_CTX digest_ctx;
1643 EVP_MD_CTX_init(&digest_ctx);
1644 EVP_PKEY_CTX* pkey_ctx;
1645 const EVP_MD* md = openssl_digest(digest);
1646 ASSERT_NE(md, nullptr);
1647 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
1648 nullptr, pkey.get()));
1649
1650 switch (padding) {
1651 case PaddingMode::RSA_PSS:
1652 EXPECT_GT(EVP_PKEY_CTX_set_rsa_padding(pkey_ctx,
1653 RSA_PKCS1_PSS_PADDING), 0); EXPECT_GT(EVP_PKEY_CTX_set_rsa_pss_saltlen(pkey_ctx,
1654 EVP_MD_size(md)), 0); break; case PaddingMode::RSA_PKCS1_1_5_SIGN:
1655 // PKCS1 is the default; don't need to set anything.
1656 break;
1657 default:
1658 FAIL();
1659 break;
1660 }
1661
1662 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
1663 message.size())); EXPECT_EQ(1, EVP_DigestVerifyFinal(&digest_ctx,
1664 reinterpret_cast<const
1665 uint8_t*>(signature.data()), signature.size())); EVP_MD_CTX_cleanup(&digest_ctx);
1666 }
1667 */
1668
1669 // Corrupt signature shouldn't verify.
1670 string corrupt_signature(signature);
1671 ++corrupt_signature[corrupt_signature.size() / 2];
1672
1673 EXPECT_EQ(ErrorCode::OK,
1674 Begin(KeyPurpose::VERIFY,
1675 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
1676 string result;
1677 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result));
1678
1679 // Corrupt message shouldn't verify
1680 EXPECT_EQ(ErrorCode::OK,
1681 Begin(KeyPurpose::VERIFY,
1682 AuthorizationSetBuilder().Digest(digest).Padding(padding)));
1683 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result));
1684 }
1685 }
1686}
1687
1688/*
1689 * VerificationOperationsTest.RsaSuccess
1690 *
1691 * Verifies ECDSA signature/verification for all digests and curves.
1692 */
1693TEST_P(VerificationOperationsTest, EcdsaAllDigestsAndCurves) {
1694 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
1695
1696 string message = "1234567890";
1697 string corrupt_message = "2234567890";
1698 for (auto curve : ValidCurves()) {
1699 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
1700 .Authorization(TAG_NO_AUTH_REQUIRED)
1701 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001702 .Digest(digests)
1703 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07001704 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
1705 if (error != ErrorCode::OK) {
1706 continue;
1707 }
1708
1709 for (auto digest : digests) {
1710 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
1711 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
1712
1713 /* TODO(seleneh) add exportkey tests back later when we have decided on
1714 * the new api.
1715
1716 // Verify with OpenSSL
1717 if (digest != Digest::NONE) {
1718 vector<uint8_t> pubkey;
1719 ASSERT_EQ(ErrorCode::OK, ExportKey(KeyFormat::X509, &pubkey))
1720 << curve << ' ' << digest;
1721
1722 const uint8_t* p = pubkey.data();
1723 EVP_PKEY_Ptr pkey(d2i_PUBKEY(nullptr, &p, pubkey.size()));
1724 ASSERT_TRUE(pkey.get());
1725
1726 EVP_MD_CTX digest_ctx;
1727 EVP_MD_CTX_init(&digest_ctx);
1728 EVP_PKEY_CTX* pkey_ctx;
1729 const EVP_MD* md = openssl_digest(digest);
1730
1731 EXPECT_EQ(1, EVP_DigestVerifyInit(&digest_ctx, &pkey_ctx, md,
1732 nullptr, pkey.get()))
1733 << curve << ' ' << digest;
1734
1735 EXPECT_EQ(1, EVP_DigestVerifyUpdate(&digest_ctx, message.data(),
1736 message.size()))
1737 << curve << ' ' << digest;
1738
1739 EXPECT_EQ(1,
1740 EVP_DigestVerifyFinal(&digest_ctx,
1741 reinterpret_cast<const
1742 uint8_t*>(signature.data()), signature.size()))
1743 << curve << ' ' << digest;
1744
1745 EVP_MD_CTX_cleanup(&digest_ctx);
1746 }
1747 */
1748 // Corrupt signature shouldn't verify.
1749 string corrupt_signature(signature);
1750 ++corrupt_signature[corrupt_signature.size() / 2];
1751
1752 EXPECT_EQ(ErrorCode::OK,
1753 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
1754 << curve << ' ' << digest;
1755
1756 string result;
1757 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, corrupt_signature, &result))
1758 << curve << ' ' << digest;
1759
1760 // Corrupt message shouldn't verify
1761 EXPECT_EQ(ErrorCode::OK,
1762 Begin(KeyPurpose::VERIFY, AuthorizationSetBuilder().Digest(digest)))
1763 << curve << ' ' << digest;
1764
1765 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corrupt_message, signature, &result))
1766 << curve << ' ' << digest;
1767 }
1768
1769 auto rc = DeleteKey();
1770 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
1771 }
1772}
1773
1774/*
1775 * VerificationOperationsTest.HmacSigningKeyCannotVerify
1776 *
1777 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
1778 */
1779TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
1780 string key_material = "HelloThisIsAKey";
1781
1782 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07001783 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07001784 EXPECT_EQ(ErrorCode::OK,
1785 ImportKey(AuthorizationSetBuilder()
1786 .Authorization(TAG_NO_AUTH_REQUIRED)
1787 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
1788 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
1789 .Digest(Digest::SHA_2_256)
1790 .Authorization(TAG_MIN_MAC_LENGTH, 160),
1791 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
1792 EXPECT_EQ(ErrorCode::OK,
1793 ImportKey(AuthorizationSetBuilder()
1794 .Authorization(TAG_NO_AUTH_REQUIRED)
1795 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
1796 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
1797 .Digest(Digest::SHA_2_256)
1798 .Authorization(TAG_MIN_MAC_LENGTH, 160),
1799 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
1800
1801 string message = "This is a message.";
1802 string signature = SignMessage(
1803 signing_key, message,
1804 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
1805
1806 // Signing key should not work.
1807 AuthorizationSet out_params;
1808 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
1809 Begin(KeyPurpose::VERIFY, signing_key,
1810 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
1811
1812 // Verification key should work.
1813 VerifyMessage(verification_key, message, signature,
1814 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
1815
1816 CheckedDeleteKey(&signing_key);
1817 CheckedDeleteKey(&verification_key);
1818}
1819
1820INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
1821
1822typedef KeyMintAidlTestBase ExportKeyTest;
1823
1824/*
1825 * ExportKeyTest.RsaUnsupportedKeyFormat
1826 *
1827 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
1828 */
1829// TODO(seleneh) add ExportKey to GenerateKey
1830// check result
1831
1832class ImportKeyTest : public KeyMintAidlTestBase {
1833 public:
1834 template <TagType tag_type, Tag tag, typename ValueT>
1835 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
1836 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07001837 for (auto& entry : key_characteristics_) {
1838 if (entry.securityLevel == SecLevel()) {
1839 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
1840 << "Tag " << tag << " with value " << expected
1841 << " not found at security level" << entry.securityLevel;
1842 } else {
1843 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
1844 << "Tag " << tag << " found at security level " << entry.securityLevel;
1845 }
Selene Huang31ab4042020-04-29 04:22:39 -07001846 }
1847 }
1848
1849 void CheckOrigin() {
1850 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07001851 // Origin isn't a crypto param, but it always lives with them.
1852 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07001853 }
1854};
1855
1856/*
1857 * ImportKeyTest.RsaSuccess
1858 *
1859 * Verifies that importing and using an RSA key pair works correctly.
1860 */
1861TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07001862 uint32_t key_size;
1863 string key;
1864
1865 if (SecLevel() == SecurityLevel::STRONGBOX) {
1866 key_size = 2048;
1867 key = rsa_2048_key;
1868 } else {
1869 key_size = 1024;
1870 key = rsa_key;
1871 }
1872
Selene Huang31ab4042020-04-29 04:22:39 -07001873 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1874 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07001875 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07001876 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001877 .Padding(PaddingMode::RSA_PSS)
1878 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07001879 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07001880
1881 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07001882 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001883 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
1884 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1885 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
1886 CheckOrigin();
1887
1888 string message(1024 / 8, 'a');
1889 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
1890 string signature = SignMessage(message, params);
1891 VerifyMessage(message, signature, params);
1892}
1893
1894/*
1895 * ImportKeyTest.RsaKeySizeMismatch
1896 *
1897 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
1898 * correct way.
1899 */
1900TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
1901 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
1902 ImportKey(AuthorizationSetBuilder()
1903 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
1904 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001905 .Padding(PaddingMode::NONE)
1906 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001907 KeyFormat::PKCS8, rsa_key));
1908}
1909
1910/*
1911 * ImportKeyTest.RsaPublicExponentMismatch
1912 *
1913 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
1914 * fails in the correct way.
1915 */
1916TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
1917 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
1918 ImportKey(AuthorizationSetBuilder()
1919 .RsaSigningKey(1024, 3 /* Doesn't match key */)
1920 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001921 .Padding(PaddingMode::NONE)
1922 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001923 KeyFormat::PKCS8, rsa_key));
1924}
1925
1926/*
1927 * ImportKeyTest.EcdsaSuccess
1928 *
1929 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
1930 */
1931TEST_P(ImportKeyTest, EcdsaSuccess) {
1932 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1933 .Authorization(TAG_NO_AUTH_REQUIRED)
1934 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001935 .Digest(Digest::SHA_2_256)
1936 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001937 KeyFormat::PKCS8, ec_256_key));
1938
1939 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
1940 CheckCryptoParam(TAG_KEY_SIZE, 256U);
1941 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1942 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
1943
1944 CheckOrigin();
1945
1946 string message(32, 'a');
1947 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
1948 string signature = SignMessage(message, params);
1949 VerifyMessage(message, signature, params);
1950}
1951
1952/*
1953 * ImportKeyTest.EcdsaP256RFC5915Success
1954 *
1955 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
1956 * correctly.
1957 */
1958TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
1959 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1960 .Authorization(TAG_NO_AUTH_REQUIRED)
1961 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001962 .Digest(Digest::SHA_2_256)
1963 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001964 KeyFormat::PKCS8, ec_256_key_rfc5915));
1965
1966 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
1967 CheckCryptoParam(TAG_KEY_SIZE, 256U);
1968 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1969 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
1970
1971 CheckOrigin();
1972
1973 string message(32, 'a');
1974 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
1975 string signature = SignMessage(message, params);
1976 VerifyMessage(message, signature, params);
1977}
1978
1979/*
1980 * ImportKeyTest.EcdsaP256SEC1Success
1981 *
1982 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
1983 */
1984TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
1985 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
1986 .Authorization(TAG_NO_AUTH_REQUIRED)
1987 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001988 .Digest(Digest::SHA_2_256)
1989 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001990 KeyFormat::PKCS8, ec_256_key_sec1));
1991
1992 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
1993 CheckCryptoParam(TAG_KEY_SIZE, 256U);
1994 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
1995 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
1996
1997 CheckOrigin();
1998
1999 string message(32, 'a');
2000 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2001 string signature = SignMessage(message, params);
2002 VerifyMessage(message, signature, params);
2003}
2004
2005/*
2006 * ImportKeyTest.Ecdsa521Success
2007 *
2008 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
2009 */
2010TEST_P(ImportKeyTest, Ecdsa521Success) {
2011 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2012 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2013 .Authorization(TAG_NO_AUTH_REQUIRED)
2014 .EcdsaSigningKey(521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002015 .Digest(Digest::SHA_2_256)
2016 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002017 KeyFormat::PKCS8, ec_521_key));
2018
2019 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
2020 CheckCryptoParam(TAG_KEY_SIZE, 521U);
2021 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2022 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
2023 CheckOrigin();
2024
2025 string message(32, 'a');
2026 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
2027 string signature = SignMessage(message, params);
2028 VerifyMessage(message, signature, params);
2029}
2030
2031/*
2032 * ImportKeyTest.EcdsaSizeMismatch
2033 *
2034 * Verifies that importing an ECDSA key pair with a size that doesn't match the key fails in the
2035 * correct way.
2036 */
2037TEST_P(ImportKeyTest, EcdsaSizeMismatch) {
2038 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2039 ImportKey(AuthorizationSetBuilder()
2040 .EcdsaSigningKey(224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002041 .Digest(Digest::NONE)
2042 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002043 KeyFormat::PKCS8, ec_256_key));
2044}
2045
2046/*
2047 * ImportKeyTest.EcdsaCurveMismatch
2048 *
2049 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
2050 * the correct way.
2051 */
2052TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
2053 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
2054 ImportKey(AuthorizationSetBuilder()
2055 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002056 .Digest(Digest::NONE)
2057 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07002058 KeyFormat::PKCS8, ec_256_key));
2059}
2060
2061/*
2062 * ImportKeyTest.AesSuccess
2063 *
2064 * Verifies that importing and using an AES key works.
2065 */
2066TEST_P(ImportKeyTest, AesSuccess) {
2067 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2068 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2069 .Authorization(TAG_NO_AUTH_REQUIRED)
2070 .AesEncryptionKey(key.size() * 8)
2071 .EcbMode()
2072 .Padding(PaddingMode::PKCS7),
2073 KeyFormat::RAW, key));
2074
2075 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
2076 CheckCryptoParam(TAG_KEY_SIZE, 128U);
2077 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
2078 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
2079 CheckOrigin();
2080
2081 string message = "Hello World!";
2082 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2083 string ciphertext = EncryptMessage(message, params);
2084 string plaintext = DecryptMessage(ciphertext, params);
2085 EXPECT_EQ(message, plaintext);
2086}
2087
2088/*
2089 * ImportKeyTest.AesSuccess
2090 *
2091 * Verifies that importing and using an HMAC key works.
2092 */
2093TEST_P(ImportKeyTest, HmacKeySuccess) {
2094 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
2095 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
2096 .Authorization(TAG_NO_AUTH_REQUIRED)
2097 .HmacKey(key.size() * 8)
2098 .Digest(Digest::SHA_2_256)
2099 .Authorization(TAG_MIN_MAC_LENGTH, 256),
2100 KeyFormat::RAW, key));
2101
2102 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
2103 CheckCryptoParam(TAG_KEY_SIZE, 128U);
2104 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
2105 CheckOrigin();
2106
2107 string message = "Hello World!";
2108 string signature = MacMessage(message, Digest::SHA_2_256, 256);
2109 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2110}
2111
2112INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
2113
2114auto wrapped_key = hex2str(
2115 "3082017902010004820100934bf94e2aa28a3f83c9f79297250262fbe3276b5a1c91159bbfa3ef8957aac8"
2116 "4b59b30b455a79c2973480823d8b3863c3deef4a8e243590268d80e18751a0e130f67ce6a1ace9f79b95e0"
2117 "97474febc981195b1d13a69086c0863f66a7b7fdb48792227b1ac5e2489febdf087ab5486483033a6f001c"
2118 "a5d1ec1e27f5c30f4cec2642074a39ae68aee552e196627a8e3d867e67a8c01b11e75f13cca0a97ab668b5"
2119 "0cda07a8ecb7cd8e3dd7009c9636534f6f239cffe1fc8daa466f78b676c7119efb96bce4e69ca2a25d0b34"
2120 "ed9c3ff999b801597d5220e307eaa5bee507fb94d1fa69f9e519b2de315bac92c36f2ea1fa1df4478c0dde"
2121 "deae8c70e0233cd098040cd796b02c370f1fa4cc0124f1302e0201033029a1083106020100020101a20302"
2122 "0120a30402020100a4053103020101a6053103020140bf83770205000420ccd540855f833a5e1480bfd2d3"
2123 "6faf3aeee15df5beabe2691bc82dde2a7aa910041064c9f689c60ff6223ab6e6999e0eb6e5");
2124
2125auto wrapped_key_masked = hex2str(
2126 "3082017902010004820100aad93ed5924f283b4bb5526fbe7a1412f9d9749ec30db9062b29e574a8546f33"
2127 "c88732452f5b8e6a391ee76c39ed1712c61d8df6213dec1cffbc17a8c6d04c7b30893d8daa9b2015213e21"
2128 "946821553207f8f9931c4caba23ed3bee28b36947e47f10e0a5c3dc51c988a628daad3e5e1f4005e79c2d5"
2129 "a96c284b4b8d7e4948f331e5b85dd5a236f85579f3ea1d1b848487470bdb0ab4f81a12bee42c99fe0df4be"
2130 "e3759453e69ad1d68a809ce06b949f7694a990429b2fe81e066ff43e56a21602db70757922a4bcc23ab89f"
2131 "1e35da77586775f423e519c2ea394caf48a28d0c8020f1dcf6b3a68ec246f615ae96dae9a079b1f6eb9590"
2132 "33c1af5c125fd94168040c6d9721d08589581ab49204a3302e0201033029a1083106020100020101a20302"
2133 "0120a30402020100a4053103020101a6053103020140bf83770205000420a61c6e247e25b3e6e69aa78eb0"
2134 "3c2d4ac20d1f99a9a024a76f35c8e2cab9b68d04102560c70109ae67c030f00b98b512a670");
2135
2136auto wrapping_key = hex2str(
2137 "308204be020100300d06092a864886f70d0101010500048204a8308204a40201000282010100aec367931d"
2138 "8900ce56b0067f7d70e1fc653f3f34d194c1fed50018fb43db937b06e673a837313d56b1c725150a3fef86"
2139 "acbddc41bb759c2854eae32d35841efb5c18d82bc90a1cb5c1d55adf245b02911f0b7cda88c421ff0ebafe"
2140 "7c0d23be312d7bd5921ffaea1347c157406fef718f682643e4e5d33c6703d61c0cf7ac0bf4645c11f5c137"
2141 "4c3886427411c449796792e0bef75dec858a2123c36753e02a95a96d7c454b504de385a642e0dfc3e60ac3"
2142 "a7ee4991d0d48b0172a95f9536f02ba13cecccb92b727db5c27e5b2f5cec09600b286af5cf14c42024c61d"
2143 "dfe71c2a8d7458f185234cb00e01d282f10f8fc6721d2aed3f4833cca2bd8fa62821dd5502030100010282"
2144 "0100431447b6251908112b1ee76f99f3711a52b6630960046c2de70de188d833f8b8b91e4d785caeeeaf4f"
2145 "0f74414e2cda40641f7fe24f14c67a88959bdb27766df9e710b630a03adc683b5d2c43080e52bee71e9eae"
2146 "b6de297a5fea1072070d181c822bccff087d63c940ba8a45f670feb29fb4484d1c95e6d2579ba02aae0a00"
2147 "900c3ebf490e3d2cd7ee8d0e20c536e4dc5a5097272888cddd7e91f228b1c4d7474c55b8fcd618c4a957bb"
2148 "ddd5ad7407cc312d8d98a5caf7e08f4a0d6b45bb41c652659d5a5ba05b663737a8696281865ba20fbdd7f8"
2149 "51e6c56e8cbe0ddbbf24dc03b2d2cb4c3d540fb0af52e034a2d06698b128e5f101e3b51a34f8d8b4f86181"
2150 "02818100de392e18d682c829266cc3454e1d6166242f32d9a1d10577753e904ea7d08bff841be5bac82a16"
2151 "4c5970007047b8c517db8f8f84e37bd5988561bdf503d4dc2bdb38f885434ae42c355f725c9a60f91f0788"
2152 "e1f1a97223b524b5357fdf72e2f696bab7d78e32bf92ba8e1864eab1229e91346130748a6e3c124f9149d7"
2153 "1c743502818100c95387c0f9d35f137b57d0d65c397c5e21cc251e47008ed62a542409c8b6b6ac7f8967b3"
2154 "863ca645fcce49582a9aa17349db6c4a95affdae0dae612e1afac99ed39a2d934c880440aed8832f984316"
2155 "3a47f27f392199dc1202f9a0f9bd08308007cb1e4e7f58309366a7de25f7c3c9b880677c068e1be936e812"
2156 "88815252a8a102818057ff8ca1895080b2cae486ef0adfd791fb0235c0b8b36cd6c136e52e4085f4ea5a06"
2157 "3212a4f105a3764743e53281988aba073f6e0027298e1c4378556e0efca0e14ece1af76ad0b030f27af6f0"
2158 "ab35fb73a060d8b1a0e142fa2647e93b32e36d8282ae0a4de50ab7afe85500a16f43a64719d6e2b9439823"
2159 "719cd08bcd03178102818100ba73b0bb28e3f81e9bd1c568713b101241acc607976c4ddccc90e65b6556ca"
2160 "31516058f92b6e09f3b160ff0e374ec40d78ae4d4979fde6ac06a1a400c61dd31254186af30b22c10582a8"
2161 "a43e34fe949c5f3b9755bae7baa7b7b7a6bd03b38cef55c86885fc6c1978b9cee7ef33da507c9df6b9277c"
2162 "ff1e6aaa5d57aca528466102818100c931617c77829dfb1270502be9195c8f2830885f57dba869536811e6"
2163 "864236d0c4736a0008a145af36b8357a7c3d139966d04c4e00934ea1aede3bb6b8ec841dc95e3f579751e2"
2164 "bfdfe27ae778983f959356210723287b0affcc9f727044d48c373f1babde0724fa17a4fd4da0902c7c9b9b"
2165 "f27ba61be6ad02dfddda8f4e6822");
2166
2167string zero_masking_key =
2168 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
2169string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
2170
2171class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
2172
2173TEST_P(ImportWrappedKeyTest, Success) {
2174 auto wrapping_key_desc = AuthorizationSetBuilder()
2175 .RsaEncryptionKey(2048, 65537)
2176 .Digest(Digest::SHA_2_256)
2177 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002178 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
2179 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002180
2181 ASSERT_EQ(ErrorCode::OK,
2182 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
2183 AuthorizationSetBuilder()
2184 .Digest(Digest::SHA_2_256)
2185 .Padding(PaddingMode::RSA_OAEP)));
2186
2187 string message = "Hello World!";
2188 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2189 string ciphertext = EncryptMessage(message, params);
2190 string plaintext = DecryptMessage(ciphertext, params);
2191 EXPECT_EQ(message, plaintext);
2192}
2193
2194TEST_P(ImportWrappedKeyTest, SuccessMasked) {
2195 auto wrapping_key_desc = AuthorizationSetBuilder()
2196 .RsaEncryptionKey(2048, 65537)
2197 .Digest(Digest::SHA_2_256)
2198 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002199 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
2200 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002201
2202 ASSERT_EQ(ErrorCode::OK,
2203 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
2204 AuthorizationSetBuilder()
2205 .Digest(Digest::SHA_2_256)
2206 .Padding(PaddingMode::RSA_OAEP)));
2207}
2208
2209TEST_P(ImportWrappedKeyTest, WrongMask) {
2210 auto wrapping_key_desc = AuthorizationSetBuilder()
2211 .RsaEncryptionKey(2048, 65537)
2212 .Digest(Digest::SHA_2_256)
2213 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002214 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
2215 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002216
2217 ASSERT_EQ(
2218 ErrorCode::VERIFICATION_FAILED,
2219 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
2220 AuthorizationSetBuilder()
2221 .Digest(Digest::SHA_2_256)
2222 .Padding(PaddingMode::RSA_OAEP)));
2223}
2224
2225TEST_P(ImportWrappedKeyTest, WrongPurpose) {
2226 auto wrapping_key_desc = AuthorizationSetBuilder()
2227 .RsaEncryptionKey(2048, 65537)
2228 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002229 .Padding(PaddingMode::RSA_OAEP)
2230 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07002231
2232 ASSERT_EQ(
2233 ErrorCode::INCOMPATIBLE_PURPOSE,
2234 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
2235 AuthorizationSetBuilder()
2236 .Digest(Digest::SHA_2_256)
2237 .Padding(PaddingMode::RSA_OAEP)));
2238}
2239
2240INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
2241
2242typedef KeyMintAidlTestBase EncryptionOperationsTest;
2243
2244/*
2245 * EncryptionOperationsTest.RsaNoPaddingSuccess
2246 *
2247 * Verifies that raw RSA encryption works.
2248 */
2249TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
2250 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2251 .Authorization(TAG_NO_AUTH_REQUIRED)
2252 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002253 .Padding(PaddingMode::NONE)
2254 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002255
2256 string message = string(2048 / 8, 'a');
2257 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2258 string ciphertext1 = EncryptMessage(message, params);
2259 EXPECT_EQ(2048U / 8, ciphertext1.size());
2260
2261 string ciphertext2 = EncryptMessage(message, params);
2262 EXPECT_EQ(2048U / 8, ciphertext2.size());
2263
2264 // Unpadded RSA is deterministic
2265 EXPECT_EQ(ciphertext1, ciphertext2);
2266}
2267
2268/*
2269 * EncryptionOperationsTest.RsaNoPaddingShortMessage
2270 *
2271 * Verifies that raw RSA encryption of short messages works.
2272 */
2273TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
2274 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2275 .Authorization(TAG_NO_AUTH_REQUIRED)
2276 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002277 .Padding(PaddingMode::NONE)
2278 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002279
2280 string message = "1";
2281 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2282
2283 string ciphertext = EncryptMessage(message, params);
2284 EXPECT_EQ(2048U / 8, ciphertext.size());
2285
2286 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
2287 string plaintext = DecryptMessage(ciphertext, params);
2288
2289 EXPECT_EQ(expected_plaintext, plaintext);
2290
2291 // Degenerate case, encrypting a numeric 1 yields 0x00..01 as the ciphertext.
2292 message = static_cast<char>(1);
2293 ciphertext = EncryptMessage(message, params);
2294 EXPECT_EQ(2048U / 8, ciphertext.size());
2295 EXPECT_EQ(ciphertext, string(2048U / 8 - 1, 0) + message);
2296}
2297
2298/*
2299 * EncryptionOperationsTest.RsaNoPaddingTooLong
2300 *
2301 * Verifies that raw RSA encryption of too-long messages fails in the expected way.
2302 */
2303TEST_P(EncryptionOperationsTest, RsaNoPaddingTooLong) {
2304 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2305 .Authorization(TAG_NO_AUTH_REQUIRED)
2306 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002307 .Padding(PaddingMode::NONE)
2308 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002309
2310 string message(2048 / 8 + 1, 'a');
2311
2312 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
2313 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2314
2315 string result;
2316 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &result));
2317}
2318
2319/*
2320 * EncryptionOperationsTest.RsaNoPaddingTooLarge
2321 *
2322 * Verifies that raw RSA encryption of too-large (numerically) messages fails in the expected
2323 * way.
2324 */
2325// TODO(seleneh) add RsaNoPaddingTooLarge test back after decided and implemented new
2326// version of ExportKey inside generateKey
2327
2328/*
2329 * EncryptionOperationsTest.RsaOaepSuccess
2330 *
2331 * Verifies that RSA-OAEP encryption operations work, with all digests.
2332 */
2333TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
2334 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
2335
2336 size_t key_size = 2048; // Need largish key for SHA-512 test.
2337 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2338 .Authorization(TAG_NO_AUTH_REQUIRED)
2339 .RsaEncryptionKey(key_size, 65537)
2340 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002341 .Digest(digests)
2342 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002343
2344 string message = "Hello";
2345
2346 for (auto digest : digests) {
2347 auto params = AuthorizationSetBuilder().Digest(digest).Padding(PaddingMode::RSA_OAEP);
2348 string ciphertext1 = EncryptMessage(message, params);
2349 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
2350 EXPECT_EQ(key_size / 8, ciphertext1.size());
2351
2352 string ciphertext2 = EncryptMessage(message, params);
2353 EXPECT_EQ(key_size / 8, ciphertext2.size());
2354
2355 // OAEP randomizes padding so every result should be different (with astronomically high
2356 // probability).
2357 EXPECT_NE(ciphertext1, ciphertext2);
2358
2359 string plaintext1 = DecryptMessage(ciphertext1, params);
2360 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
2361 string plaintext2 = DecryptMessage(ciphertext2, params);
2362 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
2363
2364 // Decrypting corrupted ciphertext should fail.
2365 size_t offset_to_corrupt = random() % ciphertext1.size();
2366 char corrupt_byte;
2367 do {
2368 corrupt_byte = static_cast<char>(random() % 256);
2369 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2370 ciphertext1[offset_to_corrupt] = corrupt_byte;
2371
2372 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2373 string result;
2374 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2375 EXPECT_EQ(0U, result.size());
2376 }
2377}
2378
2379/*
2380 * EncryptionOperationsTest.RsaOaepInvalidDigest
2381 *
2382 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2383 * without a digest.
2384 */
2385TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
2386 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2387 .Authorization(TAG_NO_AUTH_REQUIRED)
2388 .RsaEncryptionKey(2048, 65537)
2389 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002390 .Digest(Digest::NONE)
2391 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002392 string message = "Hello World!";
2393
2394 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
2395 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2396}
2397
2398/*
2399 * EncryptionOperationsTest.RsaOaepInvalidDigest
2400 *
2401 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to decrypt
2402 * with a different digest than was used to encrypt.
2403 */
2404TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
2405 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2406
2407 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2408 .Authorization(TAG_NO_AUTH_REQUIRED)
2409 .RsaEncryptionKey(1024, 65537)
2410 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002411 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
2412 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002413 string message = "Hello World!";
2414 string ciphertext = EncryptMessage(
2415 message,
2416 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
2417
2418 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
2419 .Digest(Digest::SHA_2_256)
2420 .Padding(PaddingMode::RSA_OAEP)));
2421 string result;
2422 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
2423 EXPECT_EQ(0U, result.size());
2424}
2425
2426/*
2427 * EncryptionOperationsTest.RsaOaepTooLarge
2428 *
2429 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to encrypt a
2430 * too-large message.
2431 */
2432TEST_P(EncryptionOperationsTest, RsaOaepTooLarge) {
2433 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2434 .Authorization(TAG_NO_AUTH_REQUIRED)
2435 .RsaEncryptionKey(2048, 65537)
2436 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002437 .Digest(Digest::SHA_2_256)
2438 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002439 constexpr size_t digest_size = 256 /* SHA_2_256 */ / 8;
2440 constexpr size_t oaep_overhead = 2 * digest_size + 2;
2441 string message(2048 / 8 - oaep_overhead + 1, 'a');
2442 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
2443 .Padding(PaddingMode::RSA_OAEP)
2444 .Digest(Digest::SHA_2_256)));
2445 string result;
2446 ErrorCode error = Finish(message, &result);
2447 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2448 EXPECT_EQ(0U, result.size());
2449}
2450
2451/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002452 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
2453 *
2454 * Verifies that RSA-OAEP encryption operations work, with all SHA 256 digests and all type of MGF1
2455 * digests.
2456 */
2457TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
2458 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
2459
2460 size_t key_size = 2048; // Need largish key for SHA-512 test.
2461 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2462 .OaepMGFDigest(digests)
2463 .Authorization(TAG_NO_AUTH_REQUIRED)
2464 .RsaEncryptionKey(key_size, 65537)
2465 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002466 .Digest(Digest::SHA_2_256)
2467 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002468
2469 string message = "Hello";
2470
2471 for (auto digest : digests) {
2472 auto params = AuthorizationSetBuilder()
2473 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
2474 .Digest(Digest::SHA_2_256)
2475 .Padding(PaddingMode::RSA_OAEP);
2476 string ciphertext1 = EncryptMessage(message, params);
2477 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
2478 EXPECT_EQ(key_size / 8, ciphertext1.size());
2479
2480 string ciphertext2 = EncryptMessage(message, params);
2481 EXPECT_EQ(key_size / 8, ciphertext2.size());
2482
2483 // OAEP randomizes padding so every result should be different (with astronomically high
2484 // probability).
2485 EXPECT_NE(ciphertext1, ciphertext2);
2486
2487 string plaintext1 = DecryptMessage(ciphertext1, params);
2488 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
2489 string plaintext2 = DecryptMessage(ciphertext2, params);
2490 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
2491
2492 // Decrypting corrupted ciphertext should fail.
2493 size_t offset_to_corrupt = random() % ciphertext1.size();
2494 char corrupt_byte;
2495 do {
2496 corrupt_byte = static_cast<char>(random() % 256);
2497 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2498 ciphertext1[offset_to_corrupt] = corrupt_byte;
2499
2500 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2501 string result;
2502 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2503 EXPECT_EQ(0U, result.size());
2504 }
2505}
2506
2507/*
2508 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
2509 *
2510 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2511 * with incompatible MGF digest.
2512 */
2513TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
2514 ASSERT_EQ(ErrorCode::OK,
2515 GenerateKey(AuthorizationSetBuilder()
2516 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
2517 .Authorization(TAG_NO_AUTH_REQUIRED)
2518 .RsaEncryptionKey(2048, 65537)
2519 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002520 .Digest(Digest::SHA_2_256)
2521 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002522 string message = "Hello World!";
2523
2524 auto params = AuthorizationSetBuilder()
2525 .Padding(PaddingMode::RSA_OAEP)
2526 .Digest(Digest::SHA_2_256)
2527 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
2528 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2529}
2530
2531/*
2532 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
2533 *
2534 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
2535 * with unsupported MGF digest.
2536 */
2537TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
2538 ASSERT_EQ(ErrorCode::OK,
2539 GenerateKey(AuthorizationSetBuilder()
2540 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
2541 .Authorization(TAG_NO_AUTH_REQUIRED)
2542 .RsaEncryptionKey(2048, 65537)
2543 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002544 .Digest(Digest::SHA_2_256)
2545 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05002546 string message = "Hello World!";
2547
2548 auto params = AuthorizationSetBuilder()
2549 .Padding(PaddingMode::RSA_OAEP)
2550 .Digest(Digest::SHA_2_256)
2551 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
2552 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::ENCRYPT, params));
2553}
2554
2555/*
Selene Huang31ab4042020-04-29 04:22:39 -07002556 * EncryptionOperationsTest.RsaPkcs1Success
2557 *
2558 * Verifies that RSA PKCS encryption/decrypts works.
2559 */
2560TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
2561 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2562 .Authorization(TAG_NO_AUTH_REQUIRED)
2563 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002564 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
2565 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002566
2567 string message = "Hello World!";
2568 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2569 string ciphertext1 = EncryptMessage(message, params);
2570 EXPECT_EQ(2048U / 8, ciphertext1.size());
2571
2572 string ciphertext2 = EncryptMessage(message, params);
2573 EXPECT_EQ(2048U / 8, ciphertext2.size());
2574
2575 // PKCS1 v1.5 randomizes padding so every result should be different.
2576 EXPECT_NE(ciphertext1, ciphertext2);
2577
2578 string plaintext = DecryptMessage(ciphertext1, params);
2579 EXPECT_EQ(message, plaintext);
2580
2581 // Decrypting corrupted ciphertext should fail.
2582 size_t offset_to_corrupt = random() % ciphertext1.size();
2583 char corrupt_byte;
2584 do {
2585 corrupt_byte = static_cast<char>(random() % 256);
2586 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
2587 ciphertext1[offset_to_corrupt] = corrupt_byte;
2588
2589 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2590 string result;
2591 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
2592 EXPECT_EQ(0U, result.size());
2593}
2594
2595/*
2596 * EncryptionOperationsTest.RsaPkcs1TooLarge
2597 *
2598 * Verifies that RSA PKCS encryption fails in the correct way when the mssage is too large.
2599 */
2600TEST_P(EncryptionOperationsTest, RsaPkcs1TooLarge) {
2601 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2602 .Authorization(TAG_NO_AUTH_REQUIRED)
2603 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002604 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
2605 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002606 string message(2048 / 8 - 10, 'a');
2607
2608 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
2609 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2610 string result;
2611 ErrorCode error = Finish(message, &result);
2612 EXPECT_TRUE(error == ErrorCode::INVALID_INPUT_LENGTH || error == ErrorCode::INVALID_ARGUMENT);
2613 EXPECT_EQ(0U, result.size());
2614}
2615
2616/*
2617 * EncryptionOperationsTest.EcdsaEncrypt
2618 *
2619 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
2620 */
2621TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
2622 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2623 .Authorization(TAG_NO_AUTH_REQUIRED)
2624 .EcdsaSigningKey(256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002625 .Digest(Digest::NONE)
2626 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002627 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
2628 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
2629 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
2630}
2631
2632/*
2633 * EncryptionOperationsTest.HmacEncrypt
2634 *
2635 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
2636 */
2637TEST_P(EncryptionOperationsTest, HmacEncrypt) {
2638 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2639 .Authorization(TAG_NO_AUTH_REQUIRED)
2640 .HmacKey(128)
2641 .Digest(Digest::SHA_2_256)
2642 .Padding(PaddingMode::NONE)
2643 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2644 auto params = AuthorizationSetBuilder()
2645 .Digest(Digest::SHA_2_256)
2646 .Padding(PaddingMode::NONE)
2647 .Authorization(TAG_MAC_LENGTH, 128);
2648 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
2649 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
2650}
2651
2652/*
2653 * EncryptionOperationsTest.AesEcbRoundTripSuccess
2654 *
2655 * Verifies that AES ECB mode works.
2656 */
2657TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
2658 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2659 .Authorization(TAG_NO_AUTH_REQUIRED)
2660 .AesEncryptionKey(128)
2661 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2662 .Padding(PaddingMode::NONE)));
2663
2664 ASSERT_GT(key_blob_.size(), 0U);
2665 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2666
2667 // Two-block message.
2668 string message = "12345678901234567890123456789012";
2669 string ciphertext1 = EncryptMessage(message, params);
2670 EXPECT_EQ(message.size(), ciphertext1.size());
2671
2672 string ciphertext2 = EncryptMessage(string(message), params);
2673 EXPECT_EQ(message.size(), ciphertext2.size());
2674
2675 // ECB is deterministic.
2676 EXPECT_EQ(ciphertext1, ciphertext2);
2677
2678 string plaintext = DecryptMessage(ciphertext1, params);
2679 EXPECT_EQ(message, plaintext);
2680}
2681
2682/*
2683 * EncryptionOperationsTest.AesEcbRoundTripSuccess
2684 *
2685 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
2686 */
2687TEST_P(EncryptionOperationsTest, AesWrongMode) {
2688 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2689 .Authorization(TAG_NO_AUTH_REQUIRED)
2690 .AesEncryptionKey(128)
2691 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
2692 .Padding(PaddingMode::NONE)));
2693
2694 ASSERT_GT(key_blob_.size(), 0U);
2695
2696 // Two-block message.
2697 string message = "12345678901234567890123456789012";
2698 EXPECT_EQ(
2699 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
2700 Begin(KeyPurpose::ENCRYPT,
2701 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
2702}
2703
2704/*
2705 * EncryptionOperationsTest.AesWrongPurpose
2706 *
2707 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
2708 * specified.
2709 */
2710TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
2711 auto err = GenerateKey(AuthorizationSetBuilder()
2712 .Authorization(TAG_NO_AUTH_REQUIRED)
2713 .AesKey(128)
2714 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
2715 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
2716 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2717 .Padding(PaddingMode::NONE));
2718 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
2719 ASSERT_GT(key_blob_.size(), 0U);
2720
2721 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
2722 .BlockMode(BlockMode::GCM)
2723 .Padding(PaddingMode::NONE)
2724 .Authorization(TAG_MAC_LENGTH, 128));
2725 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
2726
2727 CheckedDeleteKey();
2728
2729 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2730 .Authorization(TAG_NO_AUTH_REQUIRED)
2731 .AesKey(128)
2732 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
2733 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
2734 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2735 .Padding(PaddingMode::NONE)));
2736
2737 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
2738 .BlockMode(BlockMode::GCM)
2739 .Padding(PaddingMode::NONE)
2740 .Authorization(TAG_MAC_LENGTH, 128));
2741 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
2742}
2743
2744/*
2745 * EncryptionOperationsTest.AesEcbNoPaddingWrongInputSize
2746 *
2747 * Verifies that AES encryption fails in the correct way when provided an input that is not a
2748 * multiple of the block size and no padding is specified.
2749 */
2750TEST_P(EncryptionOperationsTest, AesEcbNoPaddingWrongInputSize) {
2751 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2752 .Authorization(TAG_NO_AUTH_REQUIRED)
2753 .AesEncryptionKey(128)
2754 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2755 .Padding(PaddingMode::NONE)));
2756 // Message is slightly shorter than two blocks.
2757 string message(16 * 2 - 1, 'a');
2758
2759 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
2760 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
2761 string ciphertext;
2762 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
2763 EXPECT_EQ(0U, ciphertext.size());
2764}
2765
2766/*
2767 * EncryptionOperationsTest.AesEcbPkcs7Padding
2768 *
2769 * Verifies that AES PKCS7 padding works for any message length.
2770 */
2771TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
2772 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2773 .Authorization(TAG_NO_AUTH_REQUIRED)
2774 .AesEncryptionKey(128)
2775 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2776 .Padding(PaddingMode::PKCS7)));
2777
2778 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2779
2780 // Try various message lengths; all should work.
2781 for (size_t i = 0; i < 32; ++i) {
2782 string message(i, 'a');
2783 string ciphertext = EncryptMessage(message, params);
2784 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
2785 string plaintext = DecryptMessage(ciphertext, params);
2786 EXPECT_EQ(message, plaintext);
2787 }
2788}
2789
2790/*
2791 * EncryptionOperationsTest.AesEcbWrongPadding
2792 *
2793 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
2794 * specified.
2795 */
2796TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
2797 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2798 .Authorization(TAG_NO_AUTH_REQUIRED)
2799 .AesEncryptionKey(128)
2800 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2801 .Padding(PaddingMode::NONE)));
2802
2803 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2804
2805 // Try various message lengths; all should fail
2806 for (size_t i = 0; i < 32; ++i) {
2807 string message(i, 'a');
2808 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
2809 }
2810}
2811
2812/*
2813 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
2814 *
2815 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
2816 */
2817TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
2818 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2819 .Authorization(TAG_NO_AUTH_REQUIRED)
2820 .AesEncryptionKey(128)
2821 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
2822 .Padding(PaddingMode::PKCS7)));
2823
2824 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
2825
2826 string message = "a";
2827 string ciphertext = EncryptMessage(message, params);
2828 EXPECT_EQ(16U, ciphertext.size());
2829 EXPECT_NE(ciphertext, message);
2830 ++ciphertext[ciphertext.size() / 2];
2831
2832 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
2833 string plaintext;
2834 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
2835}
2836
2837vector<uint8_t> CopyIv(const AuthorizationSet& set) {
2838 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002839 EXPECT_TRUE(iv);
2840 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07002841}
2842
2843/*
2844 * EncryptionOperationsTest.AesCtrRoundTripSuccess
2845 *
2846 * Verifies that AES CTR mode works.
2847 */
2848TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
2849 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2850 .Authorization(TAG_NO_AUTH_REQUIRED)
2851 .AesEncryptionKey(128)
2852 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
2853 .Padding(PaddingMode::NONE)));
2854
2855 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
2856
2857 string message = "123";
2858 AuthorizationSet out_params;
2859 string ciphertext1 = EncryptMessage(message, params, &out_params);
2860 vector<uint8_t> iv1 = CopyIv(out_params);
2861 EXPECT_EQ(16U, iv1.size());
2862
2863 EXPECT_EQ(message.size(), ciphertext1.size());
2864
2865 out_params.Clear();
2866 string ciphertext2 = EncryptMessage(message, params, &out_params);
2867 vector<uint8_t> iv2 = CopyIv(out_params);
2868 EXPECT_EQ(16U, iv2.size());
2869
2870 // IVs should be random, so ciphertexts should differ.
2871 EXPECT_NE(ciphertext1, ciphertext2);
2872
2873 auto params_iv1 =
2874 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
2875 auto params_iv2 =
2876 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
2877
2878 string plaintext = DecryptMessage(ciphertext1, params_iv1);
2879 EXPECT_EQ(message, plaintext);
2880 plaintext = DecryptMessage(ciphertext2, params_iv2);
2881 EXPECT_EQ(message, plaintext);
2882
2883 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
2884 plaintext = DecryptMessage(ciphertext1, params_iv2);
2885 EXPECT_NE(message, plaintext);
2886 plaintext = DecryptMessage(ciphertext2, params_iv1);
2887 EXPECT_NE(message, plaintext);
2888}
2889
2890/*
2891 * EncryptionOperationsTest.AesIncremental
2892 *
2893 * Verifies that AES works, all modes, when provided data in various size increments.
2894 */
2895TEST_P(EncryptionOperationsTest, AesIncremental) {
2896 auto block_modes = {
2897 BlockMode::ECB,
2898 BlockMode::CBC,
2899 BlockMode::CTR,
2900 BlockMode::GCM,
2901 };
2902
2903 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2904 .Authorization(TAG_NO_AUTH_REQUIRED)
2905 .AesEncryptionKey(128)
2906 .BlockMode(block_modes)
2907 .Padding(PaddingMode::NONE)
2908 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2909
2910 for (int increment = 1; increment <= 240; ++increment) {
2911 for (auto block_mode : block_modes) {
2912 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07002913 auto params =
2914 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
2915 if (block_mode == BlockMode::GCM) {
2916 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
2917 }
Selene Huang31ab4042020-04-29 04:22:39 -07002918
2919 AuthorizationSet output_params;
2920 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
2921
2922 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07002923 string to_send;
2924 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07002925 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07002926 }
Shawn Willden92d79c02021-02-19 07:31:55 -07002927 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
2928 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07002929
2930 switch (block_mode) {
2931 case BlockMode::GCM:
2932 EXPECT_EQ(message.size() + 16, ciphertext.size());
2933 break;
2934 case BlockMode::CTR:
2935 EXPECT_EQ(message.size(), ciphertext.size());
2936 break;
2937 case BlockMode::CBC:
2938 case BlockMode::ECB:
2939 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
2940 break;
2941 }
2942
2943 auto iv = output_params.GetTagValue(TAG_NONCE);
2944 switch (block_mode) {
2945 case BlockMode::CBC:
2946 case BlockMode::GCM:
2947 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002948 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
2949 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
2950 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07002951 break;
2952
2953 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08002954 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07002955 break;
2956 }
2957
2958 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
2959 << "Decrypt begin() failed for block mode " << block_mode;
2960
2961 string plaintext;
2962 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07002963 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07002964 }
2965 ErrorCode error = Finish(to_send, &plaintext);
2966 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
2967 << " and increment " << increment;
2968 if (error == ErrorCode::OK) {
2969 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
2970 << block_mode << " and increment " << increment;
2971 }
2972 }
2973 }
2974}
2975
2976struct AesCtrSp80038aTestVector {
2977 const char* key;
2978 const char* nonce;
2979 const char* plaintext;
2980 const char* ciphertext;
2981};
2982
2983// These test vectors are taken from
2984// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
2985static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
2986 // AES-128
2987 {
2988 "2b7e151628aed2a6abf7158809cf4f3c",
2989 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2990 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
2991 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
2992 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
2993 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
2994 },
2995 // AES-192
2996 {
2997 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
2998 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
2999 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3000 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3001 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
3002 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
3003 },
3004 // AES-256
3005 {
3006 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
3007 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
3008 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
3009 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
3010 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
3011 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
3012 },
3013};
3014
3015/*
3016 * EncryptionOperationsTest.AesCtrSp80038aTestVector
3017 *
3018 * Verifies AES CTR implementation against SP800-38A test vectors.
3019 */
3020TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
3021 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
3022 for (size_t i = 0; i < 3; i++) {
3023 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
3024 const string key = hex2str(test.key);
3025 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
3026 InvalidSizes.end())
3027 continue;
3028 const string nonce = hex2str(test.nonce);
3029 const string plaintext = hex2str(test.plaintext);
3030 const string ciphertext = hex2str(test.ciphertext);
3031 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
3032 }
3033}
3034
3035/*
3036 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
3037 *
3038 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
3039 */
3040TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
3041 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3042 .Authorization(TAG_NO_AUTH_REQUIRED)
3043 .AesEncryptionKey(128)
3044 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3045 .Padding(PaddingMode::PKCS7)));
3046 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
3047 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
3048}
3049
3050/*
3051 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3052 *
3053 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
3054 */
3055TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
3056 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3057 .Authorization(TAG_NO_AUTH_REQUIRED)
3058 .AesEncryptionKey(128)
3059 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
3060 .Authorization(TAG_CALLER_NONCE)
3061 .Padding(PaddingMode::NONE)));
3062
3063 auto params = AuthorizationSetBuilder()
3064 .BlockMode(BlockMode::CTR)
3065 .Padding(PaddingMode::NONE)
3066 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
3067 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3068
3069 params = AuthorizationSetBuilder()
3070 .BlockMode(BlockMode::CTR)
3071 .Padding(PaddingMode::NONE)
3072 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
3073 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3074
3075 params = AuthorizationSetBuilder()
3076 .BlockMode(BlockMode::CTR)
3077 .Padding(PaddingMode::NONE)
3078 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
3079 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
3080}
3081
3082/*
3083 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
3084 *
3085 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
3086 */
3087TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
3088 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3089 .Authorization(TAG_NO_AUTH_REQUIRED)
3090 .AesEncryptionKey(128)
3091 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3092 .Padding(PaddingMode::NONE)));
3093 // Two-block message.
3094 string message = "12345678901234567890123456789012";
3095 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3096 AuthorizationSet out_params;
3097 string ciphertext1 = EncryptMessage(message, params, &out_params);
3098 vector<uint8_t> iv1 = CopyIv(out_params);
3099 EXPECT_EQ(message.size(), ciphertext1.size());
3100
3101 out_params.Clear();
3102
3103 string ciphertext2 = EncryptMessage(message, params, &out_params);
3104 vector<uint8_t> iv2 = CopyIv(out_params);
3105 EXPECT_EQ(message.size(), ciphertext2.size());
3106
3107 // IVs should be random, so ciphertexts should differ.
3108 EXPECT_NE(ciphertext1, ciphertext2);
3109
3110 params.push_back(TAG_NONCE, iv1);
3111 string plaintext = DecryptMessage(ciphertext1, params);
3112 EXPECT_EQ(message, plaintext);
3113}
3114
3115/*
3116 * EncryptionOperationsTest.AesCallerNonce
3117 *
3118 * Verifies that AES caller-provided nonces work correctly.
3119 */
3120TEST_P(EncryptionOperationsTest, AesCallerNonce) {
3121 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3122 .Authorization(TAG_NO_AUTH_REQUIRED)
3123 .AesEncryptionKey(128)
3124 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3125 .Authorization(TAG_CALLER_NONCE)
3126 .Padding(PaddingMode::NONE)));
3127
3128 string message = "12345678901234567890123456789012";
3129
3130 // Don't specify nonce, should get a random one.
3131 AuthorizationSetBuilder params =
3132 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3133 AuthorizationSet out_params;
3134 string ciphertext = EncryptMessage(message, params, &out_params);
3135 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003136 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07003137
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003138 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003139 string plaintext = DecryptMessage(ciphertext, params);
3140 EXPECT_EQ(message, plaintext);
3141
3142 // Now specify a nonce, should also work.
3143 params = AuthorizationSetBuilder()
3144 .BlockMode(BlockMode::CBC)
3145 .Padding(PaddingMode::NONE)
3146 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
3147 out_params.Clear();
3148 ciphertext = EncryptMessage(message, params, &out_params);
3149
3150 // Decrypt with correct nonce.
3151 plaintext = DecryptMessage(ciphertext, params);
3152 EXPECT_EQ(message, plaintext);
3153
3154 // Try with wrong nonce.
3155 params = AuthorizationSetBuilder()
3156 .BlockMode(BlockMode::CBC)
3157 .Padding(PaddingMode::NONE)
3158 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
3159 plaintext = DecryptMessage(ciphertext, params);
3160 EXPECT_NE(message, plaintext);
3161}
3162
3163/*
3164 * EncryptionOperationsTest.AesCallerNonceProhibited
3165 *
3166 * Verifies that caller-provided nonces are not permitted when not specified in the key
3167 * authorizations.
3168 */
3169TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
3170 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3171 .Authorization(TAG_NO_AUTH_REQUIRED)
3172 .AesEncryptionKey(128)
3173 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
3174 .Padding(PaddingMode::NONE)));
3175
3176 string message = "12345678901234567890123456789012";
3177
3178 // Don't specify nonce, should get a random one.
3179 AuthorizationSetBuilder params =
3180 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
3181 AuthorizationSet out_params;
3182 string ciphertext = EncryptMessage(message, params, &out_params);
3183 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003184 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07003185
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003186 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07003187 string plaintext = DecryptMessage(ciphertext, params);
3188 EXPECT_EQ(message, plaintext);
3189
3190 // Now specify a nonce, should fail
3191 params = AuthorizationSetBuilder()
3192 .BlockMode(BlockMode::CBC)
3193 .Padding(PaddingMode::NONE)
3194 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
3195 out_params.Clear();
3196 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
3197}
3198
3199/*
3200 * EncryptionOperationsTest.AesGcmRoundTripSuccess
3201 *
3202 * Verifies that AES GCM mode works.
3203 */
3204TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
3205 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3206 .Authorization(TAG_NO_AUTH_REQUIRED)
3207 .AesEncryptionKey(128)
3208 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3209 .Padding(PaddingMode::NONE)
3210 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3211
3212 string aad = "foobar";
3213 string message = "123456789012345678901234567890123456";
3214
3215 auto begin_params = AuthorizationSetBuilder()
3216 .BlockMode(BlockMode::GCM)
3217 .Padding(PaddingMode::NONE)
3218 .Authorization(TAG_MAC_LENGTH, 128);
3219
Selene Huang31ab4042020-04-29 04:22:39 -07003220 // Encrypt
3221 AuthorizationSet begin_out_params;
3222 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3223 << "Begin encrypt";
3224 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003225 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
3226 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003227 ASSERT_EQ(ciphertext.length(), message.length() + 16);
3228
3229 // Grab nonce
3230 begin_params.push_back(begin_out_params);
3231
3232 // Decrypt.
3233 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07003234 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003235 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003236 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003237 EXPECT_EQ(message.length(), plaintext.length());
3238 EXPECT_EQ(message, plaintext);
3239}
3240
3241/*
3242 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
3243 *
3244 * Verifies that AES GCM mode works, even when there's a long delay
3245 * between operations.
3246 */
3247TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
3248 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3249 .Authorization(TAG_NO_AUTH_REQUIRED)
3250 .AesEncryptionKey(128)
3251 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3252 .Padding(PaddingMode::NONE)
3253 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3254
3255 string aad = "foobar";
3256 string message = "123456789012345678901234567890123456";
3257
3258 auto begin_params = AuthorizationSetBuilder()
3259 .BlockMode(BlockMode::GCM)
3260 .Padding(PaddingMode::NONE)
3261 .Authorization(TAG_MAC_LENGTH, 128);
3262
Selene Huang31ab4042020-04-29 04:22:39 -07003263 // Encrypt
3264 AuthorizationSet begin_out_params;
3265 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
3266 << "Begin encrypt";
3267 string ciphertext;
3268 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07003269 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003270 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07003271 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003272
3273 ASSERT_EQ(ciphertext.length(), message.length() + 16);
3274
3275 // Grab nonce
3276 begin_params.push_back(begin_out_params);
3277
3278 // Decrypt.
3279 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
3280 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003281 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003282 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07003283 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003284 sleep(5);
3285 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
3286 EXPECT_EQ(message.length(), plaintext.length());
3287 EXPECT_EQ(message, plaintext);
3288}
3289
3290/*
3291 * EncryptionOperationsTest.AesGcmDifferentNonces
3292 *
3293 * Verifies that encrypting the same data with different nonces produces different outputs.
3294 */
3295TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
3296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3297 .Authorization(TAG_NO_AUTH_REQUIRED)
3298 .AesEncryptionKey(128)
3299 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
3300 .Padding(PaddingMode::NONE)
3301 .Authorization(TAG_MIN_MAC_LENGTH, 128)
3302 .Authorization(TAG_CALLER_NONCE)));
3303
3304 string aad = "foobar";
3305 string message = "123456789012345678901234567890123456";
3306 string nonce1 = "000000000000";
3307 string nonce2 = "111111111111";
3308 string nonce3 = "222222222222";
3309
3310 string ciphertext1 =
3311 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
3312 string ciphertext2 =
3313 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
3314 string ciphertext3 =
3315 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
3316
3317 ASSERT_NE(ciphertext1, ciphertext2);
3318 ASSERT_NE(ciphertext1, ciphertext3);
3319 ASSERT_NE(ciphertext2, ciphertext3);
3320}
3321
3322/*
3323 * EncryptionOperationsTest.AesGcmTooShortTag
3324 *
3325 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
3326 */
3327TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
3328 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3329 .Authorization(TAG_NO_AUTH_REQUIRED)
3330 .AesEncryptionKey(128)
3331 .BlockMode(BlockMode::GCM)
3332 .Padding(PaddingMode::NONE)
3333 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3334 string message = "123456789012345678901234567890123456";
3335 auto params = AuthorizationSetBuilder()
3336 .BlockMode(BlockMode::GCM)
3337 .Padding(PaddingMode::NONE)
3338 .Authorization(TAG_MAC_LENGTH, 96);
3339
3340 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
3341}
3342
3343/*
3344 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
3345 *
3346 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
3347 */
3348TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
3349 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3350 .Authorization(TAG_NO_AUTH_REQUIRED)
3351 .AesEncryptionKey(128)
3352 .BlockMode(BlockMode::GCM)
3353 .Padding(PaddingMode::NONE)
3354 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3355 string aad = "foobar";
3356 string message = "123456789012345678901234567890123456";
3357 auto params = AuthorizationSetBuilder()
3358 .BlockMode(BlockMode::GCM)
3359 .Padding(PaddingMode::NONE)
3360 .Authorization(TAG_MAC_LENGTH, 128);
3361
Selene Huang31ab4042020-04-29 04:22:39 -07003362 // Encrypt
3363 AuthorizationSet begin_out_params;
3364 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3365 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08003366 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07003367
3368 AuthorizationSet finish_out_params;
3369 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003370 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
3371 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003372
3373 params = AuthorizationSetBuilder()
3374 .Authorizations(begin_out_params)
3375 .BlockMode(BlockMode::GCM)
3376 .Padding(PaddingMode::NONE)
3377 .Authorization(TAG_MAC_LENGTH, 96);
3378
3379 // Decrypt.
3380 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
3381}
3382
3383/*
3384 * EncryptionOperationsTest.AesGcmCorruptKey
3385 *
3386 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
3387 */
3388TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
3389 const uint8_t nonce_bytes[] = {
3390 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
3391 };
3392 string nonce = make_string(nonce_bytes);
3393 const uint8_t ciphertext_bytes[] = {
3394 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
3395 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
3396 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
3397 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
3398 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
3399 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
3400 };
3401 string ciphertext = make_string(ciphertext_bytes);
3402
3403 auto params = AuthorizationSetBuilder()
3404 .BlockMode(BlockMode::GCM)
3405 .Padding(PaddingMode::NONE)
3406 .Authorization(TAG_MAC_LENGTH, 128)
3407 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
3408
3409 auto import_params = AuthorizationSetBuilder()
3410 .Authorization(TAG_NO_AUTH_REQUIRED)
3411 .AesEncryptionKey(128)
3412 .BlockMode(BlockMode::GCM)
3413 .Padding(PaddingMode::NONE)
3414 .Authorization(TAG_CALLER_NONCE)
3415 .Authorization(TAG_MIN_MAC_LENGTH, 128);
3416
3417 // Import correct key and decrypt
3418 const uint8_t key_bytes[] = {
3419 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
3420 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
3421 };
3422 string key = make_string(key_bytes);
3423 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3424 string plaintext = DecryptMessage(ciphertext, params);
3425 CheckedDeleteKey();
3426
3427 // Corrupt key and attempt to decrypt
3428 key[0] = 0;
3429 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
3430 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3431 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
3432 CheckedDeleteKey();
3433}
3434
3435/*
3436 * EncryptionOperationsTest.AesGcmAadNoData
3437 *
3438 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
3439 * encrypt.
3440 */
3441TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
3442 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3443 .Authorization(TAG_NO_AUTH_REQUIRED)
3444 .AesEncryptionKey(128)
3445 .BlockMode(BlockMode::GCM)
3446 .Padding(PaddingMode::NONE)
3447 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3448
3449 string aad = "1234567890123456";
3450 auto params = AuthorizationSetBuilder()
3451 .BlockMode(BlockMode::GCM)
3452 .Padding(PaddingMode::NONE)
3453 .Authorization(TAG_MAC_LENGTH, 128);
3454
Selene Huang31ab4042020-04-29 04:22:39 -07003455 // Encrypt
3456 AuthorizationSet begin_out_params;
3457 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
3458 string ciphertext;
3459 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07003460 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
3461 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003462 EXPECT_TRUE(finish_out_params.empty());
3463
3464 // Grab nonce
3465 params.push_back(begin_out_params);
3466
3467 // Decrypt.
3468 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003469 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003470 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003471 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003472
3473 EXPECT_TRUE(finish_out_params.empty());
3474
3475 EXPECT_EQ("", plaintext);
3476}
3477
3478/*
3479 * EncryptionOperationsTest.AesGcmMultiPartAad
3480 *
3481 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
3482 * chunks.
3483 */
3484TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
3485 const size_t tag_bits = 128;
3486 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3487 .Authorization(TAG_NO_AUTH_REQUIRED)
3488 .AesEncryptionKey(128)
3489 .BlockMode(BlockMode::GCM)
3490 .Padding(PaddingMode::NONE)
3491 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3492
3493 string message = "123456789012345678901234567890123456";
3494 auto begin_params = AuthorizationSetBuilder()
3495 .BlockMode(BlockMode::GCM)
3496 .Padding(PaddingMode::NONE)
3497 .Authorization(TAG_MAC_LENGTH, tag_bits);
3498 AuthorizationSet begin_out_params;
3499
Selene Huang31ab4042020-04-29 04:22:39 -07003500 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3501
3502 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07003503 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
3504 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07003505 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003506 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
3507 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003508
Selene Huang31ab4042020-04-29 04:22:39 -07003509 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07003510 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003511
3512 // Grab nonce.
3513 begin_params.push_back(begin_out_params);
3514
3515 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003516 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003517 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07003518 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003519 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003520 EXPECT_EQ(message, plaintext);
3521}
3522
3523/*
3524 * EncryptionOperationsTest.AesGcmAadOutOfOrder
3525 *
3526 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
3527 */
3528TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
3529 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3530 .Authorization(TAG_NO_AUTH_REQUIRED)
3531 .AesEncryptionKey(128)
3532 .BlockMode(BlockMode::GCM)
3533 .Padding(PaddingMode::NONE)
3534 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3535
3536 string message = "123456789012345678901234567890123456";
3537 auto begin_params = AuthorizationSetBuilder()
3538 .BlockMode(BlockMode::GCM)
3539 .Padding(PaddingMode::NONE)
3540 .Authorization(TAG_MAC_LENGTH, 128);
3541 AuthorizationSet begin_out_params;
3542
Selene Huang31ab4042020-04-29 04:22:39 -07003543 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
3544
Shawn Willden92d79c02021-02-19 07:31:55 -07003545 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07003546 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003547 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
3548 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07003549
Shawn Willden92d79c02021-02-19 07:31:55 -07003550 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07003551}
3552
3553/*
3554 * EncryptionOperationsTest.AesGcmBadAad
3555 *
3556 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
3557 */
3558TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
3559 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3560 .Authorization(TAG_NO_AUTH_REQUIRED)
3561 .AesEncryptionKey(128)
3562 .BlockMode(BlockMode::GCM)
3563 .Padding(PaddingMode::NONE)
3564 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3565
3566 string message = "12345678901234567890123456789012";
3567 auto begin_params = AuthorizationSetBuilder()
3568 .BlockMode(BlockMode::GCM)
3569 .Padding(PaddingMode::NONE)
3570 .Authorization(TAG_MAC_LENGTH, 128);
3571
Selene Huang31ab4042020-04-29 04:22:39 -07003572 // Encrypt
3573 AuthorizationSet begin_out_params;
3574 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003575 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07003576 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003577 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003578
3579 // Grab nonce
3580 begin_params.push_back(begin_out_params);
3581
Selene Huang31ab4042020-04-29 04:22:39 -07003582 // Decrypt.
3583 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003584 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07003585 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003586 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003587}
3588
3589/*
3590 * EncryptionOperationsTest.AesGcmWrongNonce
3591 *
3592 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
3593 */
3594TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
3595 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3596 .Authorization(TAG_NO_AUTH_REQUIRED)
3597 .AesEncryptionKey(128)
3598 .BlockMode(BlockMode::GCM)
3599 .Padding(PaddingMode::NONE)
3600 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3601
3602 string message = "12345678901234567890123456789012";
3603 auto begin_params = AuthorizationSetBuilder()
3604 .BlockMode(BlockMode::GCM)
3605 .Padding(PaddingMode::NONE)
3606 .Authorization(TAG_MAC_LENGTH, 128);
3607
Selene Huang31ab4042020-04-29 04:22:39 -07003608 // Encrypt
3609 AuthorizationSet begin_out_params;
3610 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003611 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07003612 string ciphertext;
3613 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07003614 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003615
3616 // Wrong nonce
3617 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
3618
3619 // Decrypt.
3620 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003621 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07003622 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003623 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003624
3625 // With wrong nonce, should have gotten garbage plaintext (or none).
3626 EXPECT_NE(message, plaintext);
3627}
3628
3629/*
3630 * EncryptionOperationsTest.AesGcmCorruptTag
3631 *
3632 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
3633 */
3634TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
3635 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3636 .Authorization(TAG_NO_AUTH_REQUIRED)
3637 .AesEncryptionKey(128)
3638 .BlockMode(BlockMode::GCM)
3639 .Padding(PaddingMode::NONE)
3640 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3641
3642 string aad = "1234567890123456";
3643 string message = "123456789012345678901234567890123456";
3644
3645 auto params = AuthorizationSetBuilder()
3646 .BlockMode(BlockMode::GCM)
3647 .Padding(PaddingMode::NONE)
3648 .Authorization(TAG_MAC_LENGTH, 128);
3649
Selene Huang31ab4042020-04-29 04:22:39 -07003650 // Encrypt
3651 AuthorizationSet begin_out_params;
3652 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003653 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003654 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003655 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07003656
3657 // Corrupt tag
3658 ++(*ciphertext.rbegin());
3659
3660 // Grab nonce
3661 params.push_back(begin_out_params);
3662
3663 // Decrypt.
3664 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07003665 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07003666 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003667 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003668}
3669
3670/*
3671 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
3672 *
3673 * Verifies that 3DES is basically functional.
3674 */
3675TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
3676 auto auths = AuthorizationSetBuilder()
3677 .TripleDesEncryptionKey(168)
3678 .BlockMode(BlockMode::ECB)
3679 .Authorization(TAG_NO_AUTH_REQUIRED)
3680 .Padding(PaddingMode::NONE);
3681
3682 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
3683 // Two-block message.
3684 string message = "1234567890123456";
3685 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3686 string ciphertext1 = EncryptMessage(message, inParams);
3687 EXPECT_EQ(message.size(), ciphertext1.size());
3688
3689 string ciphertext2 = EncryptMessage(string(message), inParams);
3690 EXPECT_EQ(message.size(), ciphertext2.size());
3691
3692 // ECB is deterministic.
3693 EXPECT_EQ(ciphertext1, ciphertext2);
3694
3695 string plaintext = DecryptMessage(ciphertext1, inParams);
3696 EXPECT_EQ(message, plaintext);
3697}
3698
3699/*
3700 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
3701 *
3702 * Verifies that CBC keys reject ECB usage.
3703 */
3704TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
3705 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3706 .TripleDesEncryptionKey(168)
3707 .BlockMode(BlockMode::CBC)
3708 .Authorization(TAG_NO_AUTH_REQUIRED)
3709 .Padding(PaddingMode::NONE)));
3710
3711 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
3712 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
3713}
3714
3715/*
3716 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
3717 *
3718 * Tests ECB mode with PKCS#7 padding, various message sizes.
3719 */
3720TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
3721 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3722 .TripleDesEncryptionKey(168)
3723 .BlockMode(BlockMode::ECB)
3724 .Authorization(TAG_NO_AUTH_REQUIRED)
3725 .Padding(PaddingMode::PKCS7)));
3726
3727 for (size_t i = 0; i < 32; ++i) {
3728 string message(i, 'a');
3729 auto inParams =
3730 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3731 string ciphertext = EncryptMessage(message, inParams);
3732 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
3733 string plaintext = DecryptMessage(ciphertext, inParams);
3734 EXPECT_EQ(message, plaintext);
3735 }
3736}
3737
3738/*
3739 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
3740 *
3741 * Verifies that keys configured for no padding reject PKCS7 padding
3742 */
3743TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
3744 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3745 .TripleDesEncryptionKey(168)
3746 .BlockMode(BlockMode::ECB)
3747 .Authorization(TAG_NO_AUTH_REQUIRED)
3748 .Padding(PaddingMode::NONE)));
3749 for (size_t i = 0; i < 32; ++i) {
3750 auto inParams =
3751 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3752 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
3753 }
3754}
3755
3756/*
3757 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
3758 *
3759 * Verifies that corrupted padding is detected.
3760 */
3761TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
3762 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3763 .TripleDesEncryptionKey(168)
3764 .BlockMode(BlockMode::ECB)
3765 .Authorization(TAG_NO_AUTH_REQUIRED)
3766 .Padding(PaddingMode::PKCS7)));
3767
3768 string message = "a";
3769 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
3770 EXPECT_EQ(8U, ciphertext.size());
3771 EXPECT_NE(ciphertext, message);
3772 ++ciphertext[ciphertext.size() / 2];
3773
3774 AuthorizationSetBuilder begin_params;
3775 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
3776 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
3777 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
3778 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07003779 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07003780 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
3781}
3782
3783struct TripleDesTestVector {
3784 const char* name;
3785 const KeyPurpose purpose;
3786 const BlockMode block_mode;
3787 const PaddingMode padding_mode;
3788 const char* key;
3789 const char* iv;
3790 const char* input;
3791 const char* output;
3792};
3793
3794// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
3795// of the NIST vectors are multiples of the block size.
3796static const TripleDesTestVector kTripleDesTestVectors[] = {
3797 {
3798 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
3799 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
3800 "", // IV
3801 "329d86bdf1bc5af4", // input
3802 "d946c2756d78633f", // output
3803 },
3804 {
3805 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
3806 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
3807 "", // IV
3808 "6b1540781b01ce1997adae102dbf3c5b", // input
3809 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
3810 },
3811 {
3812 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
3813 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
3814 "", // IV
3815 "6daad94ce08acfe7", // input
3816 "660e7d32dcc90e79", // output
3817 },
3818 {
3819 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
3820 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
3821 "", // IV
3822 "e9653a0a1f05d31b9acd12d73aa9879d", // input
3823 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
3824 },
3825 {
3826 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
3827 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
3828 "43f791134c5647ba", // IV
3829 "dcc153cef81d6f24", // input
3830 "92538bd8af18d3ba", // output
3831 },
3832 {
3833 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
3834 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
3835 "c2e999cb6249023c", // IV
3836 "c689aee38a301bb316da75db36f110b5", // input
3837 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
3838 },
3839 {
3840 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
3841 PaddingMode::PKCS7,
3842 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
3843 "c2e999cb6249023c", // IV
3844 "c689aee38a301bb316da75db36f110b500", // input
3845 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
3846 },
3847 {
3848 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
3849 PaddingMode::PKCS7,
3850 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
3851 "c2e999cb6249023c", // IV
3852 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
3853 "c689aee38a301bb316da75db36f110b500", // output
3854 },
3855 {
3856 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
3857 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
3858 "41746c7e442d3681", // IV
3859 "c53a7b0ec40600fe", // input
3860 "d4f00eb455de1034", // output
3861 },
3862 {
3863 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
3864 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
3865 "3982bc02c3727d45", // IV
3866 "6006f10adef52991fcc777a1238bbb65", // input
3867 "edae09288e9e3bc05746d872b48e3b29", // output
3868 },
3869};
3870
3871/*
3872 * EncryptionOperationsTest.TripleDesTestVector
3873 *
3874 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
3875 */
3876TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
3877 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
3878 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
3879 SCOPED_TRACE(test->name);
3880 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
3881 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
3882 hex2str(test->output));
3883 }
3884}
3885
3886/*
3887 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
3888 *
3889 * Validates CBC mode functionality.
3890 */
3891TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
3892 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3893 .TripleDesEncryptionKey(168)
3894 .BlockMode(BlockMode::CBC)
3895 .Authorization(TAG_NO_AUTH_REQUIRED)
3896 .Padding(PaddingMode::NONE)));
3897
3898 ASSERT_GT(key_blob_.size(), 0U);
3899
3900 // Two-block message.
3901 string message = "1234567890123456";
3902 vector<uint8_t> iv1;
3903 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
3904 EXPECT_EQ(message.size(), ciphertext1.size());
3905
3906 vector<uint8_t> iv2;
3907 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
3908 EXPECT_EQ(message.size(), ciphertext2.size());
3909
3910 // IVs should be random, so ciphertexts should differ.
3911 EXPECT_NE(iv1, iv2);
3912 EXPECT_NE(ciphertext1, ciphertext2);
3913
3914 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
3915 EXPECT_EQ(message, plaintext);
3916}
3917
3918/*
3919 * EncryptionOperationsTest.TripleDesCallerIv
3920 *
3921 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
3922 */
3923TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
3924 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3925 .TripleDesEncryptionKey(168)
3926 .BlockMode(BlockMode::CBC)
3927 .Authorization(TAG_NO_AUTH_REQUIRED)
3928 .Authorization(TAG_CALLER_NONCE)
3929 .Padding(PaddingMode::NONE)));
3930 string message = "1234567890123456";
3931 vector<uint8_t> iv;
3932 // Don't specify IV, should get a random one.
3933 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
3934 EXPECT_EQ(message.size(), ciphertext1.size());
3935 EXPECT_EQ(8U, iv.size());
3936
3937 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
3938 EXPECT_EQ(message, plaintext);
3939
3940 // Now specify an IV, should also work.
3941 iv = AidlBuf("abcdefgh");
3942 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
3943
3944 // Decrypt with correct IV.
3945 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
3946 EXPECT_EQ(message, plaintext);
3947
3948 // Now try with wrong IV.
3949 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
3950 EXPECT_NE(message, plaintext);
3951}
3952
3953/*
3954 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
3955 *
3956 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVS.
3957 */
3958TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
3959 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3960 .TripleDesEncryptionKey(168)
3961 .BlockMode(BlockMode::CBC)
3962 .Authorization(TAG_NO_AUTH_REQUIRED)
3963 .Padding(PaddingMode::NONE)));
3964
3965 string message = "12345678901234567890123456789012";
3966 vector<uint8_t> iv;
3967 // Don't specify nonce, should get a random one.
3968 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
3969 EXPECT_EQ(message.size(), ciphertext1.size());
3970 EXPECT_EQ(8U, iv.size());
3971
3972 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
3973 EXPECT_EQ(message, plaintext);
3974
3975 // Now specify a nonce, should fail.
3976 auto input_params = AuthorizationSetBuilder()
3977 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
3978 .BlockMode(BlockMode::CBC)
3979 .Padding(PaddingMode::NONE);
3980 AuthorizationSet output_params;
3981 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
3982 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
3983}
3984
3985/*
3986 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
3987 *
3988 * Verifies that 3DES ECB-only keys do not allow CBC usage.
3989 */
3990TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
3991 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3992 .TripleDesEncryptionKey(168)
3993 .BlockMode(BlockMode::ECB)
3994 .Authorization(TAG_NO_AUTH_REQUIRED)
3995 .Padding(PaddingMode::NONE)));
3996 // Two-block message.
3997 string message = "1234567890123456";
3998 auto begin_params =
3999 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4000 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4001}
4002
4003/*
4004 * EncryptionOperationsTest.TripleDesCbcNoPaddingWrongInputSize
4005 *
4006 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
4007 */
4008TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingWrongInputSize) {
4009 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4010 .TripleDesEncryptionKey(168)
4011 .BlockMode(BlockMode::CBC)
4012 .Authorization(TAG_NO_AUTH_REQUIRED)
4013 .Padding(PaddingMode::NONE)));
4014 // Message is slightly shorter than two blocks.
4015 string message = "123456789012345";
4016
4017 auto begin_params =
4018 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4019 AuthorizationSet output_params;
4020 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
4021 string ciphertext;
4022 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
4023}
4024
4025/*
4026 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
4027 *
4028 * Verifies that PKCS7 padding works correctly in CBC mode.
4029 */
4030TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
4031 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4032 .TripleDesEncryptionKey(168)
4033 .BlockMode(BlockMode::CBC)
4034 .Authorization(TAG_NO_AUTH_REQUIRED)
4035 .Padding(PaddingMode::PKCS7)));
4036
4037 // Try various message lengths; all should work.
4038 for (size_t i = 0; i < 32; ++i) {
4039 string message(i, 'a');
4040 vector<uint8_t> iv;
4041 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4042 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
4043 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
4044 EXPECT_EQ(message, plaintext);
4045 }
4046}
4047
4048/*
4049 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
4050 *
4051 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
4052 */
4053TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
4054 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4055 .TripleDesEncryptionKey(168)
4056 .BlockMode(BlockMode::CBC)
4057 .Authorization(TAG_NO_AUTH_REQUIRED)
4058 .Padding(PaddingMode::NONE)));
4059
4060 // Try various message lengths; all should fail.
4061 for (size_t i = 0; i < 32; ++i) {
4062 auto begin_params =
4063 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
4064 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
4065 }
4066}
4067
4068/*
4069 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
4070 *
4071 * Verifies that corrupted PKCS7 padding is rejected during decryption.
4072 */
4073TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
4074 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4075 .TripleDesEncryptionKey(168)
4076 .BlockMode(BlockMode::CBC)
4077 .Authorization(TAG_NO_AUTH_REQUIRED)
4078 .Padding(PaddingMode::PKCS7)));
4079
4080 string message = "a";
4081 vector<uint8_t> iv;
4082 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
4083 EXPECT_EQ(8U, ciphertext.size());
4084 EXPECT_NE(ciphertext, message);
4085 ++ciphertext[ciphertext.size() / 2];
4086
4087 auto begin_params = AuthorizationSetBuilder()
4088 .BlockMode(BlockMode::CBC)
4089 .Padding(PaddingMode::PKCS7)
4090 .Authorization(TAG_NONCE, iv);
4091 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
4092 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004093 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004094 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
4095}
4096
4097/*
4098 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
4099 *
4100 * Verifies that 3DES CBC works with many different input sizes.
4101 */
4102TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
4103 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4104 .TripleDesEncryptionKey(168)
4105 .BlockMode(BlockMode::CBC)
4106 .Authorization(TAG_NO_AUTH_REQUIRED)
4107 .Padding(PaddingMode::NONE)));
4108
4109 int increment = 7;
4110 string message(240, 'a');
4111 AuthorizationSet input_params =
4112 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4113 AuthorizationSet output_params;
4114 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
4115
4116 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004117 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07004118 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004119 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
4120 EXPECT_EQ(message.size(), ciphertext.size());
4121
4122 // Move TAG_NONCE into input_params
4123 input_params = output_params;
4124 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
4125 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
4126 output_params.Clear();
4127
4128 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
4129 string plaintext;
4130 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07004131 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004132 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
4133 EXPECT_EQ(ciphertext.size(), plaintext.size());
4134 EXPECT_EQ(message, plaintext);
4135}
4136
4137INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
4138
4139typedef KeyMintAidlTestBase MaxOperationsTest;
4140
4141/*
4142 * MaxOperationsTest.TestLimitAes
4143 *
4144 * Verifies that the max uses per boot tag works correctly with AES keys.
4145 */
4146TEST_P(MaxOperationsTest, TestLimitAes) {
4147 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4148
4149 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4150 .Authorization(TAG_NO_AUTH_REQUIRED)
4151 .AesEncryptionKey(128)
4152 .EcbMode()
4153 .Padding(PaddingMode::NONE)
4154 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
4155
4156 string message = "1234567890123456";
4157
4158 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4159
4160 EncryptMessage(message, params);
4161 EncryptMessage(message, params);
4162 EncryptMessage(message, params);
4163
4164 // Fourth time should fail.
4165 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
4166}
4167
4168/*
Qi Wud22ec842020-11-26 13:27:53 +08004169 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07004170 *
4171 * Verifies that the max uses per boot tag works correctly with RSA keys.
4172 */
4173TEST_P(MaxOperationsTest, TestLimitRsa) {
4174 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4175
4176 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4177 .Authorization(TAG_NO_AUTH_REQUIRED)
4178 .RsaSigningKey(1024, 65537)
4179 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08004180 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
4181 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004182
4183 string message = "1234567890123456";
4184
4185 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4186
4187 SignMessage(message, params);
4188 SignMessage(message, params);
4189 SignMessage(message, params);
4190
4191 // Fourth time should fail.
4192 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
4193}
4194
4195INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
4196
Qi Wud22ec842020-11-26 13:27:53 +08004197typedef KeyMintAidlTestBase UsageCountLimitTest;
4198
4199/*
Qi Wubeefae42021-01-28 23:16:37 +08004200 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08004201 *
Qi Wubeefae42021-01-28 23:16:37 +08004202 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08004203 */
Qi Wubeefae42021-01-28 23:16:37 +08004204TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08004205 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4206
4207 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4208 .Authorization(TAG_NO_AUTH_REQUIRED)
4209 .AesEncryptionKey(128)
4210 .EcbMode()
4211 .Padding(PaddingMode::NONE)
4212 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
4213
4214 // Check the usage count limit tag appears in the authorizations.
4215 AuthorizationSet auths;
4216 for (auto& entry : key_characteristics_) {
4217 auths.push_back(AuthorizationSet(entry.authorizations));
4218 }
4219 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
4220 << "key usage count limit " << 1U << " missing";
4221
4222 string message = "1234567890123456";
4223 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4224
Qi Wubeefae42021-01-28 23:16:37 +08004225 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4226 AuthorizationSet keystore_auths =
4227 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4228
Qi Wud22ec842020-11-26 13:27:53 +08004229 // First usage of AES key should work.
4230 EncryptMessage(message, params);
4231
Qi Wud22ec842020-11-26 13:27:53 +08004232 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
4233 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4234 // must be invalidated from secure storage (such as RPMB partition).
4235 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
4236 } else {
Qi Wubeefae42021-01-28 23:16:37 +08004237 // Usage count limit tag is enforced by keystore, keymint does nothing.
4238 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08004239 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
4240 }
4241}
4242
4243/*
Qi Wubeefae42021-01-28 23:16:37 +08004244 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08004245 *
Qi Wubeefae42021-01-28 23:16:37 +08004246 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08004247 */
Qi Wubeefae42021-01-28 23:16:37 +08004248TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
4249 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4250
4251 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4252 .Authorization(TAG_NO_AUTH_REQUIRED)
4253 .AesEncryptionKey(128)
4254 .EcbMode()
4255 .Padding(PaddingMode::NONE)
4256 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
4257
4258 // Check the usage count limit tag appears in the authorizations.
4259 AuthorizationSet auths;
4260 for (auto& entry : key_characteristics_) {
4261 auths.push_back(AuthorizationSet(entry.authorizations));
4262 }
4263 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
4264 << "key usage count limit " << 3U << " missing";
4265
4266 string message = "1234567890123456";
4267 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
4268
4269 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4270 AuthorizationSet keystore_auths =
4271 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4272
4273 EncryptMessage(message, params);
4274 EncryptMessage(message, params);
4275 EncryptMessage(message, params);
4276
4277 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
4278 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4279 // must be invalidated from secure storage (such as RPMB partition).
4280 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
4281 } else {
4282 // Usage count limit tag is enforced by keystore, keymint does nothing.
4283 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
4284 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
4285 }
4286}
4287
4288/*
4289 * UsageCountLimitTest.TestSingleUseRsa
4290 *
4291 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
4292 */
4293TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08004294 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4295
4296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4297 .Authorization(TAG_NO_AUTH_REQUIRED)
4298 .RsaSigningKey(1024, 65537)
4299 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08004300 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
4301 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08004302
4303 // Check the usage count limit tag appears in the authorizations.
4304 AuthorizationSet auths;
4305 for (auto& entry : key_characteristics_) {
4306 auths.push_back(AuthorizationSet(entry.authorizations));
4307 }
4308 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
4309 << "key usage count limit " << 1U << " missing";
4310
4311 string message = "1234567890123456";
4312 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4313
Qi Wubeefae42021-01-28 23:16:37 +08004314 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4315 AuthorizationSet keystore_auths =
4316 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4317
Qi Wud22ec842020-11-26 13:27:53 +08004318 // First usage of RSA key should work.
4319 SignMessage(message, params);
4320
Qi Wud22ec842020-11-26 13:27:53 +08004321 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
4322 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4323 // must be invalidated from secure storage (such as RPMB partition).
4324 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
4325 } else {
Qi Wubeefae42021-01-28 23:16:37 +08004326 // Usage count limit tag is enforced by keystore, keymint does nothing.
4327 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
4328 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
4329 }
4330}
4331
4332/*
4333 * UsageCountLimitTest.TestLimitUseRsa
4334 *
4335 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
4336 */
4337TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
4338 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4339
4340 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4341 .Authorization(TAG_NO_AUTH_REQUIRED)
4342 .RsaSigningKey(1024, 65537)
4343 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08004344 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
4345 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08004346
4347 // Check the usage count limit tag appears in the authorizations.
4348 AuthorizationSet auths;
4349 for (auto& entry : key_characteristics_) {
4350 auths.push_back(AuthorizationSet(entry.authorizations));
4351 }
4352 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
4353 << "key usage count limit " << 3U << " missing";
4354
4355 string message = "1234567890123456";
4356 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4357
4358 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4359 AuthorizationSet keystore_auths =
4360 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
4361
4362 SignMessage(message, params);
4363 SignMessage(message, params);
4364 SignMessage(message, params);
4365
4366 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
4367 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4368 // must be invalidated from secure storage (such as RPMB partition).
4369 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
4370 } else {
4371 // Usage count limit tag is enforced by keystore, keymint does nothing.
4372 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08004373 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
4374 }
4375}
4376
Qi Wu8e727f72021-02-11 02:49:33 +08004377/*
4378 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
4379 *
4380 * Verifies that when rollback resistance is supported by the KeyMint implementation with
4381 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
4382 * in hardware.
4383 */
4384TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
4385 if (SecLevel() == SecurityLevel::STRONGBOX) return;
4386
4387 auto error = GenerateKey(AuthorizationSetBuilder()
4388 .RsaSigningKey(2048, 65537)
4389 .Digest(Digest::NONE)
4390 .Padding(PaddingMode::NONE)
4391 .Authorization(TAG_NO_AUTH_REQUIRED)
4392 .Authorization(TAG_ROLLBACK_RESISTANCE)
4393 .SetDefaultValidity());
4394 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4395
4396 if (error == ErrorCode::OK) {
4397 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
4398 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
4399 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4400 ASSERT_EQ(ErrorCode::OK, DeleteKey());
4401
4402 // The KeyMint should also enforce single use key in hardware when it supports rollback
4403 // resistance.
4404 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4405 .Authorization(TAG_NO_AUTH_REQUIRED)
4406 .RsaSigningKey(1024, 65537)
4407 .NoDigestOrPadding()
4408 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
4409 .SetDefaultValidity()));
4410
4411 // Check the usage count limit tag appears in the hardware authorizations.
4412 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
4413 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
4414 << "key usage count limit " << 1U << " missing";
4415
4416 string message = "1234567890123456";
4417 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
4418
4419 // First usage of RSA key should work.
4420 SignMessage(message, params);
4421
4422 // Usage count limit tag is enforced by hardware. After using the key, the key blob
4423 // must be invalidated from secure storage (such as RPMB partition).
4424 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
4425 }
4426}
4427
Qi Wud22ec842020-11-26 13:27:53 +08004428INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
4429
Selene Huang31ab4042020-04-29 04:22:39 -07004430typedef KeyMintAidlTestBase AddEntropyTest;
4431
4432/*
4433 * AddEntropyTest.AddEntropy
4434 *
4435 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
4436 * is actually added.
4437 */
4438TEST_P(AddEntropyTest, AddEntropy) {
4439 string data = "foo";
4440 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
4441}
4442
4443/*
4444 * AddEntropyTest.AddEmptyEntropy
4445 *
4446 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
4447 */
4448TEST_P(AddEntropyTest, AddEmptyEntropy) {
4449 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
4450}
4451
4452/*
4453 * AddEntropyTest.AddLargeEntropy
4454 *
4455 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
4456 */
4457TEST_P(AddEntropyTest, AddLargeEntropy) {
4458 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
4459}
4460
4461INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
4462
Selene Huang31ab4042020-04-29 04:22:39 -07004463typedef KeyMintAidlTestBase KeyDeletionTest;
4464
4465/**
4466 * KeyDeletionTest.DeleteKey
4467 *
4468 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
4469 * valid key blob.
4470 */
4471TEST_P(KeyDeletionTest, DeleteKey) {
4472 auto error = GenerateKey(AuthorizationSetBuilder()
4473 .RsaSigningKey(2048, 65537)
4474 .Digest(Digest::NONE)
4475 .Padding(PaddingMode::NONE)
4476 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08004477 .Authorization(TAG_ROLLBACK_RESISTANCE)
4478 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07004479 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4480
4481 // Delete must work if rollback protection is implemented
4482 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07004483 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07004484 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4485
4486 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
4487
4488 string message = "12345678901234567890123456789012";
4489 AuthorizationSet begin_out_params;
4490 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
4491 Begin(KeyPurpose::SIGN, key_blob_,
4492 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
4493 &begin_out_params));
4494 AbortIfNeeded();
4495 key_blob_ = AidlBuf();
4496 }
4497}
4498
4499/**
4500 * KeyDeletionTest.DeleteInvalidKey
4501 *
4502 * This test checks that the HAL excepts invalid key blobs..
4503 */
4504TEST_P(KeyDeletionTest, DeleteInvalidKey) {
4505 // Generate key just to check if rollback protection is implemented
4506 auto error = GenerateKey(AuthorizationSetBuilder()
4507 .RsaSigningKey(2048, 65537)
4508 .Digest(Digest::NONE)
4509 .Padding(PaddingMode::NONE)
4510 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08004511 .Authorization(TAG_ROLLBACK_RESISTANCE)
4512 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07004513 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4514
4515 // Delete must work if rollback protection is implemented
4516 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07004517 AuthorizationSet enforced(SecLevelAuthorizations());
4518 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004519
4520 // Delete the key we don't care about the result at this point.
4521 DeleteKey();
4522
4523 // Now create an invalid key blob and delete it.
4524 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
4525
4526 ASSERT_EQ(ErrorCode::OK, DeleteKey());
4527 }
4528}
4529
4530/**
4531 * KeyDeletionTest.DeleteAllKeys
4532 *
4533 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
4534 *
4535 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
4536 * FBE/FDE encryption keys, which means that the device will not even boot until after the
4537 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
4538 * been provisioned. Use this test only on dedicated testing devices that have no valuable
4539 * credentials stored in Keystore/Keymint.
4540 */
4541TEST_P(KeyDeletionTest, DeleteAllKeys) {
4542 if (!arm_deleteAllKeys) return;
4543 auto error = GenerateKey(AuthorizationSetBuilder()
4544 .RsaSigningKey(2048, 65537)
4545 .Digest(Digest::NONE)
4546 .Padding(PaddingMode::NONE)
4547 .Authorization(TAG_NO_AUTH_REQUIRED)
4548 .Authorization(TAG_ROLLBACK_RESISTANCE));
4549 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
4550
4551 // Delete must work if rollback protection is implemented
4552 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07004553 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07004554 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
4555
4556 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
4557
4558 string message = "12345678901234567890123456789012";
4559 AuthorizationSet begin_out_params;
4560
4561 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
4562 Begin(KeyPurpose::SIGN, key_blob_,
4563 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
4564 &begin_out_params));
4565 AbortIfNeeded();
4566 key_blob_ = AidlBuf();
4567 }
4568}
4569
4570INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
4571
4572using UpgradeKeyTest = KeyMintAidlTestBase;
4573
4574/*
4575 * UpgradeKeyTest.UpgradeKey
4576 *
4577 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
4578 */
4579TEST_P(UpgradeKeyTest, UpgradeKey) {
4580 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4581 .AesEncryptionKey(128)
4582 .Padding(PaddingMode::NONE)
4583 .Authorization(TAG_NO_AUTH_REQUIRED)));
4584
4585 auto result = UpgradeKey(key_blob_);
4586
4587 // Key doesn't need upgrading. Should get okay, but no new key blob.
4588 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
4589}
4590
4591INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
4592
4593using ClearOperationsTest = KeyMintAidlTestBase;
4594
4595/*
4596 * ClearSlotsTest.TooManyOperations
4597 *
4598 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
4599 * operations are started without being finished or aborted. Also verifies
4600 * that aborting the operations clears the operations.
4601 *
4602 */
4603TEST_P(ClearOperationsTest, TooManyOperations) {
4604 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4605 .Authorization(TAG_NO_AUTH_REQUIRED)
4606 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004607 .Padding(PaddingMode::NONE)
4608 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004609
4610 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4611 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08004612 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07004613 AuthorizationSet out_params;
4614 ErrorCode result;
4615 size_t i;
4616
4617 for (i = 0; i < max_operations; i++) {
4618 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
4619 if (ErrorCode::OK != result) {
4620 break;
4621 }
4622 }
4623 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
4624 // Try again just in case there's a weird overflow bug
4625 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
4626 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
4627 for (size_t j = 0; j < i; j++) {
4628 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
4629 << "Aboort failed for i = " << j << std::endl;
4630 }
4631 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
4632 AbortIfNeeded();
4633}
4634
4635INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
4636
4637typedef KeyMintAidlTestBase TransportLimitTest;
4638
4639/*
4640 * TransportLimitTest.FinishInput
4641 *
4642 * Verifies that passing input data to finish succeeds as expected.
4643 */
4644TEST_P(TransportLimitTest, LargeFinishInput) {
4645 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4646 .Authorization(TAG_NO_AUTH_REQUIRED)
4647 .AesEncryptionKey(128)
4648 .BlockMode(BlockMode::ECB)
4649 .Padding(PaddingMode::NONE)));
4650
4651 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
4652 auto cipher_params =
4653 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4654
4655 AuthorizationSet out_params;
4656 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
4657
4658 string plain_message = std::string(1 << msg_size, 'x');
4659 string encrypted_message;
4660 auto rc = Finish(plain_message, &encrypted_message);
4661
4662 EXPECT_EQ(ErrorCode::OK, rc);
4663 EXPECT_EQ(plain_message.size(), encrypted_message.size())
4664 << "Encrypt finish returned OK, but did not consume all of the given input";
4665 cipher_params.push_back(out_params);
4666
4667 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
4668
4669 string decrypted_message;
4670 rc = Finish(encrypted_message, &decrypted_message);
4671 EXPECT_EQ(ErrorCode::OK, rc);
4672 EXPECT_EQ(plain_message.size(), decrypted_message.size())
4673 << "Decrypt finish returned OK, did not consume all of the given input";
4674 }
4675}
4676
4677INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
4678
David Zeuthene0c40892021-01-08 12:54:11 -05004679typedef KeyMintAidlTestBase KeyAgreementTest;
4680
4681int CurveToOpenSslCurveName(EcCurve curve) {
4682 switch (curve) {
4683 case EcCurve::P_224:
4684 return NID_secp224r1;
4685 case EcCurve::P_256:
4686 return NID_X9_62_prime256v1;
4687 case EcCurve::P_384:
4688 return NID_secp384r1;
4689 case EcCurve::P_521:
4690 return NID_secp521r1;
4691 }
4692}
4693
4694/*
4695 * KeyAgreementTest.Ecdh
4696 *
4697 * Verifies that ECDH works for all curves
4698 */
4699TEST_P(KeyAgreementTest, Ecdh) {
4700 // Because it's possible to use this API with keys on different curves, we
4701 // check all N^2 combinations where N is the number of supported
4702 // curves.
4703 //
4704 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
4705 // lot more curves we can be smart about things and just pick |otherCurve| so
4706 // it's not |curve| and that way we end up with only 2*N runs
4707 //
4708 for (auto curve : ValidCurves()) {
4709 for (auto localCurve : ValidCurves()) {
4710 // Generate EC key locally (with access to private key material)
4711 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
4712 int curveName = CurveToOpenSslCurveName(localCurve);
4713 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
4714 ASSERT_NE(group, nullptr);
4715 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
4716 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
4717 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
4718 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
4719
4720 // Get encoded form of the public part of the locally generated key...
4721 unsigned char* p = nullptr;
4722 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
4723 ASSERT_GT(encodedPublicKeySize, 0);
4724 vector<uint8_t> encodedPublicKey(
4725 reinterpret_cast<const uint8_t*>(p),
4726 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
4727 OPENSSL_free(p);
4728
4729 // Generate EC key in KeyMint (only access to public key material)
4730 vector<uint8_t> challenge = {0x41, 0x42};
4731 EXPECT_EQ(
4732 ErrorCode::OK,
4733 GenerateKey(AuthorizationSetBuilder()
4734 .Authorization(TAG_NO_AUTH_REQUIRED)
4735 .Authorization(TAG_EC_CURVE, curve)
4736 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4737 .Authorization(TAG_ALGORITHM, Algorithm::EC)
4738 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08004739 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
4740 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05004741 << "Failed to generate key";
4742 ASSERT_GT(cert_chain_.size(), 0);
4743 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4744 ASSERT_NE(kmKeyCert, nullptr);
4745 // Check that keyAgreement (bit 4) is set in KeyUsage
4746 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
4747 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
4748 ASSERT_NE(kmPkey, nullptr);
4749 if (dump_Attestations) {
4750 for (size_t n = 0; n < cert_chain_.size(); n++) {
4751 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
4752 }
4753 }
4754
4755 // Now that we have the two keys, we ask KeyMint to perform ECDH...
4756 if (curve != localCurve) {
4757 // If the keys are using different curves KeyMint should fail with
4758 // ErrorCode:INVALID_ARGUMENT. Check that.
4759 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
4760 string ZabFromKeyMintStr;
4761 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
4762 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
4763 &ZabFromKeyMintStr));
4764
4765 } else {
4766 // Otherwise if the keys are using the same curve, it should work.
4767 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
4768 string ZabFromKeyMintStr;
4769 EXPECT_EQ(ErrorCode::OK,
4770 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
4771 &ZabFromKeyMintStr));
4772 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
4773
4774 // Perform local ECDH between the two keys so we can check if we get the same Zab..
4775 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
4776 ASSERT_NE(ctx, nullptr);
4777 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
4778 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
4779 size_t ZabFromTestLen = 0;
4780 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
4781 vector<uint8_t> ZabFromTest;
4782 ZabFromTest.resize(ZabFromTestLen);
4783 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
4784
4785 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
4786 }
4787
4788 CheckedDeleteKey();
4789 }
4790 }
4791}
4792
4793INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
4794
Shawn Willdend659c7c2021-02-19 14:51:51 -07004795using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00004796
4797TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
4798 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
4799 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
4800
4801 CheckedDeleteKey(&aesKeyData.blob);
4802 CheckedDeleteKey(&hmacKeyData.blob);
4803 CheckedDeleteKey(&rsaKeyData.blob);
4804 CheckedDeleteKey(&ecdsaKeyData.blob);
4805}
4806
4807// This is a more comprenhensive test, but it can only be run on a machine which is still in early
4808// boot stage, which no proper Android device is by the time we can run VTS. To use this,
4809// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
4810// early boot, so you'll have to reboot between runs.
4811TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
4812 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
4813 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
4814 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
4815 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
4816 EXPECT_TRUE(
4817 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
4818 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
4819 EXPECT_TRUE(
4820 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
4821
4822 // Should be able to use keys, since early boot has not ended
4823 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
4824 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
4825 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
4826 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
4827
4828 // End early boot
4829 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
4830 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
4831
4832 // Should not be able to use already-created keys.
4833 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
4834 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
4835 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
4836 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
4837
4838 CheckedDeleteKey(&aesKeyData.blob);
4839 CheckedDeleteKey(&hmacKeyData.blob);
4840 CheckedDeleteKey(&rsaKeyData.blob);
4841 CheckedDeleteKey(&ecdsaKeyData.blob);
4842
4843 // Should not be able to create new keys
4844 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
4845 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
4846
4847 CheckedDeleteKey(&aesKeyData.blob);
4848 CheckedDeleteKey(&hmacKeyData.blob);
4849 CheckedDeleteKey(&rsaKeyData.blob);
4850 CheckedDeleteKey(&ecdsaKeyData.blob);
4851}
Shawn Willdend659c7c2021-02-19 14:51:51 -07004852
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00004853INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
4854
Shawn Willdend659c7c2021-02-19 14:51:51 -07004855using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00004856
4857// This may be a problematic test. It can't be run repeatedly without unlocking the device in
4858// between runs... and on most test devices there are no enrolled credentials so it can't be
4859// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
4860// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
4861// a manual test process, which includes unlocking between runs, which is why it's included here.
4862// Well, that and the fact that it's the only test we can do without also making calls into the
4863// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
4864// implications might be, so that may or may not be a solution.
4865TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
4866 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
4867 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
4868
4869 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
4870 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
4871 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
4872 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
4873
4874 ErrorCode rc = GetReturnErrorCode(
4875 keyMint().deviceLocked(false /* passwordOnly */, {} /* verificationToken */));
4876 ASSERT_EQ(ErrorCode::OK, rc);
4877 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
4878 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
4879 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
4880 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
4881
4882 CheckedDeleteKey(&aesKeyData.blob);
4883 CheckedDeleteKey(&hmacKeyData.blob);
4884 CheckedDeleteKey(&rsaKeyData.blob);
4885 CheckedDeleteKey(&ecdsaKeyData.blob);
4886}
Shawn Willdend659c7c2021-02-19 14:51:51 -07004887
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00004888INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
4889
Shawn Willdend659c7c2021-02-19 14:51:51 -07004890using PerformOperationTest = KeyMintAidlTestBase;
4891
4892TEST_P(PerformOperationTest, RequireUnimplemented) {
4893 vector<uint8_t> response;
4894 auto result = keymint_->performOperation({} /* request */, &response);
4895 ASSERT_EQ(GetReturnErrorCode(result), ErrorCode::UNIMPLEMENTED);
4896}
4897
4898INSTANTIATE_KEYMINT_AIDL_TEST(PerformOperationTest);
4899
Janis Danisevskis24c04702020-12-16 18:28:39 -08004900} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07004901
4902int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07004903 std::cout << "Testing ";
4904 auto halInstances =
4905 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
4906 std::cout << "HAL instances:\n";
4907 for (auto& entry : halInstances) {
4908 std::cout << " " << entry << '\n';
4909 }
4910
Selene Huang31ab4042020-04-29 04:22:39 -07004911 ::testing::InitGoogleTest(&argc, argv);
4912 for (int i = 1; i < argc; ++i) {
4913 if (argv[i][0] == '-') {
4914 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07004915 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
4916 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07004917 }
4918 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07004919 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
4920 dump_Attestations = true;
4921 } else {
4922 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07004923 }
4924 }
4925 }
Shawn Willden08a7e432020-12-11 13:05:27 +00004926 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07004927}