blob: 92aa2ac64baeccd73c54e3d383173df499fef3da [file] [log] [blame]
Selene Huang31ab4042020-04-29 04:22:39 -07001/*
2 * Copyright (C) 2020 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Shawn Willden7c130392020-12-21 09:58:22 -070017#define LOG_TAG "keymint_1_test"
Selene Huang31ab4042020-04-29 04:22:39 -070018#include <cutils/log.h>
19
20#include <signal.h>
David Drysdale37af4b32021-05-14 16:46:59 +010021
22#include <algorithm>
Selene Huang31ab4042020-04-29 04:22:39 -070023#include <iostream>
24
David Zeuthene0c40892021-01-08 12:54:11 -050025#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070026#include <openssl/evp.h>
27#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050028#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070029
30#include <cutils/properties.h>
31
David Drysdale4dc01072021-04-01 12:17:35 +010032#include <android/binder_manager.h>
33
34#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080035#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070036
Shawn Willden08a7e432020-12-11 13:05:27 +000037#include <keymint_support/key_param_output.h>
38#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070039
40#include "KeyMintAidlTestBase.h"
41
Janis Danisevskis24c04702020-12-16 18:28:39 -080042using aidl::android::hardware::security::keymint::AuthorizationSet;
43using aidl::android::hardware::security::keymint::KeyCharacteristics;
44using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070045
Selene Huang31ab4042020-04-29 04:22:39 -070046namespace std {
47
Janis Danisevskis24c04702020-12-16 18:28:39 -080048using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070049
50template <>
51struct std::equal_to<KeyCharacteristics> {
52 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070053 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070054
Shawn Willden7f424372021-01-10 18:06:50 -070055 // this isn't very efficient. Oh, well.
56 AuthorizationSet a_auths(a.authorizations);
57 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070058
Shawn Willden7f424372021-01-10 18:06:50 -070059 a_auths.Sort();
60 b_auths.Sort();
61
62 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070063 }
64};
65
66} // namespace std
67
Janis Danisevskis24c04702020-12-16 18:28:39 -080068namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000069
Selene Huang31ab4042020-04-29 04:22:39 -070070namespace {
71
Seth Moore7a55ae32021-06-23 14:28:11 -070072// The maximum number of times we'll attempt to verify that corruption
73// of an ecrypted blob results in an error. Retries are necessary as there
74// is a small (roughly 1/256) chance that corrupting ciphertext still results
75// in valid PKCS7 padding.
76constexpr size_t kMaxPaddingCorruptionRetries = 8;
77
Selene Huang31ab4042020-04-29 04:22:39 -070078template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000079bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
80 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070081 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080082 if (auto p = authorizationValue(ttag, param)) {
83 return *p == expected_value;
84 }
85 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070086 });
87 return (it != set.end());
88}
89
90template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000091bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070092 auto it = std::find_if(set.begin(), set.end(),
93 [&](const KeyParameter& param) { return param.tag == tag; });
94 return (it != set.end());
95}
96
97constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
98 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
99 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
100 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
101 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
102 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
103 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
104 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
108 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
111 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
112 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
113
114string hex2str(string a) {
115 string b;
116 size_t num = a.size() / 2;
117 b.resize(num);
118 for (size_t i = 0; i < num; i++) {
119 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
120 }
121 return b;
122}
123
David Drysdaled2cc8c22021-04-15 13:29:45 +0100124string rsa_key = hex2str(
125 // RFC 5208 s5
126 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
127 "020100" // INTEGER length 1 value 0x00 (version)
128 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
129 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
130 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
131 "0500" // NULL (parameters)
132 // } end SEQUENCE (AlgorithmIdentifier)
133 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
134 // RFC 8017 A.1.2
135 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
136 "020100" // INTEGER length 1 value 0x00 (version)
137 "028181" // INTEGER length 0x81 value (modulus) ...
138 "00c6095409047d8634812d5a218176e4"
139 "5c41d60a75b13901f234226cffe77652"
140 "1c5a77b9e389417b71c0b6a44d13afe4"
141 "e4a2805d46c9da2935adb1ff0c1f24ea"
142 "06e62b20d776430a4d435157233c6f91"
143 "6783c30e310fcbd89b85c2d567711697"
144 "85ac12bca244abda72bfb19fc44d27c8"
145 "1e1d92de284f4061edfd99280745ea6d"
146 "25"
147 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
148 "028180" // INTEGER length 0x80 (privateExponent) value...
149 "1be0f04d9cae3718691f035338308e91"
150 "564b55899ffb5084d2460e6630257e05"
151 "b3ceab02972dfabcd6ce5f6ee2589eb6"
152 "7911ed0fac16e43a444b8c861e544a05"
153 "93365772f8baf6b22fc9e3c5f1024b06"
154 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
155 "ace7240290bef16c0b3f7f3cdd64ce3a"
156 "b5912cf6e32f39ab188358afcccd8081"
157 "0241" // INTEGER length 0x41 (prime1)
158 "00e4b49ef50f765d3b24dde01aceaaf1"
159 "30f2c76670a91a61ae08af497b4a82be"
160 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
161 "8c92bfab137fba2285227b83c342ff7c"
162 "55"
163 "0241" // INTEGER length 0x41 (prime2)
164 "00ddabb5839c4c7f6bf3d4183231f005"
165 "b31aa58affdda5c79e4cce217f6bc930"
166 "dbe563d480706c24e9ebfcab28a6cdef"
167 "d324b77e1bf7251b709092c24ff501fd"
168 "91"
169 "0240" // INTEGER length 0x40 (exponent1)
170 "23d4340eda3445d8cd26c14411da6fdc"
171 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
172 "842c1d280405bc2f6c1bea214a1d742a"
173 "b996b35b63a82a5e470fa88dbf823cdd"
174 "0240" // INTEGER length 0x40 (exponent2)
175 "1b7b57449ad30d1518249a5f56bb9829"
176 "4d4b6ac12ffc86940497a5a5837a6cf9"
177 "46262b494526d328c11e1126380fde04"
178 "c24f916dec250892db09a6d77cdba351"
179 "0240" // INTEGER length 0x40 (coefficient)
180 "7762cd8f4d050da56bd591adb515d24d"
181 "7ccd32cca0d05f866d583514bd7324d5"
182 "f33645e8ed8b4a1cb3cc4a1d67987399"
183 "f2a09f5b3fb68c88d5e5d90ac33492d6"
184 // } end SEQUENCE (PrivateKey)
185 // } end SEQUENCE (PrivateKeyInfo)
186);
Selene Huang31ab4042020-04-29 04:22:39 -0700187
Selene Huange5727e62021-04-13 22:41:20 -0700188/*
189 * DER-encoded PKCS#8 format RSA key. Generated using:
190 *
191 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
192 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100193string rsa_2048_key = hex2str(
194 // RFC 5208 s5
195 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
196 "020100" // INTEGER length 1 value 0x00 (version)
197 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
198 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
199 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
200 "0500" // NULL (parameters)
201 // } end SEQUENCE (AlgorithmIdentifier)
202 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
203 // RFC 8017 A.1.2
204 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
205 "020100" // INTEGER length 1 value 0x00 (version)
206 "02820101" // INTEGER length 0x101 value (modulus) ...
207 "00BEBC342B56D443B1299F9A6A7056E8"
208 "0A897E318476A5A18029E63B2ED739A6"
209 "1791D339F58DC763D9D14911F2EDEC38"
210 "3DEE11F6319B44510E7A3ECD9B79B973"
211 "82E49500ACF8117DC89CAF0E621F7775"
212 "6554A2FD4664BFE7AB8B59AB48340DBF"
213 "A27B93B5A81F6ECDEB02D0759307128D"
214 "F3E3BAD4055C8B840216DFAA5700670E"
215 "6C5126F0962FCB70FF308F25049164CC"
216 "F76CC2DA66A7DD9A81A714C2809D6918"
217 "6133D29D84568E892B6FFBF3199BDB14"
218 "383EE224407F190358F111A949552ABA"
219 "6714227D1BD7F6B20DD0CB88F9467B71"
220 "9339F33BFF35B3870B3F62204E4286B0"
221 "948EA348B524544B5F9838F29EE643B0"
222 "79EEF8A713B220D7806924CDF7295070"
223 "C5"
224 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
225 "02820100" // INTEGER length 0x100 (privateExponent) value...
226 "69F377F35F2F584EF075353CCD1CA997"
227 "38DB3DBC7C7FF35F9366CE176DFD1B13"
228 "5AB10030344ABF5FBECF1D4659FDEF1C"
229 "0FC430834BE1BE3911951377BB3D563A"
230 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
231 "2686C7B4B3C09A7B8354133E6F93F790"
232 "D59EAEB92E84C9A4339302CCE28FDF04"
233 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
234 "6AB706645BF074A4E4090D06FB163124"
235 "365FD5EE7A20D350E9958CC30D91326E"
236 "1B292E9EF5DB408EC42DAF737D201497"
237 "04D0A678A0FB5B5446863B099228A352"
238 "D604BA8091A164D01D5AB05397C71EAD"
239 "20BE2A08FC528FE442817809C787FEE4"
240 "AB97F97B9130D022153EDC6EB6CBE7B0"
241 "F8E3473F2E901209B5DB10F93604DB01"
242 "028181" // INTEGER length 0x81 (prime1)
243 "00E83C0998214941EA4F9293F1B77E2E"
244 "99E6CF305FAF358238E126124FEAF2EB"
245 "9724B2EA7B78E6032343821A80E55D1D"
246 "88FB12D220C3F41A56142FEC85796D19"
247 "17F1E8C774F142B67D3D6E7B7E6B4383"
248 "E94DB5929089DBB346D5BDAB40CC2D96"
249 "EE0409475E175C63BF78CFD744136740"
250 "838127EA723FF3FE7FA368C1311B4A4E"
251 "05"
252 "028181" // INTEGER length 0x81 (prime2)
253 "00D240FCC0F5D7715CDE21CB2DC86EA1"
254 "46132EA3B06F61FF2AF54BF38473F59D"
255 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
256 "B1B58C39F95E4798CCBB43E83D0119AC"
257 "F532F359CA743C85199F0286610E2009"
258 "97D7312917179AC9B67558773212EC96"
259 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
260 "94D94E066A0900B7B70E82A44FB30053"
261 "C1"
262 "028181" // INTEGER length 0x81 (exponent1)
263 "00AD15DA1CBD6A492B66851BA8C316D3"
264 "8AB700E2CFDDD926A658003513C54BAA"
265 "152B30021D667D20078F500F8AD3E7F3"
266 "945D74A891ED1A28EAD0FEEAEC8C14A8"
267 "E834CF46A13D1378C99D18940823CFDD"
268 "27EC5810D59339E0C34198AC638E09C8"
269 "7CBB1B634A9864AE9F4D5EB2D53514F6"
270 "7B4CAEC048C8AB849A02E397618F3271"
271 "35"
272 "028180" // INTEGER length 0x80 (exponent2)
273 "1FA2C1A5331880A92D8F3E281C617108"
274 "BF38244F16E352E69ED417C7153F9EC3"
275 "18F211839C643DCF8B4DD67CE2AC312E"
276 "95178D5D952F06B1BF779F4916924B70"
277 "F582A23F11304E02A5E7565AE22A35E7"
278 "4FECC8B6FDC93F92A1A37703E4CF0E63"
279 "783BD02EB716A7ECBBFA606B10B74D01"
280 "579522E7EF84D91FC522292108D902C1"
281 "028180" // INTEGER length 0x80 (coefficient)
282 "796FE3825F9DCC85DF22D58690065D93"
283 "898ACD65C087BEA8DA3A63BF4549B795"
284 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
285 "0D74F40DED8E1102C52152A31B6165F8"
286 "3A6722AECFCC35A493D7634664B888A0"
287 "8D3EB034F12EA28BFEE346E205D33482"
288 "7F778B16ED40872BD29FCB36536B6E93"
289 "FFB06778696B4A9D81BB0A9423E63DE5"
290 // } end SEQUENCE (PrivateKey)
291 // } end SEQUENCE (PrivateKeyInfo)
292);
Selene Huange5727e62021-04-13 22:41:20 -0700293
David Drysdaled2cc8c22021-04-15 13:29:45 +0100294string ec_256_key = hex2str(
295 // RFC 5208 s5
296 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
297 "020100" // INTEGER length 1 value 0 (version)
298 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
299 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
300 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
301 "0608" // OBJECT IDENTIFIER length 8 (param)
302 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
303 // } end SEQUENCE (AlgorithmIdentifier)
304 "046d" // OCTET STRING length 0x6d (privateKey) holding...
305 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
306 "020101" // INTEGER length 1 value 1 (version)
307 "0420" // OCTET STRING length 0x20 (privateKey)
308 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
309 "941eed09366bc03299986481f3a4d859"
310 "a144" // TAG [1] len 0x44 (publicKey) {
311 "03420004bf85d7720d07c25461683bc6"
312 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
313 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
314 "bcc41c6eb00083cf3376d11fd44949e0"
315 "b2183bfe"
316 // } end SEQUENCE (ECPrivateKey)
317 // } end SEQUENCE (PrivateKeyInfo)
318);
Selene Huang31ab4042020-04-29 04:22:39 -0700319
David Drysdaled2cc8c22021-04-15 13:29:45 +0100320string ec_521_key = hex2str(
321 // RFC 5208 s5
322 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
323 "020100" // INTEGER length 1 value 0 (version)
324 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
325 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
326 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
327 "0605" // OBJECT IDENTIFIER length 5 (param)
328 "2B81040023" // 1.3.132.0.35 (secp521r1)
329 // } end SEQUENCE (AlgorithmIdentifier)
330 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
331 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
332 "020101" // INTEGER length 1 value 1 (version)
333 "0442" // OCTET STRING length 0x42 (privateKey)
334 "0011458C586DB5DAA92AFAB03F4FE46A"
335 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
336 "9D18D7D08B5BCFA0E53C75B064AD51C4"
337 "49BAE0258D54B94B1E885DED08ED4FB2"
338 "5CE9"
339 "A18189" // TAG [1] len 0x89 (publicKey) {
340 "03818600040149EC11C6DF0FA122C6A9"
341 "AFD9754A4FA9513A627CA329E349535A"
342 "5629875A8ADFBE27DCB932C051986377"
343 "108D054C28C6F39B6F2C9AF81802F9F3"
344 "26B842FF2E5F3C00AB7635CFB36157FC"
345 "0882D574A10D839C1A0C049DC5E0D775"
346 "E2EE50671A208431BB45E78E70BEFE93"
347 "0DB34818EE4D5C26259F5C6B8E28A652"
348 "950F9F88D7B4B2C9D9"
349 // } end SEQUENCE (ECPrivateKey)
350 // } end SEQUENCE (PrivateKeyInfo)
351);
Selene Huang31ab4042020-04-29 04:22:39 -0700352
David Drysdaled2cc8c22021-04-15 13:29:45 +0100353string ec_256_key_rfc5915 = hex2str(
354 // RFC 5208 s5
355 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
356 "020100" // INTEGER length 1 value 0 (version)
357 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
358 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
359 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
360 "0608" // OBJECT IDENTIFIER length 8 (param)
361 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
362 // } end SEQUENCE (AlgorithmIdentifier)
363 "0479" // OCTET STRING length 0x79 (privateKey) holding...
364 // RFC 5915 s3
365 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
366 "020101" // INTEGER length 1 value 1 (version)
367 "0420" // OCTET STRING length 0x42 (privateKey)
368 "782370a8c8ce5537baadd04dcff079c8"
369 "158cfa9c67b818b38e8d21c9fa750c1d"
370 "a00a" // TAG [0] length 0xa (parameters)
371 "0608" // OBJECT IDENTIFIER length 8
372 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
373 // } end TAG [0]
374 "a144" // TAG [1] length 0x44 (publicKey) {
375 "0342" // BIT STRING length 0x42
376 "00" // no pad bits
377 "04e2cc561ee701da0ad0ef0d176bb0c9"
378 "19d42e79c393fdc1bd6c4010d85cf2cf"
379 "8e68c905464666f98dad4f01573ba810"
380 "78b3428570a439ba3229fbc026c55068"
381 "2f"
382 // } end SEQUENCE (ECPrivateKey)
383 // } end SEQUENCE (PrivateKeyInfo)
384);
Selene Huang31ab4042020-04-29 04:22:39 -0700385
David Drysdaled2cc8c22021-04-15 13:29:45 +0100386string ec_256_key_sec1 = hex2str(
387 // RFC 5208 s5
388 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
389 "020100" // INTEGER length 1 value 0 (version)
390 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
391 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
392 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
393 "0608" // OBJECT IDENTIFIER length 8 (param)
394 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
395 // } end SEQUENCE (AlgorithmIdentifier)
396 "046d" // OCTET STRING length 0x6d (privateKey) holding...
397 // SEC1-v2 C.4
398 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
399 "020101" // INTEGER length 1 value 0x01 (version)
400 "0420" // OCTET STRING length 0x20 (privateKey)
401 "782370a8c8ce5537baadd04dcff079c8"
402 "158cfa9c67b818b38e8d21c9fa750c1d"
403 "a144" // TAG [1] length 0x44 (publicKey) {
404 "0342" // BIT STRING length 0x42
405 "00" // no pad bits
406 "04e2cc561ee701da0ad0ef0d176bb0c9"
407 "19d42e79c393fdc1bd6c4010d85cf2cf"
408 "8e68c905464666f98dad4f01573ba810"
409 "78b3428570a439ba3229fbc026c55068"
410 "2f"
411 // } end TAG [1] (publicKey)
412 // } end SEQUENCE (PrivateKeyInfo)
413);
Selene Huang31ab4042020-04-29 04:22:39 -0700414
415struct RSA_Delete {
416 void operator()(RSA* p) { RSA_free(p); }
417};
418
Selene Huang31ab4042020-04-29 04:22:39 -0700419std::string make_string(const uint8_t* data, size_t length) {
420 return std::string(reinterpret_cast<const char*>(data), length);
421}
422
423template <size_t N>
424std::string make_string(const uint8_t (&a)[N]) {
425 return make_string(a, N);
426}
427
428class AidlBuf : public vector<uint8_t> {
429 typedef vector<uint8_t> super;
430
431 public:
432 AidlBuf() {}
433 AidlBuf(const super& other) : super(other) {}
434 AidlBuf(super&& other) : super(std::move(other)) {}
435 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
436
437 AidlBuf& operator=(const super& other) {
438 super::operator=(other);
439 return *this;
440 }
441
442 AidlBuf& operator=(super&& other) {
443 super::operator=(std::move(other));
444 return *this;
445 }
446
447 AidlBuf& operator=(const string& other) {
448 resize(other.size());
449 for (size_t i = 0; i < other.size(); ++i) {
450 (*this)[i] = static_cast<uint8_t>(other[i]);
451 }
452 return *this;
453 }
454
455 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
456};
457
David Drysdale4dc01072021-04-01 12:17:35 +0100458string device_suffix(const string& name) {
459 size_t pos = name.find('/');
460 if (pos == string::npos) {
461 return name;
462 }
463 return name.substr(pos + 1);
464}
465
466bool matching_rp_instance(const string& km_name,
467 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
468 string km_suffix = device_suffix(km_name);
469
470 vector<string> rp_names =
471 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
472 for (const string& rp_name : rp_names) {
473 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
474 // KeyMint instance, assume they match.
475 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
476 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
477 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
478 return true;
479 }
480 }
481 return false;
482}
483
Selene Huang31ab4042020-04-29 04:22:39 -0700484} // namespace
485
486class NewKeyGenerationTest : public KeyMintAidlTestBase {
487 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700488 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000489 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700490 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700491
Selene Huang31ab4042020-04-29 04:22:39 -0700492 // Check that some unexpected tags/values are NOT present.
493 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
494 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000495 }
496
497 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
498 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
499 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
500 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
501
502 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000503 }
504
505 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
506 // TODO(swillden): Distinguish which params should be in which auth list.
507 AuthorizationSet auths;
508 for (auto& entry : keyCharacteristics) {
509 auths.push_back(AuthorizationSet(entry.authorizations));
510 }
511 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
512
513 // Verify that App data, ROT and auth timeout are NOT included.
514 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
515 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700516 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
517
David Drysdaled2cc8c22021-04-15 13:29:45 +0100518 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
519 // never adds it.
520 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
521
David Drysdale7de9feb2021-03-05 14:56:19 +0000522 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700523 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000524 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700525 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700526 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000527 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700528 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000529
David Drysdalef5bfa002021-09-27 17:30:41 +0100530 // Should include vendor and boot patchlevels.
531 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
532 EXPECT_TRUE(vendor_pl);
533 EXPECT_EQ(*vendor_pl, vendor_patch_level());
534 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
535 EXPECT_TRUE(boot_pl);
David Drysdalebb3d85e2021-04-13 11:15:51 +0100536
David Drysdale7de9feb2021-03-05 14:56:19 +0000537 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700538 }
539};
540
541/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000542 * NewKeyGenerationTest.Aes
543 *
544 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
545 * have correct characteristics.
546 */
547TEST_P(NewKeyGenerationTest, Aes) {
548 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
549 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
550 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
551 SCOPED_TRACE(testing::Message()
552 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
553 vector<uint8_t> key_blob;
554 vector<KeyCharacteristics> key_characteristics;
555 auto builder = AuthorizationSetBuilder()
556 .AesEncryptionKey(key_size)
557 .BlockMode(block_mode)
558 .Padding(padding_mode)
559 .SetDefaultValidity();
560 if (block_mode == BlockMode::GCM) {
561 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
562 }
563 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
564
565 EXPECT_GT(key_blob.size(), 0U);
566 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100567 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000568
569 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
570
571 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
572 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
573 << "Key size " << key_size << "missing";
574
575 CheckedDeleteKey(&key_blob);
576 }
577 }
578 }
579}
580
581/*
582 * NewKeyGenerationTest.AesInvalidSize
583 *
584 * Verifies that specifying an invalid key size for AES key generation returns
585 * UNSUPPORTED_KEY_SIZE.
586 */
587TEST_P(NewKeyGenerationTest, AesInvalidSize) {
588 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
589 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
590 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
591 SCOPED_TRACE(testing::Message()
592 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
593 vector<uint8_t> key_blob;
594 vector<KeyCharacteristics> key_characteristics;
595 auto builder = AuthorizationSetBuilder()
596 .AesEncryptionKey(key_size)
597 .BlockMode(block_mode)
598 .Padding(padding_mode)
599 .SetDefaultValidity();
600 if (block_mode == BlockMode::GCM) {
601 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
602 }
603 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
604 GenerateKey(builder, &key_blob, &key_characteristics));
605 }
606 }
607 }
608
609 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
610 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
611 vector<uint8_t> key_blob;
612 vector<KeyCharacteristics> key_characteristics;
613 // No key size specified
614 auto builder = AuthorizationSetBuilder()
615 .Authorization(TAG_ALGORITHM, Algorithm::AES)
616 .BlockMode(block_mode)
617 .Padding(padding_mode)
618 .SetDefaultValidity();
619 if (block_mode == BlockMode::GCM) {
620 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
621 }
622 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
623 GenerateKey(builder, &key_blob, &key_characteristics));
624 }
625 }
626}
627
628/*
629 * NewKeyGenerationTest.AesInvalidPadding
630 *
631 * Verifies that specifying an invalid padding on AES keys gives a failure
632 * somewhere along the way.
633 */
634TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
635 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
636 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
637 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
638 SCOPED_TRACE(testing::Message()
639 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000640 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800641 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000642 .AesEncryptionKey(key_size)
643 .BlockMode(block_mode)
644 .Padding(padding_mode)
645 .SetDefaultValidity();
646 if (block_mode == BlockMode::GCM) {
647 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
648 }
649
Tommy Chiu3950b452021-05-03 22:01:46 +0800650 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000651 if (result == ErrorCode::OK) {
652 // Key creation was OK but has generated a key that cannot be used.
653 auto params =
654 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800655 if (block_mode == BlockMode::GCM) {
656 params.Authorization(TAG_MAC_LENGTH, 128);
657 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000658 auto result = Begin(KeyPurpose::ENCRYPT, params);
659 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100660 result == ErrorCode::INVALID_KEY_BLOB)
661 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000662 } else {
663 // The KeyMint implementation detected that the generated key
664 // is unusable.
665 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
666 }
667 }
668 }
669 }
670}
671
672/*
673 * NewKeyGenerationTest.AesGcmMissingMinMac
674 *
675 * Verifies that specifying an invalid key size for AES key generation returns
676 * UNSUPPORTED_KEY_SIZE.
677 */
678TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
679 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
680 BlockMode block_mode = BlockMode::GCM;
681 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
682 SCOPED_TRACE(testing::Message()
683 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
684 vector<uint8_t> key_blob;
685 vector<KeyCharacteristics> key_characteristics;
686 // No MIN_MAC_LENGTH provided.
687 auto builder = AuthorizationSetBuilder()
688 .AesEncryptionKey(key_size)
689 .BlockMode(block_mode)
690 .Padding(padding_mode)
691 .SetDefaultValidity();
692 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
693 GenerateKey(builder, &key_blob, &key_characteristics));
694 }
695 }
696}
697
698/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100699 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
700 *
701 * Verifies that specifying an invalid min MAC size for AES key generation returns
702 * UNSUPPORTED_MIN_MAC_LENGTH.
703 */
704TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
705 for (size_t min_mac_len : {88, 136}) {
706 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
707 BlockMode block_mode = BlockMode::GCM;
708 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
709 SCOPED_TRACE(testing::Message()
710 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
711 vector<uint8_t> key_blob;
712 vector<KeyCharacteristics> key_characteristics;
713 auto builder = AuthorizationSetBuilder()
714 .AesEncryptionKey(key_size)
715 .BlockMode(block_mode)
716 .Padding(padding_mode)
717 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
718 .SetDefaultValidity();
719 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
720 GenerateKey(builder, &key_blob, &key_characteristics));
721 }
722 }
723 }
724}
725
726/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000727 * NewKeyGenerationTest.TripleDes
728 *
729 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
730 * have correct characteristics.
731 */
732TEST_P(NewKeyGenerationTest, TripleDes) {
733 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
734 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
735 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
736 SCOPED_TRACE(testing::Message()
737 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
738 vector<uint8_t> key_blob;
739 vector<KeyCharacteristics> key_characteristics;
740 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
741 .TripleDesEncryptionKey(key_size)
742 .BlockMode(block_mode)
743 .Padding(padding_mode)
744 .Authorization(TAG_NO_AUTH_REQUIRED)
745 .SetDefaultValidity(),
746 &key_blob, &key_characteristics));
747
748 EXPECT_GT(key_blob.size(), 0U);
749 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100750 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000751
752 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
753
754 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
755 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
756 << "Key size " << key_size << "missing";
757
758 CheckedDeleteKey(&key_blob);
759 }
760 }
761 }
762}
763
764/*
765 * NewKeyGenerationTest.TripleDesWithAttestation
766 *
767 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
768 * have correct characteristics.
769 *
770 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
771 * put in a certificate) but which isn't an error.
772 */
773TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
774 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
775 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
776 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
777 SCOPED_TRACE(testing::Message()
778 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
779
780 auto challenge = "hello";
781 auto app_id = "foo";
782
783 vector<uint8_t> key_blob;
784 vector<KeyCharacteristics> key_characteristics;
785 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
786 .TripleDesEncryptionKey(key_size)
787 .BlockMode(block_mode)
788 .Padding(padding_mode)
789 .Authorization(TAG_NO_AUTH_REQUIRED)
790 .AttestationChallenge(challenge)
791 .AttestationApplicationId(app_id)
792 .SetDefaultValidity(),
793 &key_blob, &key_characteristics));
794
795 EXPECT_GT(key_blob.size(), 0U);
796 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100797 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000798
799 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
800
801 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
802 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
803 << "Key size " << key_size << "missing";
804
805 CheckedDeleteKey(&key_blob);
806 }
807 }
808 }
809}
810
811/*
812 * NewKeyGenerationTest.TripleDesInvalidSize
813 *
814 * Verifies that specifying an invalid key size for 3-DES key generation returns
815 * UNSUPPORTED_KEY_SIZE.
816 */
817TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
818 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
819 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
820 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
821 SCOPED_TRACE(testing::Message()
822 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
823 vector<uint8_t> key_blob;
824 vector<KeyCharacteristics> key_characteristics;
825 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
826 GenerateKey(AuthorizationSetBuilder()
827 .TripleDesEncryptionKey(key_size)
828 .BlockMode(block_mode)
829 .Padding(padding_mode)
830 .Authorization(TAG_NO_AUTH_REQUIRED)
831 .SetDefaultValidity(),
832 &key_blob, &key_characteristics));
833 }
834 }
835 }
836
837 // Omitting the key size fails.
838 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
839 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
840 SCOPED_TRACE(testing::Message()
841 << "3DES-default-" << block_mode << "-" << padding_mode);
842 vector<uint8_t> key_blob;
843 vector<KeyCharacteristics> key_characteristics;
844 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
845 GenerateKey(AuthorizationSetBuilder()
846 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
847 .BlockMode(block_mode)
848 .Padding(padding_mode)
849 .Authorization(TAG_NO_AUTH_REQUIRED)
850 .SetDefaultValidity(),
851 &key_blob, &key_characteristics));
852 }
853 }
854}
855
856/*
Selene Huang31ab4042020-04-29 04:22:39 -0700857 * NewKeyGenerationTest.Rsa
858 *
859 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
860 * have correct characteristics.
861 */
862TEST_P(NewKeyGenerationTest, Rsa) {
863 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
864 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700865 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700866 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
867 .RsaSigningKey(key_size, 65537)
868 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800869 .Padding(PaddingMode::NONE)
870 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700871 &key_blob, &key_characteristics));
872
873 ASSERT_GT(key_blob.size(), 0U);
874 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100875 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700876
Shawn Willden7f424372021-01-10 18:06:50 -0700877 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700878
879 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
880 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
881 << "Key size " << key_size << "missing";
882 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
883
884 CheckedDeleteKey(&key_blob);
885 }
886}
887
888/*
Qi Wud22ec842020-11-26 13:27:53 +0800889 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700890 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100891 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
892 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700893 */
894TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700895 auto challenge = "hello";
896 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700897
Selene Huang6e46f142021-04-20 19:20:11 -0700898 auto subject = "cert subj 2";
899 vector<uint8_t> subject_der(make_name_from_str(subject));
900
901 uint64_t serial_int = 66;
902 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
903
Selene Huang4f64c222021-04-13 19:54:36 -0700904 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700905 vector<uint8_t> key_blob;
906 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700907 ASSERT_EQ(ErrorCode::OK,
908 GenerateKey(AuthorizationSetBuilder()
909 .RsaSigningKey(key_size, 65537)
910 .Digest(Digest::NONE)
911 .Padding(PaddingMode::NONE)
912 .AttestationChallenge(challenge)
913 .AttestationApplicationId(app_id)
914 .Authorization(TAG_NO_AUTH_REQUIRED)
915 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
916 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
917 .SetDefaultValidity(),
918 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700919
920 ASSERT_GT(key_blob.size(), 0U);
921 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100922 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700923
924 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
925
926 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
927 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
928 << "Key size " << key_size << "missing";
929 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
930
Selene Huang6e46f142021-04-20 19:20:11 -0700931 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700932 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700933 ASSERT_GT(cert_chain_.size(), 0);
934
935 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
936 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
937 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
938 sw_enforced, hw_enforced, SecLevel(),
939 cert_chain_[0].encodedCertificate));
940
941 CheckedDeleteKey(&key_blob);
942 }
943}
944
945/*
David Drysdale4dc01072021-04-01 12:17:35 +0100946 * NewKeyGenerationTest.RsaWithRpkAttestation
947 *
948 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
949 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +0100950 *
951 * This test is disabled because the KeyMint specification does not require that implementations
952 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
953 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +0100954 */
David Drysdale0fce69d2021-04-13 17:22:13 +0100955TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +0100956 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
957 // instance.
958 std::shared_ptr<IRemotelyProvisionedComponent> rp;
959 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
960 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
961
962 // Generate a P-256 keypair to use as an attestation key.
963 MacedPublicKey macedPubKey;
964 std::vector<uint8_t> privateKeyBlob;
965 auto status =
966 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
967 ASSERT_TRUE(status.isOk());
968 vector<uint8_t> coseKeyData;
969 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
970
971 AttestationKey attestation_key;
972 attestation_key.keyBlob = std::move(privateKeyBlob);
973 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
974
975 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
976 auto challenge = "hello";
977 auto app_id = "foo";
978
979 vector<uint8_t> key_blob;
980 vector<KeyCharacteristics> key_characteristics;
981 ASSERT_EQ(ErrorCode::OK,
982 GenerateKey(AuthorizationSetBuilder()
983 .RsaSigningKey(key_size, 65537)
984 .Digest(Digest::NONE)
985 .Padding(PaddingMode::NONE)
986 .AttestationChallenge(challenge)
987 .AttestationApplicationId(app_id)
988 .Authorization(TAG_NO_AUTH_REQUIRED)
989 .SetDefaultValidity(),
990 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
991
992 ASSERT_GT(key_blob.size(), 0U);
993 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100994 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +0100995
996 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
997
998 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
999 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1000 << "Key size " << key_size << "missing";
1001 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1002
1003 // Attestation by itself is not valid (last entry is not self-signed).
1004 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1005
1006 // The signature over the attested key should correspond to the P256 public key.
1007 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1008 ASSERT_TRUE(key_cert.get());
1009 EVP_PKEY_Ptr signing_pubkey;
1010 p256_pub_key(coseKeyData, &signing_pubkey);
1011 ASSERT_TRUE(signing_pubkey.get());
1012
1013 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1014 << "Verification of attested certificate failed "
1015 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1016
1017 CheckedDeleteKey(&key_blob);
1018 }
1019}
1020
1021/*
Selene Huang4f64c222021-04-13 19:54:36 -07001022 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1023 *
1024 * Verifies that keymint attestation for RSA encryption keys with challenge and
1025 * app id is also successful.
1026 */
1027TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1028 auto key_size = 2048;
1029 auto challenge = "hello";
1030 auto app_id = "foo";
1031
Selene Huang6e46f142021-04-20 19:20:11 -07001032 auto subject = "subj 2";
1033 vector<uint8_t> subject_der(make_name_from_str(subject));
1034
1035 uint64_t serial_int = 111166;
1036 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1037
Selene Huang4f64c222021-04-13 19:54:36 -07001038 vector<uint8_t> key_blob;
1039 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001040 ASSERT_EQ(ErrorCode::OK,
1041 GenerateKey(AuthorizationSetBuilder()
1042 .RsaEncryptionKey(key_size, 65537)
1043 .Padding(PaddingMode::NONE)
1044 .AttestationChallenge(challenge)
1045 .AttestationApplicationId(app_id)
1046 .Authorization(TAG_NO_AUTH_REQUIRED)
1047 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1048 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1049 .SetDefaultValidity(),
1050 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001051
1052 ASSERT_GT(key_blob.size(), 0U);
1053 AuthorizationSet auths;
1054 for (auto& entry : key_characteristics) {
1055 auths.push_back(AuthorizationSet(entry.authorizations));
1056 }
1057
1058 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1059 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1060
1061 // Verify that App data and ROT are NOT included.
1062 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1063 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1064
1065 // Check that some unexpected tags/values are NOT present.
1066 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1067 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1068
1069 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1070
1071 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1072 ASSERT_TRUE(os_ver);
1073 EXPECT_EQ(*os_ver, os_version());
1074
1075 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1076
1077 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1078 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1079 << "Key size " << key_size << "missing";
1080 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1081
Selene Huang6e46f142021-04-20 19:20:11 -07001082 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001083 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1084 ASSERT_GT(cert_chain_.size(), 0);
1085
1086 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1087 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1088 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1089 sw_enforced, hw_enforced, SecLevel(),
1090 cert_chain_[0].encodedCertificate));
1091
1092 CheckedDeleteKey(&key_blob);
1093}
1094
1095/*
1096 * NewKeyGenerationTest.RsaWithSelfSign
1097 *
1098 * Verifies that attesting to RSA key generation is successful, and returns
1099 * self signed certificate if no challenge is provided. And signing etc
1100 * works as expected.
1101 */
1102TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001103 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1104 vector<uint8_t> subject_der(make_name_from_str(subject));
1105
1106 uint64_t serial_int = 0;
1107 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1108
Selene Huang4f64c222021-04-13 19:54:36 -07001109 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1110 vector<uint8_t> key_blob;
1111 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001112 ASSERT_EQ(ErrorCode::OK,
1113 GenerateKey(AuthorizationSetBuilder()
1114 .RsaSigningKey(key_size, 65537)
1115 .Digest(Digest::NONE)
1116 .Padding(PaddingMode::NONE)
1117 .Authorization(TAG_NO_AUTH_REQUIRED)
1118 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1119 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1120 .SetDefaultValidity(),
1121 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001122
1123 ASSERT_GT(key_blob.size(), 0U);
1124 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001125 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001126
1127 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1128
1129 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1130 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1131 << "Key size " << key_size << "missing";
1132 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1133
Selene Huang6e46f142021-04-20 19:20:11 -07001134 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001135 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1136 ASSERT_EQ(cert_chain_.size(), 1);
1137
1138 CheckedDeleteKey(&key_blob);
1139 }
1140}
1141
1142/*
1143 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1144 *
1145 * Verifies that attesting to RSA checks for missing app ID.
1146 */
1147TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1148 auto challenge = "hello";
1149 vector<uint8_t> key_blob;
1150 vector<KeyCharacteristics> key_characteristics;
1151
1152 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1153 GenerateKey(AuthorizationSetBuilder()
1154 .RsaSigningKey(2048, 65537)
1155 .Digest(Digest::NONE)
1156 .Padding(PaddingMode::NONE)
1157 .AttestationChallenge(challenge)
1158 .Authorization(TAG_NO_AUTH_REQUIRED)
1159 .SetDefaultValidity(),
1160 &key_blob, &key_characteristics));
1161}
1162
1163/*
1164 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1165 *
1166 * Verifies that attesting to RSA ignores app id if challenge is missing.
1167 */
1168TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1169 auto key_size = 2048;
1170 auto app_id = "foo";
1171
Selene Huang6e46f142021-04-20 19:20:11 -07001172 auto subject = "cert subj 2";
1173 vector<uint8_t> subject_der(make_name_from_str(subject));
1174
1175 uint64_t serial_int = 1;
1176 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1177
Selene Huang4f64c222021-04-13 19:54:36 -07001178 vector<uint8_t> key_blob;
1179 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001180 ASSERT_EQ(ErrorCode::OK,
1181 GenerateKey(AuthorizationSetBuilder()
1182 .RsaSigningKey(key_size, 65537)
1183 .Digest(Digest::NONE)
1184 .Padding(PaddingMode::NONE)
1185 .AttestationApplicationId(app_id)
1186 .Authorization(TAG_NO_AUTH_REQUIRED)
1187 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1188 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1189 .SetDefaultValidity(),
1190 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001191
1192 ASSERT_GT(key_blob.size(), 0U);
1193 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001194 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001195
1196 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1197
1198 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1199 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1200 << "Key size " << key_size << "missing";
1201 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1202
Selene Huang6e46f142021-04-20 19:20:11 -07001203 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001204 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1205 ASSERT_EQ(cert_chain_.size(), 1);
1206
1207 CheckedDeleteKey(&key_blob);
1208}
1209
1210/*
Qi Wud22ec842020-11-26 13:27:53 +08001211 * NewKeyGenerationTest.LimitedUsageRsa
1212 *
1213 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1214 * resulting keys have correct characteristics.
1215 */
1216TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1217 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1218 vector<uint8_t> key_blob;
1219 vector<KeyCharacteristics> key_characteristics;
1220 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1221 .RsaSigningKey(key_size, 65537)
1222 .Digest(Digest::NONE)
1223 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001224 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1225 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001226 &key_blob, &key_characteristics));
1227
1228 ASSERT_GT(key_blob.size(), 0U);
1229 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001230 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001231
1232 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1233
1234 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1235 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1236 << "Key size " << key_size << "missing";
1237 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1238
1239 // Check the usage count limit tag appears in the authorizations.
1240 AuthorizationSet auths;
1241 for (auto& entry : key_characteristics) {
1242 auths.push_back(AuthorizationSet(entry.authorizations));
1243 }
1244 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1245 << "key usage count limit " << 1U << " missing";
1246
1247 CheckedDeleteKey(&key_blob);
1248 }
1249}
1250
1251/*
Qi Wubeefae42021-01-28 23:16:37 +08001252 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1253 *
1254 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1255 * resulting keys have correct characteristics and attestation.
1256 */
1257TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001258 auto challenge = "hello";
1259 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001260
Selene Huang6e46f142021-04-20 19:20:11 -07001261 auto subject = "cert subj 2";
1262 vector<uint8_t> subject_der(make_name_from_str(subject));
1263
1264 uint64_t serial_int = 66;
1265 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1266
Selene Huang4f64c222021-04-13 19:54:36 -07001267 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001268 vector<uint8_t> key_blob;
1269 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001270 ASSERT_EQ(ErrorCode::OK,
1271 GenerateKey(AuthorizationSetBuilder()
1272 .RsaSigningKey(key_size, 65537)
1273 .Digest(Digest::NONE)
1274 .Padding(PaddingMode::NONE)
1275 .AttestationChallenge(challenge)
1276 .AttestationApplicationId(app_id)
1277 .Authorization(TAG_NO_AUTH_REQUIRED)
1278 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1279 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1280 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1281 .SetDefaultValidity(),
1282 &key_blob, &key_characteristics));
Qi Wubeefae42021-01-28 23:16:37 +08001283
1284 ASSERT_GT(key_blob.size(), 0U);
1285 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001286 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001287
1288 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1289
1290 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1291 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1292 << "Key size " << key_size << "missing";
1293 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1294
1295 // Check the usage count limit tag appears in the authorizations.
1296 AuthorizationSet auths;
1297 for (auto& entry : key_characteristics) {
1298 auths.push_back(AuthorizationSet(entry.authorizations));
1299 }
1300 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1301 << "key usage count limit " << 1U << " missing";
1302
1303 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001304 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001305 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001306 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001307
1308 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1309 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1310 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1311 sw_enforced, hw_enforced, SecLevel(),
1312 cert_chain_[0].encodedCertificate));
1313
1314 CheckedDeleteKey(&key_blob);
1315 }
1316}
1317
1318/*
Selene Huang31ab4042020-04-29 04:22:39 -07001319 * NewKeyGenerationTest.NoInvalidRsaSizes
1320 *
1321 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1322 */
1323TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1324 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1325 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001326 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001327 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1328 GenerateKey(AuthorizationSetBuilder()
1329 .RsaSigningKey(key_size, 65537)
1330 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001331 .Padding(PaddingMode::NONE)
1332 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001333 &key_blob, &key_characteristics));
1334 }
1335}
1336
1337/*
1338 * NewKeyGenerationTest.RsaNoDefaultSize
1339 *
1340 * Verifies that failing to specify a key size for RSA key generation returns
1341 * UNSUPPORTED_KEY_SIZE.
1342 */
1343TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1344 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1345 GenerateKey(AuthorizationSetBuilder()
1346 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1347 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001348 .SigningKey()
1349 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001350}
1351
1352/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001353 * NewKeyGenerationTest.RsaMissingParams
1354 *
1355 * Verifies that omitting optional tags works.
1356 */
1357TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1358 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1359 ASSERT_EQ(ErrorCode::OK,
1360 GenerateKey(
1361 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1362 CheckedDeleteKey();
1363 }
1364}
1365
1366/*
Selene Huang31ab4042020-04-29 04:22:39 -07001367 * NewKeyGenerationTest.Ecdsa
1368 *
1369 * Verifies that keymint can generate all required EC key sizes, and that the resulting keys
1370 * have correct characteristics.
1371 */
1372TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001373 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001374 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001375 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001376 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001377 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001378 .Digest(Digest::NONE)
1379 .SetDefaultValidity(),
1380 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001381 ASSERT_GT(key_blob.size(), 0U);
1382 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001383 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001384
Shawn Willden7f424372021-01-10 18:06:50 -07001385 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001386
1387 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001388 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001389
1390 CheckedDeleteKey(&key_blob);
1391 }
1392}
1393
1394/*
Selene Huang4f64c222021-04-13 19:54:36 -07001395 * NewKeyGenerationTest.EcdsaAttestation
1396 *
1397 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1398 * an attestation will be generated.
1399 */
1400TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1401 auto challenge = "hello";
1402 auto app_id = "foo";
1403
Selene Huang6e46f142021-04-20 19:20:11 -07001404 auto subject = "cert subj 2";
1405 vector<uint8_t> subject_der(make_name_from_str(subject));
1406
1407 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1408 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1409
David Drysdaledf09e542021-06-08 15:46:11 +01001410 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001411 vector<uint8_t> key_blob;
1412 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001413 ASSERT_EQ(ErrorCode::OK,
1414 GenerateKey(AuthorizationSetBuilder()
1415 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001416 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001417 .Digest(Digest::NONE)
1418 .AttestationChallenge(challenge)
1419 .AttestationApplicationId(app_id)
1420 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1421 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1422 .SetDefaultValidity(),
1423 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001424 ASSERT_GT(key_blob.size(), 0U);
1425 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001426 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001427
1428 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1429
1430 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001431 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001432
1433 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1434 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001435 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001436
1437 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1438 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1439 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1440 sw_enforced, hw_enforced, SecLevel(),
1441 cert_chain_[0].encodedCertificate));
1442
1443 CheckedDeleteKey(&key_blob);
1444 }
1445}
1446
1447/*
David Drysdale37af4b32021-05-14 16:46:59 +01001448 * NewKeyGenerationTest.EcdsaAttestationTags
1449 *
1450 * Verifies that creation of an attested ECDSA key includes various tags in the
1451 * attestation extension.
1452 */
1453TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1454 auto challenge = "hello";
1455 auto app_id = "foo";
1456 auto subject = "cert subj 2";
1457 vector<uint8_t> subject_der(make_name_from_str(subject));
1458 uint64_t serial_int = 0x1010;
1459 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1460 const AuthorizationSetBuilder base_builder =
1461 AuthorizationSetBuilder()
1462 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001463 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001464 .Digest(Digest::NONE)
1465 .AttestationChallenge(challenge)
1466 .AttestationApplicationId(app_id)
1467 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1468 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1469 .SetDefaultValidity();
1470
1471 // Various tags that map to fields in the attestation extension ASN.1 schema.
1472 auto extra_tags = AuthorizationSetBuilder()
1473 .Authorization(TAG_ROLLBACK_RESISTANCE)
1474 .Authorization(TAG_EARLY_BOOT_ONLY)
1475 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1476 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1477 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1478 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1479 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1480 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1481 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1482 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1483 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1484 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001485
David Drysdale37af4b32021-05-14 16:46:59 +01001486 for (const KeyParameter& tag : extra_tags) {
1487 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1488 vector<uint8_t> key_blob;
1489 vector<KeyCharacteristics> key_characteristics;
1490 AuthorizationSetBuilder builder = base_builder;
1491 builder.push_back(tag);
1492 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1493 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1494 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1495 continue;
1496 }
Seth Mooreb393b082021-07-12 14:18:28 -07001497 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1498 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001499 continue;
1500 }
1501 ASSERT_EQ(result, ErrorCode::OK);
1502 ASSERT_GT(key_blob.size(), 0U);
1503
1504 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1505 ASSERT_GT(cert_chain_.size(), 0);
1506 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1507
1508 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1509 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001510 // Some tags are optional, so don't require them to be in the enforcements.
1511 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001512 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1513 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1514 }
1515
1516 // Verifying the attestation record will check for the specific tag because
1517 // it's included in the authorizations.
1518 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1519 SecLevel(), cert_chain_[0].encodedCertificate));
1520
1521 CheckedDeleteKey(&key_blob);
1522 }
1523
David Drysdalec53b7d92021-10-11 12:35:58 +01001524 // Collection of invalid attestation ID tags.
1525 auto invalid_tags =
1526 AuthorizationSetBuilder()
1527 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1528 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1529 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1530 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1531 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1532 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1533 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1534 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001535 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001536 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001537 vector<uint8_t> key_blob;
1538 vector<KeyCharacteristics> key_characteristics;
1539 AuthorizationSetBuilder builder =
1540 AuthorizationSetBuilder()
1541 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001542 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001543 .Digest(Digest::NONE)
1544 .AttestationChallenge(challenge)
1545 .AttestationApplicationId(app_id)
1546 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1547 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1548 .SetDefaultValidity();
1549 builder.push_back(tag);
1550 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1551 GenerateKey(builder, &key_blob, &key_characteristics));
1552 }
1553}
1554
1555/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001556 * NewKeyGenerationTest.EcdsaAttestationIdTags
1557 *
1558 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1559 * attestation extension.
1560 */
1561TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
1562 auto challenge = "hello";
1563 auto app_id = "foo";
1564 auto subject = "cert subj 2";
1565 vector<uint8_t> subject_der(make_name_from_str(subject));
1566 uint64_t serial_int = 0x1010;
1567 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1568 const AuthorizationSetBuilder base_builder =
1569 AuthorizationSetBuilder()
1570 .Authorization(TAG_NO_AUTH_REQUIRED)
1571 .EcdsaSigningKey(EcCurve::P_256)
1572 .Digest(Digest::NONE)
1573 .AttestationChallenge(challenge)
1574 .AttestationApplicationId(app_id)
1575 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1576 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1577 .SetDefaultValidity();
1578
1579 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1580 auto extra_tags = AuthorizationSetBuilder();
1581 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1582 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1583 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1584 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1585 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1586 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1587
1588 for (const KeyParameter& tag : extra_tags) {
1589 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1590 vector<uint8_t> key_blob;
1591 vector<KeyCharacteristics> key_characteristics;
1592 AuthorizationSetBuilder builder = base_builder;
1593 builder.push_back(tag);
1594 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1595 if (result == ErrorCode::CANNOT_ATTEST_IDS) {
1596 // Device ID attestation is optional; KeyMint may not support it at all.
1597 continue;
1598 }
1599 ASSERT_EQ(result, ErrorCode::OK);
1600 ASSERT_GT(key_blob.size(), 0U);
1601
1602 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1603 ASSERT_GT(cert_chain_.size(), 0);
1604 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1605
1606 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1607 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1608
1609 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
1610 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
1611 // attestation extension should contain them, so make sure the extra tag is added.
1612 hw_enforced.push_back(tag);
1613
1614 // Verifying the attestation record will check for the specific tag because
1615 // it's included in the authorizations.
1616 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1617 SecLevel(), cert_chain_[0].encodedCertificate));
1618
1619 CheckedDeleteKey(&key_blob);
1620 }
1621}
1622
1623/*
David Drysdale565ccc72021-10-11 12:49:50 +01001624 * NewKeyGenerationTest.EcdsaAttestationUniqueId
1625 *
1626 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
1627 */
1628TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
1629 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00001630 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01001631 auto challenge = "hello";
1632 auto subject = "cert subj 2";
1633 vector<uint8_t> subject_der(make_name_from_str(subject));
1634 uint64_t serial_int = 0x1010;
1635 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00001636 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01001637 AuthorizationSetBuilder()
1638 .Authorization(TAG_NO_AUTH_REQUIRED)
1639 .Authorization(TAG_INCLUDE_UNIQUE_ID)
1640 .EcdsaSigningKey(EcCurve::P_256)
1641 .Digest(Digest::NONE)
1642 .AttestationChallenge(challenge)
1643 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1644 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1645 .AttestationApplicationId(app_id)
1646 .Authorization(TAG_CREATION_DATETIME, datetime)
1647 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00001648 if (reset) {
1649 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
1650 }
David Drysdale565ccc72021-10-11 12:49:50 +01001651
1652 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
1653 ASSERT_GT(key_blob_.size(), 0U);
1654
1655 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1656 ASSERT_GT(cert_chain_.size(), 0);
1657 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1658
1659 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
1660 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
1661
1662 // Check that the unique ID field in the extension is non-empty.
1663 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1664 SecLevel(), cert_chain_[0].encodedCertificate,
1665 unique_id));
1666 EXPECT_GT(unique_id->size(), 0);
1667 CheckedDeleteKey();
1668 };
1669
1670 // Generate unique ID
1671 auto app_id = "foo";
1672 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
1673 vector<uint8_t> unique_id;
1674 get_unique_id(app_id, cert_date, &unique_id);
1675
1676 // Generating a new key with the same parameters should give the same unique ID.
1677 vector<uint8_t> unique_id2;
1678 get_unique_id(app_id, cert_date, &unique_id2);
1679 EXPECT_EQ(unique_id, unique_id2);
1680
1681 // Generating a new key with a slightly different date should give the same unique ID.
1682 uint64_t rounded_date = cert_date / 2592000000LLU;
1683 uint64_t min_date = rounded_date * 2592000000LLU;
1684 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
1685
1686 vector<uint8_t> unique_id3;
1687 get_unique_id(app_id, min_date, &unique_id3);
1688 EXPECT_EQ(unique_id, unique_id3);
1689
1690 vector<uint8_t> unique_id4;
1691 get_unique_id(app_id, max_date, &unique_id4);
1692 EXPECT_EQ(unique_id, unique_id4);
1693
1694 // A different attestation application ID should yield a different unique ID.
1695 auto app_id2 = "different_foo";
1696 vector<uint8_t> unique_id5;
1697 get_unique_id(app_id2, cert_date, &unique_id5);
1698 EXPECT_NE(unique_id, unique_id5);
1699
1700 // A radically different date should yield a different unique ID.
1701 vector<uint8_t> unique_id6;
1702 get_unique_id(app_id, 1611621648000, &unique_id6);
1703 EXPECT_NE(unique_id, unique_id6);
1704
1705 vector<uint8_t> unique_id7;
1706 get_unique_id(app_id, max_date + 1, &unique_id7);
1707 EXPECT_NE(unique_id, unique_id7);
1708
1709 vector<uint8_t> unique_id8;
1710 get_unique_id(app_id, min_date - 1, &unique_id8);
1711 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00001712
1713 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
1714 vector<uint8_t> unique_id9;
1715 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
1716 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01001717}
1718
1719/*
David Drysdale37af4b32021-05-14 16:46:59 +01001720 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1721 *
1722 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1723 */
1724TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1725 auto challenge = "hello";
1726 auto attest_app_id = "foo";
1727 auto subject = "cert subj 2";
1728 vector<uint8_t> subject_der(make_name_from_str(subject));
1729 uint64_t serial_int = 0x1010;
1730 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1731
1732 // Earlier versions of the attestation extension schema included a slot:
1733 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1734 // This should never have been included, and should never be filled in.
1735 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1736 // to confirm that this field never makes it into the attestation extension.
1737 vector<uint8_t> key_blob;
1738 vector<KeyCharacteristics> key_characteristics;
1739 auto result = GenerateKey(AuthorizationSetBuilder()
1740 .Authorization(TAG_NO_AUTH_REQUIRED)
1741 .EcdsaSigningKey(EcCurve::P_256)
1742 .Digest(Digest::NONE)
1743 .AttestationChallenge(challenge)
1744 .AttestationApplicationId(attest_app_id)
1745 .Authorization(TAG_APPLICATION_ID, "client_id")
1746 .Authorization(TAG_APPLICATION_DATA, "appdata")
1747 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1748 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1749 .SetDefaultValidity(),
1750 &key_blob, &key_characteristics);
1751 ASSERT_EQ(result, ErrorCode::OK);
1752 ASSERT_GT(key_blob.size(), 0U);
1753
1754 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1755 ASSERT_GT(cert_chain_.size(), 0);
1756 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1757
1758 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1759 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1760 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1761 SecLevel(), cert_chain_[0].encodedCertificate));
1762
1763 // Check that the app id is not in the cert.
1764 string app_id = "clientid";
1765 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1766 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1767 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1768 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1769 cert_chain_[0].encodedCertificate.end());
1770
1771 CheckedDeleteKey(&key_blob);
1772}
1773
1774/*
Selene Huang4f64c222021-04-13 19:54:36 -07001775 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1776 *
1777 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1778 * the key will generate a self signed attestation.
1779 */
1780TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001781 auto subject = "cert subj 2";
1782 vector<uint8_t> subject_der(make_name_from_str(subject));
1783
1784 uint64_t serial_int = 0x123456FFF1234;
1785 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1786
David Drysdaledf09e542021-06-08 15:46:11 +01001787 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001788 vector<uint8_t> key_blob;
1789 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001790 ASSERT_EQ(ErrorCode::OK,
1791 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001792 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001793 .Digest(Digest::NONE)
1794 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1795 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1796 .SetDefaultValidity(),
1797 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001798 ASSERT_GT(key_blob.size(), 0U);
1799 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001800 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001801
1802 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1803
1804 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001805 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001806
1807 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001808 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001809 ASSERT_EQ(cert_chain_.size(), 1);
1810
1811 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1812 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1813
1814 CheckedDeleteKey(&key_blob);
1815 }
1816}
1817
1818/*
1819 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1820 *
1821 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1822 * app id must also be provided or else it will fail.
1823 */
1824TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1825 auto challenge = "hello";
1826 vector<uint8_t> key_blob;
1827 vector<KeyCharacteristics> key_characteristics;
1828
1829 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1830 GenerateKey(AuthorizationSetBuilder()
1831 .EcdsaSigningKey(EcCurve::P_256)
1832 .Digest(Digest::NONE)
1833 .AttestationChallenge(challenge)
1834 .SetDefaultValidity(),
1835 &key_blob, &key_characteristics));
1836}
1837
1838/*
1839 * NewKeyGenerationTest.EcdsaIgnoreAppId
1840 *
1841 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1842 * any appid will be ignored, and keymint will generate a self sign certificate.
1843 */
1844TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1845 auto app_id = "foo";
1846
David Drysdaledf09e542021-06-08 15:46:11 +01001847 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001848 vector<uint8_t> key_blob;
1849 vector<KeyCharacteristics> key_characteristics;
1850 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001851 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001852 .Digest(Digest::NONE)
1853 .AttestationApplicationId(app_id)
1854 .SetDefaultValidity(),
1855 &key_blob, &key_characteristics));
1856
1857 ASSERT_GT(key_blob.size(), 0U);
1858 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001859 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001860
1861 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1862
1863 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001864 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001865
1866 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1867 ASSERT_EQ(cert_chain_.size(), 1);
1868
1869 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1870 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1871
1872 CheckedDeleteKey(&key_blob);
1873 }
1874}
1875
1876/*
1877 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1878 *
1879 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1880 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1881 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1882 * to specify how many following bytes will be used to encode the length.
1883 */
1884TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1885 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001886 std::vector<uint32_t> app_id_lengths{143, 258};
1887
1888 for (uint32_t length : app_id_lengths) {
1889 const string app_id(length, 'a');
1890 vector<uint8_t> key_blob;
1891 vector<KeyCharacteristics> key_characteristics;
1892 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1893 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001894 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001895 .Digest(Digest::NONE)
1896 .AttestationChallenge(challenge)
1897 .AttestationApplicationId(app_id)
1898 .SetDefaultValidity(),
1899 &key_blob, &key_characteristics));
1900 ASSERT_GT(key_blob.size(), 0U);
1901 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001902 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001903
1904 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1905
1906 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001907 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001908
1909 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1910 ASSERT_GT(cert_chain_.size(), 0);
1911
1912 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1913 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1914 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1915 sw_enforced, hw_enforced, SecLevel(),
1916 cert_chain_[0].encodedCertificate));
1917
1918 CheckedDeleteKey(&key_blob);
1919 }
1920}
1921
1922/*
Qi Wud22ec842020-11-26 13:27:53 +08001923 * NewKeyGenerationTest.LimitedUsageEcdsa
1924 *
1925 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1926 * resulting keys have correct characteristics.
1927 */
1928TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001929 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001930 vector<uint8_t> key_blob;
1931 vector<KeyCharacteristics> key_characteristics;
1932 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001933 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001934 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001935 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1936 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001937 &key_blob, &key_characteristics));
1938
1939 ASSERT_GT(key_blob.size(), 0U);
1940 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001941 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001942
1943 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1944
1945 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001946 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001947
1948 // Check the usage count limit tag appears in the authorizations.
1949 AuthorizationSet auths;
1950 for (auto& entry : key_characteristics) {
1951 auths.push_back(AuthorizationSet(entry.authorizations));
1952 }
1953 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1954 << "key usage count limit " << 1U << " missing";
1955
1956 CheckedDeleteKey(&key_blob);
1957 }
1958}
1959
1960/*
Selene Huang31ab4042020-04-29 04:22:39 -07001961 * NewKeyGenerationTest.EcdsaDefaultSize
1962 *
David Drysdaledf09e542021-06-08 15:46:11 +01001963 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001964 * UNSUPPORTED_KEY_SIZE.
1965 */
1966TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1967 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1968 GenerateKey(AuthorizationSetBuilder()
1969 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1970 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001971 .Digest(Digest::NONE)
1972 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001973}
1974
1975/*
1976 * NewKeyGenerationTest.EcdsaInvalidSize
1977 *
1978 * Verifies that specifying an invalid key size for EC key generation returns
1979 * UNSUPPORTED_KEY_SIZE.
1980 */
1981TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdaledf09e542021-06-08 15:46:11 +01001982 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001983 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001984 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001985 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001986 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001987 .Digest(Digest::NONE)
1988 .SetDefaultValidity(),
1989 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001990 }
1991
David Drysdaledf09e542021-06-08 15:46:11 +01001992 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1993 GenerateKey(AuthorizationSetBuilder()
1994 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1995 .Authorization(TAG_KEY_SIZE, 190)
1996 .SigningKey()
1997 .Digest(Digest::NONE)
1998 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001999}
2000
2001/*
2002 * NewKeyGenerationTest.EcdsaMismatchKeySize
2003 *
2004 * Verifies that specifying mismatched key size and curve for EC key generation returns
2005 * INVALID_ARGUMENT.
2006 */
2007TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002008 if (SecLevel() == SecurityLevel::STRONGBOX) {
2009 GTEST_SKIP() << "Test not applicable to StrongBox device";
2010 }
Selene Huang31ab4042020-04-29 04:22:39 -07002011
David Drysdaledf09e542021-06-08 15:46:11 +01002012 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002013 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002014 .Authorization(TAG_KEY_SIZE, 224)
2015 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002016 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002017 .Digest(Digest::NONE)
2018 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002019 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002020}
2021
2022/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002023 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002024 *
2025 * Verifies that keymint does not support any curve designated as unsupported.
2026 */
2027TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2028 Digest digest;
2029 if (SecLevel() == SecurityLevel::STRONGBOX) {
2030 digest = Digest::SHA_2_256;
2031 } else {
2032 digest = Digest::SHA_2_512;
2033 }
2034 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002035 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2036 .EcdsaSigningKey(curve)
2037 .Digest(digest)
2038 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002039 << "Failed to generate key on curve: " << curve;
2040 CheckedDeleteKey();
2041 }
2042}
2043
2044/*
2045 * NewKeyGenerationTest.Hmac
2046 *
2047 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2048 * characteristics.
2049 */
2050TEST_P(NewKeyGenerationTest, Hmac) {
2051 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2052 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002053 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002054 constexpr size_t key_size = 128;
2055 ASSERT_EQ(ErrorCode::OK,
2056 GenerateKey(
2057 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2058 TAG_MIN_MAC_LENGTH, 128),
2059 &key_blob, &key_characteristics));
2060
2061 ASSERT_GT(key_blob.size(), 0U);
2062 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002063 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002064
Shawn Willden7f424372021-01-10 18:06:50 -07002065 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2066 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2067 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2068 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002069
2070 CheckedDeleteKey(&key_blob);
2071 }
2072}
2073
2074/*
Selene Huang4f64c222021-04-13 19:54:36 -07002075 * NewKeyGenerationTest.HmacNoAttestation
2076 *
2077 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2078 * and app id are provided.
2079 */
2080TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2081 auto challenge = "hello";
2082 auto app_id = "foo";
2083
2084 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2085 vector<uint8_t> key_blob;
2086 vector<KeyCharacteristics> key_characteristics;
2087 constexpr size_t key_size = 128;
2088 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2089 .HmacKey(key_size)
2090 .Digest(digest)
2091 .AttestationChallenge(challenge)
2092 .AttestationApplicationId(app_id)
2093 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2094 &key_blob, &key_characteristics));
2095
2096 ASSERT_GT(key_blob.size(), 0U);
2097 ASSERT_EQ(cert_chain_.size(), 0);
2098 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002099 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002100
2101 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2102 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2103 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2104 << "Key size " << key_size << "missing";
2105
2106 CheckedDeleteKey(&key_blob);
2107 }
2108}
2109
2110/*
Qi Wud22ec842020-11-26 13:27:53 +08002111 * NewKeyGenerationTest.LimitedUsageHmac
2112 *
2113 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2114 * resulting keys have correct characteristics.
2115 */
2116TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2117 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2118 vector<uint8_t> key_blob;
2119 vector<KeyCharacteristics> key_characteristics;
2120 constexpr size_t key_size = 128;
2121 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2122 .HmacKey(key_size)
2123 .Digest(digest)
2124 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2125 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2126 &key_blob, &key_characteristics));
2127
2128 ASSERT_GT(key_blob.size(), 0U);
2129 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002130 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002131
2132 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2133 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2134 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2135 << "Key size " << key_size << "missing";
2136
2137 // Check the usage count limit tag appears in the authorizations.
2138 AuthorizationSet auths;
2139 for (auto& entry : key_characteristics) {
2140 auths.push_back(AuthorizationSet(entry.authorizations));
2141 }
2142 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2143 << "key usage count limit " << 1U << " missing";
2144
2145 CheckedDeleteKey(&key_blob);
2146 }
2147}
2148
2149/*
Selene Huang31ab4042020-04-29 04:22:39 -07002150 * NewKeyGenerationTest.HmacCheckKeySizes
2151 *
2152 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2153 */
2154TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2155 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2156 if (key_size < 64 || key_size % 8 != 0) {
2157 // To keep this test from being very slow, we only test a random fraction of
2158 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2159 // them, we expect to run ~40 of them in each run.
2160 if (key_size % 8 == 0 || random() % 10 == 0) {
2161 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2162 GenerateKey(AuthorizationSetBuilder()
2163 .HmacKey(key_size)
2164 .Digest(Digest::SHA_2_256)
2165 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2166 << "HMAC key size " << key_size << " invalid";
2167 }
2168 } else {
2169 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2170 .HmacKey(key_size)
2171 .Digest(Digest::SHA_2_256)
2172 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2173 << "Failed to generate HMAC key of size " << key_size;
2174 CheckedDeleteKey();
2175 }
2176 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002177 if (SecLevel() == SecurityLevel::STRONGBOX) {
2178 // STRONGBOX devices must not support keys larger than 512 bits.
2179 size_t key_size = 520;
2180 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2181 GenerateKey(AuthorizationSetBuilder()
2182 .HmacKey(key_size)
2183 .Digest(Digest::SHA_2_256)
2184 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2185 << "HMAC key size " << key_size << " unexpectedly valid";
2186 }
Selene Huang31ab4042020-04-29 04:22:39 -07002187}
2188
2189/*
2190 * NewKeyGenerationTest.HmacCheckMinMacLengths
2191 *
2192 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2193 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2194 * specific MAC length that failed, so reproducing a failed run will be easy.
2195 */
2196TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2197 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2198 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2199 // To keep this test from being very long, we only test a random fraction of
2200 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2201 // we expect to run ~17 of them in each run.
2202 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2203 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2204 GenerateKey(AuthorizationSetBuilder()
2205 .HmacKey(128)
2206 .Digest(Digest::SHA_2_256)
2207 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2208 << "HMAC min mac length " << min_mac_length << " invalid.";
2209 }
2210 } else {
2211 EXPECT_EQ(ErrorCode::OK,
2212 GenerateKey(AuthorizationSetBuilder()
2213 .HmacKey(128)
2214 .Digest(Digest::SHA_2_256)
2215 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2216 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2217 CheckedDeleteKey();
2218 }
2219 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002220
2221 // Minimum MAC length must be no more than 512 bits.
2222 size_t min_mac_length = 520;
2223 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2224 GenerateKey(AuthorizationSetBuilder()
2225 .HmacKey(128)
2226 .Digest(Digest::SHA_2_256)
2227 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2228 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002229}
2230
2231/*
2232 * NewKeyGenerationTest.HmacMultipleDigests
2233 *
2234 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2235 */
2236TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002237 if (SecLevel() == SecurityLevel::STRONGBOX) {
2238 GTEST_SKIP() << "Test not applicable to StrongBox device";
2239 }
Selene Huang31ab4042020-04-29 04:22:39 -07002240
2241 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2242 GenerateKey(AuthorizationSetBuilder()
2243 .HmacKey(128)
2244 .Digest(Digest::SHA1)
2245 .Digest(Digest::SHA_2_256)
2246 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2247}
2248
2249/*
2250 * NewKeyGenerationTest.HmacDigestNone
2251 *
2252 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2253 */
2254TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2255 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2256 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2257 128)));
2258
2259 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2260 GenerateKey(AuthorizationSetBuilder()
2261 .HmacKey(128)
2262 .Digest(Digest::NONE)
2263 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2264}
2265
Selene Huang4f64c222021-04-13 19:54:36 -07002266/*
2267 * NewKeyGenerationTest.AesNoAttestation
2268 *
2269 * Verifies that attestation parameters to AES keys are ignored and generateKey
2270 * will succeed.
2271 */
2272TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2273 auto challenge = "hello";
2274 auto app_id = "foo";
2275
2276 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2277 .Authorization(TAG_NO_AUTH_REQUIRED)
2278 .AesEncryptionKey(128)
2279 .EcbMode()
2280 .Padding(PaddingMode::PKCS7)
2281 .AttestationChallenge(challenge)
2282 .AttestationApplicationId(app_id)));
2283
2284 ASSERT_EQ(cert_chain_.size(), 0);
2285}
2286
2287/*
2288 * NewKeyGenerationTest.TripleDesNoAttestation
2289 *
2290 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2291 * will be successful. No attestation should be generated.
2292 */
2293TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2294 auto challenge = "hello";
2295 auto app_id = "foo";
2296
2297 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2298 .TripleDesEncryptionKey(168)
2299 .BlockMode(BlockMode::ECB)
2300 .Authorization(TAG_NO_AUTH_REQUIRED)
2301 .Padding(PaddingMode::NONE)
2302 .AttestationChallenge(challenge)
2303 .AttestationApplicationId(app_id)));
2304 ASSERT_EQ(cert_chain_.size(), 0);
2305}
2306
Selene Huang31ab4042020-04-29 04:22:39 -07002307INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2308
2309typedef KeyMintAidlTestBase SigningOperationsTest;
2310
2311/*
2312 * SigningOperationsTest.RsaSuccess
2313 *
2314 * Verifies that raw RSA signature operations succeed.
2315 */
2316TEST_P(SigningOperationsTest, RsaSuccess) {
2317 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2318 .RsaSigningKey(2048, 65537)
2319 .Digest(Digest::NONE)
2320 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002321 .Authorization(TAG_NO_AUTH_REQUIRED)
2322 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002323 string message = "12345678901234567890123456789012";
2324 string signature = SignMessage(
2325 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002326 LocalVerifyMessage(message, signature,
2327 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2328}
2329
2330/*
2331 * SigningOperationsTest.RsaAllPaddingsAndDigests
2332 *
2333 * Verifies RSA signature/verification for all padding modes and digests.
2334 */
2335TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2336 auto authorizations = AuthorizationSetBuilder()
2337 .Authorization(TAG_NO_AUTH_REQUIRED)
2338 .RsaSigningKey(2048, 65537)
2339 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2340 .Padding(PaddingMode::NONE)
2341 .Padding(PaddingMode::RSA_PSS)
2342 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2343 .SetDefaultValidity();
2344
2345 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2346
2347 string message(128, 'a');
2348 string corrupt_message(message);
2349 ++corrupt_message[corrupt_message.size() / 2];
2350
2351 for (auto padding :
2352 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2353 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2354 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2355 // Digesting only makes sense with padding.
2356 continue;
2357 }
2358
2359 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2360 // PSS requires digesting.
2361 continue;
2362 }
2363
2364 string signature =
2365 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2366 LocalVerifyMessage(message, signature,
2367 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2368 }
2369 }
Selene Huang31ab4042020-04-29 04:22:39 -07002370}
2371
2372/*
2373 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2374 *
Shawn Willden7f424372021-01-10 18:06:50 -07002375 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002376 */
2377TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2378 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2379 .Authorization(TAG_NO_AUTH_REQUIRED)
2380 .RsaSigningKey(2048, 65537)
2381 .Digest(Digest::NONE)
2382 .Padding(PaddingMode::NONE)
2383 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002384 .Authorization(TAG_APPLICATION_DATA, "appdata")
2385 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002386
2387 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2388
Selene Huang31ab4042020-04-29 04:22:39 -07002389 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2390 Begin(KeyPurpose::SIGN,
2391 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2392 AbortIfNeeded();
2393 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2394 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2395 .Digest(Digest::NONE)
2396 .Padding(PaddingMode::NONE)
2397 .Authorization(TAG_APPLICATION_ID, "clientid")));
2398 AbortIfNeeded();
2399 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2400 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2401 .Digest(Digest::NONE)
2402 .Padding(PaddingMode::NONE)
2403 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2404 AbortIfNeeded();
2405 EXPECT_EQ(ErrorCode::OK,
2406 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2407 .Digest(Digest::NONE)
2408 .Padding(PaddingMode::NONE)
2409 .Authorization(TAG_APPLICATION_DATA, "appdata")
2410 .Authorization(TAG_APPLICATION_ID, "clientid")));
2411 AbortIfNeeded();
2412}
2413
2414/*
2415 * SigningOperationsTest.RsaPssSha256Success
2416 *
2417 * Verifies that RSA-PSS signature operations succeed.
2418 */
2419TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2420 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2421 .RsaSigningKey(2048, 65537)
2422 .Digest(Digest::SHA_2_256)
2423 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002424 .Authorization(TAG_NO_AUTH_REQUIRED)
2425 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002426 // Use large message, which won't work without digesting.
2427 string message(1024, 'a');
2428 string signature = SignMessage(
2429 message,
2430 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2431}
2432
2433/*
2434 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2435 *
2436 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2437 * supports only unpadded operations.
2438 */
2439TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
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::NONE)
2445 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002446 string message = "12345678901234567890123456789012";
2447 string signature;
2448
2449 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2450 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2451 .Digest(Digest::NONE)
2452 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2453}
2454
2455/*
2456 * SigningOperationsTest.NoUserConfirmation
2457 *
2458 * Verifies that keymint rejects signing operations for keys with
2459 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2460 * presented.
2461 */
2462TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002463 if (SecLevel() == SecurityLevel::STRONGBOX) {
2464 GTEST_SKIP() << "Test not applicable to StrongBox device";
2465 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002466 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2467 .RsaSigningKey(1024, 65537)
2468 .Digest(Digest::NONE)
2469 .Padding(PaddingMode::NONE)
2470 .Authorization(TAG_NO_AUTH_REQUIRED)
2471 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2472 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002473
2474 const string message = "12345678901234567890123456789012";
2475 EXPECT_EQ(ErrorCode::OK,
2476 Begin(KeyPurpose::SIGN,
2477 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2478 string signature;
2479 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2480}
2481
2482/*
2483 * SigningOperationsTest.RsaPkcs1Sha256Success
2484 *
2485 * Verifies that digested RSA-PKCS1 signature operations succeed.
2486 */
2487TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2488 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2489 .RsaSigningKey(2048, 65537)
2490 .Digest(Digest::SHA_2_256)
2491 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002492 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2493 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002494 string message(1024, 'a');
2495 string signature = SignMessage(message, AuthorizationSetBuilder()
2496 .Digest(Digest::SHA_2_256)
2497 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2498}
2499
2500/*
2501 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2502 *
2503 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2504 */
2505TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2506 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2507 .RsaSigningKey(2048, 65537)
2508 .Digest(Digest::NONE)
2509 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002510 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2511 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002512 string message(53, 'a');
2513 string signature = SignMessage(message, AuthorizationSetBuilder()
2514 .Digest(Digest::NONE)
2515 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2516}
2517
2518/*
2519 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2520 *
2521 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2522 * given a too-long message.
2523 */
2524TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
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::RSA_PKCS1_1_5_SIGN)
2530 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002531 string message(257, 'a');
2532
2533 EXPECT_EQ(ErrorCode::OK,
2534 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2535 .Digest(Digest::NONE)
2536 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2537 string signature;
2538 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2539}
2540
2541/*
2542 * SigningOperationsTest.RsaPssSha512TooSmallKey
2543 *
2544 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2545 * used with a key that is too small for the message.
2546 *
2547 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2548 * keymint specification requires that salt_size == digest_size, so the message will be
2549 * digest_size * 2 +
2550 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2551 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2552 * for a 1024-bit key.
2553 */
2554TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01002555 if (SecLevel() == SecurityLevel::STRONGBOX) {
2556 GTEST_SKIP() << "Test not applicable to StrongBox device";
2557 }
Selene Huang31ab4042020-04-29 04:22:39 -07002558 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2559 .RsaSigningKey(1024, 65537)
2560 .Digest(Digest::SHA_2_512)
2561 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002562 .Padding(PaddingMode::RSA_PSS)
2563 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002564 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2565 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2566 .Digest(Digest::SHA_2_512)
2567 .Padding(PaddingMode::RSA_PSS)));
2568}
2569
2570/*
2571 * SigningOperationsTest.RsaNoPaddingTooLong
2572 *
2573 * Verifies that raw RSA signature operations fail with the correct error code when
2574 * given a too-long message.
2575 */
2576TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2577 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2578 .RsaSigningKey(2048, 65537)
2579 .Digest(Digest::NONE)
2580 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002581 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2582 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002583 // One byte too long
2584 string message(2048 / 8 + 1, 'a');
2585 ASSERT_EQ(ErrorCode::OK,
2586 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2587 .Digest(Digest::NONE)
2588 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2589 string result;
2590 ErrorCode finish_error_code = Finish(message, &result);
2591 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2592 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2593
2594 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2595 message = string(128 * 1024, 'a');
2596 ASSERT_EQ(ErrorCode::OK,
2597 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2598 .Digest(Digest::NONE)
2599 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2600 finish_error_code = Finish(message, &result);
2601 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2602 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2603}
2604
2605/*
2606 * SigningOperationsTest.RsaAbort
2607 *
2608 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2609 * test, but the behavior should be algorithm and purpose-independent.
2610 */
2611TEST_P(SigningOperationsTest, RsaAbort) {
2612 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2613 .RsaSigningKey(2048, 65537)
2614 .Digest(Digest::NONE)
2615 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002616 .Padding(PaddingMode::NONE)
2617 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002618
2619 ASSERT_EQ(ErrorCode::OK,
2620 Begin(KeyPurpose::SIGN,
2621 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2622 EXPECT_EQ(ErrorCode::OK, Abort());
2623
2624 // Another abort should fail
2625 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2626
2627 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002628 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002629}
2630
2631/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002632 * SigningOperationsTest.RsaNonUniqueParams
2633 *
2634 * Verifies that an operation with multiple padding modes is rejected.
2635 */
2636TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2637 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2638 .RsaSigningKey(2048, 65537)
2639 .Digest(Digest::NONE)
2640 .Digest(Digest::SHA1)
2641 .Authorization(TAG_NO_AUTH_REQUIRED)
2642 .Padding(PaddingMode::NONE)
2643 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2644 .SetDefaultValidity()));
2645
2646 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2647 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2648 .Digest(Digest::NONE)
2649 .Padding(PaddingMode::NONE)
2650 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2651
Tommy Chiuc93c4392021-05-11 18:36:50 +08002652 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2653 .Digest(Digest::NONE)
2654 .Digest(Digest::SHA1)
2655 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2656 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002657
2658 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2659 Begin(KeyPurpose::SIGN,
2660 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2661}
2662
2663/*
Selene Huang31ab4042020-04-29 04:22:39 -07002664 * SigningOperationsTest.RsaUnsupportedPadding
2665 *
2666 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2667 * with a padding mode inappropriate for RSA.
2668 */
2669TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2670 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2671 .RsaSigningKey(2048, 65537)
2672 .Authorization(TAG_NO_AUTH_REQUIRED)
2673 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002674 .Padding(PaddingMode::PKCS7)
2675 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002676 ASSERT_EQ(
2677 ErrorCode::UNSUPPORTED_PADDING_MODE,
2678 Begin(KeyPurpose::SIGN,
2679 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002680 CheckedDeleteKey();
2681
2682 ASSERT_EQ(ErrorCode::OK,
2683 GenerateKey(
2684 AuthorizationSetBuilder()
2685 .RsaSigningKey(2048, 65537)
2686 .Authorization(TAG_NO_AUTH_REQUIRED)
2687 .Digest(Digest::SHA_2_256 /* supported digest */)
2688 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2689 .SetDefaultValidity()));
2690 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2691 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2692 .Digest(Digest::SHA_2_256)
2693 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002694}
2695
2696/*
2697 * SigningOperationsTest.RsaPssNoDigest
2698 *
2699 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2700 */
2701TEST_P(SigningOperationsTest, RsaNoDigest) {
2702 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2703 .RsaSigningKey(2048, 65537)
2704 .Authorization(TAG_NO_AUTH_REQUIRED)
2705 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002706 .Padding(PaddingMode::RSA_PSS)
2707 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002708 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2709 Begin(KeyPurpose::SIGN,
2710 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2711
2712 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2713 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2714}
2715
2716/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002717 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002718 *
2719 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2720 * supported in some cases (as validated in other tests), but a mode must be specified.
2721 */
2722TEST_P(SigningOperationsTest, RsaNoPadding) {
2723 // Padding must be specified
2724 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2725 .RsaKey(2048, 65537)
2726 .Authorization(TAG_NO_AUTH_REQUIRED)
2727 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002728 .Digest(Digest::NONE)
2729 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002730 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2731 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2732}
2733
2734/*
2735 * SigningOperationsTest.RsaShortMessage
2736 *
2737 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2738 */
2739TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2740 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2741 .Authorization(TAG_NO_AUTH_REQUIRED)
2742 .RsaSigningKey(2048, 65537)
2743 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002744 .Padding(PaddingMode::NONE)
2745 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002746
2747 // Barely shorter
2748 string message(2048 / 8 - 1, 'a');
2749 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2750
2751 // Much shorter
2752 message = "a";
2753 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2754}
2755
2756/*
2757 * SigningOperationsTest.RsaSignWithEncryptionKey
2758 *
2759 * Verifies that RSA encryption keys cannot be used to sign.
2760 */
2761TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2762 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2763 .Authorization(TAG_NO_AUTH_REQUIRED)
2764 .RsaEncryptionKey(2048, 65537)
2765 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002766 .Padding(PaddingMode::NONE)
2767 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002768 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2769 Begin(KeyPurpose::SIGN,
2770 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2771}
2772
2773/*
2774 * SigningOperationsTest.RsaSignTooLargeMessage
2775 *
2776 * Verifies that attempting a raw signature of a message which is the same length as the key,
2777 * but numerically larger than the public modulus, fails with the correct error.
2778 */
2779TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2780 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2781 .Authorization(TAG_NO_AUTH_REQUIRED)
2782 .RsaSigningKey(2048, 65537)
2783 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002784 .Padding(PaddingMode::NONE)
2785 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002786
2787 // Largest possible message will always be larger than the public modulus.
2788 string message(2048 / 8, static_cast<char>(0xff));
2789 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2790 .Authorization(TAG_NO_AUTH_REQUIRED)
2791 .Digest(Digest::NONE)
2792 .Padding(PaddingMode::NONE)));
2793 string signature;
2794 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2795}
2796
2797/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002798 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2799 *
2800 * Verifies ECDSA signature/verification for all digests and curves.
2801 */
2802TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2803 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2804
2805 string message = "1234567890";
2806 string corrupt_message = "2234567890";
2807 for (auto curve : ValidCurves()) {
2808 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2809 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2810 .Authorization(TAG_NO_AUTH_REQUIRED)
2811 .EcdsaSigningKey(curve)
2812 .Digest(digests)
2813 .SetDefaultValidity());
2814 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2815 if (error != ErrorCode::OK) {
2816 continue;
2817 }
2818
2819 for (auto digest : digests) {
2820 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2821 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2822 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2823 }
2824
2825 auto rc = DeleteKey();
2826 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2827 }
2828}
2829
2830/*
Selene Huang31ab4042020-04-29 04:22:39 -07002831 * SigningOperationsTest.EcdsaAllCurves
2832 *
2833 * Verifies that ECDSA operations succeed with all possible curves.
2834 */
2835TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2836 for (auto curve : ValidCurves()) {
2837 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2838 .Authorization(TAG_NO_AUTH_REQUIRED)
2839 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002840 .Digest(Digest::SHA_2_256)
2841 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002842 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2843 if (error != ErrorCode::OK) continue;
2844
2845 string message(1024, 'a');
2846 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2847 CheckedDeleteKey();
2848 }
2849}
2850
2851/*
2852 * SigningOperationsTest.EcdsaNoDigestHugeData
2853 *
2854 * Verifies that ECDSA operations support very large messages, even without digesting. This
2855 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2856 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2857 * the framework.
2858 */
2859TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2860 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2861 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002862 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002863 .Digest(Digest::NONE)
2864 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002865 string message(1 * 1024, 'a');
2866 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2867}
2868
2869/*
2870 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2871 *
2872 * Verifies that using an EC key requires the correct app ID/data.
2873 */
2874TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2875 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2876 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002877 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002878 .Digest(Digest::NONE)
2879 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002880 .Authorization(TAG_APPLICATION_DATA, "appdata")
2881 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002882
2883 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2884
Selene Huang31ab4042020-04-29 04:22:39 -07002885 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2886 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2887 AbortIfNeeded();
2888 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2889 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2890 .Digest(Digest::NONE)
2891 .Authorization(TAG_APPLICATION_ID, "clientid")));
2892 AbortIfNeeded();
2893 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2894 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2895 .Digest(Digest::NONE)
2896 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2897 AbortIfNeeded();
2898 EXPECT_EQ(ErrorCode::OK,
2899 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2900 .Digest(Digest::NONE)
2901 .Authorization(TAG_APPLICATION_DATA, "appdata")
2902 .Authorization(TAG_APPLICATION_ID, "clientid")));
2903 AbortIfNeeded();
2904}
2905
2906/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002907 * SigningOperationsTest.EcdsaIncompatibleDigest
2908 *
2909 * Verifies that using an EC key requires compatible digest.
2910 */
2911TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2912 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2913 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002914 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002915 .Digest(Digest::NONE)
2916 .Digest(Digest::SHA1)
2917 .SetDefaultValidity()));
2918 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2919 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2920 AbortIfNeeded();
2921}
2922
2923/*
Selene Huang31ab4042020-04-29 04:22:39 -07002924 * SigningOperationsTest.AesEcbSign
2925 *
2926 * Verifies that attempts to use AES keys to sign fail in the correct way.
2927 */
2928TEST_P(SigningOperationsTest, AesEcbSign) {
2929 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2930 .Authorization(TAG_NO_AUTH_REQUIRED)
2931 .SigningKey()
2932 .AesEncryptionKey(128)
2933 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2934
2935 AuthorizationSet out_params;
2936 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2937 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2938 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2939 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2940}
2941
2942/*
2943 * SigningOperationsTest.HmacAllDigests
2944 *
2945 * Verifies that HMAC works with all digests.
2946 */
2947TEST_P(SigningOperationsTest, HmacAllDigests) {
2948 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2949 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2950 .Authorization(TAG_NO_AUTH_REQUIRED)
2951 .HmacKey(128)
2952 .Digest(digest)
2953 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2954 << "Failed to create HMAC key with digest " << digest;
2955 string message = "12345678901234567890123456789012";
2956 string signature = MacMessage(message, digest, 160);
2957 EXPECT_EQ(160U / 8U, signature.size())
2958 << "Failed to sign with HMAC key with digest " << digest;
2959 CheckedDeleteKey();
2960 }
2961}
2962
2963/*
2964 * SigningOperationsTest.HmacSha256TooLargeMacLength
2965 *
2966 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2967 * digest size.
2968 */
2969TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2970 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2971 .Authorization(TAG_NO_AUTH_REQUIRED)
2972 .HmacKey(128)
2973 .Digest(Digest::SHA_2_256)
2974 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2975 AuthorizationSet output_params;
2976 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2977 AuthorizationSetBuilder()
2978 .Digest(Digest::SHA_2_256)
2979 .Authorization(TAG_MAC_LENGTH, 264),
2980 &output_params));
2981}
2982
2983/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002984 * SigningOperationsTest.HmacSha256InvalidMacLength
2985 *
2986 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2987 * not a multiple of 8.
2988 */
2989TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2990 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2991 .Authorization(TAG_NO_AUTH_REQUIRED)
2992 .HmacKey(128)
2993 .Digest(Digest::SHA_2_256)
2994 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2995 AuthorizationSet output_params;
2996 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2997 AuthorizationSetBuilder()
2998 .Digest(Digest::SHA_2_256)
2999 .Authorization(TAG_MAC_LENGTH, 161),
3000 &output_params));
3001}
3002
3003/*
Selene Huang31ab4042020-04-29 04:22:39 -07003004 * SigningOperationsTest.HmacSha256TooSmallMacLength
3005 *
3006 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3007 * specified minimum MAC length.
3008 */
3009TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3010 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3011 .Authorization(TAG_NO_AUTH_REQUIRED)
3012 .HmacKey(128)
3013 .Digest(Digest::SHA_2_256)
3014 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3015 AuthorizationSet output_params;
3016 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3017 AuthorizationSetBuilder()
3018 .Digest(Digest::SHA_2_256)
3019 .Authorization(TAG_MAC_LENGTH, 120),
3020 &output_params));
3021}
3022
3023/*
3024 * SigningOperationsTest.HmacRfc4231TestCase3
3025 *
3026 * Validates against the test vectors from RFC 4231 test case 3.
3027 */
3028TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3029 string key(20, 0xaa);
3030 string message(50, 0xdd);
3031 uint8_t sha_224_expected[] = {
3032 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3033 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3034 };
3035 uint8_t sha_256_expected[] = {
3036 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3037 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3038 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3039 };
3040 uint8_t sha_384_expected[] = {
3041 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3042 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3043 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3044 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3045 };
3046 uint8_t sha_512_expected[] = {
3047 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3048 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3049 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3050 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3051 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3052 };
3053
3054 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3055 if (SecLevel() != SecurityLevel::STRONGBOX) {
3056 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3057 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3058 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3059 }
3060}
3061
3062/*
3063 * SigningOperationsTest.HmacRfc4231TestCase5
3064 *
3065 * Validates against the test vectors from RFC 4231 test case 5.
3066 */
3067TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3068 string key(20, 0x0c);
3069 string message = "Test With Truncation";
3070
3071 uint8_t sha_224_expected[] = {
3072 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3073 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3074 };
3075 uint8_t sha_256_expected[] = {
3076 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3077 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3078 };
3079 uint8_t sha_384_expected[] = {
3080 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3081 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3082 };
3083 uint8_t sha_512_expected[] = {
3084 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3085 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3086 };
3087
3088 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3089 if (SecLevel() != SecurityLevel::STRONGBOX) {
3090 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3091 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3092 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3093 }
3094}
3095
3096INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3097
3098typedef KeyMintAidlTestBase VerificationOperationsTest;
3099
3100/*
Selene Huang31ab4042020-04-29 04:22:39 -07003101 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3102 *
3103 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3104 */
3105TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3106 string key_material = "HelloThisIsAKey";
3107
3108 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003109 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003110 EXPECT_EQ(ErrorCode::OK,
3111 ImportKey(AuthorizationSetBuilder()
3112 .Authorization(TAG_NO_AUTH_REQUIRED)
3113 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3114 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3115 .Digest(Digest::SHA_2_256)
3116 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3117 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3118 EXPECT_EQ(ErrorCode::OK,
3119 ImportKey(AuthorizationSetBuilder()
3120 .Authorization(TAG_NO_AUTH_REQUIRED)
3121 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3122 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3123 .Digest(Digest::SHA_2_256)
3124 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3125 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3126
3127 string message = "This is a message.";
3128 string signature = SignMessage(
3129 signing_key, message,
3130 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3131
3132 // Signing key should not work.
3133 AuthorizationSet out_params;
3134 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3135 Begin(KeyPurpose::VERIFY, signing_key,
3136 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3137
3138 // Verification key should work.
3139 VerifyMessage(verification_key, message, signature,
3140 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3141
3142 CheckedDeleteKey(&signing_key);
3143 CheckedDeleteKey(&verification_key);
3144}
3145
3146INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3147
3148typedef KeyMintAidlTestBase ExportKeyTest;
3149
3150/*
3151 * ExportKeyTest.RsaUnsupportedKeyFormat
3152 *
3153 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3154 */
3155// TODO(seleneh) add ExportKey to GenerateKey
3156// check result
3157
3158class ImportKeyTest : public KeyMintAidlTestBase {
3159 public:
3160 template <TagType tag_type, Tag tag, typename ValueT>
3161 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3162 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003163 for (auto& entry : key_characteristics_) {
3164 if (entry.securityLevel == SecLevel()) {
3165 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3166 << "Tag " << tag << " with value " << expected
3167 << " not found at security level" << entry.securityLevel;
3168 } else {
3169 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3170 << "Tag " << tag << " found at security level " << entry.securityLevel;
3171 }
Selene Huang31ab4042020-04-29 04:22:39 -07003172 }
3173 }
3174
3175 void CheckOrigin() {
3176 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003177 // Origin isn't a crypto param, but it always lives with them.
3178 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003179 }
3180};
3181
3182/*
3183 * ImportKeyTest.RsaSuccess
3184 *
3185 * Verifies that importing and using an RSA key pair works correctly.
3186 */
3187TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003188 uint32_t key_size;
3189 string key;
3190
3191 if (SecLevel() == SecurityLevel::STRONGBOX) {
3192 key_size = 2048;
3193 key = rsa_2048_key;
3194 } else {
3195 key_size = 1024;
3196 key = rsa_key;
3197 }
3198
Selene Huang31ab4042020-04-29 04:22:39 -07003199 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3200 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003201 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003202 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003203 .Padding(PaddingMode::RSA_PSS)
3204 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003205 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003206
3207 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003208 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003209 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3210 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3211 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3212 CheckOrigin();
3213
3214 string message(1024 / 8, 'a');
3215 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3216 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003217 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003218}
3219
3220/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003221 * ImportKeyTest.RsaSuccessWithoutParams
3222 *
3223 * Verifies that importing and using an RSA key pair without specifying parameters
3224 * works correctly.
3225 */
3226TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3227 uint32_t key_size;
3228 string key;
3229
3230 if (SecLevel() == SecurityLevel::STRONGBOX) {
3231 key_size = 2048;
3232 key = rsa_2048_key;
3233 } else {
3234 key_size = 1024;
3235 key = rsa_key;
3236 }
3237
3238 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3239 .Authorization(TAG_NO_AUTH_REQUIRED)
3240 .SigningKey()
3241 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3242 .Digest(Digest::SHA_2_256)
3243 .Padding(PaddingMode::RSA_PSS)
3244 .SetDefaultValidity(),
3245 KeyFormat::PKCS8, key));
3246
3247 // Key size and public exponent are determined from the imported key material.
3248 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3249 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3250
3251 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3252 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3253 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3254 CheckOrigin();
3255
3256 string message(1024 / 8, 'a');
3257 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3258 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003259 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003260}
3261
3262/*
Selene Huang31ab4042020-04-29 04:22:39 -07003263 * ImportKeyTest.RsaKeySizeMismatch
3264 *
3265 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3266 * correct way.
3267 */
3268TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3269 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3270 ImportKey(AuthorizationSetBuilder()
3271 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3272 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003273 .Padding(PaddingMode::NONE)
3274 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003275 KeyFormat::PKCS8, rsa_key));
3276}
3277
3278/*
3279 * ImportKeyTest.RsaPublicExponentMismatch
3280 *
3281 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3282 * fails in the correct way.
3283 */
3284TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3285 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3286 ImportKey(AuthorizationSetBuilder()
3287 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3288 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003289 .Padding(PaddingMode::NONE)
3290 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003291 KeyFormat::PKCS8, rsa_key));
3292}
3293
3294/*
3295 * ImportKeyTest.EcdsaSuccess
3296 *
3297 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3298 */
3299TEST_P(ImportKeyTest, EcdsaSuccess) {
3300 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3301 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003302 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003303 .Digest(Digest::SHA_2_256)
3304 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003305 KeyFormat::PKCS8, ec_256_key));
3306
3307 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003308 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3309 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3310
3311 CheckOrigin();
3312
3313 string message(32, 'a');
3314 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3315 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003316 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003317}
3318
3319/*
3320 * ImportKeyTest.EcdsaP256RFC5915Success
3321 *
3322 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3323 * correctly.
3324 */
3325TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3326 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3327 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003328 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003329 .Digest(Digest::SHA_2_256)
3330 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003331 KeyFormat::PKCS8, ec_256_key_rfc5915));
3332
3333 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003334 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3335 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3336
3337 CheckOrigin();
3338
3339 string message(32, 'a');
3340 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3341 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003342 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003343}
3344
3345/*
3346 * ImportKeyTest.EcdsaP256SEC1Success
3347 *
3348 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3349 */
3350TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3351 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3352 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003353 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003354 .Digest(Digest::SHA_2_256)
3355 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003356 KeyFormat::PKCS8, ec_256_key_sec1));
3357
3358 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003359 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3360 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3361
3362 CheckOrigin();
3363
3364 string message(32, 'a');
3365 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3366 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003367 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003368}
3369
3370/*
3371 * ImportKeyTest.Ecdsa521Success
3372 *
3373 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3374 */
3375TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01003376 if (SecLevel() == SecurityLevel::STRONGBOX) {
3377 GTEST_SKIP() << "Test not applicable to StrongBox device";
3378 }
Selene Huang31ab4042020-04-29 04:22:39 -07003379 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3380 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003381 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003382 .Digest(Digest::SHA_2_256)
3383 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003384 KeyFormat::PKCS8, ec_521_key));
3385
3386 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003387 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3388 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3389 CheckOrigin();
3390
3391 string message(32, 'a');
3392 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3393 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003394 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003395}
3396
3397/*
Selene Huang31ab4042020-04-29 04:22:39 -07003398 * ImportKeyTest.EcdsaCurveMismatch
3399 *
3400 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3401 * the correct way.
3402 */
3403TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3404 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3405 ImportKey(AuthorizationSetBuilder()
3406 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003407 .Digest(Digest::NONE)
3408 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003409 KeyFormat::PKCS8, ec_256_key));
3410}
3411
3412/*
3413 * ImportKeyTest.AesSuccess
3414 *
3415 * Verifies that importing and using an AES key works.
3416 */
3417TEST_P(ImportKeyTest, AesSuccess) {
3418 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3419 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3420 .Authorization(TAG_NO_AUTH_REQUIRED)
3421 .AesEncryptionKey(key.size() * 8)
3422 .EcbMode()
3423 .Padding(PaddingMode::PKCS7),
3424 KeyFormat::RAW, key));
3425
3426 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3427 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3428 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3429 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3430 CheckOrigin();
3431
3432 string message = "Hello World!";
3433 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3434 string ciphertext = EncryptMessage(message, params);
3435 string plaintext = DecryptMessage(ciphertext, params);
3436 EXPECT_EQ(message, plaintext);
3437}
3438
3439/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003440 * ImportKeyTest.AesFailure
3441 *
3442 * Verifies that importing an invalid AES key fails.
3443 */
3444TEST_P(ImportKeyTest, AesFailure) {
3445 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3446 uint32_t bitlen = key.size() * 8;
3447 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003448 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003449 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003450 .Authorization(TAG_NO_AUTH_REQUIRED)
3451 .AesEncryptionKey(key_size)
3452 .EcbMode()
3453 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003454 KeyFormat::RAW, key);
3455 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003456 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3457 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003458 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003459
3460 // Explicit key size matches that of the provided key, but it's not a valid size.
3461 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3462 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3463 ImportKey(AuthorizationSetBuilder()
3464 .Authorization(TAG_NO_AUTH_REQUIRED)
3465 .AesEncryptionKey(long_key.size() * 8)
3466 .EcbMode()
3467 .Padding(PaddingMode::PKCS7),
3468 KeyFormat::RAW, long_key));
3469 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3470 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3471 ImportKey(AuthorizationSetBuilder()
3472 .Authorization(TAG_NO_AUTH_REQUIRED)
3473 .AesEncryptionKey(short_key.size() * 8)
3474 .EcbMode()
3475 .Padding(PaddingMode::PKCS7),
3476 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003477}
3478
3479/*
3480 * ImportKeyTest.TripleDesSuccess
3481 *
3482 * Verifies that importing and using a 3DES key works.
3483 */
3484TEST_P(ImportKeyTest, TripleDesSuccess) {
3485 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3486 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3487 .Authorization(TAG_NO_AUTH_REQUIRED)
3488 .TripleDesEncryptionKey(168)
3489 .EcbMode()
3490 .Padding(PaddingMode::PKCS7),
3491 KeyFormat::RAW, key));
3492
3493 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3494 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3495 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3496 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3497 CheckOrigin();
3498
3499 string message = "Hello World!";
3500 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3501 string ciphertext = EncryptMessage(message, params);
3502 string plaintext = DecryptMessage(ciphertext, params);
3503 EXPECT_EQ(message, plaintext);
3504}
3505
3506/*
3507 * ImportKeyTest.TripleDesFailure
3508 *
3509 * Verifies that importing an invalid 3DES key fails.
3510 */
3511TEST_P(ImportKeyTest, TripleDesFailure) {
3512 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003513 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003514 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003515 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003516 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003517 .Authorization(TAG_NO_AUTH_REQUIRED)
3518 .TripleDesEncryptionKey(key_size)
3519 .EcbMode()
3520 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003521 KeyFormat::RAW, key);
3522 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003523 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3524 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003525 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003526 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003527 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003528 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3529 ImportKey(AuthorizationSetBuilder()
3530 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003531 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003532 .EcbMode()
3533 .Padding(PaddingMode::PKCS7),
3534 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003535 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003536 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3537 ImportKey(AuthorizationSetBuilder()
3538 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003539 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003540 .EcbMode()
3541 .Padding(PaddingMode::PKCS7),
3542 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003543}
3544
3545/*
3546 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003547 *
3548 * Verifies that importing and using an HMAC key works.
3549 */
3550TEST_P(ImportKeyTest, HmacKeySuccess) {
3551 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3552 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3553 .Authorization(TAG_NO_AUTH_REQUIRED)
3554 .HmacKey(key.size() * 8)
3555 .Digest(Digest::SHA_2_256)
3556 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3557 KeyFormat::RAW, key));
3558
3559 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3560 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3561 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3562 CheckOrigin();
3563
3564 string message = "Hello World!";
3565 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3566 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3567}
3568
3569INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3570
3571auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003572 // IKeyMintDevice.aidl
3573 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3574 "020100" // INTEGER length 1 value 0x00 (version)
3575 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3576 "934bf94e2aa28a3f83c9f79297250262"
3577 "fbe3276b5a1c91159bbfa3ef8957aac8"
3578 "4b59b30b455a79c2973480823d8b3863"
3579 "c3deef4a8e243590268d80e18751a0e1"
3580 "30f67ce6a1ace9f79b95e097474febc9"
3581 "81195b1d13a69086c0863f66a7b7fdb4"
3582 "8792227b1ac5e2489febdf087ab54864"
3583 "83033a6f001ca5d1ec1e27f5c30f4cec"
3584 "2642074a39ae68aee552e196627a8e3d"
3585 "867e67a8c01b11e75f13cca0a97ab668"
3586 "b50cda07a8ecb7cd8e3dd7009c963653"
3587 "4f6f239cffe1fc8daa466f78b676c711"
3588 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3589 "99b801597d5220e307eaa5bee507fb94"
3590 "d1fa69f9e519b2de315bac92c36f2ea1"
3591 "fa1df4478c0ddedeae8c70e0233cd098"
3592 "040c" // OCTET STRING length 0x0c (initializationVector)
3593 "d796b02c370f1fa4cc0124f1"
3594 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3595 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3596 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3597 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3598 "3106" // SET length 0x06
3599 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3600 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3601 // } end SET
3602 // } end [1]
3603 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3604 "020120" // INTEGER length 1 value 0x20 (AES)
3605 // } end [2]
3606 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3607 "02020100" // INTEGER length 2 value 0x100
3608 // } end [3]
3609 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3610 "3103" // SET length 0x03 {
3611 "020101" // INTEGER length 1 value 0x01 (ECB)
3612 // } end SET
3613 // } end [4]
3614 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3615 "3103" // SET length 0x03 {
3616 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3617 // } end SET
3618 // } end [5]
3619 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3620 // (noAuthRequired)
3621 "0500" // NULL
3622 // } end [503]
3623 // } end SEQUENCE (AuthorizationList)
3624 // } end SEQUENCE (KeyDescription)
3625 "0420" // OCTET STRING length 0x20 (encryptedKey)
3626 "ccd540855f833a5e1480bfd2d36faf3a"
3627 "eee15df5beabe2691bc82dde2a7aa910"
3628 "0410" // OCTET STRING length 0x10 (tag)
3629 "64c9f689c60ff6223ab6e6999e0eb6e5"
3630 // } SEQUENCE (SecureKeyWrapper)
3631);
Selene Huang31ab4042020-04-29 04:22:39 -07003632
3633auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003634 // IKeyMintDevice.aidl
3635 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3636 "020100" // INTEGER length 1 value 0x00 (version)
3637 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3638 "aad93ed5924f283b4bb5526fbe7a1412"
3639 "f9d9749ec30db9062b29e574a8546f33"
3640 "c88732452f5b8e6a391ee76c39ed1712"
3641 "c61d8df6213dec1cffbc17a8c6d04c7b"
3642 "30893d8daa9b2015213e219468215532"
3643 "07f8f9931c4caba23ed3bee28b36947e"
3644 "47f10e0a5c3dc51c988a628daad3e5e1"
3645 "f4005e79c2d5a96c284b4b8d7e4948f3"
3646 "31e5b85dd5a236f85579f3ea1d1b8484"
3647 "87470bdb0ab4f81a12bee42c99fe0df4"
3648 "bee3759453e69ad1d68a809ce06b949f"
3649 "7694a990429b2fe81e066ff43e56a216"
3650 "02db70757922a4bcc23ab89f1e35da77"
3651 "586775f423e519c2ea394caf48a28d0c"
3652 "8020f1dcf6b3a68ec246f615ae96dae9"
3653 "a079b1f6eb959033c1af5c125fd94168"
3654 "040c" // OCTET STRING length 0x0c (initializationVector)
3655 "6d9721d08589581ab49204a3"
3656 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3657 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3658 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3659 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3660 "3106" // SET length 0x06
3661 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3662 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3663 // } end SET
3664 // } end [1]
3665 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3666 "020120" // INTEGER length 1 value 0x20 (AES)
3667 // } end [2]
3668 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3669 "02020100" // INTEGER length 2 value 0x100
3670 // } end [3]
3671 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3672 "3103" // SET length 0x03 {
3673 "020101" // INTEGER length 1 value 0x01 (ECB)
3674 // } end SET
3675 // } end [4]
3676 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3677 "3103" // SET length 0x03 {
3678 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3679 // } end SET
3680 // } end [5]
3681 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3682 // (noAuthRequired)
3683 "0500" // NULL
3684 // } end [503]
3685 // } end SEQUENCE (AuthorizationList)
3686 // } end SEQUENCE (KeyDescription)
3687 "0420" // OCTET STRING length 0x20 (encryptedKey)
3688 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3689 "c20d1f99a9a024a76f35c8e2cab9b68d"
3690 "0410" // OCTET STRING length 0x10 (tag)
3691 "2560c70109ae67c030f00b98b512a670"
3692 // } SEQUENCE (SecureKeyWrapper)
3693);
Selene Huang31ab4042020-04-29 04:22:39 -07003694
3695auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003696 // RFC 5208 s5
3697 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3698 "020100" // INTEGER length 1 value 0x00 (version)
3699 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3700 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3701 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3702 "0500" // NULL (parameters)
3703 // } SEQUENCE (AlgorithmIdentifier)
3704 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3705 // RFC 8017 A.1.2
3706 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3707 "020100" // INTEGER length 1 value 0x00 (version)
3708 "02820101" // INTEGER length 0x0101 (modulus) value...
3709 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3710 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3711 "7b06e673a837313d56b1c725150a3fef" // 0x30
3712 "86acbddc41bb759c2854eae32d35841e" // 0x40
3713 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3714 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3715 "312d7bd5921ffaea1347c157406fef71" // 0x70
3716 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3717 "f4645c11f5c1374c3886427411c44979" // 0x90
3718 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3719 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3720 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3721 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3722 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3723 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3724 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3725 "55" // 0x101
3726 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3727 "02820100" // INTEGER length 0x100 (privateExponent) value...
3728 "431447b6251908112b1ee76f99f3711a" // 0x10
3729 "52b6630960046c2de70de188d833f8b8" // 0x20
3730 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3731 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3732 "e710b630a03adc683b5d2c43080e52be" // 0x50
3733 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3734 "822bccff087d63c940ba8a45f670feb2" // 0x70
3735 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3736 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3737 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3738 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3739 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3740 "52659d5a5ba05b663737a8696281865b" // 0xd0
3741 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3742 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3743 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3744 "028181" // INTEGER length 0x81 (prime1) value...
3745 "00de392e18d682c829266cc3454e1d61" // 0x10
3746 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3747 "ff841be5bac82a164c5970007047b8c5" // 0x30
3748 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3749 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3750 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3751 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3752 "9e91346130748a6e3c124f9149d71c74" // 0x80
3753 "35"
3754 "028181" // INTEGER length 0x81 (prime2) value...
3755 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3756 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3757 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3758 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3759 "9ed39a2d934c880440aed8832f984316" // 0x50
3760 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3761 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3762 "b880677c068e1be936e81288815252a8" // 0x80
3763 "a1"
3764 "028180" // INTEGER length 0x80 (exponent1) value...
3765 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3766 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3767 "5a063212a4f105a3764743e53281988a" // 0x30
3768 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3769 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3770 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3771 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3772 "4719d6e2b9439823719cd08bcd031781" // 0x80
3773 "028181" // INTEGER length 0x81 (exponent2) value...
3774 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3775 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3776 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3777 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3778 "1254186af30b22c10582a8a43e34fe94" // 0x50
3779 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3780 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3781 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3782 "61"
3783 "028181" // INTEGER length 0x81 (coefficient) value...
3784 "00c931617c77829dfb1270502be9195c" // 0x10
3785 "8f2830885f57dba869536811e6864236" // 0x20
3786 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3787 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3788 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3789 "959356210723287b0affcc9f727044d4" // 0x60
3790 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3791 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3792 "22"
3793 // } SEQUENCE
3794 // } SEQUENCE ()
3795);
Selene Huang31ab4042020-04-29 04:22:39 -07003796
3797string zero_masking_key =
3798 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3799string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3800
3801class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3802
3803TEST_P(ImportWrappedKeyTest, Success) {
3804 auto wrapping_key_desc = AuthorizationSetBuilder()
3805 .RsaEncryptionKey(2048, 65537)
3806 .Digest(Digest::SHA_2_256)
3807 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003808 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3809 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003810
3811 ASSERT_EQ(ErrorCode::OK,
3812 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3813 AuthorizationSetBuilder()
3814 .Digest(Digest::SHA_2_256)
3815 .Padding(PaddingMode::RSA_OAEP)));
3816
3817 string message = "Hello World!";
3818 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3819 string ciphertext = EncryptMessage(message, params);
3820 string plaintext = DecryptMessage(ciphertext, params);
3821 EXPECT_EQ(message, plaintext);
3822}
3823
David Drysdaled2cc8c22021-04-15 13:29:45 +01003824/*
3825 * ImportWrappedKeyTest.SuccessSidsIgnored
3826 *
3827 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3828 * include Tag:USER_SECURE_ID.
3829 */
3830TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3831 auto wrapping_key_desc = AuthorizationSetBuilder()
3832 .RsaEncryptionKey(2048, 65537)
3833 .Digest(Digest::SHA_2_256)
3834 .Padding(PaddingMode::RSA_OAEP)
3835 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3836 .SetDefaultValidity();
3837
3838 int64_t password_sid = 42;
3839 int64_t biometric_sid = 24;
3840 ASSERT_EQ(ErrorCode::OK,
3841 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3842 AuthorizationSetBuilder()
3843 .Digest(Digest::SHA_2_256)
3844 .Padding(PaddingMode::RSA_OAEP),
3845 password_sid, biometric_sid));
3846
3847 string message = "Hello World!";
3848 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3849 string ciphertext = EncryptMessage(message, params);
3850 string plaintext = DecryptMessage(ciphertext, params);
3851 EXPECT_EQ(message, plaintext);
3852}
3853
Selene Huang31ab4042020-04-29 04:22:39 -07003854TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3855 auto wrapping_key_desc = AuthorizationSetBuilder()
3856 .RsaEncryptionKey(2048, 65537)
3857 .Digest(Digest::SHA_2_256)
3858 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003859 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3860 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003861
3862 ASSERT_EQ(ErrorCode::OK,
3863 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3864 AuthorizationSetBuilder()
3865 .Digest(Digest::SHA_2_256)
3866 .Padding(PaddingMode::RSA_OAEP)));
3867}
3868
3869TEST_P(ImportWrappedKeyTest, WrongMask) {
3870 auto wrapping_key_desc = AuthorizationSetBuilder()
3871 .RsaEncryptionKey(2048, 65537)
3872 .Digest(Digest::SHA_2_256)
3873 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003874 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3875 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003876
3877 ASSERT_EQ(
3878 ErrorCode::VERIFICATION_FAILED,
3879 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3880 AuthorizationSetBuilder()
3881 .Digest(Digest::SHA_2_256)
3882 .Padding(PaddingMode::RSA_OAEP)));
3883}
3884
3885TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3886 auto wrapping_key_desc = AuthorizationSetBuilder()
3887 .RsaEncryptionKey(2048, 65537)
3888 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003889 .Padding(PaddingMode::RSA_OAEP)
3890 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003891
3892 ASSERT_EQ(
3893 ErrorCode::INCOMPATIBLE_PURPOSE,
3894 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3895 AuthorizationSetBuilder()
3896 .Digest(Digest::SHA_2_256)
3897 .Padding(PaddingMode::RSA_OAEP)));
3898}
3899
David Drysdaled2cc8c22021-04-15 13:29:45 +01003900TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3901 auto wrapping_key_desc = AuthorizationSetBuilder()
3902 .RsaEncryptionKey(2048, 65537)
3903 .Digest(Digest::SHA_2_256)
3904 .Padding(PaddingMode::RSA_PSS)
3905 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3906 .SetDefaultValidity();
3907
3908 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3909 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3910 AuthorizationSetBuilder()
3911 .Digest(Digest::SHA_2_256)
3912 .Padding(PaddingMode::RSA_OAEP)));
3913}
3914
3915TEST_P(ImportWrappedKeyTest, WrongDigest) {
3916 auto wrapping_key_desc = AuthorizationSetBuilder()
3917 .RsaEncryptionKey(2048, 65537)
3918 .Digest(Digest::SHA_2_512)
3919 .Padding(PaddingMode::RSA_OAEP)
3920 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3921 .SetDefaultValidity();
3922
3923 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3924 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3925 AuthorizationSetBuilder()
3926 .Digest(Digest::SHA_2_256)
3927 .Padding(PaddingMode::RSA_OAEP)));
3928}
3929
Selene Huang31ab4042020-04-29 04:22:39 -07003930INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3931
3932typedef KeyMintAidlTestBase EncryptionOperationsTest;
3933
3934/*
3935 * EncryptionOperationsTest.RsaNoPaddingSuccess
3936 *
David Drysdale59cae642021-05-12 13:52:03 +01003937 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003938 */
3939TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003940 for (uint64_t exponent : {3, 65537}) {
3941 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3942 .Authorization(TAG_NO_AUTH_REQUIRED)
3943 .RsaEncryptionKey(2048, exponent)
3944 .Padding(PaddingMode::NONE)
3945 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003946
David Drysdaled2cc8c22021-04-15 13:29:45 +01003947 string message = string(2048 / 8, 'a');
3948 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003949 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003950 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003951
David Drysdale59cae642021-05-12 13:52:03 +01003952 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003953 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003954
David Drysdaled2cc8c22021-04-15 13:29:45 +01003955 // Unpadded RSA is deterministic
3956 EXPECT_EQ(ciphertext1, ciphertext2);
3957
3958 CheckedDeleteKey();
3959 }
Selene Huang31ab4042020-04-29 04:22:39 -07003960}
3961
3962/*
3963 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3964 *
David Drysdale59cae642021-05-12 13:52:03 +01003965 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003966 */
3967TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3968 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3969 .Authorization(TAG_NO_AUTH_REQUIRED)
3970 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003971 .Padding(PaddingMode::NONE)
3972 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003973
3974 string message = "1";
3975 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3976
David Drysdale59cae642021-05-12 13:52:03 +01003977 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003978 EXPECT_EQ(2048U / 8, ciphertext.size());
3979
3980 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3981 string plaintext = DecryptMessage(ciphertext, params);
3982
3983 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003984}
3985
3986/*
Selene Huang31ab4042020-04-29 04:22:39 -07003987 * EncryptionOperationsTest.RsaOaepSuccess
3988 *
David Drysdale59cae642021-05-12 13:52:03 +01003989 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003990 */
3991TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3992 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3993
3994 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01003995 ASSERT_EQ(ErrorCode::OK,
3996 GenerateKey(AuthorizationSetBuilder()
3997 .Authorization(TAG_NO_AUTH_REQUIRED)
3998 .RsaEncryptionKey(key_size, 65537)
3999 .Padding(PaddingMode::RSA_OAEP)
4000 .Digest(digests)
4001 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4002 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004003
4004 string message = "Hello";
4005
4006 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004007 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4008
4009 auto params = AuthorizationSetBuilder()
4010 .Digest(digest)
4011 .Padding(PaddingMode::RSA_OAEP)
4012 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4013 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004014 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4015 EXPECT_EQ(key_size / 8, ciphertext1.size());
4016
David Drysdale59cae642021-05-12 13:52:03 +01004017 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004018 EXPECT_EQ(key_size / 8, ciphertext2.size());
4019
4020 // OAEP randomizes padding so every result should be different (with astronomically high
4021 // probability).
4022 EXPECT_NE(ciphertext1, ciphertext2);
4023
4024 string plaintext1 = DecryptMessage(ciphertext1, params);
4025 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4026 string plaintext2 = DecryptMessage(ciphertext2, params);
4027 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4028
4029 // Decrypting corrupted ciphertext should fail.
4030 size_t offset_to_corrupt = random() % ciphertext1.size();
4031 char corrupt_byte;
4032 do {
4033 corrupt_byte = static_cast<char>(random() % 256);
4034 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4035 ciphertext1[offset_to_corrupt] = corrupt_byte;
4036
4037 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4038 string result;
4039 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4040 EXPECT_EQ(0U, result.size());
4041 }
4042}
4043
4044/*
4045 * EncryptionOperationsTest.RsaOaepInvalidDigest
4046 *
David Drysdale59cae642021-05-12 13:52:03 +01004047 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004048 * without a digest.
4049 */
4050TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4051 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4052 .Authorization(TAG_NO_AUTH_REQUIRED)
4053 .RsaEncryptionKey(2048, 65537)
4054 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004055 .Digest(Digest::NONE)
4056 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004057
4058 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004059 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07004060}
4061
4062/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004063 * EncryptionOperationsTest.RsaOaepInvalidPadding
4064 *
David Drysdale59cae642021-05-12 13:52:03 +01004065 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01004066 * with a padding value that is only suitable for signing/verifying.
4067 */
4068TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
4069 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4070 .Authorization(TAG_NO_AUTH_REQUIRED)
4071 .RsaEncryptionKey(2048, 65537)
4072 .Padding(PaddingMode::RSA_PSS)
4073 .Digest(Digest::NONE)
4074 .SetDefaultValidity()));
4075
4076 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004077 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01004078}
4079
4080/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004081 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07004082 *
David Drysdale59cae642021-05-12 13:52:03 +01004083 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004084 * with a different digest than was used to encrypt.
4085 */
4086TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01004087 if (SecLevel() == SecurityLevel::STRONGBOX) {
4088 GTEST_SKIP() << "Test not applicable to StrongBox device";
4089 }
Selene Huang31ab4042020-04-29 04:22:39 -07004090
4091 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4092 .Authorization(TAG_NO_AUTH_REQUIRED)
4093 .RsaEncryptionKey(1024, 65537)
4094 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004095 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
4096 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004097 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01004098 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07004099 message,
4100 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
4101
4102 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4103 .Digest(Digest::SHA_2_256)
4104 .Padding(PaddingMode::RSA_OAEP)));
4105 string result;
4106 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
4107 EXPECT_EQ(0U, result.size());
4108}
4109
4110/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004111 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
4112 *
David Drysdale59cae642021-05-12 13:52:03 +01004113 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004114 * digests.
4115 */
4116TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
4117 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4118
4119 size_t key_size = 2048; // Need largish key for SHA-512 test.
4120 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4121 .OaepMGFDigest(digests)
4122 .Authorization(TAG_NO_AUTH_REQUIRED)
4123 .RsaEncryptionKey(key_size, 65537)
4124 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004125 .Digest(Digest::SHA_2_256)
4126 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004127
4128 string message = "Hello";
4129
4130 for (auto digest : digests) {
4131 auto params = AuthorizationSetBuilder()
4132 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4133 .Digest(Digest::SHA_2_256)
4134 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01004135 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004136 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4137 EXPECT_EQ(key_size / 8, ciphertext1.size());
4138
David Drysdale59cae642021-05-12 13:52:03 +01004139 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004140 EXPECT_EQ(key_size / 8, ciphertext2.size());
4141
4142 // OAEP randomizes padding so every result should be different (with astronomically high
4143 // probability).
4144 EXPECT_NE(ciphertext1, ciphertext2);
4145
4146 string plaintext1 = DecryptMessage(ciphertext1, params);
4147 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4148 string plaintext2 = DecryptMessage(ciphertext2, params);
4149 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4150
4151 // Decrypting corrupted ciphertext should fail.
4152 size_t offset_to_corrupt = random() % ciphertext1.size();
4153 char corrupt_byte;
4154 do {
4155 corrupt_byte = static_cast<char>(random() % 256);
4156 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4157 ciphertext1[offset_to_corrupt] = corrupt_byte;
4158
4159 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4160 string result;
4161 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4162 EXPECT_EQ(0U, result.size());
4163 }
4164}
4165
4166/*
4167 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4168 *
David Drysdale59cae642021-05-12 13:52:03 +01004169 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004170 * with incompatible MGF digest.
4171 */
4172TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4173 ASSERT_EQ(ErrorCode::OK,
4174 GenerateKey(AuthorizationSetBuilder()
4175 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4176 .Authorization(TAG_NO_AUTH_REQUIRED)
4177 .RsaEncryptionKey(2048, 65537)
4178 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004179 .Digest(Digest::SHA_2_256)
4180 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004181 string message = "Hello World!";
4182
4183 auto params = AuthorizationSetBuilder()
4184 .Padding(PaddingMode::RSA_OAEP)
4185 .Digest(Digest::SHA_2_256)
4186 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004187 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004188}
4189
4190/*
4191 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4192 *
4193 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4194 * with unsupported MGF digest.
4195 */
4196TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4197 ASSERT_EQ(ErrorCode::OK,
4198 GenerateKey(AuthorizationSetBuilder()
4199 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4200 .Authorization(TAG_NO_AUTH_REQUIRED)
4201 .RsaEncryptionKey(2048, 65537)
4202 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004203 .Digest(Digest::SHA_2_256)
4204 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004205 string message = "Hello World!";
4206
4207 auto params = AuthorizationSetBuilder()
4208 .Padding(PaddingMode::RSA_OAEP)
4209 .Digest(Digest::SHA_2_256)
4210 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004211 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004212}
4213
4214/*
Selene Huang31ab4042020-04-29 04:22:39 -07004215 * EncryptionOperationsTest.RsaPkcs1Success
4216 *
4217 * Verifies that RSA PKCS encryption/decrypts works.
4218 */
4219TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4220 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4221 .Authorization(TAG_NO_AUTH_REQUIRED)
4222 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004223 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4224 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004225
4226 string message = "Hello World!";
4227 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004228 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004229 EXPECT_EQ(2048U / 8, ciphertext1.size());
4230
David Drysdale59cae642021-05-12 13:52:03 +01004231 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004232 EXPECT_EQ(2048U / 8, ciphertext2.size());
4233
4234 // PKCS1 v1.5 randomizes padding so every result should be different.
4235 EXPECT_NE(ciphertext1, ciphertext2);
4236
4237 string plaintext = DecryptMessage(ciphertext1, params);
4238 EXPECT_EQ(message, plaintext);
4239
4240 // Decrypting corrupted ciphertext should fail.
4241 size_t offset_to_corrupt = random() % ciphertext1.size();
4242 char corrupt_byte;
4243 do {
4244 corrupt_byte = static_cast<char>(random() % 256);
4245 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4246 ciphertext1[offset_to_corrupt] = corrupt_byte;
4247
4248 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4249 string result;
4250 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4251 EXPECT_EQ(0U, result.size());
4252}
4253
4254/*
Selene Huang31ab4042020-04-29 04:22:39 -07004255 * EncryptionOperationsTest.EcdsaEncrypt
4256 *
4257 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4258 */
4259TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4260 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4261 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004262 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004263 .Digest(Digest::NONE)
4264 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004265 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4266 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4267 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4268}
4269
4270/*
4271 * EncryptionOperationsTest.HmacEncrypt
4272 *
4273 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4274 */
4275TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4276 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4277 .Authorization(TAG_NO_AUTH_REQUIRED)
4278 .HmacKey(128)
4279 .Digest(Digest::SHA_2_256)
4280 .Padding(PaddingMode::NONE)
4281 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4282 auto params = AuthorizationSetBuilder()
4283 .Digest(Digest::SHA_2_256)
4284 .Padding(PaddingMode::NONE)
4285 .Authorization(TAG_MAC_LENGTH, 128);
4286 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4287 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4288}
4289
4290/*
4291 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4292 *
4293 * Verifies that AES ECB mode works.
4294 */
4295TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4297 .Authorization(TAG_NO_AUTH_REQUIRED)
4298 .AesEncryptionKey(128)
4299 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4300 .Padding(PaddingMode::NONE)));
4301
4302 ASSERT_GT(key_blob_.size(), 0U);
4303 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4304
4305 // Two-block message.
4306 string message = "12345678901234567890123456789012";
4307 string ciphertext1 = EncryptMessage(message, params);
4308 EXPECT_EQ(message.size(), ciphertext1.size());
4309
4310 string ciphertext2 = EncryptMessage(string(message), params);
4311 EXPECT_EQ(message.size(), ciphertext2.size());
4312
4313 // ECB is deterministic.
4314 EXPECT_EQ(ciphertext1, ciphertext2);
4315
4316 string plaintext = DecryptMessage(ciphertext1, params);
4317 EXPECT_EQ(message, plaintext);
4318}
4319
4320/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004321 * EncryptionOperationsTest.AesEcbUnknownTag
4322 *
4323 * Verifies that AES ECB operations ignore unknown tags.
4324 */
4325TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4326 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4327 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4328 KeyParameter unknown_param;
4329 unknown_param.tag = unknown_tag;
4330
4331 vector<KeyCharacteristics> key_characteristics;
4332 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4333 .Authorization(TAG_NO_AUTH_REQUIRED)
4334 .AesEncryptionKey(128)
4335 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4336 .Padding(PaddingMode::NONE)
4337 .Authorization(unknown_param),
4338 &key_blob_, &key_characteristics));
4339 ASSERT_GT(key_blob_.size(), 0U);
4340
4341 // Unknown tags should not be returned in key characteristics.
4342 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4343 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4344 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4345 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4346
4347 // Encrypt without mentioning the unknown parameter.
4348 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4349 string message = "12345678901234567890123456789012";
4350 string ciphertext = EncryptMessage(message, params);
4351 EXPECT_EQ(message.size(), ciphertext.size());
4352
4353 // Decrypt including the unknown parameter.
4354 auto decrypt_params = AuthorizationSetBuilder()
4355 .BlockMode(BlockMode::ECB)
4356 .Padding(PaddingMode::NONE)
4357 .Authorization(unknown_param);
4358 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4359 EXPECT_EQ(message, plaintext);
4360}
4361
4362/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004363 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004364 *
4365 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4366 */
4367TEST_P(EncryptionOperationsTest, AesWrongMode) {
4368 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4369 .Authorization(TAG_NO_AUTH_REQUIRED)
4370 .AesEncryptionKey(128)
4371 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4372 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004373 ASSERT_GT(key_blob_.size(), 0U);
4374
Selene Huang31ab4042020-04-29 04:22:39 -07004375 EXPECT_EQ(
4376 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4377 Begin(KeyPurpose::ENCRYPT,
4378 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4379}
4380
4381/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004382 * EncryptionOperationsTest.AesWrongPadding
4383 *
4384 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4385 */
4386TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4387 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4388 .Authorization(TAG_NO_AUTH_REQUIRED)
4389 .AesEncryptionKey(128)
4390 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4391 .Padding(PaddingMode::NONE)));
4392 ASSERT_GT(key_blob_.size(), 0U);
4393
4394 EXPECT_EQ(
4395 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4396 Begin(KeyPurpose::ENCRYPT,
4397 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4398}
4399
4400/*
4401 * EncryptionOperationsTest.AesInvalidParams
4402 *
4403 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4404 */
4405TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4406 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4407 .Authorization(TAG_NO_AUTH_REQUIRED)
4408 .AesEncryptionKey(128)
4409 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4410 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4411 .Padding(PaddingMode::NONE)
4412 .Padding(PaddingMode::PKCS7)));
4413 ASSERT_GT(key_blob_.size(), 0U);
4414
4415 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4416 .BlockMode(BlockMode::CBC)
4417 .BlockMode(BlockMode::ECB)
4418 .Padding(PaddingMode::NONE));
4419 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4420 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4421
4422 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4423 .BlockMode(BlockMode::ECB)
4424 .Padding(PaddingMode::NONE)
4425 .Padding(PaddingMode::PKCS7));
4426 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4427 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4428}
4429
4430/*
Selene Huang31ab4042020-04-29 04:22:39 -07004431 * EncryptionOperationsTest.AesWrongPurpose
4432 *
4433 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4434 * specified.
4435 */
4436TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4437 auto err = GenerateKey(AuthorizationSetBuilder()
4438 .Authorization(TAG_NO_AUTH_REQUIRED)
4439 .AesKey(128)
4440 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4441 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4442 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4443 .Padding(PaddingMode::NONE));
4444 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4445 ASSERT_GT(key_blob_.size(), 0U);
4446
4447 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4448 .BlockMode(BlockMode::GCM)
4449 .Padding(PaddingMode::NONE)
4450 .Authorization(TAG_MAC_LENGTH, 128));
4451 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4452
4453 CheckedDeleteKey();
4454
4455 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4456 .Authorization(TAG_NO_AUTH_REQUIRED)
4457 .AesKey(128)
4458 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4459 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4460 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4461 .Padding(PaddingMode::NONE)));
4462
4463 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4464 .BlockMode(BlockMode::GCM)
4465 .Padding(PaddingMode::NONE)
4466 .Authorization(TAG_MAC_LENGTH, 128));
4467 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4468}
4469
4470/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004471 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004472 *
4473 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4474 * multiple of the block size and no padding is specified.
4475 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004476TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4477 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4478 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4479 .Authorization(TAG_NO_AUTH_REQUIRED)
4480 .AesEncryptionKey(128)
4481 .Authorization(TAG_BLOCK_MODE, blockMode)
4482 .Padding(PaddingMode::NONE)));
4483 // Message is slightly shorter than two blocks.
4484 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004485
David Drysdaled2cc8c22021-04-15 13:29:45 +01004486 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4487 AuthorizationSet out_params;
4488 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4489 string ciphertext;
4490 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4491 EXPECT_EQ(0U, ciphertext.size());
4492
4493 CheckedDeleteKey();
4494 }
Selene Huang31ab4042020-04-29 04:22:39 -07004495}
4496
4497/*
4498 * EncryptionOperationsTest.AesEcbPkcs7Padding
4499 *
4500 * Verifies that AES PKCS7 padding works for any message length.
4501 */
4502TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4503 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4504 .Authorization(TAG_NO_AUTH_REQUIRED)
4505 .AesEncryptionKey(128)
4506 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4507 .Padding(PaddingMode::PKCS7)));
4508
4509 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4510
4511 // Try various message lengths; all should work.
4512 for (size_t i = 0; i < 32; ++i) {
4513 string message(i, 'a');
4514 string ciphertext = EncryptMessage(message, params);
4515 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4516 string plaintext = DecryptMessage(ciphertext, params);
4517 EXPECT_EQ(message, plaintext);
4518 }
4519}
4520
4521/*
4522 * EncryptionOperationsTest.AesEcbWrongPadding
4523 *
4524 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4525 * specified.
4526 */
4527TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4528 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4529 .Authorization(TAG_NO_AUTH_REQUIRED)
4530 .AesEncryptionKey(128)
4531 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4532 .Padding(PaddingMode::NONE)));
4533
4534 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4535
4536 // Try various message lengths; all should fail
4537 for (size_t i = 0; i < 32; ++i) {
4538 string message(i, 'a');
4539 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4540 }
4541}
4542
4543/*
4544 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4545 *
4546 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4547 */
4548TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4549 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4550 .Authorization(TAG_NO_AUTH_REQUIRED)
4551 .AesEncryptionKey(128)
4552 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4553 .Padding(PaddingMode::PKCS7)));
4554
4555 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4556
4557 string message = "a";
4558 string ciphertext = EncryptMessage(message, params);
4559 EXPECT_EQ(16U, ciphertext.size());
4560 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07004561
Seth Moore7a55ae32021-06-23 14:28:11 -07004562 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
4563 ++ciphertext[ciphertext.size() / 2];
4564
4565 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4566 string plaintext;
4567 ErrorCode error = Finish(message, &plaintext);
4568 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
4569 // This is the expected error, we can exit the test now.
4570 return;
4571 } else {
4572 // Very small chance we got valid decryption, so try again.
4573 ASSERT_EQ(error, ErrorCode::OK);
4574 }
4575 }
4576 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07004577}
4578
4579vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4580 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004581 EXPECT_TRUE(iv);
4582 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004583}
4584
4585/*
4586 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4587 *
4588 * Verifies that AES CTR mode works.
4589 */
4590TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4591 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4592 .Authorization(TAG_NO_AUTH_REQUIRED)
4593 .AesEncryptionKey(128)
4594 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4595 .Padding(PaddingMode::NONE)));
4596
4597 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4598
4599 string message = "123";
4600 AuthorizationSet out_params;
4601 string ciphertext1 = EncryptMessage(message, params, &out_params);
4602 vector<uint8_t> iv1 = CopyIv(out_params);
4603 EXPECT_EQ(16U, iv1.size());
4604
4605 EXPECT_EQ(message.size(), ciphertext1.size());
4606
4607 out_params.Clear();
4608 string ciphertext2 = EncryptMessage(message, params, &out_params);
4609 vector<uint8_t> iv2 = CopyIv(out_params);
4610 EXPECT_EQ(16U, iv2.size());
4611
4612 // IVs should be random, so ciphertexts should differ.
4613 EXPECT_NE(ciphertext1, ciphertext2);
4614
4615 auto params_iv1 =
4616 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4617 auto params_iv2 =
4618 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4619
4620 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4621 EXPECT_EQ(message, plaintext);
4622 plaintext = DecryptMessage(ciphertext2, params_iv2);
4623 EXPECT_EQ(message, plaintext);
4624
4625 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4626 plaintext = DecryptMessage(ciphertext1, params_iv2);
4627 EXPECT_NE(message, plaintext);
4628 plaintext = DecryptMessage(ciphertext2, params_iv1);
4629 EXPECT_NE(message, plaintext);
4630}
4631
4632/*
4633 * EncryptionOperationsTest.AesIncremental
4634 *
4635 * Verifies that AES works, all modes, when provided data in various size increments.
4636 */
4637TEST_P(EncryptionOperationsTest, AesIncremental) {
4638 auto block_modes = {
4639 BlockMode::ECB,
4640 BlockMode::CBC,
4641 BlockMode::CTR,
4642 BlockMode::GCM,
4643 };
4644
4645 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4646 .Authorization(TAG_NO_AUTH_REQUIRED)
4647 .AesEncryptionKey(128)
4648 .BlockMode(block_modes)
4649 .Padding(PaddingMode::NONE)
4650 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4651
4652 for (int increment = 1; increment <= 240; ++increment) {
4653 for (auto block_mode : block_modes) {
4654 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004655 auto params =
4656 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4657 if (block_mode == BlockMode::GCM) {
4658 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4659 }
Selene Huang31ab4042020-04-29 04:22:39 -07004660
4661 AuthorizationSet output_params;
4662 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4663
4664 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004665 string to_send;
4666 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004667 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004668 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004669 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4670 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004671
4672 switch (block_mode) {
4673 case BlockMode::GCM:
4674 EXPECT_EQ(message.size() + 16, ciphertext.size());
4675 break;
4676 case BlockMode::CTR:
4677 EXPECT_EQ(message.size(), ciphertext.size());
4678 break;
4679 case BlockMode::CBC:
4680 case BlockMode::ECB:
4681 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4682 break;
4683 }
4684
4685 auto iv = output_params.GetTagValue(TAG_NONCE);
4686 switch (block_mode) {
4687 case BlockMode::CBC:
4688 case BlockMode::GCM:
4689 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004690 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4691 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4692 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004693 break;
4694
4695 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004696 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004697 break;
4698 }
4699
4700 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4701 << "Decrypt begin() failed for block mode " << block_mode;
4702
4703 string plaintext;
4704 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004705 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004706 }
4707 ErrorCode error = Finish(to_send, &plaintext);
4708 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4709 << " and increment " << increment;
4710 if (error == ErrorCode::OK) {
4711 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4712 << block_mode << " and increment " << increment;
4713 }
4714 }
4715 }
4716}
4717
4718struct AesCtrSp80038aTestVector {
4719 const char* key;
4720 const char* nonce;
4721 const char* plaintext;
4722 const char* ciphertext;
4723};
4724
4725// These test vectors are taken from
4726// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4727static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4728 // AES-128
4729 {
4730 "2b7e151628aed2a6abf7158809cf4f3c",
4731 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4732 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4733 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4734 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4735 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4736 },
4737 // AES-192
4738 {
4739 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4740 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4741 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4742 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4743 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4744 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4745 },
4746 // AES-256
4747 {
4748 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4749 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4750 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4751 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4752 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4753 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4754 },
4755};
4756
4757/*
4758 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4759 *
4760 * Verifies AES CTR implementation against SP800-38A test vectors.
4761 */
4762TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4763 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4764 for (size_t i = 0; i < 3; i++) {
4765 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4766 const string key = hex2str(test.key);
4767 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4768 InvalidSizes.end())
4769 continue;
4770 const string nonce = hex2str(test.nonce);
4771 const string plaintext = hex2str(test.plaintext);
4772 const string ciphertext = hex2str(test.ciphertext);
4773 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4774 }
4775}
4776
4777/*
4778 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4779 *
4780 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4781 */
4782TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4783 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4784 .Authorization(TAG_NO_AUTH_REQUIRED)
4785 .AesEncryptionKey(128)
4786 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4787 .Padding(PaddingMode::PKCS7)));
4788 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4789 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4790}
4791
4792/*
4793 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4794 *
4795 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4796 */
4797TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4798 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4799 .Authorization(TAG_NO_AUTH_REQUIRED)
4800 .AesEncryptionKey(128)
4801 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4802 .Authorization(TAG_CALLER_NONCE)
4803 .Padding(PaddingMode::NONE)));
4804
4805 auto params = AuthorizationSetBuilder()
4806 .BlockMode(BlockMode::CTR)
4807 .Padding(PaddingMode::NONE)
4808 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4809 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4810
4811 params = AuthorizationSetBuilder()
4812 .BlockMode(BlockMode::CTR)
4813 .Padding(PaddingMode::NONE)
4814 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4815 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4816
4817 params = AuthorizationSetBuilder()
4818 .BlockMode(BlockMode::CTR)
4819 .Padding(PaddingMode::NONE)
4820 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4821 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4822}
4823
4824/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004825 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004826 *
4827 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4828 */
4829TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4830 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4831 .Authorization(TAG_NO_AUTH_REQUIRED)
4832 .AesEncryptionKey(128)
4833 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4834 .Padding(PaddingMode::NONE)));
4835 // Two-block message.
4836 string message = "12345678901234567890123456789012";
4837 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4838 AuthorizationSet out_params;
4839 string ciphertext1 = EncryptMessage(message, params, &out_params);
4840 vector<uint8_t> iv1 = CopyIv(out_params);
4841 EXPECT_EQ(message.size(), ciphertext1.size());
4842
4843 out_params.Clear();
4844
4845 string ciphertext2 = EncryptMessage(message, params, &out_params);
4846 vector<uint8_t> iv2 = CopyIv(out_params);
4847 EXPECT_EQ(message.size(), ciphertext2.size());
4848
4849 // IVs should be random, so ciphertexts should differ.
4850 EXPECT_NE(ciphertext1, ciphertext2);
4851
4852 params.push_back(TAG_NONCE, iv1);
4853 string plaintext = DecryptMessage(ciphertext1, params);
4854 EXPECT_EQ(message, plaintext);
4855}
4856
4857/*
4858 * EncryptionOperationsTest.AesCallerNonce
4859 *
4860 * Verifies that AES caller-provided nonces work correctly.
4861 */
4862TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4863 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4864 .Authorization(TAG_NO_AUTH_REQUIRED)
4865 .AesEncryptionKey(128)
4866 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4867 .Authorization(TAG_CALLER_NONCE)
4868 .Padding(PaddingMode::NONE)));
4869
4870 string message = "12345678901234567890123456789012";
4871
4872 // Don't specify nonce, should get a random one.
4873 AuthorizationSetBuilder params =
4874 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4875 AuthorizationSet out_params;
4876 string ciphertext = EncryptMessage(message, params, &out_params);
4877 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004878 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004879
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004880 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004881 string plaintext = DecryptMessage(ciphertext, params);
4882 EXPECT_EQ(message, plaintext);
4883
4884 // Now specify a nonce, should also work.
4885 params = AuthorizationSetBuilder()
4886 .BlockMode(BlockMode::CBC)
4887 .Padding(PaddingMode::NONE)
4888 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4889 out_params.Clear();
4890 ciphertext = EncryptMessage(message, params, &out_params);
4891
4892 // Decrypt with correct nonce.
4893 plaintext = DecryptMessage(ciphertext, params);
4894 EXPECT_EQ(message, plaintext);
4895
4896 // Try with wrong nonce.
4897 params = AuthorizationSetBuilder()
4898 .BlockMode(BlockMode::CBC)
4899 .Padding(PaddingMode::NONE)
4900 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4901 plaintext = DecryptMessage(ciphertext, params);
4902 EXPECT_NE(message, plaintext);
4903}
4904
4905/*
4906 * EncryptionOperationsTest.AesCallerNonceProhibited
4907 *
4908 * Verifies that caller-provided nonces are not permitted when not specified in the key
4909 * authorizations.
4910 */
4911TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4912 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4913 .Authorization(TAG_NO_AUTH_REQUIRED)
4914 .AesEncryptionKey(128)
4915 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4916 .Padding(PaddingMode::NONE)));
4917
4918 string message = "12345678901234567890123456789012";
4919
4920 // Don't specify nonce, should get a random one.
4921 AuthorizationSetBuilder params =
4922 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4923 AuthorizationSet out_params;
4924 string ciphertext = EncryptMessage(message, params, &out_params);
4925 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004926 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004927
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004928 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004929 string plaintext = DecryptMessage(ciphertext, params);
4930 EXPECT_EQ(message, plaintext);
4931
4932 // Now specify a nonce, should fail
4933 params = AuthorizationSetBuilder()
4934 .BlockMode(BlockMode::CBC)
4935 .Padding(PaddingMode::NONE)
4936 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4937 out_params.Clear();
4938 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4939}
4940
4941/*
4942 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4943 *
4944 * Verifies that AES GCM mode works.
4945 */
4946TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4947 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4948 .Authorization(TAG_NO_AUTH_REQUIRED)
4949 .AesEncryptionKey(128)
4950 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4951 .Padding(PaddingMode::NONE)
4952 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4953
4954 string aad = "foobar";
4955 string message = "123456789012345678901234567890123456";
4956
4957 auto begin_params = AuthorizationSetBuilder()
4958 .BlockMode(BlockMode::GCM)
4959 .Padding(PaddingMode::NONE)
4960 .Authorization(TAG_MAC_LENGTH, 128);
4961
Selene Huang31ab4042020-04-29 04:22:39 -07004962 // Encrypt
4963 AuthorizationSet begin_out_params;
4964 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4965 << "Begin encrypt";
4966 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004967 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4968 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004969 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4970
4971 // Grab nonce
4972 begin_params.push_back(begin_out_params);
4973
4974 // Decrypt.
4975 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004976 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004977 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004978 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004979 EXPECT_EQ(message.length(), plaintext.length());
4980 EXPECT_EQ(message, plaintext);
4981}
4982
4983/*
4984 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4985 *
4986 * Verifies that AES GCM mode works, even when there's a long delay
4987 * between operations.
4988 */
4989TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4990 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4991 .Authorization(TAG_NO_AUTH_REQUIRED)
4992 .AesEncryptionKey(128)
4993 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4994 .Padding(PaddingMode::NONE)
4995 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4996
4997 string aad = "foobar";
4998 string message = "123456789012345678901234567890123456";
4999
5000 auto begin_params = AuthorizationSetBuilder()
5001 .BlockMode(BlockMode::GCM)
5002 .Padding(PaddingMode::NONE)
5003 .Authorization(TAG_MAC_LENGTH, 128);
5004
Selene Huang31ab4042020-04-29 04:22:39 -07005005 // Encrypt
5006 AuthorizationSet begin_out_params;
5007 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5008 << "Begin encrypt";
5009 string ciphertext;
5010 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005011 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005012 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005013 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005014
5015 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5016
5017 // Grab nonce
5018 begin_params.push_back(begin_out_params);
5019
5020 // Decrypt.
5021 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5022 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005023 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005024 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005025 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005026 sleep(5);
5027 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5028 EXPECT_EQ(message.length(), plaintext.length());
5029 EXPECT_EQ(message, plaintext);
5030}
5031
5032/*
5033 * EncryptionOperationsTest.AesGcmDifferentNonces
5034 *
5035 * Verifies that encrypting the same data with different nonces produces different outputs.
5036 */
5037TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
5038 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5039 .Authorization(TAG_NO_AUTH_REQUIRED)
5040 .AesEncryptionKey(128)
5041 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5042 .Padding(PaddingMode::NONE)
5043 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5044 .Authorization(TAG_CALLER_NONCE)));
5045
5046 string aad = "foobar";
5047 string message = "123456789012345678901234567890123456";
5048 string nonce1 = "000000000000";
5049 string nonce2 = "111111111111";
5050 string nonce3 = "222222222222";
5051
5052 string ciphertext1 =
5053 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
5054 string ciphertext2 =
5055 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
5056 string ciphertext3 =
5057 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
5058
5059 ASSERT_NE(ciphertext1, ciphertext2);
5060 ASSERT_NE(ciphertext1, ciphertext3);
5061 ASSERT_NE(ciphertext2, ciphertext3);
5062}
5063
5064/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005065 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
5066 *
5067 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
5068 */
5069TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
5070 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5071 .Authorization(TAG_NO_AUTH_REQUIRED)
5072 .AesEncryptionKey(128)
5073 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5074 .Padding(PaddingMode::NONE)
5075 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5076
5077 string aad = "foobar";
5078 string message = "123456789012345678901234567890123456";
5079
5080 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5081 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5082 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5083
5084 ASSERT_NE(ciphertext1, ciphertext2);
5085 ASSERT_NE(ciphertext1, ciphertext3);
5086 ASSERT_NE(ciphertext2, ciphertext3);
5087}
5088
5089/*
Selene Huang31ab4042020-04-29 04:22:39 -07005090 * EncryptionOperationsTest.AesGcmTooShortTag
5091 *
5092 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
5093 */
5094TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
5095 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5096 .Authorization(TAG_NO_AUTH_REQUIRED)
5097 .AesEncryptionKey(128)
5098 .BlockMode(BlockMode::GCM)
5099 .Padding(PaddingMode::NONE)
5100 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5101 string message = "123456789012345678901234567890123456";
5102 auto params = AuthorizationSetBuilder()
5103 .BlockMode(BlockMode::GCM)
5104 .Padding(PaddingMode::NONE)
5105 .Authorization(TAG_MAC_LENGTH, 96);
5106
5107 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5108}
5109
5110/*
5111 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
5112 *
5113 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
5114 */
5115TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
5116 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5117 .Authorization(TAG_NO_AUTH_REQUIRED)
5118 .AesEncryptionKey(128)
5119 .BlockMode(BlockMode::GCM)
5120 .Padding(PaddingMode::NONE)
5121 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5122 string aad = "foobar";
5123 string message = "123456789012345678901234567890123456";
5124 auto params = AuthorizationSetBuilder()
5125 .BlockMode(BlockMode::GCM)
5126 .Padding(PaddingMode::NONE)
5127 .Authorization(TAG_MAC_LENGTH, 128);
5128
Selene Huang31ab4042020-04-29 04:22:39 -07005129 // Encrypt
5130 AuthorizationSet begin_out_params;
5131 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5132 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005133 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005134
5135 AuthorizationSet finish_out_params;
5136 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005137 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5138 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005139
5140 params = AuthorizationSetBuilder()
5141 .Authorizations(begin_out_params)
5142 .BlockMode(BlockMode::GCM)
5143 .Padding(PaddingMode::NONE)
5144 .Authorization(TAG_MAC_LENGTH, 96);
5145
5146 // Decrypt.
5147 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5148}
5149
5150/*
5151 * EncryptionOperationsTest.AesGcmCorruptKey
5152 *
5153 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5154 */
5155TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5156 const uint8_t nonce_bytes[] = {
5157 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5158 };
5159 string nonce = make_string(nonce_bytes);
5160 const uint8_t ciphertext_bytes[] = {
5161 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5162 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5163 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5164 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5165 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5166 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5167 };
5168 string ciphertext = make_string(ciphertext_bytes);
5169
5170 auto params = AuthorizationSetBuilder()
5171 .BlockMode(BlockMode::GCM)
5172 .Padding(PaddingMode::NONE)
5173 .Authorization(TAG_MAC_LENGTH, 128)
5174 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5175
5176 auto import_params = AuthorizationSetBuilder()
5177 .Authorization(TAG_NO_AUTH_REQUIRED)
5178 .AesEncryptionKey(128)
5179 .BlockMode(BlockMode::GCM)
5180 .Padding(PaddingMode::NONE)
5181 .Authorization(TAG_CALLER_NONCE)
5182 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5183
5184 // Import correct key and decrypt
5185 const uint8_t key_bytes[] = {
5186 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5187 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5188 };
5189 string key = make_string(key_bytes);
5190 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5191 string plaintext = DecryptMessage(ciphertext, params);
5192 CheckedDeleteKey();
5193
5194 // Corrupt key and attempt to decrypt
5195 key[0] = 0;
5196 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5197 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5198 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5199 CheckedDeleteKey();
5200}
5201
5202/*
5203 * EncryptionOperationsTest.AesGcmAadNoData
5204 *
5205 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5206 * encrypt.
5207 */
5208TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5209 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5210 .Authorization(TAG_NO_AUTH_REQUIRED)
5211 .AesEncryptionKey(128)
5212 .BlockMode(BlockMode::GCM)
5213 .Padding(PaddingMode::NONE)
5214 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5215
5216 string aad = "1234567890123456";
5217 auto params = AuthorizationSetBuilder()
5218 .BlockMode(BlockMode::GCM)
5219 .Padding(PaddingMode::NONE)
5220 .Authorization(TAG_MAC_LENGTH, 128);
5221
Selene Huang31ab4042020-04-29 04:22:39 -07005222 // Encrypt
5223 AuthorizationSet begin_out_params;
5224 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5225 string ciphertext;
5226 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005227 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5228 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005229 EXPECT_TRUE(finish_out_params.empty());
5230
5231 // Grab nonce
5232 params.push_back(begin_out_params);
5233
5234 // Decrypt.
5235 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005236 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005237 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005238 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005239
5240 EXPECT_TRUE(finish_out_params.empty());
5241
5242 EXPECT_EQ("", plaintext);
5243}
5244
5245/*
5246 * EncryptionOperationsTest.AesGcmMultiPartAad
5247 *
5248 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5249 * chunks.
5250 */
5251TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5252 const size_t tag_bits = 128;
5253 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5254 .Authorization(TAG_NO_AUTH_REQUIRED)
5255 .AesEncryptionKey(128)
5256 .BlockMode(BlockMode::GCM)
5257 .Padding(PaddingMode::NONE)
5258 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5259
5260 string message = "123456789012345678901234567890123456";
5261 auto begin_params = AuthorizationSetBuilder()
5262 .BlockMode(BlockMode::GCM)
5263 .Padding(PaddingMode::NONE)
5264 .Authorization(TAG_MAC_LENGTH, tag_bits);
5265 AuthorizationSet begin_out_params;
5266
Selene Huang31ab4042020-04-29 04:22:39 -07005267 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5268
5269 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005270 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5271 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005272 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005273 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5274 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005275
Selene Huang31ab4042020-04-29 04:22:39 -07005276 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005277 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005278
5279 // Grab nonce.
5280 begin_params.push_back(begin_out_params);
5281
5282 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005283 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005284 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005285 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005286 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005287 EXPECT_EQ(message, plaintext);
5288}
5289
5290/*
5291 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5292 *
5293 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5294 */
5295TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5297 .Authorization(TAG_NO_AUTH_REQUIRED)
5298 .AesEncryptionKey(128)
5299 .BlockMode(BlockMode::GCM)
5300 .Padding(PaddingMode::NONE)
5301 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5302
5303 string message = "123456789012345678901234567890123456";
5304 auto begin_params = AuthorizationSetBuilder()
5305 .BlockMode(BlockMode::GCM)
5306 .Padding(PaddingMode::NONE)
5307 .Authorization(TAG_MAC_LENGTH, 128);
5308 AuthorizationSet begin_out_params;
5309
Selene Huang31ab4042020-04-29 04:22:39 -07005310 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5311
Shawn Willden92d79c02021-02-19 07:31:55 -07005312 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005313 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005314 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5315 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005316
David Drysdaled2cc8c22021-04-15 13:29:45 +01005317 // The failure should have already cancelled the operation.
5318 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5319
Shawn Willden92d79c02021-02-19 07:31:55 -07005320 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005321}
5322
5323/*
5324 * EncryptionOperationsTest.AesGcmBadAad
5325 *
5326 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5327 */
5328TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5329 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5330 .Authorization(TAG_NO_AUTH_REQUIRED)
5331 .AesEncryptionKey(128)
5332 .BlockMode(BlockMode::GCM)
5333 .Padding(PaddingMode::NONE)
5334 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5335
5336 string message = "12345678901234567890123456789012";
5337 auto begin_params = AuthorizationSetBuilder()
5338 .BlockMode(BlockMode::GCM)
5339 .Padding(PaddingMode::NONE)
5340 .Authorization(TAG_MAC_LENGTH, 128);
5341
Selene Huang31ab4042020-04-29 04:22:39 -07005342 // Encrypt
5343 AuthorizationSet begin_out_params;
5344 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005345 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005346 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005347 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005348
5349 // Grab nonce
5350 begin_params.push_back(begin_out_params);
5351
Selene Huang31ab4042020-04-29 04:22:39 -07005352 // Decrypt.
5353 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005354 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005355 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005356 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005357}
5358
5359/*
5360 * EncryptionOperationsTest.AesGcmWrongNonce
5361 *
5362 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5363 */
5364TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5365 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5366 .Authorization(TAG_NO_AUTH_REQUIRED)
5367 .AesEncryptionKey(128)
5368 .BlockMode(BlockMode::GCM)
5369 .Padding(PaddingMode::NONE)
5370 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5371
5372 string message = "12345678901234567890123456789012";
5373 auto begin_params = AuthorizationSetBuilder()
5374 .BlockMode(BlockMode::GCM)
5375 .Padding(PaddingMode::NONE)
5376 .Authorization(TAG_MAC_LENGTH, 128);
5377
Selene Huang31ab4042020-04-29 04:22:39 -07005378 // Encrypt
5379 AuthorizationSet begin_out_params;
5380 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005381 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005382 string ciphertext;
5383 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005384 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005385
5386 // Wrong nonce
5387 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5388
5389 // Decrypt.
5390 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005391 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005392 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005393 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005394
5395 // With wrong nonce, should have gotten garbage plaintext (or none).
5396 EXPECT_NE(message, plaintext);
5397}
5398
5399/*
5400 * EncryptionOperationsTest.AesGcmCorruptTag
5401 *
5402 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5403 */
5404TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5405 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5406 .Authorization(TAG_NO_AUTH_REQUIRED)
5407 .AesEncryptionKey(128)
5408 .BlockMode(BlockMode::GCM)
5409 .Padding(PaddingMode::NONE)
5410 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5411
5412 string aad = "1234567890123456";
5413 string message = "123456789012345678901234567890123456";
5414
5415 auto params = AuthorizationSetBuilder()
5416 .BlockMode(BlockMode::GCM)
5417 .Padding(PaddingMode::NONE)
5418 .Authorization(TAG_MAC_LENGTH, 128);
5419
Selene Huang31ab4042020-04-29 04:22:39 -07005420 // Encrypt
5421 AuthorizationSet begin_out_params;
5422 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005423 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005424 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005425 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005426
5427 // Corrupt tag
5428 ++(*ciphertext.rbegin());
5429
5430 // Grab nonce
5431 params.push_back(begin_out_params);
5432
5433 // Decrypt.
5434 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005435 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005436 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005437 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005438}
5439
5440/*
5441 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5442 *
5443 * Verifies that 3DES is basically functional.
5444 */
5445TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5446 auto auths = AuthorizationSetBuilder()
5447 .TripleDesEncryptionKey(168)
5448 .BlockMode(BlockMode::ECB)
5449 .Authorization(TAG_NO_AUTH_REQUIRED)
5450 .Padding(PaddingMode::NONE);
5451
5452 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5453 // Two-block message.
5454 string message = "1234567890123456";
5455 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5456 string ciphertext1 = EncryptMessage(message, inParams);
5457 EXPECT_EQ(message.size(), ciphertext1.size());
5458
5459 string ciphertext2 = EncryptMessage(string(message), inParams);
5460 EXPECT_EQ(message.size(), ciphertext2.size());
5461
5462 // ECB is deterministic.
5463 EXPECT_EQ(ciphertext1, ciphertext2);
5464
5465 string plaintext = DecryptMessage(ciphertext1, inParams);
5466 EXPECT_EQ(message, plaintext);
5467}
5468
5469/*
5470 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5471 *
5472 * Verifies that CBC keys reject ECB usage.
5473 */
5474TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5475 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5476 .TripleDesEncryptionKey(168)
5477 .BlockMode(BlockMode::CBC)
5478 .Authorization(TAG_NO_AUTH_REQUIRED)
5479 .Padding(PaddingMode::NONE)));
5480
5481 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5482 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5483}
5484
5485/*
5486 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5487 *
5488 * Tests ECB mode with PKCS#7 padding, various message sizes.
5489 */
5490TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5491 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5492 .TripleDesEncryptionKey(168)
5493 .BlockMode(BlockMode::ECB)
5494 .Authorization(TAG_NO_AUTH_REQUIRED)
5495 .Padding(PaddingMode::PKCS7)));
5496
5497 for (size_t i = 0; i < 32; ++i) {
5498 string message(i, 'a');
5499 auto inParams =
5500 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5501 string ciphertext = EncryptMessage(message, inParams);
5502 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5503 string plaintext = DecryptMessage(ciphertext, inParams);
5504 EXPECT_EQ(message, plaintext);
5505 }
5506}
5507
5508/*
5509 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5510 *
5511 * Verifies that keys configured for no padding reject PKCS7 padding
5512 */
5513TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5514 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5515 .TripleDesEncryptionKey(168)
5516 .BlockMode(BlockMode::ECB)
5517 .Authorization(TAG_NO_AUTH_REQUIRED)
5518 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005519 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5520 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005521}
5522
5523/*
5524 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5525 *
5526 * Verifies that corrupted padding is detected.
5527 */
5528TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5529 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5530 .TripleDesEncryptionKey(168)
5531 .BlockMode(BlockMode::ECB)
5532 .Authorization(TAG_NO_AUTH_REQUIRED)
5533 .Padding(PaddingMode::PKCS7)));
5534
5535 string message = "a";
5536 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5537 EXPECT_EQ(8U, ciphertext.size());
5538 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005539
5540 AuthorizationSetBuilder begin_params;
5541 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5542 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07005543
5544 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5545 ++ciphertext[ciphertext.size() / 2];
5546
5547 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5548 string plaintext;
5549 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5550 ErrorCode error = Finish(&plaintext);
5551 if (error == ErrorCode::INVALID_ARGUMENT) {
5552 // This is the expected error, we can exit the test now.
5553 return;
5554 } else {
5555 // Very small chance we got valid decryption, so try again.
5556 ASSERT_EQ(error, ErrorCode::OK);
5557 }
5558 }
5559 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005560}
5561
5562struct TripleDesTestVector {
5563 const char* name;
5564 const KeyPurpose purpose;
5565 const BlockMode block_mode;
5566 const PaddingMode padding_mode;
5567 const char* key;
5568 const char* iv;
5569 const char* input;
5570 const char* output;
5571};
5572
5573// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5574// of the NIST vectors are multiples of the block size.
5575static const TripleDesTestVector kTripleDesTestVectors[] = {
5576 {
5577 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5578 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5579 "", // IV
5580 "329d86bdf1bc5af4", // input
5581 "d946c2756d78633f", // output
5582 },
5583 {
5584 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5585 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5586 "", // IV
5587 "6b1540781b01ce1997adae102dbf3c5b", // input
5588 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5589 },
5590 {
5591 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5592 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5593 "", // IV
5594 "6daad94ce08acfe7", // input
5595 "660e7d32dcc90e79", // output
5596 },
5597 {
5598 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5599 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5600 "", // IV
5601 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5602 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5603 },
5604 {
5605 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5606 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5607 "43f791134c5647ba", // IV
5608 "dcc153cef81d6f24", // input
5609 "92538bd8af18d3ba", // output
5610 },
5611 {
5612 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5613 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5614 "c2e999cb6249023c", // IV
5615 "c689aee38a301bb316da75db36f110b5", // input
5616 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5617 },
5618 {
5619 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5620 PaddingMode::PKCS7,
5621 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5622 "c2e999cb6249023c", // IV
5623 "c689aee38a301bb316da75db36f110b500", // input
5624 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5625 },
5626 {
5627 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5628 PaddingMode::PKCS7,
5629 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5630 "c2e999cb6249023c", // IV
5631 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5632 "c689aee38a301bb316da75db36f110b500", // output
5633 },
5634 {
5635 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5636 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5637 "41746c7e442d3681", // IV
5638 "c53a7b0ec40600fe", // input
5639 "d4f00eb455de1034", // output
5640 },
5641 {
5642 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5643 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5644 "3982bc02c3727d45", // IV
5645 "6006f10adef52991fcc777a1238bbb65", // input
5646 "edae09288e9e3bc05746d872b48e3b29", // output
5647 },
5648};
5649
5650/*
5651 * EncryptionOperationsTest.TripleDesTestVector
5652 *
5653 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5654 */
5655TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5656 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5657 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5658 SCOPED_TRACE(test->name);
5659 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5660 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5661 hex2str(test->output));
5662 }
5663}
5664
5665/*
5666 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5667 *
5668 * Validates CBC mode functionality.
5669 */
5670TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5671 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5672 .TripleDesEncryptionKey(168)
5673 .BlockMode(BlockMode::CBC)
5674 .Authorization(TAG_NO_AUTH_REQUIRED)
5675 .Padding(PaddingMode::NONE)));
5676
5677 ASSERT_GT(key_blob_.size(), 0U);
5678
5679 // Two-block message.
5680 string message = "1234567890123456";
5681 vector<uint8_t> iv1;
5682 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5683 EXPECT_EQ(message.size(), ciphertext1.size());
5684
5685 vector<uint8_t> iv2;
5686 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5687 EXPECT_EQ(message.size(), ciphertext2.size());
5688
5689 // IVs should be random, so ciphertexts should differ.
5690 EXPECT_NE(iv1, iv2);
5691 EXPECT_NE(ciphertext1, ciphertext2);
5692
5693 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5694 EXPECT_EQ(message, plaintext);
5695}
5696
5697/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005698 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5699 *
5700 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5701 */
5702TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5703 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5704 .TripleDesEncryptionKey(168)
5705 .BlockMode(BlockMode::CBC)
5706 .Authorization(TAG_NO_AUTH_REQUIRED)
5707 .Authorization(TAG_CALLER_NONCE)
5708 .Padding(PaddingMode::NONE)));
5709 auto params = AuthorizationSetBuilder()
5710 .BlockMode(BlockMode::CBC)
5711 .Padding(PaddingMode::NONE)
5712 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5713 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5714}
5715
5716/*
Selene Huang31ab4042020-04-29 04:22:39 -07005717 * EncryptionOperationsTest.TripleDesCallerIv
5718 *
5719 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5720 */
5721TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5722 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5723 .TripleDesEncryptionKey(168)
5724 .BlockMode(BlockMode::CBC)
5725 .Authorization(TAG_NO_AUTH_REQUIRED)
5726 .Authorization(TAG_CALLER_NONCE)
5727 .Padding(PaddingMode::NONE)));
5728 string message = "1234567890123456";
5729 vector<uint8_t> iv;
5730 // Don't specify IV, should get a random one.
5731 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5732 EXPECT_EQ(message.size(), ciphertext1.size());
5733 EXPECT_EQ(8U, iv.size());
5734
5735 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5736 EXPECT_EQ(message, plaintext);
5737
5738 // Now specify an IV, should also work.
5739 iv = AidlBuf("abcdefgh");
5740 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5741
5742 // Decrypt with correct IV.
5743 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5744 EXPECT_EQ(message, plaintext);
5745
5746 // Now try with wrong IV.
5747 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5748 EXPECT_NE(message, plaintext);
5749}
5750
5751/*
5752 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5753 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005754 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005755 */
5756TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5757 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5758 .TripleDesEncryptionKey(168)
5759 .BlockMode(BlockMode::CBC)
5760 .Authorization(TAG_NO_AUTH_REQUIRED)
5761 .Padding(PaddingMode::NONE)));
5762
5763 string message = "12345678901234567890123456789012";
5764 vector<uint8_t> iv;
5765 // Don't specify nonce, should get a random one.
5766 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5767 EXPECT_EQ(message.size(), ciphertext1.size());
5768 EXPECT_EQ(8U, iv.size());
5769
5770 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5771 EXPECT_EQ(message, plaintext);
5772
5773 // Now specify a nonce, should fail.
5774 auto input_params = AuthorizationSetBuilder()
5775 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5776 .BlockMode(BlockMode::CBC)
5777 .Padding(PaddingMode::NONE);
5778 AuthorizationSet output_params;
5779 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5780 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5781}
5782
5783/*
5784 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5785 *
5786 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5787 */
5788TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5789 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5790 .TripleDesEncryptionKey(168)
5791 .BlockMode(BlockMode::ECB)
5792 .Authorization(TAG_NO_AUTH_REQUIRED)
5793 .Padding(PaddingMode::NONE)));
5794 // Two-block message.
5795 string message = "1234567890123456";
5796 auto begin_params =
5797 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5798 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5799}
5800
5801/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005802 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005803 *
5804 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5805 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005806TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5807 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5808 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5809 .TripleDesEncryptionKey(168)
5810 .BlockMode(blockMode)
5811 .Authorization(TAG_NO_AUTH_REQUIRED)
5812 .Padding(PaddingMode::NONE)));
5813 // Message is slightly shorter than two blocks.
5814 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005815
David Drysdaled2cc8c22021-04-15 13:29:45 +01005816 auto begin_params =
5817 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5818 AuthorizationSet output_params;
5819 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5820 string ciphertext;
5821 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5822
5823 CheckedDeleteKey();
5824 }
Selene Huang31ab4042020-04-29 04:22:39 -07005825}
5826
5827/*
5828 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5829 *
5830 * Verifies that PKCS7 padding works correctly in CBC mode.
5831 */
5832TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5833 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5834 .TripleDesEncryptionKey(168)
5835 .BlockMode(BlockMode::CBC)
5836 .Authorization(TAG_NO_AUTH_REQUIRED)
5837 .Padding(PaddingMode::PKCS7)));
5838
5839 // Try various message lengths; all should work.
5840 for (size_t i = 0; i < 32; ++i) {
5841 string message(i, 'a');
5842 vector<uint8_t> iv;
5843 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5844 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5845 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5846 EXPECT_EQ(message, plaintext);
5847 }
5848}
5849
5850/*
5851 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5852 *
5853 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5854 */
5855TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5856 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5857 .TripleDesEncryptionKey(168)
5858 .BlockMode(BlockMode::CBC)
5859 .Authorization(TAG_NO_AUTH_REQUIRED)
5860 .Padding(PaddingMode::NONE)));
5861
5862 // Try various message lengths; all should fail.
5863 for (size_t i = 0; i < 32; ++i) {
5864 auto begin_params =
5865 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5866 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5867 }
5868}
5869
5870/*
5871 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5872 *
5873 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5874 */
5875TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5876 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5877 .TripleDesEncryptionKey(168)
5878 .BlockMode(BlockMode::CBC)
5879 .Authorization(TAG_NO_AUTH_REQUIRED)
5880 .Padding(PaddingMode::PKCS7)));
5881
5882 string message = "a";
5883 vector<uint8_t> iv;
5884 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5885 EXPECT_EQ(8U, ciphertext.size());
5886 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005887
5888 auto begin_params = AuthorizationSetBuilder()
5889 .BlockMode(BlockMode::CBC)
5890 .Padding(PaddingMode::PKCS7)
5891 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07005892
5893 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5894 ++ciphertext[ciphertext.size() / 2];
5895 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5896 string plaintext;
5897 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5898 ErrorCode error = Finish(&plaintext);
5899 if (error == ErrorCode::INVALID_ARGUMENT) {
5900 // This is the expected error, we can exit the test now.
5901 return;
5902 } else {
5903 // Very small chance we got valid decryption, so try again.
5904 ASSERT_EQ(error, ErrorCode::OK);
5905 }
5906 }
5907 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005908}
5909
5910/*
5911 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5912 *
5913 * Verifies that 3DES CBC works with many different input sizes.
5914 */
5915TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5916 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5917 .TripleDesEncryptionKey(168)
5918 .BlockMode(BlockMode::CBC)
5919 .Authorization(TAG_NO_AUTH_REQUIRED)
5920 .Padding(PaddingMode::NONE)));
5921
5922 int increment = 7;
5923 string message(240, 'a');
5924 AuthorizationSet input_params =
5925 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5926 AuthorizationSet output_params;
5927 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5928
5929 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005930 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005931 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005932 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5933 EXPECT_EQ(message.size(), ciphertext.size());
5934
5935 // Move TAG_NONCE into input_params
5936 input_params = output_params;
5937 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5938 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5939 output_params.Clear();
5940
5941 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5942 string plaintext;
5943 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005944 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005945 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5946 EXPECT_EQ(ciphertext.size(), plaintext.size());
5947 EXPECT_EQ(message, plaintext);
5948}
5949
5950INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5951
5952typedef KeyMintAidlTestBase MaxOperationsTest;
5953
5954/*
5955 * MaxOperationsTest.TestLimitAes
5956 *
5957 * Verifies that the max uses per boot tag works correctly with AES keys.
5958 */
5959TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01005960 if (SecLevel() == SecurityLevel::STRONGBOX) {
5961 GTEST_SKIP() << "Test not applicable to StrongBox device";
5962 }
Selene Huang31ab4042020-04-29 04:22:39 -07005963
5964 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5965 .Authorization(TAG_NO_AUTH_REQUIRED)
5966 .AesEncryptionKey(128)
5967 .EcbMode()
5968 .Padding(PaddingMode::NONE)
5969 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5970
5971 string message = "1234567890123456";
5972
5973 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5974
5975 EncryptMessage(message, params);
5976 EncryptMessage(message, params);
5977 EncryptMessage(message, params);
5978
5979 // Fourth time should fail.
5980 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5981}
5982
5983/*
Qi Wud22ec842020-11-26 13:27:53 +08005984 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005985 *
5986 * Verifies that the max uses per boot tag works correctly with RSA keys.
5987 */
5988TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01005989 if (SecLevel() == SecurityLevel::STRONGBOX) {
5990 GTEST_SKIP() << "Test not applicable to StrongBox device";
5991 }
Selene Huang31ab4042020-04-29 04:22:39 -07005992
5993 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5994 .Authorization(TAG_NO_AUTH_REQUIRED)
5995 .RsaSigningKey(1024, 65537)
5996 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005997 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5998 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005999
6000 string message = "1234567890123456";
6001
6002 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6003
6004 SignMessage(message, params);
6005 SignMessage(message, params);
6006 SignMessage(message, params);
6007
6008 // Fourth time should fail.
6009 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6010}
6011
6012INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6013
Qi Wud22ec842020-11-26 13:27:53 +08006014typedef KeyMintAidlTestBase UsageCountLimitTest;
6015
6016/*
Qi Wubeefae42021-01-28 23:16:37 +08006017 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006018 *
Qi Wubeefae42021-01-28 23:16:37 +08006019 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006020 */
Qi Wubeefae42021-01-28 23:16:37 +08006021TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006022 if (SecLevel() == SecurityLevel::STRONGBOX) {
6023 GTEST_SKIP() << "Test not applicable to StrongBox device";
6024 }
Qi Wud22ec842020-11-26 13:27:53 +08006025
6026 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6027 .Authorization(TAG_NO_AUTH_REQUIRED)
6028 .AesEncryptionKey(128)
6029 .EcbMode()
6030 .Padding(PaddingMode::NONE)
6031 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
6032
6033 // Check the usage count limit tag appears in the authorizations.
6034 AuthorizationSet auths;
6035 for (auto& entry : key_characteristics_) {
6036 auths.push_back(AuthorizationSet(entry.authorizations));
6037 }
6038 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6039 << "key usage count limit " << 1U << " missing";
6040
6041 string message = "1234567890123456";
6042 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6043
Qi Wubeefae42021-01-28 23:16:37 +08006044 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6045 AuthorizationSet keystore_auths =
6046 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6047
Qi Wud22ec842020-11-26 13:27:53 +08006048 // First usage of AES key should work.
6049 EncryptMessage(message, params);
6050
Qi Wud22ec842020-11-26 13:27:53 +08006051 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6052 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6053 // must be invalidated from secure storage (such as RPMB partition).
6054 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6055 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006056 // Usage count limit tag is enforced by keystore, keymint does nothing.
6057 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08006058 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6059 }
6060}
6061
6062/*
Qi Wubeefae42021-01-28 23:16:37 +08006063 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006064 *
Qi Wubeefae42021-01-28 23:16:37 +08006065 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006066 */
Qi Wubeefae42021-01-28 23:16:37 +08006067TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006068 if (SecLevel() == SecurityLevel::STRONGBOX) {
6069 GTEST_SKIP() << "Test not applicable to StrongBox device";
6070 }
Qi Wubeefae42021-01-28 23:16:37 +08006071
6072 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6073 .Authorization(TAG_NO_AUTH_REQUIRED)
6074 .AesEncryptionKey(128)
6075 .EcbMode()
6076 .Padding(PaddingMode::NONE)
6077 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
6078
6079 // Check the usage count limit tag appears in the authorizations.
6080 AuthorizationSet auths;
6081 for (auto& entry : key_characteristics_) {
6082 auths.push_back(AuthorizationSet(entry.authorizations));
6083 }
6084 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6085 << "key usage count limit " << 3U << " missing";
6086
6087 string message = "1234567890123456";
6088 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6089
6090 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6091 AuthorizationSet keystore_auths =
6092 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6093
6094 EncryptMessage(message, params);
6095 EncryptMessage(message, params);
6096 EncryptMessage(message, params);
6097
6098 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6099 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6100 // must be invalidated from secure storage (such as RPMB partition).
6101 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6102 } else {
6103 // Usage count limit tag is enforced by keystore, keymint does nothing.
6104 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
6105 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6106 }
6107}
6108
6109/*
6110 * UsageCountLimitTest.TestSingleUseRsa
6111 *
6112 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
6113 */
6114TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006115 if (SecLevel() == SecurityLevel::STRONGBOX) {
6116 GTEST_SKIP() << "Test not applicable to StrongBox device";
6117 }
Qi Wud22ec842020-11-26 13:27:53 +08006118
6119 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6120 .Authorization(TAG_NO_AUTH_REQUIRED)
6121 .RsaSigningKey(1024, 65537)
6122 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006123 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6124 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08006125
6126 // Check the usage count limit tag appears in the authorizations.
6127 AuthorizationSet auths;
6128 for (auto& entry : key_characteristics_) {
6129 auths.push_back(AuthorizationSet(entry.authorizations));
6130 }
6131 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6132 << "key usage count limit " << 1U << " missing";
6133
6134 string message = "1234567890123456";
6135 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6136
Qi Wubeefae42021-01-28 23:16:37 +08006137 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6138 AuthorizationSet keystore_auths =
6139 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6140
Qi Wud22ec842020-11-26 13:27:53 +08006141 // First usage of RSA key should work.
6142 SignMessage(message, params);
6143
Qi Wud22ec842020-11-26 13:27:53 +08006144 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6145 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6146 // must be invalidated from secure storage (such as RPMB partition).
6147 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6148 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006149 // Usage count limit tag is enforced by keystore, keymint does nothing.
6150 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
6151 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6152 }
6153}
6154
6155/*
6156 * UsageCountLimitTest.TestLimitUseRsa
6157 *
6158 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6159 */
6160TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006161 if (SecLevel() == SecurityLevel::STRONGBOX) {
6162 GTEST_SKIP() << "Test not applicable to StrongBox device";
6163 }
Qi Wubeefae42021-01-28 23:16:37 +08006164
6165 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6166 .Authorization(TAG_NO_AUTH_REQUIRED)
6167 .RsaSigningKey(1024, 65537)
6168 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006169 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6170 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006171
6172 // Check the usage count limit tag appears in the authorizations.
6173 AuthorizationSet auths;
6174 for (auto& entry : key_characteristics_) {
6175 auths.push_back(AuthorizationSet(entry.authorizations));
6176 }
6177 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6178 << "key usage count limit " << 3U << " missing";
6179
6180 string message = "1234567890123456";
6181 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6182
6183 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6184 AuthorizationSet keystore_auths =
6185 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6186
6187 SignMessage(message, params);
6188 SignMessage(message, params);
6189 SignMessage(message, params);
6190
6191 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6192 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6193 // must be invalidated from secure storage (such as RPMB partition).
6194 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6195 } else {
6196 // Usage count limit tag is enforced by keystore, keymint does nothing.
6197 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006198 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6199 }
6200}
6201
Qi Wu8e727f72021-02-11 02:49:33 +08006202/*
6203 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6204 *
6205 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6206 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6207 * in hardware.
6208 */
6209TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01006210 if (SecLevel() == SecurityLevel::STRONGBOX) {
6211 GTEST_SKIP() << "Test not applicable to StrongBox device";
6212 }
Qi Wu8e727f72021-02-11 02:49:33 +08006213
6214 auto error = GenerateKey(AuthorizationSetBuilder()
6215 .RsaSigningKey(2048, 65537)
6216 .Digest(Digest::NONE)
6217 .Padding(PaddingMode::NONE)
6218 .Authorization(TAG_NO_AUTH_REQUIRED)
6219 .Authorization(TAG_ROLLBACK_RESISTANCE)
6220 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006221 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6222 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08006223 }
David Drysdale513bf122021-10-06 11:53:13 +01006224
6225 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6226 ASSERT_EQ(ErrorCode::OK, error);
6227 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6228 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6229 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6230
6231 // The KeyMint should also enforce single use key in hardware when it supports rollback
6232 // resistance.
6233 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6234 .Authorization(TAG_NO_AUTH_REQUIRED)
6235 .RsaSigningKey(1024, 65537)
6236 .NoDigestOrPadding()
6237 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6238 .SetDefaultValidity()));
6239
6240 // Check the usage count limit tag appears in the hardware authorizations.
6241 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6242 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6243 << "key usage count limit " << 1U << " missing";
6244
6245 string message = "1234567890123456";
6246 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6247
6248 // First usage of RSA key should work.
6249 SignMessage(message, params);
6250
6251 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6252 // must be invalidated from secure storage (such as RPMB partition).
6253 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08006254}
6255
Qi Wud22ec842020-11-26 13:27:53 +08006256INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6257
David Drysdale7de9feb2021-03-05 14:56:19 +00006258typedef KeyMintAidlTestBase GetHardwareInfoTest;
6259
6260TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6261 // Retrieving hardware info should give the same result each time.
6262 KeyMintHardwareInfo info;
6263 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6264 KeyMintHardwareInfo info2;
6265 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6266 EXPECT_EQ(info, info2);
6267}
6268
6269INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6270
Selene Huang31ab4042020-04-29 04:22:39 -07006271typedef KeyMintAidlTestBase AddEntropyTest;
6272
6273/*
6274 * AddEntropyTest.AddEntropy
6275 *
6276 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6277 * is actually added.
6278 */
6279TEST_P(AddEntropyTest, AddEntropy) {
6280 string data = "foo";
6281 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6282}
6283
6284/*
6285 * AddEntropyTest.AddEmptyEntropy
6286 *
6287 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6288 */
6289TEST_P(AddEntropyTest, AddEmptyEntropy) {
6290 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6291}
6292
6293/*
6294 * AddEntropyTest.AddLargeEntropy
6295 *
6296 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6297 */
6298TEST_P(AddEntropyTest, AddLargeEntropy) {
6299 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6300}
6301
David Drysdalebb3d85e2021-04-13 11:15:51 +01006302/*
6303 * AddEntropyTest.AddTooLargeEntropy
6304 *
6305 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6306 */
6307TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6308 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6309 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6310}
6311
Selene Huang31ab4042020-04-29 04:22:39 -07006312INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6313
Selene Huang31ab4042020-04-29 04:22:39 -07006314typedef KeyMintAidlTestBase KeyDeletionTest;
6315
6316/**
6317 * KeyDeletionTest.DeleteKey
6318 *
6319 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6320 * valid key blob.
6321 */
6322TEST_P(KeyDeletionTest, DeleteKey) {
6323 auto error = GenerateKey(AuthorizationSetBuilder()
6324 .RsaSigningKey(2048, 65537)
6325 .Digest(Digest::NONE)
6326 .Padding(PaddingMode::NONE)
6327 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006328 .Authorization(TAG_ROLLBACK_RESISTANCE)
6329 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006330 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6331 GTEST_SKIP() << "Rollback resistance not supported";
6332 }
Selene Huang31ab4042020-04-29 04:22:39 -07006333
6334 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006335 ASSERT_EQ(ErrorCode::OK, error);
6336 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6337 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006338
David Drysdale513bf122021-10-06 11:53:13 +01006339 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07006340
David Drysdale513bf122021-10-06 11:53:13 +01006341 string message = "12345678901234567890123456789012";
6342 AuthorizationSet begin_out_params;
6343 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6344 Begin(KeyPurpose::SIGN, key_blob_,
6345 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6346 &begin_out_params));
6347 AbortIfNeeded();
6348 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006349}
6350
6351/**
6352 * KeyDeletionTest.DeleteInvalidKey
6353 *
6354 * This test checks that the HAL excepts invalid key blobs..
6355 */
6356TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6357 // Generate key just to check if rollback protection is implemented
6358 auto error = GenerateKey(AuthorizationSetBuilder()
6359 .RsaSigningKey(2048, 65537)
6360 .Digest(Digest::NONE)
6361 .Padding(PaddingMode::NONE)
6362 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006363 .Authorization(TAG_ROLLBACK_RESISTANCE)
6364 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006365 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6366 GTEST_SKIP() << "Rollback resistance not supported";
6367 }
Selene Huang31ab4042020-04-29 04:22:39 -07006368
6369 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006370 ASSERT_EQ(ErrorCode::OK, error);
6371 AuthorizationSet enforced(SecLevelAuthorizations());
6372 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006373
David Drysdale513bf122021-10-06 11:53:13 +01006374 // Delete the key we don't care about the result at this point.
6375 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07006376
David Drysdale513bf122021-10-06 11:53:13 +01006377 // Now create an invalid key blob and delete it.
6378 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07006379
David Drysdale513bf122021-10-06 11:53:13 +01006380 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07006381}
6382
6383/**
6384 * KeyDeletionTest.DeleteAllKeys
6385 *
6386 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6387 *
6388 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6389 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6390 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6391 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6392 * credentials stored in Keystore/Keymint.
6393 */
6394TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01006395 if (!arm_deleteAllKeys) {
6396 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
6397 return;
6398 }
Selene Huang31ab4042020-04-29 04:22:39 -07006399 auto error = GenerateKey(AuthorizationSetBuilder()
6400 .RsaSigningKey(2048, 65537)
6401 .Digest(Digest::NONE)
6402 .Padding(PaddingMode::NONE)
6403 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06006404 .Authorization(TAG_ROLLBACK_RESISTANCE)
6405 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006406 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6407 GTEST_SKIP() << "Rollback resistance not supported";
6408 }
Selene Huang31ab4042020-04-29 04:22:39 -07006409
6410 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006411 ASSERT_EQ(ErrorCode::OK, error);
6412 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6413 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006414
David Drysdale513bf122021-10-06 11:53:13 +01006415 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07006416
David Drysdale513bf122021-10-06 11:53:13 +01006417 string message = "12345678901234567890123456789012";
6418 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07006419
David Drysdale513bf122021-10-06 11:53:13 +01006420 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6421 Begin(KeyPurpose::SIGN, key_blob_,
6422 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6423 &begin_out_params));
6424 AbortIfNeeded();
6425 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006426}
6427
6428INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6429
David Drysdaled2cc8c22021-04-15 13:29:45 +01006430typedef KeyMintAidlTestBase KeyUpgradeTest;
6431
6432/**
6433 * KeyUpgradeTest.UpgradeInvalidKey
6434 *
6435 * This test checks that the HAL excepts invalid key blobs..
6436 */
6437TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6438 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6439
6440 std::vector<uint8_t> new_blob;
6441 Status result = keymint_->upgradeKey(key_blob,
6442 AuthorizationSetBuilder()
6443 .Authorization(TAG_APPLICATION_ID, "clientid")
6444 .Authorization(TAG_APPLICATION_DATA, "appdata")
6445 .vector_data(),
6446 &new_blob);
6447 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6448}
6449
6450INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6451
Selene Huang31ab4042020-04-29 04:22:39 -07006452using UpgradeKeyTest = KeyMintAidlTestBase;
6453
6454/*
6455 * UpgradeKeyTest.UpgradeKey
6456 *
6457 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6458 */
6459TEST_P(UpgradeKeyTest, UpgradeKey) {
6460 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6461 .AesEncryptionKey(128)
6462 .Padding(PaddingMode::NONE)
6463 .Authorization(TAG_NO_AUTH_REQUIRED)));
6464
6465 auto result = UpgradeKey(key_blob_);
6466
6467 // Key doesn't need upgrading. Should get okay, but no new key blob.
6468 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6469}
6470
6471INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6472
6473using ClearOperationsTest = KeyMintAidlTestBase;
6474
6475/*
6476 * ClearSlotsTest.TooManyOperations
6477 *
6478 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6479 * operations are started without being finished or aborted. Also verifies
6480 * that aborting the operations clears the operations.
6481 *
6482 */
6483TEST_P(ClearOperationsTest, TooManyOperations) {
6484 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6485 .Authorization(TAG_NO_AUTH_REQUIRED)
6486 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006487 .Padding(PaddingMode::NONE)
6488 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006489
6490 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6491 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006492 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006493 AuthorizationSet out_params;
6494 ErrorCode result;
6495 size_t i;
6496
6497 for (i = 0; i < max_operations; i++) {
6498 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6499 if (ErrorCode::OK != result) {
6500 break;
6501 }
6502 }
6503 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6504 // Try again just in case there's a weird overflow bug
6505 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6506 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6507 for (size_t j = 0; j < i; j++) {
6508 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6509 << "Aboort failed for i = " << j << std::endl;
6510 }
6511 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6512 AbortIfNeeded();
6513}
6514
6515INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6516
6517typedef KeyMintAidlTestBase TransportLimitTest;
6518
6519/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006520 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006521 *
6522 * Verifies that passing input data to finish succeeds as expected.
6523 */
6524TEST_P(TransportLimitTest, LargeFinishInput) {
6525 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6526 .Authorization(TAG_NO_AUTH_REQUIRED)
6527 .AesEncryptionKey(128)
6528 .BlockMode(BlockMode::ECB)
6529 .Padding(PaddingMode::NONE)));
6530
6531 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6532 auto cipher_params =
6533 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6534
6535 AuthorizationSet out_params;
6536 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6537
6538 string plain_message = std::string(1 << msg_size, 'x');
6539 string encrypted_message;
6540 auto rc = Finish(plain_message, &encrypted_message);
6541
6542 EXPECT_EQ(ErrorCode::OK, rc);
6543 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6544 << "Encrypt finish returned OK, but did not consume all of the given input";
6545 cipher_params.push_back(out_params);
6546
6547 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6548
6549 string decrypted_message;
6550 rc = Finish(encrypted_message, &decrypted_message);
6551 EXPECT_EQ(ErrorCode::OK, rc);
6552 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6553 << "Decrypt finish returned OK, did not consume all of the given input";
6554 }
6555}
6556
6557INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6558
David Zeuthene0c40892021-01-08 12:54:11 -05006559typedef KeyMintAidlTestBase KeyAgreementTest;
6560
6561int CurveToOpenSslCurveName(EcCurve curve) {
6562 switch (curve) {
6563 case EcCurve::P_224:
6564 return NID_secp224r1;
6565 case EcCurve::P_256:
6566 return NID_X9_62_prime256v1;
6567 case EcCurve::P_384:
6568 return NID_secp384r1;
6569 case EcCurve::P_521:
6570 return NID_secp521r1;
6571 }
6572}
6573
6574/*
6575 * KeyAgreementTest.Ecdh
6576 *
6577 * Verifies that ECDH works for all curves
6578 */
6579TEST_P(KeyAgreementTest, Ecdh) {
6580 // Because it's possible to use this API with keys on different curves, we
6581 // check all N^2 combinations where N is the number of supported
6582 // curves.
6583 //
6584 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6585 // lot more curves we can be smart about things and just pick |otherCurve| so
6586 // it's not |curve| and that way we end up with only 2*N runs
6587 //
6588 for (auto curve : ValidCurves()) {
6589 for (auto localCurve : ValidCurves()) {
6590 // Generate EC key locally (with access to private key material)
6591 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6592 int curveName = CurveToOpenSslCurveName(localCurve);
6593 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6594 ASSERT_NE(group, nullptr);
6595 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6596 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6597 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6598 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6599
6600 // Get encoded form of the public part of the locally generated key...
6601 unsigned char* p = nullptr;
6602 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6603 ASSERT_GT(encodedPublicKeySize, 0);
6604 vector<uint8_t> encodedPublicKey(
6605 reinterpret_cast<const uint8_t*>(p),
6606 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6607 OPENSSL_free(p);
6608
6609 // Generate EC key in KeyMint (only access to public key material)
6610 vector<uint8_t> challenge = {0x41, 0x42};
6611 EXPECT_EQ(
6612 ErrorCode::OK,
6613 GenerateKey(AuthorizationSetBuilder()
6614 .Authorization(TAG_NO_AUTH_REQUIRED)
6615 .Authorization(TAG_EC_CURVE, curve)
6616 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6617 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6618 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006619 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6620 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006621 << "Failed to generate key";
6622 ASSERT_GT(cert_chain_.size(), 0);
6623 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6624 ASSERT_NE(kmKeyCert, nullptr);
6625 // Check that keyAgreement (bit 4) is set in KeyUsage
6626 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6627 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6628 ASSERT_NE(kmPkey, nullptr);
6629 if (dump_Attestations) {
6630 for (size_t n = 0; n < cert_chain_.size(); n++) {
6631 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6632 }
6633 }
6634
6635 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6636 if (curve != localCurve) {
6637 // If the keys are using different curves KeyMint should fail with
6638 // ErrorCode:INVALID_ARGUMENT. Check that.
6639 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6640 string ZabFromKeyMintStr;
6641 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6642 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6643 &ZabFromKeyMintStr));
6644
6645 } else {
6646 // Otherwise if the keys are using the same curve, it should work.
6647 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6648 string ZabFromKeyMintStr;
6649 EXPECT_EQ(ErrorCode::OK,
6650 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6651 &ZabFromKeyMintStr));
6652 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6653
6654 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6655 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6656 ASSERT_NE(ctx, nullptr);
6657 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6658 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6659 size_t ZabFromTestLen = 0;
6660 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6661 vector<uint8_t> ZabFromTest;
6662 ZabFromTest.resize(ZabFromTestLen);
6663 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6664
6665 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6666 }
6667
6668 CheckedDeleteKey();
6669 }
6670 }
6671}
6672
6673INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6674
David Drysdaled2cc8c22021-04-15 13:29:45 +01006675using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6676
6677// This is a problematic test, as it can render the device under test permanently unusable.
6678// Re-enable and run at your own risk.
6679TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6680 auto result = DestroyAttestationIds();
6681 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6682}
6683
6684INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6685
Shawn Willdend659c7c2021-02-19 14:51:51 -07006686using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006687
David Drysdaledb0dcf52021-05-18 11:43:31 +01006688/*
6689 * EarlyBootKeyTest.CreateEarlyBootKeys
6690 *
6691 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6692 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006693TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01006694 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006695 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6696 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6697
David Drysdaleadfe6112021-05-27 12:00:53 +01006698 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6699 ASSERT_GT(keyData.blob.size(), 0U);
6700 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6701 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6702 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006703 CheckedDeleteKey(&aesKeyData.blob);
6704 CheckedDeleteKey(&hmacKeyData.blob);
6705 CheckedDeleteKey(&rsaKeyData.blob);
6706 CheckedDeleteKey(&ecdsaKeyData.blob);
6707}
6708
David Drysdaledb0dcf52021-05-18 11:43:31 +01006709/*
David Drysdaleadfe6112021-05-27 12:00:53 +01006710 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6711 *
6712 * Verifies that creating an early boot key with attestation succeeds.
6713 */
6714TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6715 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6716 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6717 builder->AttestationChallenge("challenge");
6718 builder->AttestationApplicationId("app_id");
6719 });
6720
6721 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6722 ASSERT_GT(keyData.blob.size(), 0U);
6723 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6724 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6725 }
6726 CheckedDeleteKey(&aesKeyData.blob);
6727 CheckedDeleteKey(&hmacKeyData.blob);
6728 CheckedDeleteKey(&rsaKeyData.blob);
6729 CheckedDeleteKey(&ecdsaKeyData.blob);
6730}
6731
6732/*
6733 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01006734 *
6735 * Verifies that using early boot keys at a later stage fails.
6736 */
6737TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6738 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6739 .Authorization(TAG_NO_AUTH_REQUIRED)
6740 .Authorization(TAG_EARLY_BOOT_ONLY)
6741 .HmacKey(128)
6742 .Digest(Digest::SHA_2_256)
6743 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6744 AuthorizationSet output_params;
6745 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6746 AuthorizationSetBuilder()
6747 .Digest(Digest::SHA_2_256)
6748 .Authorization(TAG_MAC_LENGTH, 256),
6749 &output_params));
6750}
6751
6752/*
6753 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6754 *
6755 * Verifies that importing early boot keys fails.
6756 */
6757TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6758 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6759 .Authorization(TAG_NO_AUTH_REQUIRED)
6760 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01006761 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01006762 .Digest(Digest::SHA_2_256)
6763 .SetDefaultValidity(),
6764 KeyFormat::PKCS8, ec_256_key));
6765}
6766
David Drysdaled2cc8c22021-04-15 13:29:45 +01006767// 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 +00006768// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6769// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6770// early boot, so you'll have to reboot between runs.
6771TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6772 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6773 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6774 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6775 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6776 EXPECT_TRUE(
6777 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6778 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6779 EXPECT_TRUE(
6780 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6781
6782 // Should be able to use keys, since early boot has not ended
6783 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6784 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6785 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6786 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6787
6788 // End early boot
6789 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6790 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6791
6792 // Should not be able to use already-created keys.
6793 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6794 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6795 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6796 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6797
6798 CheckedDeleteKey(&aesKeyData.blob);
6799 CheckedDeleteKey(&hmacKeyData.blob);
6800 CheckedDeleteKey(&rsaKeyData.blob);
6801 CheckedDeleteKey(&ecdsaKeyData.blob);
6802
6803 // Should not be able to create new keys
6804 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6805 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6806
6807 CheckedDeleteKey(&aesKeyData.blob);
6808 CheckedDeleteKey(&hmacKeyData.blob);
6809 CheckedDeleteKey(&rsaKeyData.blob);
6810 CheckedDeleteKey(&ecdsaKeyData.blob);
6811}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006812
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006813INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6814
Shawn Willdend659c7c2021-02-19 14:51:51 -07006815using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006816
6817// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6818// between runs... and on most test devices there are no enrolled credentials so it can't be
6819// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6820// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6821// a manual test process, which includes unlocking between runs, which is why it's included here.
6822// Well, that and the fact that it's the only test we can do without also making calls into the
6823// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6824// implications might be, so that may or may not be a solution.
6825TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6826 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6827 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6828
6829 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6830 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6831 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6832 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6833
6834 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006835 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006836 ASSERT_EQ(ErrorCode::OK, rc);
6837 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6838 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6839 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6840 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6841
6842 CheckedDeleteKey(&aesKeyData.blob);
6843 CheckedDeleteKey(&hmacKeyData.blob);
6844 CheckedDeleteKey(&rsaKeyData.blob);
6845 CheckedDeleteKey(&ecdsaKeyData.blob);
6846}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006847
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006848INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6849
Janis Danisevskis24c04702020-12-16 18:28:39 -08006850} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006851
6852int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006853 std::cout << "Testing ";
6854 auto halInstances =
6855 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6856 std::cout << "HAL instances:\n";
6857 for (auto& entry : halInstances) {
6858 std::cout << " " << entry << '\n';
6859 }
6860
Selene Huang31ab4042020-04-29 04:22:39 -07006861 ::testing::InitGoogleTest(&argc, argv);
6862 for (int i = 1; i < argc; ++i) {
6863 if (argv[i][0] == '-') {
6864 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006865 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6866 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006867 }
6868 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006869 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6870 dump_Attestations = true;
6871 } else {
6872 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006873 }
6874 }
6875 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006876 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006877}