blob: 5647db6a073d9b187dd9fe0da15d6123de533e12 [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 Drysdale92464372021-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
David Drysdalebb3d85e2021-04-13 11:15:51 +010072bool check_patchLevels = false;
73
Selene Huang31ab4042020-04-29 04:22:39 -070074template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000075bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
76 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070077 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080078 if (auto p = authorizationValue(ttag, param)) {
79 return *p == expected_value;
80 }
81 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070082 });
83 return (it != set.end());
84}
85
86template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000087bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(),
89 [&](const KeyParameter& param) { return param.tag == tag; });
90 return (it != set.end());
91}
92
93constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
94 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
95 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
96 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
97 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
98 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
99 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
100 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
101 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
102 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
103 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 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
110string hex2str(string a) {
111 string b;
112 size_t num = a.size() / 2;
113 b.resize(num);
114 for (size_t i = 0; i < num; i++) {
115 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
116 }
117 return b;
118}
119
David Drysdaled2cc8c22021-04-15 13:29:45 +0100120string rsa_key = hex2str(
121 // RFC 5208 s5
122 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
123 "020100" // INTEGER length 1 value 0x00 (version)
124 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
125 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
126 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
127 "0500" // NULL (parameters)
128 // } end SEQUENCE (AlgorithmIdentifier)
129 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
130 // RFC 8017 A.1.2
131 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
132 "020100" // INTEGER length 1 value 0x00 (version)
133 "028181" // INTEGER length 0x81 value (modulus) ...
134 "00c6095409047d8634812d5a218176e4"
135 "5c41d60a75b13901f234226cffe77652"
136 "1c5a77b9e389417b71c0b6a44d13afe4"
137 "e4a2805d46c9da2935adb1ff0c1f24ea"
138 "06e62b20d776430a4d435157233c6f91"
139 "6783c30e310fcbd89b85c2d567711697"
140 "85ac12bca244abda72bfb19fc44d27c8"
141 "1e1d92de284f4061edfd99280745ea6d"
142 "25"
143 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
144 "028180" // INTEGER length 0x80 (privateExponent) value...
145 "1be0f04d9cae3718691f035338308e91"
146 "564b55899ffb5084d2460e6630257e05"
147 "b3ceab02972dfabcd6ce5f6ee2589eb6"
148 "7911ed0fac16e43a444b8c861e544a05"
149 "93365772f8baf6b22fc9e3c5f1024b06"
150 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
151 "ace7240290bef16c0b3f7f3cdd64ce3a"
152 "b5912cf6e32f39ab188358afcccd8081"
153 "0241" // INTEGER length 0x41 (prime1)
154 "00e4b49ef50f765d3b24dde01aceaaf1"
155 "30f2c76670a91a61ae08af497b4a82be"
156 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
157 "8c92bfab137fba2285227b83c342ff7c"
158 "55"
159 "0241" // INTEGER length 0x41 (prime2)
160 "00ddabb5839c4c7f6bf3d4183231f005"
161 "b31aa58affdda5c79e4cce217f6bc930"
162 "dbe563d480706c24e9ebfcab28a6cdef"
163 "d324b77e1bf7251b709092c24ff501fd"
164 "91"
165 "0240" // INTEGER length 0x40 (exponent1)
166 "23d4340eda3445d8cd26c14411da6fdc"
167 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
168 "842c1d280405bc2f6c1bea214a1d742a"
169 "b996b35b63a82a5e470fa88dbf823cdd"
170 "0240" // INTEGER length 0x40 (exponent2)
171 "1b7b57449ad30d1518249a5f56bb9829"
172 "4d4b6ac12ffc86940497a5a5837a6cf9"
173 "46262b494526d328c11e1126380fde04"
174 "c24f916dec250892db09a6d77cdba351"
175 "0240" // INTEGER length 0x40 (coefficient)
176 "7762cd8f4d050da56bd591adb515d24d"
177 "7ccd32cca0d05f866d583514bd7324d5"
178 "f33645e8ed8b4a1cb3cc4a1d67987399"
179 "f2a09f5b3fb68c88d5e5d90ac33492d6"
180 // } end SEQUENCE (PrivateKey)
181 // } end SEQUENCE (PrivateKeyInfo)
182);
Selene Huang31ab4042020-04-29 04:22:39 -0700183
Selene Huange5727e62021-04-13 22:41:20 -0700184/*
185 * DER-encoded PKCS#8 format RSA key. Generated using:
186 *
187 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
188 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100189string rsa_2048_key = hex2str(
190 // RFC 5208 s5
191 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
192 "020100" // INTEGER length 1 value 0x00 (version)
193 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
194 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
195 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
196 "0500" // NULL (parameters)
197 // } end SEQUENCE (AlgorithmIdentifier)
198 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
199 // RFC 8017 A.1.2
200 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
201 "020100" // INTEGER length 1 value 0x00 (version)
202 "02820101" // INTEGER length 0x101 value (modulus) ...
203 "00BEBC342B56D443B1299F9A6A7056E8"
204 "0A897E318476A5A18029E63B2ED739A6"
205 "1791D339F58DC763D9D14911F2EDEC38"
206 "3DEE11F6319B44510E7A3ECD9B79B973"
207 "82E49500ACF8117DC89CAF0E621F7775"
208 "6554A2FD4664BFE7AB8B59AB48340DBF"
209 "A27B93B5A81F6ECDEB02D0759307128D"
210 "F3E3BAD4055C8B840216DFAA5700670E"
211 "6C5126F0962FCB70FF308F25049164CC"
212 "F76CC2DA66A7DD9A81A714C2809D6918"
213 "6133D29D84568E892B6FFBF3199BDB14"
214 "383EE224407F190358F111A949552ABA"
215 "6714227D1BD7F6B20DD0CB88F9467B71"
216 "9339F33BFF35B3870B3F62204E4286B0"
217 "948EA348B524544B5F9838F29EE643B0"
218 "79EEF8A713B220D7806924CDF7295070"
219 "C5"
220 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
221 "02820100" // INTEGER length 0x100 (privateExponent) value...
222 "69F377F35F2F584EF075353CCD1CA997"
223 "38DB3DBC7C7FF35F9366CE176DFD1B13"
224 "5AB10030344ABF5FBECF1D4659FDEF1C"
225 "0FC430834BE1BE3911951377BB3D563A"
226 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
227 "2686C7B4B3C09A7B8354133E6F93F790"
228 "D59EAEB92E84C9A4339302CCE28FDF04"
229 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
230 "6AB706645BF074A4E4090D06FB163124"
231 "365FD5EE7A20D350E9958CC30D91326E"
232 "1B292E9EF5DB408EC42DAF737D201497"
233 "04D0A678A0FB5B5446863B099228A352"
234 "D604BA8091A164D01D5AB05397C71EAD"
235 "20BE2A08FC528FE442817809C787FEE4"
236 "AB97F97B9130D022153EDC6EB6CBE7B0"
237 "F8E3473F2E901209B5DB10F93604DB01"
238 "028181" // INTEGER length 0x81 (prime1)
239 "00E83C0998214941EA4F9293F1B77E2E"
240 "99E6CF305FAF358238E126124FEAF2EB"
241 "9724B2EA7B78E6032343821A80E55D1D"
242 "88FB12D220C3F41A56142FEC85796D19"
243 "17F1E8C774F142B67D3D6E7B7E6B4383"
244 "E94DB5929089DBB346D5BDAB40CC2D96"
245 "EE0409475E175C63BF78CFD744136740"
246 "838127EA723FF3FE7FA368C1311B4A4E"
247 "05"
248 "028181" // INTEGER length 0x81 (prime2)
249 "00D240FCC0F5D7715CDE21CB2DC86EA1"
250 "46132EA3B06F61FF2AF54BF38473F59D"
251 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
252 "B1B58C39F95E4798CCBB43E83D0119AC"
253 "F532F359CA743C85199F0286610E2009"
254 "97D7312917179AC9B67558773212EC96"
255 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
256 "94D94E066A0900B7B70E82A44FB30053"
257 "C1"
258 "028181" // INTEGER length 0x81 (exponent1)
259 "00AD15DA1CBD6A492B66851BA8C316D3"
260 "8AB700E2CFDDD926A658003513C54BAA"
261 "152B30021D667D20078F500F8AD3E7F3"
262 "945D74A891ED1A28EAD0FEEAEC8C14A8"
263 "E834CF46A13D1378C99D18940823CFDD"
264 "27EC5810D59339E0C34198AC638E09C8"
265 "7CBB1B634A9864AE9F4D5EB2D53514F6"
266 "7B4CAEC048C8AB849A02E397618F3271"
267 "35"
268 "028180" // INTEGER length 0x80 (exponent2)
269 "1FA2C1A5331880A92D8F3E281C617108"
270 "BF38244F16E352E69ED417C7153F9EC3"
271 "18F211839C643DCF8B4DD67CE2AC312E"
272 "95178D5D952F06B1BF779F4916924B70"
273 "F582A23F11304E02A5E7565AE22A35E7"
274 "4FECC8B6FDC93F92A1A37703E4CF0E63"
275 "783BD02EB716A7ECBBFA606B10B74D01"
276 "579522E7EF84D91FC522292108D902C1"
277 "028180" // INTEGER length 0x80 (coefficient)
278 "796FE3825F9DCC85DF22D58690065D93"
279 "898ACD65C087BEA8DA3A63BF4549B795"
280 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
281 "0D74F40DED8E1102C52152A31B6165F8"
282 "3A6722AECFCC35A493D7634664B888A0"
283 "8D3EB034F12EA28BFEE346E205D33482"
284 "7F778B16ED40872BD29FCB36536B6E93"
285 "FFB06778696B4A9D81BB0A9423E63DE5"
286 // } end SEQUENCE (PrivateKey)
287 // } end SEQUENCE (PrivateKeyInfo)
288);
Selene Huange5727e62021-04-13 22:41:20 -0700289
David Drysdaled2cc8c22021-04-15 13:29:45 +0100290string ec_256_key = hex2str(
291 // RFC 5208 s5
292 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
293 "020100" // INTEGER length 1 value 0 (version)
294 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
295 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
296 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
297 "0608" // OBJECT IDENTIFIER length 8 (param)
298 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
299 // } end SEQUENCE (AlgorithmIdentifier)
300 "046d" // OCTET STRING length 0x6d (privateKey) holding...
301 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
302 "020101" // INTEGER length 1 value 1 (version)
303 "0420" // OCTET STRING length 0x20 (privateKey)
304 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
305 "941eed09366bc03299986481f3a4d859"
306 "a144" // TAG [1] len 0x44 (publicKey) {
307 "03420004bf85d7720d07c25461683bc6"
308 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
309 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
310 "bcc41c6eb00083cf3376d11fd44949e0"
311 "b2183bfe"
312 // } end SEQUENCE (ECPrivateKey)
313 // } end SEQUENCE (PrivateKeyInfo)
314);
Selene Huang31ab4042020-04-29 04:22:39 -0700315
David Drysdaled2cc8c22021-04-15 13:29:45 +0100316string ec_521_key = hex2str(
317 // RFC 5208 s5
318 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
319 "020100" // INTEGER length 1 value 0 (version)
320 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
321 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
322 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
323 "0605" // OBJECT IDENTIFIER length 5 (param)
324 "2B81040023" // 1.3.132.0.35 (secp521r1)
325 // } end SEQUENCE (AlgorithmIdentifier)
326 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
327 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
328 "020101" // INTEGER length 1 value 1 (version)
329 "0442" // OCTET STRING length 0x42 (privateKey)
330 "0011458C586DB5DAA92AFAB03F4FE46A"
331 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
332 "9D18D7D08B5BCFA0E53C75B064AD51C4"
333 "49BAE0258D54B94B1E885DED08ED4FB2"
334 "5CE9"
335 "A18189" // TAG [1] len 0x89 (publicKey) {
336 "03818600040149EC11C6DF0FA122C6A9"
337 "AFD9754A4FA9513A627CA329E349535A"
338 "5629875A8ADFBE27DCB932C051986377"
339 "108D054C28C6F39B6F2C9AF81802F9F3"
340 "26B842FF2E5F3C00AB7635CFB36157FC"
341 "0882D574A10D839C1A0C049DC5E0D775"
342 "E2EE50671A208431BB45E78E70BEFE93"
343 "0DB34818EE4D5C26259F5C6B8E28A652"
344 "950F9F88D7B4B2C9D9"
345 // } end SEQUENCE (ECPrivateKey)
346 // } end SEQUENCE (PrivateKeyInfo)
347);
Selene Huang31ab4042020-04-29 04:22:39 -0700348
David Drysdaled2cc8c22021-04-15 13:29:45 +0100349string ec_256_key_rfc5915 = hex2str(
350 // RFC 5208 s5
351 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
352 "020100" // INTEGER length 1 value 0 (version)
353 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
354 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
355 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
356 "0608" // OBJECT IDENTIFIER length 8 (param)
357 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
358 // } end SEQUENCE (AlgorithmIdentifier)
359 "0479" // OCTET STRING length 0x79 (privateKey) holding...
360 // RFC 5915 s3
361 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
362 "020101" // INTEGER length 1 value 1 (version)
363 "0420" // OCTET STRING length 0x42 (privateKey)
364 "782370a8c8ce5537baadd04dcff079c8"
365 "158cfa9c67b818b38e8d21c9fa750c1d"
366 "a00a" // TAG [0] length 0xa (parameters)
367 "0608" // OBJECT IDENTIFIER length 8
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end TAG [0]
370 "a144" // TAG [1] length 0x44 (publicKey) {
371 "0342" // BIT STRING length 0x42
372 "00" // no pad bits
373 "04e2cc561ee701da0ad0ef0d176bb0c9"
374 "19d42e79c393fdc1bd6c4010d85cf2cf"
375 "8e68c905464666f98dad4f01573ba810"
376 "78b3428570a439ba3229fbc026c55068"
377 "2f"
378 // } end SEQUENCE (ECPrivateKey)
379 // } end SEQUENCE (PrivateKeyInfo)
380);
Selene Huang31ab4042020-04-29 04:22:39 -0700381
David Drysdaled2cc8c22021-04-15 13:29:45 +0100382string ec_256_key_sec1 = hex2str(
383 // RFC 5208 s5
384 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
385 "020100" // INTEGER length 1 value 0 (version)
386 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
387 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
388 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
389 "0608" // OBJECT IDENTIFIER length 8 (param)
390 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
391 // } end SEQUENCE (AlgorithmIdentifier)
392 "046d" // OCTET STRING length 0x6d (privateKey) holding...
393 // SEC1-v2 C.4
394 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
395 "020101" // INTEGER length 1 value 0x01 (version)
396 "0420" // OCTET STRING length 0x20 (privateKey)
397 "782370a8c8ce5537baadd04dcff079c8"
398 "158cfa9c67b818b38e8d21c9fa750c1d"
399 "a144" // TAG [1] length 0x44 (publicKey) {
400 "0342" // BIT STRING length 0x42
401 "00" // no pad bits
402 "04e2cc561ee701da0ad0ef0d176bb0c9"
403 "19d42e79c393fdc1bd6c4010d85cf2cf"
404 "8e68c905464666f98dad4f01573ba810"
405 "78b3428570a439ba3229fbc026c55068"
406 "2f"
407 // } end TAG [1] (publicKey)
408 // } end SEQUENCE (PrivateKeyInfo)
409);
Selene Huang31ab4042020-04-29 04:22:39 -0700410
411struct RSA_Delete {
412 void operator()(RSA* p) { RSA_free(p); }
413};
414
Selene Huang31ab4042020-04-29 04:22:39 -0700415std::string make_string(const uint8_t* data, size_t length) {
416 return std::string(reinterpret_cast<const char*>(data), length);
417}
418
419template <size_t N>
420std::string make_string(const uint8_t (&a)[N]) {
421 return make_string(a, N);
422}
423
424class AidlBuf : public vector<uint8_t> {
425 typedef vector<uint8_t> super;
426
427 public:
428 AidlBuf() {}
429 AidlBuf(const super& other) : super(other) {}
430 AidlBuf(super&& other) : super(std::move(other)) {}
431 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
432
433 AidlBuf& operator=(const super& other) {
434 super::operator=(other);
435 return *this;
436 }
437
438 AidlBuf& operator=(super&& other) {
439 super::operator=(std::move(other));
440 return *this;
441 }
442
443 AidlBuf& operator=(const string& other) {
444 resize(other.size());
445 for (size_t i = 0; i < other.size(); ++i) {
446 (*this)[i] = static_cast<uint8_t>(other[i]);
447 }
448 return *this;
449 }
450
451 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
452};
453
David Drysdale4dc01072021-04-01 12:17:35 +0100454string device_suffix(const string& name) {
455 size_t pos = name.find('/');
456 if (pos == string::npos) {
457 return name;
458 }
459 return name.substr(pos + 1);
460}
461
462bool matching_rp_instance(const string& km_name,
463 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
464 string km_suffix = device_suffix(km_name);
465
466 vector<string> rp_names =
467 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
468 for (const string& rp_name : rp_names) {
469 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
470 // KeyMint instance, assume they match.
471 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
472 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
473 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
474 return true;
475 }
476 }
477 return false;
478}
479
Selene Huang31ab4042020-04-29 04:22:39 -0700480} // namespace
481
482class NewKeyGenerationTest : public KeyMintAidlTestBase {
483 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700484 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000485 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700486 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700487
Selene Huang31ab4042020-04-29 04:22:39 -0700488 // Check that some unexpected tags/values are NOT present.
489 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
490 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000491 }
492
493 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
494 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
495 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
496 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
497
498 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000499 }
500
501 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
502 // TODO(swillden): Distinguish which params should be in which auth list.
503 AuthorizationSet auths;
504 for (auto& entry : keyCharacteristics) {
505 auths.push_back(AuthorizationSet(entry.authorizations));
506 }
507 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
508
509 // Verify that App data, ROT and auth timeout are NOT included.
510 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
511 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700512 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
513
David Drysdaled2cc8c22021-04-15 13:29:45 +0100514 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
515 // never adds it.
516 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
517
David Drysdale7de9feb2021-03-05 14:56:19 +0000518 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700519 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000520 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700521 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700522 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000523 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700524 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000525
David Drysdalebb3d85e2021-04-13 11:15:51 +0100526 if (check_patchLevels) {
527 // Should include vendor and boot patchlevels.
528 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
529 EXPECT_TRUE(vendor_pl);
530 EXPECT_EQ(*vendor_pl, vendor_patch_level());
531 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
532 EXPECT_TRUE(boot_pl);
533 }
534
David Drysdale7de9feb2021-03-05 14:56:19 +0000535 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700536 }
537};
538
539/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000540 * NewKeyGenerationTest.Aes
541 *
542 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
543 * have correct characteristics.
544 */
545TEST_P(NewKeyGenerationTest, Aes) {
546 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
547 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
548 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
549 SCOPED_TRACE(testing::Message()
550 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
551 vector<uint8_t> key_blob;
552 vector<KeyCharacteristics> key_characteristics;
553 auto builder = AuthorizationSetBuilder()
554 .AesEncryptionKey(key_size)
555 .BlockMode(block_mode)
556 .Padding(padding_mode)
557 .SetDefaultValidity();
558 if (block_mode == BlockMode::GCM) {
559 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
560 }
561 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
562
563 EXPECT_GT(key_blob.size(), 0U);
564 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100565 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000566
567 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
568
569 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
570 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
571 << "Key size " << key_size << "missing";
572
573 CheckedDeleteKey(&key_blob);
574 }
575 }
576 }
577}
578
579/*
580 * NewKeyGenerationTest.AesInvalidSize
581 *
582 * Verifies that specifying an invalid key size for AES key generation returns
583 * UNSUPPORTED_KEY_SIZE.
584 */
585TEST_P(NewKeyGenerationTest, AesInvalidSize) {
586 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
587 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
588 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
589 SCOPED_TRACE(testing::Message()
590 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
591 vector<uint8_t> key_blob;
592 vector<KeyCharacteristics> key_characteristics;
593 auto builder = AuthorizationSetBuilder()
594 .AesEncryptionKey(key_size)
595 .BlockMode(block_mode)
596 .Padding(padding_mode)
597 .SetDefaultValidity();
598 if (block_mode == BlockMode::GCM) {
599 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
600 }
601 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
602 GenerateKey(builder, &key_blob, &key_characteristics));
603 }
604 }
605 }
606
607 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
608 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
609 vector<uint8_t> key_blob;
610 vector<KeyCharacteristics> key_characteristics;
611 // No key size specified
612 auto builder = AuthorizationSetBuilder()
613 .Authorization(TAG_ALGORITHM, Algorithm::AES)
614 .BlockMode(block_mode)
615 .Padding(padding_mode)
616 .SetDefaultValidity();
617 if (block_mode == BlockMode::GCM) {
618 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
619 }
620 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
621 GenerateKey(builder, &key_blob, &key_characteristics));
622 }
623 }
624}
625
626/*
627 * NewKeyGenerationTest.AesInvalidPadding
628 *
629 * Verifies that specifying an invalid padding on AES keys gives a failure
630 * somewhere along the way.
631 */
632TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
633 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
634 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
635 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
636 SCOPED_TRACE(testing::Message()
637 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000638 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800639 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000640 .AesEncryptionKey(key_size)
641 .BlockMode(block_mode)
642 .Padding(padding_mode)
643 .SetDefaultValidity();
644 if (block_mode == BlockMode::GCM) {
645 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
646 }
647
Tommy Chiu3950b452021-05-03 22:01:46 +0800648 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 if (result == ErrorCode::OK) {
650 // Key creation was OK but has generated a key that cannot be used.
651 auto params =
652 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800653 if (block_mode == BlockMode::GCM) {
654 params.Authorization(TAG_MAC_LENGTH, 128);
655 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000656 auto result = Begin(KeyPurpose::ENCRYPT, params);
657 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100658 result == ErrorCode::INVALID_KEY_BLOB)
659 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000660 } else {
661 // The KeyMint implementation detected that the generated key
662 // is unusable.
663 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
664 }
665 }
666 }
667 }
668}
669
670/*
671 * NewKeyGenerationTest.AesGcmMissingMinMac
672 *
673 * Verifies that specifying an invalid key size for AES key generation returns
674 * UNSUPPORTED_KEY_SIZE.
675 */
676TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
677 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
678 BlockMode block_mode = BlockMode::GCM;
679 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
680 SCOPED_TRACE(testing::Message()
681 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
682 vector<uint8_t> key_blob;
683 vector<KeyCharacteristics> key_characteristics;
684 // No MIN_MAC_LENGTH provided.
685 auto builder = AuthorizationSetBuilder()
686 .AesEncryptionKey(key_size)
687 .BlockMode(block_mode)
688 .Padding(padding_mode)
689 .SetDefaultValidity();
690 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
691 GenerateKey(builder, &key_blob, &key_characteristics));
692 }
693 }
694}
695
696/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100697 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
698 *
699 * Verifies that specifying an invalid min MAC size for AES key generation returns
700 * UNSUPPORTED_MIN_MAC_LENGTH.
701 */
702TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
703 for (size_t min_mac_len : {88, 136}) {
704 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
705 BlockMode block_mode = BlockMode::GCM;
706 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
707 SCOPED_TRACE(testing::Message()
708 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
709 vector<uint8_t> key_blob;
710 vector<KeyCharacteristics> key_characteristics;
711 auto builder = AuthorizationSetBuilder()
712 .AesEncryptionKey(key_size)
713 .BlockMode(block_mode)
714 .Padding(padding_mode)
715 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
716 .SetDefaultValidity();
717 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
718 GenerateKey(builder, &key_blob, &key_characteristics));
719 }
720 }
721 }
722}
723
724/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000725 * NewKeyGenerationTest.TripleDes
726 *
727 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
728 * have correct characteristics.
729 */
730TEST_P(NewKeyGenerationTest, TripleDes) {
731 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
732 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
733 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
734 SCOPED_TRACE(testing::Message()
735 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
736 vector<uint8_t> key_blob;
737 vector<KeyCharacteristics> key_characteristics;
738 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
739 .TripleDesEncryptionKey(key_size)
740 .BlockMode(block_mode)
741 .Padding(padding_mode)
742 .Authorization(TAG_NO_AUTH_REQUIRED)
743 .SetDefaultValidity(),
744 &key_blob, &key_characteristics));
745
746 EXPECT_GT(key_blob.size(), 0U);
747 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100748 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000749
750 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
751
752 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
753 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
754 << "Key size " << key_size << "missing";
755
756 CheckedDeleteKey(&key_blob);
757 }
758 }
759 }
760}
761
762/*
763 * NewKeyGenerationTest.TripleDesWithAttestation
764 *
765 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
766 * have correct characteristics.
767 *
768 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
769 * put in a certificate) but which isn't an error.
770 */
771TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
772 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
773 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
774 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
775 SCOPED_TRACE(testing::Message()
776 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
777
778 auto challenge = "hello";
779 auto app_id = "foo";
780
781 vector<uint8_t> key_blob;
782 vector<KeyCharacteristics> key_characteristics;
783 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
784 .TripleDesEncryptionKey(key_size)
785 .BlockMode(block_mode)
786 .Padding(padding_mode)
787 .Authorization(TAG_NO_AUTH_REQUIRED)
788 .AttestationChallenge(challenge)
789 .AttestationApplicationId(app_id)
790 .SetDefaultValidity(),
791 &key_blob, &key_characteristics));
792
793 EXPECT_GT(key_blob.size(), 0U);
794 CheckSymmetricParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100795 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000796
797 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
798
799 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
800 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
801 << "Key size " << key_size << "missing";
802
803 CheckedDeleteKey(&key_blob);
804 }
805 }
806 }
807}
808
809/*
810 * NewKeyGenerationTest.TripleDesInvalidSize
811 *
812 * Verifies that specifying an invalid key size for 3-DES key generation returns
813 * UNSUPPORTED_KEY_SIZE.
814 */
815TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
816 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
817 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
818 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
819 SCOPED_TRACE(testing::Message()
820 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
821 vector<uint8_t> key_blob;
822 vector<KeyCharacteristics> key_characteristics;
823 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
824 GenerateKey(AuthorizationSetBuilder()
825 .TripleDesEncryptionKey(key_size)
826 .BlockMode(block_mode)
827 .Padding(padding_mode)
828 .Authorization(TAG_NO_AUTH_REQUIRED)
829 .SetDefaultValidity(),
830 &key_blob, &key_characteristics));
831 }
832 }
833 }
834
835 // Omitting the key size fails.
836 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
837 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
838 SCOPED_TRACE(testing::Message()
839 << "3DES-default-" << block_mode << "-" << padding_mode);
840 vector<uint8_t> key_blob;
841 vector<KeyCharacteristics> key_characteristics;
842 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
843 GenerateKey(AuthorizationSetBuilder()
844 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
845 .BlockMode(block_mode)
846 .Padding(padding_mode)
847 .Authorization(TAG_NO_AUTH_REQUIRED)
848 .SetDefaultValidity(),
849 &key_blob, &key_characteristics));
850 }
851 }
852}
853
854/*
Selene Huang31ab4042020-04-29 04:22:39 -0700855 * NewKeyGenerationTest.Rsa
856 *
857 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
858 * have correct characteristics.
859 */
860TEST_P(NewKeyGenerationTest, Rsa) {
861 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
862 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700863 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700864 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
865 .RsaSigningKey(key_size, 65537)
866 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800867 .Padding(PaddingMode::NONE)
868 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700869 &key_blob, &key_characteristics));
870
871 ASSERT_GT(key_blob.size(), 0U);
872 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100873 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700874
Shawn Willden7f424372021-01-10 18:06:50 -0700875 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700876
877 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
878 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
879 << "Key size " << key_size << "missing";
880 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
881
882 CheckedDeleteKey(&key_blob);
883 }
884}
885
886/*
Qi Wud22ec842020-11-26 13:27:53 +0800887 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700888 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100889 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
890 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700891 */
892TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700893 auto challenge = "hello";
894 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700895
Selene Huang6e46f142021-04-20 19:20:11 -0700896 auto subject = "cert subj 2";
897 vector<uint8_t> subject_der(make_name_from_str(subject));
898
899 uint64_t serial_int = 66;
900 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
901
Selene Huang4f64c222021-04-13 19:54:36 -0700902 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700903 vector<uint8_t> key_blob;
904 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700905 ASSERT_EQ(ErrorCode::OK,
906 GenerateKey(AuthorizationSetBuilder()
907 .RsaSigningKey(key_size, 65537)
908 .Digest(Digest::NONE)
909 .Padding(PaddingMode::NONE)
910 .AttestationChallenge(challenge)
911 .AttestationApplicationId(app_id)
912 .Authorization(TAG_NO_AUTH_REQUIRED)
913 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
914 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
915 .SetDefaultValidity(),
916 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700917
918 ASSERT_GT(key_blob.size(), 0U);
919 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100920 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700921
922 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
923
924 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
925 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
926 << "Key size " << key_size << "missing";
927 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
928
Selene Huang6e46f142021-04-20 19:20:11 -0700929 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700930 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700931 ASSERT_GT(cert_chain_.size(), 0);
932
933 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
934 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
935 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
936 sw_enforced, hw_enforced, SecLevel(),
937 cert_chain_[0].encodedCertificate));
938
939 CheckedDeleteKey(&key_blob);
940 }
941}
942
943/*
David Drysdale4dc01072021-04-01 12:17:35 +0100944 * NewKeyGenerationTest.RsaWithRpkAttestation
945 *
946 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
947 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale11860f22021-04-13 17:22:13 +0100948 *
949 * This test is disabled because the KeyMint specification does not require that implementations
950 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
951 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +0100952 */
David Drysdale11860f22021-04-13 17:22:13 +0100953TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +0100954 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
955 // instance.
956 std::shared_ptr<IRemotelyProvisionedComponent> rp;
957 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
958 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
959
960 // Generate a P-256 keypair to use as an attestation key.
961 MacedPublicKey macedPubKey;
962 std::vector<uint8_t> privateKeyBlob;
963 auto status =
964 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
965 ASSERT_TRUE(status.isOk());
966 vector<uint8_t> coseKeyData;
967 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
968
969 AttestationKey attestation_key;
970 attestation_key.keyBlob = std::move(privateKeyBlob);
971 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
972
973 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
974 auto challenge = "hello";
975 auto app_id = "foo";
976
977 vector<uint8_t> key_blob;
978 vector<KeyCharacteristics> key_characteristics;
979 ASSERT_EQ(ErrorCode::OK,
980 GenerateKey(AuthorizationSetBuilder()
981 .RsaSigningKey(key_size, 65537)
982 .Digest(Digest::NONE)
983 .Padding(PaddingMode::NONE)
984 .AttestationChallenge(challenge)
985 .AttestationApplicationId(app_id)
986 .Authorization(TAG_NO_AUTH_REQUIRED)
987 .SetDefaultValidity(),
988 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
989
990 ASSERT_GT(key_blob.size(), 0U);
991 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +0100992 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +0100993
994 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
995
996 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
997 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
998 << "Key size " << key_size << "missing";
999 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1000
1001 // Attestation by itself is not valid (last entry is not self-signed).
1002 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1003
1004 // The signature over the attested key should correspond to the P256 public key.
1005 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1006 ASSERT_TRUE(key_cert.get());
1007 EVP_PKEY_Ptr signing_pubkey;
1008 p256_pub_key(coseKeyData, &signing_pubkey);
1009 ASSERT_TRUE(signing_pubkey.get());
1010
1011 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1012 << "Verification of attested certificate failed "
1013 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1014
1015 CheckedDeleteKey(&key_blob);
1016 }
1017}
1018
1019/*
Selene Huang4f64c222021-04-13 19:54:36 -07001020 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1021 *
1022 * Verifies that keymint attestation for RSA encryption keys with challenge and
1023 * app id is also successful.
1024 */
1025TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1026 auto key_size = 2048;
1027 auto challenge = "hello";
1028 auto app_id = "foo";
1029
Selene Huang6e46f142021-04-20 19:20:11 -07001030 auto subject = "subj 2";
1031 vector<uint8_t> subject_der(make_name_from_str(subject));
1032
1033 uint64_t serial_int = 111166;
1034 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1035
Selene Huang4f64c222021-04-13 19:54:36 -07001036 vector<uint8_t> key_blob;
1037 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001038 ASSERT_EQ(ErrorCode::OK,
1039 GenerateKey(AuthorizationSetBuilder()
1040 .RsaEncryptionKey(key_size, 65537)
1041 .Padding(PaddingMode::NONE)
1042 .AttestationChallenge(challenge)
1043 .AttestationApplicationId(app_id)
1044 .Authorization(TAG_NO_AUTH_REQUIRED)
1045 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1046 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1047 .SetDefaultValidity(),
1048 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001049
1050 ASSERT_GT(key_blob.size(), 0U);
1051 AuthorizationSet auths;
1052 for (auto& entry : key_characteristics) {
1053 auths.push_back(AuthorizationSet(entry.authorizations));
1054 }
1055
1056 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1057 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1058
1059 // Verify that App data and ROT are NOT included.
1060 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1061 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1062
1063 // Check that some unexpected tags/values are NOT present.
1064 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1065 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1066
1067 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1068
1069 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1070 ASSERT_TRUE(os_ver);
1071 EXPECT_EQ(*os_ver, os_version());
1072
1073 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1074
1075 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1076 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1077 << "Key size " << key_size << "missing";
1078 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1079
Selene Huang6e46f142021-04-20 19:20:11 -07001080 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001081 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1082 ASSERT_GT(cert_chain_.size(), 0);
1083
1084 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1085 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1086 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1087 sw_enforced, hw_enforced, SecLevel(),
1088 cert_chain_[0].encodedCertificate));
1089
1090 CheckedDeleteKey(&key_blob);
1091}
1092
1093/*
1094 * NewKeyGenerationTest.RsaWithSelfSign
1095 *
1096 * Verifies that attesting to RSA key generation is successful, and returns
1097 * self signed certificate if no challenge is provided. And signing etc
1098 * works as expected.
1099 */
1100TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001101 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1102 vector<uint8_t> subject_der(make_name_from_str(subject));
1103
1104 uint64_t serial_int = 0;
1105 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1106
Selene Huang4f64c222021-04-13 19:54:36 -07001107 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1108 vector<uint8_t> key_blob;
1109 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001110 ASSERT_EQ(ErrorCode::OK,
1111 GenerateKey(AuthorizationSetBuilder()
1112 .RsaSigningKey(key_size, 65537)
1113 .Digest(Digest::NONE)
1114 .Padding(PaddingMode::NONE)
1115 .Authorization(TAG_NO_AUTH_REQUIRED)
1116 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1117 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1118 .SetDefaultValidity(),
1119 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001120
1121 ASSERT_GT(key_blob.size(), 0U);
1122 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001123 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001124
1125 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1126
1127 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1128 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1129 << "Key size " << key_size << "missing";
1130 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1131
Selene Huang6e46f142021-04-20 19:20:11 -07001132 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001133 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1134 ASSERT_EQ(cert_chain_.size(), 1);
1135
1136 CheckedDeleteKey(&key_blob);
1137 }
1138}
1139
1140/*
1141 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1142 *
1143 * Verifies that attesting to RSA checks for missing app ID.
1144 */
1145TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1146 auto challenge = "hello";
1147 vector<uint8_t> key_blob;
1148 vector<KeyCharacteristics> key_characteristics;
1149
1150 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1151 GenerateKey(AuthorizationSetBuilder()
1152 .RsaSigningKey(2048, 65537)
1153 .Digest(Digest::NONE)
1154 .Padding(PaddingMode::NONE)
1155 .AttestationChallenge(challenge)
1156 .Authorization(TAG_NO_AUTH_REQUIRED)
1157 .SetDefaultValidity(),
1158 &key_blob, &key_characteristics));
1159}
1160
1161/*
1162 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1163 *
1164 * Verifies that attesting to RSA ignores app id if challenge is missing.
1165 */
1166TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1167 auto key_size = 2048;
1168 auto app_id = "foo";
1169
Selene Huang6e46f142021-04-20 19:20:11 -07001170 auto subject = "cert subj 2";
1171 vector<uint8_t> subject_der(make_name_from_str(subject));
1172
1173 uint64_t serial_int = 1;
1174 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1175
Selene Huang4f64c222021-04-13 19:54:36 -07001176 vector<uint8_t> key_blob;
1177 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001178 ASSERT_EQ(ErrorCode::OK,
1179 GenerateKey(AuthorizationSetBuilder()
1180 .RsaSigningKey(key_size, 65537)
1181 .Digest(Digest::NONE)
1182 .Padding(PaddingMode::NONE)
1183 .AttestationApplicationId(app_id)
1184 .Authorization(TAG_NO_AUTH_REQUIRED)
1185 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1186 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1187 .SetDefaultValidity(),
1188 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001189
1190 ASSERT_GT(key_blob.size(), 0U);
1191 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001192 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001193
1194 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1195
1196 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1197 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1198 << "Key size " << key_size << "missing";
1199 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1200
Selene Huang6e46f142021-04-20 19:20:11 -07001201 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001202 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1203 ASSERT_EQ(cert_chain_.size(), 1);
1204
1205 CheckedDeleteKey(&key_blob);
1206}
1207
1208/*
Qi Wud22ec842020-11-26 13:27:53 +08001209 * NewKeyGenerationTest.LimitedUsageRsa
1210 *
1211 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1212 * resulting keys have correct characteristics.
1213 */
1214TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1215 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1216 vector<uint8_t> key_blob;
1217 vector<KeyCharacteristics> key_characteristics;
1218 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1219 .RsaSigningKey(key_size, 65537)
1220 .Digest(Digest::NONE)
1221 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001222 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1223 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001224 &key_blob, &key_characteristics));
1225
1226 ASSERT_GT(key_blob.size(), 0U);
1227 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001228 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001229
1230 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1231
1232 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1233 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1234 << "Key size " << key_size << "missing";
1235 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1236
1237 // Check the usage count limit tag appears in the authorizations.
1238 AuthorizationSet auths;
1239 for (auto& entry : key_characteristics) {
1240 auths.push_back(AuthorizationSet(entry.authorizations));
1241 }
1242 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1243 << "key usage count limit " << 1U << " missing";
1244
1245 CheckedDeleteKey(&key_blob);
1246 }
1247}
1248
1249/*
Qi Wubeefae42021-01-28 23:16:37 +08001250 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1251 *
1252 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1253 * resulting keys have correct characteristics and attestation.
1254 */
1255TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001256 auto challenge = "hello";
1257 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001258
Selene Huang6e46f142021-04-20 19:20:11 -07001259 auto subject = "cert subj 2";
1260 vector<uint8_t> subject_der(make_name_from_str(subject));
1261
1262 uint64_t serial_int = 66;
1263 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1264
Selene Huang4f64c222021-04-13 19:54:36 -07001265 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001266 vector<uint8_t> key_blob;
1267 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001268 ASSERT_EQ(ErrorCode::OK,
1269 GenerateKey(AuthorizationSetBuilder()
1270 .RsaSigningKey(key_size, 65537)
1271 .Digest(Digest::NONE)
1272 .Padding(PaddingMode::NONE)
1273 .AttestationChallenge(challenge)
1274 .AttestationApplicationId(app_id)
1275 .Authorization(TAG_NO_AUTH_REQUIRED)
1276 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1277 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1278 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1279 .SetDefaultValidity(),
1280 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001281
1282 ASSERT_GT(key_blob.size(), 0U);
1283 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001284 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001285
1286 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1287
1288 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1289 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1290 << "Key size " << key_size << "missing";
1291 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1292
1293 // Check the usage count limit tag appears in the authorizations.
1294 AuthorizationSet auths;
1295 for (auto& entry : key_characteristics) {
1296 auths.push_back(AuthorizationSet(entry.authorizations));
1297 }
1298 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1299 << "key usage count limit " << 1U << " missing";
1300
1301 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001302 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001303 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001304 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001305
1306 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1307 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1308 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1309 sw_enforced, hw_enforced, SecLevel(),
1310 cert_chain_[0].encodedCertificate));
1311
1312 CheckedDeleteKey(&key_blob);
1313 }
1314}
1315
1316/*
Selene Huang31ab4042020-04-29 04:22:39 -07001317 * NewKeyGenerationTest.NoInvalidRsaSizes
1318 *
1319 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1320 */
1321TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1322 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1323 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001324 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001325 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1326 GenerateKey(AuthorizationSetBuilder()
1327 .RsaSigningKey(key_size, 65537)
1328 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001329 .Padding(PaddingMode::NONE)
1330 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001331 &key_blob, &key_characteristics));
1332 }
1333}
1334
1335/*
1336 * NewKeyGenerationTest.RsaNoDefaultSize
1337 *
1338 * Verifies that failing to specify a key size for RSA key generation returns
1339 * UNSUPPORTED_KEY_SIZE.
1340 */
1341TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1342 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1343 GenerateKey(AuthorizationSetBuilder()
1344 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1345 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001346 .SigningKey()
1347 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001348}
1349
1350/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001351 * NewKeyGenerationTest.RsaMissingParams
1352 *
1353 * Verifies that omitting optional tags works.
1354 */
1355TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1356 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1357 ASSERT_EQ(ErrorCode::OK,
1358 GenerateKey(
1359 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1360 CheckedDeleteKey();
1361 }
1362}
1363
1364/*
Selene Huang31ab4042020-04-29 04:22:39 -07001365 * NewKeyGenerationTest.Ecdsa
1366 *
1367 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1368 * have correct characteristics.
1369 */
1370TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdale308916b2021-06-08 15:46:11 +01001371 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001372 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001373 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001374 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001375 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001376 .Digest(Digest::NONE)
1377 .SetDefaultValidity(),
1378 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001379 ASSERT_GT(key_blob.size(), 0U);
1380 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001381 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001382
Shawn Willden7f424372021-01-10 18:06:50 -07001383 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001384
1385 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001386 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001387
1388 CheckedDeleteKey(&key_blob);
1389 }
1390}
1391
1392/*
Selene Huang4f64c222021-04-13 19:54:36 -07001393 * NewKeyGenerationTest.EcdsaAttestation
1394 *
1395 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1396 * an attestation will be generated.
1397 */
1398TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1399 auto challenge = "hello";
1400 auto app_id = "foo";
1401
Selene Huang6e46f142021-04-20 19:20:11 -07001402 auto subject = "cert subj 2";
1403 vector<uint8_t> subject_der(make_name_from_str(subject));
1404
1405 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1406 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1407
David Drysdale308916b2021-06-08 15:46:11 +01001408 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001409 vector<uint8_t> key_blob;
1410 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001411 ASSERT_EQ(ErrorCode::OK,
1412 GenerateKey(AuthorizationSetBuilder()
1413 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001414 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001415 .Digest(Digest::NONE)
1416 .AttestationChallenge(challenge)
1417 .AttestationApplicationId(app_id)
1418 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1419 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1420 .SetDefaultValidity(),
1421 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001422 ASSERT_GT(key_blob.size(), 0U);
1423 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001424 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001425
1426 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1427
1428 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001429 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001430
1431 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1432 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001433 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001434
1435 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1436 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1437 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1438 sw_enforced, hw_enforced, SecLevel(),
1439 cert_chain_[0].encodedCertificate));
1440
1441 CheckedDeleteKey(&key_blob);
1442 }
1443}
1444
1445/*
David Drysdale92464372021-05-14 16:46:59 +01001446 * NewKeyGenerationTest.EcdsaAttestationTags
1447 *
1448 * Verifies that creation of an attested ECDSA key includes various tags in the
1449 * attestation extension.
1450 */
1451TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1452 auto challenge = "hello";
1453 auto app_id = "foo";
1454 auto subject = "cert subj 2";
1455 vector<uint8_t> subject_der(make_name_from_str(subject));
1456 uint64_t serial_int = 0x1010;
1457 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1458 const AuthorizationSetBuilder base_builder =
1459 AuthorizationSetBuilder()
1460 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001461 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale92464372021-05-14 16:46:59 +01001462 .Digest(Digest::NONE)
1463 .AttestationChallenge(challenge)
1464 .AttestationApplicationId(app_id)
1465 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1466 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1467 .SetDefaultValidity();
1468
1469 // Various tags that map to fields in the attestation extension ASN.1 schema.
1470 auto extra_tags = AuthorizationSetBuilder()
1471 .Authorization(TAG_ROLLBACK_RESISTANCE)
1472 .Authorization(TAG_EARLY_BOOT_ONLY)
1473 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1474 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1475 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1476 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1477 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1478 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1479 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1480 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1481 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1482 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
1483 for (const KeyParameter& tag : extra_tags) {
1484 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1485 vector<uint8_t> key_blob;
1486 vector<KeyCharacteristics> key_characteristics;
1487 AuthorizationSetBuilder builder = base_builder;
1488 builder.push_back(tag);
1489 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1490 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1491 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1492 continue;
1493 }
Seth Moore3dbdaa92021-07-12 14:18:28 -07001494 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1495 // Tag not required to be supported by all KeyMint implementations.
David Drysdale92464372021-05-14 16:46:59 +01001496 continue;
1497 }
1498 ASSERT_EQ(result, ErrorCode::OK);
1499 ASSERT_GT(key_blob.size(), 0U);
1500
1501 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1502 ASSERT_GT(cert_chain_.size(), 0);
1503 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1504
1505 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1506 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Moore3dbdaa92021-07-12 14:18:28 -07001507 // Some tags are optional, so don't require them to be in the enforcements.
1508 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale92464372021-05-14 16:46:59 +01001509 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1510 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1511 }
1512
1513 // Verifying the attestation record will check for the specific tag because
1514 // it's included in the authorizations.
1515 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1516 SecLevel(), cert_chain_[0].encodedCertificate));
1517
1518 CheckedDeleteKey(&key_blob);
1519 }
1520
1521 // Device attestation IDs should be rejected for normal attestation requests; these fields
1522 // are only used for device unique attestation.
1523 auto invalid_tags = AuthorizationSetBuilder()
1524 .Authorization(TAG_ATTESTATION_ID_BRAND, "brand")
1525 .Authorization(TAG_ATTESTATION_ID_DEVICE, "device")
1526 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "product")
1527 .Authorization(TAG_ATTESTATION_ID_SERIAL, "serial")
1528 .Authorization(TAG_ATTESTATION_ID_IMEI, "imei")
1529 .Authorization(TAG_ATTESTATION_ID_MEID, "meid")
1530 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer")
1531 .Authorization(TAG_ATTESTATION_ID_MODEL, "model");
1532 for (const KeyParameter& tag : invalid_tags) {
1533 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1534 vector<uint8_t> key_blob;
1535 vector<KeyCharacteristics> key_characteristics;
1536 AuthorizationSetBuilder builder =
1537 AuthorizationSetBuilder()
1538 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001539 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale92464372021-05-14 16:46:59 +01001540 .Digest(Digest::NONE)
1541 .AttestationChallenge(challenge)
1542 .AttestationApplicationId(app_id)
1543 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1544 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1545 .SetDefaultValidity();
1546 builder.push_back(tag);
1547 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1548 GenerateKey(builder, &key_blob, &key_characteristics));
1549 }
1550}
1551
1552/*
David Drysdale2f361c12021-10-11 12:49:50 +01001553 * NewKeyGenerationTest.EcdsaAttestationUniqueId
1554 *
1555 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
1556 */
1557TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
1558 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
1559 vector<uint8_t>* unique_id) {
1560 auto challenge = "hello";
1561 auto subject = "cert subj 2";
1562 vector<uint8_t> subject_der(make_name_from_str(subject));
1563 uint64_t serial_int = 0x1010;
1564 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1565 const AuthorizationSetBuilder builder =
1566 AuthorizationSetBuilder()
1567 .Authorization(TAG_NO_AUTH_REQUIRED)
1568 .Authorization(TAG_INCLUDE_UNIQUE_ID)
1569 .EcdsaSigningKey(EcCurve::P_256)
1570 .Digest(Digest::NONE)
1571 .AttestationChallenge(challenge)
1572 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1573 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1574 .AttestationApplicationId(app_id)
1575 .Authorization(TAG_CREATION_DATETIME, datetime)
1576 .SetDefaultValidity();
1577
1578 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
1579 ASSERT_GT(key_blob_.size(), 0U);
1580
1581 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1582 ASSERT_GT(cert_chain_.size(), 0);
1583 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1584
1585 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
1586 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
1587
1588 // Check that the unique ID field in the extension is non-empty.
1589 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1590 SecLevel(), cert_chain_[0].encodedCertificate,
1591 unique_id));
1592 EXPECT_GT(unique_id->size(), 0);
1593 CheckedDeleteKey();
1594 };
1595
1596 // Generate unique ID
1597 auto app_id = "foo";
1598 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
1599 vector<uint8_t> unique_id;
1600 get_unique_id(app_id, cert_date, &unique_id);
1601
1602 // Generating a new key with the same parameters should give the same unique ID.
1603 vector<uint8_t> unique_id2;
1604 get_unique_id(app_id, cert_date, &unique_id2);
1605 EXPECT_EQ(unique_id, unique_id2);
1606
1607 // Generating a new key with a slightly different date should give the same unique ID.
1608 uint64_t rounded_date = cert_date / 2592000000LLU;
1609 uint64_t min_date = rounded_date * 2592000000LLU;
1610 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
1611
1612 vector<uint8_t> unique_id3;
1613 get_unique_id(app_id, min_date, &unique_id3);
1614 EXPECT_EQ(unique_id, unique_id3);
1615
1616 vector<uint8_t> unique_id4;
1617 get_unique_id(app_id, max_date, &unique_id4);
1618 EXPECT_EQ(unique_id, unique_id4);
1619
1620 // A different attestation application ID should yield a different unique ID.
1621 auto app_id2 = "different_foo";
1622 vector<uint8_t> unique_id5;
1623 get_unique_id(app_id2, cert_date, &unique_id5);
1624 EXPECT_NE(unique_id, unique_id5);
1625
1626 // A radically different date should yield a different unique ID.
1627 vector<uint8_t> unique_id6;
1628 get_unique_id(app_id, 1611621648000, &unique_id6);
1629 EXPECT_NE(unique_id, unique_id6);
1630
1631 vector<uint8_t> unique_id7;
1632 get_unique_id(app_id, max_date + 1, &unique_id7);
1633 EXPECT_NE(unique_id, unique_id7);
1634
1635 vector<uint8_t> unique_id8;
1636 get_unique_id(app_id, min_date - 1, &unique_id8);
1637 EXPECT_NE(unique_id, unique_id8);
1638}
1639
1640/*
David Drysdale92464372021-05-14 16:46:59 +01001641 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1642 *
1643 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1644 */
1645TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1646 auto challenge = "hello";
1647 auto attest_app_id = "foo";
1648 auto subject = "cert subj 2";
1649 vector<uint8_t> subject_der(make_name_from_str(subject));
1650 uint64_t serial_int = 0x1010;
1651 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1652
1653 // Earlier versions of the attestation extension schema included a slot:
1654 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1655 // This should never have been included, and should never be filled in.
1656 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1657 // to confirm that this field never makes it into the attestation extension.
1658 vector<uint8_t> key_blob;
1659 vector<KeyCharacteristics> key_characteristics;
1660 auto result = GenerateKey(AuthorizationSetBuilder()
1661 .Authorization(TAG_NO_AUTH_REQUIRED)
1662 .EcdsaSigningKey(EcCurve::P_256)
1663 .Digest(Digest::NONE)
1664 .AttestationChallenge(challenge)
1665 .AttestationApplicationId(attest_app_id)
1666 .Authorization(TAG_APPLICATION_ID, "client_id")
1667 .Authorization(TAG_APPLICATION_DATA, "appdata")
1668 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1669 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1670 .SetDefaultValidity(),
1671 &key_blob, &key_characteristics);
1672 ASSERT_EQ(result, ErrorCode::OK);
1673 ASSERT_GT(key_blob.size(), 0U);
1674
1675 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1676 ASSERT_GT(cert_chain_.size(), 0);
1677 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1678
1679 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1680 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1681 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1682 SecLevel(), cert_chain_[0].encodedCertificate));
1683
1684 // Check that the app id is not in the cert.
1685 string app_id = "clientid";
1686 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1687 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1688 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1689 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1690 cert_chain_[0].encodedCertificate.end());
1691
1692 CheckedDeleteKey(&key_blob);
1693}
1694
1695/*
Selene Huang4f64c222021-04-13 19:54:36 -07001696 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1697 *
1698 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1699 * the key will generate a self signed attestation.
1700 */
1701TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001702 auto subject = "cert subj 2";
1703 vector<uint8_t> subject_der(make_name_from_str(subject));
1704
1705 uint64_t serial_int = 0x123456FFF1234;
1706 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1707
David Drysdale308916b2021-06-08 15:46:11 +01001708 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001709 vector<uint8_t> key_blob;
1710 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001711 ASSERT_EQ(ErrorCode::OK,
1712 GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001713 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001714 .Digest(Digest::NONE)
1715 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1716 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1717 .SetDefaultValidity(),
1718 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001719 ASSERT_GT(key_blob.size(), 0U);
1720 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001721 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001722
1723 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1724
1725 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001726 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001727
1728 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001729 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001730 ASSERT_EQ(cert_chain_.size(), 1);
1731
1732 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1733 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1734
1735 CheckedDeleteKey(&key_blob);
1736 }
1737}
1738
1739/*
1740 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1741 *
1742 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1743 * app id must also be provided or else it will fail.
1744 */
1745TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1746 auto challenge = "hello";
1747 vector<uint8_t> key_blob;
1748 vector<KeyCharacteristics> key_characteristics;
1749
1750 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1751 GenerateKey(AuthorizationSetBuilder()
1752 .EcdsaSigningKey(EcCurve::P_256)
1753 .Digest(Digest::NONE)
1754 .AttestationChallenge(challenge)
1755 .SetDefaultValidity(),
1756 &key_blob, &key_characteristics));
1757}
1758
1759/*
1760 * NewKeyGenerationTest.EcdsaIgnoreAppId
1761 *
1762 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1763 * any appid will be ignored, and keymint will generate a self sign certificate.
1764 */
1765TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1766 auto app_id = "foo";
1767
David Drysdale308916b2021-06-08 15:46:11 +01001768 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001769 vector<uint8_t> key_blob;
1770 vector<KeyCharacteristics> key_characteristics;
1771 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001772 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001773 .Digest(Digest::NONE)
1774 .AttestationApplicationId(app_id)
1775 .SetDefaultValidity(),
1776 &key_blob, &key_characteristics));
1777
1778 ASSERT_GT(key_blob.size(), 0U);
1779 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001780 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001781
1782 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1783
1784 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001785 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001786
1787 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1788 ASSERT_EQ(cert_chain_.size(), 1);
1789
1790 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1791 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1792
1793 CheckedDeleteKey(&key_blob);
1794 }
1795}
1796
1797/*
1798 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1799 *
1800 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1801 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1802 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1803 * to specify how many following bytes will be used to encode the length.
1804 */
1805TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1806 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001807 std::vector<uint32_t> app_id_lengths{143, 258};
1808
1809 for (uint32_t length : app_id_lengths) {
1810 const string app_id(length, 'a');
1811 vector<uint8_t> key_blob;
1812 vector<KeyCharacteristics> key_characteristics;
1813 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1814 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01001815 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001816 .Digest(Digest::NONE)
1817 .AttestationChallenge(challenge)
1818 .AttestationApplicationId(app_id)
1819 .SetDefaultValidity(),
1820 &key_blob, &key_characteristics));
1821 ASSERT_GT(key_blob.size(), 0U);
1822 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001823 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001824
1825 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1826
1827 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001828 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001829
1830 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1831 ASSERT_GT(cert_chain_.size(), 0);
1832
1833 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1834 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1835 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1836 sw_enforced, hw_enforced, SecLevel(),
1837 cert_chain_[0].encodedCertificate));
1838
1839 CheckedDeleteKey(&key_blob);
1840 }
1841}
1842
1843/*
Qi Wud22ec842020-11-26 13:27:53 +08001844 * NewKeyGenerationTest.LimitedUsageEcdsa
1845 *
1846 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1847 * resulting keys have correct characteristics.
1848 */
1849TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdale308916b2021-06-08 15:46:11 +01001850 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001851 vector<uint8_t> key_blob;
1852 vector<KeyCharacteristics> key_characteristics;
1853 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001854 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001855 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001856 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1857 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001858 &key_blob, &key_characteristics));
1859
1860 ASSERT_GT(key_blob.size(), 0U);
1861 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001862 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001863
1864 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1865
1866 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdale308916b2021-06-08 15:46:11 +01001867 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001868
1869 // Check the usage count limit tag appears in the authorizations.
1870 AuthorizationSet auths;
1871 for (auto& entry : key_characteristics) {
1872 auths.push_back(AuthorizationSet(entry.authorizations));
1873 }
1874 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1875 << "key usage count limit " << 1U << " missing";
1876
1877 CheckedDeleteKey(&key_blob);
1878 }
1879}
1880
1881/*
Selene Huang31ab4042020-04-29 04:22:39 -07001882 * NewKeyGenerationTest.EcdsaDefaultSize
1883 *
David Drysdale308916b2021-06-08 15:46:11 +01001884 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001885 * UNSUPPORTED_KEY_SIZE.
1886 */
1887TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1888 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1889 GenerateKey(AuthorizationSetBuilder()
1890 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1891 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001892 .Digest(Digest::NONE)
1893 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001894}
1895
1896/*
1897 * NewKeyGenerationTest.EcdsaInvalidSize
1898 *
1899 * Verifies that specifying an invalid key size for EC key generation returns
1900 * UNSUPPORTED_KEY_SIZE.
1901 */
1902TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdale308916b2021-06-08 15:46:11 +01001903 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001904 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001905 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001906 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdale308916b2021-06-08 15:46:11 +01001907 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001908 .Digest(Digest::NONE)
1909 .SetDefaultValidity(),
1910 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001911 }
1912
David Drysdale308916b2021-06-08 15:46:11 +01001913 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1914 GenerateKey(AuthorizationSetBuilder()
1915 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1916 .Authorization(TAG_KEY_SIZE, 190)
1917 .SigningKey()
1918 .Digest(Digest::NONE)
1919 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001920}
1921
1922/*
1923 * NewKeyGenerationTest.EcdsaMismatchKeySize
1924 *
1925 * Verifies that specifying mismatched key size and curve for EC key generation returns
1926 * INVALID_ARGUMENT.
1927 */
1928TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1929 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1930
David Drysdale308916b2021-06-08 15:46:11 +01001931 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleca76a752021-08-18 16:45:50 +01001932 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdale308916b2021-06-08 15:46:11 +01001933 .Authorization(TAG_KEY_SIZE, 224)
1934 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleca76a752021-08-18 16:45:50 +01001935 .SigningKey()
David Drysdale308916b2021-06-08 15:46:11 +01001936 .Digest(Digest::NONE)
1937 .SetDefaultValidity());
David Drysdaleca76a752021-08-18 16:45:50 +01001938 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07001939}
1940
1941/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001942 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001943 *
1944 * Verifies that keymint does not support any curve designated as unsupported.
1945 */
1946TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1947 Digest digest;
1948 if (SecLevel() == SecurityLevel::STRONGBOX) {
1949 digest = Digest::SHA_2_256;
1950 } else {
1951 digest = Digest::SHA_2_512;
1952 }
1953 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001954 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1955 .EcdsaSigningKey(curve)
1956 .Digest(digest)
1957 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001958 << "Failed to generate key on curve: " << curve;
1959 CheckedDeleteKey();
1960 }
1961}
1962
1963/*
1964 * NewKeyGenerationTest.Hmac
1965 *
1966 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1967 * characteristics.
1968 */
1969TEST_P(NewKeyGenerationTest, Hmac) {
1970 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1971 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001972 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001973 constexpr size_t key_size = 128;
1974 ASSERT_EQ(ErrorCode::OK,
1975 GenerateKey(
1976 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1977 TAG_MIN_MAC_LENGTH, 128),
1978 &key_blob, &key_characteristics));
1979
1980 ASSERT_GT(key_blob.size(), 0U);
1981 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01001982 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001983
Shawn Willden7f424372021-01-10 18:06:50 -07001984 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1985 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1986 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1987 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001988
1989 CheckedDeleteKey(&key_blob);
1990 }
1991}
1992
1993/*
Selene Huang4f64c222021-04-13 19:54:36 -07001994 * NewKeyGenerationTest.HmacNoAttestation
1995 *
1996 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1997 * and app id are provided.
1998 */
1999TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2000 auto challenge = "hello";
2001 auto app_id = "foo";
2002
2003 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2004 vector<uint8_t> key_blob;
2005 vector<KeyCharacteristics> key_characteristics;
2006 constexpr size_t key_size = 128;
2007 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2008 .HmacKey(key_size)
2009 .Digest(digest)
2010 .AttestationChallenge(challenge)
2011 .AttestationApplicationId(app_id)
2012 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2013 &key_blob, &key_characteristics));
2014
2015 ASSERT_GT(key_blob.size(), 0U);
2016 ASSERT_EQ(cert_chain_.size(), 0);
2017 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01002018 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002019
2020 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2021 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2022 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2023 << "Key size " << key_size << "missing";
2024
2025 CheckedDeleteKey(&key_blob);
2026 }
2027}
2028
2029/*
Qi Wud22ec842020-11-26 13:27:53 +08002030 * NewKeyGenerationTest.LimitedUsageHmac
2031 *
2032 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2033 * resulting keys have correct characteristics.
2034 */
2035TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2036 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2037 vector<uint8_t> key_blob;
2038 vector<KeyCharacteristics> key_characteristics;
2039 constexpr size_t key_size = 128;
2040 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2041 .HmacKey(key_size)
2042 .Digest(digest)
2043 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2044 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2045 &key_blob, &key_characteristics));
2046
2047 ASSERT_GT(key_blob.size(), 0U);
2048 CheckBaseParams(key_characteristics);
David Drysdale96ad2032021-05-20 12:05:26 +01002049 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002050
2051 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2052 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2053 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2054 << "Key size " << key_size << "missing";
2055
2056 // Check the usage count limit tag appears in the authorizations.
2057 AuthorizationSet auths;
2058 for (auto& entry : key_characteristics) {
2059 auths.push_back(AuthorizationSet(entry.authorizations));
2060 }
2061 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2062 << "key usage count limit " << 1U << " missing";
2063
2064 CheckedDeleteKey(&key_blob);
2065 }
2066}
2067
2068/*
Selene Huang31ab4042020-04-29 04:22:39 -07002069 * NewKeyGenerationTest.HmacCheckKeySizes
2070 *
2071 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2072 */
2073TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2074 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2075 if (key_size < 64 || key_size % 8 != 0) {
2076 // To keep this test from being very slow, we only test a random fraction of
2077 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2078 // them, we expect to run ~40 of them in each run.
2079 if (key_size % 8 == 0 || random() % 10 == 0) {
2080 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2081 GenerateKey(AuthorizationSetBuilder()
2082 .HmacKey(key_size)
2083 .Digest(Digest::SHA_2_256)
2084 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2085 << "HMAC key size " << key_size << " invalid";
2086 }
2087 } else {
2088 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2089 .HmacKey(key_size)
2090 .Digest(Digest::SHA_2_256)
2091 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2092 << "Failed to generate HMAC key of size " << key_size;
2093 CheckedDeleteKey();
2094 }
2095 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002096 if (SecLevel() == SecurityLevel::STRONGBOX) {
2097 // STRONGBOX devices must not support keys larger than 512 bits.
2098 size_t key_size = 520;
2099 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2100 GenerateKey(AuthorizationSetBuilder()
2101 .HmacKey(key_size)
2102 .Digest(Digest::SHA_2_256)
2103 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2104 << "HMAC key size " << key_size << " unexpectedly valid";
2105 }
Selene Huang31ab4042020-04-29 04:22:39 -07002106}
2107
2108/*
2109 * NewKeyGenerationTest.HmacCheckMinMacLengths
2110 *
2111 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2112 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2113 * specific MAC length that failed, so reproducing a failed run will be easy.
2114 */
2115TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2116 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2117 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2118 // To keep this test from being very long, we only test a random fraction of
2119 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2120 // we expect to run ~17 of them in each run.
2121 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2122 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2123 GenerateKey(AuthorizationSetBuilder()
2124 .HmacKey(128)
2125 .Digest(Digest::SHA_2_256)
2126 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2127 << "HMAC min mac length " << min_mac_length << " invalid.";
2128 }
2129 } else {
2130 EXPECT_EQ(ErrorCode::OK,
2131 GenerateKey(AuthorizationSetBuilder()
2132 .HmacKey(128)
2133 .Digest(Digest::SHA_2_256)
2134 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2135 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2136 CheckedDeleteKey();
2137 }
2138 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002139
2140 // Minimum MAC length must be no more than 512 bits.
2141 size_t min_mac_length = 520;
2142 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2143 GenerateKey(AuthorizationSetBuilder()
2144 .HmacKey(128)
2145 .Digest(Digest::SHA_2_256)
2146 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2147 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002148}
2149
2150/*
2151 * NewKeyGenerationTest.HmacMultipleDigests
2152 *
2153 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2154 */
2155TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
2156 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2157
2158 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2159 GenerateKey(AuthorizationSetBuilder()
2160 .HmacKey(128)
2161 .Digest(Digest::SHA1)
2162 .Digest(Digest::SHA_2_256)
2163 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2164}
2165
2166/*
2167 * NewKeyGenerationTest.HmacDigestNone
2168 *
2169 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2170 */
2171TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2172 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2173 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2174 128)));
2175
2176 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2177 GenerateKey(AuthorizationSetBuilder()
2178 .HmacKey(128)
2179 .Digest(Digest::NONE)
2180 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2181}
2182
Selene Huang4f64c222021-04-13 19:54:36 -07002183/*
2184 * NewKeyGenerationTest.AesNoAttestation
2185 *
2186 * Verifies that attestation parameters to AES keys are ignored and generateKey
2187 * will succeed.
2188 */
2189TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2190 auto challenge = "hello";
2191 auto app_id = "foo";
2192
2193 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2194 .Authorization(TAG_NO_AUTH_REQUIRED)
2195 .AesEncryptionKey(128)
2196 .EcbMode()
2197 .Padding(PaddingMode::PKCS7)
2198 .AttestationChallenge(challenge)
2199 .AttestationApplicationId(app_id)));
2200
2201 ASSERT_EQ(cert_chain_.size(), 0);
2202}
2203
2204/*
2205 * NewKeyGenerationTest.TripleDesNoAttestation
2206 *
2207 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2208 * will be successful. No attestation should be generated.
2209 */
2210TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2211 auto challenge = "hello";
2212 auto app_id = "foo";
2213
2214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2215 .TripleDesEncryptionKey(168)
2216 .BlockMode(BlockMode::ECB)
2217 .Authorization(TAG_NO_AUTH_REQUIRED)
2218 .Padding(PaddingMode::NONE)
2219 .AttestationChallenge(challenge)
2220 .AttestationApplicationId(app_id)));
2221 ASSERT_EQ(cert_chain_.size(), 0);
2222}
2223
Selene Huang31ab4042020-04-29 04:22:39 -07002224INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2225
2226typedef KeyMintAidlTestBase SigningOperationsTest;
2227
2228/*
2229 * SigningOperationsTest.RsaSuccess
2230 *
2231 * Verifies that raw RSA signature operations succeed.
2232 */
2233TEST_P(SigningOperationsTest, RsaSuccess) {
2234 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2235 .RsaSigningKey(2048, 65537)
2236 .Digest(Digest::NONE)
2237 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002238 .Authorization(TAG_NO_AUTH_REQUIRED)
2239 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002240 string message = "12345678901234567890123456789012";
2241 string signature = SignMessage(
2242 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdalefe42aa32021-05-06 08:10:58 +01002243 LocalVerifyMessage(message, signature,
2244 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2245}
2246
2247/*
2248 * SigningOperationsTest.RsaAllPaddingsAndDigests
2249 *
2250 * Verifies RSA signature/verification for all padding modes and digests.
2251 */
2252TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2253 auto authorizations = AuthorizationSetBuilder()
2254 .Authorization(TAG_NO_AUTH_REQUIRED)
2255 .RsaSigningKey(2048, 65537)
2256 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2257 .Padding(PaddingMode::NONE)
2258 .Padding(PaddingMode::RSA_PSS)
2259 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2260 .SetDefaultValidity();
2261
2262 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2263
2264 string message(128, 'a');
2265 string corrupt_message(message);
2266 ++corrupt_message[corrupt_message.size() / 2];
2267
2268 for (auto padding :
2269 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2270 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2271 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2272 // Digesting only makes sense with padding.
2273 continue;
2274 }
2275
2276 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2277 // PSS requires digesting.
2278 continue;
2279 }
2280
2281 string signature =
2282 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2283 LocalVerifyMessage(message, signature,
2284 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2285 }
2286 }
Selene Huang31ab4042020-04-29 04:22:39 -07002287}
2288
2289/*
2290 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2291 *
Shawn Willden7f424372021-01-10 18:06:50 -07002292 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002293 */
2294TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2295 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2296 .Authorization(TAG_NO_AUTH_REQUIRED)
2297 .RsaSigningKey(2048, 65537)
2298 .Digest(Digest::NONE)
2299 .Padding(PaddingMode::NONE)
2300 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002301 .Authorization(TAG_APPLICATION_DATA, "appdata")
2302 .SetDefaultValidity()));
David Drysdale96ad2032021-05-20 12:05:26 +01002303
2304 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2305
Selene Huang31ab4042020-04-29 04:22:39 -07002306 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2307 Begin(KeyPurpose::SIGN,
2308 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2309 AbortIfNeeded();
2310 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2311 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2312 .Digest(Digest::NONE)
2313 .Padding(PaddingMode::NONE)
2314 .Authorization(TAG_APPLICATION_ID, "clientid")));
2315 AbortIfNeeded();
2316 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2317 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2318 .Digest(Digest::NONE)
2319 .Padding(PaddingMode::NONE)
2320 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2321 AbortIfNeeded();
2322 EXPECT_EQ(ErrorCode::OK,
2323 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2324 .Digest(Digest::NONE)
2325 .Padding(PaddingMode::NONE)
2326 .Authorization(TAG_APPLICATION_DATA, "appdata")
2327 .Authorization(TAG_APPLICATION_ID, "clientid")));
2328 AbortIfNeeded();
2329}
2330
2331/*
2332 * SigningOperationsTest.RsaPssSha256Success
2333 *
2334 * Verifies that RSA-PSS signature operations succeed.
2335 */
2336TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2337 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2338 .RsaSigningKey(2048, 65537)
2339 .Digest(Digest::SHA_2_256)
2340 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002341 .Authorization(TAG_NO_AUTH_REQUIRED)
2342 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002343 // Use large message, which won't work without digesting.
2344 string message(1024, 'a');
2345 string signature = SignMessage(
2346 message,
2347 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2348}
2349
2350/*
2351 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2352 *
2353 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2354 * supports only unpadded operations.
2355 */
2356TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2357 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2358 .RsaSigningKey(2048, 65537)
2359 .Digest(Digest::NONE)
2360 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002361 .Padding(PaddingMode::NONE)
2362 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002363 string message = "12345678901234567890123456789012";
2364 string signature;
2365
2366 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2367 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2368 .Digest(Digest::NONE)
2369 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2370}
2371
2372/*
2373 * SigningOperationsTest.NoUserConfirmation
2374 *
2375 * Verifies that keymint rejects signing operations for keys with
2376 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2377 * presented.
2378 */
2379TEST_P(SigningOperationsTest, NoUserConfirmation) {
2380 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002381 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2382 .RsaSigningKey(1024, 65537)
2383 .Digest(Digest::NONE)
2384 .Padding(PaddingMode::NONE)
2385 .Authorization(TAG_NO_AUTH_REQUIRED)
2386 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2387 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002388
2389 const string message = "12345678901234567890123456789012";
2390 EXPECT_EQ(ErrorCode::OK,
2391 Begin(KeyPurpose::SIGN,
2392 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2393 string signature;
2394 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2395}
2396
2397/*
2398 * SigningOperationsTest.RsaPkcs1Sha256Success
2399 *
2400 * Verifies that digested RSA-PKCS1 signature operations succeed.
2401 */
2402TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2403 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2404 .RsaSigningKey(2048, 65537)
2405 .Digest(Digest::SHA_2_256)
2406 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002407 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2408 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002409 string message(1024, 'a');
2410 string signature = SignMessage(message, AuthorizationSetBuilder()
2411 .Digest(Digest::SHA_2_256)
2412 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2413}
2414
2415/*
2416 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2417 *
2418 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2419 */
2420TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2421 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2422 .RsaSigningKey(2048, 65537)
2423 .Digest(Digest::NONE)
2424 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002425 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2426 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002427 string message(53, 'a');
2428 string signature = SignMessage(message, AuthorizationSetBuilder()
2429 .Digest(Digest::NONE)
2430 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2431}
2432
2433/*
2434 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2435 *
2436 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2437 * given a too-long message.
2438 */
2439TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2440 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2441 .RsaSigningKey(2048, 65537)
2442 .Digest(Digest::NONE)
2443 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002444 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2445 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002446 string message(257, 'a');
2447
2448 EXPECT_EQ(ErrorCode::OK,
2449 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2450 .Digest(Digest::NONE)
2451 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2452 string signature;
2453 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2454}
2455
2456/*
2457 * SigningOperationsTest.RsaPssSha512TooSmallKey
2458 *
2459 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2460 * used with a key that is too small for the message.
2461 *
2462 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2463 * keymint specification requires that salt_size == digest_size, so the message will be
2464 * digest_size * 2 +
2465 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2466 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2467 * for a 1024-bit key.
2468 */
2469TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2470 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2471 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2472 .RsaSigningKey(1024, 65537)
2473 .Digest(Digest::SHA_2_512)
2474 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002475 .Padding(PaddingMode::RSA_PSS)
2476 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002477 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2478 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2479 .Digest(Digest::SHA_2_512)
2480 .Padding(PaddingMode::RSA_PSS)));
2481}
2482
2483/*
2484 * SigningOperationsTest.RsaNoPaddingTooLong
2485 *
2486 * Verifies that raw RSA signature operations fail with the correct error code when
2487 * given a too-long message.
2488 */
2489TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2490 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2491 .RsaSigningKey(2048, 65537)
2492 .Digest(Digest::NONE)
2493 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002494 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2495 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002496 // One byte too long
2497 string message(2048 / 8 + 1, 'a');
2498 ASSERT_EQ(ErrorCode::OK,
2499 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2500 .Digest(Digest::NONE)
2501 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2502 string result;
2503 ErrorCode finish_error_code = Finish(message, &result);
2504 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2505 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2506
2507 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2508 message = string(128 * 1024, 'a');
2509 ASSERT_EQ(ErrorCode::OK,
2510 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2511 .Digest(Digest::NONE)
2512 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2513 finish_error_code = Finish(message, &result);
2514 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2515 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2516}
2517
2518/*
2519 * SigningOperationsTest.RsaAbort
2520 *
2521 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2522 * test, but the behavior should be algorithm and purpose-independent.
2523 */
2524TEST_P(SigningOperationsTest, RsaAbort) {
2525 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2526 .RsaSigningKey(2048, 65537)
2527 .Digest(Digest::NONE)
2528 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002529 .Padding(PaddingMode::NONE)
2530 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002531
2532 ASSERT_EQ(ErrorCode::OK,
2533 Begin(KeyPurpose::SIGN,
2534 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2535 EXPECT_EQ(ErrorCode::OK, Abort());
2536
2537 // Another abort should fail
2538 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2539
2540 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002541 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002542}
2543
2544/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002545 * SigningOperationsTest.RsaNonUniqueParams
2546 *
2547 * Verifies that an operation with multiple padding modes is rejected.
2548 */
2549TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2550 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2551 .RsaSigningKey(2048, 65537)
2552 .Digest(Digest::NONE)
2553 .Digest(Digest::SHA1)
2554 .Authorization(TAG_NO_AUTH_REQUIRED)
2555 .Padding(PaddingMode::NONE)
2556 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2557 .SetDefaultValidity()));
2558
2559 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2560 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2561 .Digest(Digest::NONE)
2562 .Padding(PaddingMode::NONE)
2563 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2564
Tommy Chiu3b56cbc2021-05-11 18:36:50 +08002565 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2566 .Digest(Digest::NONE)
2567 .Digest(Digest::SHA1)
2568 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2569 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002570
2571 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2572 Begin(KeyPurpose::SIGN,
2573 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2574}
2575
2576/*
Selene Huang31ab4042020-04-29 04:22:39 -07002577 * SigningOperationsTest.RsaUnsupportedPadding
2578 *
2579 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2580 * with a padding mode inappropriate for RSA.
2581 */
2582TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2583 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2584 .RsaSigningKey(2048, 65537)
2585 .Authorization(TAG_NO_AUTH_REQUIRED)
2586 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002587 .Padding(PaddingMode::PKCS7)
2588 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002589 ASSERT_EQ(
2590 ErrorCode::UNSUPPORTED_PADDING_MODE,
2591 Begin(KeyPurpose::SIGN,
2592 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002593 CheckedDeleteKey();
2594
2595 ASSERT_EQ(ErrorCode::OK,
2596 GenerateKey(
2597 AuthorizationSetBuilder()
2598 .RsaSigningKey(2048, 65537)
2599 .Authorization(TAG_NO_AUTH_REQUIRED)
2600 .Digest(Digest::SHA_2_256 /* supported digest */)
2601 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2602 .SetDefaultValidity()));
2603 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2604 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2605 .Digest(Digest::SHA_2_256)
2606 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002607}
2608
2609/*
2610 * SigningOperationsTest.RsaPssNoDigest
2611 *
2612 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2613 */
2614TEST_P(SigningOperationsTest, RsaNoDigest) {
2615 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2616 .RsaSigningKey(2048, 65537)
2617 .Authorization(TAG_NO_AUTH_REQUIRED)
2618 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002619 .Padding(PaddingMode::RSA_PSS)
2620 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002621 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2622 Begin(KeyPurpose::SIGN,
2623 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2624
2625 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2626 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2627}
2628
2629/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002630 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002631 *
2632 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2633 * supported in some cases (as validated in other tests), but a mode must be specified.
2634 */
2635TEST_P(SigningOperationsTest, RsaNoPadding) {
2636 // Padding must be specified
2637 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2638 .RsaKey(2048, 65537)
2639 .Authorization(TAG_NO_AUTH_REQUIRED)
2640 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002641 .Digest(Digest::NONE)
2642 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002643 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2644 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2645}
2646
2647/*
2648 * SigningOperationsTest.RsaShortMessage
2649 *
2650 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2651 */
2652TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2653 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2654 .Authorization(TAG_NO_AUTH_REQUIRED)
2655 .RsaSigningKey(2048, 65537)
2656 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002657 .Padding(PaddingMode::NONE)
2658 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002659
2660 // Barely shorter
2661 string message(2048 / 8 - 1, 'a');
2662 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2663
2664 // Much shorter
2665 message = "a";
2666 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2667}
2668
2669/*
2670 * SigningOperationsTest.RsaSignWithEncryptionKey
2671 *
2672 * Verifies that RSA encryption keys cannot be used to sign.
2673 */
2674TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2675 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2676 .Authorization(TAG_NO_AUTH_REQUIRED)
2677 .RsaEncryptionKey(2048, 65537)
2678 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002679 .Padding(PaddingMode::NONE)
2680 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002681 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2682 Begin(KeyPurpose::SIGN,
2683 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2684}
2685
2686/*
2687 * SigningOperationsTest.RsaSignTooLargeMessage
2688 *
2689 * Verifies that attempting a raw signature of a message which is the same length as the key,
2690 * but numerically larger than the public modulus, fails with the correct error.
2691 */
2692TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2693 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2694 .Authorization(TAG_NO_AUTH_REQUIRED)
2695 .RsaSigningKey(2048, 65537)
2696 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002697 .Padding(PaddingMode::NONE)
2698 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002699
2700 // Largest possible message will always be larger than the public modulus.
2701 string message(2048 / 8, static_cast<char>(0xff));
2702 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2703 .Authorization(TAG_NO_AUTH_REQUIRED)
2704 .Digest(Digest::NONE)
2705 .Padding(PaddingMode::NONE)));
2706 string signature;
2707 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2708}
2709
2710/*
David Drysdalefe42aa32021-05-06 08:10:58 +01002711 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2712 *
2713 * Verifies ECDSA signature/verification for all digests and curves.
2714 */
2715TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2716 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2717
2718 string message = "1234567890";
2719 string corrupt_message = "2234567890";
2720 for (auto curve : ValidCurves()) {
2721 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2722 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2723 .Authorization(TAG_NO_AUTH_REQUIRED)
2724 .EcdsaSigningKey(curve)
2725 .Digest(digests)
2726 .SetDefaultValidity());
2727 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2728 if (error != ErrorCode::OK) {
2729 continue;
2730 }
2731
2732 for (auto digest : digests) {
2733 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2734 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2735 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2736 }
2737
2738 auto rc = DeleteKey();
2739 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2740 }
2741}
2742
2743/*
Selene Huang31ab4042020-04-29 04:22:39 -07002744 * SigningOperationsTest.EcdsaAllCurves
2745 *
2746 * Verifies that ECDSA operations succeed with all possible curves.
2747 */
2748TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2749 for (auto curve : ValidCurves()) {
2750 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2751 .Authorization(TAG_NO_AUTH_REQUIRED)
2752 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002753 .Digest(Digest::SHA_2_256)
2754 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002755 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2756 if (error != ErrorCode::OK) continue;
2757
2758 string message(1024, 'a');
2759 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2760 CheckedDeleteKey();
2761 }
2762}
2763
2764/*
2765 * SigningOperationsTest.EcdsaNoDigestHugeData
2766 *
2767 * Verifies that ECDSA operations support very large messages, even without digesting. This
2768 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2769 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2770 * the framework.
2771 */
2772TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2773 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2774 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01002775 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002776 .Digest(Digest::NONE)
2777 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002778 string message(1 * 1024, 'a');
2779 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2780}
2781
2782/*
2783 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2784 *
2785 * Verifies that using an EC key requires the correct app ID/data.
2786 */
2787TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2788 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2789 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01002790 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002791 .Digest(Digest::NONE)
2792 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002793 .Authorization(TAG_APPLICATION_DATA, "appdata")
2794 .SetDefaultValidity()));
David Drysdale96ad2032021-05-20 12:05:26 +01002795
2796 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2797
Selene Huang31ab4042020-04-29 04:22:39 -07002798 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2799 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2800 AbortIfNeeded();
2801 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2802 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2803 .Digest(Digest::NONE)
2804 .Authorization(TAG_APPLICATION_ID, "clientid")));
2805 AbortIfNeeded();
2806 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2807 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2808 .Digest(Digest::NONE)
2809 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2810 AbortIfNeeded();
2811 EXPECT_EQ(ErrorCode::OK,
2812 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2813 .Digest(Digest::NONE)
2814 .Authorization(TAG_APPLICATION_DATA, "appdata")
2815 .Authorization(TAG_APPLICATION_ID, "clientid")));
2816 AbortIfNeeded();
2817}
2818
2819/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002820 * SigningOperationsTest.EcdsaIncompatibleDigest
2821 *
2822 * Verifies that using an EC key requires compatible digest.
2823 */
2824TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2825 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2826 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01002827 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002828 .Digest(Digest::NONE)
2829 .Digest(Digest::SHA1)
2830 .SetDefaultValidity()));
2831 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2832 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2833 AbortIfNeeded();
2834}
2835
2836/*
Selene Huang31ab4042020-04-29 04:22:39 -07002837 * SigningOperationsTest.AesEcbSign
2838 *
2839 * Verifies that attempts to use AES keys to sign fail in the correct way.
2840 */
2841TEST_P(SigningOperationsTest, AesEcbSign) {
2842 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2843 .Authorization(TAG_NO_AUTH_REQUIRED)
2844 .SigningKey()
2845 .AesEncryptionKey(128)
2846 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2847
2848 AuthorizationSet out_params;
2849 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2850 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2851 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2852 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2853}
2854
2855/*
2856 * SigningOperationsTest.HmacAllDigests
2857 *
2858 * Verifies that HMAC works with all digests.
2859 */
2860TEST_P(SigningOperationsTest, HmacAllDigests) {
2861 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2862 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2863 .Authorization(TAG_NO_AUTH_REQUIRED)
2864 .HmacKey(128)
2865 .Digest(digest)
2866 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2867 << "Failed to create HMAC key with digest " << digest;
2868 string message = "12345678901234567890123456789012";
2869 string signature = MacMessage(message, digest, 160);
2870 EXPECT_EQ(160U / 8U, signature.size())
2871 << "Failed to sign with HMAC key with digest " << digest;
2872 CheckedDeleteKey();
2873 }
2874}
2875
2876/*
2877 * SigningOperationsTest.HmacSha256TooLargeMacLength
2878 *
2879 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2880 * digest size.
2881 */
2882TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2883 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2884 .Authorization(TAG_NO_AUTH_REQUIRED)
2885 .HmacKey(128)
2886 .Digest(Digest::SHA_2_256)
2887 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2888 AuthorizationSet output_params;
2889 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2890 AuthorizationSetBuilder()
2891 .Digest(Digest::SHA_2_256)
2892 .Authorization(TAG_MAC_LENGTH, 264),
2893 &output_params));
2894}
2895
2896/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002897 * SigningOperationsTest.HmacSha256InvalidMacLength
2898 *
2899 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2900 * not a multiple of 8.
2901 */
2902TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2903 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2904 .Authorization(TAG_NO_AUTH_REQUIRED)
2905 .HmacKey(128)
2906 .Digest(Digest::SHA_2_256)
2907 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2908 AuthorizationSet output_params;
2909 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2910 AuthorizationSetBuilder()
2911 .Digest(Digest::SHA_2_256)
2912 .Authorization(TAG_MAC_LENGTH, 161),
2913 &output_params));
2914}
2915
2916/*
Selene Huang31ab4042020-04-29 04:22:39 -07002917 * SigningOperationsTest.HmacSha256TooSmallMacLength
2918 *
2919 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2920 * specified minimum MAC length.
2921 */
2922TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2923 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2924 .Authorization(TAG_NO_AUTH_REQUIRED)
2925 .HmacKey(128)
2926 .Digest(Digest::SHA_2_256)
2927 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2928 AuthorizationSet output_params;
2929 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2930 AuthorizationSetBuilder()
2931 .Digest(Digest::SHA_2_256)
2932 .Authorization(TAG_MAC_LENGTH, 120),
2933 &output_params));
2934}
2935
2936/*
2937 * SigningOperationsTest.HmacRfc4231TestCase3
2938 *
2939 * Validates against the test vectors from RFC 4231 test case 3.
2940 */
2941TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2942 string key(20, 0xaa);
2943 string message(50, 0xdd);
2944 uint8_t sha_224_expected[] = {
2945 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2946 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2947 };
2948 uint8_t sha_256_expected[] = {
2949 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2950 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2951 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2952 };
2953 uint8_t sha_384_expected[] = {
2954 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2955 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2956 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2957 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2958 };
2959 uint8_t sha_512_expected[] = {
2960 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2961 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2962 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2963 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2964 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2965 };
2966
2967 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2968 if (SecLevel() != SecurityLevel::STRONGBOX) {
2969 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2970 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2971 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2972 }
2973}
2974
2975/*
2976 * SigningOperationsTest.HmacRfc4231TestCase5
2977 *
2978 * Validates against the test vectors from RFC 4231 test case 5.
2979 */
2980TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2981 string key(20, 0x0c);
2982 string message = "Test With Truncation";
2983
2984 uint8_t sha_224_expected[] = {
2985 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2986 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2987 };
2988 uint8_t sha_256_expected[] = {
2989 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2990 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2991 };
2992 uint8_t sha_384_expected[] = {
2993 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2994 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2995 };
2996 uint8_t sha_512_expected[] = {
2997 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2998 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2999 };
3000
3001 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3002 if (SecLevel() != SecurityLevel::STRONGBOX) {
3003 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3004 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3005 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3006 }
3007}
3008
3009INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3010
3011typedef KeyMintAidlTestBase VerificationOperationsTest;
3012
3013/*
Selene Huang31ab4042020-04-29 04:22:39 -07003014 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3015 *
3016 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3017 */
3018TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3019 string key_material = "HelloThisIsAKey";
3020
3021 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003022 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003023 EXPECT_EQ(ErrorCode::OK,
3024 ImportKey(AuthorizationSetBuilder()
3025 .Authorization(TAG_NO_AUTH_REQUIRED)
3026 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3027 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3028 .Digest(Digest::SHA_2_256)
3029 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3030 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3031 EXPECT_EQ(ErrorCode::OK,
3032 ImportKey(AuthorizationSetBuilder()
3033 .Authorization(TAG_NO_AUTH_REQUIRED)
3034 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3035 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3036 .Digest(Digest::SHA_2_256)
3037 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3038 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3039
3040 string message = "This is a message.";
3041 string signature = SignMessage(
3042 signing_key, message,
3043 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3044
3045 // Signing key should not work.
3046 AuthorizationSet out_params;
3047 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3048 Begin(KeyPurpose::VERIFY, signing_key,
3049 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3050
3051 // Verification key should work.
3052 VerifyMessage(verification_key, message, signature,
3053 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3054
3055 CheckedDeleteKey(&signing_key);
3056 CheckedDeleteKey(&verification_key);
3057}
3058
3059INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3060
3061typedef KeyMintAidlTestBase ExportKeyTest;
3062
3063/*
3064 * ExportKeyTest.RsaUnsupportedKeyFormat
3065 *
3066 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3067 */
3068// TODO(seleneh) add ExportKey to GenerateKey
3069// check result
3070
3071class ImportKeyTest : public KeyMintAidlTestBase {
3072 public:
3073 template <TagType tag_type, Tag tag, typename ValueT>
3074 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3075 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003076 for (auto& entry : key_characteristics_) {
3077 if (entry.securityLevel == SecLevel()) {
3078 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3079 << "Tag " << tag << " with value " << expected
3080 << " not found at security level" << entry.securityLevel;
3081 } else {
3082 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3083 << "Tag " << tag << " found at security level " << entry.securityLevel;
3084 }
Selene Huang31ab4042020-04-29 04:22:39 -07003085 }
3086 }
3087
3088 void CheckOrigin() {
3089 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003090 // Origin isn't a crypto param, but it always lives with them.
3091 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003092 }
3093};
3094
3095/*
3096 * ImportKeyTest.RsaSuccess
3097 *
3098 * Verifies that importing and using an RSA key pair works correctly.
3099 */
3100TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003101 uint32_t key_size;
3102 string key;
3103
3104 if (SecLevel() == SecurityLevel::STRONGBOX) {
3105 key_size = 2048;
3106 key = rsa_2048_key;
3107 } else {
3108 key_size = 1024;
3109 key = rsa_key;
3110 }
3111
Selene Huang31ab4042020-04-29 04:22:39 -07003112 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3113 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003114 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003115 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003116 .Padding(PaddingMode::RSA_PSS)
3117 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003118 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003119
3120 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003121 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003122 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3123 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3124 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3125 CheckOrigin();
3126
3127 string message(1024 / 8, 'a');
3128 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3129 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003130 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003131}
3132
3133/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003134 * ImportKeyTest.RsaSuccessWithoutParams
3135 *
3136 * Verifies that importing and using an RSA key pair without specifying parameters
3137 * works correctly.
3138 */
3139TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3140 uint32_t key_size;
3141 string key;
3142
3143 if (SecLevel() == SecurityLevel::STRONGBOX) {
3144 key_size = 2048;
3145 key = rsa_2048_key;
3146 } else {
3147 key_size = 1024;
3148 key = rsa_key;
3149 }
3150
3151 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3152 .Authorization(TAG_NO_AUTH_REQUIRED)
3153 .SigningKey()
3154 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3155 .Digest(Digest::SHA_2_256)
3156 .Padding(PaddingMode::RSA_PSS)
3157 .SetDefaultValidity(),
3158 KeyFormat::PKCS8, key));
3159
3160 // Key size and public exponent are determined from the imported key material.
3161 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3162 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3163
3164 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3165 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3166 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3167 CheckOrigin();
3168
3169 string message(1024 / 8, 'a');
3170 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3171 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003172 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003173}
3174
3175/*
Selene Huang31ab4042020-04-29 04:22:39 -07003176 * ImportKeyTest.RsaKeySizeMismatch
3177 *
3178 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3179 * correct way.
3180 */
3181TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3182 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3183 ImportKey(AuthorizationSetBuilder()
3184 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3185 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003186 .Padding(PaddingMode::NONE)
3187 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003188 KeyFormat::PKCS8, rsa_key));
3189}
3190
3191/*
3192 * ImportKeyTest.RsaPublicExponentMismatch
3193 *
3194 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3195 * fails in the correct way.
3196 */
3197TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3198 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3199 ImportKey(AuthorizationSetBuilder()
3200 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3201 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003202 .Padding(PaddingMode::NONE)
3203 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003204 KeyFormat::PKCS8, rsa_key));
3205}
3206
3207/*
3208 * ImportKeyTest.EcdsaSuccess
3209 *
3210 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3211 */
3212TEST_P(ImportKeyTest, EcdsaSuccess) {
3213 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3214 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003215 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003216 .Digest(Digest::SHA_2_256)
3217 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003218 KeyFormat::PKCS8, ec_256_key));
3219
3220 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003221 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3222 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3223
3224 CheckOrigin();
3225
3226 string message(32, 'a');
3227 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3228 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003229 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003230}
3231
3232/*
3233 * ImportKeyTest.EcdsaP256RFC5915Success
3234 *
3235 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3236 * correctly.
3237 */
3238TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3239 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3240 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003241 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003242 .Digest(Digest::SHA_2_256)
3243 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003244 KeyFormat::PKCS8, ec_256_key_rfc5915));
3245
3246 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003247 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3248 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3249
3250 CheckOrigin();
3251
3252 string message(32, 'a');
3253 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3254 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003255 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003256}
3257
3258/*
3259 * ImportKeyTest.EcdsaP256SEC1Success
3260 *
3261 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3262 */
3263TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3264 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3265 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003266 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003267 .Digest(Digest::SHA_2_256)
3268 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003269 KeyFormat::PKCS8, ec_256_key_sec1));
3270
3271 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003272 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3273 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3274
3275 CheckOrigin();
3276
3277 string message(32, 'a');
3278 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3279 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003280 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003281}
3282
3283/*
3284 * ImportKeyTest.Ecdsa521Success
3285 *
3286 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3287 */
3288TEST_P(ImportKeyTest, Ecdsa521Success) {
3289 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3290 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3291 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01003292 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003293 .Digest(Digest::SHA_2_256)
3294 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003295 KeyFormat::PKCS8, ec_521_key));
3296
3297 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003298 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3299 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3300 CheckOrigin();
3301
3302 string message(32, 'a');
3303 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3304 string signature = SignMessage(message, params);
David Drysdalefe42aa32021-05-06 08:10:58 +01003305 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003306}
3307
3308/*
Selene Huang31ab4042020-04-29 04:22:39 -07003309 * ImportKeyTest.EcdsaCurveMismatch
3310 *
3311 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3312 * the correct way.
3313 */
3314TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3315 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3316 ImportKey(AuthorizationSetBuilder()
3317 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003318 .Digest(Digest::NONE)
3319 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003320 KeyFormat::PKCS8, ec_256_key));
3321}
3322
3323/*
3324 * ImportKeyTest.AesSuccess
3325 *
3326 * Verifies that importing and using an AES key works.
3327 */
3328TEST_P(ImportKeyTest, AesSuccess) {
3329 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3330 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3331 .Authorization(TAG_NO_AUTH_REQUIRED)
3332 .AesEncryptionKey(key.size() * 8)
3333 .EcbMode()
3334 .Padding(PaddingMode::PKCS7),
3335 KeyFormat::RAW, key));
3336
3337 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3338 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3339 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3340 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3341 CheckOrigin();
3342
3343 string message = "Hello World!";
3344 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3345 string ciphertext = EncryptMessage(message, params);
3346 string plaintext = DecryptMessage(ciphertext, params);
3347 EXPECT_EQ(message, plaintext);
3348}
3349
3350/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003351 * ImportKeyTest.AesFailure
3352 *
3353 * Verifies that importing an invalid AES key fails.
3354 */
3355TEST_P(ImportKeyTest, AesFailure) {
3356 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3357 uint32_t bitlen = key.size() * 8;
3358 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003359 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003360 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003361 .Authorization(TAG_NO_AUTH_REQUIRED)
3362 .AesEncryptionKey(key_size)
3363 .EcbMode()
3364 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003365 KeyFormat::RAW, key);
3366 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003367 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3368 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003369 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003370
3371 // Explicit key size matches that of the provided key, but it's not a valid size.
3372 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3373 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3374 ImportKey(AuthorizationSetBuilder()
3375 .Authorization(TAG_NO_AUTH_REQUIRED)
3376 .AesEncryptionKey(long_key.size() * 8)
3377 .EcbMode()
3378 .Padding(PaddingMode::PKCS7),
3379 KeyFormat::RAW, long_key));
3380 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3381 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3382 ImportKey(AuthorizationSetBuilder()
3383 .Authorization(TAG_NO_AUTH_REQUIRED)
3384 .AesEncryptionKey(short_key.size() * 8)
3385 .EcbMode()
3386 .Padding(PaddingMode::PKCS7),
3387 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003388}
3389
3390/*
3391 * ImportKeyTest.TripleDesSuccess
3392 *
3393 * Verifies that importing and using a 3DES key works.
3394 */
3395TEST_P(ImportKeyTest, TripleDesSuccess) {
3396 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3397 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3398 .Authorization(TAG_NO_AUTH_REQUIRED)
3399 .TripleDesEncryptionKey(168)
3400 .EcbMode()
3401 .Padding(PaddingMode::PKCS7),
3402 KeyFormat::RAW, key));
3403
3404 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3405 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3406 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3407 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3408 CheckOrigin();
3409
3410 string message = "Hello World!";
3411 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3412 string ciphertext = EncryptMessage(message, params);
3413 string plaintext = DecryptMessage(ciphertext, params);
3414 EXPECT_EQ(message, plaintext);
3415}
3416
3417/*
3418 * ImportKeyTest.TripleDesFailure
3419 *
3420 * Verifies that importing an invalid 3DES key fails.
3421 */
3422TEST_P(ImportKeyTest, TripleDesFailure) {
3423 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003424 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003425 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003426 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003427 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003428 .Authorization(TAG_NO_AUTH_REQUIRED)
3429 .TripleDesEncryptionKey(key_size)
3430 .EcbMode()
3431 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003432 KeyFormat::RAW, key);
3433 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003434 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3435 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003436 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003437 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003438 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003439 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3440 ImportKey(AuthorizationSetBuilder()
3441 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003442 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003443 .EcbMode()
3444 .Padding(PaddingMode::PKCS7),
3445 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003446 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003447 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3448 ImportKey(AuthorizationSetBuilder()
3449 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003450 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003451 .EcbMode()
3452 .Padding(PaddingMode::PKCS7),
3453 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003454}
3455
3456/*
3457 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003458 *
3459 * Verifies that importing and using an HMAC key works.
3460 */
3461TEST_P(ImportKeyTest, HmacKeySuccess) {
3462 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3463 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3464 .Authorization(TAG_NO_AUTH_REQUIRED)
3465 .HmacKey(key.size() * 8)
3466 .Digest(Digest::SHA_2_256)
3467 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3468 KeyFormat::RAW, key));
3469
3470 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3471 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3472 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3473 CheckOrigin();
3474
3475 string message = "Hello World!";
3476 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3477 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3478}
3479
3480INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3481
3482auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003483 // IKeyMintDevice.aidl
3484 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3485 "020100" // INTEGER length 1 value 0x00 (version)
3486 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3487 "934bf94e2aa28a3f83c9f79297250262"
3488 "fbe3276b5a1c91159bbfa3ef8957aac8"
3489 "4b59b30b455a79c2973480823d8b3863"
3490 "c3deef4a8e243590268d80e18751a0e1"
3491 "30f67ce6a1ace9f79b95e097474febc9"
3492 "81195b1d13a69086c0863f66a7b7fdb4"
3493 "8792227b1ac5e2489febdf087ab54864"
3494 "83033a6f001ca5d1ec1e27f5c30f4cec"
3495 "2642074a39ae68aee552e196627a8e3d"
3496 "867e67a8c01b11e75f13cca0a97ab668"
3497 "b50cda07a8ecb7cd8e3dd7009c963653"
3498 "4f6f239cffe1fc8daa466f78b676c711"
3499 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3500 "99b801597d5220e307eaa5bee507fb94"
3501 "d1fa69f9e519b2de315bac92c36f2ea1"
3502 "fa1df4478c0ddedeae8c70e0233cd098"
3503 "040c" // OCTET STRING length 0x0c (initializationVector)
3504 "d796b02c370f1fa4cc0124f1"
3505 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3506 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3507 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3508 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3509 "3106" // SET length 0x06
3510 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3511 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3512 // } end SET
3513 // } end [1]
3514 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3515 "020120" // INTEGER length 1 value 0x20 (AES)
3516 // } end [2]
3517 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3518 "02020100" // INTEGER length 2 value 0x100
3519 // } end [3]
3520 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3521 "3103" // SET length 0x03 {
3522 "020101" // INTEGER length 1 value 0x01 (ECB)
3523 // } end SET
3524 // } end [4]
3525 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3526 "3103" // SET length 0x03 {
3527 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3528 // } end SET
3529 // } end [5]
3530 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3531 // (noAuthRequired)
3532 "0500" // NULL
3533 // } end [503]
3534 // } end SEQUENCE (AuthorizationList)
3535 // } end SEQUENCE (KeyDescription)
3536 "0420" // OCTET STRING length 0x20 (encryptedKey)
3537 "ccd540855f833a5e1480bfd2d36faf3a"
3538 "eee15df5beabe2691bc82dde2a7aa910"
3539 "0410" // OCTET STRING length 0x10 (tag)
3540 "64c9f689c60ff6223ab6e6999e0eb6e5"
3541 // } SEQUENCE (SecureKeyWrapper)
3542);
Selene Huang31ab4042020-04-29 04:22:39 -07003543
3544auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003545 // IKeyMintDevice.aidl
3546 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3547 "020100" // INTEGER length 1 value 0x00 (version)
3548 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3549 "aad93ed5924f283b4bb5526fbe7a1412"
3550 "f9d9749ec30db9062b29e574a8546f33"
3551 "c88732452f5b8e6a391ee76c39ed1712"
3552 "c61d8df6213dec1cffbc17a8c6d04c7b"
3553 "30893d8daa9b2015213e219468215532"
3554 "07f8f9931c4caba23ed3bee28b36947e"
3555 "47f10e0a5c3dc51c988a628daad3e5e1"
3556 "f4005e79c2d5a96c284b4b8d7e4948f3"
3557 "31e5b85dd5a236f85579f3ea1d1b8484"
3558 "87470bdb0ab4f81a12bee42c99fe0df4"
3559 "bee3759453e69ad1d68a809ce06b949f"
3560 "7694a990429b2fe81e066ff43e56a216"
3561 "02db70757922a4bcc23ab89f1e35da77"
3562 "586775f423e519c2ea394caf48a28d0c"
3563 "8020f1dcf6b3a68ec246f615ae96dae9"
3564 "a079b1f6eb959033c1af5c125fd94168"
3565 "040c" // OCTET STRING length 0x0c (initializationVector)
3566 "6d9721d08589581ab49204a3"
3567 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3568 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3569 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3570 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3571 "3106" // SET length 0x06
3572 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3573 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3574 // } end SET
3575 // } end [1]
3576 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3577 "020120" // INTEGER length 1 value 0x20 (AES)
3578 // } end [2]
3579 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3580 "02020100" // INTEGER length 2 value 0x100
3581 // } end [3]
3582 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3583 "3103" // SET length 0x03 {
3584 "020101" // INTEGER length 1 value 0x01 (ECB)
3585 // } end SET
3586 // } end [4]
3587 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3588 "3103" // SET length 0x03 {
3589 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3590 // } end SET
3591 // } end [5]
3592 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3593 // (noAuthRequired)
3594 "0500" // NULL
3595 // } end [503]
3596 // } end SEQUENCE (AuthorizationList)
3597 // } end SEQUENCE (KeyDescription)
3598 "0420" // OCTET STRING length 0x20 (encryptedKey)
3599 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3600 "c20d1f99a9a024a76f35c8e2cab9b68d"
3601 "0410" // OCTET STRING length 0x10 (tag)
3602 "2560c70109ae67c030f00b98b512a670"
3603 // } SEQUENCE (SecureKeyWrapper)
3604);
Selene Huang31ab4042020-04-29 04:22:39 -07003605
3606auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003607 // RFC 5208 s5
3608 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3609 "020100" // INTEGER length 1 value 0x00 (version)
3610 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3611 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3612 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3613 "0500" // NULL (parameters)
3614 // } SEQUENCE (AlgorithmIdentifier)
3615 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3616 // RFC 8017 A.1.2
3617 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3618 "020100" // INTEGER length 1 value 0x00 (version)
3619 "02820101" // INTEGER length 0x0101 (modulus) value...
3620 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3621 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3622 "7b06e673a837313d56b1c725150a3fef" // 0x30
3623 "86acbddc41bb759c2854eae32d35841e" // 0x40
3624 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3625 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3626 "312d7bd5921ffaea1347c157406fef71" // 0x70
3627 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3628 "f4645c11f5c1374c3886427411c44979" // 0x90
3629 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3630 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3631 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3632 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3633 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3634 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3635 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3636 "55" // 0x101
3637 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3638 "02820100" // INTEGER length 0x100 (privateExponent) value...
3639 "431447b6251908112b1ee76f99f3711a" // 0x10
3640 "52b6630960046c2de70de188d833f8b8" // 0x20
3641 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3642 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3643 "e710b630a03adc683b5d2c43080e52be" // 0x50
3644 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3645 "822bccff087d63c940ba8a45f670feb2" // 0x70
3646 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3647 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3648 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3649 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3650 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3651 "52659d5a5ba05b663737a8696281865b" // 0xd0
3652 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3653 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3654 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3655 "028181" // INTEGER length 0x81 (prime1) value...
3656 "00de392e18d682c829266cc3454e1d61" // 0x10
3657 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3658 "ff841be5bac82a164c5970007047b8c5" // 0x30
3659 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3660 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3661 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3662 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3663 "9e91346130748a6e3c124f9149d71c74" // 0x80
3664 "35"
3665 "028181" // INTEGER length 0x81 (prime2) value...
3666 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3667 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3668 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3669 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3670 "9ed39a2d934c880440aed8832f984316" // 0x50
3671 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3672 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3673 "b880677c068e1be936e81288815252a8" // 0x80
3674 "a1"
3675 "028180" // INTEGER length 0x80 (exponent1) value...
3676 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3677 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3678 "5a063212a4f105a3764743e53281988a" // 0x30
3679 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3680 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3681 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3682 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3683 "4719d6e2b9439823719cd08bcd031781" // 0x80
3684 "028181" // INTEGER length 0x81 (exponent2) value...
3685 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3686 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3687 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3688 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3689 "1254186af30b22c10582a8a43e34fe94" // 0x50
3690 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3691 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3692 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3693 "61"
3694 "028181" // INTEGER length 0x81 (coefficient) value...
3695 "00c931617c77829dfb1270502be9195c" // 0x10
3696 "8f2830885f57dba869536811e6864236" // 0x20
3697 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3698 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3699 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3700 "959356210723287b0affcc9f727044d4" // 0x60
3701 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3702 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3703 "22"
3704 // } SEQUENCE
3705 // } SEQUENCE ()
3706);
Selene Huang31ab4042020-04-29 04:22:39 -07003707
3708string zero_masking_key =
3709 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3710string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3711
3712class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3713
3714TEST_P(ImportWrappedKeyTest, Success) {
3715 auto wrapping_key_desc = AuthorizationSetBuilder()
3716 .RsaEncryptionKey(2048, 65537)
3717 .Digest(Digest::SHA_2_256)
3718 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003719 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3720 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003721
3722 ASSERT_EQ(ErrorCode::OK,
3723 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3724 AuthorizationSetBuilder()
3725 .Digest(Digest::SHA_2_256)
3726 .Padding(PaddingMode::RSA_OAEP)));
3727
3728 string message = "Hello World!";
3729 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3730 string ciphertext = EncryptMessage(message, params);
3731 string plaintext = DecryptMessage(ciphertext, params);
3732 EXPECT_EQ(message, plaintext);
3733}
3734
David Drysdaled2cc8c22021-04-15 13:29:45 +01003735/*
3736 * ImportWrappedKeyTest.SuccessSidsIgnored
3737 *
3738 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3739 * include Tag:USER_SECURE_ID.
3740 */
3741TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3742 auto wrapping_key_desc = AuthorizationSetBuilder()
3743 .RsaEncryptionKey(2048, 65537)
3744 .Digest(Digest::SHA_2_256)
3745 .Padding(PaddingMode::RSA_OAEP)
3746 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3747 .SetDefaultValidity();
3748
3749 int64_t password_sid = 42;
3750 int64_t biometric_sid = 24;
3751 ASSERT_EQ(ErrorCode::OK,
3752 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3753 AuthorizationSetBuilder()
3754 .Digest(Digest::SHA_2_256)
3755 .Padding(PaddingMode::RSA_OAEP),
3756 password_sid, biometric_sid));
3757
3758 string message = "Hello World!";
3759 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3760 string ciphertext = EncryptMessage(message, params);
3761 string plaintext = DecryptMessage(ciphertext, params);
3762 EXPECT_EQ(message, plaintext);
3763}
3764
Selene Huang31ab4042020-04-29 04:22:39 -07003765TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3766 auto wrapping_key_desc = AuthorizationSetBuilder()
3767 .RsaEncryptionKey(2048, 65537)
3768 .Digest(Digest::SHA_2_256)
3769 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003770 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3771 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003772
3773 ASSERT_EQ(ErrorCode::OK,
3774 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3775 AuthorizationSetBuilder()
3776 .Digest(Digest::SHA_2_256)
3777 .Padding(PaddingMode::RSA_OAEP)));
3778}
3779
3780TEST_P(ImportWrappedKeyTest, WrongMask) {
3781 auto wrapping_key_desc = AuthorizationSetBuilder()
3782 .RsaEncryptionKey(2048, 65537)
3783 .Digest(Digest::SHA_2_256)
3784 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003785 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3786 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003787
3788 ASSERT_EQ(
3789 ErrorCode::VERIFICATION_FAILED,
3790 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3791 AuthorizationSetBuilder()
3792 .Digest(Digest::SHA_2_256)
3793 .Padding(PaddingMode::RSA_OAEP)));
3794}
3795
3796TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3797 auto wrapping_key_desc = AuthorizationSetBuilder()
3798 .RsaEncryptionKey(2048, 65537)
3799 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003800 .Padding(PaddingMode::RSA_OAEP)
3801 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003802
3803 ASSERT_EQ(
3804 ErrorCode::INCOMPATIBLE_PURPOSE,
3805 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3806 AuthorizationSetBuilder()
3807 .Digest(Digest::SHA_2_256)
3808 .Padding(PaddingMode::RSA_OAEP)));
3809}
3810
David Drysdaled2cc8c22021-04-15 13:29:45 +01003811TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3812 auto wrapping_key_desc = AuthorizationSetBuilder()
3813 .RsaEncryptionKey(2048, 65537)
3814 .Digest(Digest::SHA_2_256)
3815 .Padding(PaddingMode::RSA_PSS)
3816 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3817 .SetDefaultValidity();
3818
3819 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3820 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3821 AuthorizationSetBuilder()
3822 .Digest(Digest::SHA_2_256)
3823 .Padding(PaddingMode::RSA_OAEP)));
3824}
3825
3826TEST_P(ImportWrappedKeyTest, WrongDigest) {
3827 auto wrapping_key_desc = AuthorizationSetBuilder()
3828 .RsaEncryptionKey(2048, 65537)
3829 .Digest(Digest::SHA_2_512)
3830 .Padding(PaddingMode::RSA_OAEP)
3831 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3832 .SetDefaultValidity();
3833
3834 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3835 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3836 AuthorizationSetBuilder()
3837 .Digest(Digest::SHA_2_256)
3838 .Padding(PaddingMode::RSA_OAEP)));
3839}
3840
Selene Huang31ab4042020-04-29 04:22:39 -07003841INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3842
3843typedef KeyMintAidlTestBase EncryptionOperationsTest;
3844
3845/*
3846 * EncryptionOperationsTest.RsaNoPaddingSuccess
3847 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003848 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003849 */
3850TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003851 for (uint64_t exponent : {3, 65537}) {
3852 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3853 .Authorization(TAG_NO_AUTH_REQUIRED)
3854 .RsaEncryptionKey(2048, exponent)
3855 .Padding(PaddingMode::NONE)
3856 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003857
David Drysdaled2cc8c22021-04-15 13:29:45 +01003858 string message = string(2048 / 8, 'a');
3859 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003860 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003861 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003862
David Drysdale2b6c3512021-05-12 13:52:03 +01003863 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003864 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003865
David Drysdaled2cc8c22021-04-15 13:29:45 +01003866 // Unpadded RSA is deterministic
3867 EXPECT_EQ(ciphertext1, ciphertext2);
3868
3869 CheckedDeleteKey();
3870 }
Selene Huang31ab4042020-04-29 04:22:39 -07003871}
3872
3873/*
3874 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3875 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003876 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003877 */
3878TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3879 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3880 .Authorization(TAG_NO_AUTH_REQUIRED)
3881 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003882 .Padding(PaddingMode::NONE)
3883 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003884
3885 string message = "1";
3886 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3887
David Drysdale2b6c3512021-05-12 13:52:03 +01003888 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003889 EXPECT_EQ(2048U / 8, ciphertext.size());
3890
3891 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3892 string plaintext = DecryptMessage(ciphertext, params);
3893
3894 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003895}
3896
3897/*
Selene Huang31ab4042020-04-29 04:22:39 -07003898 * EncryptionOperationsTest.RsaOaepSuccess
3899 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003900 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003901 */
3902TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3903 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3904
3905 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale2b6c3512021-05-12 13:52:03 +01003906 ASSERT_EQ(ErrorCode::OK,
3907 GenerateKey(AuthorizationSetBuilder()
3908 .Authorization(TAG_NO_AUTH_REQUIRED)
3909 .RsaEncryptionKey(key_size, 65537)
3910 .Padding(PaddingMode::RSA_OAEP)
3911 .Digest(digests)
3912 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3913 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003914
3915 string message = "Hello";
3916
3917 for (auto digest : digests) {
David Drysdale2b6c3512021-05-12 13:52:03 +01003918 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3919
3920 auto params = AuthorizationSetBuilder()
3921 .Digest(digest)
3922 .Padding(PaddingMode::RSA_OAEP)
3923 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3924 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003925 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3926 EXPECT_EQ(key_size / 8, ciphertext1.size());
3927
David Drysdale2b6c3512021-05-12 13:52:03 +01003928 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003929 EXPECT_EQ(key_size / 8, ciphertext2.size());
3930
3931 // OAEP randomizes padding so every result should be different (with astronomically high
3932 // probability).
3933 EXPECT_NE(ciphertext1, ciphertext2);
3934
3935 string plaintext1 = DecryptMessage(ciphertext1, params);
3936 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3937 string plaintext2 = DecryptMessage(ciphertext2, params);
3938 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3939
3940 // Decrypting corrupted ciphertext should fail.
3941 size_t offset_to_corrupt = random() % ciphertext1.size();
3942 char corrupt_byte;
3943 do {
3944 corrupt_byte = static_cast<char>(random() % 256);
3945 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3946 ciphertext1[offset_to_corrupt] = corrupt_byte;
3947
3948 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3949 string result;
3950 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3951 EXPECT_EQ(0U, result.size());
3952 }
3953}
3954
3955/*
3956 * EncryptionOperationsTest.RsaOaepInvalidDigest
3957 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003958 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003959 * without a digest.
3960 */
3961TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3962 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3963 .Authorization(TAG_NO_AUTH_REQUIRED)
3964 .RsaEncryptionKey(2048, 65537)
3965 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003966 .Digest(Digest::NONE)
3967 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003968
3969 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003970 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003971}
3972
3973/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003974 * EncryptionOperationsTest.RsaOaepInvalidPadding
3975 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003976 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003977 * with a padding value that is only suitable for signing/verifying.
3978 */
3979TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3980 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3981 .Authorization(TAG_NO_AUTH_REQUIRED)
3982 .RsaEncryptionKey(2048, 65537)
3983 .Padding(PaddingMode::RSA_PSS)
3984 .Digest(Digest::NONE)
3985 .SetDefaultValidity()));
3986
3987 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01003988 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003989}
3990
3991/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003992 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003993 *
David Drysdale2b6c3512021-05-12 13:52:03 +01003994 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003995 * with a different digest than was used to encrypt.
3996 */
3997TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3998 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3999
4000 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4001 .Authorization(TAG_NO_AUTH_REQUIRED)
4002 .RsaEncryptionKey(1024, 65537)
4003 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004004 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
4005 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004006 string message = "Hello World!";
David Drysdale2b6c3512021-05-12 13:52:03 +01004007 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07004008 message,
4009 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
4010
4011 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4012 .Digest(Digest::SHA_2_256)
4013 .Padding(PaddingMode::RSA_OAEP)));
4014 string result;
4015 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
4016 EXPECT_EQ(0U, result.size());
4017}
4018
4019/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004020 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
4021 *
David Drysdale2b6c3512021-05-12 13:52:03 +01004022 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004023 * digests.
4024 */
4025TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
4026 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4027
4028 size_t key_size = 2048; // Need largish key for SHA-512 test.
4029 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4030 .OaepMGFDigest(digests)
4031 .Authorization(TAG_NO_AUTH_REQUIRED)
4032 .RsaEncryptionKey(key_size, 65537)
4033 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004034 .Digest(Digest::SHA_2_256)
4035 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004036
4037 string message = "Hello";
4038
4039 for (auto digest : digests) {
4040 auto params = AuthorizationSetBuilder()
4041 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4042 .Digest(Digest::SHA_2_256)
4043 .Padding(PaddingMode::RSA_OAEP);
David Drysdale2b6c3512021-05-12 13:52:03 +01004044 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004045 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4046 EXPECT_EQ(key_size / 8, ciphertext1.size());
4047
David Drysdale2b6c3512021-05-12 13:52:03 +01004048 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004049 EXPECT_EQ(key_size / 8, ciphertext2.size());
4050
4051 // OAEP randomizes padding so every result should be different (with astronomically high
4052 // probability).
4053 EXPECT_NE(ciphertext1, ciphertext2);
4054
4055 string plaintext1 = DecryptMessage(ciphertext1, params);
4056 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4057 string plaintext2 = DecryptMessage(ciphertext2, params);
4058 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4059
4060 // Decrypting corrupted ciphertext should fail.
4061 size_t offset_to_corrupt = random() % ciphertext1.size();
4062 char corrupt_byte;
4063 do {
4064 corrupt_byte = static_cast<char>(random() % 256);
4065 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4066 ciphertext1[offset_to_corrupt] = corrupt_byte;
4067
4068 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4069 string result;
4070 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4071 EXPECT_EQ(0U, result.size());
4072 }
4073}
4074
4075/*
4076 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4077 *
David Drysdale2b6c3512021-05-12 13:52:03 +01004078 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004079 * with incompatible MGF digest.
4080 */
4081TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4082 ASSERT_EQ(ErrorCode::OK,
4083 GenerateKey(AuthorizationSetBuilder()
4084 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4085 .Authorization(TAG_NO_AUTH_REQUIRED)
4086 .RsaEncryptionKey(2048, 65537)
4087 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004088 .Digest(Digest::SHA_2_256)
4089 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004090 string message = "Hello World!";
4091
4092 auto params = AuthorizationSetBuilder()
4093 .Padding(PaddingMode::RSA_OAEP)
4094 .Digest(Digest::SHA_2_256)
4095 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale2b6c3512021-05-12 13:52:03 +01004096 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004097}
4098
4099/*
4100 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4101 *
4102 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4103 * with unsupported MGF digest.
4104 */
4105TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4106 ASSERT_EQ(ErrorCode::OK,
4107 GenerateKey(AuthorizationSetBuilder()
4108 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4109 .Authorization(TAG_NO_AUTH_REQUIRED)
4110 .RsaEncryptionKey(2048, 65537)
4111 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004112 .Digest(Digest::SHA_2_256)
4113 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004114 string message = "Hello World!";
4115
4116 auto params = AuthorizationSetBuilder()
4117 .Padding(PaddingMode::RSA_OAEP)
4118 .Digest(Digest::SHA_2_256)
4119 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale2b6c3512021-05-12 13:52:03 +01004120 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004121}
4122
4123/*
Selene Huang31ab4042020-04-29 04:22:39 -07004124 * EncryptionOperationsTest.RsaPkcs1Success
4125 *
4126 * Verifies that RSA PKCS encryption/decrypts works.
4127 */
4128TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4129 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4130 .Authorization(TAG_NO_AUTH_REQUIRED)
4131 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004132 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4133 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004134
4135 string message = "Hello World!";
4136 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale2b6c3512021-05-12 13:52:03 +01004137 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004138 EXPECT_EQ(2048U / 8, ciphertext1.size());
4139
David Drysdale2b6c3512021-05-12 13:52:03 +01004140 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004141 EXPECT_EQ(2048U / 8, ciphertext2.size());
4142
4143 // PKCS1 v1.5 randomizes padding so every result should be different.
4144 EXPECT_NE(ciphertext1, ciphertext2);
4145
4146 string plaintext = DecryptMessage(ciphertext1, params);
4147 EXPECT_EQ(message, plaintext);
4148
4149 // Decrypting corrupted ciphertext should fail.
4150 size_t offset_to_corrupt = random() % ciphertext1.size();
4151 char corrupt_byte;
4152 do {
4153 corrupt_byte = static_cast<char>(random() % 256);
4154 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4155 ciphertext1[offset_to_corrupt] = corrupt_byte;
4156
4157 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4158 string result;
4159 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4160 EXPECT_EQ(0U, result.size());
4161}
4162
4163/*
Selene Huang31ab4042020-04-29 04:22:39 -07004164 * EncryptionOperationsTest.EcdsaEncrypt
4165 *
4166 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4167 */
4168TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4169 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4170 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale308916b2021-06-08 15:46:11 +01004171 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004172 .Digest(Digest::NONE)
4173 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004174 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4175 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4176 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4177}
4178
4179/*
4180 * EncryptionOperationsTest.HmacEncrypt
4181 *
4182 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4183 */
4184TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4185 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4186 .Authorization(TAG_NO_AUTH_REQUIRED)
4187 .HmacKey(128)
4188 .Digest(Digest::SHA_2_256)
4189 .Padding(PaddingMode::NONE)
4190 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4191 auto params = AuthorizationSetBuilder()
4192 .Digest(Digest::SHA_2_256)
4193 .Padding(PaddingMode::NONE)
4194 .Authorization(TAG_MAC_LENGTH, 128);
4195 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4196 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4197}
4198
4199/*
4200 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4201 *
4202 * Verifies that AES ECB mode works.
4203 */
4204TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4205 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4206 .Authorization(TAG_NO_AUTH_REQUIRED)
4207 .AesEncryptionKey(128)
4208 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4209 .Padding(PaddingMode::NONE)));
4210
4211 ASSERT_GT(key_blob_.size(), 0U);
4212 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4213
4214 // Two-block message.
4215 string message = "12345678901234567890123456789012";
4216 string ciphertext1 = EncryptMessage(message, params);
4217 EXPECT_EQ(message.size(), ciphertext1.size());
4218
4219 string ciphertext2 = EncryptMessage(string(message), params);
4220 EXPECT_EQ(message.size(), ciphertext2.size());
4221
4222 // ECB is deterministic.
4223 EXPECT_EQ(ciphertext1, ciphertext2);
4224
4225 string plaintext = DecryptMessage(ciphertext1, params);
4226 EXPECT_EQ(message, plaintext);
4227}
4228
4229/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004230 * EncryptionOperationsTest.AesEcbUnknownTag
4231 *
4232 * Verifies that AES ECB operations ignore unknown tags.
4233 */
4234TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4235 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4236 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4237 KeyParameter unknown_param;
4238 unknown_param.tag = unknown_tag;
4239
4240 vector<KeyCharacteristics> key_characteristics;
4241 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4242 .Authorization(TAG_NO_AUTH_REQUIRED)
4243 .AesEncryptionKey(128)
4244 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4245 .Padding(PaddingMode::NONE)
4246 .Authorization(unknown_param),
4247 &key_blob_, &key_characteristics));
4248 ASSERT_GT(key_blob_.size(), 0U);
4249
4250 // Unknown tags should not be returned in key characteristics.
4251 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4252 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4253 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4254 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4255
4256 // Encrypt without mentioning the unknown parameter.
4257 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4258 string message = "12345678901234567890123456789012";
4259 string ciphertext = EncryptMessage(message, params);
4260 EXPECT_EQ(message.size(), ciphertext.size());
4261
4262 // Decrypt including the unknown parameter.
4263 auto decrypt_params = AuthorizationSetBuilder()
4264 .BlockMode(BlockMode::ECB)
4265 .Padding(PaddingMode::NONE)
4266 .Authorization(unknown_param);
4267 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4268 EXPECT_EQ(message, plaintext);
4269}
4270
4271/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004272 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004273 *
4274 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4275 */
4276TEST_P(EncryptionOperationsTest, AesWrongMode) {
4277 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4278 .Authorization(TAG_NO_AUTH_REQUIRED)
4279 .AesEncryptionKey(128)
4280 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4281 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004282 ASSERT_GT(key_blob_.size(), 0U);
4283
Selene Huang31ab4042020-04-29 04:22:39 -07004284 EXPECT_EQ(
4285 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4286 Begin(KeyPurpose::ENCRYPT,
4287 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4288}
4289
4290/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004291 * EncryptionOperationsTest.AesWrongPadding
4292 *
4293 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4294 */
4295TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4297 .Authorization(TAG_NO_AUTH_REQUIRED)
4298 .AesEncryptionKey(128)
4299 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4300 .Padding(PaddingMode::NONE)));
4301 ASSERT_GT(key_blob_.size(), 0U);
4302
4303 EXPECT_EQ(
4304 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4305 Begin(KeyPurpose::ENCRYPT,
4306 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4307}
4308
4309/*
4310 * EncryptionOperationsTest.AesInvalidParams
4311 *
4312 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4313 */
4314TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4315 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4316 .Authorization(TAG_NO_AUTH_REQUIRED)
4317 .AesEncryptionKey(128)
4318 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4319 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4320 .Padding(PaddingMode::NONE)
4321 .Padding(PaddingMode::PKCS7)));
4322 ASSERT_GT(key_blob_.size(), 0U);
4323
4324 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4325 .BlockMode(BlockMode::CBC)
4326 .BlockMode(BlockMode::ECB)
4327 .Padding(PaddingMode::NONE));
4328 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4329 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4330
4331 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4332 .BlockMode(BlockMode::ECB)
4333 .Padding(PaddingMode::NONE)
4334 .Padding(PaddingMode::PKCS7));
4335 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4336 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4337}
4338
4339/*
Selene Huang31ab4042020-04-29 04:22:39 -07004340 * EncryptionOperationsTest.AesWrongPurpose
4341 *
4342 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4343 * specified.
4344 */
4345TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4346 auto err = GenerateKey(AuthorizationSetBuilder()
4347 .Authorization(TAG_NO_AUTH_REQUIRED)
4348 .AesKey(128)
4349 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4350 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4351 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4352 .Padding(PaddingMode::NONE));
4353 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4354 ASSERT_GT(key_blob_.size(), 0U);
4355
4356 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4357 .BlockMode(BlockMode::GCM)
4358 .Padding(PaddingMode::NONE)
4359 .Authorization(TAG_MAC_LENGTH, 128));
4360 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4361
4362 CheckedDeleteKey();
4363
4364 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4365 .Authorization(TAG_NO_AUTH_REQUIRED)
4366 .AesKey(128)
4367 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4368 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4369 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4370 .Padding(PaddingMode::NONE)));
4371
4372 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4373 .BlockMode(BlockMode::GCM)
4374 .Padding(PaddingMode::NONE)
4375 .Authorization(TAG_MAC_LENGTH, 128));
4376 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4377}
4378
4379/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004380 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004381 *
4382 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4383 * multiple of the block size and no padding is specified.
4384 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004385TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4386 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4387 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4388 .Authorization(TAG_NO_AUTH_REQUIRED)
4389 .AesEncryptionKey(128)
4390 .Authorization(TAG_BLOCK_MODE, blockMode)
4391 .Padding(PaddingMode::NONE)));
4392 // Message is slightly shorter than two blocks.
4393 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004394
David Drysdaled2cc8c22021-04-15 13:29:45 +01004395 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4396 AuthorizationSet out_params;
4397 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4398 string ciphertext;
4399 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4400 EXPECT_EQ(0U, ciphertext.size());
4401
4402 CheckedDeleteKey();
4403 }
Selene Huang31ab4042020-04-29 04:22:39 -07004404}
4405
4406/*
4407 * EncryptionOperationsTest.AesEcbPkcs7Padding
4408 *
4409 * Verifies that AES PKCS7 padding works for any message length.
4410 */
4411TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4412 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4413 .Authorization(TAG_NO_AUTH_REQUIRED)
4414 .AesEncryptionKey(128)
4415 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4416 .Padding(PaddingMode::PKCS7)));
4417
4418 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4419
4420 // Try various message lengths; all should work.
4421 for (size_t i = 0; i < 32; ++i) {
4422 string message(i, 'a');
4423 string ciphertext = EncryptMessage(message, params);
4424 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4425 string plaintext = DecryptMessage(ciphertext, params);
4426 EXPECT_EQ(message, plaintext);
4427 }
4428}
4429
4430/*
4431 * EncryptionOperationsTest.AesEcbWrongPadding
4432 *
4433 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4434 * specified.
4435 */
4436TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4437 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4438 .Authorization(TAG_NO_AUTH_REQUIRED)
4439 .AesEncryptionKey(128)
4440 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4441 .Padding(PaddingMode::NONE)));
4442
4443 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4444
4445 // Try various message lengths; all should fail
4446 for (size_t i = 0; i < 32; ++i) {
4447 string message(i, 'a');
4448 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4449 }
4450}
4451
4452/*
4453 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4454 *
4455 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4456 */
4457TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4458 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4459 .Authorization(TAG_NO_AUTH_REQUIRED)
4460 .AesEncryptionKey(128)
4461 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4462 .Padding(PaddingMode::PKCS7)));
4463
4464 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4465
4466 string message = "a";
4467 string ciphertext = EncryptMessage(message, params);
4468 EXPECT_EQ(16U, ciphertext.size());
4469 EXPECT_NE(ciphertext, message);
4470 ++ciphertext[ciphertext.size() / 2];
4471
4472 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4473 string plaintext;
4474 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &plaintext));
4475}
4476
4477vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4478 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004479 EXPECT_TRUE(iv);
4480 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004481}
4482
4483/*
4484 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4485 *
4486 * Verifies that AES CTR mode works.
4487 */
4488TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4489 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4490 .Authorization(TAG_NO_AUTH_REQUIRED)
4491 .AesEncryptionKey(128)
4492 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4493 .Padding(PaddingMode::NONE)));
4494
4495 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4496
4497 string message = "123";
4498 AuthorizationSet out_params;
4499 string ciphertext1 = EncryptMessage(message, params, &out_params);
4500 vector<uint8_t> iv1 = CopyIv(out_params);
4501 EXPECT_EQ(16U, iv1.size());
4502
4503 EXPECT_EQ(message.size(), ciphertext1.size());
4504
4505 out_params.Clear();
4506 string ciphertext2 = EncryptMessage(message, params, &out_params);
4507 vector<uint8_t> iv2 = CopyIv(out_params);
4508 EXPECT_EQ(16U, iv2.size());
4509
4510 // IVs should be random, so ciphertexts should differ.
4511 EXPECT_NE(ciphertext1, ciphertext2);
4512
4513 auto params_iv1 =
4514 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4515 auto params_iv2 =
4516 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4517
4518 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4519 EXPECT_EQ(message, plaintext);
4520 plaintext = DecryptMessage(ciphertext2, params_iv2);
4521 EXPECT_EQ(message, plaintext);
4522
4523 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4524 plaintext = DecryptMessage(ciphertext1, params_iv2);
4525 EXPECT_NE(message, plaintext);
4526 plaintext = DecryptMessage(ciphertext2, params_iv1);
4527 EXPECT_NE(message, plaintext);
4528}
4529
4530/*
4531 * EncryptionOperationsTest.AesIncremental
4532 *
4533 * Verifies that AES works, all modes, when provided data in various size increments.
4534 */
4535TEST_P(EncryptionOperationsTest, AesIncremental) {
4536 auto block_modes = {
4537 BlockMode::ECB,
4538 BlockMode::CBC,
4539 BlockMode::CTR,
4540 BlockMode::GCM,
4541 };
4542
4543 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4544 .Authorization(TAG_NO_AUTH_REQUIRED)
4545 .AesEncryptionKey(128)
4546 .BlockMode(block_modes)
4547 .Padding(PaddingMode::NONE)
4548 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4549
4550 for (int increment = 1; increment <= 240; ++increment) {
4551 for (auto block_mode : block_modes) {
4552 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004553 auto params =
4554 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4555 if (block_mode == BlockMode::GCM) {
4556 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4557 }
Selene Huang31ab4042020-04-29 04:22:39 -07004558
4559 AuthorizationSet output_params;
4560 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4561
4562 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004563 string to_send;
4564 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004565 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004566 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004567 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4568 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004569
4570 switch (block_mode) {
4571 case BlockMode::GCM:
4572 EXPECT_EQ(message.size() + 16, ciphertext.size());
4573 break;
4574 case BlockMode::CTR:
4575 EXPECT_EQ(message.size(), ciphertext.size());
4576 break;
4577 case BlockMode::CBC:
4578 case BlockMode::ECB:
4579 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4580 break;
4581 }
4582
4583 auto iv = output_params.GetTagValue(TAG_NONCE);
4584 switch (block_mode) {
4585 case BlockMode::CBC:
4586 case BlockMode::GCM:
4587 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004588 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4589 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4590 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004591 break;
4592
4593 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004594 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004595 break;
4596 }
4597
4598 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4599 << "Decrypt begin() failed for block mode " << block_mode;
4600
4601 string plaintext;
4602 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004603 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004604 }
4605 ErrorCode error = Finish(to_send, &plaintext);
4606 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4607 << " and increment " << increment;
4608 if (error == ErrorCode::OK) {
4609 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4610 << block_mode << " and increment " << increment;
4611 }
4612 }
4613 }
4614}
4615
4616struct AesCtrSp80038aTestVector {
4617 const char* key;
4618 const char* nonce;
4619 const char* plaintext;
4620 const char* ciphertext;
4621};
4622
4623// These test vectors are taken from
4624// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4625static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4626 // AES-128
4627 {
4628 "2b7e151628aed2a6abf7158809cf4f3c",
4629 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4630 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4631 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4632 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4633 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4634 },
4635 // AES-192
4636 {
4637 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4638 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4639 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4640 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4641 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4642 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4643 },
4644 // AES-256
4645 {
4646 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4647 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4648 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4649 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4650 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4651 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4652 },
4653};
4654
4655/*
4656 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4657 *
4658 * Verifies AES CTR implementation against SP800-38A test vectors.
4659 */
4660TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4661 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4662 for (size_t i = 0; i < 3; i++) {
4663 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4664 const string key = hex2str(test.key);
4665 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4666 InvalidSizes.end())
4667 continue;
4668 const string nonce = hex2str(test.nonce);
4669 const string plaintext = hex2str(test.plaintext);
4670 const string ciphertext = hex2str(test.ciphertext);
4671 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4672 }
4673}
4674
4675/*
4676 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4677 *
4678 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4679 */
4680TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4681 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4682 .Authorization(TAG_NO_AUTH_REQUIRED)
4683 .AesEncryptionKey(128)
4684 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4685 .Padding(PaddingMode::PKCS7)));
4686 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4687 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4688}
4689
4690/*
4691 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4692 *
4693 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4694 */
4695TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4696 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4697 .Authorization(TAG_NO_AUTH_REQUIRED)
4698 .AesEncryptionKey(128)
4699 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4700 .Authorization(TAG_CALLER_NONCE)
4701 .Padding(PaddingMode::NONE)));
4702
4703 auto params = AuthorizationSetBuilder()
4704 .BlockMode(BlockMode::CTR)
4705 .Padding(PaddingMode::NONE)
4706 .Authorization(TAG_NONCE, AidlBuf(string(1, '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(15, 'a')));
4713 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4714
4715 params = AuthorizationSetBuilder()
4716 .BlockMode(BlockMode::CTR)
4717 .Padding(PaddingMode::NONE)
4718 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4719 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4720}
4721
4722/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004723 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004724 *
4725 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4726 */
4727TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4728 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4729 .Authorization(TAG_NO_AUTH_REQUIRED)
4730 .AesEncryptionKey(128)
4731 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4732 .Padding(PaddingMode::NONE)));
4733 // Two-block message.
4734 string message = "12345678901234567890123456789012";
4735 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4736 AuthorizationSet out_params;
4737 string ciphertext1 = EncryptMessage(message, params, &out_params);
4738 vector<uint8_t> iv1 = CopyIv(out_params);
4739 EXPECT_EQ(message.size(), ciphertext1.size());
4740
4741 out_params.Clear();
4742
4743 string ciphertext2 = EncryptMessage(message, params, &out_params);
4744 vector<uint8_t> iv2 = CopyIv(out_params);
4745 EXPECT_EQ(message.size(), ciphertext2.size());
4746
4747 // IVs should be random, so ciphertexts should differ.
4748 EXPECT_NE(ciphertext1, ciphertext2);
4749
4750 params.push_back(TAG_NONCE, iv1);
4751 string plaintext = DecryptMessage(ciphertext1, params);
4752 EXPECT_EQ(message, plaintext);
4753}
4754
4755/*
4756 * EncryptionOperationsTest.AesCallerNonce
4757 *
4758 * Verifies that AES caller-provided nonces work correctly.
4759 */
4760TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4761 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4762 .Authorization(TAG_NO_AUTH_REQUIRED)
4763 .AesEncryptionKey(128)
4764 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4765 .Authorization(TAG_CALLER_NONCE)
4766 .Padding(PaddingMode::NONE)));
4767
4768 string message = "12345678901234567890123456789012";
4769
4770 // Don't specify nonce, should get a random one.
4771 AuthorizationSetBuilder params =
4772 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4773 AuthorizationSet out_params;
4774 string ciphertext = EncryptMessage(message, params, &out_params);
4775 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004776 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004777
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004778 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004779 string plaintext = DecryptMessage(ciphertext, params);
4780 EXPECT_EQ(message, plaintext);
4781
4782 // Now specify a nonce, should also work.
4783 params = AuthorizationSetBuilder()
4784 .BlockMode(BlockMode::CBC)
4785 .Padding(PaddingMode::NONE)
4786 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4787 out_params.Clear();
4788 ciphertext = EncryptMessage(message, params, &out_params);
4789
4790 // Decrypt with correct nonce.
4791 plaintext = DecryptMessage(ciphertext, params);
4792 EXPECT_EQ(message, plaintext);
4793
4794 // Try with wrong nonce.
4795 params = AuthorizationSetBuilder()
4796 .BlockMode(BlockMode::CBC)
4797 .Padding(PaddingMode::NONE)
4798 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4799 plaintext = DecryptMessage(ciphertext, params);
4800 EXPECT_NE(message, plaintext);
4801}
4802
4803/*
4804 * EncryptionOperationsTest.AesCallerNonceProhibited
4805 *
4806 * Verifies that caller-provided nonces are not permitted when not specified in the key
4807 * authorizations.
4808 */
4809TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4810 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4811 .Authorization(TAG_NO_AUTH_REQUIRED)
4812 .AesEncryptionKey(128)
4813 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4814 .Padding(PaddingMode::NONE)));
4815
4816 string message = "12345678901234567890123456789012";
4817
4818 // Don't specify nonce, should get a random one.
4819 AuthorizationSetBuilder params =
4820 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4821 AuthorizationSet out_params;
4822 string ciphertext = EncryptMessage(message, params, &out_params);
4823 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004824 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004825
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004826 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004827 string plaintext = DecryptMessage(ciphertext, params);
4828 EXPECT_EQ(message, plaintext);
4829
4830 // Now specify a nonce, should fail
4831 params = AuthorizationSetBuilder()
4832 .BlockMode(BlockMode::CBC)
4833 .Padding(PaddingMode::NONE)
4834 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4835 out_params.Clear();
4836 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4837}
4838
4839/*
4840 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4841 *
4842 * Verifies that AES GCM mode works.
4843 */
4844TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4845 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4846 .Authorization(TAG_NO_AUTH_REQUIRED)
4847 .AesEncryptionKey(128)
4848 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4849 .Padding(PaddingMode::NONE)
4850 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4851
4852 string aad = "foobar";
4853 string message = "123456789012345678901234567890123456";
4854
4855 auto begin_params = AuthorizationSetBuilder()
4856 .BlockMode(BlockMode::GCM)
4857 .Padding(PaddingMode::NONE)
4858 .Authorization(TAG_MAC_LENGTH, 128);
4859
Selene Huang31ab4042020-04-29 04:22:39 -07004860 // Encrypt
4861 AuthorizationSet begin_out_params;
4862 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4863 << "Begin encrypt";
4864 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004865 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4866 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004867 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4868
4869 // Grab nonce
4870 begin_params.push_back(begin_out_params);
4871
4872 // Decrypt.
4873 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004874 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004875 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004876 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004877 EXPECT_EQ(message.length(), plaintext.length());
4878 EXPECT_EQ(message, plaintext);
4879}
4880
4881/*
4882 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4883 *
4884 * Verifies that AES GCM mode works, even when there's a long delay
4885 * between operations.
4886 */
4887TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4888 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4889 .Authorization(TAG_NO_AUTH_REQUIRED)
4890 .AesEncryptionKey(128)
4891 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4892 .Padding(PaddingMode::NONE)
4893 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4894
4895 string aad = "foobar";
4896 string message = "123456789012345678901234567890123456";
4897
4898 auto begin_params = AuthorizationSetBuilder()
4899 .BlockMode(BlockMode::GCM)
4900 .Padding(PaddingMode::NONE)
4901 .Authorization(TAG_MAC_LENGTH, 128);
4902
Selene Huang31ab4042020-04-29 04:22:39 -07004903 // Encrypt
4904 AuthorizationSet begin_out_params;
4905 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4906 << "Begin encrypt";
4907 string ciphertext;
4908 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004909 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004910 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004911 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004912
4913 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4914
4915 // Grab nonce
4916 begin_params.push_back(begin_out_params);
4917
4918 // Decrypt.
4919 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4920 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004921 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004922 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004923 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004924 sleep(5);
4925 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4926 EXPECT_EQ(message.length(), plaintext.length());
4927 EXPECT_EQ(message, plaintext);
4928}
4929
4930/*
4931 * EncryptionOperationsTest.AesGcmDifferentNonces
4932 *
4933 * Verifies that encrypting the same data with different nonces produces different outputs.
4934 */
4935TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4936 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4937 .Authorization(TAG_NO_AUTH_REQUIRED)
4938 .AesEncryptionKey(128)
4939 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4940 .Padding(PaddingMode::NONE)
4941 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4942 .Authorization(TAG_CALLER_NONCE)));
4943
4944 string aad = "foobar";
4945 string message = "123456789012345678901234567890123456";
4946 string nonce1 = "000000000000";
4947 string nonce2 = "111111111111";
4948 string nonce3 = "222222222222";
4949
4950 string ciphertext1 =
4951 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4952 string ciphertext2 =
4953 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4954 string ciphertext3 =
4955 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4956
4957 ASSERT_NE(ciphertext1, ciphertext2);
4958 ASSERT_NE(ciphertext1, ciphertext3);
4959 ASSERT_NE(ciphertext2, ciphertext3);
4960}
4961
4962/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004963 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4964 *
4965 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4966 */
4967TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4968 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4969 .Authorization(TAG_NO_AUTH_REQUIRED)
4970 .AesEncryptionKey(128)
4971 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4972 .Padding(PaddingMode::NONE)
4973 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4974
4975 string aad = "foobar";
4976 string message = "123456789012345678901234567890123456";
4977
4978 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4979 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4980 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4981
4982 ASSERT_NE(ciphertext1, ciphertext2);
4983 ASSERT_NE(ciphertext1, ciphertext3);
4984 ASSERT_NE(ciphertext2, ciphertext3);
4985}
4986
4987/*
Selene Huang31ab4042020-04-29 04:22:39 -07004988 * EncryptionOperationsTest.AesGcmTooShortTag
4989 *
4990 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4991 */
4992TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4993 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4994 .Authorization(TAG_NO_AUTH_REQUIRED)
4995 .AesEncryptionKey(128)
4996 .BlockMode(BlockMode::GCM)
4997 .Padding(PaddingMode::NONE)
4998 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4999 string message = "123456789012345678901234567890123456";
5000 auto params = AuthorizationSetBuilder()
5001 .BlockMode(BlockMode::GCM)
5002 .Padding(PaddingMode::NONE)
5003 .Authorization(TAG_MAC_LENGTH, 96);
5004
5005 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5006}
5007
5008/*
5009 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
5010 *
5011 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
5012 */
5013TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
5014 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5015 .Authorization(TAG_NO_AUTH_REQUIRED)
5016 .AesEncryptionKey(128)
5017 .BlockMode(BlockMode::GCM)
5018 .Padding(PaddingMode::NONE)
5019 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5020 string aad = "foobar";
5021 string message = "123456789012345678901234567890123456";
5022 auto params = AuthorizationSetBuilder()
5023 .BlockMode(BlockMode::GCM)
5024 .Padding(PaddingMode::NONE)
5025 .Authorization(TAG_MAC_LENGTH, 128);
5026
Selene Huang31ab4042020-04-29 04:22:39 -07005027 // Encrypt
5028 AuthorizationSet begin_out_params;
5029 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5030 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005031 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005032
5033 AuthorizationSet finish_out_params;
5034 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005035 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5036 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005037
5038 params = AuthorizationSetBuilder()
5039 .Authorizations(begin_out_params)
5040 .BlockMode(BlockMode::GCM)
5041 .Padding(PaddingMode::NONE)
5042 .Authorization(TAG_MAC_LENGTH, 96);
5043
5044 // Decrypt.
5045 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5046}
5047
5048/*
5049 * EncryptionOperationsTest.AesGcmCorruptKey
5050 *
5051 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5052 */
5053TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5054 const uint8_t nonce_bytes[] = {
5055 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5056 };
5057 string nonce = make_string(nonce_bytes);
5058 const uint8_t ciphertext_bytes[] = {
5059 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5060 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5061 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5062 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5063 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5064 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5065 };
5066 string ciphertext = make_string(ciphertext_bytes);
5067
5068 auto params = AuthorizationSetBuilder()
5069 .BlockMode(BlockMode::GCM)
5070 .Padding(PaddingMode::NONE)
5071 .Authorization(TAG_MAC_LENGTH, 128)
5072 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5073
5074 auto import_params = AuthorizationSetBuilder()
5075 .Authorization(TAG_NO_AUTH_REQUIRED)
5076 .AesEncryptionKey(128)
5077 .BlockMode(BlockMode::GCM)
5078 .Padding(PaddingMode::NONE)
5079 .Authorization(TAG_CALLER_NONCE)
5080 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5081
5082 // Import correct key and decrypt
5083 const uint8_t key_bytes[] = {
5084 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5085 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5086 };
5087 string key = make_string(key_bytes);
5088 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5089 string plaintext = DecryptMessage(ciphertext, params);
5090 CheckedDeleteKey();
5091
5092 // Corrupt key and attempt to decrypt
5093 key[0] = 0;
5094 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5095 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5096 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5097 CheckedDeleteKey();
5098}
5099
5100/*
5101 * EncryptionOperationsTest.AesGcmAadNoData
5102 *
5103 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5104 * encrypt.
5105 */
5106TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5107 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5108 .Authorization(TAG_NO_AUTH_REQUIRED)
5109 .AesEncryptionKey(128)
5110 .BlockMode(BlockMode::GCM)
5111 .Padding(PaddingMode::NONE)
5112 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5113
5114 string aad = "1234567890123456";
5115 auto params = AuthorizationSetBuilder()
5116 .BlockMode(BlockMode::GCM)
5117 .Padding(PaddingMode::NONE)
5118 .Authorization(TAG_MAC_LENGTH, 128);
5119
Selene Huang31ab4042020-04-29 04:22:39 -07005120 // Encrypt
5121 AuthorizationSet begin_out_params;
5122 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5123 string ciphertext;
5124 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005125 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5126 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005127 EXPECT_TRUE(finish_out_params.empty());
5128
5129 // Grab nonce
5130 params.push_back(begin_out_params);
5131
5132 // Decrypt.
5133 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005134 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005135 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005136 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005137
5138 EXPECT_TRUE(finish_out_params.empty());
5139
5140 EXPECT_EQ("", plaintext);
5141}
5142
5143/*
5144 * EncryptionOperationsTest.AesGcmMultiPartAad
5145 *
5146 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5147 * chunks.
5148 */
5149TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5150 const size_t tag_bits = 128;
5151 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5152 .Authorization(TAG_NO_AUTH_REQUIRED)
5153 .AesEncryptionKey(128)
5154 .BlockMode(BlockMode::GCM)
5155 .Padding(PaddingMode::NONE)
5156 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5157
5158 string message = "123456789012345678901234567890123456";
5159 auto begin_params = AuthorizationSetBuilder()
5160 .BlockMode(BlockMode::GCM)
5161 .Padding(PaddingMode::NONE)
5162 .Authorization(TAG_MAC_LENGTH, tag_bits);
5163 AuthorizationSet begin_out_params;
5164
Selene Huang31ab4042020-04-29 04:22:39 -07005165 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5166
5167 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005168 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5169 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005170 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005171 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5172 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005173
Selene Huang31ab4042020-04-29 04:22:39 -07005174 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005175 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005176
5177 // Grab nonce.
5178 begin_params.push_back(begin_out_params);
5179
5180 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005181 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005182 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005183 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005184 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005185 EXPECT_EQ(message, plaintext);
5186}
5187
5188/*
5189 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5190 *
5191 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5192 */
5193TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5194 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5195 .Authorization(TAG_NO_AUTH_REQUIRED)
5196 .AesEncryptionKey(128)
5197 .BlockMode(BlockMode::GCM)
5198 .Padding(PaddingMode::NONE)
5199 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5200
5201 string message = "123456789012345678901234567890123456";
5202 auto begin_params = AuthorizationSetBuilder()
5203 .BlockMode(BlockMode::GCM)
5204 .Padding(PaddingMode::NONE)
5205 .Authorization(TAG_MAC_LENGTH, 128);
5206 AuthorizationSet begin_out_params;
5207
Selene Huang31ab4042020-04-29 04:22:39 -07005208 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5209
Shawn Willden92d79c02021-02-19 07:31:55 -07005210 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005211 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005212 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5213 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005214
David Drysdaled2cc8c22021-04-15 13:29:45 +01005215 // The failure should have already cancelled the operation.
5216 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5217
Shawn Willden92d79c02021-02-19 07:31:55 -07005218 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005219}
5220
5221/*
5222 * EncryptionOperationsTest.AesGcmBadAad
5223 *
5224 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5225 */
5226TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5227 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5228 .Authorization(TAG_NO_AUTH_REQUIRED)
5229 .AesEncryptionKey(128)
5230 .BlockMode(BlockMode::GCM)
5231 .Padding(PaddingMode::NONE)
5232 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5233
5234 string message = "12345678901234567890123456789012";
5235 auto begin_params = AuthorizationSetBuilder()
5236 .BlockMode(BlockMode::GCM)
5237 .Padding(PaddingMode::NONE)
5238 .Authorization(TAG_MAC_LENGTH, 128);
5239
Selene Huang31ab4042020-04-29 04:22:39 -07005240 // Encrypt
5241 AuthorizationSet begin_out_params;
5242 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005243 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005244 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005245 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005246
5247 // Grab nonce
5248 begin_params.push_back(begin_out_params);
5249
Selene Huang31ab4042020-04-29 04:22:39 -07005250 // Decrypt.
5251 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005252 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005253 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005254 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005255}
5256
5257/*
5258 * EncryptionOperationsTest.AesGcmWrongNonce
5259 *
5260 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5261 */
5262TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5263 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5264 .Authorization(TAG_NO_AUTH_REQUIRED)
5265 .AesEncryptionKey(128)
5266 .BlockMode(BlockMode::GCM)
5267 .Padding(PaddingMode::NONE)
5268 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5269
5270 string message = "12345678901234567890123456789012";
5271 auto begin_params = AuthorizationSetBuilder()
5272 .BlockMode(BlockMode::GCM)
5273 .Padding(PaddingMode::NONE)
5274 .Authorization(TAG_MAC_LENGTH, 128);
5275
Selene Huang31ab4042020-04-29 04:22:39 -07005276 // Encrypt
5277 AuthorizationSet begin_out_params;
5278 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005279 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005280 string ciphertext;
5281 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005282 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005283
5284 // Wrong nonce
5285 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5286
5287 // Decrypt.
5288 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005289 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005290 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005291 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005292
5293 // With wrong nonce, should have gotten garbage plaintext (or none).
5294 EXPECT_NE(message, plaintext);
5295}
5296
5297/*
5298 * EncryptionOperationsTest.AesGcmCorruptTag
5299 *
5300 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5301 */
5302TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5303 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5304 .Authorization(TAG_NO_AUTH_REQUIRED)
5305 .AesEncryptionKey(128)
5306 .BlockMode(BlockMode::GCM)
5307 .Padding(PaddingMode::NONE)
5308 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5309
5310 string aad = "1234567890123456";
5311 string message = "123456789012345678901234567890123456";
5312
5313 auto params = AuthorizationSetBuilder()
5314 .BlockMode(BlockMode::GCM)
5315 .Padding(PaddingMode::NONE)
5316 .Authorization(TAG_MAC_LENGTH, 128);
5317
Selene Huang31ab4042020-04-29 04:22:39 -07005318 // Encrypt
5319 AuthorizationSet begin_out_params;
5320 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005321 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005322 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005323 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005324
5325 // Corrupt tag
5326 ++(*ciphertext.rbegin());
5327
5328 // Grab nonce
5329 params.push_back(begin_out_params);
5330
5331 // Decrypt.
5332 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005333 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005334 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005335 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005336}
5337
5338/*
5339 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5340 *
5341 * Verifies that 3DES is basically functional.
5342 */
5343TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5344 auto auths = AuthorizationSetBuilder()
5345 .TripleDesEncryptionKey(168)
5346 .BlockMode(BlockMode::ECB)
5347 .Authorization(TAG_NO_AUTH_REQUIRED)
5348 .Padding(PaddingMode::NONE);
5349
5350 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5351 // Two-block message.
5352 string message = "1234567890123456";
5353 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5354 string ciphertext1 = EncryptMessage(message, inParams);
5355 EXPECT_EQ(message.size(), ciphertext1.size());
5356
5357 string ciphertext2 = EncryptMessage(string(message), inParams);
5358 EXPECT_EQ(message.size(), ciphertext2.size());
5359
5360 // ECB is deterministic.
5361 EXPECT_EQ(ciphertext1, ciphertext2);
5362
5363 string plaintext = DecryptMessage(ciphertext1, inParams);
5364 EXPECT_EQ(message, plaintext);
5365}
5366
5367/*
5368 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5369 *
5370 * Verifies that CBC keys reject ECB usage.
5371 */
5372TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5373 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5374 .TripleDesEncryptionKey(168)
5375 .BlockMode(BlockMode::CBC)
5376 .Authorization(TAG_NO_AUTH_REQUIRED)
5377 .Padding(PaddingMode::NONE)));
5378
5379 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5380 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5381}
5382
5383/*
5384 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5385 *
5386 * Tests ECB mode with PKCS#7 padding, various message sizes.
5387 */
5388TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5389 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5390 .TripleDesEncryptionKey(168)
5391 .BlockMode(BlockMode::ECB)
5392 .Authorization(TAG_NO_AUTH_REQUIRED)
5393 .Padding(PaddingMode::PKCS7)));
5394
5395 for (size_t i = 0; i < 32; ++i) {
5396 string message(i, 'a');
5397 auto inParams =
5398 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5399 string ciphertext = EncryptMessage(message, inParams);
5400 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5401 string plaintext = DecryptMessage(ciphertext, inParams);
5402 EXPECT_EQ(message, plaintext);
5403 }
5404}
5405
5406/*
5407 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5408 *
5409 * Verifies that keys configured for no padding reject PKCS7 padding
5410 */
5411TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5412 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5413 .TripleDesEncryptionKey(168)
5414 .BlockMode(BlockMode::ECB)
5415 .Authorization(TAG_NO_AUTH_REQUIRED)
5416 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005417 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5418 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005419}
5420
5421/*
5422 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5423 *
5424 * Verifies that corrupted padding is detected.
5425 */
5426TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5427 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5428 .TripleDesEncryptionKey(168)
5429 .BlockMode(BlockMode::ECB)
5430 .Authorization(TAG_NO_AUTH_REQUIRED)
5431 .Padding(PaddingMode::PKCS7)));
5432
5433 string message = "a";
5434 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5435 EXPECT_EQ(8U, ciphertext.size());
5436 EXPECT_NE(ciphertext, message);
5437 ++ciphertext[ciphertext.size() / 2];
5438
5439 AuthorizationSetBuilder begin_params;
5440 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5441 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
5442 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5443 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005444 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005445 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5446}
5447
5448struct TripleDesTestVector {
5449 const char* name;
5450 const KeyPurpose purpose;
5451 const BlockMode block_mode;
5452 const PaddingMode padding_mode;
5453 const char* key;
5454 const char* iv;
5455 const char* input;
5456 const char* output;
5457};
5458
5459// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5460// of the NIST vectors are multiples of the block size.
5461static const TripleDesTestVector kTripleDesTestVectors[] = {
5462 {
5463 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5464 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5465 "", // IV
5466 "329d86bdf1bc5af4", // input
5467 "d946c2756d78633f", // output
5468 },
5469 {
5470 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5471 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5472 "", // IV
5473 "6b1540781b01ce1997adae102dbf3c5b", // input
5474 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5475 },
5476 {
5477 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5478 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5479 "", // IV
5480 "6daad94ce08acfe7", // input
5481 "660e7d32dcc90e79", // output
5482 },
5483 {
5484 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5485 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5486 "", // IV
5487 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5488 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5489 },
5490 {
5491 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5492 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5493 "43f791134c5647ba", // IV
5494 "dcc153cef81d6f24", // input
5495 "92538bd8af18d3ba", // output
5496 },
5497 {
5498 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5499 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5500 "c2e999cb6249023c", // IV
5501 "c689aee38a301bb316da75db36f110b5", // input
5502 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5503 },
5504 {
5505 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5506 PaddingMode::PKCS7,
5507 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5508 "c2e999cb6249023c", // IV
5509 "c689aee38a301bb316da75db36f110b500", // input
5510 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5511 },
5512 {
5513 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5514 PaddingMode::PKCS7,
5515 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5516 "c2e999cb6249023c", // IV
5517 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5518 "c689aee38a301bb316da75db36f110b500", // output
5519 },
5520 {
5521 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5522 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5523 "41746c7e442d3681", // IV
5524 "c53a7b0ec40600fe", // input
5525 "d4f00eb455de1034", // output
5526 },
5527 {
5528 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5529 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5530 "3982bc02c3727d45", // IV
5531 "6006f10adef52991fcc777a1238bbb65", // input
5532 "edae09288e9e3bc05746d872b48e3b29", // output
5533 },
5534};
5535
5536/*
5537 * EncryptionOperationsTest.TripleDesTestVector
5538 *
5539 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5540 */
5541TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5542 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5543 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5544 SCOPED_TRACE(test->name);
5545 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5546 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5547 hex2str(test->output));
5548 }
5549}
5550
5551/*
5552 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5553 *
5554 * Validates CBC mode functionality.
5555 */
5556TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5557 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5558 .TripleDesEncryptionKey(168)
5559 .BlockMode(BlockMode::CBC)
5560 .Authorization(TAG_NO_AUTH_REQUIRED)
5561 .Padding(PaddingMode::NONE)));
5562
5563 ASSERT_GT(key_blob_.size(), 0U);
5564
5565 // Two-block message.
5566 string message = "1234567890123456";
5567 vector<uint8_t> iv1;
5568 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5569 EXPECT_EQ(message.size(), ciphertext1.size());
5570
5571 vector<uint8_t> iv2;
5572 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5573 EXPECT_EQ(message.size(), ciphertext2.size());
5574
5575 // IVs should be random, so ciphertexts should differ.
5576 EXPECT_NE(iv1, iv2);
5577 EXPECT_NE(ciphertext1, ciphertext2);
5578
5579 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5580 EXPECT_EQ(message, plaintext);
5581}
5582
5583/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005584 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5585 *
5586 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5587 */
5588TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5589 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5590 .TripleDesEncryptionKey(168)
5591 .BlockMode(BlockMode::CBC)
5592 .Authorization(TAG_NO_AUTH_REQUIRED)
5593 .Authorization(TAG_CALLER_NONCE)
5594 .Padding(PaddingMode::NONE)));
5595 auto params = AuthorizationSetBuilder()
5596 .BlockMode(BlockMode::CBC)
5597 .Padding(PaddingMode::NONE)
5598 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5599 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5600}
5601
5602/*
Selene Huang31ab4042020-04-29 04:22:39 -07005603 * EncryptionOperationsTest.TripleDesCallerIv
5604 *
5605 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5606 */
5607TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5608 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5609 .TripleDesEncryptionKey(168)
5610 .BlockMode(BlockMode::CBC)
5611 .Authorization(TAG_NO_AUTH_REQUIRED)
5612 .Authorization(TAG_CALLER_NONCE)
5613 .Padding(PaddingMode::NONE)));
5614 string message = "1234567890123456";
5615 vector<uint8_t> iv;
5616 // Don't specify IV, should get a random one.
5617 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5618 EXPECT_EQ(message.size(), ciphertext1.size());
5619 EXPECT_EQ(8U, iv.size());
5620
5621 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5622 EXPECT_EQ(message, plaintext);
5623
5624 // Now specify an IV, should also work.
5625 iv = AidlBuf("abcdefgh");
5626 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5627
5628 // Decrypt with correct IV.
5629 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5630 EXPECT_EQ(message, plaintext);
5631
5632 // Now try with wrong IV.
5633 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5634 EXPECT_NE(message, plaintext);
5635}
5636
5637/*
5638 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5639 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005640 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005641 */
5642TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5643 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5644 .TripleDesEncryptionKey(168)
5645 .BlockMode(BlockMode::CBC)
5646 .Authorization(TAG_NO_AUTH_REQUIRED)
5647 .Padding(PaddingMode::NONE)));
5648
5649 string message = "12345678901234567890123456789012";
5650 vector<uint8_t> iv;
5651 // Don't specify nonce, should get a random one.
5652 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5653 EXPECT_EQ(message.size(), ciphertext1.size());
5654 EXPECT_EQ(8U, iv.size());
5655
5656 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5657 EXPECT_EQ(message, plaintext);
5658
5659 // Now specify a nonce, should fail.
5660 auto input_params = AuthorizationSetBuilder()
5661 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5662 .BlockMode(BlockMode::CBC)
5663 .Padding(PaddingMode::NONE);
5664 AuthorizationSet output_params;
5665 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5666 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5667}
5668
5669/*
5670 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5671 *
5672 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5673 */
5674TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5675 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5676 .TripleDesEncryptionKey(168)
5677 .BlockMode(BlockMode::ECB)
5678 .Authorization(TAG_NO_AUTH_REQUIRED)
5679 .Padding(PaddingMode::NONE)));
5680 // Two-block message.
5681 string message = "1234567890123456";
5682 auto begin_params =
5683 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5684 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5685}
5686
5687/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005688 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005689 *
5690 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5691 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005692TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5693 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5694 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5695 .TripleDesEncryptionKey(168)
5696 .BlockMode(blockMode)
5697 .Authorization(TAG_NO_AUTH_REQUIRED)
5698 .Padding(PaddingMode::NONE)));
5699 // Message is slightly shorter than two blocks.
5700 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005701
David Drysdaled2cc8c22021-04-15 13:29:45 +01005702 auto begin_params =
5703 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5704 AuthorizationSet output_params;
5705 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5706 string ciphertext;
5707 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5708
5709 CheckedDeleteKey();
5710 }
Selene Huang31ab4042020-04-29 04:22:39 -07005711}
5712
5713/*
5714 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5715 *
5716 * Verifies that PKCS7 padding works correctly in CBC mode.
5717 */
5718TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5719 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5720 .TripleDesEncryptionKey(168)
5721 .BlockMode(BlockMode::CBC)
5722 .Authorization(TAG_NO_AUTH_REQUIRED)
5723 .Padding(PaddingMode::PKCS7)));
5724
5725 // Try various message lengths; all should work.
5726 for (size_t i = 0; i < 32; ++i) {
5727 string message(i, 'a');
5728 vector<uint8_t> iv;
5729 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5730 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5731 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5732 EXPECT_EQ(message, plaintext);
5733 }
5734}
5735
5736/*
5737 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5738 *
5739 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5740 */
5741TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5742 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5743 .TripleDesEncryptionKey(168)
5744 .BlockMode(BlockMode::CBC)
5745 .Authorization(TAG_NO_AUTH_REQUIRED)
5746 .Padding(PaddingMode::NONE)));
5747
5748 // Try various message lengths; all should fail.
5749 for (size_t i = 0; i < 32; ++i) {
5750 auto begin_params =
5751 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5752 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5753 }
5754}
5755
5756/*
5757 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5758 *
5759 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5760 */
5761TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5762 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5763 .TripleDesEncryptionKey(168)
5764 .BlockMode(BlockMode::CBC)
5765 .Authorization(TAG_NO_AUTH_REQUIRED)
5766 .Padding(PaddingMode::PKCS7)));
5767
5768 string message = "a";
5769 vector<uint8_t> iv;
5770 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5771 EXPECT_EQ(8U, ciphertext.size());
5772 EXPECT_NE(ciphertext, message);
5773 ++ciphertext[ciphertext.size() / 2];
5774
5775 auto begin_params = AuthorizationSetBuilder()
5776 .BlockMode(BlockMode::CBC)
5777 .Padding(PaddingMode::PKCS7)
5778 .Authorization(TAG_NONCE, iv);
5779 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5780 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005781 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005782 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(&plaintext));
5783}
5784
5785/*
5786 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5787 *
5788 * Verifies that 3DES CBC works with many different input sizes.
5789 */
5790TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5791 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5792 .TripleDesEncryptionKey(168)
5793 .BlockMode(BlockMode::CBC)
5794 .Authorization(TAG_NO_AUTH_REQUIRED)
5795 .Padding(PaddingMode::NONE)));
5796
5797 int increment = 7;
5798 string message(240, 'a');
5799 AuthorizationSet input_params =
5800 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5801 AuthorizationSet output_params;
5802 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5803
5804 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005805 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005806 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005807 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5808 EXPECT_EQ(message.size(), ciphertext.size());
5809
5810 // Move TAG_NONCE into input_params
5811 input_params = output_params;
5812 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5813 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5814 output_params.Clear();
5815
5816 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5817 string plaintext;
5818 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005819 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005820 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5821 EXPECT_EQ(ciphertext.size(), plaintext.size());
5822 EXPECT_EQ(message, plaintext);
5823}
5824
5825INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5826
5827typedef KeyMintAidlTestBase MaxOperationsTest;
5828
5829/*
5830 * MaxOperationsTest.TestLimitAes
5831 *
5832 * Verifies that the max uses per boot tag works correctly with AES keys.
5833 */
5834TEST_P(MaxOperationsTest, TestLimitAes) {
5835 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5836
5837 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5838 .Authorization(TAG_NO_AUTH_REQUIRED)
5839 .AesEncryptionKey(128)
5840 .EcbMode()
5841 .Padding(PaddingMode::NONE)
5842 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5843
5844 string message = "1234567890123456";
5845
5846 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5847
5848 EncryptMessage(message, params);
5849 EncryptMessage(message, params);
5850 EncryptMessage(message, params);
5851
5852 // Fourth time should fail.
5853 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5854}
5855
5856/*
Qi Wud22ec842020-11-26 13:27:53 +08005857 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005858 *
5859 * Verifies that the max uses per boot tag works correctly with RSA keys.
5860 */
5861TEST_P(MaxOperationsTest, TestLimitRsa) {
5862 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5863
5864 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5865 .Authorization(TAG_NO_AUTH_REQUIRED)
5866 .RsaSigningKey(1024, 65537)
5867 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005868 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5869 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005870
5871 string message = "1234567890123456";
5872
5873 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5874
5875 SignMessage(message, params);
5876 SignMessage(message, params);
5877 SignMessage(message, params);
5878
5879 // Fourth time should fail.
5880 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5881}
5882
5883INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5884
Qi Wud22ec842020-11-26 13:27:53 +08005885typedef KeyMintAidlTestBase UsageCountLimitTest;
5886
5887/*
Qi Wubeefae42021-01-28 23:16:37 +08005888 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005889 *
Qi Wubeefae42021-01-28 23:16:37 +08005890 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005891 */
Qi Wubeefae42021-01-28 23:16:37 +08005892TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005893 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5894
5895 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5896 .Authorization(TAG_NO_AUTH_REQUIRED)
5897 .AesEncryptionKey(128)
5898 .EcbMode()
5899 .Padding(PaddingMode::NONE)
5900 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5901
5902 // Check the usage count limit tag appears in the authorizations.
5903 AuthorizationSet auths;
5904 for (auto& entry : key_characteristics_) {
5905 auths.push_back(AuthorizationSet(entry.authorizations));
5906 }
5907 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5908 << "key usage count limit " << 1U << " missing";
5909
5910 string message = "1234567890123456";
5911 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5912
Qi Wubeefae42021-01-28 23:16:37 +08005913 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5914 AuthorizationSet keystore_auths =
5915 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5916
Qi Wud22ec842020-11-26 13:27:53 +08005917 // First usage of AES key should work.
5918 EncryptMessage(message, params);
5919
Qi Wud22ec842020-11-26 13:27:53 +08005920 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5921 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5922 // must be invalidated from secure storage (such as RPMB partition).
5923 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5924 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005925 // Usage count limit tag is enforced by keystore, keymint does nothing.
5926 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005927 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5928 }
5929}
5930
5931/*
Qi Wubeefae42021-01-28 23:16:37 +08005932 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005933 *
Qi Wubeefae42021-01-28 23:16:37 +08005934 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005935 */
Qi Wubeefae42021-01-28 23:16:37 +08005936TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5937 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5938
5939 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5940 .Authorization(TAG_NO_AUTH_REQUIRED)
5941 .AesEncryptionKey(128)
5942 .EcbMode()
5943 .Padding(PaddingMode::NONE)
5944 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5945
5946 // Check the usage count limit tag appears in the authorizations.
5947 AuthorizationSet auths;
5948 for (auto& entry : key_characteristics_) {
5949 auths.push_back(AuthorizationSet(entry.authorizations));
5950 }
5951 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5952 << "key usage count limit " << 3U << " missing";
5953
5954 string message = "1234567890123456";
5955 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5956
5957 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5958 AuthorizationSet keystore_auths =
5959 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5960
5961 EncryptMessage(message, params);
5962 EncryptMessage(message, params);
5963 EncryptMessage(message, params);
5964
5965 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5966 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5967 // must be invalidated from secure storage (such as RPMB partition).
5968 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5969 } else {
5970 // Usage count limit tag is enforced by keystore, keymint does nothing.
5971 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5972 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5973 }
5974}
5975
5976/*
5977 * UsageCountLimitTest.TestSingleUseRsa
5978 *
5979 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5980 */
5981TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005982 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5983
5984 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5985 .Authorization(TAG_NO_AUTH_REQUIRED)
5986 .RsaSigningKey(1024, 65537)
5987 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005988 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5989 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005990
5991 // Check the usage count limit tag appears in the authorizations.
5992 AuthorizationSet auths;
5993 for (auto& entry : key_characteristics_) {
5994 auths.push_back(AuthorizationSet(entry.authorizations));
5995 }
5996 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5997 << "key usage count limit " << 1U << " missing";
5998
5999 string message = "1234567890123456";
6000 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6001
Qi Wubeefae42021-01-28 23:16:37 +08006002 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6003 AuthorizationSet keystore_auths =
6004 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6005
Qi Wud22ec842020-11-26 13:27:53 +08006006 // First usage of RSA key should work.
6007 SignMessage(message, params);
6008
Qi Wud22ec842020-11-26 13:27:53 +08006009 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6010 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6011 // must be invalidated from secure storage (such as RPMB partition).
6012 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6013 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006014 // Usage count limit tag is enforced by keystore, keymint does nothing.
6015 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
6016 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6017 }
6018}
6019
6020/*
6021 * UsageCountLimitTest.TestLimitUseRsa
6022 *
6023 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6024 */
6025TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
6026 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6027
6028 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6029 .Authorization(TAG_NO_AUTH_REQUIRED)
6030 .RsaSigningKey(1024, 65537)
6031 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006032 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6033 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006034
6035 // Check the usage count limit tag appears in the authorizations.
6036 AuthorizationSet auths;
6037 for (auto& entry : key_characteristics_) {
6038 auths.push_back(AuthorizationSet(entry.authorizations));
6039 }
6040 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6041 << "key usage count limit " << 3U << " missing";
6042
6043 string message = "1234567890123456";
6044 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6045
6046 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6047 AuthorizationSet keystore_auths =
6048 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6049
6050 SignMessage(message, params);
6051 SignMessage(message, params);
6052 SignMessage(message, params);
6053
6054 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6055 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6056 // must be invalidated from secure storage (such as RPMB partition).
6057 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6058 } else {
6059 // Usage count limit tag is enforced by keystore, keymint does nothing.
6060 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006061 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6062 }
6063}
6064
Qi Wu8e727f72021-02-11 02:49:33 +08006065/*
6066 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6067 *
6068 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6069 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6070 * in hardware.
6071 */
6072TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
6073 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6074
6075 auto error = GenerateKey(AuthorizationSetBuilder()
6076 .RsaSigningKey(2048, 65537)
6077 .Digest(Digest::NONE)
6078 .Padding(PaddingMode::NONE)
6079 .Authorization(TAG_NO_AUTH_REQUIRED)
6080 .Authorization(TAG_ROLLBACK_RESISTANCE)
6081 .SetDefaultValidity());
6082 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6083
6084 if (error == ErrorCode::OK) {
6085 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6086 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6087 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6088 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6089
6090 // The KeyMint should also enforce single use key in hardware when it supports rollback
6091 // resistance.
6092 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6093 .Authorization(TAG_NO_AUTH_REQUIRED)
6094 .RsaSigningKey(1024, 65537)
6095 .NoDigestOrPadding()
6096 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6097 .SetDefaultValidity()));
6098
6099 // Check the usage count limit tag appears in the hardware authorizations.
6100 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6101 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6102 << "key usage count limit " << 1U << " missing";
6103
6104 string message = "1234567890123456";
6105 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6106
6107 // First usage of RSA key should work.
6108 SignMessage(message, params);
6109
6110 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6111 // must be invalidated from secure storage (such as RPMB partition).
6112 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6113 }
6114}
6115
Qi Wud22ec842020-11-26 13:27:53 +08006116INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6117
David Drysdale7de9feb2021-03-05 14:56:19 +00006118typedef KeyMintAidlTestBase GetHardwareInfoTest;
6119
6120TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6121 // Retrieving hardware info should give the same result each time.
6122 KeyMintHardwareInfo info;
6123 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6124 KeyMintHardwareInfo info2;
6125 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6126 EXPECT_EQ(info, info2);
6127}
6128
6129INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6130
Selene Huang31ab4042020-04-29 04:22:39 -07006131typedef KeyMintAidlTestBase AddEntropyTest;
6132
6133/*
6134 * AddEntropyTest.AddEntropy
6135 *
6136 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6137 * is actually added.
6138 */
6139TEST_P(AddEntropyTest, AddEntropy) {
6140 string data = "foo";
6141 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6142}
6143
6144/*
6145 * AddEntropyTest.AddEmptyEntropy
6146 *
6147 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6148 */
6149TEST_P(AddEntropyTest, AddEmptyEntropy) {
6150 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6151}
6152
6153/*
6154 * AddEntropyTest.AddLargeEntropy
6155 *
6156 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6157 */
6158TEST_P(AddEntropyTest, AddLargeEntropy) {
6159 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6160}
6161
David Drysdalebb3d85e2021-04-13 11:15:51 +01006162/*
6163 * AddEntropyTest.AddTooLargeEntropy
6164 *
6165 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6166 */
6167TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6168 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6169 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6170}
6171
Selene Huang31ab4042020-04-29 04:22:39 -07006172INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6173
Selene Huang31ab4042020-04-29 04:22:39 -07006174typedef KeyMintAidlTestBase KeyDeletionTest;
6175
6176/**
6177 * KeyDeletionTest.DeleteKey
6178 *
6179 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6180 * valid key blob.
6181 */
6182TEST_P(KeyDeletionTest, DeleteKey) {
6183 auto error = GenerateKey(AuthorizationSetBuilder()
6184 .RsaSigningKey(2048, 65537)
6185 .Digest(Digest::NONE)
6186 .Padding(PaddingMode::NONE)
6187 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006188 .Authorization(TAG_ROLLBACK_RESISTANCE)
6189 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006190 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6191
6192 // Delete must work if rollback protection is implemented
6193 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006194 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006195 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6196
6197 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6198
6199 string message = "12345678901234567890123456789012";
6200 AuthorizationSet begin_out_params;
6201 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6202 Begin(KeyPurpose::SIGN, key_blob_,
6203 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6204 &begin_out_params));
6205 AbortIfNeeded();
6206 key_blob_ = AidlBuf();
6207 }
6208}
6209
6210/**
6211 * KeyDeletionTest.DeleteInvalidKey
6212 *
6213 * This test checks that the HAL excepts invalid key blobs..
6214 */
6215TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6216 // Generate key just to check if rollback protection is implemented
6217 auto error = GenerateKey(AuthorizationSetBuilder()
6218 .RsaSigningKey(2048, 65537)
6219 .Digest(Digest::NONE)
6220 .Padding(PaddingMode::NONE)
6221 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006222 .Authorization(TAG_ROLLBACK_RESISTANCE)
6223 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006224 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6225
6226 // Delete must work if rollback protection is implemented
6227 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006228 AuthorizationSet enforced(SecLevelAuthorizations());
6229 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006230
6231 // Delete the key we don't care about the result at this point.
6232 DeleteKey();
6233
6234 // Now create an invalid key blob and delete it.
6235 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6236
6237 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6238 }
6239}
6240
6241/**
6242 * KeyDeletionTest.DeleteAllKeys
6243 *
6244 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6245 *
6246 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6247 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6248 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6249 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6250 * credentials stored in Keystore/Keymint.
6251 */
6252TEST_P(KeyDeletionTest, DeleteAllKeys) {
6253 if (!arm_deleteAllKeys) return;
6254 auto error = GenerateKey(AuthorizationSetBuilder()
6255 .RsaSigningKey(2048, 65537)
6256 .Digest(Digest::NONE)
6257 .Padding(PaddingMode::NONE)
6258 .Authorization(TAG_NO_AUTH_REQUIRED)
6259 .Authorization(TAG_ROLLBACK_RESISTANCE));
6260 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6261
6262 // Delete must work if rollback protection is implemented
6263 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006264 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006265 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6266
6267 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6268
6269 string message = "12345678901234567890123456789012";
6270 AuthorizationSet begin_out_params;
6271
6272 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6273 Begin(KeyPurpose::SIGN, key_blob_,
6274 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6275 &begin_out_params));
6276 AbortIfNeeded();
6277 key_blob_ = AidlBuf();
6278 }
6279}
6280
6281INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6282
David Drysdaled2cc8c22021-04-15 13:29:45 +01006283typedef KeyMintAidlTestBase KeyUpgradeTest;
6284
6285/**
6286 * KeyUpgradeTest.UpgradeInvalidKey
6287 *
6288 * This test checks that the HAL excepts invalid key blobs..
6289 */
6290TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6291 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6292
6293 std::vector<uint8_t> new_blob;
6294 Status result = keymint_->upgradeKey(key_blob,
6295 AuthorizationSetBuilder()
6296 .Authorization(TAG_APPLICATION_ID, "clientid")
6297 .Authorization(TAG_APPLICATION_DATA, "appdata")
6298 .vector_data(),
6299 &new_blob);
6300 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6301}
6302
6303INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6304
Selene Huang31ab4042020-04-29 04:22:39 -07006305using UpgradeKeyTest = KeyMintAidlTestBase;
6306
6307/*
6308 * UpgradeKeyTest.UpgradeKey
6309 *
6310 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6311 */
6312TEST_P(UpgradeKeyTest, UpgradeKey) {
6313 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6314 .AesEncryptionKey(128)
6315 .Padding(PaddingMode::NONE)
6316 .Authorization(TAG_NO_AUTH_REQUIRED)));
6317
6318 auto result = UpgradeKey(key_blob_);
6319
6320 // Key doesn't need upgrading. Should get okay, but no new key blob.
6321 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6322}
6323
6324INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6325
6326using ClearOperationsTest = KeyMintAidlTestBase;
6327
6328/*
6329 * ClearSlotsTest.TooManyOperations
6330 *
6331 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6332 * operations are started without being finished or aborted. Also verifies
6333 * that aborting the operations clears the operations.
6334 *
6335 */
6336TEST_P(ClearOperationsTest, TooManyOperations) {
6337 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6338 .Authorization(TAG_NO_AUTH_REQUIRED)
6339 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006340 .Padding(PaddingMode::NONE)
6341 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006342
6343 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6344 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006345 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006346 AuthorizationSet out_params;
6347 ErrorCode result;
6348 size_t i;
6349
6350 for (i = 0; i < max_operations; i++) {
6351 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6352 if (ErrorCode::OK != result) {
6353 break;
6354 }
6355 }
6356 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6357 // Try again just in case there's a weird overflow bug
6358 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6359 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6360 for (size_t j = 0; j < i; j++) {
6361 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6362 << "Aboort failed for i = " << j << std::endl;
6363 }
6364 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6365 AbortIfNeeded();
6366}
6367
6368INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6369
6370typedef KeyMintAidlTestBase TransportLimitTest;
6371
6372/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006373 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006374 *
6375 * Verifies that passing input data to finish succeeds as expected.
6376 */
6377TEST_P(TransportLimitTest, LargeFinishInput) {
6378 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6379 .Authorization(TAG_NO_AUTH_REQUIRED)
6380 .AesEncryptionKey(128)
6381 .BlockMode(BlockMode::ECB)
6382 .Padding(PaddingMode::NONE)));
6383
6384 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6385 auto cipher_params =
6386 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6387
6388 AuthorizationSet out_params;
6389 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6390
6391 string plain_message = std::string(1 << msg_size, 'x');
6392 string encrypted_message;
6393 auto rc = Finish(plain_message, &encrypted_message);
6394
6395 EXPECT_EQ(ErrorCode::OK, rc);
6396 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6397 << "Encrypt finish returned OK, but did not consume all of the given input";
6398 cipher_params.push_back(out_params);
6399
6400 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6401
6402 string decrypted_message;
6403 rc = Finish(encrypted_message, &decrypted_message);
6404 EXPECT_EQ(ErrorCode::OK, rc);
6405 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6406 << "Decrypt finish returned OK, did not consume all of the given input";
6407 }
6408}
6409
6410INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6411
David Zeuthene0c40892021-01-08 12:54:11 -05006412typedef KeyMintAidlTestBase KeyAgreementTest;
6413
6414int CurveToOpenSslCurveName(EcCurve curve) {
6415 switch (curve) {
6416 case EcCurve::P_224:
6417 return NID_secp224r1;
6418 case EcCurve::P_256:
6419 return NID_X9_62_prime256v1;
6420 case EcCurve::P_384:
6421 return NID_secp384r1;
6422 case EcCurve::P_521:
6423 return NID_secp521r1;
6424 }
6425}
6426
6427/*
6428 * KeyAgreementTest.Ecdh
6429 *
6430 * Verifies that ECDH works for all curves
6431 */
6432TEST_P(KeyAgreementTest, Ecdh) {
6433 // Because it's possible to use this API with keys on different curves, we
6434 // check all N^2 combinations where N is the number of supported
6435 // curves.
6436 //
6437 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6438 // lot more curves we can be smart about things and just pick |otherCurve| so
6439 // it's not |curve| and that way we end up with only 2*N runs
6440 //
6441 for (auto curve : ValidCurves()) {
6442 for (auto localCurve : ValidCurves()) {
6443 // Generate EC key locally (with access to private key material)
6444 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6445 int curveName = CurveToOpenSslCurveName(localCurve);
6446 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6447 ASSERT_NE(group, nullptr);
6448 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6449 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6450 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6451 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6452
6453 // Get encoded form of the public part of the locally generated key...
6454 unsigned char* p = nullptr;
6455 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6456 ASSERT_GT(encodedPublicKeySize, 0);
6457 vector<uint8_t> encodedPublicKey(
6458 reinterpret_cast<const uint8_t*>(p),
6459 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6460 OPENSSL_free(p);
6461
6462 // Generate EC key in KeyMint (only access to public key material)
6463 vector<uint8_t> challenge = {0x41, 0x42};
6464 EXPECT_EQ(
6465 ErrorCode::OK,
6466 GenerateKey(AuthorizationSetBuilder()
6467 .Authorization(TAG_NO_AUTH_REQUIRED)
6468 .Authorization(TAG_EC_CURVE, curve)
6469 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6470 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6471 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006472 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6473 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006474 << "Failed to generate key";
6475 ASSERT_GT(cert_chain_.size(), 0);
6476 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6477 ASSERT_NE(kmKeyCert, nullptr);
6478 // Check that keyAgreement (bit 4) is set in KeyUsage
6479 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6480 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6481 ASSERT_NE(kmPkey, nullptr);
6482 if (dump_Attestations) {
6483 for (size_t n = 0; n < cert_chain_.size(); n++) {
6484 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6485 }
6486 }
6487
6488 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6489 if (curve != localCurve) {
6490 // If the keys are using different curves KeyMint should fail with
6491 // ErrorCode:INVALID_ARGUMENT. Check that.
6492 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6493 string ZabFromKeyMintStr;
6494 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6495 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6496 &ZabFromKeyMintStr));
6497
6498 } else {
6499 // Otherwise if the keys are using the same curve, it should work.
6500 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6501 string ZabFromKeyMintStr;
6502 EXPECT_EQ(ErrorCode::OK,
6503 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6504 &ZabFromKeyMintStr));
6505 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6506
6507 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6508 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6509 ASSERT_NE(ctx, nullptr);
6510 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6511 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6512 size_t ZabFromTestLen = 0;
6513 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6514 vector<uint8_t> ZabFromTest;
6515 ZabFromTest.resize(ZabFromTestLen);
6516 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6517
6518 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6519 }
6520
6521 CheckedDeleteKey();
6522 }
6523 }
6524}
6525
6526INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6527
David Drysdaled2cc8c22021-04-15 13:29:45 +01006528using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6529
6530// This is a problematic test, as it can render the device under test permanently unusable.
6531// Re-enable and run at your own risk.
6532TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6533 auto result = DestroyAttestationIds();
6534 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6535}
6536
6537INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6538
Shawn Willdend659c7c2021-02-19 14:51:51 -07006539using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006540
David Drysdale216d9922021-05-18 11:43:31 +01006541/*
6542 * EarlyBootKeyTest.CreateEarlyBootKeys
6543 *
6544 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6545 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006546TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdale216d9922021-05-18 11:43:31 +01006547 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006548 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6549 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6550
David Drysdaleeaab0f22021-05-27 12:00:53 +01006551 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6552 ASSERT_GT(keyData.blob.size(), 0U);
6553 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6554 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6555 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006556 CheckedDeleteKey(&aesKeyData.blob);
6557 CheckedDeleteKey(&hmacKeyData.blob);
6558 CheckedDeleteKey(&rsaKeyData.blob);
6559 CheckedDeleteKey(&ecdsaKeyData.blob);
6560}
6561
David Drysdale216d9922021-05-18 11:43:31 +01006562/*
David Drysdaleeaab0f22021-05-27 12:00:53 +01006563 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6564 *
6565 * Verifies that creating an early boot key with attestation succeeds.
6566 */
6567TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6568 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6569 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6570 builder->AttestationChallenge("challenge");
6571 builder->AttestationApplicationId("app_id");
6572 });
6573
6574 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6575 ASSERT_GT(keyData.blob.size(), 0U);
6576 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6577 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6578 }
6579 CheckedDeleteKey(&aesKeyData.blob);
6580 CheckedDeleteKey(&hmacKeyData.blob);
6581 CheckedDeleteKey(&rsaKeyData.blob);
6582 CheckedDeleteKey(&ecdsaKeyData.blob);
6583}
6584
6585/*
6586 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdale216d9922021-05-18 11:43:31 +01006587 *
6588 * Verifies that using early boot keys at a later stage fails.
6589 */
6590TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6591 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6592 .Authorization(TAG_NO_AUTH_REQUIRED)
6593 .Authorization(TAG_EARLY_BOOT_ONLY)
6594 .HmacKey(128)
6595 .Digest(Digest::SHA_2_256)
6596 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6597 AuthorizationSet output_params;
6598 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6599 AuthorizationSetBuilder()
6600 .Digest(Digest::SHA_2_256)
6601 .Authorization(TAG_MAC_LENGTH, 256),
6602 &output_params));
6603}
6604
6605/*
6606 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6607 *
6608 * Verifies that importing early boot keys fails.
6609 */
6610TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6611 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6612 .Authorization(TAG_NO_AUTH_REQUIRED)
6613 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdale308916b2021-06-08 15:46:11 +01006614 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale216d9922021-05-18 11:43:31 +01006615 .Digest(Digest::SHA_2_256)
6616 .SetDefaultValidity(),
6617 KeyFormat::PKCS8, ec_256_key));
6618}
6619
David Drysdaled2cc8c22021-04-15 13:29:45 +01006620// 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 +00006621// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6622// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6623// early boot, so you'll have to reboot between runs.
6624TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6625 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6626 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6627 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6628 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6629 EXPECT_TRUE(
6630 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6631 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6632 EXPECT_TRUE(
6633 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6634
6635 // Should be able to use keys, since early boot has not ended
6636 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6637 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6638 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6639 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6640
6641 // End early boot
6642 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6643 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6644
6645 // Should not be able to use already-created keys.
6646 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6647 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6648 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6649 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6650
6651 CheckedDeleteKey(&aesKeyData.blob);
6652 CheckedDeleteKey(&hmacKeyData.blob);
6653 CheckedDeleteKey(&rsaKeyData.blob);
6654 CheckedDeleteKey(&ecdsaKeyData.blob);
6655
6656 // Should not be able to create new keys
6657 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6658 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6659
6660 CheckedDeleteKey(&aesKeyData.blob);
6661 CheckedDeleteKey(&hmacKeyData.blob);
6662 CheckedDeleteKey(&rsaKeyData.blob);
6663 CheckedDeleteKey(&ecdsaKeyData.blob);
6664}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006665
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006666INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6667
Shawn Willdend659c7c2021-02-19 14:51:51 -07006668using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006669
6670// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6671// between runs... and on most test devices there are no enrolled credentials so it can't be
6672// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6673// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6674// a manual test process, which includes unlocking between runs, which is why it's included here.
6675// Well, that and the fact that it's the only test we can do without also making calls into the
6676// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6677// implications might be, so that may or may not be a solution.
6678TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6679 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6680 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6681
6682 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6683 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6684 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6685 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6686
6687 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006688 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006689 ASSERT_EQ(ErrorCode::OK, rc);
6690 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6691 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6692 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6693 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6694
6695 CheckedDeleteKey(&aesKeyData.blob);
6696 CheckedDeleteKey(&hmacKeyData.blob);
6697 CheckedDeleteKey(&rsaKeyData.blob);
6698 CheckedDeleteKey(&ecdsaKeyData.blob);
6699}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006700
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006701INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6702
Janis Danisevskis24c04702020-12-16 18:28:39 -08006703} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006704
6705int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006706 std::cout << "Testing ";
6707 auto halInstances =
6708 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6709 std::cout << "HAL instances:\n";
6710 for (auto& entry : halInstances) {
6711 std::cout << " " << entry << '\n';
6712 }
6713
Selene Huang31ab4042020-04-29 04:22:39 -07006714 ::testing::InitGoogleTest(&argc, argv);
6715 for (int i = 1; i < argc; ++i) {
6716 if (argv[i][0] == '-') {
6717 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006718 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6719 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006720 }
6721 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006722 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6723 dump_Attestations = true;
6724 } else {
6725 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006726 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006727 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6728 if (std::string(argv[i]) == "--check_patchLevels") {
6729 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6730 }
Selene Huang31ab4042020-04-29 04:22:39 -07006731 }
6732 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006733 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006734}