blob: 186873880cf47c2f9f846e90b894df1c004a4922 [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,
1630 vector<uint8_t>* unique_id) {
1631 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));
1636 const AuthorizationSetBuilder builder =
1637 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();
1648
1649 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder));
1650 ASSERT_GT(key_blob_.size(), 0U);
1651
1652 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1653 ASSERT_GT(cert_chain_.size(), 0);
1654 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1655
1656 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
1657 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
1658
1659 // Check that the unique ID field in the extension is non-empty.
1660 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1661 SecLevel(), cert_chain_[0].encodedCertificate,
1662 unique_id));
1663 EXPECT_GT(unique_id->size(), 0);
1664 CheckedDeleteKey();
1665 };
1666
1667 // Generate unique ID
1668 auto app_id = "foo";
1669 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
1670 vector<uint8_t> unique_id;
1671 get_unique_id(app_id, cert_date, &unique_id);
1672
1673 // Generating a new key with the same parameters should give the same unique ID.
1674 vector<uint8_t> unique_id2;
1675 get_unique_id(app_id, cert_date, &unique_id2);
1676 EXPECT_EQ(unique_id, unique_id2);
1677
1678 // Generating a new key with a slightly different date should give the same unique ID.
1679 uint64_t rounded_date = cert_date / 2592000000LLU;
1680 uint64_t min_date = rounded_date * 2592000000LLU;
1681 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
1682
1683 vector<uint8_t> unique_id3;
1684 get_unique_id(app_id, min_date, &unique_id3);
1685 EXPECT_EQ(unique_id, unique_id3);
1686
1687 vector<uint8_t> unique_id4;
1688 get_unique_id(app_id, max_date, &unique_id4);
1689 EXPECT_EQ(unique_id, unique_id4);
1690
1691 // A different attestation application ID should yield a different unique ID.
1692 auto app_id2 = "different_foo";
1693 vector<uint8_t> unique_id5;
1694 get_unique_id(app_id2, cert_date, &unique_id5);
1695 EXPECT_NE(unique_id, unique_id5);
1696
1697 // A radically different date should yield a different unique ID.
1698 vector<uint8_t> unique_id6;
1699 get_unique_id(app_id, 1611621648000, &unique_id6);
1700 EXPECT_NE(unique_id, unique_id6);
1701
1702 vector<uint8_t> unique_id7;
1703 get_unique_id(app_id, max_date + 1, &unique_id7);
1704 EXPECT_NE(unique_id, unique_id7);
1705
1706 vector<uint8_t> unique_id8;
1707 get_unique_id(app_id, min_date - 1, &unique_id8);
1708 EXPECT_NE(unique_id, unique_id8);
1709}
1710
1711/*
David Drysdale37af4b32021-05-14 16:46:59 +01001712 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1713 *
1714 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1715 */
1716TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1717 auto challenge = "hello";
1718 auto attest_app_id = "foo";
1719 auto subject = "cert subj 2";
1720 vector<uint8_t> subject_der(make_name_from_str(subject));
1721 uint64_t serial_int = 0x1010;
1722 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1723
1724 // Earlier versions of the attestation extension schema included a slot:
1725 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1726 // This should never have been included, and should never be filled in.
1727 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1728 // to confirm that this field never makes it into the attestation extension.
1729 vector<uint8_t> key_blob;
1730 vector<KeyCharacteristics> key_characteristics;
1731 auto result = GenerateKey(AuthorizationSetBuilder()
1732 .Authorization(TAG_NO_AUTH_REQUIRED)
1733 .EcdsaSigningKey(EcCurve::P_256)
1734 .Digest(Digest::NONE)
1735 .AttestationChallenge(challenge)
1736 .AttestationApplicationId(attest_app_id)
1737 .Authorization(TAG_APPLICATION_ID, "client_id")
1738 .Authorization(TAG_APPLICATION_DATA, "appdata")
1739 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1740 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1741 .SetDefaultValidity(),
1742 &key_blob, &key_characteristics);
1743 ASSERT_EQ(result, ErrorCode::OK);
1744 ASSERT_GT(key_blob.size(), 0U);
1745
1746 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1747 ASSERT_GT(cert_chain_.size(), 0);
1748 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1749
1750 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1751 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1752 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1753 SecLevel(), cert_chain_[0].encodedCertificate));
1754
1755 // Check that the app id is not in the cert.
1756 string app_id = "clientid";
1757 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1758 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1759 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1760 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1761 cert_chain_[0].encodedCertificate.end());
1762
1763 CheckedDeleteKey(&key_blob);
1764}
1765
1766/*
Selene Huang4f64c222021-04-13 19:54:36 -07001767 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1768 *
1769 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1770 * the key will generate a self signed attestation.
1771 */
1772TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001773 auto subject = "cert subj 2";
1774 vector<uint8_t> subject_der(make_name_from_str(subject));
1775
1776 uint64_t serial_int = 0x123456FFF1234;
1777 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1778
David Drysdaledf09e542021-06-08 15:46:11 +01001779 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001780 vector<uint8_t> key_blob;
1781 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001782 ASSERT_EQ(ErrorCode::OK,
1783 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001784 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001785 .Digest(Digest::NONE)
1786 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1787 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1788 .SetDefaultValidity(),
1789 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001790 ASSERT_GT(key_blob.size(), 0U);
1791 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001792 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001793
1794 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1795
1796 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001797 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001798
1799 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001800 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001801 ASSERT_EQ(cert_chain_.size(), 1);
1802
1803 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1804 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1805
1806 CheckedDeleteKey(&key_blob);
1807 }
1808}
1809
1810/*
1811 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1812 *
1813 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1814 * app id must also be provided or else it will fail.
1815 */
1816TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1817 auto challenge = "hello";
1818 vector<uint8_t> key_blob;
1819 vector<KeyCharacteristics> key_characteristics;
1820
1821 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1822 GenerateKey(AuthorizationSetBuilder()
1823 .EcdsaSigningKey(EcCurve::P_256)
1824 .Digest(Digest::NONE)
1825 .AttestationChallenge(challenge)
1826 .SetDefaultValidity(),
1827 &key_blob, &key_characteristics));
1828}
1829
1830/*
1831 * NewKeyGenerationTest.EcdsaIgnoreAppId
1832 *
1833 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1834 * any appid will be ignored, and keymint will generate a self sign certificate.
1835 */
1836TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1837 auto app_id = "foo";
1838
David Drysdaledf09e542021-06-08 15:46:11 +01001839 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001840 vector<uint8_t> key_blob;
1841 vector<KeyCharacteristics> key_characteristics;
1842 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001843 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001844 .Digest(Digest::NONE)
1845 .AttestationApplicationId(app_id)
1846 .SetDefaultValidity(),
1847 &key_blob, &key_characteristics));
1848
1849 ASSERT_GT(key_blob.size(), 0U);
1850 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001851 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001852
1853 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1854
1855 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001856 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001857
1858 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1859 ASSERT_EQ(cert_chain_.size(), 1);
1860
1861 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1862 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1863
1864 CheckedDeleteKey(&key_blob);
1865 }
1866}
1867
1868/*
1869 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1870 *
1871 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1872 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1873 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1874 * to specify how many following bytes will be used to encode the length.
1875 */
1876TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1877 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001878 std::vector<uint32_t> app_id_lengths{143, 258};
1879
1880 for (uint32_t length : app_id_lengths) {
1881 const string app_id(length, 'a');
1882 vector<uint8_t> key_blob;
1883 vector<KeyCharacteristics> key_characteristics;
1884 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1885 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001886 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001887 .Digest(Digest::NONE)
1888 .AttestationChallenge(challenge)
1889 .AttestationApplicationId(app_id)
1890 .SetDefaultValidity(),
1891 &key_blob, &key_characteristics));
1892 ASSERT_GT(key_blob.size(), 0U);
1893 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001894 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001895
1896 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1897
1898 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001899 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001900
1901 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1902 ASSERT_GT(cert_chain_.size(), 0);
1903
1904 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1905 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1906 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1907 sw_enforced, hw_enforced, SecLevel(),
1908 cert_chain_[0].encodedCertificate));
1909
1910 CheckedDeleteKey(&key_blob);
1911 }
1912}
1913
1914/*
Qi Wud22ec842020-11-26 13:27:53 +08001915 * NewKeyGenerationTest.LimitedUsageEcdsa
1916 *
1917 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1918 * resulting keys have correct characteristics.
1919 */
1920TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001921 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001922 vector<uint8_t> key_blob;
1923 vector<KeyCharacteristics> key_characteristics;
1924 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001925 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001926 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001927 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1928 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001929 &key_blob, &key_characteristics));
1930
1931 ASSERT_GT(key_blob.size(), 0U);
1932 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001933 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001934
1935 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1936
1937 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001938 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001939
1940 // Check the usage count limit tag appears in the authorizations.
1941 AuthorizationSet auths;
1942 for (auto& entry : key_characteristics) {
1943 auths.push_back(AuthorizationSet(entry.authorizations));
1944 }
1945 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1946 << "key usage count limit " << 1U << " missing";
1947
1948 CheckedDeleteKey(&key_blob);
1949 }
1950}
1951
1952/*
Selene Huang31ab4042020-04-29 04:22:39 -07001953 * NewKeyGenerationTest.EcdsaDefaultSize
1954 *
David Drysdaledf09e542021-06-08 15:46:11 +01001955 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001956 * UNSUPPORTED_KEY_SIZE.
1957 */
1958TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1959 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1960 GenerateKey(AuthorizationSetBuilder()
1961 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1962 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001963 .Digest(Digest::NONE)
1964 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001965}
1966
1967/*
1968 * NewKeyGenerationTest.EcdsaInvalidSize
1969 *
1970 * Verifies that specifying an invalid key size for EC key generation returns
1971 * UNSUPPORTED_KEY_SIZE.
1972 */
1973TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdaledf09e542021-06-08 15:46:11 +01001974 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001975 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001976 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001977 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001978 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001979 .Digest(Digest::NONE)
1980 .SetDefaultValidity(),
1981 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001982 }
1983
David Drysdaledf09e542021-06-08 15:46:11 +01001984 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1985 GenerateKey(AuthorizationSetBuilder()
1986 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1987 .Authorization(TAG_KEY_SIZE, 190)
1988 .SigningKey()
1989 .Digest(Digest::NONE)
1990 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001991}
1992
1993/*
1994 * NewKeyGenerationTest.EcdsaMismatchKeySize
1995 *
1996 * Verifies that specifying mismatched key size and curve for EC key generation returns
1997 * INVALID_ARGUMENT.
1998 */
1999TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002000 if (SecLevel() == SecurityLevel::STRONGBOX) {
2001 GTEST_SKIP() << "Test not applicable to StrongBox device";
2002 }
Selene Huang31ab4042020-04-29 04:22:39 -07002003
David Drysdaledf09e542021-06-08 15:46:11 +01002004 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002005 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002006 .Authorization(TAG_KEY_SIZE, 224)
2007 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002008 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002009 .Digest(Digest::NONE)
2010 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002011 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002012}
2013
2014/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002015 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002016 *
2017 * Verifies that keymint does not support any curve designated as unsupported.
2018 */
2019TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2020 Digest digest;
2021 if (SecLevel() == SecurityLevel::STRONGBOX) {
2022 digest = Digest::SHA_2_256;
2023 } else {
2024 digest = Digest::SHA_2_512;
2025 }
2026 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002027 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2028 .EcdsaSigningKey(curve)
2029 .Digest(digest)
2030 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002031 << "Failed to generate key on curve: " << curve;
2032 CheckedDeleteKey();
2033 }
2034}
2035
2036/*
2037 * NewKeyGenerationTest.Hmac
2038 *
2039 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2040 * characteristics.
2041 */
2042TEST_P(NewKeyGenerationTest, Hmac) {
2043 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2044 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002045 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002046 constexpr size_t key_size = 128;
2047 ASSERT_EQ(ErrorCode::OK,
2048 GenerateKey(
2049 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2050 TAG_MIN_MAC_LENGTH, 128),
2051 &key_blob, &key_characteristics));
2052
2053 ASSERT_GT(key_blob.size(), 0U);
2054 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002055 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002056
Shawn Willden7f424372021-01-10 18:06:50 -07002057 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2058 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2059 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2060 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002061
2062 CheckedDeleteKey(&key_blob);
2063 }
2064}
2065
2066/*
Selene Huang4f64c222021-04-13 19:54:36 -07002067 * NewKeyGenerationTest.HmacNoAttestation
2068 *
2069 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2070 * and app id are provided.
2071 */
2072TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2073 auto challenge = "hello";
2074 auto app_id = "foo";
2075
2076 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2077 vector<uint8_t> key_blob;
2078 vector<KeyCharacteristics> key_characteristics;
2079 constexpr size_t key_size = 128;
2080 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2081 .HmacKey(key_size)
2082 .Digest(digest)
2083 .AttestationChallenge(challenge)
2084 .AttestationApplicationId(app_id)
2085 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2086 &key_blob, &key_characteristics));
2087
2088 ASSERT_GT(key_blob.size(), 0U);
2089 ASSERT_EQ(cert_chain_.size(), 0);
2090 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002091 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002092
2093 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2094 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2095 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2096 << "Key size " << key_size << "missing";
2097
2098 CheckedDeleteKey(&key_blob);
2099 }
2100}
2101
2102/*
Qi Wud22ec842020-11-26 13:27:53 +08002103 * NewKeyGenerationTest.LimitedUsageHmac
2104 *
2105 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2106 * resulting keys have correct characteristics.
2107 */
2108TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2109 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2110 vector<uint8_t> key_blob;
2111 vector<KeyCharacteristics> key_characteristics;
2112 constexpr size_t key_size = 128;
2113 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2114 .HmacKey(key_size)
2115 .Digest(digest)
2116 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2117 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2118 &key_blob, &key_characteristics));
2119
2120 ASSERT_GT(key_blob.size(), 0U);
2121 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002122 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002123
2124 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2125 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2126 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2127 << "Key size " << key_size << "missing";
2128
2129 // Check the usage count limit tag appears in the authorizations.
2130 AuthorizationSet auths;
2131 for (auto& entry : key_characteristics) {
2132 auths.push_back(AuthorizationSet(entry.authorizations));
2133 }
2134 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2135 << "key usage count limit " << 1U << " missing";
2136
2137 CheckedDeleteKey(&key_blob);
2138 }
2139}
2140
2141/*
Selene Huang31ab4042020-04-29 04:22:39 -07002142 * NewKeyGenerationTest.HmacCheckKeySizes
2143 *
2144 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2145 */
2146TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2147 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2148 if (key_size < 64 || key_size % 8 != 0) {
2149 // To keep this test from being very slow, we only test a random fraction of
2150 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2151 // them, we expect to run ~40 of them in each run.
2152 if (key_size % 8 == 0 || random() % 10 == 0) {
2153 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2154 GenerateKey(AuthorizationSetBuilder()
2155 .HmacKey(key_size)
2156 .Digest(Digest::SHA_2_256)
2157 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2158 << "HMAC key size " << key_size << " invalid";
2159 }
2160 } else {
2161 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2162 .HmacKey(key_size)
2163 .Digest(Digest::SHA_2_256)
2164 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2165 << "Failed to generate HMAC key of size " << key_size;
2166 CheckedDeleteKey();
2167 }
2168 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002169 if (SecLevel() == SecurityLevel::STRONGBOX) {
2170 // STRONGBOX devices must not support keys larger than 512 bits.
2171 size_t key_size = 520;
2172 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2173 GenerateKey(AuthorizationSetBuilder()
2174 .HmacKey(key_size)
2175 .Digest(Digest::SHA_2_256)
2176 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2177 << "HMAC key size " << key_size << " unexpectedly valid";
2178 }
Selene Huang31ab4042020-04-29 04:22:39 -07002179}
2180
2181/*
2182 * NewKeyGenerationTest.HmacCheckMinMacLengths
2183 *
2184 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2185 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2186 * specific MAC length that failed, so reproducing a failed run will be easy.
2187 */
2188TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2189 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2190 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2191 // To keep this test from being very long, we only test a random fraction of
2192 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2193 // we expect to run ~17 of them in each run.
2194 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2195 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2196 GenerateKey(AuthorizationSetBuilder()
2197 .HmacKey(128)
2198 .Digest(Digest::SHA_2_256)
2199 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2200 << "HMAC min mac length " << min_mac_length << " invalid.";
2201 }
2202 } else {
2203 EXPECT_EQ(ErrorCode::OK,
2204 GenerateKey(AuthorizationSetBuilder()
2205 .HmacKey(128)
2206 .Digest(Digest::SHA_2_256)
2207 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2208 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2209 CheckedDeleteKey();
2210 }
2211 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002212
2213 // Minimum MAC length must be no more than 512 bits.
2214 size_t min_mac_length = 520;
2215 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2216 GenerateKey(AuthorizationSetBuilder()
2217 .HmacKey(128)
2218 .Digest(Digest::SHA_2_256)
2219 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2220 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002221}
2222
2223/*
2224 * NewKeyGenerationTest.HmacMultipleDigests
2225 *
2226 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2227 */
2228TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002229 if (SecLevel() == SecurityLevel::STRONGBOX) {
2230 GTEST_SKIP() << "Test not applicable to StrongBox device";
2231 }
Selene Huang31ab4042020-04-29 04:22:39 -07002232
2233 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2234 GenerateKey(AuthorizationSetBuilder()
2235 .HmacKey(128)
2236 .Digest(Digest::SHA1)
2237 .Digest(Digest::SHA_2_256)
2238 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2239}
2240
2241/*
2242 * NewKeyGenerationTest.HmacDigestNone
2243 *
2244 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2245 */
2246TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2247 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2248 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2249 128)));
2250
2251 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2252 GenerateKey(AuthorizationSetBuilder()
2253 .HmacKey(128)
2254 .Digest(Digest::NONE)
2255 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2256}
2257
Selene Huang4f64c222021-04-13 19:54:36 -07002258/*
2259 * NewKeyGenerationTest.AesNoAttestation
2260 *
2261 * Verifies that attestation parameters to AES keys are ignored and generateKey
2262 * will succeed.
2263 */
2264TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2265 auto challenge = "hello";
2266 auto app_id = "foo";
2267
2268 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2269 .Authorization(TAG_NO_AUTH_REQUIRED)
2270 .AesEncryptionKey(128)
2271 .EcbMode()
2272 .Padding(PaddingMode::PKCS7)
2273 .AttestationChallenge(challenge)
2274 .AttestationApplicationId(app_id)));
2275
2276 ASSERT_EQ(cert_chain_.size(), 0);
2277}
2278
2279/*
2280 * NewKeyGenerationTest.TripleDesNoAttestation
2281 *
2282 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2283 * will be successful. No attestation should be generated.
2284 */
2285TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2286 auto challenge = "hello";
2287 auto app_id = "foo";
2288
2289 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2290 .TripleDesEncryptionKey(168)
2291 .BlockMode(BlockMode::ECB)
2292 .Authorization(TAG_NO_AUTH_REQUIRED)
2293 .Padding(PaddingMode::NONE)
2294 .AttestationChallenge(challenge)
2295 .AttestationApplicationId(app_id)));
2296 ASSERT_EQ(cert_chain_.size(), 0);
2297}
2298
Selene Huang31ab4042020-04-29 04:22:39 -07002299INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2300
2301typedef KeyMintAidlTestBase SigningOperationsTest;
2302
2303/*
2304 * SigningOperationsTest.RsaSuccess
2305 *
2306 * Verifies that raw RSA signature operations succeed.
2307 */
2308TEST_P(SigningOperationsTest, RsaSuccess) {
2309 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2310 .RsaSigningKey(2048, 65537)
2311 .Digest(Digest::NONE)
2312 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002313 .Authorization(TAG_NO_AUTH_REQUIRED)
2314 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002315 string message = "12345678901234567890123456789012";
2316 string signature = SignMessage(
2317 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002318 LocalVerifyMessage(message, signature,
2319 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2320}
2321
2322/*
2323 * SigningOperationsTest.RsaAllPaddingsAndDigests
2324 *
2325 * Verifies RSA signature/verification for all padding modes and digests.
2326 */
2327TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2328 auto authorizations = AuthorizationSetBuilder()
2329 .Authorization(TAG_NO_AUTH_REQUIRED)
2330 .RsaSigningKey(2048, 65537)
2331 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2332 .Padding(PaddingMode::NONE)
2333 .Padding(PaddingMode::RSA_PSS)
2334 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2335 .SetDefaultValidity();
2336
2337 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2338
2339 string message(128, 'a');
2340 string corrupt_message(message);
2341 ++corrupt_message[corrupt_message.size() / 2];
2342
2343 for (auto padding :
2344 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2345 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2346 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2347 // Digesting only makes sense with padding.
2348 continue;
2349 }
2350
2351 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2352 // PSS requires digesting.
2353 continue;
2354 }
2355
2356 string signature =
2357 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2358 LocalVerifyMessage(message, signature,
2359 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2360 }
2361 }
Selene Huang31ab4042020-04-29 04:22:39 -07002362}
2363
2364/*
2365 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2366 *
Shawn Willden7f424372021-01-10 18:06:50 -07002367 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002368 */
2369TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2370 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2371 .Authorization(TAG_NO_AUTH_REQUIRED)
2372 .RsaSigningKey(2048, 65537)
2373 .Digest(Digest::NONE)
2374 .Padding(PaddingMode::NONE)
2375 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002376 .Authorization(TAG_APPLICATION_DATA, "appdata")
2377 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002378
2379 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2380
Selene Huang31ab4042020-04-29 04:22:39 -07002381 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2382 Begin(KeyPurpose::SIGN,
2383 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2384 AbortIfNeeded();
2385 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2386 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2387 .Digest(Digest::NONE)
2388 .Padding(PaddingMode::NONE)
2389 .Authorization(TAG_APPLICATION_ID, "clientid")));
2390 AbortIfNeeded();
2391 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2392 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2393 .Digest(Digest::NONE)
2394 .Padding(PaddingMode::NONE)
2395 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2396 AbortIfNeeded();
2397 EXPECT_EQ(ErrorCode::OK,
2398 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2399 .Digest(Digest::NONE)
2400 .Padding(PaddingMode::NONE)
2401 .Authorization(TAG_APPLICATION_DATA, "appdata")
2402 .Authorization(TAG_APPLICATION_ID, "clientid")));
2403 AbortIfNeeded();
2404}
2405
2406/*
2407 * SigningOperationsTest.RsaPssSha256Success
2408 *
2409 * Verifies that RSA-PSS signature operations succeed.
2410 */
2411TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2412 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2413 .RsaSigningKey(2048, 65537)
2414 .Digest(Digest::SHA_2_256)
2415 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002416 .Authorization(TAG_NO_AUTH_REQUIRED)
2417 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002418 // Use large message, which won't work without digesting.
2419 string message(1024, 'a');
2420 string signature = SignMessage(
2421 message,
2422 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2423}
2424
2425/*
2426 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2427 *
2428 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2429 * supports only unpadded operations.
2430 */
2431TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2432 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2433 .RsaSigningKey(2048, 65537)
2434 .Digest(Digest::NONE)
2435 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002436 .Padding(PaddingMode::NONE)
2437 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002438 string message = "12345678901234567890123456789012";
2439 string signature;
2440
2441 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2442 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2443 .Digest(Digest::NONE)
2444 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2445}
2446
2447/*
2448 * SigningOperationsTest.NoUserConfirmation
2449 *
2450 * Verifies that keymint rejects signing operations for keys with
2451 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2452 * presented.
2453 */
2454TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002455 if (SecLevel() == SecurityLevel::STRONGBOX) {
2456 GTEST_SKIP() << "Test not applicable to StrongBox device";
2457 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002458 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2459 .RsaSigningKey(1024, 65537)
2460 .Digest(Digest::NONE)
2461 .Padding(PaddingMode::NONE)
2462 .Authorization(TAG_NO_AUTH_REQUIRED)
2463 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2464 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002465
2466 const string message = "12345678901234567890123456789012";
2467 EXPECT_EQ(ErrorCode::OK,
2468 Begin(KeyPurpose::SIGN,
2469 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2470 string signature;
2471 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2472}
2473
2474/*
2475 * SigningOperationsTest.RsaPkcs1Sha256Success
2476 *
2477 * Verifies that digested RSA-PKCS1 signature operations succeed.
2478 */
2479TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2480 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2481 .RsaSigningKey(2048, 65537)
2482 .Digest(Digest::SHA_2_256)
2483 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002484 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2485 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002486 string message(1024, 'a');
2487 string signature = SignMessage(message, AuthorizationSetBuilder()
2488 .Digest(Digest::SHA_2_256)
2489 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2490}
2491
2492/*
2493 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2494 *
2495 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2496 */
2497TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2498 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2499 .RsaSigningKey(2048, 65537)
2500 .Digest(Digest::NONE)
2501 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002502 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2503 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002504 string message(53, 'a');
2505 string signature = SignMessage(message, AuthorizationSetBuilder()
2506 .Digest(Digest::NONE)
2507 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2508}
2509
2510/*
2511 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2512 *
2513 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2514 * given a too-long message.
2515 */
2516TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2517 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2518 .RsaSigningKey(2048, 65537)
2519 .Digest(Digest::NONE)
2520 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002521 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2522 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002523 string message(257, 'a');
2524
2525 EXPECT_EQ(ErrorCode::OK,
2526 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2527 .Digest(Digest::NONE)
2528 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2529 string signature;
2530 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2531}
2532
2533/*
2534 * SigningOperationsTest.RsaPssSha512TooSmallKey
2535 *
2536 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2537 * used with a key that is too small for the message.
2538 *
2539 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2540 * keymint specification requires that salt_size == digest_size, so the message will be
2541 * digest_size * 2 +
2542 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2543 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2544 * for a 1024-bit key.
2545 */
2546TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01002547 if (SecLevel() == SecurityLevel::STRONGBOX) {
2548 GTEST_SKIP() << "Test not applicable to StrongBox device";
2549 }
Selene Huang31ab4042020-04-29 04:22:39 -07002550 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2551 .RsaSigningKey(1024, 65537)
2552 .Digest(Digest::SHA_2_512)
2553 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002554 .Padding(PaddingMode::RSA_PSS)
2555 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002556 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2557 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2558 .Digest(Digest::SHA_2_512)
2559 .Padding(PaddingMode::RSA_PSS)));
2560}
2561
2562/*
2563 * SigningOperationsTest.RsaNoPaddingTooLong
2564 *
2565 * Verifies that raw RSA signature operations fail with the correct error code when
2566 * given a too-long message.
2567 */
2568TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2569 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2570 .RsaSigningKey(2048, 65537)
2571 .Digest(Digest::NONE)
2572 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002573 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2574 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002575 // One byte too long
2576 string message(2048 / 8 + 1, 'a');
2577 ASSERT_EQ(ErrorCode::OK,
2578 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2579 .Digest(Digest::NONE)
2580 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2581 string result;
2582 ErrorCode finish_error_code = Finish(message, &result);
2583 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2584 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2585
2586 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2587 message = string(128 * 1024, 'a');
2588 ASSERT_EQ(ErrorCode::OK,
2589 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2590 .Digest(Digest::NONE)
2591 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2592 finish_error_code = Finish(message, &result);
2593 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2594 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2595}
2596
2597/*
2598 * SigningOperationsTest.RsaAbort
2599 *
2600 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2601 * test, but the behavior should be algorithm and purpose-independent.
2602 */
2603TEST_P(SigningOperationsTest, RsaAbort) {
2604 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2605 .RsaSigningKey(2048, 65537)
2606 .Digest(Digest::NONE)
2607 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002608 .Padding(PaddingMode::NONE)
2609 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002610
2611 ASSERT_EQ(ErrorCode::OK,
2612 Begin(KeyPurpose::SIGN,
2613 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2614 EXPECT_EQ(ErrorCode::OK, Abort());
2615
2616 // Another abort should fail
2617 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2618
2619 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002620 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002621}
2622
2623/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002624 * SigningOperationsTest.RsaNonUniqueParams
2625 *
2626 * Verifies that an operation with multiple padding modes is rejected.
2627 */
2628TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2629 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2630 .RsaSigningKey(2048, 65537)
2631 .Digest(Digest::NONE)
2632 .Digest(Digest::SHA1)
2633 .Authorization(TAG_NO_AUTH_REQUIRED)
2634 .Padding(PaddingMode::NONE)
2635 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2636 .SetDefaultValidity()));
2637
2638 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2639 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2640 .Digest(Digest::NONE)
2641 .Padding(PaddingMode::NONE)
2642 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2643
Tommy Chiuc93c4392021-05-11 18:36:50 +08002644 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2645 .Digest(Digest::NONE)
2646 .Digest(Digest::SHA1)
2647 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2648 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002649
2650 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2651 Begin(KeyPurpose::SIGN,
2652 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2653}
2654
2655/*
Selene Huang31ab4042020-04-29 04:22:39 -07002656 * SigningOperationsTest.RsaUnsupportedPadding
2657 *
2658 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2659 * with a padding mode inappropriate for RSA.
2660 */
2661TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2662 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2663 .RsaSigningKey(2048, 65537)
2664 .Authorization(TAG_NO_AUTH_REQUIRED)
2665 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002666 .Padding(PaddingMode::PKCS7)
2667 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002668 ASSERT_EQ(
2669 ErrorCode::UNSUPPORTED_PADDING_MODE,
2670 Begin(KeyPurpose::SIGN,
2671 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002672 CheckedDeleteKey();
2673
2674 ASSERT_EQ(ErrorCode::OK,
2675 GenerateKey(
2676 AuthorizationSetBuilder()
2677 .RsaSigningKey(2048, 65537)
2678 .Authorization(TAG_NO_AUTH_REQUIRED)
2679 .Digest(Digest::SHA_2_256 /* supported digest */)
2680 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2681 .SetDefaultValidity()));
2682 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2683 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2684 .Digest(Digest::SHA_2_256)
2685 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002686}
2687
2688/*
2689 * SigningOperationsTest.RsaPssNoDigest
2690 *
2691 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2692 */
2693TEST_P(SigningOperationsTest, RsaNoDigest) {
2694 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2695 .RsaSigningKey(2048, 65537)
2696 .Authorization(TAG_NO_AUTH_REQUIRED)
2697 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002698 .Padding(PaddingMode::RSA_PSS)
2699 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002700 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2701 Begin(KeyPurpose::SIGN,
2702 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2703
2704 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2705 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2706}
2707
2708/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002709 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002710 *
2711 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2712 * supported in some cases (as validated in other tests), but a mode must be specified.
2713 */
2714TEST_P(SigningOperationsTest, RsaNoPadding) {
2715 // Padding must be specified
2716 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2717 .RsaKey(2048, 65537)
2718 .Authorization(TAG_NO_AUTH_REQUIRED)
2719 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002720 .Digest(Digest::NONE)
2721 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002722 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2723 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2724}
2725
2726/*
2727 * SigningOperationsTest.RsaShortMessage
2728 *
2729 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2730 */
2731TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2732 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2733 .Authorization(TAG_NO_AUTH_REQUIRED)
2734 .RsaSigningKey(2048, 65537)
2735 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002736 .Padding(PaddingMode::NONE)
2737 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002738
2739 // Barely shorter
2740 string message(2048 / 8 - 1, 'a');
2741 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2742
2743 // Much shorter
2744 message = "a";
2745 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2746}
2747
2748/*
2749 * SigningOperationsTest.RsaSignWithEncryptionKey
2750 *
2751 * Verifies that RSA encryption keys cannot be used to sign.
2752 */
2753TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2754 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2755 .Authorization(TAG_NO_AUTH_REQUIRED)
2756 .RsaEncryptionKey(2048, 65537)
2757 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002758 .Padding(PaddingMode::NONE)
2759 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002760 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2761 Begin(KeyPurpose::SIGN,
2762 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2763}
2764
2765/*
2766 * SigningOperationsTest.RsaSignTooLargeMessage
2767 *
2768 * Verifies that attempting a raw signature of a message which is the same length as the key,
2769 * but numerically larger than the public modulus, fails with the correct error.
2770 */
2771TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2772 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2773 .Authorization(TAG_NO_AUTH_REQUIRED)
2774 .RsaSigningKey(2048, 65537)
2775 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002776 .Padding(PaddingMode::NONE)
2777 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002778
2779 // Largest possible message will always be larger than the public modulus.
2780 string message(2048 / 8, static_cast<char>(0xff));
2781 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2782 .Authorization(TAG_NO_AUTH_REQUIRED)
2783 .Digest(Digest::NONE)
2784 .Padding(PaddingMode::NONE)));
2785 string signature;
2786 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2787}
2788
2789/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002790 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2791 *
2792 * Verifies ECDSA signature/verification for all digests and curves.
2793 */
2794TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2795 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2796
2797 string message = "1234567890";
2798 string corrupt_message = "2234567890";
2799 for (auto curve : ValidCurves()) {
2800 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2801 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2802 .Authorization(TAG_NO_AUTH_REQUIRED)
2803 .EcdsaSigningKey(curve)
2804 .Digest(digests)
2805 .SetDefaultValidity());
2806 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2807 if (error != ErrorCode::OK) {
2808 continue;
2809 }
2810
2811 for (auto digest : digests) {
2812 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2813 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2814 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2815 }
2816
2817 auto rc = DeleteKey();
2818 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2819 }
2820}
2821
2822/*
Selene Huang31ab4042020-04-29 04:22:39 -07002823 * SigningOperationsTest.EcdsaAllCurves
2824 *
2825 * Verifies that ECDSA operations succeed with all possible curves.
2826 */
2827TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2828 for (auto curve : ValidCurves()) {
2829 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2830 .Authorization(TAG_NO_AUTH_REQUIRED)
2831 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002832 .Digest(Digest::SHA_2_256)
2833 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002834 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2835 if (error != ErrorCode::OK) continue;
2836
2837 string message(1024, 'a');
2838 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2839 CheckedDeleteKey();
2840 }
2841}
2842
2843/*
2844 * SigningOperationsTest.EcdsaNoDigestHugeData
2845 *
2846 * Verifies that ECDSA operations support very large messages, even without digesting. This
2847 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2848 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2849 * the framework.
2850 */
2851TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2852 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2853 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002854 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002855 .Digest(Digest::NONE)
2856 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002857 string message(1 * 1024, 'a');
2858 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2859}
2860
2861/*
2862 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2863 *
2864 * Verifies that using an EC key requires the correct app ID/data.
2865 */
2866TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2867 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2868 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002869 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002870 .Digest(Digest::NONE)
2871 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002872 .Authorization(TAG_APPLICATION_DATA, "appdata")
2873 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002874
2875 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2876
Selene Huang31ab4042020-04-29 04:22:39 -07002877 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2878 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2879 AbortIfNeeded();
2880 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2881 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2882 .Digest(Digest::NONE)
2883 .Authorization(TAG_APPLICATION_ID, "clientid")));
2884 AbortIfNeeded();
2885 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2886 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2887 .Digest(Digest::NONE)
2888 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2889 AbortIfNeeded();
2890 EXPECT_EQ(ErrorCode::OK,
2891 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2892 .Digest(Digest::NONE)
2893 .Authorization(TAG_APPLICATION_DATA, "appdata")
2894 .Authorization(TAG_APPLICATION_ID, "clientid")));
2895 AbortIfNeeded();
2896}
2897
2898/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002899 * SigningOperationsTest.EcdsaIncompatibleDigest
2900 *
2901 * Verifies that using an EC key requires compatible digest.
2902 */
2903TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2904 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2905 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002906 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002907 .Digest(Digest::NONE)
2908 .Digest(Digest::SHA1)
2909 .SetDefaultValidity()));
2910 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2911 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2912 AbortIfNeeded();
2913}
2914
2915/*
Selene Huang31ab4042020-04-29 04:22:39 -07002916 * SigningOperationsTest.AesEcbSign
2917 *
2918 * Verifies that attempts to use AES keys to sign fail in the correct way.
2919 */
2920TEST_P(SigningOperationsTest, AesEcbSign) {
2921 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2922 .Authorization(TAG_NO_AUTH_REQUIRED)
2923 .SigningKey()
2924 .AesEncryptionKey(128)
2925 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2926
2927 AuthorizationSet out_params;
2928 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2929 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2930 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2931 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2932}
2933
2934/*
2935 * SigningOperationsTest.HmacAllDigests
2936 *
2937 * Verifies that HMAC works with all digests.
2938 */
2939TEST_P(SigningOperationsTest, HmacAllDigests) {
2940 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2941 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2942 .Authorization(TAG_NO_AUTH_REQUIRED)
2943 .HmacKey(128)
2944 .Digest(digest)
2945 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2946 << "Failed to create HMAC key with digest " << digest;
2947 string message = "12345678901234567890123456789012";
2948 string signature = MacMessage(message, digest, 160);
2949 EXPECT_EQ(160U / 8U, signature.size())
2950 << "Failed to sign with HMAC key with digest " << digest;
2951 CheckedDeleteKey();
2952 }
2953}
2954
2955/*
2956 * SigningOperationsTest.HmacSha256TooLargeMacLength
2957 *
2958 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2959 * digest size.
2960 */
2961TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2962 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2963 .Authorization(TAG_NO_AUTH_REQUIRED)
2964 .HmacKey(128)
2965 .Digest(Digest::SHA_2_256)
2966 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2967 AuthorizationSet output_params;
2968 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2969 AuthorizationSetBuilder()
2970 .Digest(Digest::SHA_2_256)
2971 .Authorization(TAG_MAC_LENGTH, 264),
2972 &output_params));
2973}
2974
2975/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002976 * SigningOperationsTest.HmacSha256InvalidMacLength
2977 *
2978 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2979 * not a multiple of 8.
2980 */
2981TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2982 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2983 .Authorization(TAG_NO_AUTH_REQUIRED)
2984 .HmacKey(128)
2985 .Digest(Digest::SHA_2_256)
2986 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2987 AuthorizationSet output_params;
2988 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2989 AuthorizationSetBuilder()
2990 .Digest(Digest::SHA_2_256)
2991 .Authorization(TAG_MAC_LENGTH, 161),
2992 &output_params));
2993}
2994
2995/*
Selene Huang31ab4042020-04-29 04:22:39 -07002996 * SigningOperationsTest.HmacSha256TooSmallMacLength
2997 *
2998 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2999 * specified minimum MAC length.
3000 */
3001TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3002 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3003 .Authorization(TAG_NO_AUTH_REQUIRED)
3004 .HmacKey(128)
3005 .Digest(Digest::SHA_2_256)
3006 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3007 AuthorizationSet output_params;
3008 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3009 AuthorizationSetBuilder()
3010 .Digest(Digest::SHA_2_256)
3011 .Authorization(TAG_MAC_LENGTH, 120),
3012 &output_params));
3013}
3014
3015/*
3016 * SigningOperationsTest.HmacRfc4231TestCase3
3017 *
3018 * Validates against the test vectors from RFC 4231 test case 3.
3019 */
3020TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3021 string key(20, 0xaa);
3022 string message(50, 0xdd);
3023 uint8_t sha_224_expected[] = {
3024 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3025 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3026 };
3027 uint8_t sha_256_expected[] = {
3028 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3029 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3030 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3031 };
3032 uint8_t sha_384_expected[] = {
3033 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3034 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3035 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3036 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3037 };
3038 uint8_t sha_512_expected[] = {
3039 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3040 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3041 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3042 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3043 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3044 };
3045
3046 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3047 if (SecLevel() != SecurityLevel::STRONGBOX) {
3048 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3049 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3050 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3051 }
3052}
3053
3054/*
3055 * SigningOperationsTest.HmacRfc4231TestCase5
3056 *
3057 * Validates against the test vectors from RFC 4231 test case 5.
3058 */
3059TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3060 string key(20, 0x0c);
3061 string message = "Test With Truncation";
3062
3063 uint8_t sha_224_expected[] = {
3064 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3065 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3066 };
3067 uint8_t sha_256_expected[] = {
3068 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3069 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3070 };
3071 uint8_t sha_384_expected[] = {
3072 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3073 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3074 };
3075 uint8_t sha_512_expected[] = {
3076 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3077 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3078 };
3079
3080 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3081 if (SecLevel() != SecurityLevel::STRONGBOX) {
3082 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3083 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3084 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3085 }
3086}
3087
3088INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3089
3090typedef KeyMintAidlTestBase VerificationOperationsTest;
3091
3092/*
Selene Huang31ab4042020-04-29 04:22:39 -07003093 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3094 *
3095 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3096 */
3097TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3098 string key_material = "HelloThisIsAKey";
3099
3100 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003101 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003102 EXPECT_EQ(ErrorCode::OK,
3103 ImportKey(AuthorizationSetBuilder()
3104 .Authorization(TAG_NO_AUTH_REQUIRED)
3105 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3106 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3107 .Digest(Digest::SHA_2_256)
3108 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3109 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3110 EXPECT_EQ(ErrorCode::OK,
3111 ImportKey(AuthorizationSetBuilder()
3112 .Authorization(TAG_NO_AUTH_REQUIRED)
3113 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3114 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3115 .Digest(Digest::SHA_2_256)
3116 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3117 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3118
3119 string message = "This is a message.";
3120 string signature = SignMessage(
3121 signing_key, message,
3122 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3123
3124 // Signing key should not work.
3125 AuthorizationSet out_params;
3126 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3127 Begin(KeyPurpose::VERIFY, signing_key,
3128 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3129
3130 // Verification key should work.
3131 VerifyMessage(verification_key, message, signature,
3132 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3133
3134 CheckedDeleteKey(&signing_key);
3135 CheckedDeleteKey(&verification_key);
3136}
3137
3138INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3139
3140typedef KeyMintAidlTestBase ExportKeyTest;
3141
3142/*
3143 * ExportKeyTest.RsaUnsupportedKeyFormat
3144 *
3145 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3146 */
3147// TODO(seleneh) add ExportKey to GenerateKey
3148// check result
3149
3150class ImportKeyTest : public KeyMintAidlTestBase {
3151 public:
3152 template <TagType tag_type, Tag tag, typename ValueT>
3153 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3154 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003155 for (auto& entry : key_characteristics_) {
3156 if (entry.securityLevel == SecLevel()) {
3157 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3158 << "Tag " << tag << " with value " << expected
3159 << " not found at security level" << entry.securityLevel;
3160 } else {
3161 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3162 << "Tag " << tag << " found at security level " << entry.securityLevel;
3163 }
Selene Huang31ab4042020-04-29 04:22:39 -07003164 }
3165 }
3166
3167 void CheckOrigin() {
3168 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003169 // Origin isn't a crypto param, but it always lives with them.
3170 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003171 }
3172};
3173
3174/*
3175 * ImportKeyTest.RsaSuccess
3176 *
3177 * Verifies that importing and using an RSA key pair works correctly.
3178 */
3179TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003180 uint32_t key_size;
3181 string key;
3182
3183 if (SecLevel() == SecurityLevel::STRONGBOX) {
3184 key_size = 2048;
3185 key = rsa_2048_key;
3186 } else {
3187 key_size = 1024;
3188 key = rsa_key;
3189 }
3190
Selene Huang31ab4042020-04-29 04:22:39 -07003191 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3192 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003193 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003194 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003195 .Padding(PaddingMode::RSA_PSS)
3196 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003197 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003198
3199 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003200 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003201 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3202 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3203 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3204 CheckOrigin();
3205
3206 string message(1024 / 8, 'a');
3207 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3208 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003209 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003210}
3211
3212/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003213 * ImportKeyTest.RsaSuccessWithoutParams
3214 *
3215 * Verifies that importing and using an RSA key pair without specifying parameters
3216 * works correctly.
3217 */
3218TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3219 uint32_t key_size;
3220 string key;
3221
3222 if (SecLevel() == SecurityLevel::STRONGBOX) {
3223 key_size = 2048;
3224 key = rsa_2048_key;
3225 } else {
3226 key_size = 1024;
3227 key = rsa_key;
3228 }
3229
3230 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3231 .Authorization(TAG_NO_AUTH_REQUIRED)
3232 .SigningKey()
3233 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3234 .Digest(Digest::SHA_2_256)
3235 .Padding(PaddingMode::RSA_PSS)
3236 .SetDefaultValidity(),
3237 KeyFormat::PKCS8, key));
3238
3239 // Key size and public exponent are determined from the imported key material.
3240 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3241 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3242
3243 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3244 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3245 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3246 CheckOrigin();
3247
3248 string message(1024 / 8, 'a');
3249 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3250 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003251 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003252}
3253
3254/*
Selene Huang31ab4042020-04-29 04:22:39 -07003255 * ImportKeyTest.RsaKeySizeMismatch
3256 *
3257 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3258 * correct way.
3259 */
3260TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3261 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3262 ImportKey(AuthorizationSetBuilder()
3263 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3264 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003265 .Padding(PaddingMode::NONE)
3266 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003267 KeyFormat::PKCS8, rsa_key));
3268}
3269
3270/*
3271 * ImportKeyTest.RsaPublicExponentMismatch
3272 *
3273 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3274 * fails in the correct way.
3275 */
3276TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3277 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3278 ImportKey(AuthorizationSetBuilder()
3279 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3280 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003281 .Padding(PaddingMode::NONE)
3282 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003283 KeyFormat::PKCS8, rsa_key));
3284}
3285
3286/*
David Drysdalee60248c2021-10-04 12:54:13 +01003287 * ImportKeyTest.RsaAttestMultiPurposeFail
3288 *
3289 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3290 */
3291TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
3292 uint32_t key_size = 2048;
3293 string key = rsa_2048_key;
3294
3295 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3296 ImportKey(AuthorizationSetBuilder()
3297 .Authorization(TAG_NO_AUTH_REQUIRED)
3298 .RsaSigningKey(key_size, 65537)
3299 .AttestKey()
3300 .Digest(Digest::SHA_2_256)
3301 .Padding(PaddingMode::RSA_PSS)
3302 .SetDefaultValidity(),
3303 KeyFormat::PKCS8, key));
3304}
3305
3306/*
Selene Huang31ab4042020-04-29 04:22:39 -07003307 * ImportKeyTest.EcdsaSuccess
3308 *
3309 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3310 */
3311TEST_P(ImportKeyTest, EcdsaSuccess) {
3312 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3313 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003314 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003315 .Digest(Digest::SHA_2_256)
3316 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003317 KeyFormat::PKCS8, ec_256_key));
3318
3319 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003320 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3321 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3322
3323 CheckOrigin();
3324
3325 string message(32, 'a');
3326 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3327 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003328 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003329}
3330
3331/*
3332 * ImportKeyTest.EcdsaP256RFC5915Success
3333 *
3334 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3335 * correctly.
3336 */
3337TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3338 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3339 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003340 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003341 .Digest(Digest::SHA_2_256)
3342 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003343 KeyFormat::PKCS8, ec_256_key_rfc5915));
3344
3345 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003346 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3347 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3348
3349 CheckOrigin();
3350
3351 string message(32, 'a');
3352 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3353 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003354 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003355}
3356
3357/*
3358 * ImportKeyTest.EcdsaP256SEC1Success
3359 *
3360 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3361 */
3362TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3363 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3364 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003365 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003366 .Digest(Digest::SHA_2_256)
3367 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003368 KeyFormat::PKCS8, ec_256_key_sec1));
3369
3370 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003371 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3372 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3373
3374 CheckOrigin();
3375
3376 string message(32, 'a');
3377 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3378 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003379 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003380}
3381
3382/*
3383 * ImportKeyTest.Ecdsa521Success
3384 *
3385 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3386 */
3387TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01003388 if (SecLevel() == SecurityLevel::STRONGBOX) {
3389 GTEST_SKIP() << "Test not applicable to StrongBox device";
3390 }
Selene Huang31ab4042020-04-29 04:22:39 -07003391 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3392 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003393 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003394 .Digest(Digest::SHA_2_256)
3395 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003396 KeyFormat::PKCS8, ec_521_key));
3397
3398 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003399 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3400 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3401 CheckOrigin();
3402
3403 string message(32, 'a');
3404 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3405 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003406 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003407}
3408
3409/*
Selene Huang31ab4042020-04-29 04:22:39 -07003410 * ImportKeyTest.EcdsaCurveMismatch
3411 *
3412 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3413 * the correct way.
3414 */
3415TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3416 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3417 ImportKey(AuthorizationSetBuilder()
3418 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003419 .Digest(Digest::NONE)
3420 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003421 KeyFormat::PKCS8, ec_256_key));
3422}
3423
3424/*
David Drysdalee60248c2021-10-04 12:54:13 +01003425 * ImportKeyTest.EcdsaAttestMultiPurposeFail
3426 *
3427 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
3428 */
3429TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
3430 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3431 ImportKey(AuthorizationSetBuilder()
3432 .Authorization(TAG_NO_AUTH_REQUIRED)
3433 .EcdsaSigningKey(EcCurve::P_256)
3434 .AttestKey()
3435 .Digest(Digest::SHA_2_256)
3436 .SetDefaultValidity(),
3437 KeyFormat::PKCS8, ec_256_key));
3438}
3439
3440/*
Selene Huang31ab4042020-04-29 04:22:39 -07003441 * ImportKeyTest.AesSuccess
3442 *
3443 * Verifies that importing and using an AES key works.
3444 */
3445TEST_P(ImportKeyTest, AesSuccess) {
3446 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3447 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3448 .Authorization(TAG_NO_AUTH_REQUIRED)
3449 .AesEncryptionKey(key.size() * 8)
3450 .EcbMode()
3451 .Padding(PaddingMode::PKCS7),
3452 KeyFormat::RAW, key));
3453
3454 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3455 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3456 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3457 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3458 CheckOrigin();
3459
3460 string message = "Hello World!";
3461 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3462 string ciphertext = EncryptMessage(message, params);
3463 string plaintext = DecryptMessage(ciphertext, params);
3464 EXPECT_EQ(message, plaintext);
3465}
3466
3467/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003468 * ImportKeyTest.AesFailure
3469 *
3470 * Verifies that importing an invalid AES key fails.
3471 */
3472TEST_P(ImportKeyTest, AesFailure) {
3473 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3474 uint32_t bitlen = key.size() * 8;
3475 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003476 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003477 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003478 .Authorization(TAG_NO_AUTH_REQUIRED)
3479 .AesEncryptionKey(key_size)
3480 .EcbMode()
3481 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003482 KeyFormat::RAW, key);
3483 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003484 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3485 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003486 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003487
3488 // Explicit key size matches that of the provided key, but it's not a valid size.
3489 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3490 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3491 ImportKey(AuthorizationSetBuilder()
3492 .Authorization(TAG_NO_AUTH_REQUIRED)
3493 .AesEncryptionKey(long_key.size() * 8)
3494 .EcbMode()
3495 .Padding(PaddingMode::PKCS7),
3496 KeyFormat::RAW, long_key));
3497 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3498 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3499 ImportKey(AuthorizationSetBuilder()
3500 .Authorization(TAG_NO_AUTH_REQUIRED)
3501 .AesEncryptionKey(short_key.size() * 8)
3502 .EcbMode()
3503 .Padding(PaddingMode::PKCS7),
3504 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003505}
3506
3507/*
3508 * ImportKeyTest.TripleDesSuccess
3509 *
3510 * Verifies that importing and using a 3DES key works.
3511 */
3512TEST_P(ImportKeyTest, TripleDesSuccess) {
3513 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3514 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3515 .Authorization(TAG_NO_AUTH_REQUIRED)
3516 .TripleDesEncryptionKey(168)
3517 .EcbMode()
3518 .Padding(PaddingMode::PKCS7),
3519 KeyFormat::RAW, key));
3520
3521 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3522 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3523 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3524 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3525 CheckOrigin();
3526
3527 string message = "Hello World!";
3528 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3529 string ciphertext = EncryptMessage(message, params);
3530 string plaintext = DecryptMessage(ciphertext, params);
3531 EXPECT_EQ(message, plaintext);
3532}
3533
3534/*
3535 * ImportKeyTest.TripleDesFailure
3536 *
3537 * Verifies that importing an invalid 3DES key fails.
3538 */
3539TEST_P(ImportKeyTest, TripleDesFailure) {
3540 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003541 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003542 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003543 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003544 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003545 .Authorization(TAG_NO_AUTH_REQUIRED)
3546 .TripleDesEncryptionKey(key_size)
3547 .EcbMode()
3548 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003549 KeyFormat::RAW, key);
3550 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003551 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3552 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003553 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003554 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003555 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003556 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3557 ImportKey(AuthorizationSetBuilder()
3558 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003559 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003560 .EcbMode()
3561 .Padding(PaddingMode::PKCS7),
3562 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003563 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003564 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3565 ImportKey(AuthorizationSetBuilder()
3566 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003567 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003568 .EcbMode()
3569 .Padding(PaddingMode::PKCS7),
3570 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003571}
3572
3573/*
3574 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003575 *
3576 * Verifies that importing and using an HMAC key works.
3577 */
3578TEST_P(ImportKeyTest, HmacKeySuccess) {
3579 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3580 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3581 .Authorization(TAG_NO_AUTH_REQUIRED)
3582 .HmacKey(key.size() * 8)
3583 .Digest(Digest::SHA_2_256)
3584 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3585 KeyFormat::RAW, key));
3586
3587 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3588 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3589 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3590 CheckOrigin();
3591
3592 string message = "Hello World!";
3593 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3594 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3595}
3596
3597INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3598
3599auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003600 // IKeyMintDevice.aidl
3601 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3602 "020100" // INTEGER length 1 value 0x00 (version)
3603 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3604 "934bf94e2aa28a3f83c9f79297250262"
3605 "fbe3276b5a1c91159bbfa3ef8957aac8"
3606 "4b59b30b455a79c2973480823d8b3863"
3607 "c3deef4a8e243590268d80e18751a0e1"
3608 "30f67ce6a1ace9f79b95e097474febc9"
3609 "81195b1d13a69086c0863f66a7b7fdb4"
3610 "8792227b1ac5e2489febdf087ab54864"
3611 "83033a6f001ca5d1ec1e27f5c30f4cec"
3612 "2642074a39ae68aee552e196627a8e3d"
3613 "867e67a8c01b11e75f13cca0a97ab668"
3614 "b50cda07a8ecb7cd8e3dd7009c963653"
3615 "4f6f239cffe1fc8daa466f78b676c711"
3616 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3617 "99b801597d5220e307eaa5bee507fb94"
3618 "d1fa69f9e519b2de315bac92c36f2ea1"
3619 "fa1df4478c0ddedeae8c70e0233cd098"
3620 "040c" // OCTET STRING length 0x0c (initializationVector)
3621 "d796b02c370f1fa4cc0124f1"
3622 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3623 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3624 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3625 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3626 "3106" // SET length 0x06
3627 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3628 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3629 // } end SET
3630 // } end [1]
3631 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3632 "020120" // INTEGER length 1 value 0x20 (AES)
3633 // } end [2]
3634 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3635 "02020100" // INTEGER length 2 value 0x100
3636 // } end [3]
3637 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3638 "3103" // SET length 0x03 {
3639 "020101" // INTEGER length 1 value 0x01 (ECB)
3640 // } end SET
3641 // } end [4]
3642 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3643 "3103" // SET length 0x03 {
3644 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3645 // } end SET
3646 // } end [5]
3647 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3648 // (noAuthRequired)
3649 "0500" // NULL
3650 // } end [503]
3651 // } end SEQUENCE (AuthorizationList)
3652 // } end SEQUENCE (KeyDescription)
3653 "0420" // OCTET STRING length 0x20 (encryptedKey)
3654 "ccd540855f833a5e1480bfd2d36faf3a"
3655 "eee15df5beabe2691bc82dde2a7aa910"
3656 "0410" // OCTET STRING length 0x10 (tag)
3657 "64c9f689c60ff6223ab6e6999e0eb6e5"
3658 // } SEQUENCE (SecureKeyWrapper)
3659);
Selene Huang31ab4042020-04-29 04:22:39 -07003660
3661auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003662 // IKeyMintDevice.aidl
3663 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3664 "020100" // INTEGER length 1 value 0x00 (version)
3665 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3666 "aad93ed5924f283b4bb5526fbe7a1412"
3667 "f9d9749ec30db9062b29e574a8546f33"
3668 "c88732452f5b8e6a391ee76c39ed1712"
3669 "c61d8df6213dec1cffbc17a8c6d04c7b"
3670 "30893d8daa9b2015213e219468215532"
3671 "07f8f9931c4caba23ed3bee28b36947e"
3672 "47f10e0a5c3dc51c988a628daad3e5e1"
3673 "f4005e79c2d5a96c284b4b8d7e4948f3"
3674 "31e5b85dd5a236f85579f3ea1d1b8484"
3675 "87470bdb0ab4f81a12bee42c99fe0df4"
3676 "bee3759453e69ad1d68a809ce06b949f"
3677 "7694a990429b2fe81e066ff43e56a216"
3678 "02db70757922a4bcc23ab89f1e35da77"
3679 "586775f423e519c2ea394caf48a28d0c"
3680 "8020f1dcf6b3a68ec246f615ae96dae9"
3681 "a079b1f6eb959033c1af5c125fd94168"
3682 "040c" // OCTET STRING length 0x0c (initializationVector)
3683 "6d9721d08589581ab49204a3"
3684 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3685 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3686 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3687 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3688 "3106" // SET length 0x06
3689 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3690 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3691 // } end SET
3692 // } end [1]
3693 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3694 "020120" // INTEGER length 1 value 0x20 (AES)
3695 // } end [2]
3696 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3697 "02020100" // INTEGER length 2 value 0x100
3698 // } end [3]
3699 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3700 "3103" // SET length 0x03 {
3701 "020101" // INTEGER length 1 value 0x01 (ECB)
3702 // } end SET
3703 // } end [4]
3704 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3705 "3103" // SET length 0x03 {
3706 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3707 // } end SET
3708 // } end [5]
3709 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3710 // (noAuthRequired)
3711 "0500" // NULL
3712 // } end [503]
3713 // } end SEQUENCE (AuthorizationList)
3714 // } end SEQUENCE (KeyDescription)
3715 "0420" // OCTET STRING length 0x20 (encryptedKey)
3716 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3717 "c20d1f99a9a024a76f35c8e2cab9b68d"
3718 "0410" // OCTET STRING length 0x10 (tag)
3719 "2560c70109ae67c030f00b98b512a670"
3720 // } SEQUENCE (SecureKeyWrapper)
3721);
Selene Huang31ab4042020-04-29 04:22:39 -07003722
3723auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003724 // RFC 5208 s5
3725 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3726 "020100" // INTEGER length 1 value 0x00 (version)
3727 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3728 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3729 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3730 "0500" // NULL (parameters)
3731 // } SEQUENCE (AlgorithmIdentifier)
3732 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3733 // RFC 8017 A.1.2
3734 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3735 "020100" // INTEGER length 1 value 0x00 (version)
3736 "02820101" // INTEGER length 0x0101 (modulus) value...
3737 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3738 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3739 "7b06e673a837313d56b1c725150a3fef" // 0x30
3740 "86acbddc41bb759c2854eae32d35841e" // 0x40
3741 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3742 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3743 "312d7bd5921ffaea1347c157406fef71" // 0x70
3744 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3745 "f4645c11f5c1374c3886427411c44979" // 0x90
3746 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3747 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3748 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3749 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3750 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3751 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3752 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3753 "55" // 0x101
3754 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3755 "02820100" // INTEGER length 0x100 (privateExponent) value...
3756 "431447b6251908112b1ee76f99f3711a" // 0x10
3757 "52b6630960046c2de70de188d833f8b8" // 0x20
3758 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3759 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3760 "e710b630a03adc683b5d2c43080e52be" // 0x50
3761 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3762 "822bccff087d63c940ba8a45f670feb2" // 0x70
3763 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3764 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3765 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3766 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3767 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3768 "52659d5a5ba05b663737a8696281865b" // 0xd0
3769 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3770 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3771 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3772 "028181" // INTEGER length 0x81 (prime1) value...
3773 "00de392e18d682c829266cc3454e1d61" // 0x10
3774 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3775 "ff841be5bac82a164c5970007047b8c5" // 0x30
3776 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3777 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3778 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3779 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3780 "9e91346130748a6e3c124f9149d71c74" // 0x80
3781 "35"
3782 "028181" // INTEGER length 0x81 (prime2) value...
3783 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3784 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3785 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3786 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3787 "9ed39a2d934c880440aed8832f984316" // 0x50
3788 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3789 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3790 "b880677c068e1be936e81288815252a8" // 0x80
3791 "a1"
3792 "028180" // INTEGER length 0x80 (exponent1) value...
3793 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3794 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3795 "5a063212a4f105a3764743e53281988a" // 0x30
3796 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3797 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3798 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3799 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3800 "4719d6e2b9439823719cd08bcd031781" // 0x80
3801 "028181" // INTEGER length 0x81 (exponent2) value...
3802 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3803 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3804 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3805 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3806 "1254186af30b22c10582a8a43e34fe94" // 0x50
3807 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3808 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3809 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3810 "61"
3811 "028181" // INTEGER length 0x81 (coefficient) value...
3812 "00c931617c77829dfb1270502be9195c" // 0x10
3813 "8f2830885f57dba869536811e6864236" // 0x20
3814 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3815 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3816 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3817 "959356210723287b0affcc9f727044d4" // 0x60
3818 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3819 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3820 "22"
3821 // } SEQUENCE
3822 // } SEQUENCE ()
3823);
Selene Huang31ab4042020-04-29 04:22:39 -07003824
3825string zero_masking_key =
3826 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3827string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3828
3829class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3830
3831TEST_P(ImportWrappedKeyTest, Success) {
3832 auto wrapping_key_desc = AuthorizationSetBuilder()
3833 .RsaEncryptionKey(2048, 65537)
3834 .Digest(Digest::SHA_2_256)
3835 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003836 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3837 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003838
3839 ASSERT_EQ(ErrorCode::OK,
3840 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3841 AuthorizationSetBuilder()
3842 .Digest(Digest::SHA_2_256)
3843 .Padding(PaddingMode::RSA_OAEP)));
3844
3845 string message = "Hello World!";
3846 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3847 string ciphertext = EncryptMessage(message, params);
3848 string plaintext = DecryptMessage(ciphertext, params);
3849 EXPECT_EQ(message, plaintext);
3850}
3851
David Drysdaled2cc8c22021-04-15 13:29:45 +01003852/*
3853 * ImportWrappedKeyTest.SuccessSidsIgnored
3854 *
3855 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3856 * include Tag:USER_SECURE_ID.
3857 */
3858TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3859 auto wrapping_key_desc = AuthorizationSetBuilder()
3860 .RsaEncryptionKey(2048, 65537)
3861 .Digest(Digest::SHA_2_256)
3862 .Padding(PaddingMode::RSA_OAEP)
3863 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3864 .SetDefaultValidity();
3865
3866 int64_t password_sid = 42;
3867 int64_t biometric_sid = 24;
3868 ASSERT_EQ(ErrorCode::OK,
3869 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3870 AuthorizationSetBuilder()
3871 .Digest(Digest::SHA_2_256)
3872 .Padding(PaddingMode::RSA_OAEP),
3873 password_sid, biometric_sid));
3874
3875 string message = "Hello World!";
3876 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3877 string ciphertext = EncryptMessage(message, params);
3878 string plaintext = DecryptMessage(ciphertext, params);
3879 EXPECT_EQ(message, plaintext);
3880}
3881
Selene Huang31ab4042020-04-29 04:22:39 -07003882TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3883 auto wrapping_key_desc = AuthorizationSetBuilder()
3884 .RsaEncryptionKey(2048, 65537)
3885 .Digest(Digest::SHA_2_256)
3886 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003887 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3888 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003889
3890 ASSERT_EQ(ErrorCode::OK,
3891 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3892 AuthorizationSetBuilder()
3893 .Digest(Digest::SHA_2_256)
3894 .Padding(PaddingMode::RSA_OAEP)));
3895}
3896
3897TEST_P(ImportWrappedKeyTest, WrongMask) {
3898 auto wrapping_key_desc = AuthorizationSetBuilder()
3899 .RsaEncryptionKey(2048, 65537)
3900 .Digest(Digest::SHA_2_256)
3901 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003902 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3903 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003904
3905 ASSERT_EQ(
3906 ErrorCode::VERIFICATION_FAILED,
3907 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3908 AuthorizationSetBuilder()
3909 .Digest(Digest::SHA_2_256)
3910 .Padding(PaddingMode::RSA_OAEP)));
3911}
3912
3913TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3914 auto wrapping_key_desc = AuthorizationSetBuilder()
3915 .RsaEncryptionKey(2048, 65537)
3916 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003917 .Padding(PaddingMode::RSA_OAEP)
3918 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003919
3920 ASSERT_EQ(
3921 ErrorCode::INCOMPATIBLE_PURPOSE,
3922 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3923 AuthorizationSetBuilder()
3924 .Digest(Digest::SHA_2_256)
3925 .Padding(PaddingMode::RSA_OAEP)));
3926}
3927
David Drysdaled2cc8c22021-04-15 13:29:45 +01003928TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3929 auto wrapping_key_desc = AuthorizationSetBuilder()
3930 .RsaEncryptionKey(2048, 65537)
3931 .Digest(Digest::SHA_2_256)
3932 .Padding(PaddingMode::RSA_PSS)
3933 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3934 .SetDefaultValidity();
3935
3936 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3937 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3938 AuthorizationSetBuilder()
3939 .Digest(Digest::SHA_2_256)
3940 .Padding(PaddingMode::RSA_OAEP)));
3941}
3942
3943TEST_P(ImportWrappedKeyTest, WrongDigest) {
3944 auto wrapping_key_desc = AuthorizationSetBuilder()
3945 .RsaEncryptionKey(2048, 65537)
3946 .Digest(Digest::SHA_2_512)
3947 .Padding(PaddingMode::RSA_OAEP)
3948 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3949 .SetDefaultValidity();
3950
3951 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3952 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3953 AuthorizationSetBuilder()
3954 .Digest(Digest::SHA_2_256)
3955 .Padding(PaddingMode::RSA_OAEP)));
3956}
3957
Selene Huang31ab4042020-04-29 04:22:39 -07003958INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3959
3960typedef KeyMintAidlTestBase EncryptionOperationsTest;
3961
3962/*
3963 * EncryptionOperationsTest.RsaNoPaddingSuccess
3964 *
David Drysdale59cae642021-05-12 13:52:03 +01003965 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003966 */
3967TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003968 for (uint64_t exponent : {3, 65537}) {
3969 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3970 .Authorization(TAG_NO_AUTH_REQUIRED)
3971 .RsaEncryptionKey(2048, exponent)
3972 .Padding(PaddingMode::NONE)
3973 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003974
David Drysdaled2cc8c22021-04-15 13:29:45 +01003975 string message = string(2048 / 8, 'a');
3976 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003977 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003978 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003979
David Drysdale59cae642021-05-12 13:52:03 +01003980 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003981 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003982
David Drysdaled2cc8c22021-04-15 13:29:45 +01003983 // Unpadded RSA is deterministic
3984 EXPECT_EQ(ciphertext1, ciphertext2);
3985
3986 CheckedDeleteKey();
3987 }
Selene Huang31ab4042020-04-29 04:22:39 -07003988}
3989
3990/*
3991 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3992 *
David Drysdale59cae642021-05-12 13:52:03 +01003993 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003994 */
3995TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3996 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3997 .Authorization(TAG_NO_AUTH_REQUIRED)
3998 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003999 .Padding(PaddingMode::NONE)
4000 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004001
4002 string message = "1";
4003 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4004
David Drysdale59cae642021-05-12 13:52:03 +01004005 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004006 EXPECT_EQ(2048U / 8, ciphertext.size());
4007
4008 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4009 string plaintext = DecryptMessage(ciphertext, params);
4010
4011 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004012}
4013
4014/*
Selene Huang31ab4042020-04-29 04:22:39 -07004015 * EncryptionOperationsTest.RsaOaepSuccess
4016 *
David Drysdale59cae642021-05-12 13:52:03 +01004017 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004018 */
4019TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4020 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4021
4022 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01004023 ASSERT_EQ(ErrorCode::OK,
4024 GenerateKey(AuthorizationSetBuilder()
4025 .Authorization(TAG_NO_AUTH_REQUIRED)
4026 .RsaEncryptionKey(key_size, 65537)
4027 .Padding(PaddingMode::RSA_OAEP)
4028 .Digest(digests)
4029 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4030 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004031
4032 string message = "Hello";
4033
4034 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004035 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4036
4037 auto params = AuthorizationSetBuilder()
4038 .Digest(digest)
4039 .Padding(PaddingMode::RSA_OAEP)
4040 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4041 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004042 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4043 EXPECT_EQ(key_size / 8, ciphertext1.size());
4044
David Drysdale59cae642021-05-12 13:52:03 +01004045 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004046 EXPECT_EQ(key_size / 8, ciphertext2.size());
4047
4048 // OAEP randomizes padding so every result should be different (with astronomically high
4049 // probability).
4050 EXPECT_NE(ciphertext1, ciphertext2);
4051
4052 string plaintext1 = DecryptMessage(ciphertext1, params);
4053 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4054 string plaintext2 = DecryptMessage(ciphertext2, params);
4055 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4056
4057 // Decrypting corrupted ciphertext should fail.
4058 size_t offset_to_corrupt = random() % ciphertext1.size();
4059 char corrupt_byte;
4060 do {
4061 corrupt_byte = static_cast<char>(random() % 256);
4062 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4063 ciphertext1[offset_to_corrupt] = corrupt_byte;
4064
4065 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4066 string result;
4067 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4068 EXPECT_EQ(0U, result.size());
4069 }
4070}
4071
4072/*
4073 * EncryptionOperationsTest.RsaOaepInvalidDigest
4074 *
David Drysdale59cae642021-05-12 13:52:03 +01004075 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004076 * without a digest.
4077 */
4078TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4079 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4080 .Authorization(TAG_NO_AUTH_REQUIRED)
4081 .RsaEncryptionKey(2048, 65537)
4082 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004083 .Digest(Digest::NONE)
4084 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004085
4086 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004087 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07004088}
4089
4090/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004091 * EncryptionOperationsTest.RsaOaepInvalidPadding
4092 *
David Drysdale59cae642021-05-12 13:52:03 +01004093 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01004094 * with a padding value that is only suitable for signing/verifying.
4095 */
4096TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
4097 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4098 .Authorization(TAG_NO_AUTH_REQUIRED)
4099 .RsaEncryptionKey(2048, 65537)
4100 .Padding(PaddingMode::RSA_PSS)
4101 .Digest(Digest::NONE)
4102 .SetDefaultValidity()));
4103
4104 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004105 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01004106}
4107
4108/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004109 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07004110 *
David Drysdale59cae642021-05-12 13:52:03 +01004111 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07004112 * with a different digest than was used to encrypt.
4113 */
4114TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01004115 if (SecLevel() == SecurityLevel::STRONGBOX) {
4116 GTEST_SKIP() << "Test not applicable to StrongBox device";
4117 }
Selene Huang31ab4042020-04-29 04:22:39 -07004118
4119 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4120 .Authorization(TAG_NO_AUTH_REQUIRED)
4121 .RsaEncryptionKey(1024, 65537)
4122 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004123 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
4124 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004125 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01004126 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07004127 message,
4128 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
4129
4130 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4131 .Digest(Digest::SHA_2_256)
4132 .Padding(PaddingMode::RSA_OAEP)));
4133 string result;
4134 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
4135 EXPECT_EQ(0U, result.size());
4136}
4137
4138/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004139 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
4140 *
David Drysdale59cae642021-05-12 13:52:03 +01004141 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004142 * digests.
4143 */
4144TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
4145 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4146
4147 size_t key_size = 2048; // Need largish key for SHA-512 test.
4148 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4149 .OaepMGFDigest(digests)
4150 .Authorization(TAG_NO_AUTH_REQUIRED)
4151 .RsaEncryptionKey(key_size, 65537)
4152 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004153 .Digest(Digest::SHA_2_256)
4154 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004155
4156 string message = "Hello";
4157
4158 for (auto digest : digests) {
4159 auto params = AuthorizationSetBuilder()
4160 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
4161 .Digest(Digest::SHA_2_256)
4162 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01004163 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004164 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4165 EXPECT_EQ(key_size / 8, ciphertext1.size());
4166
David Drysdale59cae642021-05-12 13:52:03 +01004167 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004168 EXPECT_EQ(key_size / 8, ciphertext2.size());
4169
4170 // OAEP randomizes padding so every result should be different (with astronomically high
4171 // probability).
4172 EXPECT_NE(ciphertext1, ciphertext2);
4173
4174 string plaintext1 = DecryptMessage(ciphertext1, params);
4175 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4176 string plaintext2 = DecryptMessage(ciphertext2, params);
4177 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4178
4179 // Decrypting corrupted ciphertext should fail.
4180 size_t offset_to_corrupt = random() % ciphertext1.size();
4181 char corrupt_byte;
4182 do {
4183 corrupt_byte = static_cast<char>(random() % 256);
4184 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4185 ciphertext1[offset_to_corrupt] = corrupt_byte;
4186
4187 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4188 string result;
4189 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4190 EXPECT_EQ(0U, result.size());
4191 }
4192}
4193
4194/*
4195 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
4196 *
David Drysdale59cae642021-05-12 13:52:03 +01004197 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004198 * with incompatible MGF digest.
4199 */
4200TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
4201 ASSERT_EQ(ErrorCode::OK,
4202 GenerateKey(AuthorizationSetBuilder()
4203 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4204 .Authorization(TAG_NO_AUTH_REQUIRED)
4205 .RsaEncryptionKey(2048, 65537)
4206 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004207 .Digest(Digest::SHA_2_256)
4208 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004209 string message = "Hello World!";
4210
4211 auto params = AuthorizationSetBuilder()
4212 .Padding(PaddingMode::RSA_OAEP)
4213 .Digest(Digest::SHA_2_256)
4214 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004215 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004216}
4217
4218/*
4219 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4220 *
4221 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4222 * with unsupported MGF digest.
4223 */
4224TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4225 ASSERT_EQ(ErrorCode::OK,
4226 GenerateKey(AuthorizationSetBuilder()
4227 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4228 .Authorization(TAG_NO_AUTH_REQUIRED)
4229 .RsaEncryptionKey(2048, 65537)
4230 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004231 .Digest(Digest::SHA_2_256)
4232 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004233 string message = "Hello World!";
4234
4235 auto params = AuthorizationSetBuilder()
4236 .Padding(PaddingMode::RSA_OAEP)
4237 .Digest(Digest::SHA_2_256)
4238 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004239 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004240}
4241
4242/*
Selene Huang31ab4042020-04-29 04:22:39 -07004243 * EncryptionOperationsTest.RsaPkcs1Success
4244 *
4245 * Verifies that RSA PKCS encryption/decrypts works.
4246 */
4247TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4248 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4249 .Authorization(TAG_NO_AUTH_REQUIRED)
4250 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004251 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4252 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004253
4254 string message = "Hello World!";
4255 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004256 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004257 EXPECT_EQ(2048U / 8, ciphertext1.size());
4258
David Drysdale59cae642021-05-12 13:52:03 +01004259 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004260 EXPECT_EQ(2048U / 8, ciphertext2.size());
4261
4262 // PKCS1 v1.5 randomizes padding so every result should be different.
4263 EXPECT_NE(ciphertext1, ciphertext2);
4264
4265 string plaintext = DecryptMessage(ciphertext1, params);
4266 EXPECT_EQ(message, plaintext);
4267
4268 // Decrypting corrupted ciphertext should fail.
4269 size_t offset_to_corrupt = random() % ciphertext1.size();
4270 char corrupt_byte;
4271 do {
4272 corrupt_byte = static_cast<char>(random() % 256);
4273 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4274 ciphertext1[offset_to_corrupt] = corrupt_byte;
4275
4276 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4277 string result;
4278 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4279 EXPECT_EQ(0U, result.size());
4280}
4281
4282/*
Selene Huang31ab4042020-04-29 04:22:39 -07004283 * EncryptionOperationsTest.EcdsaEncrypt
4284 *
4285 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4286 */
4287TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4288 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4289 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004290 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004291 .Digest(Digest::NONE)
4292 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004293 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4294 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4295 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4296}
4297
4298/*
4299 * EncryptionOperationsTest.HmacEncrypt
4300 *
4301 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4302 */
4303TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4304 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4305 .Authorization(TAG_NO_AUTH_REQUIRED)
4306 .HmacKey(128)
4307 .Digest(Digest::SHA_2_256)
4308 .Padding(PaddingMode::NONE)
4309 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4310 auto params = AuthorizationSetBuilder()
4311 .Digest(Digest::SHA_2_256)
4312 .Padding(PaddingMode::NONE)
4313 .Authorization(TAG_MAC_LENGTH, 128);
4314 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4315 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4316}
4317
4318/*
4319 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4320 *
4321 * Verifies that AES ECB mode works.
4322 */
4323TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4324 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4325 .Authorization(TAG_NO_AUTH_REQUIRED)
4326 .AesEncryptionKey(128)
4327 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4328 .Padding(PaddingMode::NONE)));
4329
4330 ASSERT_GT(key_blob_.size(), 0U);
4331 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4332
4333 // Two-block message.
4334 string message = "12345678901234567890123456789012";
4335 string ciphertext1 = EncryptMessage(message, params);
4336 EXPECT_EQ(message.size(), ciphertext1.size());
4337
4338 string ciphertext2 = EncryptMessage(string(message), params);
4339 EXPECT_EQ(message.size(), ciphertext2.size());
4340
4341 // ECB is deterministic.
4342 EXPECT_EQ(ciphertext1, ciphertext2);
4343
4344 string plaintext = DecryptMessage(ciphertext1, params);
4345 EXPECT_EQ(message, plaintext);
4346}
4347
4348/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004349 * EncryptionOperationsTest.AesEcbUnknownTag
4350 *
4351 * Verifies that AES ECB operations ignore unknown tags.
4352 */
4353TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4354 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4355 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4356 KeyParameter unknown_param;
4357 unknown_param.tag = unknown_tag;
4358
4359 vector<KeyCharacteristics> key_characteristics;
4360 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4361 .Authorization(TAG_NO_AUTH_REQUIRED)
4362 .AesEncryptionKey(128)
4363 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4364 .Padding(PaddingMode::NONE)
4365 .Authorization(unknown_param),
4366 &key_blob_, &key_characteristics));
4367 ASSERT_GT(key_blob_.size(), 0U);
4368
4369 // Unknown tags should not be returned in key characteristics.
4370 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4371 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4372 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4373 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4374
4375 // Encrypt without mentioning the unknown parameter.
4376 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4377 string message = "12345678901234567890123456789012";
4378 string ciphertext = EncryptMessage(message, params);
4379 EXPECT_EQ(message.size(), ciphertext.size());
4380
4381 // Decrypt including the unknown parameter.
4382 auto decrypt_params = AuthorizationSetBuilder()
4383 .BlockMode(BlockMode::ECB)
4384 .Padding(PaddingMode::NONE)
4385 .Authorization(unknown_param);
4386 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4387 EXPECT_EQ(message, plaintext);
4388}
4389
4390/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004391 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004392 *
4393 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4394 */
4395TEST_P(EncryptionOperationsTest, AesWrongMode) {
4396 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4397 .Authorization(TAG_NO_AUTH_REQUIRED)
4398 .AesEncryptionKey(128)
4399 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4400 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004401 ASSERT_GT(key_blob_.size(), 0U);
4402
Selene Huang31ab4042020-04-29 04:22:39 -07004403 EXPECT_EQ(
4404 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4405 Begin(KeyPurpose::ENCRYPT,
4406 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4407}
4408
4409/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004410 * EncryptionOperationsTest.AesWrongPadding
4411 *
4412 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4413 */
4414TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4415 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4416 .Authorization(TAG_NO_AUTH_REQUIRED)
4417 .AesEncryptionKey(128)
4418 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4419 .Padding(PaddingMode::NONE)));
4420 ASSERT_GT(key_blob_.size(), 0U);
4421
4422 EXPECT_EQ(
4423 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4424 Begin(KeyPurpose::ENCRYPT,
4425 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4426}
4427
4428/*
4429 * EncryptionOperationsTest.AesInvalidParams
4430 *
4431 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4432 */
4433TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4434 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4435 .Authorization(TAG_NO_AUTH_REQUIRED)
4436 .AesEncryptionKey(128)
4437 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4438 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4439 .Padding(PaddingMode::NONE)
4440 .Padding(PaddingMode::PKCS7)));
4441 ASSERT_GT(key_blob_.size(), 0U);
4442
4443 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4444 .BlockMode(BlockMode::CBC)
4445 .BlockMode(BlockMode::ECB)
4446 .Padding(PaddingMode::NONE));
4447 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4448 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4449
4450 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4451 .BlockMode(BlockMode::ECB)
4452 .Padding(PaddingMode::NONE)
4453 .Padding(PaddingMode::PKCS7));
4454 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4455 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4456}
4457
4458/*
Selene Huang31ab4042020-04-29 04:22:39 -07004459 * EncryptionOperationsTest.AesWrongPurpose
4460 *
4461 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4462 * specified.
4463 */
4464TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4465 auto err = GenerateKey(AuthorizationSetBuilder()
4466 .Authorization(TAG_NO_AUTH_REQUIRED)
4467 .AesKey(128)
4468 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4469 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4470 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4471 .Padding(PaddingMode::NONE));
4472 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4473 ASSERT_GT(key_blob_.size(), 0U);
4474
4475 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4476 .BlockMode(BlockMode::GCM)
4477 .Padding(PaddingMode::NONE)
4478 .Authorization(TAG_MAC_LENGTH, 128));
4479 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4480
4481 CheckedDeleteKey();
4482
4483 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4484 .Authorization(TAG_NO_AUTH_REQUIRED)
4485 .AesKey(128)
4486 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4487 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4488 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4489 .Padding(PaddingMode::NONE)));
4490
4491 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4492 .BlockMode(BlockMode::GCM)
4493 .Padding(PaddingMode::NONE)
4494 .Authorization(TAG_MAC_LENGTH, 128));
4495 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4496}
4497
4498/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004499 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004500 *
4501 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4502 * multiple of the block size and no padding is specified.
4503 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004504TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4505 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4506 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4507 .Authorization(TAG_NO_AUTH_REQUIRED)
4508 .AesEncryptionKey(128)
4509 .Authorization(TAG_BLOCK_MODE, blockMode)
4510 .Padding(PaddingMode::NONE)));
4511 // Message is slightly shorter than two blocks.
4512 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004513
David Drysdaled2cc8c22021-04-15 13:29:45 +01004514 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4515 AuthorizationSet out_params;
4516 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4517 string ciphertext;
4518 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4519 EXPECT_EQ(0U, ciphertext.size());
4520
4521 CheckedDeleteKey();
4522 }
Selene Huang31ab4042020-04-29 04:22:39 -07004523}
4524
4525/*
4526 * EncryptionOperationsTest.AesEcbPkcs7Padding
4527 *
4528 * Verifies that AES PKCS7 padding works for any message length.
4529 */
4530TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4531 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4532 .Authorization(TAG_NO_AUTH_REQUIRED)
4533 .AesEncryptionKey(128)
4534 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4535 .Padding(PaddingMode::PKCS7)));
4536
4537 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4538
4539 // Try various message lengths; all should work.
4540 for (size_t i = 0; i < 32; ++i) {
4541 string message(i, 'a');
4542 string ciphertext = EncryptMessage(message, params);
4543 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4544 string plaintext = DecryptMessage(ciphertext, params);
4545 EXPECT_EQ(message, plaintext);
4546 }
4547}
4548
4549/*
4550 * EncryptionOperationsTest.AesEcbWrongPadding
4551 *
4552 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4553 * specified.
4554 */
4555TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4556 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4557 .Authorization(TAG_NO_AUTH_REQUIRED)
4558 .AesEncryptionKey(128)
4559 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4560 .Padding(PaddingMode::NONE)));
4561
4562 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4563
4564 // Try various message lengths; all should fail
4565 for (size_t i = 0; i < 32; ++i) {
4566 string message(i, 'a');
4567 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4568 }
4569}
4570
4571/*
4572 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4573 *
4574 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4575 */
4576TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4577 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4578 .Authorization(TAG_NO_AUTH_REQUIRED)
4579 .AesEncryptionKey(128)
4580 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4581 .Padding(PaddingMode::PKCS7)));
4582
4583 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4584
4585 string message = "a";
4586 string ciphertext = EncryptMessage(message, params);
4587 EXPECT_EQ(16U, ciphertext.size());
4588 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07004589
Seth Moore7a55ae32021-06-23 14:28:11 -07004590 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
4591 ++ciphertext[ciphertext.size() / 2];
4592
4593 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4594 string plaintext;
4595 ErrorCode error = Finish(message, &plaintext);
4596 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
4597 // This is the expected error, we can exit the test now.
4598 return;
4599 } else {
4600 // Very small chance we got valid decryption, so try again.
4601 ASSERT_EQ(error, ErrorCode::OK);
4602 }
4603 }
4604 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07004605}
4606
4607vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4608 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004609 EXPECT_TRUE(iv);
4610 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004611}
4612
4613/*
4614 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4615 *
4616 * Verifies that AES CTR mode works.
4617 */
4618TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4619 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4620 .Authorization(TAG_NO_AUTH_REQUIRED)
4621 .AesEncryptionKey(128)
4622 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4623 .Padding(PaddingMode::NONE)));
4624
4625 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4626
4627 string message = "123";
4628 AuthorizationSet out_params;
4629 string ciphertext1 = EncryptMessage(message, params, &out_params);
4630 vector<uint8_t> iv1 = CopyIv(out_params);
4631 EXPECT_EQ(16U, iv1.size());
4632
4633 EXPECT_EQ(message.size(), ciphertext1.size());
4634
4635 out_params.Clear();
4636 string ciphertext2 = EncryptMessage(message, params, &out_params);
4637 vector<uint8_t> iv2 = CopyIv(out_params);
4638 EXPECT_EQ(16U, iv2.size());
4639
4640 // IVs should be random, so ciphertexts should differ.
4641 EXPECT_NE(ciphertext1, ciphertext2);
4642
4643 auto params_iv1 =
4644 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4645 auto params_iv2 =
4646 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4647
4648 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4649 EXPECT_EQ(message, plaintext);
4650 plaintext = DecryptMessage(ciphertext2, params_iv2);
4651 EXPECT_EQ(message, plaintext);
4652
4653 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4654 plaintext = DecryptMessage(ciphertext1, params_iv2);
4655 EXPECT_NE(message, plaintext);
4656 plaintext = DecryptMessage(ciphertext2, params_iv1);
4657 EXPECT_NE(message, plaintext);
4658}
4659
4660/*
4661 * EncryptionOperationsTest.AesIncremental
4662 *
4663 * Verifies that AES works, all modes, when provided data in various size increments.
4664 */
4665TEST_P(EncryptionOperationsTest, AesIncremental) {
4666 auto block_modes = {
4667 BlockMode::ECB,
4668 BlockMode::CBC,
4669 BlockMode::CTR,
4670 BlockMode::GCM,
4671 };
4672
4673 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4674 .Authorization(TAG_NO_AUTH_REQUIRED)
4675 .AesEncryptionKey(128)
4676 .BlockMode(block_modes)
4677 .Padding(PaddingMode::NONE)
4678 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4679
4680 for (int increment = 1; increment <= 240; ++increment) {
4681 for (auto block_mode : block_modes) {
4682 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004683 auto params =
4684 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4685 if (block_mode == BlockMode::GCM) {
4686 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4687 }
Selene Huang31ab4042020-04-29 04:22:39 -07004688
4689 AuthorizationSet output_params;
4690 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4691
4692 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004693 string to_send;
4694 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004695 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004696 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004697 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4698 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004699
4700 switch (block_mode) {
4701 case BlockMode::GCM:
4702 EXPECT_EQ(message.size() + 16, ciphertext.size());
4703 break;
4704 case BlockMode::CTR:
4705 EXPECT_EQ(message.size(), ciphertext.size());
4706 break;
4707 case BlockMode::CBC:
4708 case BlockMode::ECB:
4709 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4710 break;
4711 }
4712
4713 auto iv = output_params.GetTagValue(TAG_NONCE);
4714 switch (block_mode) {
4715 case BlockMode::CBC:
4716 case BlockMode::GCM:
4717 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004718 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4719 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4720 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004721 break;
4722
4723 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004724 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004725 break;
4726 }
4727
4728 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4729 << "Decrypt begin() failed for block mode " << block_mode;
4730
4731 string plaintext;
4732 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004733 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004734 }
4735 ErrorCode error = Finish(to_send, &plaintext);
4736 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4737 << " and increment " << increment;
4738 if (error == ErrorCode::OK) {
4739 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4740 << block_mode << " and increment " << increment;
4741 }
4742 }
4743 }
4744}
4745
4746struct AesCtrSp80038aTestVector {
4747 const char* key;
4748 const char* nonce;
4749 const char* plaintext;
4750 const char* ciphertext;
4751};
4752
4753// These test vectors are taken from
4754// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4755static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4756 // AES-128
4757 {
4758 "2b7e151628aed2a6abf7158809cf4f3c",
4759 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4760 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4761 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4762 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4763 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4764 },
4765 // AES-192
4766 {
4767 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4768 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4769 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4770 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4771 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4772 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4773 },
4774 // AES-256
4775 {
4776 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4777 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4778 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4779 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4780 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4781 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4782 },
4783};
4784
4785/*
4786 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4787 *
4788 * Verifies AES CTR implementation against SP800-38A test vectors.
4789 */
4790TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4791 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4792 for (size_t i = 0; i < 3; i++) {
4793 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4794 const string key = hex2str(test.key);
4795 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4796 InvalidSizes.end())
4797 continue;
4798 const string nonce = hex2str(test.nonce);
4799 const string plaintext = hex2str(test.plaintext);
4800 const string ciphertext = hex2str(test.ciphertext);
4801 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4802 }
4803}
4804
4805/*
4806 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4807 *
4808 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4809 */
4810TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4811 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4812 .Authorization(TAG_NO_AUTH_REQUIRED)
4813 .AesEncryptionKey(128)
4814 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4815 .Padding(PaddingMode::PKCS7)));
4816 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4817 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4818}
4819
4820/*
4821 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4822 *
4823 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4824 */
4825TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4826 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4827 .Authorization(TAG_NO_AUTH_REQUIRED)
4828 .AesEncryptionKey(128)
4829 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4830 .Authorization(TAG_CALLER_NONCE)
4831 .Padding(PaddingMode::NONE)));
4832
4833 auto params = AuthorizationSetBuilder()
4834 .BlockMode(BlockMode::CTR)
4835 .Padding(PaddingMode::NONE)
4836 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4837 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4838
4839 params = AuthorizationSetBuilder()
4840 .BlockMode(BlockMode::CTR)
4841 .Padding(PaddingMode::NONE)
4842 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4843 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4844
4845 params = AuthorizationSetBuilder()
4846 .BlockMode(BlockMode::CTR)
4847 .Padding(PaddingMode::NONE)
4848 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4849 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4850}
4851
4852/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004853 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004854 *
4855 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4856 */
4857TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4858 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4859 .Authorization(TAG_NO_AUTH_REQUIRED)
4860 .AesEncryptionKey(128)
4861 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4862 .Padding(PaddingMode::NONE)));
4863 // Two-block message.
4864 string message = "12345678901234567890123456789012";
4865 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4866 AuthorizationSet out_params;
4867 string ciphertext1 = EncryptMessage(message, params, &out_params);
4868 vector<uint8_t> iv1 = CopyIv(out_params);
4869 EXPECT_EQ(message.size(), ciphertext1.size());
4870
4871 out_params.Clear();
4872
4873 string ciphertext2 = EncryptMessage(message, params, &out_params);
4874 vector<uint8_t> iv2 = CopyIv(out_params);
4875 EXPECT_EQ(message.size(), ciphertext2.size());
4876
4877 // IVs should be random, so ciphertexts should differ.
4878 EXPECT_NE(ciphertext1, ciphertext2);
4879
4880 params.push_back(TAG_NONCE, iv1);
4881 string plaintext = DecryptMessage(ciphertext1, params);
4882 EXPECT_EQ(message, plaintext);
4883}
4884
4885/*
4886 * EncryptionOperationsTest.AesCallerNonce
4887 *
4888 * Verifies that AES caller-provided nonces work correctly.
4889 */
4890TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4891 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4892 .Authorization(TAG_NO_AUTH_REQUIRED)
4893 .AesEncryptionKey(128)
4894 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4895 .Authorization(TAG_CALLER_NONCE)
4896 .Padding(PaddingMode::NONE)));
4897
4898 string message = "12345678901234567890123456789012";
4899
4900 // Don't specify nonce, should get a random one.
4901 AuthorizationSetBuilder params =
4902 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4903 AuthorizationSet out_params;
4904 string ciphertext = EncryptMessage(message, params, &out_params);
4905 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004906 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004907
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004908 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004909 string plaintext = DecryptMessage(ciphertext, params);
4910 EXPECT_EQ(message, plaintext);
4911
4912 // Now specify a nonce, should also work.
4913 params = AuthorizationSetBuilder()
4914 .BlockMode(BlockMode::CBC)
4915 .Padding(PaddingMode::NONE)
4916 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4917 out_params.Clear();
4918 ciphertext = EncryptMessage(message, params, &out_params);
4919
4920 // Decrypt with correct nonce.
4921 plaintext = DecryptMessage(ciphertext, params);
4922 EXPECT_EQ(message, plaintext);
4923
4924 // Try with wrong nonce.
4925 params = AuthorizationSetBuilder()
4926 .BlockMode(BlockMode::CBC)
4927 .Padding(PaddingMode::NONE)
4928 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4929 plaintext = DecryptMessage(ciphertext, params);
4930 EXPECT_NE(message, plaintext);
4931}
4932
4933/*
4934 * EncryptionOperationsTest.AesCallerNonceProhibited
4935 *
4936 * Verifies that caller-provided nonces are not permitted when not specified in the key
4937 * authorizations.
4938 */
4939TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4940 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4941 .Authorization(TAG_NO_AUTH_REQUIRED)
4942 .AesEncryptionKey(128)
4943 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4944 .Padding(PaddingMode::NONE)));
4945
4946 string message = "12345678901234567890123456789012";
4947
4948 // Don't specify nonce, should get a random one.
4949 AuthorizationSetBuilder params =
4950 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4951 AuthorizationSet out_params;
4952 string ciphertext = EncryptMessage(message, params, &out_params);
4953 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004954 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004955
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004956 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004957 string plaintext = DecryptMessage(ciphertext, params);
4958 EXPECT_EQ(message, plaintext);
4959
4960 // Now specify a nonce, should fail
4961 params = AuthorizationSetBuilder()
4962 .BlockMode(BlockMode::CBC)
4963 .Padding(PaddingMode::NONE)
4964 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4965 out_params.Clear();
4966 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4967}
4968
4969/*
4970 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4971 *
4972 * Verifies that AES GCM mode works.
4973 */
4974TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4975 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4976 .Authorization(TAG_NO_AUTH_REQUIRED)
4977 .AesEncryptionKey(128)
4978 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4979 .Padding(PaddingMode::NONE)
4980 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4981
4982 string aad = "foobar";
4983 string message = "123456789012345678901234567890123456";
4984
4985 auto begin_params = AuthorizationSetBuilder()
4986 .BlockMode(BlockMode::GCM)
4987 .Padding(PaddingMode::NONE)
4988 .Authorization(TAG_MAC_LENGTH, 128);
4989
Selene Huang31ab4042020-04-29 04:22:39 -07004990 // Encrypt
4991 AuthorizationSet begin_out_params;
4992 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4993 << "Begin encrypt";
4994 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004995 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4996 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004997 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4998
4999 // Grab nonce
5000 begin_params.push_back(begin_out_params);
5001
5002 // Decrypt.
5003 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07005004 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005005 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005006 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005007 EXPECT_EQ(message.length(), plaintext.length());
5008 EXPECT_EQ(message, plaintext);
5009}
5010
5011/*
5012 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
5013 *
5014 * Verifies that AES GCM mode works, even when there's a long delay
5015 * between operations.
5016 */
5017TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
5018 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5019 .Authorization(TAG_NO_AUTH_REQUIRED)
5020 .AesEncryptionKey(128)
5021 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5022 .Padding(PaddingMode::NONE)
5023 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5024
5025 string aad = "foobar";
5026 string message = "123456789012345678901234567890123456";
5027
5028 auto begin_params = AuthorizationSetBuilder()
5029 .BlockMode(BlockMode::GCM)
5030 .Padding(PaddingMode::NONE)
5031 .Authorization(TAG_MAC_LENGTH, 128);
5032
Selene Huang31ab4042020-04-29 04:22:39 -07005033 // Encrypt
5034 AuthorizationSet begin_out_params;
5035 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5036 << "Begin encrypt";
5037 string ciphertext;
5038 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005039 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005040 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005041 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005042
5043 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5044
5045 // Grab nonce
5046 begin_params.push_back(begin_out_params);
5047
5048 // Decrypt.
5049 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5050 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005051 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005052 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005053 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005054 sleep(5);
5055 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5056 EXPECT_EQ(message.length(), plaintext.length());
5057 EXPECT_EQ(message, plaintext);
5058}
5059
5060/*
5061 * EncryptionOperationsTest.AesGcmDifferentNonces
5062 *
5063 * Verifies that encrypting the same data with different nonces produces different outputs.
5064 */
5065TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
5066 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5067 .Authorization(TAG_NO_AUTH_REQUIRED)
5068 .AesEncryptionKey(128)
5069 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5070 .Padding(PaddingMode::NONE)
5071 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5072 .Authorization(TAG_CALLER_NONCE)));
5073
5074 string aad = "foobar";
5075 string message = "123456789012345678901234567890123456";
5076 string nonce1 = "000000000000";
5077 string nonce2 = "111111111111";
5078 string nonce3 = "222222222222";
5079
5080 string ciphertext1 =
5081 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
5082 string ciphertext2 =
5083 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
5084 string ciphertext3 =
5085 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
5086
5087 ASSERT_NE(ciphertext1, ciphertext2);
5088 ASSERT_NE(ciphertext1, ciphertext3);
5089 ASSERT_NE(ciphertext2, ciphertext3);
5090}
5091
5092/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005093 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
5094 *
5095 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
5096 */
5097TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
5098 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5099 .Authorization(TAG_NO_AUTH_REQUIRED)
5100 .AesEncryptionKey(128)
5101 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5102 .Padding(PaddingMode::NONE)
5103 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5104
5105 string aad = "foobar";
5106 string message = "123456789012345678901234567890123456";
5107
5108 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5109 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5110 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5111
5112 ASSERT_NE(ciphertext1, ciphertext2);
5113 ASSERT_NE(ciphertext1, ciphertext3);
5114 ASSERT_NE(ciphertext2, ciphertext3);
5115}
5116
5117/*
Selene Huang31ab4042020-04-29 04:22:39 -07005118 * EncryptionOperationsTest.AesGcmTooShortTag
5119 *
5120 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
5121 */
5122TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
5123 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5124 .Authorization(TAG_NO_AUTH_REQUIRED)
5125 .AesEncryptionKey(128)
5126 .BlockMode(BlockMode::GCM)
5127 .Padding(PaddingMode::NONE)
5128 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5129 string message = "123456789012345678901234567890123456";
5130 auto params = AuthorizationSetBuilder()
5131 .BlockMode(BlockMode::GCM)
5132 .Padding(PaddingMode::NONE)
5133 .Authorization(TAG_MAC_LENGTH, 96);
5134
5135 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5136}
5137
5138/*
5139 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
5140 *
5141 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
5142 */
5143TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
5144 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5145 .Authorization(TAG_NO_AUTH_REQUIRED)
5146 .AesEncryptionKey(128)
5147 .BlockMode(BlockMode::GCM)
5148 .Padding(PaddingMode::NONE)
5149 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5150 string aad = "foobar";
5151 string message = "123456789012345678901234567890123456";
5152 auto params = AuthorizationSetBuilder()
5153 .BlockMode(BlockMode::GCM)
5154 .Padding(PaddingMode::NONE)
5155 .Authorization(TAG_MAC_LENGTH, 128);
5156
Selene Huang31ab4042020-04-29 04:22:39 -07005157 // Encrypt
5158 AuthorizationSet begin_out_params;
5159 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5160 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005161 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07005162
5163 AuthorizationSet finish_out_params;
5164 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005165 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5166 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005167
5168 params = AuthorizationSetBuilder()
5169 .Authorizations(begin_out_params)
5170 .BlockMode(BlockMode::GCM)
5171 .Padding(PaddingMode::NONE)
5172 .Authorization(TAG_MAC_LENGTH, 96);
5173
5174 // Decrypt.
5175 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
5176}
5177
5178/*
5179 * EncryptionOperationsTest.AesGcmCorruptKey
5180 *
5181 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
5182 */
5183TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
5184 const uint8_t nonce_bytes[] = {
5185 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
5186 };
5187 string nonce = make_string(nonce_bytes);
5188 const uint8_t ciphertext_bytes[] = {
5189 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
5190 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
5191 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
5192 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
5193 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
5194 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
5195 };
5196 string ciphertext = make_string(ciphertext_bytes);
5197
5198 auto params = AuthorizationSetBuilder()
5199 .BlockMode(BlockMode::GCM)
5200 .Padding(PaddingMode::NONE)
5201 .Authorization(TAG_MAC_LENGTH, 128)
5202 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
5203
5204 auto import_params = AuthorizationSetBuilder()
5205 .Authorization(TAG_NO_AUTH_REQUIRED)
5206 .AesEncryptionKey(128)
5207 .BlockMode(BlockMode::GCM)
5208 .Padding(PaddingMode::NONE)
5209 .Authorization(TAG_CALLER_NONCE)
5210 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5211
5212 // Import correct key and decrypt
5213 const uint8_t key_bytes[] = {
5214 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5215 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5216 };
5217 string key = make_string(key_bytes);
5218 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5219 string plaintext = DecryptMessage(ciphertext, params);
5220 CheckedDeleteKey();
5221
5222 // Corrupt key and attempt to decrypt
5223 key[0] = 0;
5224 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5225 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5226 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5227 CheckedDeleteKey();
5228}
5229
5230/*
5231 * EncryptionOperationsTest.AesGcmAadNoData
5232 *
5233 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5234 * encrypt.
5235 */
5236TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5237 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5238 .Authorization(TAG_NO_AUTH_REQUIRED)
5239 .AesEncryptionKey(128)
5240 .BlockMode(BlockMode::GCM)
5241 .Padding(PaddingMode::NONE)
5242 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5243
5244 string aad = "1234567890123456";
5245 auto params = AuthorizationSetBuilder()
5246 .BlockMode(BlockMode::GCM)
5247 .Padding(PaddingMode::NONE)
5248 .Authorization(TAG_MAC_LENGTH, 128);
5249
Selene Huang31ab4042020-04-29 04:22:39 -07005250 // Encrypt
5251 AuthorizationSet begin_out_params;
5252 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5253 string ciphertext;
5254 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005255 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5256 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005257 EXPECT_TRUE(finish_out_params.empty());
5258
5259 // Grab nonce
5260 params.push_back(begin_out_params);
5261
5262 // Decrypt.
5263 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005264 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005265 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005266 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005267
5268 EXPECT_TRUE(finish_out_params.empty());
5269
5270 EXPECT_EQ("", plaintext);
5271}
5272
5273/*
5274 * EncryptionOperationsTest.AesGcmMultiPartAad
5275 *
5276 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5277 * chunks.
5278 */
5279TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5280 const size_t tag_bits = 128;
5281 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5282 .Authorization(TAG_NO_AUTH_REQUIRED)
5283 .AesEncryptionKey(128)
5284 .BlockMode(BlockMode::GCM)
5285 .Padding(PaddingMode::NONE)
5286 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5287
5288 string message = "123456789012345678901234567890123456";
5289 auto begin_params = AuthorizationSetBuilder()
5290 .BlockMode(BlockMode::GCM)
5291 .Padding(PaddingMode::NONE)
5292 .Authorization(TAG_MAC_LENGTH, tag_bits);
5293 AuthorizationSet begin_out_params;
5294
Selene Huang31ab4042020-04-29 04:22:39 -07005295 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5296
5297 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005298 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5299 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005300 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005301 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5302 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005303
Selene Huang31ab4042020-04-29 04:22:39 -07005304 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005305 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005306
5307 // Grab nonce.
5308 begin_params.push_back(begin_out_params);
5309
5310 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005311 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005312 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005313 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005314 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005315 EXPECT_EQ(message, plaintext);
5316}
5317
5318/*
5319 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5320 *
5321 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5322 */
5323TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5324 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5325 .Authorization(TAG_NO_AUTH_REQUIRED)
5326 .AesEncryptionKey(128)
5327 .BlockMode(BlockMode::GCM)
5328 .Padding(PaddingMode::NONE)
5329 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5330
5331 string message = "123456789012345678901234567890123456";
5332 auto begin_params = AuthorizationSetBuilder()
5333 .BlockMode(BlockMode::GCM)
5334 .Padding(PaddingMode::NONE)
5335 .Authorization(TAG_MAC_LENGTH, 128);
5336 AuthorizationSet begin_out_params;
5337
Selene Huang31ab4042020-04-29 04:22:39 -07005338 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5339
Shawn Willden92d79c02021-02-19 07:31:55 -07005340 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005341 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005342 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5343 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005344
David Drysdaled2cc8c22021-04-15 13:29:45 +01005345 // The failure should have already cancelled the operation.
5346 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5347
Shawn Willden92d79c02021-02-19 07:31:55 -07005348 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005349}
5350
5351/*
5352 * EncryptionOperationsTest.AesGcmBadAad
5353 *
5354 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5355 */
5356TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5357 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5358 .Authorization(TAG_NO_AUTH_REQUIRED)
5359 .AesEncryptionKey(128)
5360 .BlockMode(BlockMode::GCM)
5361 .Padding(PaddingMode::NONE)
5362 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5363
5364 string message = "12345678901234567890123456789012";
5365 auto begin_params = AuthorizationSetBuilder()
5366 .BlockMode(BlockMode::GCM)
5367 .Padding(PaddingMode::NONE)
5368 .Authorization(TAG_MAC_LENGTH, 128);
5369
Selene Huang31ab4042020-04-29 04:22:39 -07005370 // Encrypt
5371 AuthorizationSet begin_out_params;
5372 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005373 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005374 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005375 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005376
5377 // Grab nonce
5378 begin_params.push_back(begin_out_params);
5379
Selene Huang31ab4042020-04-29 04:22:39 -07005380 // Decrypt.
5381 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005382 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005383 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005384 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005385}
5386
5387/*
5388 * EncryptionOperationsTest.AesGcmWrongNonce
5389 *
5390 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5391 */
5392TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5393 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5394 .Authorization(TAG_NO_AUTH_REQUIRED)
5395 .AesEncryptionKey(128)
5396 .BlockMode(BlockMode::GCM)
5397 .Padding(PaddingMode::NONE)
5398 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5399
5400 string message = "12345678901234567890123456789012";
5401 auto begin_params = AuthorizationSetBuilder()
5402 .BlockMode(BlockMode::GCM)
5403 .Padding(PaddingMode::NONE)
5404 .Authorization(TAG_MAC_LENGTH, 128);
5405
Selene Huang31ab4042020-04-29 04:22:39 -07005406 // Encrypt
5407 AuthorizationSet begin_out_params;
5408 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005409 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005410 string ciphertext;
5411 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005412 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005413
5414 // Wrong nonce
5415 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5416
5417 // Decrypt.
5418 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005419 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005420 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005421 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005422
5423 // With wrong nonce, should have gotten garbage plaintext (or none).
5424 EXPECT_NE(message, plaintext);
5425}
5426
5427/*
5428 * EncryptionOperationsTest.AesGcmCorruptTag
5429 *
5430 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5431 */
5432TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5433 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5434 .Authorization(TAG_NO_AUTH_REQUIRED)
5435 .AesEncryptionKey(128)
5436 .BlockMode(BlockMode::GCM)
5437 .Padding(PaddingMode::NONE)
5438 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5439
5440 string aad = "1234567890123456";
5441 string message = "123456789012345678901234567890123456";
5442
5443 auto params = AuthorizationSetBuilder()
5444 .BlockMode(BlockMode::GCM)
5445 .Padding(PaddingMode::NONE)
5446 .Authorization(TAG_MAC_LENGTH, 128);
5447
Selene Huang31ab4042020-04-29 04:22:39 -07005448 // Encrypt
5449 AuthorizationSet begin_out_params;
5450 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005451 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005452 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005453 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005454
5455 // Corrupt tag
5456 ++(*ciphertext.rbegin());
5457
5458 // Grab nonce
5459 params.push_back(begin_out_params);
5460
5461 // Decrypt.
5462 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005463 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005464 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005465 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005466}
5467
5468/*
5469 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5470 *
5471 * Verifies that 3DES is basically functional.
5472 */
5473TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5474 auto auths = AuthorizationSetBuilder()
5475 .TripleDesEncryptionKey(168)
5476 .BlockMode(BlockMode::ECB)
5477 .Authorization(TAG_NO_AUTH_REQUIRED)
5478 .Padding(PaddingMode::NONE);
5479
5480 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5481 // Two-block message.
5482 string message = "1234567890123456";
5483 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5484 string ciphertext1 = EncryptMessage(message, inParams);
5485 EXPECT_EQ(message.size(), ciphertext1.size());
5486
5487 string ciphertext2 = EncryptMessage(string(message), inParams);
5488 EXPECT_EQ(message.size(), ciphertext2.size());
5489
5490 // ECB is deterministic.
5491 EXPECT_EQ(ciphertext1, ciphertext2);
5492
5493 string plaintext = DecryptMessage(ciphertext1, inParams);
5494 EXPECT_EQ(message, plaintext);
5495}
5496
5497/*
5498 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5499 *
5500 * Verifies that CBC keys reject ECB usage.
5501 */
5502TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5503 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5504 .TripleDesEncryptionKey(168)
5505 .BlockMode(BlockMode::CBC)
5506 .Authorization(TAG_NO_AUTH_REQUIRED)
5507 .Padding(PaddingMode::NONE)));
5508
5509 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5510 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5511}
5512
5513/*
5514 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5515 *
5516 * Tests ECB mode with PKCS#7 padding, various message sizes.
5517 */
5518TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5519 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5520 .TripleDesEncryptionKey(168)
5521 .BlockMode(BlockMode::ECB)
5522 .Authorization(TAG_NO_AUTH_REQUIRED)
5523 .Padding(PaddingMode::PKCS7)));
5524
5525 for (size_t i = 0; i < 32; ++i) {
5526 string message(i, 'a');
5527 auto inParams =
5528 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5529 string ciphertext = EncryptMessage(message, inParams);
5530 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5531 string plaintext = DecryptMessage(ciphertext, inParams);
5532 EXPECT_EQ(message, plaintext);
5533 }
5534}
5535
5536/*
5537 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5538 *
5539 * Verifies that keys configured for no padding reject PKCS7 padding
5540 */
5541TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5542 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5543 .TripleDesEncryptionKey(168)
5544 .BlockMode(BlockMode::ECB)
5545 .Authorization(TAG_NO_AUTH_REQUIRED)
5546 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005547 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5548 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005549}
5550
5551/*
5552 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5553 *
5554 * Verifies that corrupted padding is detected.
5555 */
5556TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5557 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5558 .TripleDesEncryptionKey(168)
5559 .BlockMode(BlockMode::ECB)
5560 .Authorization(TAG_NO_AUTH_REQUIRED)
5561 .Padding(PaddingMode::PKCS7)));
5562
5563 string message = "a";
5564 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5565 EXPECT_EQ(8U, ciphertext.size());
5566 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005567
5568 AuthorizationSetBuilder begin_params;
5569 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5570 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07005571
5572 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5573 ++ciphertext[ciphertext.size() / 2];
5574
5575 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5576 string plaintext;
5577 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5578 ErrorCode error = Finish(&plaintext);
5579 if (error == ErrorCode::INVALID_ARGUMENT) {
5580 // This is the expected error, we can exit the test now.
5581 return;
5582 } else {
5583 // Very small chance we got valid decryption, so try again.
5584 ASSERT_EQ(error, ErrorCode::OK);
5585 }
5586 }
5587 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005588}
5589
5590struct TripleDesTestVector {
5591 const char* name;
5592 const KeyPurpose purpose;
5593 const BlockMode block_mode;
5594 const PaddingMode padding_mode;
5595 const char* key;
5596 const char* iv;
5597 const char* input;
5598 const char* output;
5599};
5600
5601// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5602// of the NIST vectors are multiples of the block size.
5603static const TripleDesTestVector kTripleDesTestVectors[] = {
5604 {
5605 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5606 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5607 "", // IV
5608 "329d86bdf1bc5af4", // input
5609 "d946c2756d78633f", // output
5610 },
5611 {
5612 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5613 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5614 "", // IV
5615 "6b1540781b01ce1997adae102dbf3c5b", // input
5616 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5617 },
5618 {
5619 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5620 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5621 "", // IV
5622 "6daad94ce08acfe7", // input
5623 "660e7d32dcc90e79", // output
5624 },
5625 {
5626 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5627 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5628 "", // IV
5629 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5630 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5631 },
5632 {
5633 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5634 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5635 "43f791134c5647ba", // IV
5636 "dcc153cef81d6f24", // input
5637 "92538bd8af18d3ba", // output
5638 },
5639 {
5640 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5641 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5642 "c2e999cb6249023c", // IV
5643 "c689aee38a301bb316da75db36f110b5", // input
5644 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5645 },
5646 {
5647 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5648 PaddingMode::PKCS7,
5649 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5650 "c2e999cb6249023c", // IV
5651 "c689aee38a301bb316da75db36f110b500", // input
5652 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5653 },
5654 {
5655 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5656 PaddingMode::PKCS7,
5657 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5658 "c2e999cb6249023c", // IV
5659 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5660 "c689aee38a301bb316da75db36f110b500", // output
5661 },
5662 {
5663 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5664 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5665 "41746c7e442d3681", // IV
5666 "c53a7b0ec40600fe", // input
5667 "d4f00eb455de1034", // output
5668 },
5669 {
5670 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5671 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5672 "3982bc02c3727d45", // IV
5673 "6006f10adef52991fcc777a1238bbb65", // input
5674 "edae09288e9e3bc05746d872b48e3b29", // output
5675 },
5676};
5677
5678/*
5679 * EncryptionOperationsTest.TripleDesTestVector
5680 *
5681 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5682 */
5683TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5684 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5685 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5686 SCOPED_TRACE(test->name);
5687 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5688 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5689 hex2str(test->output));
5690 }
5691}
5692
5693/*
5694 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5695 *
5696 * Validates CBC mode functionality.
5697 */
5698TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5699 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5700 .TripleDesEncryptionKey(168)
5701 .BlockMode(BlockMode::CBC)
5702 .Authorization(TAG_NO_AUTH_REQUIRED)
5703 .Padding(PaddingMode::NONE)));
5704
5705 ASSERT_GT(key_blob_.size(), 0U);
5706
5707 // Two-block message.
5708 string message = "1234567890123456";
5709 vector<uint8_t> iv1;
5710 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5711 EXPECT_EQ(message.size(), ciphertext1.size());
5712
5713 vector<uint8_t> iv2;
5714 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5715 EXPECT_EQ(message.size(), ciphertext2.size());
5716
5717 // IVs should be random, so ciphertexts should differ.
5718 EXPECT_NE(iv1, iv2);
5719 EXPECT_NE(ciphertext1, ciphertext2);
5720
5721 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5722 EXPECT_EQ(message, plaintext);
5723}
5724
5725/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005726 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5727 *
5728 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5729 */
5730TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5731 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5732 .TripleDesEncryptionKey(168)
5733 .BlockMode(BlockMode::CBC)
5734 .Authorization(TAG_NO_AUTH_REQUIRED)
5735 .Authorization(TAG_CALLER_NONCE)
5736 .Padding(PaddingMode::NONE)));
5737 auto params = AuthorizationSetBuilder()
5738 .BlockMode(BlockMode::CBC)
5739 .Padding(PaddingMode::NONE)
5740 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5741 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5742}
5743
5744/*
Selene Huang31ab4042020-04-29 04:22:39 -07005745 * EncryptionOperationsTest.TripleDesCallerIv
5746 *
5747 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5748 */
5749TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5750 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5751 .TripleDesEncryptionKey(168)
5752 .BlockMode(BlockMode::CBC)
5753 .Authorization(TAG_NO_AUTH_REQUIRED)
5754 .Authorization(TAG_CALLER_NONCE)
5755 .Padding(PaddingMode::NONE)));
5756 string message = "1234567890123456";
5757 vector<uint8_t> iv;
5758 // Don't specify IV, should get a random one.
5759 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5760 EXPECT_EQ(message.size(), ciphertext1.size());
5761 EXPECT_EQ(8U, iv.size());
5762
5763 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5764 EXPECT_EQ(message, plaintext);
5765
5766 // Now specify an IV, should also work.
5767 iv = AidlBuf("abcdefgh");
5768 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5769
5770 // Decrypt with correct IV.
5771 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5772 EXPECT_EQ(message, plaintext);
5773
5774 // Now try with wrong IV.
5775 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5776 EXPECT_NE(message, plaintext);
5777}
5778
5779/*
5780 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5781 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005782 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005783 */
5784TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5785 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5786 .TripleDesEncryptionKey(168)
5787 .BlockMode(BlockMode::CBC)
5788 .Authorization(TAG_NO_AUTH_REQUIRED)
5789 .Padding(PaddingMode::NONE)));
5790
5791 string message = "12345678901234567890123456789012";
5792 vector<uint8_t> iv;
5793 // Don't specify nonce, should get a random one.
5794 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5795 EXPECT_EQ(message.size(), ciphertext1.size());
5796 EXPECT_EQ(8U, iv.size());
5797
5798 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5799 EXPECT_EQ(message, plaintext);
5800
5801 // Now specify a nonce, should fail.
5802 auto input_params = AuthorizationSetBuilder()
5803 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5804 .BlockMode(BlockMode::CBC)
5805 .Padding(PaddingMode::NONE);
5806 AuthorizationSet output_params;
5807 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5808 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5809}
5810
5811/*
5812 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5813 *
5814 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5815 */
5816TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5817 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5818 .TripleDesEncryptionKey(168)
5819 .BlockMode(BlockMode::ECB)
5820 .Authorization(TAG_NO_AUTH_REQUIRED)
5821 .Padding(PaddingMode::NONE)));
5822 // Two-block message.
5823 string message = "1234567890123456";
5824 auto begin_params =
5825 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5826 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5827}
5828
5829/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005830 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005831 *
5832 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5833 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005834TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5835 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5836 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5837 .TripleDesEncryptionKey(168)
5838 .BlockMode(blockMode)
5839 .Authorization(TAG_NO_AUTH_REQUIRED)
5840 .Padding(PaddingMode::NONE)));
5841 // Message is slightly shorter than two blocks.
5842 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005843
David Drysdaled2cc8c22021-04-15 13:29:45 +01005844 auto begin_params =
5845 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5846 AuthorizationSet output_params;
5847 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5848 string ciphertext;
5849 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5850
5851 CheckedDeleteKey();
5852 }
Selene Huang31ab4042020-04-29 04:22:39 -07005853}
5854
5855/*
5856 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5857 *
5858 * Verifies that PKCS7 padding works correctly in CBC mode.
5859 */
5860TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5861 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5862 .TripleDesEncryptionKey(168)
5863 .BlockMode(BlockMode::CBC)
5864 .Authorization(TAG_NO_AUTH_REQUIRED)
5865 .Padding(PaddingMode::PKCS7)));
5866
5867 // Try various message lengths; all should work.
5868 for (size_t i = 0; i < 32; ++i) {
5869 string message(i, 'a');
5870 vector<uint8_t> iv;
5871 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5872 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5873 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5874 EXPECT_EQ(message, plaintext);
5875 }
5876}
5877
5878/*
5879 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5880 *
5881 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5882 */
5883TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5884 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5885 .TripleDesEncryptionKey(168)
5886 .BlockMode(BlockMode::CBC)
5887 .Authorization(TAG_NO_AUTH_REQUIRED)
5888 .Padding(PaddingMode::NONE)));
5889
5890 // Try various message lengths; all should fail.
5891 for (size_t i = 0; i < 32; ++i) {
5892 auto begin_params =
5893 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5894 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5895 }
5896}
5897
5898/*
5899 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5900 *
5901 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5902 */
5903TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5904 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5905 .TripleDesEncryptionKey(168)
5906 .BlockMode(BlockMode::CBC)
5907 .Authorization(TAG_NO_AUTH_REQUIRED)
5908 .Padding(PaddingMode::PKCS7)));
5909
5910 string message = "a";
5911 vector<uint8_t> iv;
5912 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5913 EXPECT_EQ(8U, ciphertext.size());
5914 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005915
5916 auto begin_params = AuthorizationSetBuilder()
5917 .BlockMode(BlockMode::CBC)
5918 .Padding(PaddingMode::PKCS7)
5919 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07005920
5921 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5922 ++ciphertext[ciphertext.size() / 2];
5923 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5924 string plaintext;
5925 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5926 ErrorCode error = Finish(&plaintext);
5927 if (error == ErrorCode::INVALID_ARGUMENT) {
5928 // This is the expected error, we can exit the test now.
5929 return;
5930 } else {
5931 // Very small chance we got valid decryption, so try again.
5932 ASSERT_EQ(error, ErrorCode::OK);
5933 }
5934 }
5935 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005936}
5937
5938/*
5939 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5940 *
5941 * Verifies that 3DES CBC works with many different input sizes.
5942 */
5943TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5944 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5945 .TripleDesEncryptionKey(168)
5946 .BlockMode(BlockMode::CBC)
5947 .Authorization(TAG_NO_AUTH_REQUIRED)
5948 .Padding(PaddingMode::NONE)));
5949
5950 int increment = 7;
5951 string message(240, 'a');
5952 AuthorizationSet input_params =
5953 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5954 AuthorizationSet output_params;
5955 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5956
5957 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005958 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005959 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005960 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5961 EXPECT_EQ(message.size(), ciphertext.size());
5962
5963 // Move TAG_NONCE into input_params
5964 input_params = output_params;
5965 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5966 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5967 output_params.Clear();
5968
5969 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5970 string plaintext;
5971 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005972 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005973 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5974 EXPECT_EQ(ciphertext.size(), plaintext.size());
5975 EXPECT_EQ(message, plaintext);
5976}
5977
5978INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5979
5980typedef KeyMintAidlTestBase MaxOperationsTest;
5981
5982/*
5983 * MaxOperationsTest.TestLimitAes
5984 *
5985 * Verifies that the max uses per boot tag works correctly with AES keys.
5986 */
5987TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01005988 if (SecLevel() == SecurityLevel::STRONGBOX) {
5989 GTEST_SKIP() << "Test not applicable to StrongBox device";
5990 }
Selene Huang31ab4042020-04-29 04:22:39 -07005991
5992 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5993 .Authorization(TAG_NO_AUTH_REQUIRED)
5994 .AesEncryptionKey(128)
5995 .EcbMode()
5996 .Padding(PaddingMode::NONE)
5997 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5998
5999 string message = "1234567890123456";
6000
6001 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6002
6003 EncryptMessage(message, params);
6004 EncryptMessage(message, params);
6005 EncryptMessage(message, params);
6006
6007 // Fourth time should fail.
6008 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
6009}
6010
6011/*
Qi Wud22ec842020-11-26 13:27:53 +08006012 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07006013 *
6014 * Verifies that the max uses per boot tag works correctly with RSA keys.
6015 */
6016TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006017 if (SecLevel() == SecurityLevel::STRONGBOX) {
6018 GTEST_SKIP() << "Test not applicable to StrongBox device";
6019 }
Selene Huang31ab4042020-04-29 04:22:39 -07006020
6021 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6022 .Authorization(TAG_NO_AUTH_REQUIRED)
6023 .RsaSigningKey(1024, 65537)
6024 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006025 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6026 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006027
6028 string message = "1234567890123456";
6029
6030 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6031
6032 SignMessage(message, params);
6033 SignMessage(message, params);
6034 SignMessage(message, params);
6035
6036 // Fourth time should fail.
6037 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6038}
6039
6040INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6041
Qi Wud22ec842020-11-26 13:27:53 +08006042typedef KeyMintAidlTestBase UsageCountLimitTest;
6043
6044/*
Qi Wubeefae42021-01-28 23:16:37 +08006045 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006046 *
Qi Wubeefae42021-01-28 23:16:37 +08006047 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006048 */
Qi Wubeefae42021-01-28 23:16:37 +08006049TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006050 if (SecLevel() == SecurityLevel::STRONGBOX) {
6051 GTEST_SKIP() << "Test not applicable to StrongBox device";
6052 }
Qi Wud22ec842020-11-26 13:27:53 +08006053
6054 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6055 .Authorization(TAG_NO_AUTH_REQUIRED)
6056 .AesEncryptionKey(128)
6057 .EcbMode()
6058 .Padding(PaddingMode::NONE)
6059 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
6060
6061 // Check the usage count limit tag appears in the authorizations.
6062 AuthorizationSet auths;
6063 for (auto& entry : key_characteristics_) {
6064 auths.push_back(AuthorizationSet(entry.authorizations));
6065 }
6066 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6067 << "key usage count limit " << 1U << " missing";
6068
6069 string message = "1234567890123456";
6070 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6071
Qi Wubeefae42021-01-28 23:16:37 +08006072 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6073 AuthorizationSet keystore_auths =
6074 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6075
Qi Wud22ec842020-11-26 13:27:53 +08006076 // First usage of AES key should work.
6077 EncryptMessage(message, params);
6078
Qi Wud22ec842020-11-26 13:27:53 +08006079 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6080 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6081 // must be invalidated from secure storage (such as RPMB partition).
6082 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6083 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006084 // Usage count limit tag is enforced by keystore, keymint does nothing.
6085 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08006086 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6087 }
6088}
6089
6090/*
Qi Wubeefae42021-01-28 23:16:37 +08006091 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006092 *
Qi Wubeefae42021-01-28 23:16:37 +08006093 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006094 */
Qi Wubeefae42021-01-28 23:16:37 +08006095TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006096 if (SecLevel() == SecurityLevel::STRONGBOX) {
6097 GTEST_SKIP() << "Test not applicable to StrongBox device";
6098 }
Qi Wubeefae42021-01-28 23:16:37 +08006099
6100 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6101 .Authorization(TAG_NO_AUTH_REQUIRED)
6102 .AesEncryptionKey(128)
6103 .EcbMode()
6104 .Padding(PaddingMode::NONE)
6105 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
6106
6107 // Check the usage count limit tag appears in the authorizations.
6108 AuthorizationSet auths;
6109 for (auto& entry : key_characteristics_) {
6110 auths.push_back(AuthorizationSet(entry.authorizations));
6111 }
6112 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6113 << "key usage count limit " << 3U << " missing";
6114
6115 string message = "1234567890123456";
6116 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6117
6118 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6119 AuthorizationSet keystore_auths =
6120 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6121
6122 EncryptMessage(message, params);
6123 EncryptMessage(message, params);
6124 EncryptMessage(message, params);
6125
6126 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6127 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6128 // must be invalidated from secure storage (such as RPMB partition).
6129 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6130 } else {
6131 // Usage count limit tag is enforced by keystore, keymint does nothing.
6132 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
6133 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6134 }
6135}
6136
6137/*
6138 * UsageCountLimitTest.TestSingleUseRsa
6139 *
6140 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
6141 */
6142TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006143 if (SecLevel() == SecurityLevel::STRONGBOX) {
6144 GTEST_SKIP() << "Test not applicable to StrongBox device";
6145 }
Qi Wud22ec842020-11-26 13:27:53 +08006146
6147 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6148 .Authorization(TAG_NO_AUTH_REQUIRED)
6149 .RsaSigningKey(1024, 65537)
6150 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006151 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6152 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08006153
6154 // Check the usage count limit tag appears in the authorizations.
6155 AuthorizationSet auths;
6156 for (auto& entry : key_characteristics_) {
6157 auths.push_back(AuthorizationSet(entry.authorizations));
6158 }
6159 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6160 << "key usage count limit " << 1U << " missing";
6161
6162 string message = "1234567890123456";
6163 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6164
Qi Wubeefae42021-01-28 23:16:37 +08006165 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6166 AuthorizationSet keystore_auths =
6167 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6168
Qi Wud22ec842020-11-26 13:27:53 +08006169 // First usage of RSA key should work.
6170 SignMessage(message, params);
6171
Qi Wud22ec842020-11-26 13:27:53 +08006172 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6173 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6174 // must be invalidated from secure storage (such as RPMB partition).
6175 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6176 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006177 // Usage count limit tag is enforced by keystore, keymint does nothing.
6178 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
6179 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6180 }
6181}
6182
6183/*
6184 * UsageCountLimitTest.TestLimitUseRsa
6185 *
6186 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
6187 */
6188TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006189 if (SecLevel() == SecurityLevel::STRONGBOX) {
6190 GTEST_SKIP() << "Test not applicable to StrongBox device";
6191 }
Qi Wubeefae42021-01-28 23:16:37 +08006192
6193 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6194 .Authorization(TAG_NO_AUTH_REQUIRED)
6195 .RsaSigningKey(1024, 65537)
6196 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006197 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
6198 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08006199
6200 // Check the usage count limit tag appears in the authorizations.
6201 AuthorizationSet auths;
6202 for (auto& entry : key_characteristics_) {
6203 auths.push_back(AuthorizationSet(entry.authorizations));
6204 }
6205 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6206 << "key usage count limit " << 3U << " missing";
6207
6208 string message = "1234567890123456";
6209 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6210
6211 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6212 AuthorizationSet keystore_auths =
6213 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6214
6215 SignMessage(message, params);
6216 SignMessage(message, params);
6217 SignMessage(message, params);
6218
6219 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6220 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6221 // must be invalidated from secure storage (such as RPMB partition).
6222 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6223 } else {
6224 // Usage count limit tag is enforced by keystore, keymint does nothing.
6225 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006226 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6227 }
6228}
6229
Qi Wu8e727f72021-02-11 02:49:33 +08006230/*
6231 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6232 *
6233 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6234 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6235 * in hardware.
6236 */
6237TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01006238 if (SecLevel() == SecurityLevel::STRONGBOX) {
6239 GTEST_SKIP() << "Test not applicable to StrongBox device";
6240 }
Qi Wu8e727f72021-02-11 02:49:33 +08006241
6242 auto error = GenerateKey(AuthorizationSetBuilder()
6243 .RsaSigningKey(2048, 65537)
6244 .Digest(Digest::NONE)
6245 .Padding(PaddingMode::NONE)
6246 .Authorization(TAG_NO_AUTH_REQUIRED)
6247 .Authorization(TAG_ROLLBACK_RESISTANCE)
6248 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006249 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6250 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08006251 }
David Drysdale513bf122021-10-06 11:53:13 +01006252
6253 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6254 ASSERT_EQ(ErrorCode::OK, error);
6255 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6256 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6257 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6258
6259 // The KeyMint should also enforce single use key in hardware when it supports rollback
6260 // resistance.
6261 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6262 .Authorization(TAG_NO_AUTH_REQUIRED)
6263 .RsaSigningKey(1024, 65537)
6264 .NoDigestOrPadding()
6265 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6266 .SetDefaultValidity()));
6267
6268 // Check the usage count limit tag appears in the hardware authorizations.
6269 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6270 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6271 << "key usage count limit " << 1U << " missing";
6272
6273 string message = "1234567890123456";
6274 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6275
6276 // First usage of RSA key should work.
6277 SignMessage(message, params);
6278
6279 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6280 // must be invalidated from secure storage (such as RPMB partition).
6281 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08006282}
6283
Qi Wud22ec842020-11-26 13:27:53 +08006284INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6285
David Drysdale7de9feb2021-03-05 14:56:19 +00006286typedef KeyMintAidlTestBase GetHardwareInfoTest;
6287
6288TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6289 // Retrieving hardware info should give the same result each time.
6290 KeyMintHardwareInfo info;
6291 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6292 KeyMintHardwareInfo info2;
6293 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6294 EXPECT_EQ(info, info2);
6295}
6296
6297INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6298
Selene Huang31ab4042020-04-29 04:22:39 -07006299typedef KeyMintAidlTestBase AddEntropyTest;
6300
6301/*
6302 * AddEntropyTest.AddEntropy
6303 *
6304 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6305 * is actually added.
6306 */
6307TEST_P(AddEntropyTest, AddEntropy) {
6308 string data = "foo";
6309 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6310}
6311
6312/*
6313 * AddEntropyTest.AddEmptyEntropy
6314 *
6315 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6316 */
6317TEST_P(AddEntropyTest, AddEmptyEntropy) {
6318 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6319}
6320
6321/*
6322 * AddEntropyTest.AddLargeEntropy
6323 *
6324 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6325 */
6326TEST_P(AddEntropyTest, AddLargeEntropy) {
6327 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6328}
6329
David Drysdalebb3d85e2021-04-13 11:15:51 +01006330/*
6331 * AddEntropyTest.AddTooLargeEntropy
6332 *
6333 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6334 */
6335TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6336 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6337 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6338}
6339
Selene Huang31ab4042020-04-29 04:22:39 -07006340INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6341
Selene Huang31ab4042020-04-29 04:22:39 -07006342typedef KeyMintAidlTestBase KeyDeletionTest;
6343
6344/**
6345 * KeyDeletionTest.DeleteKey
6346 *
6347 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6348 * valid key blob.
6349 */
6350TEST_P(KeyDeletionTest, DeleteKey) {
6351 auto error = GenerateKey(AuthorizationSetBuilder()
6352 .RsaSigningKey(2048, 65537)
6353 .Digest(Digest::NONE)
6354 .Padding(PaddingMode::NONE)
6355 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006356 .Authorization(TAG_ROLLBACK_RESISTANCE)
6357 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006358 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6359 GTEST_SKIP() << "Rollback resistance not supported";
6360 }
Selene Huang31ab4042020-04-29 04:22:39 -07006361
6362 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006363 ASSERT_EQ(ErrorCode::OK, error);
6364 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6365 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006366
David Drysdale513bf122021-10-06 11:53:13 +01006367 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07006368
David Drysdale513bf122021-10-06 11:53:13 +01006369 string message = "12345678901234567890123456789012";
6370 AuthorizationSet begin_out_params;
6371 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6372 Begin(KeyPurpose::SIGN, key_blob_,
6373 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6374 &begin_out_params));
6375 AbortIfNeeded();
6376 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006377}
6378
6379/**
6380 * KeyDeletionTest.DeleteInvalidKey
6381 *
6382 * This test checks that the HAL excepts invalid key blobs..
6383 */
6384TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6385 // Generate key just to check if rollback protection is implemented
6386 auto error = GenerateKey(AuthorizationSetBuilder()
6387 .RsaSigningKey(2048, 65537)
6388 .Digest(Digest::NONE)
6389 .Padding(PaddingMode::NONE)
6390 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006391 .Authorization(TAG_ROLLBACK_RESISTANCE)
6392 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006393 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6394 GTEST_SKIP() << "Rollback resistance not supported";
6395 }
Selene Huang31ab4042020-04-29 04:22:39 -07006396
6397 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006398 ASSERT_EQ(ErrorCode::OK, error);
6399 AuthorizationSet enforced(SecLevelAuthorizations());
6400 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006401
David Drysdale513bf122021-10-06 11:53:13 +01006402 // Delete the key we don't care about the result at this point.
6403 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07006404
David Drysdale513bf122021-10-06 11:53:13 +01006405 // Now create an invalid key blob and delete it.
6406 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07006407
David Drysdale513bf122021-10-06 11:53:13 +01006408 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07006409}
6410
6411/**
6412 * KeyDeletionTest.DeleteAllKeys
6413 *
6414 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6415 *
6416 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6417 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6418 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6419 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6420 * credentials stored in Keystore/Keymint.
6421 */
6422TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01006423 if (!arm_deleteAllKeys) {
6424 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
6425 return;
6426 }
Selene Huang31ab4042020-04-29 04:22:39 -07006427 auto error = GenerateKey(AuthorizationSetBuilder()
6428 .RsaSigningKey(2048, 65537)
6429 .Digest(Digest::NONE)
6430 .Padding(PaddingMode::NONE)
6431 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06006432 .Authorization(TAG_ROLLBACK_RESISTANCE)
6433 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01006434 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
6435 GTEST_SKIP() << "Rollback resistance not supported";
6436 }
Selene Huang31ab4042020-04-29 04:22:39 -07006437
6438 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01006439 ASSERT_EQ(ErrorCode::OK, error);
6440 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6441 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006442
David Drysdale513bf122021-10-06 11:53:13 +01006443 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07006444
David Drysdale513bf122021-10-06 11:53:13 +01006445 string message = "12345678901234567890123456789012";
6446 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07006447
David Drysdale513bf122021-10-06 11:53:13 +01006448 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6449 Begin(KeyPurpose::SIGN, key_blob_,
6450 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6451 &begin_out_params));
6452 AbortIfNeeded();
6453 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07006454}
6455
6456INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6457
David Drysdaled2cc8c22021-04-15 13:29:45 +01006458typedef KeyMintAidlTestBase KeyUpgradeTest;
6459
6460/**
6461 * KeyUpgradeTest.UpgradeInvalidKey
6462 *
6463 * This test checks that the HAL excepts invalid key blobs..
6464 */
6465TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6466 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6467
6468 std::vector<uint8_t> new_blob;
6469 Status result = keymint_->upgradeKey(key_blob,
6470 AuthorizationSetBuilder()
6471 .Authorization(TAG_APPLICATION_ID, "clientid")
6472 .Authorization(TAG_APPLICATION_DATA, "appdata")
6473 .vector_data(),
6474 &new_blob);
6475 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6476}
6477
6478INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6479
Selene Huang31ab4042020-04-29 04:22:39 -07006480using UpgradeKeyTest = KeyMintAidlTestBase;
6481
6482/*
6483 * UpgradeKeyTest.UpgradeKey
6484 *
6485 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6486 */
6487TEST_P(UpgradeKeyTest, UpgradeKey) {
6488 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6489 .AesEncryptionKey(128)
6490 .Padding(PaddingMode::NONE)
6491 .Authorization(TAG_NO_AUTH_REQUIRED)));
6492
6493 auto result = UpgradeKey(key_blob_);
6494
6495 // Key doesn't need upgrading. Should get okay, but no new key blob.
6496 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6497}
6498
6499INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6500
6501using ClearOperationsTest = KeyMintAidlTestBase;
6502
6503/*
6504 * ClearSlotsTest.TooManyOperations
6505 *
6506 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6507 * operations are started without being finished or aborted. Also verifies
6508 * that aborting the operations clears the operations.
6509 *
6510 */
6511TEST_P(ClearOperationsTest, TooManyOperations) {
6512 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6513 .Authorization(TAG_NO_AUTH_REQUIRED)
6514 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006515 .Padding(PaddingMode::NONE)
6516 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006517
6518 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6519 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006520 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006521 AuthorizationSet out_params;
6522 ErrorCode result;
6523 size_t i;
6524
6525 for (i = 0; i < max_operations; i++) {
6526 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6527 if (ErrorCode::OK != result) {
6528 break;
6529 }
6530 }
6531 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6532 // Try again just in case there's a weird overflow bug
6533 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6534 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6535 for (size_t j = 0; j < i; j++) {
6536 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6537 << "Aboort failed for i = " << j << std::endl;
6538 }
6539 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6540 AbortIfNeeded();
6541}
6542
6543INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6544
6545typedef KeyMintAidlTestBase TransportLimitTest;
6546
6547/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006548 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006549 *
6550 * Verifies that passing input data to finish succeeds as expected.
6551 */
6552TEST_P(TransportLimitTest, LargeFinishInput) {
6553 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6554 .Authorization(TAG_NO_AUTH_REQUIRED)
6555 .AesEncryptionKey(128)
6556 .BlockMode(BlockMode::ECB)
6557 .Padding(PaddingMode::NONE)));
6558
6559 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6560 auto cipher_params =
6561 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6562
6563 AuthorizationSet out_params;
6564 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6565
6566 string plain_message = std::string(1 << msg_size, 'x');
6567 string encrypted_message;
6568 auto rc = Finish(plain_message, &encrypted_message);
6569
6570 EXPECT_EQ(ErrorCode::OK, rc);
6571 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6572 << "Encrypt finish returned OK, but did not consume all of the given input";
6573 cipher_params.push_back(out_params);
6574
6575 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6576
6577 string decrypted_message;
6578 rc = Finish(encrypted_message, &decrypted_message);
6579 EXPECT_EQ(ErrorCode::OK, rc);
6580 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6581 << "Decrypt finish returned OK, did not consume all of the given input";
6582 }
6583}
6584
6585INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6586
David Zeuthene0c40892021-01-08 12:54:11 -05006587typedef KeyMintAidlTestBase KeyAgreementTest;
6588
6589int CurveToOpenSslCurveName(EcCurve curve) {
6590 switch (curve) {
6591 case EcCurve::P_224:
6592 return NID_secp224r1;
6593 case EcCurve::P_256:
6594 return NID_X9_62_prime256v1;
6595 case EcCurve::P_384:
6596 return NID_secp384r1;
6597 case EcCurve::P_521:
6598 return NID_secp521r1;
6599 }
6600}
6601
6602/*
6603 * KeyAgreementTest.Ecdh
6604 *
6605 * Verifies that ECDH works for all curves
6606 */
6607TEST_P(KeyAgreementTest, Ecdh) {
6608 // Because it's possible to use this API with keys on different curves, we
6609 // check all N^2 combinations where N is the number of supported
6610 // curves.
6611 //
6612 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6613 // lot more curves we can be smart about things and just pick |otherCurve| so
6614 // it's not |curve| and that way we end up with only 2*N runs
6615 //
6616 for (auto curve : ValidCurves()) {
6617 for (auto localCurve : ValidCurves()) {
6618 // Generate EC key locally (with access to private key material)
6619 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6620 int curveName = CurveToOpenSslCurveName(localCurve);
6621 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6622 ASSERT_NE(group, nullptr);
6623 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6624 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6625 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6626 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6627
6628 // Get encoded form of the public part of the locally generated key...
6629 unsigned char* p = nullptr;
6630 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6631 ASSERT_GT(encodedPublicKeySize, 0);
6632 vector<uint8_t> encodedPublicKey(
6633 reinterpret_cast<const uint8_t*>(p),
6634 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6635 OPENSSL_free(p);
6636
6637 // Generate EC key in KeyMint (only access to public key material)
6638 vector<uint8_t> challenge = {0x41, 0x42};
6639 EXPECT_EQ(
6640 ErrorCode::OK,
6641 GenerateKey(AuthorizationSetBuilder()
6642 .Authorization(TAG_NO_AUTH_REQUIRED)
6643 .Authorization(TAG_EC_CURVE, curve)
6644 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6645 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6646 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006647 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6648 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006649 << "Failed to generate key";
6650 ASSERT_GT(cert_chain_.size(), 0);
6651 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6652 ASSERT_NE(kmKeyCert, nullptr);
6653 // Check that keyAgreement (bit 4) is set in KeyUsage
6654 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6655 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6656 ASSERT_NE(kmPkey, nullptr);
6657 if (dump_Attestations) {
6658 for (size_t n = 0; n < cert_chain_.size(); n++) {
6659 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6660 }
6661 }
6662
6663 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6664 if (curve != localCurve) {
6665 // If the keys are using different curves KeyMint should fail with
6666 // ErrorCode:INVALID_ARGUMENT. Check that.
6667 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6668 string ZabFromKeyMintStr;
6669 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6670 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6671 &ZabFromKeyMintStr));
6672
6673 } else {
6674 // Otherwise if the keys are using the same curve, it should work.
6675 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6676 string ZabFromKeyMintStr;
6677 EXPECT_EQ(ErrorCode::OK,
6678 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6679 &ZabFromKeyMintStr));
6680 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6681
6682 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6683 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6684 ASSERT_NE(ctx, nullptr);
6685 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6686 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6687 size_t ZabFromTestLen = 0;
6688 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6689 vector<uint8_t> ZabFromTest;
6690 ZabFromTest.resize(ZabFromTestLen);
6691 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6692
6693 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6694 }
6695
6696 CheckedDeleteKey();
6697 }
6698 }
6699}
6700
6701INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6702
David Drysdaled2cc8c22021-04-15 13:29:45 +01006703using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6704
6705// This is a problematic test, as it can render the device under test permanently unusable.
6706// Re-enable and run at your own risk.
6707TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6708 auto result = DestroyAttestationIds();
6709 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6710}
6711
6712INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6713
Shawn Willdend659c7c2021-02-19 14:51:51 -07006714using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006715
David Drysdaledb0dcf52021-05-18 11:43:31 +01006716/*
6717 * EarlyBootKeyTest.CreateEarlyBootKeys
6718 *
6719 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6720 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006721TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01006722 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006723 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6724 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6725
David Drysdaleadfe6112021-05-27 12:00:53 +01006726 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6727 ASSERT_GT(keyData.blob.size(), 0U);
6728 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6729 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6730 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006731 CheckedDeleteKey(&aesKeyData.blob);
6732 CheckedDeleteKey(&hmacKeyData.blob);
6733 CheckedDeleteKey(&rsaKeyData.blob);
6734 CheckedDeleteKey(&ecdsaKeyData.blob);
6735}
6736
David Drysdaledb0dcf52021-05-18 11:43:31 +01006737/*
David Drysdaleadfe6112021-05-27 12:00:53 +01006738 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6739 *
6740 * Verifies that creating an early boot key with attestation succeeds.
6741 */
6742TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6743 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6744 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6745 builder->AttestationChallenge("challenge");
6746 builder->AttestationApplicationId("app_id");
6747 });
6748
6749 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6750 ASSERT_GT(keyData.blob.size(), 0U);
6751 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6752 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6753 }
6754 CheckedDeleteKey(&aesKeyData.blob);
6755 CheckedDeleteKey(&hmacKeyData.blob);
6756 CheckedDeleteKey(&rsaKeyData.blob);
6757 CheckedDeleteKey(&ecdsaKeyData.blob);
6758}
6759
6760/*
6761 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01006762 *
6763 * Verifies that using early boot keys at a later stage fails.
6764 */
6765TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6766 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6767 .Authorization(TAG_NO_AUTH_REQUIRED)
6768 .Authorization(TAG_EARLY_BOOT_ONLY)
6769 .HmacKey(128)
6770 .Digest(Digest::SHA_2_256)
6771 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6772 AuthorizationSet output_params;
6773 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6774 AuthorizationSetBuilder()
6775 .Digest(Digest::SHA_2_256)
6776 .Authorization(TAG_MAC_LENGTH, 256),
6777 &output_params));
6778}
6779
6780/*
6781 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6782 *
6783 * Verifies that importing early boot keys fails.
6784 */
6785TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6786 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6787 .Authorization(TAG_NO_AUTH_REQUIRED)
6788 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01006789 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01006790 .Digest(Digest::SHA_2_256)
6791 .SetDefaultValidity(),
6792 KeyFormat::PKCS8, ec_256_key));
6793}
6794
David Drysdaled2cc8c22021-04-15 13:29:45 +01006795// 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 +00006796// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6797// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6798// early boot, so you'll have to reboot between runs.
6799TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6800 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6801 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6802 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6803 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6804 EXPECT_TRUE(
6805 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6806 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6807 EXPECT_TRUE(
6808 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6809
6810 // Should be able to use keys, since early boot has not ended
6811 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6812 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6813 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6814 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6815
6816 // End early boot
6817 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6818 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6819
6820 // Should not be able to use already-created keys.
6821 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6822 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6823 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6824 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6825
6826 CheckedDeleteKey(&aesKeyData.blob);
6827 CheckedDeleteKey(&hmacKeyData.blob);
6828 CheckedDeleteKey(&rsaKeyData.blob);
6829 CheckedDeleteKey(&ecdsaKeyData.blob);
6830
6831 // Should not be able to create new keys
6832 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6833 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6834
6835 CheckedDeleteKey(&aesKeyData.blob);
6836 CheckedDeleteKey(&hmacKeyData.blob);
6837 CheckedDeleteKey(&rsaKeyData.blob);
6838 CheckedDeleteKey(&ecdsaKeyData.blob);
6839}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006840
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006841INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6842
Shawn Willdend659c7c2021-02-19 14:51:51 -07006843using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006844
6845// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6846// between runs... and on most test devices there are no enrolled credentials so it can't be
6847// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6848// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6849// a manual test process, which includes unlocking between runs, which is why it's included here.
6850// Well, that and the fact that it's the only test we can do without also making calls into the
6851// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6852// implications might be, so that may or may not be a solution.
6853TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6854 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6855 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6856
6857 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6858 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6859 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6860 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6861
6862 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006863 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006864 ASSERT_EQ(ErrorCode::OK, rc);
6865 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6866 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6867 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6868 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6869
6870 CheckedDeleteKey(&aesKeyData.blob);
6871 CheckedDeleteKey(&hmacKeyData.blob);
6872 CheckedDeleteKey(&rsaKeyData.blob);
6873 CheckedDeleteKey(&ecdsaKeyData.blob);
6874}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006875
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006876INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6877
Janis Danisevskis24c04702020-12-16 18:28:39 -08006878} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006879
6880int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006881 std::cout << "Testing ";
6882 auto halInstances =
6883 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6884 std::cout << "HAL instances:\n";
6885 for (auto& entry : halInstances) {
6886 std::cout << " " << entry << '\n';
6887 }
6888
Selene Huang31ab4042020-04-29 04:22:39 -07006889 ::testing::InitGoogleTest(&argc, argv);
6890 for (int i = 1; i < argc; ++i) {
6891 if (argv[i][0] == '-') {
6892 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006893 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6894 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006895 }
6896 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006897 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6898 dump_Attestations = true;
6899 } else {
6900 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006901 }
6902 }
6903 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006904 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006905}