blob: f654d889a5f669ab62c3ae9def9a1f2bbd883edb [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>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Zeuthene0c40892021-01-08 12:54:11 -050025#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070026#include <openssl/evp.h>
27#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050028#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070029
30#include <cutils/properties.h>
31
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <android/binder_manager.h>
33
34#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080035#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070036
Shawn Willden08a7e432020-12-11 13:05:27 +000037#include <keymint_support/key_param_output.h>
38#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070039
40#include "KeyMintAidlTestBase.h"
41
Janis Danisevskis24c04702020-12-16 18:28:39 -080042using aidl::android::hardware::security::keymint::AuthorizationSet;
43using aidl::android::hardware::security::keymint::KeyCharacteristics;
44using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070045
Selene Huang31ab4042020-04-29 04:22:39 -070046namespace std {
47
Janis Danisevskis24c04702020-12-16 18:28:39 -080048using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070049
50template <>
51struct std::equal_to<KeyCharacteristics> {
52 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070053 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070054
Shawn Willden7f424372021-01-10 18:06:50 -070055 // this isn't very efficient. Oh, well.
56 AuthorizationSet a_auths(a.authorizations);
57 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070058
Shawn Willden7f424372021-01-10 18:06:50 -070059 a_auths.Sort();
60 b_auths.Sort();
61
62 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070063 }
64};
65
66} // namespace std
67
Janis Danisevskis24c04702020-12-16 18:28:39 -080068namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000069
Selene Huang31ab4042020-04-29 04:22:39 -070070namespace {
71
Seth Moore7a55ae32021-06-23 14:28:11 -070072// The maximum number of times we'll attempt to verify that corruption
73// of an ecrypted blob results in an error. Retries are necessary as there
74// is a small (roughly 1/256) chance that corrupting ciphertext still results
75// in valid PKCS7 padding.
76constexpr size_t kMaxPaddingCorruptionRetries = 8;
77
Selene Huang31ab4042020-04-29 04:22:39 -070078template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000079bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
80 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070081 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080082 if (auto p = authorizationValue(ttag, param)) {
83 return *p == expected_value;
84 }
85 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070086 });
87 return (it != set.end());
88}
89
90template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000091bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070092 auto it = std::find_if(set.begin(), set.end(),
93 [&](const KeyParameter& param) { return param.tag == tag; });
94 return (it != set.end());
95}
96
97constexpr char hex_value[256] = {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, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
101 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
102 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
103 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
113
114string hex2str(string a) {
115 string b;
116 size_t num = a.size() / 2;
117 b.resize(num);
118 for (size_t i = 0; i < num; i++) {
119 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
120 }
121 return b;
122}
123
David Drysdaled2cc8c22021-04-15 13:29:45 +0100124string rsa_key = hex2str(
125 // RFC 5208 s5
126 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
127 "020100" // INTEGER length 1 value 0x00 (version)
128 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
129 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
130 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
131 "0500" // NULL (parameters)
132 // } end SEQUENCE (AlgorithmIdentifier)
133 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
134 // RFC 8017 A.1.2
135 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
136 "020100" // INTEGER length 1 value 0x00 (version)
137 "028181" // INTEGER length 0x81 value (modulus) ...
138 "00c6095409047d8634812d5a218176e4"
139 "5c41d60a75b13901f234226cffe77652"
140 "1c5a77b9e389417b71c0b6a44d13afe4"
141 "e4a2805d46c9da2935adb1ff0c1f24ea"
142 "06e62b20d776430a4d435157233c6f91"
143 "6783c30e310fcbd89b85c2d567711697"
144 "85ac12bca244abda72bfb19fc44d27c8"
145 "1e1d92de284f4061edfd99280745ea6d"
146 "25"
147 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
148 "028180" // INTEGER length 0x80 (privateExponent) value...
149 "1be0f04d9cae3718691f035338308e91"
150 "564b55899ffb5084d2460e6630257e05"
151 "b3ceab02972dfabcd6ce5f6ee2589eb6"
152 "7911ed0fac16e43a444b8c861e544a05"
153 "93365772f8baf6b22fc9e3c5f1024b06"
154 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
155 "ace7240290bef16c0b3f7f3cdd64ce3a"
156 "b5912cf6e32f39ab188358afcccd8081"
157 "0241" // INTEGER length 0x41 (prime1)
158 "00e4b49ef50f765d3b24dde01aceaaf1"
159 "30f2c76670a91a61ae08af497b4a82be"
160 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
161 "8c92bfab137fba2285227b83c342ff7c"
162 "55"
163 "0241" // INTEGER length 0x41 (prime2)
164 "00ddabb5839c4c7f6bf3d4183231f005"
165 "b31aa58affdda5c79e4cce217f6bc930"
166 "dbe563d480706c24e9ebfcab28a6cdef"
167 "d324b77e1bf7251b709092c24ff501fd"
168 "91"
169 "0240" // INTEGER length 0x40 (exponent1)
170 "23d4340eda3445d8cd26c14411da6fdc"
171 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
172 "842c1d280405bc2f6c1bea214a1d742a"
173 "b996b35b63a82a5e470fa88dbf823cdd"
174 "0240" // INTEGER length 0x40 (exponent2)
175 "1b7b57449ad30d1518249a5f56bb9829"
176 "4d4b6ac12ffc86940497a5a5837a6cf9"
177 "46262b494526d328c11e1126380fde04"
178 "c24f916dec250892db09a6d77cdba351"
179 "0240" // INTEGER length 0x40 (coefficient)
180 "7762cd8f4d050da56bd591adb515d24d"
181 "7ccd32cca0d05f866d583514bd7324d5"
182 "f33645e8ed8b4a1cb3cc4a1d67987399"
183 "f2a09f5b3fb68c88d5e5d90ac33492d6"
184 // } end SEQUENCE (PrivateKey)
185 // } end SEQUENCE (PrivateKeyInfo)
186);
Selene Huang31ab4042020-04-29 04:22:39 -0700187
Selene Huange5727e62021-04-13 22:41:20 -0700188/*
189 * DER-encoded PKCS#8 format RSA key. Generated using:
190 *
191 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
192 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100193string rsa_2048_key = hex2str(
194 // RFC 5208 s5
195 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
196 "020100" // INTEGER length 1 value 0x00 (version)
197 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
198 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
199 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
200 "0500" // NULL (parameters)
201 // } end SEQUENCE (AlgorithmIdentifier)
202 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
203 // RFC 8017 A.1.2
204 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
205 "020100" // INTEGER length 1 value 0x00 (version)
206 "02820101" // INTEGER length 0x101 value (modulus) ...
207 "00BEBC342B56D443B1299F9A6A7056E8"
208 "0A897E318476A5A18029E63B2ED739A6"
209 "1791D339F58DC763D9D14911F2EDEC38"
210 "3DEE11F6319B44510E7A3ECD9B79B973"
211 "82E49500ACF8117DC89CAF0E621F7775"
212 "6554A2FD4664BFE7AB8B59AB48340DBF"
213 "A27B93B5A81F6ECDEB02D0759307128D"
214 "F3E3BAD4055C8B840216DFAA5700670E"
215 "6C5126F0962FCB70FF308F25049164CC"
216 "F76CC2DA66A7DD9A81A714C2809D6918"
217 "6133D29D84568E892B6FFBF3199BDB14"
218 "383EE224407F190358F111A949552ABA"
219 "6714227D1BD7F6B20DD0CB88F9467B71"
220 "9339F33BFF35B3870B3F62204E4286B0"
221 "948EA348B524544B5F9838F29EE643B0"
222 "79EEF8A713B220D7806924CDF7295070"
223 "C5"
224 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
225 "02820100" // INTEGER length 0x100 (privateExponent) value...
226 "69F377F35F2F584EF075353CCD1CA997"
227 "38DB3DBC7C7FF35F9366CE176DFD1B13"
228 "5AB10030344ABF5FBECF1D4659FDEF1C"
229 "0FC430834BE1BE3911951377BB3D563A"
230 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
231 "2686C7B4B3C09A7B8354133E6F93F790"
232 "D59EAEB92E84C9A4339302CCE28FDF04"
233 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
234 "6AB706645BF074A4E4090D06FB163124"
235 "365FD5EE7A20D350E9958CC30D91326E"
236 "1B292E9EF5DB408EC42DAF737D201497"
237 "04D0A678A0FB5B5446863B099228A352"
238 "D604BA8091A164D01D5AB05397C71EAD"
239 "20BE2A08FC528FE442817809C787FEE4"
240 "AB97F97B9130D022153EDC6EB6CBE7B0"
241 "F8E3473F2E901209B5DB10F93604DB01"
242 "028181" // INTEGER length 0x81 (prime1)
243 "00E83C0998214941EA4F9293F1B77E2E"
244 "99E6CF305FAF358238E126124FEAF2EB"
245 "9724B2EA7B78E6032343821A80E55D1D"
246 "88FB12D220C3F41A56142FEC85796D19"
247 "17F1E8C774F142B67D3D6E7B7E6B4383"
248 "E94DB5929089DBB346D5BDAB40CC2D96"
249 "EE0409475E175C63BF78CFD744136740"
250 "838127EA723FF3FE7FA368C1311B4A4E"
251 "05"
252 "028181" // INTEGER length 0x81 (prime2)
253 "00D240FCC0F5D7715CDE21CB2DC86EA1"
254 "46132EA3B06F61FF2AF54BF38473F59D"
255 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
256 "B1B58C39F95E4798CCBB43E83D0119AC"
257 "F532F359CA743C85199F0286610E2009"
258 "97D7312917179AC9B67558773212EC96"
259 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
260 "94D94E066A0900B7B70E82A44FB30053"
261 "C1"
262 "028181" // INTEGER length 0x81 (exponent1)
263 "00AD15DA1CBD6A492B66851BA8C316D3"
264 "8AB700E2CFDDD926A658003513C54BAA"
265 "152B30021D667D20078F500F8AD3E7F3"
266 "945D74A891ED1A28EAD0FEEAEC8C14A8"
267 "E834CF46A13D1378C99D18940823CFDD"
268 "27EC5810D59339E0C34198AC638E09C8"
269 "7CBB1B634A9864AE9F4D5EB2D53514F6"
270 "7B4CAEC048C8AB849A02E397618F3271"
271 "35"
272 "028180" // INTEGER length 0x80 (exponent2)
273 "1FA2C1A5331880A92D8F3E281C617108"
274 "BF38244F16E352E69ED417C7153F9EC3"
275 "18F211839C643DCF8B4DD67CE2AC312E"
276 "95178D5D952F06B1BF779F4916924B70"
277 "F582A23F11304E02A5E7565AE22A35E7"
278 "4FECC8B6FDC93F92A1A37703E4CF0E63"
279 "783BD02EB716A7ECBBFA606B10B74D01"
280 "579522E7EF84D91FC522292108D902C1"
281 "028180" // INTEGER length 0x80 (coefficient)
282 "796FE3825F9DCC85DF22D58690065D93"
283 "898ACD65C087BEA8DA3A63BF4549B795"
284 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
285 "0D74F40DED8E1102C52152A31B6165F8"
286 "3A6722AECFCC35A493D7634664B888A0"
287 "8D3EB034F12EA28BFEE346E205D33482"
288 "7F778B16ED40872BD29FCB36536B6E93"
289 "FFB06778696B4A9D81BB0A9423E63DE5"
290 // } end SEQUENCE (PrivateKey)
291 // } end SEQUENCE (PrivateKeyInfo)
292);
Selene Huange5727e62021-04-13 22:41:20 -0700293
David Drysdaled2cc8c22021-04-15 13:29:45 +0100294string ec_256_key = hex2str(
295 // RFC 5208 s5
296 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
297 "020100" // INTEGER length 1 value 0 (version)
298 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
299 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
300 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
301 "0608" // OBJECT IDENTIFIER length 8 (param)
302 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
303 // } end SEQUENCE (AlgorithmIdentifier)
304 "046d" // OCTET STRING length 0x6d (privateKey) holding...
305 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
306 "020101" // INTEGER length 1 value 1 (version)
307 "0420" // OCTET STRING length 0x20 (privateKey)
308 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
309 "941eed09366bc03299986481f3a4d859"
310 "a144" // TAG [1] len 0x44 (publicKey) {
311 "03420004bf85d7720d07c25461683bc6"
312 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
313 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
314 "bcc41c6eb00083cf3376d11fd44949e0"
315 "b2183bfe"
316 // } end SEQUENCE (ECPrivateKey)
317 // } end SEQUENCE (PrivateKeyInfo)
318);
Selene Huang31ab4042020-04-29 04:22:39 -0700319
David Drysdaled2cc8c22021-04-15 13:29:45 +0100320string ec_521_key = hex2str(
321 // RFC 5208 s5
322 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
323 "020100" // INTEGER length 1 value 0 (version)
324 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
325 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
326 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
327 "0605" // OBJECT IDENTIFIER length 5 (param)
328 "2B81040023" // 1.3.132.0.35 (secp521r1)
329 // } end SEQUENCE (AlgorithmIdentifier)
330 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
331 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
332 "020101" // INTEGER length 1 value 1 (version)
333 "0442" // OCTET STRING length 0x42 (privateKey)
334 "0011458C586DB5DAA92AFAB03F4FE46A"
335 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
336 "9D18D7D08B5BCFA0E53C75B064AD51C4"
337 "49BAE0258D54B94B1E885DED08ED4FB2"
338 "5CE9"
339 "A18189" // TAG [1] len 0x89 (publicKey) {
340 "03818600040149EC11C6DF0FA122C6A9"
341 "AFD9754A4FA9513A627CA329E349535A"
342 "5629875A8ADFBE27DCB932C051986377"
343 "108D054C28C6F39B6F2C9AF81802F9F3"
344 "26B842FF2E5F3C00AB7635CFB36157FC"
345 "0882D574A10D839C1A0C049DC5E0D775"
346 "E2EE50671A208431BB45E78E70BEFE93"
347 "0DB34818EE4D5C26259F5C6B8E28A652"
348 "950F9F88D7B4B2C9D9"
349 // } end SEQUENCE (ECPrivateKey)
350 // } end SEQUENCE (PrivateKeyInfo)
351);
Selene Huang31ab4042020-04-29 04:22:39 -0700352
David Drysdaled2cc8c22021-04-15 13:29:45 +0100353string ec_256_key_rfc5915 = hex2str(
354 // RFC 5208 s5
355 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
356 "020100" // INTEGER length 1 value 0 (version)
357 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
358 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
359 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
360 "0608" // OBJECT IDENTIFIER length 8 (param)
361 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
362 // } end SEQUENCE (AlgorithmIdentifier)
363 "0479" // OCTET STRING length 0x79 (privateKey) holding...
364 // RFC 5915 s3
365 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
366 "020101" // INTEGER length 1 value 1 (version)
367 "0420" // OCTET STRING length 0x42 (privateKey)
368 "782370a8c8ce5537baadd04dcff079c8"
369 "158cfa9c67b818b38e8d21c9fa750c1d"
370 "a00a" // TAG [0] length 0xa (parameters)
371 "0608" // OBJECT IDENTIFIER length 8
372 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
373 // } end TAG [0]
374 "a144" // TAG [1] length 0x44 (publicKey) {
375 "0342" // BIT STRING length 0x42
376 "00" // no pad bits
377 "04e2cc561ee701da0ad0ef0d176bb0c9"
378 "19d42e79c393fdc1bd6c4010d85cf2cf"
379 "8e68c905464666f98dad4f01573ba810"
380 "78b3428570a439ba3229fbc026c55068"
381 "2f"
382 // } end SEQUENCE (ECPrivateKey)
383 // } end SEQUENCE (PrivateKeyInfo)
384);
Selene Huang31ab4042020-04-29 04:22:39 -0700385
David Drysdaled2cc8c22021-04-15 13:29:45 +0100386string ec_256_key_sec1 = hex2str(
387 // RFC 5208 s5
388 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
389 "020100" // INTEGER length 1 value 0 (version)
390 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
391 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
392 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
393 "0608" // OBJECT IDENTIFIER length 8 (param)
394 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
395 // } end SEQUENCE (AlgorithmIdentifier)
396 "046d" // OCTET STRING length 0x6d (privateKey) holding...
397 // SEC1-v2 C.4
398 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
399 "020101" // INTEGER length 1 value 0x01 (version)
400 "0420" // OCTET STRING length 0x20 (privateKey)
401 "782370a8c8ce5537baadd04dcff079c8"
402 "158cfa9c67b818b38e8d21c9fa750c1d"
403 "a144" // TAG [1] length 0x44 (publicKey) {
404 "0342" // BIT STRING length 0x42
405 "00" // no pad bits
406 "04e2cc561ee701da0ad0ef0d176bb0c9"
407 "19d42e79c393fdc1bd6c4010d85cf2cf"
408 "8e68c905464666f98dad4f01573ba810"
409 "78b3428570a439ba3229fbc026c55068"
410 "2f"
411 // } end TAG [1] (publicKey)
412 // } end SEQUENCE (PrivateKeyInfo)
413);
Selene Huang31ab4042020-04-29 04:22:39 -0700414
415struct RSA_Delete {
416 void operator()(RSA* p) { RSA_free(p); }
417};
418
Selene Huang31ab4042020-04-29 04:22:39 -0700419std::string make_string(const uint8_t* data, size_t length) {
420 return std::string(reinterpret_cast<const char*>(data), length);
421}
422
423template <size_t N>
424std::string make_string(const uint8_t (&a)[N]) {
425 return make_string(a, N);
426}
427
428class AidlBuf : public vector<uint8_t> {
429 typedef vector<uint8_t> super;
430
431 public:
432 AidlBuf() {}
433 AidlBuf(const super& other) : super(other) {}
434 AidlBuf(super&& other) : super(std::move(other)) {}
435 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
436
437 AidlBuf& operator=(const super& other) {
438 super::operator=(other);
439 return *this;
440 }
441
442 AidlBuf& operator=(super&& other) {
443 super::operator=(std::move(other));
444 return *this;
445 }
446
447 AidlBuf& operator=(const string& other) {
448 resize(other.size());
449 for (size_t i = 0; i < other.size(); ++i) {
450 (*this)[i] = static_cast<uint8_t>(other[i]);
451 }
452 return *this;
453 }
454
455 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
456};
457
David Drysdale4dc01072021-04-01 12:17:35 +0100458string device_suffix(const string& name) {
459 size_t pos = name.find('/');
460 if (pos == string::npos) {
461 return name;
462 }
463 return name.substr(pos + 1);
464}
465
466bool matching_rp_instance(const string& km_name,
467 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
468 string km_suffix = device_suffix(km_name);
469
470 vector<string> rp_names =
471 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
472 for (const string& rp_name : rp_names) {
473 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
474 // KeyMint instance, assume they match.
475 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
476 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
477 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
478 return true;
479 }
480 }
481 return false;
482}
483
Selene Huang31ab4042020-04-29 04:22:39 -0700484} // namespace
485
486class NewKeyGenerationTest : public KeyMintAidlTestBase {
487 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700488 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000489 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700490 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700491
Selene Huang31ab4042020-04-29 04:22:39 -0700492 // Check that some unexpected tags/values are NOT present.
493 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
494 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000495 }
496
497 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
498 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
499 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
500 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
501
502 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000503 }
504
505 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
506 // TODO(swillden): Distinguish which params should be in which auth list.
507 AuthorizationSet auths;
508 for (auto& entry : keyCharacteristics) {
509 auths.push_back(AuthorizationSet(entry.authorizations));
510 }
511 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
512
513 // Verify that App data, ROT and auth timeout are NOT included.
514 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
515 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700516 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
517
David Drysdaled2cc8c22021-04-15 13:29:45 +0100518 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
519 // never adds it.
520 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
521
David Drysdale7de9feb2021-03-05 14:56:19 +0000522 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700523 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000524 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700525 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700526 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000527 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700528 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000529
David Drysdalef5bfa002021-09-27 17:30:41 +0100530 // Should include vendor and boot patchlevels.
531 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
532 EXPECT_TRUE(vendor_pl);
533 EXPECT_EQ(*vendor_pl, vendor_patch_level());
534 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
535 EXPECT_TRUE(boot_pl);
David Drysdalebb3d85e2021-04-13 11:15:51 +0100536
David Drysdale7de9feb2021-03-05 14:56:19 +0000537 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700538 }
539};
540
541/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000542 * NewKeyGenerationTest.Aes
543 *
544 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
545 * have correct characteristics.
546 */
547TEST_P(NewKeyGenerationTest, Aes) {
548 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
549 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
550 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
551 SCOPED_TRACE(testing::Message()
552 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
553 vector<uint8_t> key_blob;
554 vector<KeyCharacteristics> key_characteristics;
555 auto builder = AuthorizationSetBuilder()
556 .AesEncryptionKey(key_size)
557 .BlockMode(block_mode)
558 .Padding(padding_mode)
559 .SetDefaultValidity();
560 if (block_mode == BlockMode::GCM) {
561 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
562 }
563 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
564
565 EXPECT_GT(key_blob.size(), 0U);
566 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100567 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000568
569 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
570
571 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
572 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
573 << "Key size " << key_size << "missing";
574
575 CheckedDeleteKey(&key_blob);
576 }
577 }
578 }
579}
580
581/*
582 * NewKeyGenerationTest.AesInvalidSize
583 *
584 * Verifies that specifying an invalid key size for AES key generation returns
585 * UNSUPPORTED_KEY_SIZE.
586 */
587TEST_P(NewKeyGenerationTest, AesInvalidSize) {
588 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
589 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
590 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
591 SCOPED_TRACE(testing::Message()
592 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
593 vector<uint8_t> key_blob;
594 vector<KeyCharacteristics> key_characteristics;
595 auto builder = AuthorizationSetBuilder()
596 .AesEncryptionKey(key_size)
597 .BlockMode(block_mode)
598 .Padding(padding_mode)
599 .SetDefaultValidity();
600 if (block_mode == BlockMode::GCM) {
601 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
602 }
603 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
604 GenerateKey(builder, &key_blob, &key_characteristics));
605 }
606 }
607 }
608
609 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
610 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
611 vector<uint8_t> key_blob;
612 vector<KeyCharacteristics> key_characteristics;
613 // No key size specified
614 auto builder = AuthorizationSetBuilder()
615 .Authorization(TAG_ALGORITHM, Algorithm::AES)
616 .BlockMode(block_mode)
617 .Padding(padding_mode)
618 .SetDefaultValidity();
619 if (block_mode == BlockMode::GCM) {
620 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
621 }
622 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
623 GenerateKey(builder, &key_blob, &key_characteristics));
624 }
625 }
626}
627
628/*
629 * NewKeyGenerationTest.AesInvalidPadding
630 *
631 * Verifies that specifying an invalid padding on AES keys gives a failure
632 * somewhere along the way.
633 */
634TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
635 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
636 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
637 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
638 SCOPED_TRACE(testing::Message()
639 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000640 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800641 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000642 .AesEncryptionKey(key_size)
643 .BlockMode(block_mode)
644 .Padding(padding_mode)
645 .SetDefaultValidity();
646 if (block_mode == BlockMode::GCM) {
647 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
648 }
649
Tommy Chiu3950b452021-05-03 22:01:46 +0800650 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000651 if (result == ErrorCode::OK) {
652 // Key creation was OK but has generated a key that cannot be used.
653 auto params =
654 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800655 if (block_mode == BlockMode::GCM) {
656 params.Authorization(TAG_MAC_LENGTH, 128);
657 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000658 auto result = Begin(KeyPurpose::ENCRYPT, params);
659 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100660 result == ErrorCode::INVALID_KEY_BLOB)
661 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000662 } else {
663 // The KeyMint implementation detected that the generated key
664 // is unusable.
665 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
666 }
667 }
668 }
669 }
670}
671
672/*
673 * NewKeyGenerationTest.AesGcmMissingMinMac
674 *
675 * Verifies that specifying an invalid key size for AES key generation returns
676 * UNSUPPORTED_KEY_SIZE.
677 */
678TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
679 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
680 BlockMode block_mode = BlockMode::GCM;
681 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
682 SCOPED_TRACE(testing::Message()
683 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
684 vector<uint8_t> key_blob;
685 vector<KeyCharacteristics> key_characteristics;
686 // No MIN_MAC_LENGTH provided.
687 auto builder = AuthorizationSetBuilder()
688 .AesEncryptionKey(key_size)
689 .BlockMode(block_mode)
690 .Padding(padding_mode)
691 .SetDefaultValidity();
692 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
693 GenerateKey(builder, &key_blob, &key_characteristics));
694 }
695 }
696}
697
698/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100699 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
700 *
701 * Verifies that specifying an invalid min MAC size for AES key generation returns
702 * UNSUPPORTED_MIN_MAC_LENGTH.
703 */
704TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
705 for (size_t min_mac_len : {88, 136}) {
706 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
707 BlockMode block_mode = BlockMode::GCM;
708 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
709 SCOPED_TRACE(testing::Message()
710 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
711 vector<uint8_t> key_blob;
712 vector<KeyCharacteristics> key_characteristics;
713 auto builder = AuthorizationSetBuilder()
714 .AesEncryptionKey(key_size)
715 .BlockMode(block_mode)
716 .Padding(padding_mode)
717 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
718 .SetDefaultValidity();
719 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
720 GenerateKey(builder, &key_blob, &key_characteristics));
721 }
722 }
723 }
724}
725
726/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000727 * NewKeyGenerationTest.TripleDes
728 *
729 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
730 * have correct characteristics.
731 */
732TEST_P(NewKeyGenerationTest, TripleDes) {
733 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
734 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
735 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
736 SCOPED_TRACE(testing::Message()
737 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
738 vector<uint8_t> key_blob;
739 vector<KeyCharacteristics> key_characteristics;
740 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
741 .TripleDesEncryptionKey(key_size)
742 .BlockMode(block_mode)
743 .Padding(padding_mode)
744 .Authorization(TAG_NO_AUTH_REQUIRED)
745 .SetDefaultValidity(),
746 &key_blob, &key_characteristics));
747
748 EXPECT_GT(key_blob.size(), 0U);
749 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100750 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000751
752 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
753
754 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
755 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
756 << "Key size " << key_size << "missing";
757
758 CheckedDeleteKey(&key_blob);
759 }
760 }
761 }
762}
763
764/*
765 * NewKeyGenerationTest.TripleDesWithAttestation
766 *
767 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
768 * have correct characteristics.
769 *
770 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
771 * put in a certificate) but which isn't an error.
772 */
773TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
774 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
775 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
776 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
777 SCOPED_TRACE(testing::Message()
778 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
779
780 auto challenge = "hello";
781 auto app_id = "foo";
782
783 vector<uint8_t> key_blob;
784 vector<KeyCharacteristics> key_characteristics;
785 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
786 .TripleDesEncryptionKey(key_size)
787 .BlockMode(block_mode)
788 .Padding(padding_mode)
789 .Authorization(TAG_NO_AUTH_REQUIRED)
790 .AttestationChallenge(challenge)
791 .AttestationApplicationId(app_id)
792 .SetDefaultValidity(),
793 &key_blob, &key_characteristics));
794
795 EXPECT_GT(key_blob.size(), 0U);
796 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100797 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000798
799 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
800
801 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
802 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
803 << "Key size " << key_size << "missing";
804
805 CheckedDeleteKey(&key_blob);
806 }
807 }
808 }
809}
810
811/*
812 * NewKeyGenerationTest.TripleDesInvalidSize
813 *
814 * Verifies that specifying an invalid key size for 3-DES key generation returns
815 * UNSUPPORTED_KEY_SIZE.
816 */
817TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
818 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
819 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
820 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
821 SCOPED_TRACE(testing::Message()
822 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
823 vector<uint8_t> key_blob;
824 vector<KeyCharacteristics> key_characteristics;
825 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
826 GenerateKey(AuthorizationSetBuilder()
827 .TripleDesEncryptionKey(key_size)
828 .BlockMode(block_mode)
829 .Padding(padding_mode)
830 .Authorization(TAG_NO_AUTH_REQUIRED)
831 .SetDefaultValidity(),
832 &key_blob, &key_characteristics));
833 }
834 }
835 }
836
837 // Omitting the key size fails.
838 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
839 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
840 SCOPED_TRACE(testing::Message()
841 << "3DES-default-" << block_mode << "-" << padding_mode);
842 vector<uint8_t> key_blob;
843 vector<KeyCharacteristics> key_characteristics;
844 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
845 GenerateKey(AuthorizationSetBuilder()
846 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
847 .BlockMode(block_mode)
848 .Padding(padding_mode)
849 .Authorization(TAG_NO_AUTH_REQUIRED)
850 .SetDefaultValidity(),
851 &key_blob, &key_characteristics));
852 }
853 }
854}
855
856/*
Selene Huang31ab4042020-04-29 04:22:39 -0700857 * NewKeyGenerationTest.Rsa
858 *
859 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
860 * have correct characteristics.
861 */
862TEST_P(NewKeyGenerationTest, Rsa) {
863 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
864 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700865 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700866 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
867 .RsaSigningKey(key_size, 65537)
868 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800869 .Padding(PaddingMode::NONE)
870 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700871 &key_blob, &key_characteristics));
872
873 ASSERT_GT(key_blob.size(), 0U);
874 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100875 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700876
Shawn Willden7f424372021-01-10 18:06:50 -0700877 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700878
879 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
880 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
881 << "Key size " << key_size << "missing";
882 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
883
884 CheckedDeleteKey(&key_blob);
885 }
886}
887
888/*
Qi Wud22ec842020-11-26 13:27:53 +0800889 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700890 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100891 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
892 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700893 */
894TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700895 auto challenge = "hello";
896 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700897
Selene Huang6e46f142021-04-20 19:20:11 -0700898 auto subject = "cert subj 2";
899 vector<uint8_t> subject_der(make_name_from_str(subject));
900
901 uint64_t serial_int = 66;
902 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
903
Selene Huang4f64c222021-04-13 19:54:36 -0700904 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700905 vector<uint8_t> key_blob;
906 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700907 ASSERT_EQ(ErrorCode::OK,
908 GenerateKey(AuthorizationSetBuilder()
909 .RsaSigningKey(key_size, 65537)
910 .Digest(Digest::NONE)
911 .Padding(PaddingMode::NONE)
912 .AttestationChallenge(challenge)
913 .AttestationApplicationId(app_id)
914 .Authorization(TAG_NO_AUTH_REQUIRED)
915 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
916 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
917 .SetDefaultValidity(),
918 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700919
920 ASSERT_GT(key_blob.size(), 0U);
921 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100922 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700923
924 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
925
926 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
927 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
928 << "Key size " << key_size << "missing";
929 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
930
Selene Huang6e46f142021-04-20 19:20:11 -0700931 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700932 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700933 ASSERT_GT(cert_chain_.size(), 0);
934
935 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
936 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
937 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
938 sw_enforced, hw_enforced, SecLevel(),
939 cert_chain_[0].encodedCertificate));
940
941 CheckedDeleteKey(&key_blob);
942 }
943}
944
945/*
David Drysdale4dc01072021-04-01 12:17:35 +0100946 * NewKeyGenerationTest.RsaWithRpkAttestation
947 *
948 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
949 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +0100950 *
951 * This test is disabled because the KeyMint specification does not require that implementations
952 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
953 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +0100954 */
David Drysdale0fce69d2021-04-13 17:22:13 +0100955TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +0100956 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
957 // instance.
958 std::shared_ptr<IRemotelyProvisionedComponent> rp;
959 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
960 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
961
962 // Generate a P-256 keypair to use as an attestation key.
963 MacedPublicKey macedPubKey;
964 std::vector<uint8_t> privateKeyBlob;
965 auto status =
966 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
967 ASSERT_TRUE(status.isOk());
968 vector<uint8_t> coseKeyData;
969 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
970
971 AttestationKey attestation_key;
972 attestation_key.keyBlob = std::move(privateKeyBlob);
973 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
974
975 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
976 auto challenge = "hello";
977 auto app_id = "foo";
978
979 vector<uint8_t> key_blob;
980 vector<KeyCharacteristics> key_characteristics;
981 ASSERT_EQ(ErrorCode::OK,
982 GenerateKey(AuthorizationSetBuilder()
983 .RsaSigningKey(key_size, 65537)
984 .Digest(Digest::NONE)
985 .Padding(PaddingMode::NONE)
986 .AttestationChallenge(challenge)
987 .AttestationApplicationId(app_id)
988 .Authorization(TAG_NO_AUTH_REQUIRED)
989 .SetDefaultValidity(),
990 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
991
992 ASSERT_GT(key_blob.size(), 0U);
993 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100994 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +0100995
996 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
997
998 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
999 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1000 << "Key size " << key_size << "missing";
1001 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1002
1003 // Attestation by itself is not valid (last entry is not self-signed).
1004 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1005
1006 // The signature over the attested key should correspond to the P256 public key.
1007 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1008 ASSERT_TRUE(key_cert.get());
1009 EVP_PKEY_Ptr signing_pubkey;
1010 p256_pub_key(coseKeyData, &signing_pubkey);
1011 ASSERT_TRUE(signing_pubkey.get());
1012
1013 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1014 << "Verification of attested certificate failed "
1015 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1016
1017 CheckedDeleteKey(&key_blob);
1018 }
1019}
1020
1021/*
Selene Huang4f64c222021-04-13 19:54:36 -07001022 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1023 *
1024 * Verifies that keymint attestation for RSA encryption keys with challenge and
1025 * app id is also successful.
1026 */
1027TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1028 auto key_size = 2048;
1029 auto challenge = "hello";
1030 auto app_id = "foo";
1031
Selene Huang6e46f142021-04-20 19:20:11 -07001032 auto subject = "subj 2";
1033 vector<uint8_t> subject_der(make_name_from_str(subject));
1034
1035 uint64_t serial_int = 111166;
1036 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1037
Selene Huang4f64c222021-04-13 19:54:36 -07001038 vector<uint8_t> key_blob;
1039 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001040 ASSERT_EQ(ErrorCode::OK,
1041 GenerateKey(AuthorizationSetBuilder()
1042 .RsaEncryptionKey(key_size, 65537)
1043 .Padding(PaddingMode::NONE)
1044 .AttestationChallenge(challenge)
1045 .AttestationApplicationId(app_id)
1046 .Authorization(TAG_NO_AUTH_REQUIRED)
1047 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1048 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1049 .SetDefaultValidity(),
1050 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001051
1052 ASSERT_GT(key_blob.size(), 0U);
1053 AuthorizationSet auths;
1054 for (auto& entry : key_characteristics) {
1055 auths.push_back(AuthorizationSet(entry.authorizations));
1056 }
1057
1058 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1059 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1060
1061 // Verify that App data and ROT are NOT included.
1062 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1063 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1064
1065 // Check that some unexpected tags/values are NOT present.
1066 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1067 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1068
1069 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1070
1071 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1072 ASSERT_TRUE(os_ver);
1073 EXPECT_EQ(*os_ver, os_version());
1074
1075 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1076
1077 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1078 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1079 << "Key size " << key_size << "missing";
1080 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1081
Selene Huang6e46f142021-04-20 19:20:11 -07001082 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001083 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1084 ASSERT_GT(cert_chain_.size(), 0);
1085
1086 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1087 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1088 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1089 sw_enforced, hw_enforced, SecLevel(),
1090 cert_chain_[0].encodedCertificate));
1091
1092 CheckedDeleteKey(&key_blob);
1093}
1094
1095/*
1096 * NewKeyGenerationTest.RsaWithSelfSign
1097 *
1098 * Verifies that attesting to RSA key generation is successful, and returns
1099 * self signed certificate if no challenge is provided. And signing etc
1100 * works as expected.
1101 */
1102TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001103 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1104 vector<uint8_t> subject_der(make_name_from_str(subject));
1105
1106 uint64_t serial_int = 0;
1107 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1108
Selene Huang4f64c222021-04-13 19:54:36 -07001109 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1110 vector<uint8_t> key_blob;
1111 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001112 ASSERT_EQ(ErrorCode::OK,
1113 GenerateKey(AuthorizationSetBuilder()
1114 .RsaSigningKey(key_size, 65537)
1115 .Digest(Digest::NONE)
1116 .Padding(PaddingMode::NONE)
1117 .Authorization(TAG_NO_AUTH_REQUIRED)
1118 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1119 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1120 .SetDefaultValidity(),
1121 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001122
1123 ASSERT_GT(key_blob.size(), 0U);
1124 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001125 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001126
1127 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1128
1129 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1130 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1131 << "Key size " << key_size << "missing";
1132 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1133
Selene Huang6e46f142021-04-20 19:20:11 -07001134 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001135 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1136 ASSERT_EQ(cert_chain_.size(), 1);
1137
1138 CheckedDeleteKey(&key_blob);
1139 }
1140}
1141
1142/*
1143 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1144 *
1145 * Verifies that attesting to RSA checks for missing app ID.
1146 */
1147TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1148 auto challenge = "hello";
1149 vector<uint8_t> key_blob;
1150 vector<KeyCharacteristics> key_characteristics;
1151
1152 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1153 GenerateKey(AuthorizationSetBuilder()
1154 .RsaSigningKey(2048, 65537)
1155 .Digest(Digest::NONE)
1156 .Padding(PaddingMode::NONE)
1157 .AttestationChallenge(challenge)
1158 .Authorization(TAG_NO_AUTH_REQUIRED)
1159 .SetDefaultValidity(),
1160 &key_blob, &key_characteristics));
1161}
1162
1163/*
1164 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1165 *
1166 * Verifies that attesting to RSA ignores app id if challenge is missing.
1167 */
1168TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1169 auto key_size = 2048;
1170 auto app_id = "foo";
1171
Selene Huang6e46f142021-04-20 19:20:11 -07001172 auto subject = "cert subj 2";
1173 vector<uint8_t> subject_der(make_name_from_str(subject));
1174
1175 uint64_t serial_int = 1;
1176 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1177
Selene Huang4f64c222021-04-13 19:54:36 -07001178 vector<uint8_t> key_blob;
1179 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001180 ASSERT_EQ(ErrorCode::OK,
1181 GenerateKey(AuthorizationSetBuilder()
1182 .RsaSigningKey(key_size, 65537)
1183 .Digest(Digest::NONE)
1184 .Padding(PaddingMode::NONE)
1185 .AttestationApplicationId(app_id)
1186 .Authorization(TAG_NO_AUTH_REQUIRED)
1187 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1188 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1189 .SetDefaultValidity(),
1190 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001191
1192 ASSERT_GT(key_blob.size(), 0U);
1193 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001194 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001195
1196 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1197
1198 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1199 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1200 << "Key size " << key_size << "missing";
1201 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1202
Selene Huang6e46f142021-04-20 19:20:11 -07001203 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001204 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1205 ASSERT_EQ(cert_chain_.size(), 1);
1206
1207 CheckedDeleteKey(&key_blob);
1208}
1209
1210/*
Qi Wud22ec842020-11-26 13:27:53 +08001211 * NewKeyGenerationTest.LimitedUsageRsa
1212 *
1213 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1214 * resulting keys have correct characteristics.
1215 */
1216TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1217 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1218 vector<uint8_t> key_blob;
1219 vector<KeyCharacteristics> key_characteristics;
1220 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1221 .RsaSigningKey(key_size, 65537)
1222 .Digest(Digest::NONE)
1223 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001224 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1225 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001226 &key_blob, &key_characteristics));
1227
1228 ASSERT_GT(key_blob.size(), 0U);
1229 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001230 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001231
1232 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1233
1234 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1235 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1236 << "Key size " << key_size << "missing";
1237 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1238
1239 // Check the usage count limit tag appears in the authorizations.
1240 AuthorizationSet auths;
1241 for (auto& entry : key_characteristics) {
1242 auths.push_back(AuthorizationSet(entry.authorizations));
1243 }
1244 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1245 << "key usage count limit " << 1U << " missing";
1246
1247 CheckedDeleteKey(&key_blob);
1248 }
1249}
1250
1251/*
Qi Wubeefae42021-01-28 23:16:37 +08001252 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1253 *
1254 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1255 * resulting keys have correct characteristics and attestation.
1256 */
1257TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001258 auto challenge = "hello";
1259 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001260
Selene Huang6e46f142021-04-20 19:20:11 -07001261 auto subject = "cert subj 2";
1262 vector<uint8_t> subject_der(make_name_from_str(subject));
1263
1264 uint64_t serial_int = 66;
1265 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1266
Selene Huang4f64c222021-04-13 19:54:36 -07001267 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001268 vector<uint8_t> key_blob;
1269 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001270 ASSERT_EQ(ErrorCode::OK,
1271 GenerateKey(AuthorizationSetBuilder()
1272 .RsaSigningKey(key_size, 65537)
1273 .Digest(Digest::NONE)
1274 .Padding(PaddingMode::NONE)
1275 .AttestationChallenge(challenge)
1276 .AttestationApplicationId(app_id)
1277 .Authorization(TAG_NO_AUTH_REQUIRED)
1278 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1279 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1280 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1281 .SetDefaultValidity(),
1282 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001283
1284 ASSERT_GT(key_blob.size(), 0U);
1285 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001286 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001287
1288 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1289
1290 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1291 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1292 << "Key size " << key_size << "missing";
1293 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1294
1295 // Check the usage count limit tag appears in the authorizations.
1296 AuthorizationSet auths;
1297 for (auto& entry : key_characteristics) {
1298 auths.push_back(AuthorizationSet(entry.authorizations));
1299 }
1300 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1301 << "key usage count limit " << 1U << " missing";
1302
1303 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001304 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001305 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001306 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001307
1308 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1309 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1310 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1311 sw_enforced, hw_enforced, SecLevel(),
1312 cert_chain_[0].encodedCertificate));
1313
1314 CheckedDeleteKey(&key_blob);
1315 }
1316}
1317
1318/*
Selene Huang31ab4042020-04-29 04:22:39 -07001319 * NewKeyGenerationTest.NoInvalidRsaSizes
1320 *
1321 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1322 */
1323TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1324 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1325 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001326 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001327 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1328 GenerateKey(AuthorizationSetBuilder()
1329 .RsaSigningKey(key_size, 65537)
1330 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001331 .Padding(PaddingMode::NONE)
1332 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001333 &key_blob, &key_characteristics));
1334 }
1335}
1336
1337/*
1338 * NewKeyGenerationTest.RsaNoDefaultSize
1339 *
1340 * Verifies that failing to specify a key size for RSA key generation returns
1341 * UNSUPPORTED_KEY_SIZE.
1342 */
1343TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1344 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1345 GenerateKey(AuthorizationSetBuilder()
1346 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1347 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001348 .SigningKey()
1349 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001350}
1351
1352/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001353 * NewKeyGenerationTest.RsaMissingParams
1354 *
1355 * Verifies that omitting optional tags works.
1356 */
1357TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1358 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1359 ASSERT_EQ(ErrorCode::OK,
1360 GenerateKey(
1361 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1362 CheckedDeleteKey();
1363 }
1364}
1365
1366/*
Selene Huang31ab4042020-04-29 04:22:39 -07001367 * NewKeyGenerationTest.Ecdsa
1368 *
1369 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1370 * have correct characteristics.
1371 */
1372TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001373 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001374 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001375 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001376 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001377 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001378 .Digest(Digest::NONE)
1379 .SetDefaultValidity(),
1380 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001381 ASSERT_GT(key_blob.size(), 0U);
1382 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001383 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001384
Shawn Willden7f424372021-01-10 18:06:50 -07001385 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001386
1387 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001388 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001389
1390 CheckedDeleteKey(&key_blob);
1391 }
1392}
1393
1394/*
Selene Huang4f64c222021-04-13 19:54:36 -07001395 * NewKeyGenerationTest.EcdsaAttestation
1396 *
1397 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1398 * an attestation will be generated.
1399 */
1400TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1401 auto challenge = "hello";
1402 auto app_id = "foo";
1403
Selene Huang6e46f142021-04-20 19:20:11 -07001404 auto subject = "cert subj 2";
1405 vector<uint8_t> subject_der(make_name_from_str(subject));
1406
1407 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1408 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1409
David Drysdaledf09e542021-06-08 15:46:11 +01001410 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001411 vector<uint8_t> key_blob;
1412 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001413 ASSERT_EQ(ErrorCode::OK,
1414 GenerateKey(AuthorizationSetBuilder()
1415 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001416 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001417 .Digest(Digest::NONE)
1418 .AttestationChallenge(challenge)
1419 .AttestationApplicationId(app_id)
1420 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1421 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1422 .SetDefaultValidity(),
1423 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001424 ASSERT_GT(key_blob.size(), 0U);
1425 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001426 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001427
1428 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1429
1430 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001431 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001432
1433 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1434 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001435 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001436
1437 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1438 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1439 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1440 sw_enforced, hw_enforced, SecLevel(),
1441 cert_chain_[0].encodedCertificate));
1442
1443 CheckedDeleteKey(&key_blob);
1444 }
1445}
1446
1447/*
David Drysdale37af4b32021-05-14 16:46:59 +01001448 * NewKeyGenerationTest.EcdsaAttestationTags
1449 *
1450 * Verifies that creation of an attested ECDSA key includes various tags in the
1451 * attestation extension.
1452 */
1453TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1454 auto challenge = "hello";
1455 auto app_id = "foo";
1456 auto subject = "cert subj 2";
1457 vector<uint8_t> subject_der(make_name_from_str(subject));
1458 uint64_t serial_int = 0x1010;
1459 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1460 const AuthorizationSetBuilder base_builder =
1461 AuthorizationSetBuilder()
1462 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001463 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001464 .Digest(Digest::NONE)
1465 .AttestationChallenge(challenge)
1466 .AttestationApplicationId(app_id)
1467 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1468 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1469 .SetDefaultValidity();
1470
1471 // Various tags that map to fields in the attestation extension ASN.1 schema.
1472 auto extra_tags = AuthorizationSetBuilder()
1473 .Authorization(TAG_ROLLBACK_RESISTANCE)
1474 .Authorization(TAG_EARLY_BOOT_ONLY)
1475 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1476 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1477 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1478 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1479 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1480 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1481 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1482 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1483 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1484 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001485
David Drysdale37af4b32021-05-14 16:46:59 +01001486 for (const KeyParameter& tag : extra_tags) {
1487 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1488 vector<uint8_t> key_blob;
1489 vector<KeyCharacteristics> key_characteristics;
1490 AuthorizationSetBuilder builder = base_builder;
1491 builder.push_back(tag);
1492 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1493 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1494 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1495 continue;
1496 }
Seth Mooreb393b082021-07-12 14:18:28 -07001497 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1498 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001499 continue;
1500 }
1501 ASSERT_EQ(result, ErrorCode::OK);
1502 ASSERT_GT(key_blob.size(), 0U);
1503
1504 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1505 ASSERT_GT(cert_chain_.size(), 0);
1506 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1507
1508 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1509 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001510 // Some tags are optional, so don't require them to be in the enforcements.
1511 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001512 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1513 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1514 }
1515
1516 // Verifying the attestation record will check for the specific tag because
1517 // it's included in the authorizations.
1518 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1519 SecLevel(), cert_chain_[0].encodedCertificate));
1520
1521 CheckedDeleteKey(&key_blob);
1522 }
1523
David Drysdalec53b7d92021-10-11 12:35:58 +01001524 // Collection of invalid attestation ID tags.
1525 auto invalid_tags =
1526 AuthorizationSetBuilder()
1527 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1528 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1529 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1530 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1531 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1532 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1533 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1534 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001535 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001536 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001537 vector<uint8_t> key_blob;
1538 vector<KeyCharacteristics> key_characteristics;
1539 AuthorizationSetBuilder builder =
1540 AuthorizationSetBuilder()
1541 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001542 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001543 .Digest(Digest::NONE)
1544 .AttestationChallenge(challenge)
1545 .AttestationApplicationId(app_id)
1546 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1547 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1548 .SetDefaultValidity();
1549 builder.push_back(tag);
1550 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1551 GenerateKey(builder, &key_blob, &key_characteristics));
1552 }
1553}
1554
1555/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001556 * NewKeyGenerationTest.EcdsaAttestationIdTags
1557 *
1558 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1559 * attestation extension.
1560 */
1561TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
1562 auto challenge = "hello";
1563 auto app_id = "foo";
1564 auto subject = "cert subj 2";
1565 vector<uint8_t> subject_der(make_name_from_str(subject));
1566 uint64_t serial_int = 0x1010;
1567 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1568 const AuthorizationSetBuilder base_builder =
1569 AuthorizationSetBuilder()
1570 .Authorization(TAG_NO_AUTH_REQUIRED)
1571 .EcdsaSigningKey(EcCurve::P_256)
1572 .Digest(Digest::NONE)
1573 .AttestationChallenge(challenge)
1574 .AttestationApplicationId(app_id)
1575 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1576 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1577 .SetDefaultValidity();
1578
1579 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1580 auto extra_tags = AuthorizationSetBuilder();
1581 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1582 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1583 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1584 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1585 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1586 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1587
1588 for (const KeyParameter& tag : extra_tags) {
1589 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1590 vector<uint8_t> key_blob;
1591 vector<KeyCharacteristics> key_characteristics;
1592 AuthorizationSetBuilder builder = base_builder;
1593 builder.push_back(tag);
1594 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1595 if (result == ErrorCode::CANNOT_ATTEST_IDS) {
1596 // Device ID attestation is optional; KeyMint may not support it at all.
1597 continue;
1598 }
1599 ASSERT_EQ(result, ErrorCode::OK);
1600 ASSERT_GT(key_blob.size(), 0U);
1601
1602 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1603 ASSERT_GT(cert_chain_.size(), 0);
1604 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1605
1606 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1607 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1608
1609 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
1610 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
1611 // attestation extension should contain them, so make sure the extra tag is added.
1612 hw_enforced.push_back(tag);
1613
1614 // Verifying the attestation record will check for the specific tag because
1615 // it's included in the authorizations.
1616 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1617 SecLevel(), cert_chain_[0].encodedCertificate));
1618
1619 CheckedDeleteKey(&key_blob);
1620 }
1621}
1622
1623/*
David Drysdale37af4b32021-05-14 16:46:59 +01001624 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1625 *
1626 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1627 */
1628TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1629 auto challenge = "hello";
1630 auto attest_app_id = "foo";
1631 auto subject = "cert subj 2";
1632 vector<uint8_t> subject_der(make_name_from_str(subject));
1633 uint64_t serial_int = 0x1010;
1634 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1635
1636 // Earlier versions of the attestation extension schema included a slot:
1637 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1638 // This should never have been included, and should never be filled in.
1639 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1640 // to confirm that this field never makes it into the attestation extension.
1641 vector<uint8_t> key_blob;
1642 vector<KeyCharacteristics> key_characteristics;
1643 auto result = GenerateKey(AuthorizationSetBuilder()
1644 .Authorization(TAG_NO_AUTH_REQUIRED)
1645 .EcdsaSigningKey(EcCurve::P_256)
1646 .Digest(Digest::NONE)
1647 .AttestationChallenge(challenge)
1648 .AttestationApplicationId(attest_app_id)
1649 .Authorization(TAG_APPLICATION_ID, "client_id")
1650 .Authorization(TAG_APPLICATION_DATA, "appdata")
1651 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1652 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1653 .SetDefaultValidity(),
1654 &key_blob, &key_characteristics);
1655 ASSERT_EQ(result, ErrorCode::OK);
1656 ASSERT_GT(key_blob.size(), 0U);
1657
1658 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1659 ASSERT_GT(cert_chain_.size(), 0);
1660 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1661
1662 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1663 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1664 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1665 SecLevel(), cert_chain_[0].encodedCertificate));
1666
1667 // Check that the app id is not in the cert.
1668 string app_id = "clientid";
1669 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1670 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1671 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1672 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1673 cert_chain_[0].encodedCertificate.end());
1674
1675 CheckedDeleteKey(&key_blob);
1676}
1677
1678/*
Selene Huang4f64c222021-04-13 19:54:36 -07001679 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1680 *
1681 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1682 * the key will generate a self signed attestation.
1683 */
1684TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001685 auto subject = "cert subj 2";
1686 vector<uint8_t> subject_der(make_name_from_str(subject));
1687
1688 uint64_t serial_int = 0x123456FFF1234;
1689 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1690
David Drysdaledf09e542021-06-08 15:46:11 +01001691 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001692 vector<uint8_t> key_blob;
1693 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001694 ASSERT_EQ(ErrorCode::OK,
1695 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001696 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001697 .Digest(Digest::NONE)
1698 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1699 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1700 .SetDefaultValidity(),
1701 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001702 ASSERT_GT(key_blob.size(), 0U);
1703 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001704 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001705
1706 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1707
1708 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001709 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001710
1711 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001712 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001713 ASSERT_EQ(cert_chain_.size(), 1);
1714
1715 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1716 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1717
1718 CheckedDeleteKey(&key_blob);
1719 }
1720}
1721
1722/*
1723 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1724 *
1725 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1726 * app id must also be provided or else it will fail.
1727 */
1728TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1729 auto challenge = "hello";
1730 vector<uint8_t> key_blob;
1731 vector<KeyCharacteristics> key_characteristics;
1732
1733 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1734 GenerateKey(AuthorizationSetBuilder()
1735 .EcdsaSigningKey(EcCurve::P_256)
1736 .Digest(Digest::NONE)
1737 .AttestationChallenge(challenge)
1738 .SetDefaultValidity(),
1739 &key_blob, &key_characteristics));
1740}
1741
1742/*
1743 * NewKeyGenerationTest.EcdsaIgnoreAppId
1744 *
1745 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1746 * any appid will be ignored, and keymint will generate a self sign certificate.
1747 */
1748TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1749 auto app_id = "foo";
1750
David Drysdaledf09e542021-06-08 15:46:11 +01001751 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001752 vector<uint8_t> key_blob;
1753 vector<KeyCharacteristics> key_characteristics;
1754 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001755 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001756 .Digest(Digest::NONE)
1757 .AttestationApplicationId(app_id)
1758 .SetDefaultValidity(),
1759 &key_blob, &key_characteristics));
1760
1761 ASSERT_GT(key_blob.size(), 0U);
1762 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001763 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001764
1765 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1766
1767 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001768 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001769
1770 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1771 ASSERT_EQ(cert_chain_.size(), 1);
1772
1773 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1774 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1775
1776 CheckedDeleteKey(&key_blob);
1777 }
1778}
1779
1780/*
1781 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1782 *
1783 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1784 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1785 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1786 * to specify how many following bytes will be used to encode the length.
1787 */
1788TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1789 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001790 std::vector<uint32_t> app_id_lengths{143, 258};
1791
1792 for (uint32_t length : app_id_lengths) {
1793 const string app_id(length, 'a');
1794 vector<uint8_t> key_blob;
1795 vector<KeyCharacteristics> key_characteristics;
1796 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1797 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001798 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001799 .Digest(Digest::NONE)
1800 .AttestationChallenge(challenge)
1801 .AttestationApplicationId(app_id)
1802 .SetDefaultValidity(),
1803 &key_blob, &key_characteristics));
1804 ASSERT_GT(key_blob.size(), 0U);
1805 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001806 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001807
1808 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1809
1810 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001811 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001812
1813 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1814 ASSERT_GT(cert_chain_.size(), 0);
1815
1816 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1817 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1818 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1819 sw_enforced, hw_enforced, SecLevel(),
1820 cert_chain_[0].encodedCertificate));
1821
1822 CheckedDeleteKey(&key_blob);
1823 }
1824}
1825
1826/*
Qi Wud22ec842020-11-26 13:27:53 +08001827 * NewKeyGenerationTest.LimitedUsageEcdsa
1828 *
1829 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1830 * resulting keys have correct characteristics.
1831 */
1832TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001833 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001834 vector<uint8_t> key_blob;
1835 vector<KeyCharacteristics> key_characteristics;
1836 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001837 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001838 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001839 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1840 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001841 &key_blob, &key_characteristics));
1842
1843 ASSERT_GT(key_blob.size(), 0U);
1844 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001845 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001846
1847 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1848
1849 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001850 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001851
1852 // Check the usage count limit tag appears in the authorizations.
1853 AuthorizationSet auths;
1854 for (auto& entry : key_characteristics) {
1855 auths.push_back(AuthorizationSet(entry.authorizations));
1856 }
1857 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1858 << "key usage count limit " << 1U << " missing";
1859
1860 CheckedDeleteKey(&key_blob);
1861 }
1862}
1863
1864/*
Selene Huang31ab4042020-04-29 04:22:39 -07001865 * NewKeyGenerationTest.EcdsaDefaultSize
1866 *
David Drysdaledf09e542021-06-08 15:46:11 +01001867 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001868 * UNSUPPORTED_KEY_SIZE.
1869 */
1870TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1871 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1872 GenerateKey(AuthorizationSetBuilder()
1873 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1874 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001875 .Digest(Digest::NONE)
1876 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001877}
1878
1879/*
1880 * NewKeyGenerationTest.EcdsaInvalidSize
1881 *
1882 * Verifies that specifying an invalid key size for EC key generation returns
1883 * UNSUPPORTED_KEY_SIZE.
1884 */
1885TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdaledf09e542021-06-08 15:46:11 +01001886 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001887 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001888 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001889 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001890 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001891 .Digest(Digest::NONE)
1892 .SetDefaultValidity(),
1893 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001894 }
1895
David Drysdaledf09e542021-06-08 15:46:11 +01001896 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1897 GenerateKey(AuthorizationSetBuilder()
1898 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1899 .Authorization(TAG_KEY_SIZE, 190)
1900 .SigningKey()
1901 .Digest(Digest::NONE)
1902 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001903}
1904
1905/*
1906 * NewKeyGenerationTest.EcdsaMismatchKeySize
1907 *
1908 * Verifies that specifying mismatched key size and curve for EC key generation returns
1909 * INVALID_ARGUMENT.
1910 */
1911TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1912 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1913
David Drysdaledf09e542021-06-08 15:46:11 +01001914 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01001915 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01001916 .Authorization(TAG_KEY_SIZE, 224)
1917 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01001918 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01001919 .Digest(Digest::NONE)
1920 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01001921 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07001922}
1923
1924/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001925 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001926 *
1927 * Verifies that keymint does not support any curve designated as unsupported.
1928 */
1929TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1930 Digest digest;
1931 if (SecLevel() == SecurityLevel::STRONGBOX) {
1932 digest = Digest::SHA_2_256;
1933 } else {
1934 digest = Digest::SHA_2_512;
1935 }
1936 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001937 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1938 .EcdsaSigningKey(curve)
1939 .Digest(digest)
1940 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001941 << "Failed to generate key on curve: " << curve;
1942 CheckedDeleteKey();
1943 }
1944}
1945
1946/*
1947 * NewKeyGenerationTest.Hmac
1948 *
1949 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1950 * characteristics.
1951 */
1952TEST_P(NewKeyGenerationTest, Hmac) {
1953 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1954 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001955 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001956 constexpr size_t key_size = 128;
1957 ASSERT_EQ(ErrorCode::OK,
1958 GenerateKey(
1959 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1960 TAG_MIN_MAC_LENGTH, 128),
1961 &key_blob, &key_characteristics));
1962
1963 ASSERT_GT(key_blob.size(), 0U);
1964 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001965 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001966
Shawn Willden7f424372021-01-10 18:06:50 -07001967 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1968 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1969 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1970 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001971
1972 CheckedDeleteKey(&key_blob);
1973 }
1974}
1975
1976/*
Selene Huang4f64c222021-04-13 19:54:36 -07001977 * NewKeyGenerationTest.HmacNoAttestation
1978 *
1979 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1980 * and app id are provided.
1981 */
1982TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1983 auto challenge = "hello";
1984 auto app_id = "foo";
1985
1986 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1987 vector<uint8_t> key_blob;
1988 vector<KeyCharacteristics> key_characteristics;
1989 constexpr size_t key_size = 128;
1990 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1991 .HmacKey(key_size)
1992 .Digest(digest)
1993 .AttestationChallenge(challenge)
1994 .AttestationApplicationId(app_id)
1995 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1996 &key_blob, &key_characteristics));
1997
1998 ASSERT_GT(key_blob.size(), 0U);
1999 ASSERT_EQ(cert_chain_.size(), 0);
2000 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002001 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002002
2003 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2004 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2005 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2006 << "Key size " << key_size << "missing";
2007
2008 CheckedDeleteKey(&key_blob);
2009 }
2010}
2011
2012/*
Qi Wud22ec842020-11-26 13:27:53 +08002013 * NewKeyGenerationTest.LimitedUsageHmac
2014 *
2015 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2016 * resulting keys have correct characteristics.
2017 */
2018TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2019 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2020 vector<uint8_t> key_blob;
2021 vector<KeyCharacteristics> key_characteristics;
2022 constexpr size_t key_size = 128;
2023 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2024 .HmacKey(key_size)
2025 .Digest(digest)
2026 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2027 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2028 &key_blob, &key_characteristics));
2029
2030 ASSERT_GT(key_blob.size(), 0U);
2031 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002032 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002033
2034 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2035 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2036 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2037 << "Key size " << key_size << "missing";
2038
2039 // Check the usage count limit tag appears in the authorizations.
2040 AuthorizationSet auths;
2041 for (auto& entry : key_characteristics) {
2042 auths.push_back(AuthorizationSet(entry.authorizations));
2043 }
2044 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2045 << "key usage count limit " << 1U << " missing";
2046
2047 CheckedDeleteKey(&key_blob);
2048 }
2049}
2050
2051/*
Selene Huang31ab4042020-04-29 04:22:39 -07002052 * NewKeyGenerationTest.HmacCheckKeySizes
2053 *
2054 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2055 */
2056TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2057 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2058 if (key_size < 64 || key_size % 8 != 0) {
2059 // To keep this test from being very slow, we only test a random fraction of
2060 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2061 // them, we expect to run ~40 of them in each run.
2062 if (key_size % 8 == 0 || random() % 10 == 0) {
2063 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2064 GenerateKey(AuthorizationSetBuilder()
2065 .HmacKey(key_size)
2066 .Digest(Digest::SHA_2_256)
2067 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2068 << "HMAC key size " << key_size << " invalid";
2069 }
2070 } else {
2071 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2072 .HmacKey(key_size)
2073 .Digest(Digest::SHA_2_256)
2074 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2075 << "Failed to generate HMAC key of size " << key_size;
2076 CheckedDeleteKey();
2077 }
2078 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002079 if (SecLevel() == SecurityLevel::STRONGBOX) {
2080 // STRONGBOX devices must not support keys larger than 512 bits.
2081 size_t key_size = 520;
2082 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2083 GenerateKey(AuthorizationSetBuilder()
2084 .HmacKey(key_size)
2085 .Digest(Digest::SHA_2_256)
2086 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2087 << "HMAC key size " << key_size << " unexpectedly valid";
2088 }
Selene Huang31ab4042020-04-29 04:22:39 -07002089}
2090
2091/*
2092 * NewKeyGenerationTest.HmacCheckMinMacLengths
2093 *
2094 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2095 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2096 * specific MAC length that failed, so reproducing a failed run will be easy.
2097 */
2098TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2099 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2100 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2101 // To keep this test from being very long, we only test a random fraction of
2102 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2103 // we expect to run ~17 of them in each run.
2104 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2105 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2106 GenerateKey(AuthorizationSetBuilder()
2107 .HmacKey(128)
2108 .Digest(Digest::SHA_2_256)
2109 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2110 << "HMAC min mac length " << min_mac_length << " invalid.";
2111 }
2112 } else {
2113 EXPECT_EQ(ErrorCode::OK,
2114 GenerateKey(AuthorizationSetBuilder()
2115 .HmacKey(128)
2116 .Digest(Digest::SHA_2_256)
2117 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2118 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2119 CheckedDeleteKey();
2120 }
2121 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002122
2123 // Minimum MAC length must be no more than 512 bits.
2124 size_t min_mac_length = 520;
2125 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2126 GenerateKey(AuthorizationSetBuilder()
2127 .HmacKey(128)
2128 .Digest(Digest::SHA_2_256)
2129 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2130 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002131}
2132
2133/*
2134 * NewKeyGenerationTest.HmacMultipleDigests
2135 *
2136 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2137 */
2138TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
2139 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2140
2141 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2142 GenerateKey(AuthorizationSetBuilder()
2143 .HmacKey(128)
2144 .Digest(Digest::SHA1)
2145 .Digest(Digest::SHA_2_256)
2146 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2147}
2148
2149/*
2150 * NewKeyGenerationTest.HmacDigestNone
2151 *
2152 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2153 */
2154TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2155 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2156 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2157 128)));
2158
2159 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2160 GenerateKey(AuthorizationSetBuilder()
2161 .HmacKey(128)
2162 .Digest(Digest::NONE)
2163 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2164}
2165
Selene Huang4f64c222021-04-13 19:54:36 -07002166/*
2167 * NewKeyGenerationTest.AesNoAttestation
2168 *
2169 * Verifies that attestation parameters to AES keys are ignored and generateKey
2170 * will succeed.
2171 */
2172TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2173 auto challenge = "hello";
2174 auto app_id = "foo";
2175
2176 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2177 .Authorization(TAG_NO_AUTH_REQUIRED)
2178 .AesEncryptionKey(128)
2179 .EcbMode()
2180 .Padding(PaddingMode::PKCS7)
2181 .AttestationChallenge(challenge)
2182 .AttestationApplicationId(app_id)));
2183
2184 ASSERT_EQ(cert_chain_.size(), 0);
2185}
2186
2187/*
2188 * NewKeyGenerationTest.TripleDesNoAttestation
2189 *
2190 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2191 * will be successful. No attestation should be generated.
2192 */
2193TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2194 auto challenge = "hello";
2195 auto app_id = "foo";
2196
2197 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2198 .TripleDesEncryptionKey(168)
2199 .BlockMode(BlockMode::ECB)
2200 .Authorization(TAG_NO_AUTH_REQUIRED)
2201 .Padding(PaddingMode::NONE)
2202 .AttestationChallenge(challenge)
2203 .AttestationApplicationId(app_id)));
2204 ASSERT_EQ(cert_chain_.size(), 0);
2205}
2206
Selene Huang31ab4042020-04-29 04:22:39 -07002207INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2208
2209typedef KeyMintAidlTestBase SigningOperationsTest;
2210
2211/*
2212 * SigningOperationsTest.RsaSuccess
2213 *
2214 * Verifies that raw RSA signature operations succeed.
2215 */
2216TEST_P(SigningOperationsTest, RsaSuccess) {
2217 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2218 .RsaSigningKey(2048, 65537)
2219 .Digest(Digest::NONE)
2220 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002221 .Authorization(TAG_NO_AUTH_REQUIRED)
2222 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002223 string message = "12345678901234567890123456789012";
2224 string signature = SignMessage(
2225 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002226 LocalVerifyMessage(message, signature,
2227 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2228}
2229
2230/*
2231 * SigningOperationsTest.RsaAllPaddingsAndDigests
2232 *
2233 * Verifies RSA signature/verification for all padding modes and digests.
2234 */
2235TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2236 auto authorizations = AuthorizationSetBuilder()
2237 .Authorization(TAG_NO_AUTH_REQUIRED)
2238 .RsaSigningKey(2048, 65537)
2239 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2240 .Padding(PaddingMode::NONE)
2241 .Padding(PaddingMode::RSA_PSS)
2242 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2243 .SetDefaultValidity();
2244
2245 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2246
2247 string message(128, 'a');
2248 string corrupt_message(message);
2249 ++corrupt_message[corrupt_message.size() / 2];
2250
2251 for (auto padding :
2252 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2253 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2254 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2255 // Digesting only makes sense with padding.
2256 continue;
2257 }
2258
2259 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2260 // PSS requires digesting.
2261 continue;
2262 }
2263
2264 string signature =
2265 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2266 LocalVerifyMessage(message, signature,
2267 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2268 }
2269 }
Selene Huang31ab4042020-04-29 04:22:39 -07002270}
2271
2272/*
2273 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2274 *
Shawn Willden7f424372021-01-10 18:06:50 -07002275 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002276 */
2277TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2278 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2279 .Authorization(TAG_NO_AUTH_REQUIRED)
2280 .RsaSigningKey(2048, 65537)
2281 .Digest(Digest::NONE)
2282 .Padding(PaddingMode::NONE)
2283 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002284 .Authorization(TAG_APPLICATION_DATA, "appdata")
2285 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002286
2287 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2288
Selene Huang31ab4042020-04-29 04:22:39 -07002289 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2290 Begin(KeyPurpose::SIGN,
2291 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2292 AbortIfNeeded();
2293 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2294 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2295 .Digest(Digest::NONE)
2296 .Padding(PaddingMode::NONE)
2297 .Authorization(TAG_APPLICATION_ID, "clientid")));
2298 AbortIfNeeded();
2299 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2300 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2301 .Digest(Digest::NONE)
2302 .Padding(PaddingMode::NONE)
2303 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2304 AbortIfNeeded();
2305 EXPECT_EQ(ErrorCode::OK,
2306 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2307 .Digest(Digest::NONE)
2308 .Padding(PaddingMode::NONE)
2309 .Authorization(TAG_APPLICATION_DATA, "appdata")
2310 .Authorization(TAG_APPLICATION_ID, "clientid")));
2311 AbortIfNeeded();
2312}
2313
2314/*
2315 * SigningOperationsTest.RsaPssSha256Success
2316 *
2317 * Verifies that RSA-PSS signature operations succeed.
2318 */
2319TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2320 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2321 .RsaSigningKey(2048, 65537)
2322 .Digest(Digest::SHA_2_256)
2323 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002324 .Authorization(TAG_NO_AUTH_REQUIRED)
2325 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002326 // Use large message, which won't work without digesting.
2327 string message(1024, 'a');
2328 string signature = SignMessage(
2329 message,
2330 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2331}
2332
2333/*
2334 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2335 *
2336 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2337 * supports only unpadded operations.
2338 */
2339TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2340 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2341 .RsaSigningKey(2048, 65537)
2342 .Digest(Digest::NONE)
2343 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002344 .Padding(PaddingMode::NONE)
2345 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002346 string message = "12345678901234567890123456789012";
2347 string signature;
2348
2349 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2350 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2351 .Digest(Digest::NONE)
2352 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2353}
2354
2355/*
2356 * SigningOperationsTest.NoUserConfirmation
2357 *
2358 * Verifies that keymint rejects signing operations for keys with
2359 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2360 * presented.
2361 */
2362TEST_P(SigningOperationsTest, NoUserConfirmation) {
2363 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002364 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2365 .RsaSigningKey(1024, 65537)
2366 .Digest(Digest::NONE)
2367 .Padding(PaddingMode::NONE)
2368 .Authorization(TAG_NO_AUTH_REQUIRED)
2369 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2370 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002371
2372 const string message = "12345678901234567890123456789012";
2373 EXPECT_EQ(ErrorCode::OK,
2374 Begin(KeyPurpose::SIGN,
2375 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2376 string signature;
2377 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2378}
2379
2380/*
2381 * SigningOperationsTest.RsaPkcs1Sha256Success
2382 *
2383 * Verifies that digested RSA-PKCS1 signature operations succeed.
2384 */
2385TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2386 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2387 .RsaSigningKey(2048, 65537)
2388 .Digest(Digest::SHA_2_256)
2389 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002390 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2391 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002392 string message(1024, 'a');
2393 string signature = SignMessage(message, AuthorizationSetBuilder()
2394 .Digest(Digest::SHA_2_256)
2395 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2396}
2397
2398/*
2399 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2400 *
2401 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2402 */
2403TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2404 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2405 .RsaSigningKey(2048, 65537)
2406 .Digest(Digest::NONE)
2407 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002408 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2409 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002410 string message(53, 'a');
2411 string signature = SignMessage(message, AuthorizationSetBuilder()
2412 .Digest(Digest::NONE)
2413 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2414}
2415
2416/*
2417 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2418 *
2419 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2420 * given a too-long message.
2421 */
2422TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2423 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2424 .RsaSigningKey(2048, 65537)
2425 .Digest(Digest::NONE)
2426 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002427 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2428 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002429 string message(257, 'a');
2430
2431 EXPECT_EQ(ErrorCode::OK,
2432 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2433 .Digest(Digest::NONE)
2434 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2435 string signature;
2436 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2437}
2438
2439/*
2440 * SigningOperationsTest.RsaPssSha512TooSmallKey
2441 *
2442 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2443 * used with a key that is too small for the message.
2444 *
2445 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2446 * keymint specification requires that salt_size == digest_size, so the message will be
2447 * digest_size * 2 +
2448 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2449 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2450 * for a 1024-bit key.
2451 */
2452TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2453 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2454 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2455 .RsaSigningKey(1024, 65537)
2456 .Digest(Digest::SHA_2_512)
2457 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002458 .Padding(PaddingMode::RSA_PSS)
2459 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002460 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2461 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2462 .Digest(Digest::SHA_2_512)
2463 .Padding(PaddingMode::RSA_PSS)));
2464}
2465
2466/*
2467 * SigningOperationsTest.RsaNoPaddingTooLong
2468 *
2469 * Verifies that raw RSA signature operations fail with the correct error code when
2470 * given a too-long message.
2471 */
2472TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2473 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2474 .RsaSigningKey(2048, 65537)
2475 .Digest(Digest::NONE)
2476 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002477 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2478 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002479 // One byte too long
2480 string message(2048 / 8 + 1, 'a');
2481 ASSERT_EQ(ErrorCode::OK,
2482 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2483 .Digest(Digest::NONE)
2484 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2485 string result;
2486 ErrorCode finish_error_code = Finish(message, &result);
2487 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2488 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2489
2490 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2491 message = string(128 * 1024, 'a');
2492 ASSERT_EQ(ErrorCode::OK,
2493 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2494 .Digest(Digest::NONE)
2495 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2496 finish_error_code = Finish(message, &result);
2497 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2498 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2499}
2500
2501/*
2502 * SigningOperationsTest.RsaAbort
2503 *
2504 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2505 * test, but the behavior should be algorithm and purpose-independent.
2506 */
2507TEST_P(SigningOperationsTest, RsaAbort) {
2508 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2509 .RsaSigningKey(2048, 65537)
2510 .Digest(Digest::NONE)
2511 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002512 .Padding(PaddingMode::NONE)
2513 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002514
2515 ASSERT_EQ(ErrorCode::OK,
2516 Begin(KeyPurpose::SIGN,
2517 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2518 EXPECT_EQ(ErrorCode::OK, Abort());
2519
2520 // Another abort should fail
2521 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2522
2523 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002524 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002525}
2526
2527/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002528 * SigningOperationsTest.RsaNonUniqueParams
2529 *
2530 * Verifies that an operation with multiple padding modes is rejected.
2531 */
2532TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2533 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2534 .RsaSigningKey(2048, 65537)
2535 .Digest(Digest::NONE)
2536 .Digest(Digest::SHA1)
2537 .Authorization(TAG_NO_AUTH_REQUIRED)
2538 .Padding(PaddingMode::NONE)
2539 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2540 .SetDefaultValidity()));
2541
2542 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2543 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2544 .Digest(Digest::NONE)
2545 .Padding(PaddingMode::NONE)
2546 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2547
Tommy Chiuc93c4392021-05-11 18:36:50 +08002548 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2549 .Digest(Digest::NONE)
2550 .Digest(Digest::SHA1)
2551 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2552 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002553
2554 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2555 Begin(KeyPurpose::SIGN,
2556 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2557}
2558
2559/*
Selene Huang31ab4042020-04-29 04:22:39 -07002560 * SigningOperationsTest.RsaUnsupportedPadding
2561 *
2562 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2563 * with a padding mode inappropriate for RSA.
2564 */
2565TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2566 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2567 .RsaSigningKey(2048, 65537)
2568 .Authorization(TAG_NO_AUTH_REQUIRED)
2569 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002570 .Padding(PaddingMode::PKCS7)
2571 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002572 ASSERT_EQ(
2573 ErrorCode::UNSUPPORTED_PADDING_MODE,
2574 Begin(KeyPurpose::SIGN,
2575 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002576 CheckedDeleteKey();
2577
2578 ASSERT_EQ(ErrorCode::OK,
2579 GenerateKey(
2580 AuthorizationSetBuilder()
2581 .RsaSigningKey(2048, 65537)
2582 .Authorization(TAG_NO_AUTH_REQUIRED)
2583 .Digest(Digest::SHA_2_256 /* supported digest */)
2584 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2585 .SetDefaultValidity()));
2586 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2587 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2588 .Digest(Digest::SHA_2_256)
2589 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002590}
2591
2592/*
2593 * SigningOperationsTest.RsaPssNoDigest
2594 *
2595 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2596 */
2597TEST_P(SigningOperationsTest, RsaNoDigest) {
2598 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2599 .RsaSigningKey(2048, 65537)
2600 .Authorization(TAG_NO_AUTH_REQUIRED)
2601 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002602 .Padding(PaddingMode::RSA_PSS)
2603 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002604 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2605 Begin(KeyPurpose::SIGN,
2606 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2607
2608 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2609 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2610}
2611
2612/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002613 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002614 *
2615 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2616 * supported in some cases (as validated in other tests), but a mode must be specified.
2617 */
2618TEST_P(SigningOperationsTest, RsaNoPadding) {
2619 // Padding must be specified
2620 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2621 .RsaKey(2048, 65537)
2622 .Authorization(TAG_NO_AUTH_REQUIRED)
2623 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002624 .Digest(Digest::NONE)
2625 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002626 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2627 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2628}
2629
2630/*
2631 * SigningOperationsTest.RsaShortMessage
2632 *
2633 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2634 */
2635TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2636 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2637 .Authorization(TAG_NO_AUTH_REQUIRED)
2638 .RsaSigningKey(2048, 65537)
2639 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002640 .Padding(PaddingMode::NONE)
2641 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002642
2643 // Barely shorter
2644 string message(2048 / 8 - 1, 'a');
2645 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2646
2647 // Much shorter
2648 message = "a";
2649 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2650}
2651
2652/*
2653 * SigningOperationsTest.RsaSignWithEncryptionKey
2654 *
2655 * Verifies that RSA encryption keys cannot be used to sign.
2656 */
2657TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2658 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2659 .Authorization(TAG_NO_AUTH_REQUIRED)
2660 .RsaEncryptionKey(2048, 65537)
2661 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002662 .Padding(PaddingMode::NONE)
2663 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002664 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2665 Begin(KeyPurpose::SIGN,
2666 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2667}
2668
2669/*
2670 * SigningOperationsTest.RsaSignTooLargeMessage
2671 *
2672 * Verifies that attempting a raw signature of a message which is the same length as the key,
2673 * but numerically larger than the public modulus, fails with the correct error.
2674 */
2675TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2676 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2677 .Authorization(TAG_NO_AUTH_REQUIRED)
2678 .RsaSigningKey(2048, 65537)
2679 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002680 .Padding(PaddingMode::NONE)
2681 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002682
2683 // Largest possible message will always be larger than the public modulus.
2684 string message(2048 / 8, static_cast<char>(0xff));
2685 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2686 .Authorization(TAG_NO_AUTH_REQUIRED)
2687 .Digest(Digest::NONE)
2688 .Padding(PaddingMode::NONE)));
2689 string signature;
2690 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2691}
2692
2693/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002694 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2695 *
2696 * Verifies ECDSA signature/verification for all digests and curves.
2697 */
2698TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2699 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2700
2701 string message = "1234567890";
2702 string corrupt_message = "2234567890";
2703 for (auto curve : ValidCurves()) {
2704 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2705 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2706 .Authorization(TAG_NO_AUTH_REQUIRED)
2707 .EcdsaSigningKey(curve)
2708 .Digest(digests)
2709 .SetDefaultValidity());
2710 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2711 if (error != ErrorCode::OK) {
2712 continue;
2713 }
2714
2715 for (auto digest : digests) {
2716 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2717 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2718 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2719 }
2720
2721 auto rc = DeleteKey();
2722 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2723 }
2724}
2725
2726/*
Selene Huang31ab4042020-04-29 04:22:39 -07002727 * SigningOperationsTest.EcdsaAllCurves
2728 *
2729 * Verifies that ECDSA operations succeed with all possible curves.
2730 */
2731TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2732 for (auto curve : ValidCurves()) {
2733 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2734 .Authorization(TAG_NO_AUTH_REQUIRED)
2735 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002736 .Digest(Digest::SHA_2_256)
2737 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002738 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2739 if (error != ErrorCode::OK) continue;
2740
2741 string message(1024, 'a');
2742 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2743 CheckedDeleteKey();
2744 }
2745}
2746
2747/*
2748 * SigningOperationsTest.EcdsaNoDigestHugeData
2749 *
2750 * Verifies that ECDSA operations support very large messages, even without digesting. This
2751 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2752 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2753 * the framework.
2754 */
2755TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2756 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2757 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002758 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002759 .Digest(Digest::NONE)
2760 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002761 string message(1 * 1024, 'a');
2762 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2763}
2764
2765/*
2766 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2767 *
2768 * Verifies that using an EC key requires the correct app ID/data.
2769 */
2770TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2771 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2772 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002773 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002774 .Digest(Digest::NONE)
2775 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002776 .Authorization(TAG_APPLICATION_DATA, "appdata")
2777 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002778
2779 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2780
Selene Huang31ab4042020-04-29 04:22:39 -07002781 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2782 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2783 AbortIfNeeded();
2784 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2785 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2786 .Digest(Digest::NONE)
2787 .Authorization(TAG_APPLICATION_ID, "clientid")));
2788 AbortIfNeeded();
2789 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2790 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2791 .Digest(Digest::NONE)
2792 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2793 AbortIfNeeded();
2794 EXPECT_EQ(ErrorCode::OK,
2795 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2796 .Digest(Digest::NONE)
2797 .Authorization(TAG_APPLICATION_DATA, "appdata")
2798 .Authorization(TAG_APPLICATION_ID, "clientid")));
2799 AbortIfNeeded();
2800}
2801
2802/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002803 * SigningOperationsTest.EcdsaIncompatibleDigest
2804 *
2805 * Verifies that using an EC key requires compatible digest.
2806 */
2807TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2808 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2809 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002810 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002811 .Digest(Digest::NONE)
2812 .Digest(Digest::SHA1)
2813 .SetDefaultValidity()));
2814 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2815 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2816 AbortIfNeeded();
2817}
2818
2819/*
Selene Huang31ab4042020-04-29 04:22:39 -07002820 * SigningOperationsTest.AesEcbSign
2821 *
2822 * Verifies that attempts to use AES keys to sign fail in the correct way.
2823 */
2824TEST_P(SigningOperationsTest, AesEcbSign) {
2825 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2826 .Authorization(TAG_NO_AUTH_REQUIRED)
2827 .SigningKey()
2828 .AesEncryptionKey(128)
2829 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2830
2831 AuthorizationSet out_params;
2832 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2833 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2834 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2835 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2836}
2837
2838/*
2839 * SigningOperationsTest.HmacAllDigests
2840 *
2841 * Verifies that HMAC works with all digests.
2842 */
2843TEST_P(SigningOperationsTest, HmacAllDigests) {
2844 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2845 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2846 .Authorization(TAG_NO_AUTH_REQUIRED)
2847 .HmacKey(128)
2848 .Digest(digest)
2849 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2850 << "Failed to create HMAC key with digest " << digest;
2851 string message = "12345678901234567890123456789012";
2852 string signature = MacMessage(message, digest, 160);
2853 EXPECT_EQ(160U / 8U, signature.size())
2854 << "Failed to sign with HMAC key with digest " << digest;
2855 CheckedDeleteKey();
2856 }
2857}
2858
2859/*
2860 * SigningOperationsTest.HmacSha256TooLargeMacLength
2861 *
2862 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2863 * digest size.
2864 */
2865TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2866 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2867 .Authorization(TAG_NO_AUTH_REQUIRED)
2868 .HmacKey(128)
2869 .Digest(Digest::SHA_2_256)
2870 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2871 AuthorizationSet output_params;
2872 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2873 AuthorizationSetBuilder()
2874 .Digest(Digest::SHA_2_256)
2875 .Authorization(TAG_MAC_LENGTH, 264),
2876 &output_params));
2877}
2878
2879/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002880 * SigningOperationsTest.HmacSha256InvalidMacLength
2881 *
2882 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2883 * not a multiple of 8.
2884 */
2885TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2886 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2887 .Authorization(TAG_NO_AUTH_REQUIRED)
2888 .HmacKey(128)
2889 .Digest(Digest::SHA_2_256)
2890 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2891 AuthorizationSet output_params;
2892 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2893 AuthorizationSetBuilder()
2894 .Digest(Digest::SHA_2_256)
2895 .Authorization(TAG_MAC_LENGTH, 161),
2896 &output_params));
2897}
2898
2899/*
Selene Huang31ab4042020-04-29 04:22:39 -07002900 * SigningOperationsTest.HmacSha256TooSmallMacLength
2901 *
2902 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2903 * specified minimum MAC length.
2904 */
2905TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2906 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2907 .Authorization(TAG_NO_AUTH_REQUIRED)
2908 .HmacKey(128)
2909 .Digest(Digest::SHA_2_256)
2910 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2911 AuthorizationSet output_params;
2912 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2913 AuthorizationSetBuilder()
2914 .Digest(Digest::SHA_2_256)
2915 .Authorization(TAG_MAC_LENGTH, 120),
2916 &output_params));
2917}
2918
2919/*
2920 * SigningOperationsTest.HmacRfc4231TestCase3
2921 *
2922 * Validates against the test vectors from RFC 4231 test case 3.
2923 */
2924TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2925 string key(20, 0xaa);
2926 string message(50, 0xdd);
2927 uint8_t sha_224_expected[] = {
2928 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2929 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2930 };
2931 uint8_t sha_256_expected[] = {
2932 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2933 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2934 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2935 };
2936 uint8_t sha_384_expected[] = {
2937 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2938 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2939 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2940 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2941 };
2942 uint8_t sha_512_expected[] = {
2943 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2944 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2945 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2946 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2947 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2948 };
2949
2950 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2951 if (SecLevel() != SecurityLevel::STRONGBOX) {
2952 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2953 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2954 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2955 }
2956}
2957
2958/*
2959 * SigningOperationsTest.HmacRfc4231TestCase5
2960 *
2961 * Validates against the test vectors from RFC 4231 test case 5.
2962 */
2963TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2964 string key(20, 0x0c);
2965 string message = "Test With Truncation";
2966
2967 uint8_t sha_224_expected[] = {
2968 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2969 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2970 };
2971 uint8_t sha_256_expected[] = {
2972 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2973 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2974 };
2975 uint8_t sha_384_expected[] = {
2976 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2977 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2978 };
2979 uint8_t sha_512_expected[] = {
2980 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2981 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2982 };
2983
2984 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2985 if (SecLevel() != SecurityLevel::STRONGBOX) {
2986 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2987 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2988 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2989 }
2990}
2991
2992INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2993
2994typedef KeyMintAidlTestBase VerificationOperationsTest;
2995
2996/*
Selene Huang31ab4042020-04-29 04:22:39 -07002997 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2998 *
2999 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3000 */
3001TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3002 string key_material = "HelloThisIsAKey";
3003
3004 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003005 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003006 EXPECT_EQ(ErrorCode::OK,
3007 ImportKey(AuthorizationSetBuilder()
3008 .Authorization(TAG_NO_AUTH_REQUIRED)
3009 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3010 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3011 .Digest(Digest::SHA_2_256)
3012 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3013 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3014 EXPECT_EQ(ErrorCode::OK,
3015 ImportKey(AuthorizationSetBuilder()
3016 .Authorization(TAG_NO_AUTH_REQUIRED)
3017 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3018 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3019 .Digest(Digest::SHA_2_256)
3020 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3021 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3022
3023 string message = "This is a message.";
3024 string signature = SignMessage(
3025 signing_key, message,
3026 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3027
3028 // Signing key should not work.
3029 AuthorizationSet out_params;
3030 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3031 Begin(KeyPurpose::VERIFY, signing_key,
3032 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3033
3034 // Verification key should work.
3035 VerifyMessage(verification_key, message, signature,
3036 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3037
3038 CheckedDeleteKey(&signing_key);
3039 CheckedDeleteKey(&verification_key);
3040}
3041
3042INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3043
3044typedef KeyMintAidlTestBase ExportKeyTest;
3045
3046/*
3047 * ExportKeyTest.RsaUnsupportedKeyFormat
3048 *
3049 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3050 */
3051// TODO(seleneh) add ExportKey to GenerateKey
3052// check result
3053
3054class ImportKeyTest : public KeyMintAidlTestBase {
3055 public:
3056 template <TagType tag_type, Tag tag, typename ValueT>
3057 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3058 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003059 for (auto& entry : key_characteristics_) {
3060 if (entry.securityLevel == SecLevel()) {
3061 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3062 << "Tag " << tag << " with value " << expected
3063 << " not found at security level" << entry.securityLevel;
3064 } else {
3065 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3066 << "Tag " << tag << " found at security level " << entry.securityLevel;
3067 }
Selene Huang31ab4042020-04-29 04:22:39 -07003068 }
3069 }
3070
3071 void CheckOrigin() {
3072 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003073 // Origin isn't a crypto param, but it always lives with them.
3074 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003075 }
3076};
3077
3078/*
3079 * ImportKeyTest.RsaSuccess
3080 *
3081 * Verifies that importing and using an RSA key pair works correctly.
3082 */
3083TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003084 uint32_t key_size;
3085 string key;
3086
3087 if (SecLevel() == SecurityLevel::STRONGBOX) {
3088 key_size = 2048;
3089 key = rsa_2048_key;
3090 } else {
3091 key_size = 1024;
3092 key = rsa_key;
3093 }
3094
Selene Huang31ab4042020-04-29 04:22:39 -07003095 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3096 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003097 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003098 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003099 .Padding(PaddingMode::RSA_PSS)
3100 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003101 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003102
3103 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003104 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003105 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3106 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3107 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3108 CheckOrigin();
3109
3110 string message(1024 / 8, 'a');
3111 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3112 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003113 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003114}
3115
3116/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003117 * ImportKeyTest.RsaSuccessWithoutParams
3118 *
3119 * Verifies that importing and using an RSA key pair without specifying parameters
3120 * works correctly.
3121 */
3122TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3123 uint32_t key_size;
3124 string key;
3125
3126 if (SecLevel() == SecurityLevel::STRONGBOX) {
3127 key_size = 2048;
3128 key = rsa_2048_key;
3129 } else {
3130 key_size = 1024;
3131 key = rsa_key;
3132 }
3133
3134 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3135 .Authorization(TAG_NO_AUTH_REQUIRED)
3136 .SigningKey()
3137 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3138 .Digest(Digest::SHA_2_256)
3139 .Padding(PaddingMode::RSA_PSS)
3140 .SetDefaultValidity(),
3141 KeyFormat::PKCS8, key));
3142
3143 // Key size and public exponent are determined from the imported key material.
3144 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3145 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3146
3147 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3148 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3149 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3150 CheckOrigin();
3151
3152 string message(1024 / 8, 'a');
3153 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3154 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003155 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003156}
3157
3158/*
Selene Huang31ab4042020-04-29 04:22:39 -07003159 * ImportKeyTest.RsaKeySizeMismatch
3160 *
3161 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3162 * correct way.
3163 */
3164TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3165 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3166 ImportKey(AuthorizationSetBuilder()
3167 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3168 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003169 .Padding(PaddingMode::NONE)
3170 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003171 KeyFormat::PKCS8, rsa_key));
3172}
3173
3174/*
3175 * ImportKeyTest.RsaPublicExponentMismatch
3176 *
3177 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3178 * fails in the correct way.
3179 */
3180TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3181 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3182 ImportKey(AuthorizationSetBuilder()
3183 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3184 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003185 .Padding(PaddingMode::NONE)
3186 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003187 KeyFormat::PKCS8, rsa_key));
3188}
3189
3190/*
3191 * ImportKeyTest.EcdsaSuccess
3192 *
3193 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3194 */
3195TEST_P(ImportKeyTest, EcdsaSuccess) {
3196 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3197 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003198 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003199 .Digest(Digest::SHA_2_256)
3200 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003201 KeyFormat::PKCS8, ec_256_key));
3202
3203 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003204 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3205 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3206
3207 CheckOrigin();
3208
3209 string message(32, 'a');
3210 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3211 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003212 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003213}
3214
3215/*
3216 * ImportKeyTest.EcdsaP256RFC5915Success
3217 *
3218 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3219 * correctly.
3220 */
3221TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3222 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3223 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003224 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003225 .Digest(Digest::SHA_2_256)
3226 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003227 KeyFormat::PKCS8, ec_256_key_rfc5915));
3228
3229 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003230 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3231 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3232
3233 CheckOrigin();
3234
3235 string message(32, 'a');
3236 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3237 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003238 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003239}
3240
3241/*
3242 * ImportKeyTest.EcdsaP256SEC1Success
3243 *
3244 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3245 */
3246TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3247 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3248 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003249 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003250 .Digest(Digest::SHA_2_256)
3251 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003252 KeyFormat::PKCS8, ec_256_key_sec1));
3253
3254 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003255 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3256 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3257
3258 CheckOrigin();
3259
3260 string message(32, 'a');
3261 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3262 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003263 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003264}
3265
3266/*
3267 * ImportKeyTest.Ecdsa521Success
3268 *
3269 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3270 */
3271TEST_P(ImportKeyTest, Ecdsa521Success) {
3272 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3273 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3274 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003275 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003276 .Digest(Digest::SHA_2_256)
3277 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003278 KeyFormat::PKCS8, ec_521_key));
3279
3280 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003281 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3282 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3283 CheckOrigin();
3284
3285 string message(32, 'a');
3286 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3287 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003288 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003289}
3290
3291/*
Selene Huang31ab4042020-04-29 04:22:39 -07003292 * ImportKeyTest.EcdsaCurveMismatch
3293 *
3294 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3295 * the correct way.
3296 */
3297TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3298 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3299 ImportKey(AuthorizationSetBuilder()
3300 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003301 .Digest(Digest::NONE)
3302 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003303 KeyFormat::PKCS8, ec_256_key));
3304}
3305
3306/*
3307 * ImportKeyTest.AesSuccess
3308 *
3309 * Verifies that importing and using an AES key works.
3310 */
3311TEST_P(ImportKeyTest, AesSuccess) {
3312 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3313 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3314 .Authorization(TAG_NO_AUTH_REQUIRED)
3315 .AesEncryptionKey(key.size() * 8)
3316 .EcbMode()
3317 .Padding(PaddingMode::PKCS7),
3318 KeyFormat::RAW, key));
3319
3320 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3321 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3322 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3323 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3324 CheckOrigin();
3325
3326 string message = "Hello World!";
3327 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3328 string ciphertext = EncryptMessage(message, params);
3329 string plaintext = DecryptMessage(ciphertext, params);
3330 EXPECT_EQ(message, plaintext);
3331}
3332
3333/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003334 * ImportKeyTest.AesFailure
3335 *
3336 * Verifies that importing an invalid AES key fails.
3337 */
3338TEST_P(ImportKeyTest, AesFailure) {
3339 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3340 uint32_t bitlen = key.size() * 8;
3341 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003342 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003343 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003344 .Authorization(TAG_NO_AUTH_REQUIRED)
3345 .AesEncryptionKey(key_size)
3346 .EcbMode()
3347 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003348 KeyFormat::RAW, key);
3349 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003350 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3351 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003352 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003353
3354 // Explicit key size matches that of the provided key, but it's not a valid size.
3355 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3356 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3357 ImportKey(AuthorizationSetBuilder()
3358 .Authorization(TAG_NO_AUTH_REQUIRED)
3359 .AesEncryptionKey(long_key.size() * 8)
3360 .EcbMode()
3361 .Padding(PaddingMode::PKCS7),
3362 KeyFormat::RAW, long_key));
3363 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3364 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3365 ImportKey(AuthorizationSetBuilder()
3366 .Authorization(TAG_NO_AUTH_REQUIRED)
3367 .AesEncryptionKey(short_key.size() * 8)
3368 .EcbMode()
3369 .Padding(PaddingMode::PKCS7),
3370 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003371}
3372
3373/*
3374 * ImportKeyTest.TripleDesSuccess
3375 *
3376 * Verifies that importing and using a 3DES key works.
3377 */
3378TEST_P(ImportKeyTest, TripleDesSuccess) {
3379 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3380 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3381 .Authorization(TAG_NO_AUTH_REQUIRED)
3382 .TripleDesEncryptionKey(168)
3383 .EcbMode()
3384 .Padding(PaddingMode::PKCS7),
3385 KeyFormat::RAW, key));
3386
3387 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3388 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3389 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3390 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3391 CheckOrigin();
3392
3393 string message = "Hello World!";
3394 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3395 string ciphertext = EncryptMessage(message, params);
3396 string plaintext = DecryptMessage(ciphertext, params);
3397 EXPECT_EQ(message, plaintext);
3398}
3399
3400/*
3401 * ImportKeyTest.TripleDesFailure
3402 *
3403 * Verifies that importing an invalid 3DES key fails.
3404 */
3405TEST_P(ImportKeyTest, TripleDesFailure) {
3406 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003407 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003408 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003409 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003410 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003411 .Authorization(TAG_NO_AUTH_REQUIRED)
3412 .TripleDesEncryptionKey(key_size)
3413 .EcbMode()
3414 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003415 KeyFormat::RAW, key);
3416 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003417 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3418 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003419 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003420 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003421 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003422 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3423 ImportKey(AuthorizationSetBuilder()
3424 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003425 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003426 .EcbMode()
3427 .Padding(PaddingMode::PKCS7),
3428 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003429 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003430 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3431 ImportKey(AuthorizationSetBuilder()
3432 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003433 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003434 .EcbMode()
3435 .Padding(PaddingMode::PKCS7),
3436 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003437}
3438
3439/*
3440 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003441 *
3442 * Verifies that importing and using an HMAC key works.
3443 */
3444TEST_P(ImportKeyTest, HmacKeySuccess) {
3445 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3446 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3447 .Authorization(TAG_NO_AUTH_REQUIRED)
3448 .HmacKey(key.size() * 8)
3449 .Digest(Digest::SHA_2_256)
3450 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3451 KeyFormat::RAW, key));
3452
3453 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3454 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3455 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3456 CheckOrigin();
3457
3458 string message = "Hello World!";
3459 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3460 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3461}
3462
3463INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3464
3465auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003466 // IKeyMintDevice.aidl
3467 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3468 "020100" // INTEGER length 1 value 0x00 (version)
3469 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3470 "934bf94e2aa28a3f83c9f79297250262"
3471 "fbe3276b5a1c91159bbfa3ef8957aac8"
3472 "4b59b30b455a79c2973480823d8b3863"
3473 "c3deef4a8e243590268d80e18751a0e1"
3474 "30f67ce6a1ace9f79b95e097474febc9"
3475 "81195b1d13a69086c0863f66a7b7fdb4"
3476 "8792227b1ac5e2489febdf087ab54864"
3477 "83033a6f001ca5d1ec1e27f5c30f4cec"
3478 "2642074a39ae68aee552e196627a8e3d"
3479 "867e67a8c01b11e75f13cca0a97ab668"
3480 "b50cda07a8ecb7cd8e3dd7009c963653"
3481 "4f6f239cffe1fc8daa466f78b676c711"
3482 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3483 "99b801597d5220e307eaa5bee507fb94"
3484 "d1fa69f9e519b2de315bac92c36f2ea1"
3485 "fa1df4478c0ddedeae8c70e0233cd098"
3486 "040c" // OCTET STRING length 0x0c (initializationVector)
3487 "d796b02c370f1fa4cc0124f1"
3488 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3489 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3490 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3491 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3492 "3106" // SET length 0x06
3493 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3494 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3495 // } end SET
3496 // } end [1]
3497 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3498 "020120" // INTEGER length 1 value 0x20 (AES)
3499 // } end [2]
3500 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3501 "02020100" // INTEGER length 2 value 0x100
3502 // } end [3]
3503 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3504 "3103" // SET length 0x03 {
3505 "020101" // INTEGER length 1 value 0x01 (ECB)
3506 // } end SET
3507 // } end [4]
3508 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3509 "3103" // SET length 0x03 {
3510 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3511 // } end SET
3512 // } end [5]
3513 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3514 // (noAuthRequired)
3515 "0500" // NULL
3516 // } end [503]
3517 // } end SEQUENCE (AuthorizationList)
3518 // } end SEQUENCE (KeyDescription)
3519 "0420" // OCTET STRING length 0x20 (encryptedKey)
3520 "ccd540855f833a5e1480bfd2d36faf3a"
3521 "eee15df5beabe2691bc82dde2a7aa910"
3522 "0410" // OCTET STRING length 0x10 (tag)
3523 "64c9f689c60ff6223ab6e6999e0eb6e5"
3524 // } SEQUENCE (SecureKeyWrapper)
3525);
Selene Huang31ab4042020-04-29 04:22:39 -07003526
3527auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003528 // IKeyMintDevice.aidl
3529 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3530 "020100" // INTEGER length 1 value 0x00 (version)
3531 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3532 "aad93ed5924f283b4bb5526fbe7a1412"
3533 "f9d9749ec30db9062b29e574a8546f33"
3534 "c88732452f5b8e6a391ee76c39ed1712"
3535 "c61d8df6213dec1cffbc17a8c6d04c7b"
3536 "30893d8daa9b2015213e219468215532"
3537 "07f8f9931c4caba23ed3bee28b36947e"
3538 "47f10e0a5c3dc51c988a628daad3e5e1"
3539 "f4005e79c2d5a96c284b4b8d7e4948f3"
3540 "31e5b85dd5a236f85579f3ea1d1b8484"
3541 "87470bdb0ab4f81a12bee42c99fe0df4"
3542 "bee3759453e69ad1d68a809ce06b949f"
3543 "7694a990429b2fe81e066ff43e56a216"
3544 "02db70757922a4bcc23ab89f1e35da77"
3545 "586775f423e519c2ea394caf48a28d0c"
3546 "8020f1dcf6b3a68ec246f615ae96dae9"
3547 "a079b1f6eb959033c1af5c125fd94168"
3548 "040c" // OCTET STRING length 0x0c (initializationVector)
3549 "6d9721d08589581ab49204a3"
3550 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3551 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3552 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3553 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3554 "3106" // SET length 0x06
3555 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3556 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3557 // } end SET
3558 // } end [1]
3559 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3560 "020120" // INTEGER length 1 value 0x20 (AES)
3561 // } end [2]
3562 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3563 "02020100" // INTEGER length 2 value 0x100
3564 // } end [3]
3565 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3566 "3103" // SET length 0x03 {
3567 "020101" // INTEGER length 1 value 0x01 (ECB)
3568 // } end SET
3569 // } end [4]
3570 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3571 "3103" // SET length 0x03 {
3572 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3573 // } end SET
3574 // } end [5]
3575 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3576 // (noAuthRequired)
3577 "0500" // NULL
3578 // } end [503]
3579 // } end SEQUENCE (AuthorizationList)
3580 // } end SEQUENCE (KeyDescription)
3581 "0420" // OCTET STRING length 0x20 (encryptedKey)
3582 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3583 "c20d1f99a9a024a76f35c8e2cab9b68d"
3584 "0410" // OCTET STRING length 0x10 (tag)
3585 "2560c70109ae67c030f00b98b512a670"
3586 // } SEQUENCE (SecureKeyWrapper)
3587);
Selene Huang31ab4042020-04-29 04:22:39 -07003588
3589auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003590 // RFC 5208 s5
3591 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3592 "020100" // INTEGER length 1 value 0x00 (version)
3593 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3594 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3595 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3596 "0500" // NULL (parameters)
3597 // } SEQUENCE (AlgorithmIdentifier)
3598 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3599 // RFC 8017 A.1.2
3600 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3601 "020100" // INTEGER length 1 value 0x00 (version)
3602 "02820101" // INTEGER length 0x0101 (modulus) value...
3603 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3604 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3605 "7b06e673a837313d56b1c725150a3fef" // 0x30
3606 "86acbddc41bb759c2854eae32d35841e" // 0x40
3607 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3608 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3609 "312d7bd5921ffaea1347c157406fef71" // 0x70
3610 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3611 "f4645c11f5c1374c3886427411c44979" // 0x90
3612 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3613 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3614 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3615 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3616 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3617 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3618 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3619 "55" // 0x101
3620 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3621 "02820100" // INTEGER length 0x100 (privateExponent) value...
3622 "431447b6251908112b1ee76f99f3711a" // 0x10
3623 "52b6630960046c2de70de188d833f8b8" // 0x20
3624 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3625 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3626 "e710b630a03adc683b5d2c43080e52be" // 0x50
3627 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3628 "822bccff087d63c940ba8a45f670feb2" // 0x70
3629 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3630 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3631 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3632 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3633 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3634 "52659d5a5ba05b663737a8696281865b" // 0xd0
3635 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3636 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3637 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3638 "028181" // INTEGER length 0x81 (prime1) value...
3639 "00de392e18d682c829266cc3454e1d61" // 0x10
3640 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3641 "ff841be5bac82a164c5970007047b8c5" // 0x30
3642 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3643 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3644 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3645 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3646 "9e91346130748a6e3c124f9149d71c74" // 0x80
3647 "35"
3648 "028181" // INTEGER length 0x81 (prime2) value...
3649 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3650 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3651 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3652 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3653 "9ed39a2d934c880440aed8832f984316" // 0x50
3654 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3655 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3656 "b880677c068e1be936e81288815252a8" // 0x80
3657 "a1"
3658 "028180" // INTEGER length 0x80 (exponent1) value...
3659 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3660 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3661 "5a063212a4f105a3764743e53281988a" // 0x30
3662 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3663 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3664 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3665 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3666 "4719d6e2b9439823719cd08bcd031781" // 0x80
3667 "028181" // INTEGER length 0x81 (exponent2) value...
3668 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3669 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3670 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3671 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3672 "1254186af30b22c10582a8a43e34fe94" // 0x50
3673 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3674 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3675 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3676 "61"
3677 "028181" // INTEGER length 0x81 (coefficient) value...
3678 "00c931617c77829dfb1270502be9195c" // 0x10
3679 "8f2830885f57dba869536811e6864236" // 0x20
3680 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3681 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3682 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3683 "959356210723287b0affcc9f727044d4" // 0x60
3684 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3685 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3686 "22"
3687 // } SEQUENCE
3688 // } SEQUENCE ()
3689);
Selene Huang31ab4042020-04-29 04:22:39 -07003690
3691string zero_masking_key =
3692 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3693string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3694
3695class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3696
3697TEST_P(ImportWrappedKeyTest, Success) {
3698 auto wrapping_key_desc = AuthorizationSetBuilder()
3699 .RsaEncryptionKey(2048, 65537)
3700 .Digest(Digest::SHA_2_256)
3701 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003702 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3703 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003704
3705 ASSERT_EQ(ErrorCode::OK,
3706 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3707 AuthorizationSetBuilder()
3708 .Digest(Digest::SHA_2_256)
3709 .Padding(PaddingMode::RSA_OAEP)));
3710
3711 string message = "Hello World!";
3712 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3713 string ciphertext = EncryptMessage(message, params);
3714 string plaintext = DecryptMessage(ciphertext, params);
3715 EXPECT_EQ(message, plaintext);
3716}
3717
David Drysdaled2cc8c22021-04-15 13:29:45 +01003718/*
3719 * ImportWrappedKeyTest.SuccessSidsIgnored
3720 *
3721 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3722 * include Tag:USER_SECURE_ID.
3723 */
3724TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3725 auto wrapping_key_desc = AuthorizationSetBuilder()
3726 .RsaEncryptionKey(2048, 65537)
3727 .Digest(Digest::SHA_2_256)
3728 .Padding(PaddingMode::RSA_OAEP)
3729 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3730 .SetDefaultValidity();
3731
3732 int64_t password_sid = 42;
3733 int64_t biometric_sid = 24;
3734 ASSERT_EQ(ErrorCode::OK,
3735 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3736 AuthorizationSetBuilder()
3737 .Digest(Digest::SHA_2_256)
3738 .Padding(PaddingMode::RSA_OAEP),
3739 password_sid, biometric_sid));
3740
3741 string message = "Hello World!";
3742 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3743 string ciphertext = EncryptMessage(message, params);
3744 string plaintext = DecryptMessage(ciphertext, params);
3745 EXPECT_EQ(message, plaintext);
3746}
3747
Selene Huang31ab4042020-04-29 04:22:39 -07003748TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3749 auto wrapping_key_desc = AuthorizationSetBuilder()
3750 .RsaEncryptionKey(2048, 65537)
3751 .Digest(Digest::SHA_2_256)
3752 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003753 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3754 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003755
3756 ASSERT_EQ(ErrorCode::OK,
3757 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3758 AuthorizationSetBuilder()
3759 .Digest(Digest::SHA_2_256)
3760 .Padding(PaddingMode::RSA_OAEP)));
3761}
3762
3763TEST_P(ImportWrappedKeyTest, WrongMask) {
3764 auto wrapping_key_desc = AuthorizationSetBuilder()
3765 .RsaEncryptionKey(2048, 65537)
3766 .Digest(Digest::SHA_2_256)
3767 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003768 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3769 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003770
3771 ASSERT_EQ(
3772 ErrorCode::VERIFICATION_FAILED,
3773 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3774 AuthorizationSetBuilder()
3775 .Digest(Digest::SHA_2_256)
3776 .Padding(PaddingMode::RSA_OAEP)));
3777}
3778
3779TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3780 auto wrapping_key_desc = AuthorizationSetBuilder()
3781 .RsaEncryptionKey(2048, 65537)
3782 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003783 .Padding(PaddingMode::RSA_OAEP)
3784 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003785
3786 ASSERT_EQ(
3787 ErrorCode::INCOMPATIBLE_PURPOSE,
3788 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3789 AuthorizationSetBuilder()
3790 .Digest(Digest::SHA_2_256)
3791 .Padding(PaddingMode::RSA_OAEP)));
3792}
3793
David Drysdaled2cc8c22021-04-15 13:29:45 +01003794TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3795 auto wrapping_key_desc = AuthorizationSetBuilder()
3796 .RsaEncryptionKey(2048, 65537)
3797 .Digest(Digest::SHA_2_256)
3798 .Padding(PaddingMode::RSA_PSS)
3799 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3800 .SetDefaultValidity();
3801
3802 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3803 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3804 AuthorizationSetBuilder()
3805 .Digest(Digest::SHA_2_256)
3806 .Padding(PaddingMode::RSA_OAEP)));
3807}
3808
3809TEST_P(ImportWrappedKeyTest, WrongDigest) {
3810 auto wrapping_key_desc = AuthorizationSetBuilder()
3811 .RsaEncryptionKey(2048, 65537)
3812 .Digest(Digest::SHA_2_512)
3813 .Padding(PaddingMode::RSA_OAEP)
3814 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3815 .SetDefaultValidity();
3816
3817 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3818 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3819 AuthorizationSetBuilder()
3820 .Digest(Digest::SHA_2_256)
3821 .Padding(PaddingMode::RSA_OAEP)));
3822}
3823
Selene Huang31ab4042020-04-29 04:22:39 -07003824INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3825
3826typedef KeyMintAidlTestBase EncryptionOperationsTest;
3827
3828/*
3829 * EncryptionOperationsTest.RsaNoPaddingSuccess
3830 *
David Drysdale59cae642021-05-12 13:52:03 +01003831 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003832 */
3833TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003834 for (uint64_t exponent : {3, 65537}) {
3835 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3836 .Authorization(TAG_NO_AUTH_REQUIRED)
3837 .RsaEncryptionKey(2048, exponent)
3838 .Padding(PaddingMode::NONE)
3839 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003840
David Drysdaled2cc8c22021-04-15 13:29:45 +01003841 string message = string(2048 / 8, 'a');
3842 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003843 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003844 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003845
David Drysdale59cae642021-05-12 13:52:03 +01003846 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003847 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003848
David Drysdaled2cc8c22021-04-15 13:29:45 +01003849 // Unpadded RSA is deterministic
3850 EXPECT_EQ(ciphertext1, ciphertext2);
3851
3852 CheckedDeleteKey();
3853 }
Selene Huang31ab4042020-04-29 04:22:39 -07003854}
3855
3856/*
3857 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3858 *
David Drysdale59cae642021-05-12 13:52:03 +01003859 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003860 */
3861TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3862 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3863 .Authorization(TAG_NO_AUTH_REQUIRED)
3864 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003865 .Padding(PaddingMode::NONE)
3866 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003867
3868 string message = "1";
3869 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3870
David Drysdale59cae642021-05-12 13:52:03 +01003871 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003872 EXPECT_EQ(2048U / 8, ciphertext.size());
3873
3874 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3875 string plaintext = DecryptMessage(ciphertext, params);
3876
3877 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003878}
3879
3880/*
Selene Huang31ab4042020-04-29 04:22:39 -07003881 * EncryptionOperationsTest.RsaOaepSuccess
3882 *
David Drysdale59cae642021-05-12 13:52:03 +01003883 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003884 */
3885TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3886 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3887
3888 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01003889 ASSERT_EQ(ErrorCode::OK,
3890 GenerateKey(AuthorizationSetBuilder()
3891 .Authorization(TAG_NO_AUTH_REQUIRED)
3892 .RsaEncryptionKey(key_size, 65537)
3893 .Padding(PaddingMode::RSA_OAEP)
3894 .Digest(digests)
3895 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3896 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003897
3898 string message = "Hello";
3899
3900 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01003901 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3902
3903 auto params = AuthorizationSetBuilder()
3904 .Digest(digest)
3905 .Padding(PaddingMode::RSA_OAEP)
3906 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3907 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003908 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3909 EXPECT_EQ(key_size / 8, ciphertext1.size());
3910
David Drysdale59cae642021-05-12 13:52:03 +01003911 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003912 EXPECT_EQ(key_size / 8, ciphertext2.size());
3913
3914 // OAEP randomizes padding so every result should be different (with astronomically high
3915 // probability).
3916 EXPECT_NE(ciphertext1, ciphertext2);
3917
3918 string plaintext1 = DecryptMessage(ciphertext1, params);
3919 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3920 string plaintext2 = DecryptMessage(ciphertext2, params);
3921 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3922
3923 // Decrypting corrupted ciphertext should fail.
3924 size_t offset_to_corrupt = random() % ciphertext1.size();
3925 char corrupt_byte;
3926 do {
3927 corrupt_byte = static_cast<char>(random() % 256);
3928 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3929 ciphertext1[offset_to_corrupt] = corrupt_byte;
3930
3931 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3932 string result;
3933 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3934 EXPECT_EQ(0U, result.size());
3935 }
3936}
3937
3938/*
3939 * EncryptionOperationsTest.RsaOaepInvalidDigest
3940 *
David Drysdale59cae642021-05-12 13:52:03 +01003941 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003942 * without a digest.
3943 */
3944TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3945 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3946 .Authorization(TAG_NO_AUTH_REQUIRED)
3947 .RsaEncryptionKey(2048, 65537)
3948 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003949 .Digest(Digest::NONE)
3950 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003951
3952 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003953 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003954}
3955
3956/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003957 * EncryptionOperationsTest.RsaOaepInvalidPadding
3958 *
David Drysdale59cae642021-05-12 13:52:03 +01003959 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003960 * with a padding value that is only suitable for signing/verifying.
3961 */
3962TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3963 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3964 .Authorization(TAG_NO_AUTH_REQUIRED)
3965 .RsaEncryptionKey(2048, 65537)
3966 .Padding(PaddingMode::RSA_PSS)
3967 .Digest(Digest::NONE)
3968 .SetDefaultValidity()));
3969
3970 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003971 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003972}
3973
3974/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003975 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003976 *
David Drysdale59cae642021-05-12 13:52:03 +01003977 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003978 * with a different digest than was used to encrypt.
3979 */
3980TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3981 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3982
3983 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3984 .Authorization(TAG_NO_AUTH_REQUIRED)
3985 .RsaEncryptionKey(1024, 65537)
3986 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003987 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3988 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003989 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01003990 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07003991 message,
3992 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3993
3994 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3995 .Digest(Digest::SHA_2_256)
3996 .Padding(PaddingMode::RSA_OAEP)));
3997 string result;
3998 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3999 EXPECT_EQ(0U, result.size());
4000}
4001
4002/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004003 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
4004 *
David Drysdale59cae642021-05-12 13:52:03 +01004005 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004006 * digests.
4007 */
4008TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
4009 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4010
4011 size_t key_size = 2048; // Need largish key for SHA-512 test.
4012 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4013 .OaepMGFDigest(digests)
4014 .Authorization(TAG_NO_AUTH_REQUIRED)
4015 .RsaEncryptionKey(key_size, 65537)
4016 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004017 .Digest(Digest::SHA_2_256)
4018 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004019
4020 string message = "Hello";
4021
4022 for (auto digest : digests) {
4023 auto params = AuthorizationSetBuilder()
4024 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4025 .Digest(Digest::SHA_2_256)
4026 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01004027 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004028 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4029 EXPECT_EQ(key_size / 8, ciphertext1.size());
4030
David Drysdale59cae642021-05-12 13:52:03 +01004031 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004032 EXPECT_EQ(key_size / 8, ciphertext2.size());
4033
4034 // OAEP randomizes padding so every result should be different (with astronomically high
4035 // probability).
4036 EXPECT_NE(ciphertext1, ciphertext2);
4037
4038 string plaintext1 = DecryptMessage(ciphertext1, params);
4039 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4040 string plaintext2 = DecryptMessage(ciphertext2, params);
4041 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4042
4043 // Decrypting corrupted ciphertext should fail.
4044 size_t offset_to_corrupt = random() % ciphertext1.size();
4045 char corrupt_byte;
4046 do {
4047 corrupt_byte = static_cast<char>(random() % 256);
4048 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4049 ciphertext1[offset_to_corrupt] = corrupt_byte;
4050
4051 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4052 string result;
4053 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4054 EXPECT_EQ(0U, result.size());
4055 }
4056}
4057
4058/*
4059 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4060 *
David Drysdale59cae642021-05-12 13:52:03 +01004061 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004062 * with incompatible MGF digest.
4063 */
4064TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4065 ASSERT_EQ(ErrorCode::OK,
4066 GenerateKey(AuthorizationSetBuilder()
4067 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4068 .Authorization(TAG_NO_AUTH_REQUIRED)
4069 .RsaEncryptionKey(2048, 65537)
4070 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004071 .Digest(Digest::SHA_2_256)
4072 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004073 string message = "Hello World!";
4074
4075 auto params = AuthorizationSetBuilder()
4076 .Padding(PaddingMode::RSA_OAEP)
4077 .Digest(Digest::SHA_2_256)
4078 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004079 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004080}
4081
4082/*
4083 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4084 *
4085 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4086 * with unsupported MGF digest.
4087 */
4088TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4089 ASSERT_EQ(ErrorCode::OK,
4090 GenerateKey(AuthorizationSetBuilder()
4091 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4092 .Authorization(TAG_NO_AUTH_REQUIRED)
4093 .RsaEncryptionKey(2048, 65537)
4094 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004095 .Digest(Digest::SHA_2_256)
4096 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004097 string message = "Hello World!";
4098
4099 auto params = AuthorizationSetBuilder()
4100 .Padding(PaddingMode::RSA_OAEP)
4101 .Digest(Digest::SHA_2_256)
4102 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004103 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004104}
4105
4106/*
Selene Huang31ab4042020-04-29 04:22:39 -07004107 * EncryptionOperationsTest.RsaPkcs1Success
4108 *
4109 * Verifies that RSA PKCS encryption/decrypts works.
4110 */
4111TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4112 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4113 .Authorization(TAG_NO_AUTH_REQUIRED)
4114 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004115 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4116 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004117
4118 string message = "Hello World!";
4119 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004120 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004121 EXPECT_EQ(2048U / 8, ciphertext1.size());
4122
David Drysdale59cae642021-05-12 13:52:03 +01004123 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004124 EXPECT_EQ(2048U / 8, ciphertext2.size());
4125
4126 // PKCS1 v1.5 randomizes padding so every result should be different.
4127 EXPECT_NE(ciphertext1, ciphertext2);
4128
4129 string plaintext = DecryptMessage(ciphertext1, params);
4130 EXPECT_EQ(message, plaintext);
4131
4132 // Decrypting corrupted ciphertext should fail.
4133 size_t offset_to_corrupt = random() % ciphertext1.size();
4134 char corrupt_byte;
4135 do {
4136 corrupt_byte = static_cast<char>(random() % 256);
4137 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4138 ciphertext1[offset_to_corrupt] = corrupt_byte;
4139
4140 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4141 string result;
4142 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4143 EXPECT_EQ(0U, result.size());
4144}
4145
4146/*
Selene Huang31ab4042020-04-29 04:22:39 -07004147 * EncryptionOperationsTest.EcdsaEncrypt
4148 *
4149 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4150 */
4151TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4152 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4153 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004154 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004155 .Digest(Digest::NONE)
4156 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004157 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4158 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4159 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4160}
4161
4162/*
4163 * EncryptionOperationsTest.HmacEncrypt
4164 *
4165 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4166 */
4167TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4168 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4169 .Authorization(TAG_NO_AUTH_REQUIRED)
4170 .HmacKey(128)
4171 .Digest(Digest::SHA_2_256)
4172 .Padding(PaddingMode::NONE)
4173 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4174 auto params = AuthorizationSetBuilder()
4175 .Digest(Digest::SHA_2_256)
4176 .Padding(PaddingMode::NONE)
4177 .Authorization(TAG_MAC_LENGTH, 128);
4178 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4179 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4180}
4181
4182/*
4183 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4184 *
4185 * Verifies that AES ECB mode works.
4186 */
4187TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4188 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4189 .Authorization(TAG_NO_AUTH_REQUIRED)
4190 .AesEncryptionKey(128)
4191 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4192 .Padding(PaddingMode::NONE)));
4193
4194 ASSERT_GT(key_blob_.size(), 0U);
4195 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4196
4197 // Two-block message.
4198 string message = "12345678901234567890123456789012";
4199 string ciphertext1 = EncryptMessage(message, params);
4200 EXPECT_EQ(message.size(), ciphertext1.size());
4201
4202 string ciphertext2 = EncryptMessage(string(message), params);
4203 EXPECT_EQ(message.size(), ciphertext2.size());
4204
4205 // ECB is deterministic.
4206 EXPECT_EQ(ciphertext1, ciphertext2);
4207
4208 string plaintext = DecryptMessage(ciphertext1, params);
4209 EXPECT_EQ(message, plaintext);
4210}
4211
4212/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004213 * EncryptionOperationsTest.AesEcbUnknownTag
4214 *
4215 * Verifies that AES ECB operations ignore unknown tags.
4216 */
4217TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4218 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4219 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4220 KeyParameter unknown_param;
4221 unknown_param.tag = unknown_tag;
4222
4223 vector<KeyCharacteristics> key_characteristics;
4224 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4225 .Authorization(TAG_NO_AUTH_REQUIRED)
4226 .AesEncryptionKey(128)
4227 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4228 .Padding(PaddingMode::NONE)
4229 .Authorization(unknown_param),
4230 &key_blob_, &key_characteristics));
4231 ASSERT_GT(key_blob_.size(), 0U);
4232
4233 // Unknown tags should not be returned in key characteristics.
4234 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4235 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4236 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4237 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4238
4239 // Encrypt without mentioning the unknown parameter.
4240 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4241 string message = "12345678901234567890123456789012";
4242 string ciphertext = EncryptMessage(message, params);
4243 EXPECT_EQ(message.size(), ciphertext.size());
4244
4245 // Decrypt including the unknown parameter.
4246 auto decrypt_params = AuthorizationSetBuilder()
4247 .BlockMode(BlockMode::ECB)
4248 .Padding(PaddingMode::NONE)
4249 .Authorization(unknown_param);
4250 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4251 EXPECT_EQ(message, plaintext);
4252}
4253
4254/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004255 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004256 *
4257 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4258 */
4259TEST_P(EncryptionOperationsTest, AesWrongMode) {
4260 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4261 .Authorization(TAG_NO_AUTH_REQUIRED)
4262 .AesEncryptionKey(128)
4263 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4264 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004265 ASSERT_GT(key_blob_.size(), 0U);
4266
Selene Huang31ab4042020-04-29 04:22:39 -07004267 EXPECT_EQ(
4268 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4269 Begin(KeyPurpose::ENCRYPT,
4270 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4271}
4272
4273/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004274 * EncryptionOperationsTest.AesWrongPadding
4275 *
4276 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4277 */
4278TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4279 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4280 .Authorization(TAG_NO_AUTH_REQUIRED)
4281 .AesEncryptionKey(128)
4282 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4283 .Padding(PaddingMode::NONE)));
4284 ASSERT_GT(key_blob_.size(), 0U);
4285
4286 EXPECT_EQ(
4287 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4288 Begin(KeyPurpose::ENCRYPT,
4289 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4290}
4291
4292/*
4293 * EncryptionOperationsTest.AesInvalidParams
4294 *
4295 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4296 */
4297TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4298 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4299 .Authorization(TAG_NO_AUTH_REQUIRED)
4300 .AesEncryptionKey(128)
4301 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4302 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4303 .Padding(PaddingMode::NONE)
4304 .Padding(PaddingMode::PKCS7)));
4305 ASSERT_GT(key_blob_.size(), 0U);
4306
4307 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4308 .BlockMode(BlockMode::CBC)
4309 .BlockMode(BlockMode::ECB)
4310 .Padding(PaddingMode::NONE));
4311 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4312 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4313
4314 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4315 .BlockMode(BlockMode::ECB)
4316 .Padding(PaddingMode::NONE)
4317 .Padding(PaddingMode::PKCS7));
4318 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4319 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4320}
4321
4322/*
Selene Huang31ab4042020-04-29 04:22:39 -07004323 * EncryptionOperationsTest.AesWrongPurpose
4324 *
4325 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4326 * specified.
4327 */
4328TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4329 auto err = GenerateKey(AuthorizationSetBuilder()
4330 .Authorization(TAG_NO_AUTH_REQUIRED)
4331 .AesKey(128)
4332 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4333 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4334 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4335 .Padding(PaddingMode::NONE));
4336 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4337 ASSERT_GT(key_blob_.size(), 0U);
4338
4339 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4340 .BlockMode(BlockMode::GCM)
4341 .Padding(PaddingMode::NONE)
4342 .Authorization(TAG_MAC_LENGTH, 128));
4343 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4344
4345 CheckedDeleteKey();
4346
4347 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4348 .Authorization(TAG_NO_AUTH_REQUIRED)
4349 .AesKey(128)
4350 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4351 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4352 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4353 .Padding(PaddingMode::NONE)));
4354
4355 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4356 .BlockMode(BlockMode::GCM)
4357 .Padding(PaddingMode::NONE)
4358 .Authorization(TAG_MAC_LENGTH, 128));
4359 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4360}
4361
4362/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004363 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004364 *
4365 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4366 * multiple of the block size and no padding is specified.
4367 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004368TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4369 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4370 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4371 .Authorization(TAG_NO_AUTH_REQUIRED)
4372 .AesEncryptionKey(128)
4373 .Authorization(TAG_BLOCK_MODE, blockMode)
4374 .Padding(PaddingMode::NONE)));
4375 // Message is slightly shorter than two blocks.
4376 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004377
David Drysdaled2cc8c22021-04-15 13:29:45 +01004378 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4379 AuthorizationSet out_params;
4380 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4381 string ciphertext;
4382 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4383 EXPECT_EQ(0U, ciphertext.size());
4384
4385 CheckedDeleteKey();
4386 }
Selene Huang31ab4042020-04-29 04:22:39 -07004387}
4388
4389/*
4390 * EncryptionOperationsTest.AesEcbPkcs7Padding
4391 *
4392 * Verifies that AES PKCS7 padding works for any message length.
4393 */
4394TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4395 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4396 .Authorization(TAG_NO_AUTH_REQUIRED)
4397 .AesEncryptionKey(128)
4398 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4399 .Padding(PaddingMode::PKCS7)));
4400
4401 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4402
4403 // Try various message lengths; all should work.
4404 for (size_t i = 0; i < 32; ++i) {
4405 string message(i, 'a');
4406 string ciphertext = EncryptMessage(message, params);
4407 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4408 string plaintext = DecryptMessage(ciphertext, params);
4409 EXPECT_EQ(message, plaintext);
4410 }
4411}
4412
4413/*
4414 * EncryptionOperationsTest.AesEcbWrongPadding
4415 *
4416 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4417 * specified.
4418 */
4419TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4420 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4421 .Authorization(TAG_NO_AUTH_REQUIRED)
4422 .AesEncryptionKey(128)
4423 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4424 .Padding(PaddingMode::NONE)));
4425
4426 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4427
4428 // Try various message lengths; all should fail
4429 for (size_t i = 0; i < 32; ++i) {
4430 string message(i, 'a');
4431 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4432 }
4433}
4434
4435/*
4436 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4437 *
4438 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4439 */
4440TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4441 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4442 .Authorization(TAG_NO_AUTH_REQUIRED)
4443 .AesEncryptionKey(128)
4444 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4445 .Padding(PaddingMode::PKCS7)));
4446
4447 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4448
4449 string message = "a";
4450 string ciphertext = EncryptMessage(message, params);
4451 EXPECT_EQ(16U, ciphertext.size());
4452 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07004453
Seth Moore7a55ae32021-06-23 14:28:11 -07004454 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
4455 ++ciphertext[ciphertext.size() / 2];
4456
4457 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4458 string plaintext;
4459 ErrorCode error = Finish(message, &plaintext);
4460 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
4461 // This is the expected error, we can exit the test now.
4462 return;
4463 } else {
4464 // Very small chance we got valid decryption, so try again.
4465 ASSERT_EQ(error, ErrorCode::OK);
4466 }
4467 }
4468 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07004469}
4470
4471vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4472 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004473 EXPECT_TRUE(iv);
4474 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004475}
4476
4477/*
4478 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4479 *
4480 * Verifies that AES CTR mode works.
4481 */
4482TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4483 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4484 .Authorization(TAG_NO_AUTH_REQUIRED)
4485 .AesEncryptionKey(128)
4486 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4487 .Padding(PaddingMode::NONE)));
4488
4489 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4490
4491 string message = "123";
4492 AuthorizationSet out_params;
4493 string ciphertext1 = EncryptMessage(message, params, &out_params);
4494 vector<uint8_t> iv1 = CopyIv(out_params);
4495 EXPECT_EQ(16U, iv1.size());
4496
4497 EXPECT_EQ(message.size(), ciphertext1.size());
4498
4499 out_params.Clear();
4500 string ciphertext2 = EncryptMessage(message, params, &out_params);
4501 vector<uint8_t> iv2 = CopyIv(out_params);
4502 EXPECT_EQ(16U, iv2.size());
4503
4504 // IVs should be random, so ciphertexts should differ.
4505 EXPECT_NE(ciphertext1, ciphertext2);
4506
4507 auto params_iv1 =
4508 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4509 auto params_iv2 =
4510 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4511
4512 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4513 EXPECT_EQ(message, plaintext);
4514 plaintext = DecryptMessage(ciphertext2, params_iv2);
4515 EXPECT_EQ(message, plaintext);
4516
4517 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4518 plaintext = DecryptMessage(ciphertext1, params_iv2);
4519 EXPECT_NE(message, plaintext);
4520 plaintext = DecryptMessage(ciphertext2, params_iv1);
4521 EXPECT_NE(message, plaintext);
4522}
4523
4524/*
4525 * EncryptionOperationsTest.AesIncremental
4526 *
4527 * Verifies that AES works, all modes, when provided data in various size increments.
4528 */
4529TEST_P(EncryptionOperationsTest, AesIncremental) {
4530 auto block_modes = {
4531 BlockMode::ECB,
4532 BlockMode::CBC,
4533 BlockMode::CTR,
4534 BlockMode::GCM,
4535 };
4536
4537 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4538 .Authorization(TAG_NO_AUTH_REQUIRED)
4539 .AesEncryptionKey(128)
4540 .BlockMode(block_modes)
4541 .Padding(PaddingMode::NONE)
4542 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4543
4544 for (int increment = 1; increment <= 240; ++increment) {
4545 for (auto block_mode : block_modes) {
4546 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004547 auto params =
4548 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4549 if (block_mode == BlockMode::GCM) {
4550 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4551 }
Selene Huang31ab4042020-04-29 04:22:39 -07004552
4553 AuthorizationSet output_params;
4554 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4555
4556 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004557 string to_send;
4558 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004559 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004560 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004561 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4562 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004563
4564 switch (block_mode) {
4565 case BlockMode::GCM:
4566 EXPECT_EQ(message.size() + 16, ciphertext.size());
4567 break;
4568 case BlockMode::CTR:
4569 EXPECT_EQ(message.size(), ciphertext.size());
4570 break;
4571 case BlockMode::CBC:
4572 case BlockMode::ECB:
4573 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4574 break;
4575 }
4576
4577 auto iv = output_params.GetTagValue(TAG_NONCE);
4578 switch (block_mode) {
4579 case BlockMode::CBC:
4580 case BlockMode::GCM:
4581 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004582 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4583 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4584 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004585 break;
4586
4587 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004588 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004589 break;
4590 }
4591
4592 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4593 << "Decrypt begin() failed for block mode " << block_mode;
4594
4595 string plaintext;
4596 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004597 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004598 }
4599 ErrorCode error = Finish(to_send, &plaintext);
4600 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4601 << " and increment " << increment;
4602 if (error == ErrorCode::OK) {
4603 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4604 << block_mode << " and increment " << increment;
4605 }
4606 }
4607 }
4608}
4609
4610struct AesCtrSp80038aTestVector {
4611 const char* key;
4612 const char* nonce;
4613 const char* plaintext;
4614 const char* ciphertext;
4615};
4616
4617// These test vectors are taken from
4618// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4619static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4620 // AES-128
4621 {
4622 "2b7e151628aed2a6abf7158809cf4f3c",
4623 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4624 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4625 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4626 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4627 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4628 },
4629 // AES-192
4630 {
4631 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4632 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4633 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4634 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4635 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4636 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4637 },
4638 // AES-256
4639 {
4640 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4641 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4642 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4643 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4644 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4645 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4646 },
4647};
4648
4649/*
4650 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4651 *
4652 * Verifies AES CTR implementation against SP800-38A test vectors.
4653 */
4654TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4655 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4656 for (size_t i = 0; i < 3; i++) {
4657 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4658 const string key = hex2str(test.key);
4659 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4660 InvalidSizes.end())
4661 continue;
4662 const string nonce = hex2str(test.nonce);
4663 const string plaintext = hex2str(test.plaintext);
4664 const string ciphertext = hex2str(test.ciphertext);
4665 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4666 }
4667}
4668
4669/*
4670 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4671 *
4672 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4673 */
4674TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4675 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4676 .Authorization(TAG_NO_AUTH_REQUIRED)
4677 .AesEncryptionKey(128)
4678 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4679 .Padding(PaddingMode::PKCS7)));
4680 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4681 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4682}
4683
4684/*
4685 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4686 *
4687 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4688 */
4689TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4690 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4691 .Authorization(TAG_NO_AUTH_REQUIRED)
4692 .AesEncryptionKey(128)
4693 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4694 .Authorization(TAG_CALLER_NONCE)
4695 .Padding(PaddingMode::NONE)));
4696
4697 auto params = AuthorizationSetBuilder()
4698 .BlockMode(BlockMode::CTR)
4699 .Padding(PaddingMode::NONE)
4700 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4701 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4702
4703 params = AuthorizationSetBuilder()
4704 .BlockMode(BlockMode::CTR)
4705 .Padding(PaddingMode::NONE)
4706 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4707 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4708
4709 params = AuthorizationSetBuilder()
4710 .BlockMode(BlockMode::CTR)
4711 .Padding(PaddingMode::NONE)
4712 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4713 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4714}
4715
4716/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004717 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004718 *
4719 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4720 */
4721TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4722 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4723 .Authorization(TAG_NO_AUTH_REQUIRED)
4724 .AesEncryptionKey(128)
4725 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4726 .Padding(PaddingMode::NONE)));
4727 // Two-block message.
4728 string message = "12345678901234567890123456789012";
4729 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4730 AuthorizationSet out_params;
4731 string ciphertext1 = EncryptMessage(message, params, &out_params);
4732 vector<uint8_t> iv1 = CopyIv(out_params);
4733 EXPECT_EQ(message.size(), ciphertext1.size());
4734
4735 out_params.Clear();
4736
4737 string ciphertext2 = EncryptMessage(message, params, &out_params);
4738 vector<uint8_t> iv2 = CopyIv(out_params);
4739 EXPECT_EQ(message.size(), ciphertext2.size());
4740
4741 // IVs should be random, so ciphertexts should differ.
4742 EXPECT_NE(ciphertext1, ciphertext2);
4743
4744 params.push_back(TAG_NONCE, iv1);
4745 string plaintext = DecryptMessage(ciphertext1, params);
4746 EXPECT_EQ(message, plaintext);
4747}
4748
4749/*
4750 * EncryptionOperationsTest.AesCallerNonce
4751 *
4752 * Verifies that AES caller-provided nonces work correctly.
4753 */
4754TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4755 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4756 .Authorization(TAG_NO_AUTH_REQUIRED)
4757 .AesEncryptionKey(128)
4758 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4759 .Authorization(TAG_CALLER_NONCE)
4760 .Padding(PaddingMode::NONE)));
4761
4762 string message = "12345678901234567890123456789012";
4763
4764 // Don't specify nonce, should get a random one.
4765 AuthorizationSetBuilder params =
4766 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4767 AuthorizationSet out_params;
4768 string ciphertext = EncryptMessage(message, params, &out_params);
4769 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004770 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004771
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004772 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004773 string plaintext = DecryptMessage(ciphertext, params);
4774 EXPECT_EQ(message, plaintext);
4775
4776 // Now specify a nonce, should also work.
4777 params = AuthorizationSetBuilder()
4778 .BlockMode(BlockMode::CBC)
4779 .Padding(PaddingMode::NONE)
4780 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4781 out_params.Clear();
4782 ciphertext = EncryptMessage(message, params, &out_params);
4783
4784 // Decrypt with correct nonce.
4785 plaintext = DecryptMessage(ciphertext, params);
4786 EXPECT_EQ(message, plaintext);
4787
4788 // Try with wrong nonce.
4789 params = AuthorizationSetBuilder()
4790 .BlockMode(BlockMode::CBC)
4791 .Padding(PaddingMode::NONE)
4792 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4793 plaintext = DecryptMessage(ciphertext, params);
4794 EXPECT_NE(message, plaintext);
4795}
4796
4797/*
4798 * EncryptionOperationsTest.AesCallerNonceProhibited
4799 *
4800 * Verifies that caller-provided nonces are not permitted when not specified in the key
4801 * authorizations.
4802 */
4803TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4804 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4805 .Authorization(TAG_NO_AUTH_REQUIRED)
4806 .AesEncryptionKey(128)
4807 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4808 .Padding(PaddingMode::NONE)));
4809
4810 string message = "12345678901234567890123456789012";
4811
4812 // Don't specify nonce, should get a random one.
4813 AuthorizationSetBuilder params =
4814 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4815 AuthorizationSet out_params;
4816 string ciphertext = EncryptMessage(message, params, &out_params);
4817 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004818 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004819
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004820 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004821 string plaintext = DecryptMessage(ciphertext, params);
4822 EXPECT_EQ(message, plaintext);
4823
4824 // Now specify a nonce, should fail
4825 params = AuthorizationSetBuilder()
4826 .BlockMode(BlockMode::CBC)
4827 .Padding(PaddingMode::NONE)
4828 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4829 out_params.Clear();
4830 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4831}
4832
4833/*
4834 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4835 *
4836 * Verifies that AES GCM mode works.
4837 */
4838TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4839 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4840 .Authorization(TAG_NO_AUTH_REQUIRED)
4841 .AesEncryptionKey(128)
4842 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4843 .Padding(PaddingMode::NONE)
4844 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4845
4846 string aad = "foobar";
4847 string message = "123456789012345678901234567890123456";
4848
4849 auto begin_params = AuthorizationSetBuilder()
4850 .BlockMode(BlockMode::GCM)
4851 .Padding(PaddingMode::NONE)
4852 .Authorization(TAG_MAC_LENGTH, 128);
4853
Selene Huang31ab4042020-04-29 04:22:39 -07004854 // Encrypt
4855 AuthorizationSet begin_out_params;
4856 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4857 << "Begin encrypt";
4858 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004859 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4860 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004861 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4862
4863 // Grab nonce
4864 begin_params.push_back(begin_out_params);
4865
4866 // Decrypt.
4867 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004868 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004869 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004870 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004871 EXPECT_EQ(message.length(), plaintext.length());
4872 EXPECT_EQ(message, plaintext);
4873}
4874
4875/*
4876 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4877 *
4878 * Verifies that AES GCM mode works, even when there's a long delay
4879 * between operations.
4880 */
4881TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4882 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4883 .Authorization(TAG_NO_AUTH_REQUIRED)
4884 .AesEncryptionKey(128)
4885 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4886 .Padding(PaddingMode::NONE)
4887 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4888
4889 string aad = "foobar";
4890 string message = "123456789012345678901234567890123456";
4891
4892 auto begin_params = AuthorizationSetBuilder()
4893 .BlockMode(BlockMode::GCM)
4894 .Padding(PaddingMode::NONE)
4895 .Authorization(TAG_MAC_LENGTH, 128);
4896
Selene Huang31ab4042020-04-29 04:22:39 -07004897 // Encrypt
4898 AuthorizationSet begin_out_params;
4899 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4900 << "Begin encrypt";
4901 string ciphertext;
4902 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004903 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004904 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004905 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004906
4907 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4908
4909 // Grab nonce
4910 begin_params.push_back(begin_out_params);
4911
4912 // Decrypt.
4913 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4914 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004915 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004916 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004917 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004918 sleep(5);
4919 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4920 EXPECT_EQ(message.length(), plaintext.length());
4921 EXPECT_EQ(message, plaintext);
4922}
4923
4924/*
4925 * EncryptionOperationsTest.AesGcmDifferentNonces
4926 *
4927 * Verifies that encrypting the same data with different nonces produces different outputs.
4928 */
4929TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4930 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4931 .Authorization(TAG_NO_AUTH_REQUIRED)
4932 .AesEncryptionKey(128)
4933 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4934 .Padding(PaddingMode::NONE)
4935 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4936 .Authorization(TAG_CALLER_NONCE)));
4937
4938 string aad = "foobar";
4939 string message = "123456789012345678901234567890123456";
4940 string nonce1 = "000000000000";
4941 string nonce2 = "111111111111";
4942 string nonce3 = "222222222222";
4943
4944 string ciphertext1 =
4945 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4946 string ciphertext2 =
4947 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4948 string ciphertext3 =
4949 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4950
4951 ASSERT_NE(ciphertext1, ciphertext2);
4952 ASSERT_NE(ciphertext1, ciphertext3);
4953 ASSERT_NE(ciphertext2, ciphertext3);
4954}
4955
4956/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004957 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4958 *
4959 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4960 */
4961TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4962 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4963 .Authorization(TAG_NO_AUTH_REQUIRED)
4964 .AesEncryptionKey(128)
4965 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4966 .Padding(PaddingMode::NONE)
4967 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4968
4969 string aad = "foobar";
4970 string message = "123456789012345678901234567890123456";
4971
4972 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4973 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4974 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4975
4976 ASSERT_NE(ciphertext1, ciphertext2);
4977 ASSERT_NE(ciphertext1, ciphertext3);
4978 ASSERT_NE(ciphertext2, ciphertext3);
4979}
4980
4981/*
Selene Huang31ab4042020-04-29 04:22:39 -07004982 * EncryptionOperationsTest.AesGcmTooShortTag
4983 *
4984 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4985 */
4986TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4987 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4988 .Authorization(TAG_NO_AUTH_REQUIRED)
4989 .AesEncryptionKey(128)
4990 .BlockMode(BlockMode::GCM)
4991 .Padding(PaddingMode::NONE)
4992 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4993 string message = "123456789012345678901234567890123456";
4994 auto params = AuthorizationSetBuilder()
4995 .BlockMode(BlockMode::GCM)
4996 .Padding(PaddingMode::NONE)
4997 .Authorization(TAG_MAC_LENGTH, 96);
4998
4999 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5000}
5001
5002/*
5003 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
5004 *
5005 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
5006 */
5007TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
5008 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5009 .Authorization(TAG_NO_AUTH_REQUIRED)
5010 .AesEncryptionKey(128)
5011 .BlockMode(BlockMode::GCM)
5012 .Padding(PaddingMode::NONE)
5013 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5014 string aad = "foobar";
5015 string message = "123456789012345678901234567890123456";
5016 auto params = AuthorizationSetBuilder()
5017 .BlockMode(BlockMode::GCM)
5018 .Padding(PaddingMode::NONE)
5019 .Authorization(TAG_MAC_LENGTH, 128);
5020
Selene Huang31ab4042020-04-29 04:22:39 -07005021 // Encrypt
5022 AuthorizationSet begin_out_params;
5023 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5024 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005025 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005026
5027 AuthorizationSet finish_out_params;
5028 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005029 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5030 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005031
5032 params = AuthorizationSetBuilder()
5033 .Authorizations(begin_out_params)
5034 .BlockMode(BlockMode::GCM)
5035 .Padding(PaddingMode::NONE)
5036 .Authorization(TAG_MAC_LENGTH, 96);
5037
5038 // Decrypt.
5039 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5040}
5041
5042/*
5043 * EncryptionOperationsTest.AesGcmCorruptKey
5044 *
5045 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5046 */
5047TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5048 const uint8_t nonce_bytes[] = {
5049 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5050 };
5051 string nonce = make_string(nonce_bytes);
5052 const uint8_t ciphertext_bytes[] = {
5053 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5054 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5055 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5056 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5057 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5058 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5059 };
5060 string ciphertext = make_string(ciphertext_bytes);
5061
5062 auto params = AuthorizationSetBuilder()
5063 .BlockMode(BlockMode::GCM)
5064 .Padding(PaddingMode::NONE)
5065 .Authorization(TAG_MAC_LENGTH, 128)
5066 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5067
5068 auto import_params = AuthorizationSetBuilder()
5069 .Authorization(TAG_NO_AUTH_REQUIRED)
5070 .AesEncryptionKey(128)
5071 .BlockMode(BlockMode::GCM)
5072 .Padding(PaddingMode::NONE)
5073 .Authorization(TAG_CALLER_NONCE)
5074 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5075
5076 // Import correct key and decrypt
5077 const uint8_t key_bytes[] = {
5078 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5079 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5080 };
5081 string key = make_string(key_bytes);
5082 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5083 string plaintext = DecryptMessage(ciphertext, params);
5084 CheckedDeleteKey();
5085
5086 // Corrupt key and attempt to decrypt
5087 key[0] = 0;
5088 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5089 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5090 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5091 CheckedDeleteKey();
5092}
5093
5094/*
5095 * EncryptionOperationsTest.AesGcmAadNoData
5096 *
5097 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5098 * encrypt.
5099 */
5100TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5101 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5102 .Authorization(TAG_NO_AUTH_REQUIRED)
5103 .AesEncryptionKey(128)
5104 .BlockMode(BlockMode::GCM)
5105 .Padding(PaddingMode::NONE)
5106 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5107
5108 string aad = "1234567890123456";
5109 auto params = AuthorizationSetBuilder()
5110 .BlockMode(BlockMode::GCM)
5111 .Padding(PaddingMode::NONE)
5112 .Authorization(TAG_MAC_LENGTH, 128);
5113
Selene Huang31ab4042020-04-29 04:22:39 -07005114 // Encrypt
5115 AuthorizationSet begin_out_params;
5116 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5117 string ciphertext;
5118 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005119 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5120 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005121 EXPECT_TRUE(finish_out_params.empty());
5122
5123 // Grab nonce
5124 params.push_back(begin_out_params);
5125
5126 // Decrypt.
5127 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005128 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005129 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005130 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005131
5132 EXPECT_TRUE(finish_out_params.empty());
5133
5134 EXPECT_EQ("", plaintext);
5135}
5136
5137/*
5138 * EncryptionOperationsTest.AesGcmMultiPartAad
5139 *
5140 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5141 * chunks.
5142 */
5143TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5144 const size_t tag_bits = 128;
5145 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5146 .Authorization(TAG_NO_AUTH_REQUIRED)
5147 .AesEncryptionKey(128)
5148 .BlockMode(BlockMode::GCM)
5149 .Padding(PaddingMode::NONE)
5150 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5151
5152 string message = "123456789012345678901234567890123456";
5153 auto begin_params = AuthorizationSetBuilder()
5154 .BlockMode(BlockMode::GCM)
5155 .Padding(PaddingMode::NONE)
5156 .Authorization(TAG_MAC_LENGTH, tag_bits);
5157 AuthorizationSet begin_out_params;
5158
Selene Huang31ab4042020-04-29 04:22:39 -07005159 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5160
5161 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005162 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5163 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005164 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005165 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5166 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005167
Selene Huang31ab4042020-04-29 04:22:39 -07005168 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005169 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005170
5171 // Grab nonce.
5172 begin_params.push_back(begin_out_params);
5173
5174 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005175 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005176 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005177 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005178 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005179 EXPECT_EQ(message, plaintext);
5180}
5181
5182/*
5183 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5184 *
5185 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5186 */
5187TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5188 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5189 .Authorization(TAG_NO_AUTH_REQUIRED)
5190 .AesEncryptionKey(128)
5191 .BlockMode(BlockMode::GCM)
5192 .Padding(PaddingMode::NONE)
5193 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5194
5195 string message = "123456789012345678901234567890123456";
5196 auto begin_params = AuthorizationSetBuilder()
5197 .BlockMode(BlockMode::GCM)
5198 .Padding(PaddingMode::NONE)
5199 .Authorization(TAG_MAC_LENGTH, 128);
5200 AuthorizationSet begin_out_params;
5201
Selene Huang31ab4042020-04-29 04:22:39 -07005202 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5203
Shawn Willden92d79c02021-02-19 07:31:55 -07005204 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005205 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005206 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5207 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005208
David Drysdaled2cc8c22021-04-15 13:29:45 +01005209 // The failure should have already cancelled the operation.
5210 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5211
Shawn Willden92d79c02021-02-19 07:31:55 -07005212 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005213}
5214
5215/*
5216 * EncryptionOperationsTest.AesGcmBadAad
5217 *
5218 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5219 */
5220TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5221 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5222 .Authorization(TAG_NO_AUTH_REQUIRED)
5223 .AesEncryptionKey(128)
5224 .BlockMode(BlockMode::GCM)
5225 .Padding(PaddingMode::NONE)
5226 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5227
5228 string message = "12345678901234567890123456789012";
5229 auto begin_params = AuthorizationSetBuilder()
5230 .BlockMode(BlockMode::GCM)
5231 .Padding(PaddingMode::NONE)
5232 .Authorization(TAG_MAC_LENGTH, 128);
5233
Selene Huang31ab4042020-04-29 04:22:39 -07005234 // Encrypt
5235 AuthorizationSet begin_out_params;
5236 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005237 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005238 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005239 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005240
5241 // Grab nonce
5242 begin_params.push_back(begin_out_params);
5243
Selene Huang31ab4042020-04-29 04:22:39 -07005244 // Decrypt.
5245 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005246 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005247 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005248 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005249}
5250
5251/*
5252 * EncryptionOperationsTest.AesGcmWrongNonce
5253 *
5254 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5255 */
5256TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5257 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5258 .Authorization(TAG_NO_AUTH_REQUIRED)
5259 .AesEncryptionKey(128)
5260 .BlockMode(BlockMode::GCM)
5261 .Padding(PaddingMode::NONE)
5262 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5263
5264 string message = "12345678901234567890123456789012";
5265 auto begin_params = AuthorizationSetBuilder()
5266 .BlockMode(BlockMode::GCM)
5267 .Padding(PaddingMode::NONE)
5268 .Authorization(TAG_MAC_LENGTH, 128);
5269
Selene Huang31ab4042020-04-29 04:22:39 -07005270 // Encrypt
5271 AuthorizationSet begin_out_params;
5272 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005273 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005274 string ciphertext;
5275 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005276 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005277
5278 // Wrong nonce
5279 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5280
5281 // Decrypt.
5282 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005283 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005284 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005285 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005286
5287 // With wrong nonce, should have gotten garbage plaintext (or none).
5288 EXPECT_NE(message, plaintext);
5289}
5290
5291/*
5292 * EncryptionOperationsTest.AesGcmCorruptTag
5293 *
5294 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5295 */
5296TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5297 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5298 .Authorization(TAG_NO_AUTH_REQUIRED)
5299 .AesEncryptionKey(128)
5300 .BlockMode(BlockMode::GCM)
5301 .Padding(PaddingMode::NONE)
5302 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5303
5304 string aad = "1234567890123456";
5305 string message = "123456789012345678901234567890123456";
5306
5307 auto params = AuthorizationSetBuilder()
5308 .BlockMode(BlockMode::GCM)
5309 .Padding(PaddingMode::NONE)
5310 .Authorization(TAG_MAC_LENGTH, 128);
5311
Selene Huang31ab4042020-04-29 04:22:39 -07005312 // Encrypt
5313 AuthorizationSet begin_out_params;
5314 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005315 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005316 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005317 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005318
5319 // Corrupt tag
5320 ++(*ciphertext.rbegin());
5321
5322 // Grab nonce
5323 params.push_back(begin_out_params);
5324
5325 // Decrypt.
5326 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005327 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005328 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005329 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005330}
5331
5332/*
5333 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5334 *
5335 * Verifies that 3DES is basically functional.
5336 */
5337TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5338 auto auths = AuthorizationSetBuilder()
5339 .TripleDesEncryptionKey(168)
5340 .BlockMode(BlockMode::ECB)
5341 .Authorization(TAG_NO_AUTH_REQUIRED)
5342 .Padding(PaddingMode::NONE);
5343
5344 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5345 // Two-block message.
5346 string message = "1234567890123456";
5347 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5348 string ciphertext1 = EncryptMessage(message, inParams);
5349 EXPECT_EQ(message.size(), ciphertext1.size());
5350
5351 string ciphertext2 = EncryptMessage(string(message), inParams);
5352 EXPECT_EQ(message.size(), ciphertext2.size());
5353
5354 // ECB is deterministic.
5355 EXPECT_EQ(ciphertext1, ciphertext2);
5356
5357 string plaintext = DecryptMessage(ciphertext1, inParams);
5358 EXPECT_EQ(message, plaintext);
5359}
5360
5361/*
5362 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5363 *
5364 * Verifies that CBC keys reject ECB usage.
5365 */
5366TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5367 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5368 .TripleDesEncryptionKey(168)
5369 .BlockMode(BlockMode::CBC)
5370 .Authorization(TAG_NO_AUTH_REQUIRED)
5371 .Padding(PaddingMode::NONE)));
5372
5373 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5374 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5375}
5376
5377/*
5378 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5379 *
5380 * Tests ECB mode with PKCS#7 padding, various message sizes.
5381 */
5382TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5383 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5384 .TripleDesEncryptionKey(168)
5385 .BlockMode(BlockMode::ECB)
5386 .Authorization(TAG_NO_AUTH_REQUIRED)
5387 .Padding(PaddingMode::PKCS7)));
5388
5389 for (size_t i = 0; i < 32; ++i) {
5390 string message(i, 'a');
5391 auto inParams =
5392 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5393 string ciphertext = EncryptMessage(message, inParams);
5394 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5395 string plaintext = DecryptMessage(ciphertext, inParams);
5396 EXPECT_EQ(message, plaintext);
5397 }
5398}
5399
5400/*
5401 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5402 *
5403 * Verifies that keys configured for no padding reject PKCS7 padding
5404 */
5405TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5406 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5407 .TripleDesEncryptionKey(168)
5408 .BlockMode(BlockMode::ECB)
5409 .Authorization(TAG_NO_AUTH_REQUIRED)
5410 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005411 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5412 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005413}
5414
5415/*
5416 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5417 *
5418 * Verifies that corrupted padding is detected.
5419 */
5420TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5421 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5422 .TripleDesEncryptionKey(168)
5423 .BlockMode(BlockMode::ECB)
5424 .Authorization(TAG_NO_AUTH_REQUIRED)
5425 .Padding(PaddingMode::PKCS7)));
5426
5427 string message = "a";
5428 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5429 EXPECT_EQ(8U, ciphertext.size());
5430 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005431
5432 AuthorizationSetBuilder begin_params;
5433 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5434 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07005435
5436 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5437 ++ciphertext[ciphertext.size() / 2];
5438
5439 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5440 string plaintext;
5441 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5442 ErrorCode error = Finish(&plaintext);
5443 if (error == ErrorCode::INVALID_ARGUMENT) {
5444 // This is the expected error, we can exit the test now.
5445 return;
5446 } else {
5447 // Very small chance we got valid decryption, so try again.
5448 ASSERT_EQ(error, ErrorCode::OK);
5449 }
5450 }
5451 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005452}
5453
5454struct TripleDesTestVector {
5455 const char* name;
5456 const KeyPurpose purpose;
5457 const BlockMode block_mode;
5458 const PaddingMode padding_mode;
5459 const char* key;
5460 const char* iv;
5461 const char* input;
5462 const char* output;
5463};
5464
5465// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5466// of the NIST vectors are multiples of the block size.
5467static const TripleDesTestVector kTripleDesTestVectors[] = {
5468 {
5469 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5470 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5471 "", // IV
5472 "329d86bdf1bc5af4", // input
5473 "d946c2756d78633f", // output
5474 },
5475 {
5476 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5477 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5478 "", // IV
5479 "6b1540781b01ce1997adae102dbf3c5b", // input
5480 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5481 },
5482 {
5483 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5484 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5485 "", // IV
5486 "6daad94ce08acfe7", // input
5487 "660e7d32dcc90e79", // output
5488 },
5489 {
5490 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5491 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5492 "", // IV
5493 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5494 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5495 },
5496 {
5497 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5498 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5499 "43f791134c5647ba", // IV
5500 "dcc153cef81d6f24", // input
5501 "92538bd8af18d3ba", // output
5502 },
5503 {
5504 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5505 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5506 "c2e999cb6249023c", // IV
5507 "c689aee38a301bb316da75db36f110b5", // input
5508 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5509 },
5510 {
5511 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5512 PaddingMode::PKCS7,
5513 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5514 "c2e999cb6249023c", // IV
5515 "c689aee38a301bb316da75db36f110b500", // input
5516 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5517 },
5518 {
5519 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5520 PaddingMode::PKCS7,
5521 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5522 "c2e999cb6249023c", // IV
5523 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5524 "c689aee38a301bb316da75db36f110b500", // output
5525 },
5526 {
5527 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5528 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5529 "41746c7e442d3681", // IV
5530 "c53a7b0ec40600fe", // input
5531 "d4f00eb455de1034", // output
5532 },
5533 {
5534 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5535 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5536 "3982bc02c3727d45", // IV
5537 "6006f10adef52991fcc777a1238bbb65", // input
5538 "edae09288e9e3bc05746d872b48e3b29", // output
5539 },
5540};
5541
5542/*
5543 * EncryptionOperationsTest.TripleDesTestVector
5544 *
5545 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5546 */
5547TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5548 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5549 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5550 SCOPED_TRACE(test->name);
5551 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5552 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5553 hex2str(test->output));
5554 }
5555}
5556
5557/*
5558 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5559 *
5560 * Validates CBC mode functionality.
5561 */
5562TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5563 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5564 .TripleDesEncryptionKey(168)
5565 .BlockMode(BlockMode::CBC)
5566 .Authorization(TAG_NO_AUTH_REQUIRED)
5567 .Padding(PaddingMode::NONE)));
5568
5569 ASSERT_GT(key_blob_.size(), 0U);
5570
5571 // Two-block message.
5572 string message = "1234567890123456";
5573 vector<uint8_t> iv1;
5574 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5575 EXPECT_EQ(message.size(), ciphertext1.size());
5576
5577 vector<uint8_t> iv2;
5578 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5579 EXPECT_EQ(message.size(), ciphertext2.size());
5580
5581 // IVs should be random, so ciphertexts should differ.
5582 EXPECT_NE(iv1, iv2);
5583 EXPECT_NE(ciphertext1, ciphertext2);
5584
5585 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5586 EXPECT_EQ(message, plaintext);
5587}
5588
5589/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005590 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5591 *
5592 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5593 */
5594TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5595 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5596 .TripleDesEncryptionKey(168)
5597 .BlockMode(BlockMode::CBC)
5598 .Authorization(TAG_NO_AUTH_REQUIRED)
5599 .Authorization(TAG_CALLER_NONCE)
5600 .Padding(PaddingMode::NONE)));
5601 auto params = AuthorizationSetBuilder()
5602 .BlockMode(BlockMode::CBC)
5603 .Padding(PaddingMode::NONE)
5604 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5605 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5606}
5607
5608/*
Selene Huang31ab4042020-04-29 04:22:39 -07005609 * EncryptionOperationsTest.TripleDesCallerIv
5610 *
5611 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5612 */
5613TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5614 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5615 .TripleDesEncryptionKey(168)
5616 .BlockMode(BlockMode::CBC)
5617 .Authorization(TAG_NO_AUTH_REQUIRED)
5618 .Authorization(TAG_CALLER_NONCE)
5619 .Padding(PaddingMode::NONE)));
5620 string message = "1234567890123456";
5621 vector<uint8_t> iv;
5622 // Don't specify IV, should get a random one.
5623 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5624 EXPECT_EQ(message.size(), ciphertext1.size());
5625 EXPECT_EQ(8U, iv.size());
5626
5627 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5628 EXPECT_EQ(message, plaintext);
5629
5630 // Now specify an IV, should also work.
5631 iv = AidlBuf("abcdefgh");
5632 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5633
5634 // Decrypt with correct IV.
5635 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5636 EXPECT_EQ(message, plaintext);
5637
5638 // Now try with wrong IV.
5639 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5640 EXPECT_NE(message, plaintext);
5641}
5642
5643/*
5644 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5645 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005646 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005647 */
5648TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5649 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5650 .TripleDesEncryptionKey(168)
5651 .BlockMode(BlockMode::CBC)
5652 .Authorization(TAG_NO_AUTH_REQUIRED)
5653 .Padding(PaddingMode::NONE)));
5654
5655 string message = "12345678901234567890123456789012";
5656 vector<uint8_t> iv;
5657 // Don't specify nonce, should get a random one.
5658 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5659 EXPECT_EQ(message.size(), ciphertext1.size());
5660 EXPECT_EQ(8U, iv.size());
5661
5662 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5663 EXPECT_EQ(message, plaintext);
5664
5665 // Now specify a nonce, should fail.
5666 auto input_params = AuthorizationSetBuilder()
5667 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5668 .BlockMode(BlockMode::CBC)
5669 .Padding(PaddingMode::NONE);
5670 AuthorizationSet output_params;
5671 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5672 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5673}
5674
5675/*
5676 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5677 *
5678 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5679 */
5680TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5681 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5682 .TripleDesEncryptionKey(168)
5683 .BlockMode(BlockMode::ECB)
5684 .Authorization(TAG_NO_AUTH_REQUIRED)
5685 .Padding(PaddingMode::NONE)));
5686 // Two-block message.
5687 string message = "1234567890123456";
5688 auto begin_params =
5689 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5690 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5691}
5692
5693/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005694 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005695 *
5696 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5697 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005698TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5699 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5700 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5701 .TripleDesEncryptionKey(168)
5702 .BlockMode(blockMode)
5703 .Authorization(TAG_NO_AUTH_REQUIRED)
5704 .Padding(PaddingMode::NONE)));
5705 // Message is slightly shorter than two blocks.
5706 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005707
David Drysdaled2cc8c22021-04-15 13:29:45 +01005708 auto begin_params =
5709 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5710 AuthorizationSet output_params;
5711 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5712 string ciphertext;
5713 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5714
5715 CheckedDeleteKey();
5716 }
Selene Huang31ab4042020-04-29 04:22:39 -07005717}
5718
5719/*
5720 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5721 *
5722 * Verifies that PKCS7 padding works correctly in CBC mode.
5723 */
5724TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5725 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5726 .TripleDesEncryptionKey(168)
5727 .BlockMode(BlockMode::CBC)
5728 .Authorization(TAG_NO_AUTH_REQUIRED)
5729 .Padding(PaddingMode::PKCS7)));
5730
5731 // Try various message lengths; all should work.
5732 for (size_t i = 0; i < 32; ++i) {
5733 string message(i, 'a');
5734 vector<uint8_t> iv;
5735 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5736 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5737 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5738 EXPECT_EQ(message, plaintext);
5739 }
5740}
5741
5742/*
5743 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5744 *
5745 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5746 */
5747TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5748 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5749 .TripleDesEncryptionKey(168)
5750 .BlockMode(BlockMode::CBC)
5751 .Authorization(TAG_NO_AUTH_REQUIRED)
5752 .Padding(PaddingMode::NONE)));
5753
5754 // Try various message lengths; all should fail.
5755 for (size_t i = 0; i < 32; ++i) {
5756 auto begin_params =
5757 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5758 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5759 }
5760}
5761
5762/*
5763 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5764 *
5765 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5766 */
5767TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5768 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5769 .TripleDesEncryptionKey(168)
5770 .BlockMode(BlockMode::CBC)
5771 .Authorization(TAG_NO_AUTH_REQUIRED)
5772 .Padding(PaddingMode::PKCS7)));
5773
5774 string message = "a";
5775 vector<uint8_t> iv;
5776 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5777 EXPECT_EQ(8U, ciphertext.size());
5778 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005779
5780 auto begin_params = AuthorizationSetBuilder()
5781 .BlockMode(BlockMode::CBC)
5782 .Padding(PaddingMode::PKCS7)
5783 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07005784
5785 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5786 ++ciphertext[ciphertext.size() / 2];
5787 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5788 string plaintext;
5789 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5790 ErrorCode error = Finish(&plaintext);
5791 if (error == ErrorCode::INVALID_ARGUMENT) {
5792 // This is the expected error, we can exit the test now.
5793 return;
5794 } else {
5795 // Very small chance we got valid decryption, so try again.
5796 ASSERT_EQ(error, ErrorCode::OK);
5797 }
5798 }
5799 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005800}
5801
5802/*
5803 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5804 *
5805 * Verifies that 3DES CBC works with many different input sizes.
5806 */
5807TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5808 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5809 .TripleDesEncryptionKey(168)
5810 .BlockMode(BlockMode::CBC)
5811 .Authorization(TAG_NO_AUTH_REQUIRED)
5812 .Padding(PaddingMode::NONE)));
5813
5814 int increment = 7;
5815 string message(240, 'a');
5816 AuthorizationSet input_params =
5817 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5818 AuthorizationSet output_params;
5819 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5820
5821 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005822 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005823 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005824 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5825 EXPECT_EQ(message.size(), ciphertext.size());
5826
5827 // Move TAG_NONCE into input_params
5828 input_params = output_params;
5829 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5830 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5831 output_params.Clear();
5832
5833 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5834 string plaintext;
5835 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005836 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005837 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5838 EXPECT_EQ(ciphertext.size(), plaintext.size());
5839 EXPECT_EQ(message, plaintext);
5840}
5841
5842INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5843
5844typedef KeyMintAidlTestBase MaxOperationsTest;
5845
5846/*
5847 * MaxOperationsTest.TestLimitAes
5848 *
5849 * Verifies that the max uses per boot tag works correctly with AES keys.
5850 */
5851TEST_P(MaxOperationsTest, TestLimitAes) {
5852 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5853
5854 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5855 .Authorization(TAG_NO_AUTH_REQUIRED)
5856 .AesEncryptionKey(128)
5857 .EcbMode()
5858 .Padding(PaddingMode::NONE)
5859 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5860
5861 string message = "1234567890123456";
5862
5863 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5864
5865 EncryptMessage(message, params);
5866 EncryptMessage(message, params);
5867 EncryptMessage(message, params);
5868
5869 // Fourth time should fail.
5870 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5871}
5872
5873/*
Qi Wud22ec842020-11-26 13:27:53 +08005874 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005875 *
5876 * Verifies that the max uses per boot tag works correctly with RSA keys.
5877 */
5878TEST_P(MaxOperationsTest, TestLimitRsa) {
5879 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5880
5881 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5882 .Authorization(TAG_NO_AUTH_REQUIRED)
5883 .RsaSigningKey(1024, 65537)
5884 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005885 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5886 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005887
5888 string message = "1234567890123456";
5889
5890 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5891
5892 SignMessage(message, params);
5893 SignMessage(message, params);
5894 SignMessage(message, params);
5895
5896 // Fourth time should fail.
5897 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5898}
5899
5900INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5901
Qi Wud22ec842020-11-26 13:27:53 +08005902typedef KeyMintAidlTestBase UsageCountLimitTest;
5903
5904/*
Qi Wubeefae42021-01-28 23:16:37 +08005905 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005906 *
Qi Wubeefae42021-01-28 23:16:37 +08005907 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005908 */
Qi Wubeefae42021-01-28 23:16:37 +08005909TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005910 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5911
5912 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5913 .Authorization(TAG_NO_AUTH_REQUIRED)
5914 .AesEncryptionKey(128)
5915 .EcbMode()
5916 .Padding(PaddingMode::NONE)
5917 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5918
5919 // Check the usage count limit tag appears in the authorizations.
5920 AuthorizationSet auths;
5921 for (auto& entry : key_characteristics_) {
5922 auths.push_back(AuthorizationSet(entry.authorizations));
5923 }
5924 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5925 << "key usage count limit " << 1U << " missing";
5926
5927 string message = "1234567890123456";
5928 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5929
Qi Wubeefae42021-01-28 23:16:37 +08005930 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5931 AuthorizationSet keystore_auths =
5932 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5933
Qi Wud22ec842020-11-26 13:27:53 +08005934 // First usage of AES key should work.
5935 EncryptMessage(message, params);
5936
Qi Wud22ec842020-11-26 13:27:53 +08005937 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5938 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5939 // must be invalidated from secure storage (such as RPMB partition).
5940 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5941 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005942 // Usage count limit tag is enforced by keystore, keymint does nothing.
5943 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005944 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5945 }
5946}
5947
5948/*
Qi Wubeefae42021-01-28 23:16:37 +08005949 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005950 *
Qi Wubeefae42021-01-28 23:16:37 +08005951 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005952 */
Qi Wubeefae42021-01-28 23:16:37 +08005953TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5954 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5955
5956 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5957 .Authorization(TAG_NO_AUTH_REQUIRED)
5958 .AesEncryptionKey(128)
5959 .EcbMode()
5960 .Padding(PaddingMode::NONE)
5961 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5962
5963 // Check the usage count limit tag appears in the authorizations.
5964 AuthorizationSet auths;
5965 for (auto& entry : key_characteristics_) {
5966 auths.push_back(AuthorizationSet(entry.authorizations));
5967 }
5968 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5969 << "key usage count limit " << 3U << " missing";
5970
5971 string message = "1234567890123456";
5972 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5973
5974 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5975 AuthorizationSet keystore_auths =
5976 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5977
5978 EncryptMessage(message, params);
5979 EncryptMessage(message, params);
5980 EncryptMessage(message, params);
5981
5982 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5983 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5984 // must be invalidated from secure storage (such as RPMB partition).
5985 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5986 } else {
5987 // Usage count limit tag is enforced by keystore, keymint does nothing.
5988 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5989 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5990 }
5991}
5992
5993/*
5994 * UsageCountLimitTest.TestSingleUseRsa
5995 *
5996 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5997 */
5998TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005999 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6000
6001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6002 .Authorization(TAG_NO_AUTH_REQUIRED)
6003 .RsaSigningKey(1024, 65537)
6004 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006005 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6006 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08006007
6008 // Check the usage count limit tag appears in the authorizations.
6009 AuthorizationSet auths;
6010 for (auto& entry : key_characteristics_) {
6011 auths.push_back(AuthorizationSet(entry.authorizations));
6012 }
6013 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6014 << "key usage count limit " << 1U << " missing";
6015
6016 string message = "1234567890123456";
6017 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6018
Qi Wubeefae42021-01-28 23:16:37 +08006019 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6020 AuthorizationSet keystore_auths =
6021 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6022
Qi Wud22ec842020-11-26 13:27:53 +08006023 // First usage of RSA key should work.
6024 SignMessage(message, params);
6025
Qi Wud22ec842020-11-26 13:27:53 +08006026 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6027 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6028 // must be invalidated from secure storage (such as RPMB partition).
6029 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6030 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006031 // Usage count limit tag is enforced by keystore, keymint does nothing.
6032 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
6033 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6034 }
6035}
6036
6037/*
6038 * UsageCountLimitTest.TestLimitUseRsa
6039 *
6040 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6041 */
6042TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
6043 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6044
6045 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6046 .Authorization(TAG_NO_AUTH_REQUIRED)
6047 .RsaSigningKey(1024, 65537)
6048 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006049 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6050 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006051
6052 // Check the usage count limit tag appears in the authorizations.
6053 AuthorizationSet auths;
6054 for (auto& entry : key_characteristics_) {
6055 auths.push_back(AuthorizationSet(entry.authorizations));
6056 }
6057 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6058 << "key usage count limit " << 3U << " missing";
6059
6060 string message = "1234567890123456";
6061 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6062
6063 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6064 AuthorizationSet keystore_auths =
6065 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6066
6067 SignMessage(message, params);
6068 SignMessage(message, params);
6069 SignMessage(message, params);
6070
6071 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6072 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6073 // must be invalidated from secure storage (such as RPMB partition).
6074 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6075 } else {
6076 // Usage count limit tag is enforced by keystore, keymint does nothing.
6077 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006078 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6079 }
6080}
6081
Qi Wu8e727f72021-02-11 02:49:33 +08006082/*
6083 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6084 *
6085 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6086 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6087 * in hardware.
6088 */
6089TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
6090 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6091
6092 auto error = GenerateKey(AuthorizationSetBuilder()
6093 .RsaSigningKey(2048, 65537)
6094 .Digest(Digest::NONE)
6095 .Padding(PaddingMode::NONE)
6096 .Authorization(TAG_NO_AUTH_REQUIRED)
6097 .Authorization(TAG_ROLLBACK_RESISTANCE)
6098 .SetDefaultValidity());
6099 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6100
6101 if (error == ErrorCode::OK) {
6102 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6103 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6104 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6105 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6106
6107 // The KeyMint should also enforce single use key in hardware when it supports rollback
6108 // resistance.
6109 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6110 .Authorization(TAG_NO_AUTH_REQUIRED)
6111 .RsaSigningKey(1024, 65537)
6112 .NoDigestOrPadding()
6113 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6114 .SetDefaultValidity()));
6115
6116 // Check the usage count limit tag appears in the hardware authorizations.
6117 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6118 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6119 << "key usage count limit " << 1U << " missing";
6120
6121 string message = "1234567890123456";
6122 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6123
6124 // First usage of RSA key should work.
6125 SignMessage(message, params);
6126
6127 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6128 // must be invalidated from secure storage (such as RPMB partition).
6129 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6130 }
6131}
6132
Qi Wud22ec842020-11-26 13:27:53 +08006133INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6134
David Drysdale7de9feb2021-03-05 14:56:19 +00006135typedef KeyMintAidlTestBase GetHardwareInfoTest;
6136
6137TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6138 // Retrieving hardware info should give the same result each time.
6139 KeyMintHardwareInfo info;
6140 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6141 KeyMintHardwareInfo info2;
6142 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6143 EXPECT_EQ(info, info2);
6144}
6145
6146INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6147
Selene Huang31ab4042020-04-29 04:22:39 -07006148typedef KeyMintAidlTestBase AddEntropyTest;
6149
6150/*
6151 * AddEntropyTest.AddEntropy
6152 *
6153 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6154 * is actually added.
6155 */
6156TEST_P(AddEntropyTest, AddEntropy) {
6157 string data = "foo";
6158 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6159}
6160
6161/*
6162 * AddEntropyTest.AddEmptyEntropy
6163 *
6164 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6165 */
6166TEST_P(AddEntropyTest, AddEmptyEntropy) {
6167 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6168}
6169
6170/*
6171 * AddEntropyTest.AddLargeEntropy
6172 *
6173 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6174 */
6175TEST_P(AddEntropyTest, AddLargeEntropy) {
6176 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6177}
6178
David Drysdalebb3d85e2021-04-13 11:15:51 +01006179/*
6180 * AddEntropyTest.AddTooLargeEntropy
6181 *
6182 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6183 */
6184TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6185 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6186 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6187}
6188
Selene Huang31ab4042020-04-29 04:22:39 -07006189INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6190
Selene Huang31ab4042020-04-29 04:22:39 -07006191typedef KeyMintAidlTestBase KeyDeletionTest;
6192
6193/**
6194 * KeyDeletionTest.DeleteKey
6195 *
6196 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6197 * valid key blob.
6198 */
6199TEST_P(KeyDeletionTest, DeleteKey) {
6200 auto error = GenerateKey(AuthorizationSetBuilder()
6201 .RsaSigningKey(2048, 65537)
6202 .Digest(Digest::NONE)
6203 .Padding(PaddingMode::NONE)
6204 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006205 .Authorization(TAG_ROLLBACK_RESISTANCE)
6206 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006207 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6208
6209 // Delete must work if rollback protection is implemented
6210 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006211 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006212 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6213
6214 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6215
6216 string message = "12345678901234567890123456789012";
6217 AuthorizationSet begin_out_params;
6218 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6219 Begin(KeyPurpose::SIGN, key_blob_,
6220 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6221 &begin_out_params));
6222 AbortIfNeeded();
6223 key_blob_ = AidlBuf();
6224 }
6225}
6226
6227/**
6228 * KeyDeletionTest.DeleteInvalidKey
6229 *
6230 * This test checks that the HAL excepts invalid key blobs..
6231 */
6232TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6233 // Generate key just to check if rollback protection is implemented
6234 auto error = GenerateKey(AuthorizationSetBuilder()
6235 .RsaSigningKey(2048, 65537)
6236 .Digest(Digest::NONE)
6237 .Padding(PaddingMode::NONE)
6238 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006239 .Authorization(TAG_ROLLBACK_RESISTANCE)
6240 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006241 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6242
6243 // Delete must work if rollback protection is implemented
6244 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006245 AuthorizationSet enforced(SecLevelAuthorizations());
6246 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006247
6248 // Delete the key we don't care about the result at this point.
6249 DeleteKey();
6250
6251 // Now create an invalid key blob and delete it.
6252 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6253
6254 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6255 }
6256}
6257
6258/**
6259 * KeyDeletionTest.DeleteAllKeys
6260 *
6261 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6262 *
6263 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6264 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6265 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6266 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6267 * credentials stored in Keystore/Keymint.
6268 */
6269TEST_P(KeyDeletionTest, DeleteAllKeys) {
6270 if (!arm_deleteAllKeys) return;
6271 auto error = GenerateKey(AuthorizationSetBuilder()
6272 .RsaSigningKey(2048, 65537)
6273 .Digest(Digest::NONE)
6274 .Padding(PaddingMode::NONE)
6275 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06006276 .Authorization(TAG_ROLLBACK_RESISTANCE)
6277 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006278 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6279
6280 // Delete must work if rollback protection is implemented
6281 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006282 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006283 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6284
6285 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6286
6287 string message = "12345678901234567890123456789012";
6288 AuthorizationSet begin_out_params;
6289
6290 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6291 Begin(KeyPurpose::SIGN, key_blob_,
6292 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6293 &begin_out_params));
6294 AbortIfNeeded();
6295 key_blob_ = AidlBuf();
6296 }
6297}
6298
6299INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6300
David Drysdaled2cc8c22021-04-15 13:29:45 +01006301typedef KeyMintAidlTestBase KeyUpgradeTest;
6302
6303/**
6304 * KeyUpgradeTest.UpgradeInvalidKey
6305 *
6306 * This test checks that the HAL excepts invalid key blobs..
6307 */
6308TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6309 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6310
6311 std::vector<uint8_t> new_blob;
6312 Status result = keymint_->upgradeKey(key_blob,
6313 AuthorizationSetBuilder()
6314 .Authorization(TAG_APPLICATION_ID, "clientid")
6315 .Authorization(TAG_APPLICATION_DATA, "appdata")
6316 .vector_data(),
6317 &new_blob);
6318 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6319}
6320
6321INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6322
Selene Huang31ab4042020-04-29 04:22:39 -07006323using UpgradeKeyTest = KeyMintAidlTestBase;
6324
6325/*
6326 * UpgradeKeyTest.UpgradeKey
6327 *
6328 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6329 */
6330TEST_P(UpgradeKeyTest, UpgradeKey) {
6331 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6332 .AesEncryptionKey(128)
6333 .Padding(PaddingMode::NONE)
6334 .Authorization(TAG_NO_AUTH_REQUIRED)));
6335
6336 auto result = UpgradeKey(key_blob_);
6337
6338 // Key doesn't need upgrading. Should get okay, but no new key blob.
6339 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6340}
6341
6342INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6343
6344using ClearOperationsTest = KeyMintAidlTestBase;
6345
6346/*
6347 * ClearSlotsTest.TooManyOperations
6348 *
6349 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6350 * operations are started without being finished or aborted. Also verifies
6351 * that aborting the operations clears the operations.
6352 *
6353 */
6354TEST_P(ClearOperationsTest, TooManyOperations) {
6355 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6356 .Authorization(TAG_NO_AUTH_REQUIRED)
6357 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006358 .Padding(PaddingMode::NONE)
6359 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006360
6361 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6362 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006363 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006364 AuthorizationSet out_params;
6365 ErrorCode result;
6366 size_t i;
6367
6368 for (i = 0; i < max_operations; i++) {
6369 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6370 if (ErrorCode::OK != result) {
6371 break;
6372 }
6373 }
6374 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6375 // Try again just in case there's a weird overflow bug
6376 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6377 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6378 for (size_t j = 0; j < i; j++) {
6379 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6380 << "Aboort failed for i = " << j << std::endl;
6381 }
6382 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6383 AbortIfNeeded();
6384}
6385
6386INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6387
6388typedef KeyMintAidlTestBase TransportLimitTest;
6389
6390/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006391 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006392 *
6393 * Verifies that passing input data to finish succeeds as expected.
6394 */
6395TEST_P(TransportLimitTest, LargeFinishInput) {
6396 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6397 .Authorization(TAG_NO_AUTH_REQUIRED)
6398 .AesEncryptionKey(128)
6399 .BlockMode(BlockMode::ECB)
6400 .Padding(PaddingMode::NONE)));
6401
6402 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6403 auto cipher_params =
6404 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6405
6406 AuthorizationSet out_params;
6407 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6408
6409 string plain_message = std::string(1 << msg_size, 'x');
6410 string encrypted_message;
6411 auto rc = Finish(plain_message, &encrypted_message);
6412
6413 EXPECT_EQ(ErrorCode::OK, rc);
6414 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6415 << "Encrypt finish returned OK, but did not consume all of the given input";
6416 cipher_params.push_back(out_params);
6417
6418 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6419
6420 string decrypted_message;
6421 rc = Finish(encrypted_message, &decrypted_message);
6422 EXPECT_EQ(ErrorCode::OK, rc);
6423 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6424 << "Decrypt finish returned OK, did not consume all of the given input";
6425 }
6426}
6427
6428INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6429
David Zeuthene0c40892021-01-08 12:54:11 -05006430typedef KeyMintAidlTestBase KeyAgreementTest;
6431
6432int CurveToOpenSslCurveName(EcCurve curve) {
6433 switch (curve) {
6434 case EcCurve::P_224:
6435 return NID_secp224r1;
6436 case EcCurve::P_256:
6437 return NID_X9_62_prime256v1;
6438 case EcCurve::P_384:
6439 return NID_secp384r1;
6440 case EcCurve::P_521:
6441 return NID_secp521r1;
6442 }
6443}
6444
6445/*
6446 * KeyAgreementTest.Ecdh
6447 *
6448 * Verifies that ECDH works for all curves
6449 */
6450TEST_P(KeyAgreementTest, Ecdh) {
6451 // Because it's possible to use this API with keys on different curves, we
6452 // check all N^2 combinations where N is the number of supported
6453 // curves.
6454 //
6455 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6456 // lot more curves we can be smart about things and just pick |otherCurve| so
6457 // it's not |curve| and that way we end up with only 2*N runs
6458 //
6459 for (auto curve : ValidCurves()) {
6460 for (auto localCurve : ValidCurves()) {
6461 // Generate EC key locally (with access to private key material)
6462 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6463 int curveName = CurveToOpenSslCurveName(localCurve);
6464 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6465 ASSERT_NE(group, nullptr);
6466 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6467 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6468 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6469 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6470
6471 // Get encoded form of the public part of the locally generated key...
6472 unsigned char* p = nullptr;
6473 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6474 ASSERT_GT(encodedPublicKeySize, 0);
6475 vector<uint8_t> encodedPublicKey(
6476 reinterpret_cast<const uint8_t*>(p),
6477 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6478 OPENSSL_free(p);
6479
6480 // Generate EC key in KeyMint (only access to public key material)
6481 vector<uint8_t> challenge = {0x41, 0x42};
6482 EXPECT_EQ(
6483 ErrorCode::OK,
6484 GenerateKey(AuthorizationSetBuilder()
6485 .Authorization(TAG_NO_AUTH_REQUIRED)
6486 .Authorization(TAG_EC_CURVE, curve)
6487 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6488 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6489 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006490 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6491 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006492 << "Failed to generate key";
6493 ASSERT_GT(cert_chain_.size(), 0);
6494 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6495 ASSERT_NE(kmKeyCert, nullptr);
6496 // Check that keyAgreement (bit 4) is set in KeyUsage
6497 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6498 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6499 ASSERT_NE(kmPkey, nullptr);
6500 if (dump_Attestations) {
6501 for (size_t n = 0; n < cert_chain_.size(); n++) {
6502 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6503 }
6504 }
6505
6506 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6507 if (curve != localCurve) {
6508 // If the keys are using different curves KeyMint should fail with
6509 // ErrorCode:INVALID_ARGUMENT. Check that.
6510 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6511 string ZabFromKeyMintStr;
6512 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6513 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6514 &ZabFromKeyMintStr));
6515
6516 } else {
6517 // Otherwise if the keys are using the same curve, it should work.
6518 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6519 string ZabFromKeyMintStr;
6520 EXPECT_EQ(ErrorCode::OK,
6521 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6522 &ZabFromKeyMintStr));
6523 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6524
6525 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6526 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6527 ASSERT_NE(ctx, nullptr);
6528 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6529 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6530 size_t ZabFromTestLen = 0;
6531 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6532 vector<uint8_t> ZabFromTest;
6533 ZabFromTest.resize(ZabFromTestLen);
6534 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6535
6536 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6537 }
6538
6539 CheckedDeleteKey();
6540 }
6541 }
6542}
6543
6544INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6545
David Drysdaled2cc8c22021-04-15 13:29:45 +01006546using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6547
6548// This is a problematic test, as it can render the device under test permanently unusable.
6549// Re-enable and run at your own risk.
6550TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6551 auto result = DestroyAttestationIds();
6552 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6553}
6554
6555INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6556
Shawn Willdend659c7c2021-02-19 14:51:51 -07006557using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006558
David Drysdaledb0dcf52021-05-18 11:43:31 +01006559/*
6560 * EarlyBootKeyTest.CreateEarlyBootKeys
6561 *
6562 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6563 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006564TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01006565 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006566 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6567 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6568
David Drysdaleadfe6112021-05-27 12:00:53 +01006569 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6570 ASSERT_GT(keyData.blob.size(), 0U);
6571 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6572 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6573 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006574 CheckedDeleteKey(&aesKeyData.blob);
6575 CheckedDeleteKey(&hmacKeyData.blob);
6576 CheckedDeleteKey(&rsaKeyData.blob);
6577 CheckedDeleteKey(&ecdsaKeyData.blob);
6578}
6579
David Drysdaledb0dcf52021-05-18 11:43:31 +01006580/*
David Drysdaleadfe6112021-05-27 12:00:53 +01006581 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6582 *
6583 * Verifies that creating an early boot key with attestation succeeds.
6584 */
6585TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6586 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6587 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6588 builder->AttestationChallenge("challenge");
6589 builder->AttestationApplicationId("app_id");
6590 });
6591
6592 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6593 ASSERT_GT(keyData.blob.size(), 0U);
6594 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6595 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6596 }
6597 CheckedDeleteKey(&aesKeyData.blob);
6598 CheckedDeleteKey(&hmacKeyData.blob);
6599 CheckedDeleteKey(&rsaKeyData.blob);
6600 CheckedDeleteKey(&ecdsaKeyData.blob);
6601}
6602
6603/*
6604 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01006605 *
6606 * Verifies that using early boot keys at a later stage fails.
6607 */
6608TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6609 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6610 .Authorization(TAG_NO_AUTH_REQUIRED)
6611 .Authorization(TAG_EARLY_BOOT_ONLY)
6612 .HmacKey(128)
6613 .Digest(Digest::SHA_2_256)
6614 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6615 AuthorizationSet output_params;
6616 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6617 AuthorizationSetBuilder()
6618 .Digest(Digest::SHA_2_256)
6619 .Authorization(TAG_MAC_LENGTH, 256),
6620 &output_params));
6621}
6622
6623/*
6624 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6625 *
6626 * Verifies that importing early boot keys fails.
6627 */
6628TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6629 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6630 .Authorization(TAG_NO_AUTH_REQUIRED)
6631 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01006632 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01006633 .Digest(Digest::SHA_2_256)
6634 .SetDefaultValidity(),
6635 KeyFormat::PKCS8, ec_256_key));
6636}
6637
David Drysdaled2cc8c22021-04-15 13:29:45 +01006638// This is a more comprehensive test, but it can only be run on a machine which is still in early
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006639// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6640// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6641// early boot, so you'll have to reboot between runs.
6642TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6643 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6644 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6645 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6646 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6647 EXPECT_TRUE(
6648 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6649 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6650 EXPECT_TRUE(
6651 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6652
6653 // Should be able to use keys, since early boot has not ended
6654 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6655 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6656 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6657 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6658
6659 // End early boot
6660 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6661 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6662
6663 // Should not be able to use already-created keys.
6664 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6665 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6666 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6667 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6668
6669 CheckedDeleteKey(&aesKeyData.blob);
6670 CheckedDeleteKey(&hmacKeyData.blob);
6671 CheckedDeleteKey(&rsaKeyData.blob);
6672 CheckedDeleteKey(&ecdsaKeyData.blob);
6673
6674 // Should not be able to create new keys
6675 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6676 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6677
6678 CheckedDeleteKey(&aesKeyData.blob);
6679 CheckedDeleteKey(&hmacKeyData.blob);
6680 CheckedDeleteKey(&rsaKeyData.blob);
6681 CheckedDeleteKey(&ecdsaKeyData.blob);
6682}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006683
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006684INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6685
Shawn Willdend659c7c2021-02-19 14:51:51 -07006686using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006687
6688// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6689// between runs... and on most test devices there are no enrolled credentials so it can't be
6690// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6691// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6692// a manual test process, which includes unlocking between runs, which is why it's included here.
6693// Well, that and the fact that it's the only test we can do without also making calls into the
6694// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6695// implications might be, so that may or may not be a solution.
6696TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6697 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6698 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6699
6700 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6701 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6702 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6703 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6704
6705 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006706 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006707 ASSERT_EQ(ErrorCode::OK, rc);
6708 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6709 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6710 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6711 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6712
6713 CheckedDeleteKey(&aesKeyData.blob);
6714 CheckedDeleteKey(&hmacKeyData.blob);
6715 CheckedDeleteKey(&rsaKeyData.blob);
6716 CheckedDeleteKey(&ecdsaKeyData.blob);
6717}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006718
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006719INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6720
Janis Danisevskis24c04702020-12-16 18:28:39 -08006721} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006722
6723int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006724 std::cout << "Testing ";
6725 auto halInstances =
6726 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6727 std::cout << "HAL instances:\n";
6728 for (auto& entry : halInstances) {
6729 std::cout << " " << entry << '\n';
6730 }
6731
Selene Huang31ab4042020-04-29 04:22:39 -07006732 ::testing::InitGoogleTest(&argc, argv);
6733 for (int i = 1; i < argc; ++i) {
6734 if (argv[i][0] == '-') {
6735 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006736 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6737 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006738 }
6739 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006740 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6741 dump_Attestations = true;
6742 } else {
6743 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006744 }
6745 }
6746 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006747 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006748}