blob: caac3465b427e061747de674f62db23ce459f465 [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
David Drysdalebb3d85e2021-04-13 11:15:51 +010072bool check_patchLevels = false;
73
Seth Moore7a55ae32021-06-23 14:28:11 -070074// The maximum number of times we'll attempt to verify that corruption
75// of an ecrypted blob results in an error. Retries are necessary as there
76// is a small (roughly 1/256) chance that corrupting ciphertext still results
77// in valid PKCS7 padding.
78constexpr size_t kMaxPaddingCorruptionRetries = 8;
79
Selene Huang31ab4042020-04-29 04:22:39 -070080template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000081bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
82 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070083 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080084 if (auto p = authorizationValue(ttag, param)) {
85 return *p == expected_value;
86 }
87 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070088 });
89 return (it != set.end());
90}
91
92template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000093bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070094 auto it = std::find_if(set.begin(), set.end(),
95 [&](const KeyParameter& param) { return param.tag == tag; });
96 return (it != set.end());
97}
98
99constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
100 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
101 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
102 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
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, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
114 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
115
116string hex2str(string a) {
117 string b;
118 size_t num = a.size() / 2;
119 b.resize(num);
120 for (size_t i = 0; i < num; i++) {
121 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
122 }
123 return b;
124}
125
David Drysdaled2cc8c22021-04-15 13:29:45 +0100126string rsa_key = hex2str(
127 // RFC 5208 s5
128 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
129 "020100" // INTEGER length 1 value 0x00 (version)
130 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
131 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
132 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
133 "0500" // NULL (parameters)
134 // } end SEQUENCE (AlgorithmIdentifier)
135 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
136 // RFC 8017 A.1.2
137 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
138 "020100" // INTEGER length 1 value 0x00 (version)
139 "028181" // INTEGER length 0x81 value (modulus) ...
140 "00c6095409047d8634812d5a218176e4"
141 "5c41d60a75b13901f234226cffe77652"
142 "1c5a77b9e389417b71c0b6a44d13afe4"
143 "e4a2805d46c9da2935adb1ff0c1f24ea"
144 "06e62b20d776430a4d435157233c6f91"
145 "6783c30e310fcbd89b85c2d567711697"
146 "85ac12bca244abda72bfb19fc44d27c8"
147 "1e1d92de284f4061edfd99280745ea6d"
148 "25"
149 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
150 "028180" // INTEGER length 0x80 (privateExponent) value...
151 "1be0f04d9cae3718691f035338308e91"
152 "564b55899ffb5084d2460e6630257e05"
153 "b3ceab02972dfabcd6ce5f6ee2589eb6"
154 "7911ed0fac16e43a444b8c861e544a05"
155 "93365772f8baf6b22fc9e3c5f1024b06"
156 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
157 "ace7240290bef16c0b3f7f3cdd64ce3a"
158 "b5912cf6e32f39ab188358afcccd8081"
159 "0241" // INTEGER length 0x41 (prime1)
160 "00e4b49ef50f765d3b24dde01aceaaf1"
161 "30f2c76670a91a61ae08af497b4a82be"
162 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
163 "8c92bfab137fba2285227b83c342ff7c"
164 "55"
165 "0241" // INTEGER length 0x41 (prime2)
166 "00ddabb5839c4c7f6bf3d4183231f005"
167 "b31aa58affdda5c79e4cce217f6bc930"
168 "dbe563d480706c24e9ebfcab28a6cdef"
169 "d324b77e1bf7251b709092c24ff501fd"
170 "91"
171 "0240" // INTEGER length 0x40 (exponent1)
172 "23d4340eda3445d8cd26c14411da6fdc"
173 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
174 "842c1d280405bc2f6c1bea214a1d742a"
175 "b996b35b63a82a5e470fa88dbf823cdd"
176 "0240" // INTEGER length 0x40 (exponent2)
177 "1b7b57449ad30d1518249a5f56bb9829"
178 "4d4b6ac12ffc86940497a5a5837a6cf9"
179 "46262b494526d328c11e1126380fde04"
180 "c24f916dec250892db09a6d77cdba351"
181 "0240" // INTEGER length 0x40 (coefficient)
182 "7762cd8f4d050da56bd591adb515d24d"
183 "7ccd32cca0d05f866d583514bd7324d5"
184 "f33645e8ed8b4a1cb3cc4a1d67987399"
185 "f2a09f5b3fb68c88d5e5d90ac33492d6"
186 // } end SEQUENCE (PrivateKey)
187 // } end SEQUENCE (PrivateKeyInfo)
188);
Selene Huang31ab4042020-04-29 04:22:39 -0700189
Selene Huange5727e62021-04-13 22:41:20 -0700190/*
191 * DER-encoded PKCS#8 format RSA key. Generated using:
192 *
193 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
194 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100195string rsa_2048_key = hex2str(
196 // RFC 5208 s5
197 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
198 "020100" // INTEGER length 1 value 0x00 (version)
199 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
200 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
201 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
202 "0500" // NULL (parameters)
203 // } end SEQUENCE (AlgorithmIdentifier)
204 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
205 // RFC 8017 A.1.2
206 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
207 "020100" // INTEGER length 1 value 0x00 (version)
208 "02820101" // INTEGER length 0x101 value (modulus) ...
209 "00BEBC342B56D443B1299F9A6A7056E8"
210 "0A897E318476A5A18029E63B2ED739A6"
211 "1791D339F58DC763D9D14911F2EDEC38"
212 "3DEE11F6319B44510E7A3ECD9B79B973"
213 "82E49500ACF8117DC89CAF0E621F7775"
214 "6554A2FD4664BFE7AB8B59AB48340DBF"
215 "A27B93B5A81F6ECDEB02D0759307128D"
216 "F3E3BAD4055C8B840216DFAA5700670E"
217 "6C5126F0962FCB70FF308F25049164CC"
218 "F76CC2DA66A7DD9A81A714C2809D6918"
219 "6133D29D84568E892B6FFBF3199BDB14"
220 "383EE224407F190358F111A949552ABA"
221 "6714227D1BD7F6B20DD0CB88F9467B71"
222 "9339F33BFF35B3870B3F62204E4286B0"
223 "948EA348B524544B5F9838F29EE643B0"
224 "79EEF8A713B220D7806924CDF7295070"
225 "C5"
226 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
227 "02820100" // INTEGER length 0x100 (privateExponent) value...
228 "69F377F35F2F584EF075353CCD1CA997"
229 "38DB3DBC7C7FF35F9366CE176DFD1B13"
230 "5AB10030344ABF5FBECF1D4659FDEF1C"
231 "0FC430834BE1BE3911951377BB3D563A"
232 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
233 "2686C7B4B3C09A7B8354133E6F93F790"
234 "D59EAEB92E84C9A4339302CCE28FDF04"
235 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
236 "6AB706645BF074A4E4090D06FB163124"
237 "365FD5EE7A20D350E9958CC30D91326E"
238 "1B292E9EF5DB408EC42DAF737D201497"
239 "04D0A678A0FB5B5446863B099228A352"
240 "D604BA8091A164D01D5AB05397C71EAD"
241 "20BE2A08FC528FE442817809C787FEE4"
242 "AB97F97B9130D022153EDC6EB6CBE7B0"
243 "F8E3473F2E901209B5DB10F93604DB01"
244 "028181" // INTEGER length 0x81 (prime1)
245 "00E83C0998214941EA4F9293F1B77E2E"
246 "99E6CF305FAF358238E126124FEAF2EB"
247 "9724B2EA7B78E6032343821A80E55D1D"
248 "88FB12D220C3F41A56142FEC85796D19"
249 "17F1E8C774F142B67D3D6E7B7E6B4383"
250 "E94DB5929089DBB346D5BDAB40CC2D96"
251 "EE0409475E175C63BF78CFD744136740"
252 "838127EA723FF3FE7FA368C1311B4A4E"
253 "05"
254 "028181" // INTEGER length 0x81 (prime2)
255 "00D240FCC0F5D7715CDE21CB2DC86EA1"
256 "46132EA3B06F61FF2AF54BF38473F59D"
257 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
258 "B1B58C39F95E4798CCBB43E83D0119AC"
259 "F532F359CA743C85199F0286610E2009"
260 "97D7312917179AC9B67558773212EC96"
261 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
262 "94D94E066A0900B7B70E82A44FB30053"
263 "C1"
264 "028181" // INTEGER length 0x81 (exponent1)
265 "00AD15DA1CBD6A492B66851BA8C316D3"
266 "8AB700E2CFDDD926A658003513C54BAA"
267 "152B30021D667D20078F500F8AD3E7F3"
268 "945D74A891ED1A28EAD0FEEAEC8C14A8"
269 "E834CF46A13D1378C99D18940823CFDD"
270 "27EC5810D59339E0C34198AC638E09C8"
271 "7CBB1B634A9864AE9F4D5EB2D53514F6"
272 "7B4CAEC048C8AB849A02E397618F3271"
273 "35"
274 "028180" // INTEGER length 0x80 (exponent2)
275 "1FA2C1A5331880A92D8F3E281C617108"
276 "BF38244F16E352E69ED417C7153F9EC3"
277 "18F211839C643DCF8B4DD67CE2AC312E"
278 "95178D5D952F06B1BF779F4916924B70"
279 "F582A23F11304E02A5E7565AE22A35E7"
280 "4FECC8B6FDC93F92A1A37703E4CF0E63"
281 "783BD02EB716A7ECBBFA606B10B74D01"
282 "579522E7EF84D91FC522292108D902C1"
283 "028180" // INTEGER length 0x80 (coefficient)
284 "796FE3825F9DCC85DF22D58690065D93"
285 "898ACD65C087BEA8DA3A63BF4549B795"
286 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
287 "0D74F40DED8E1102C52152A31B6165F8"
288 "3A6722AECFCC35A493D7634664B888A0"
289 "8D3EB034F12EA28BFEE346E205D33482"
290 "7F778B16ED40872BD29FCB36536B6E93"
291 "FFB06778696B4A9D81BB0A9423E63DE5"
292 // } end SEQUENCE (PrivateKey)
293 // } end SEQUENCE (PrivateKeyInfo)
294);
Selene Huange5727e62021-04-13 22:41:20 -0700295
David Drysdaled2cc8c22021-04-15 13:29:45 +0100296string ec_256_key = hex2str(
297 // RFC 5208 s5
298 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
299 "020100" // INTEGER length 1 value 0 (version)
300 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
301 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
302 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
303 "0608" // OBJECT IDENTIFIER length 8 (param)
304 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
305 // } end SEQUENCE (AlgorithmIdentifier)
306 "046d" // OCTET STRING length 0x6d (privateKey) holding...
307 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
308 "020101" // INTEGER length 1 value 1 (version)
309 "0420" // OCTET STRING length 0x20 (privateKey)
310 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
311 "941eed09366bc03299986481f3a4d859"
312 "a144" // TAG [1] len 0x44 (publicKey) {
313 "03420004bf85d7720d07c25461683bc6"
314 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
315 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
316 "bcc41c6eb00083cf3376d11fd44949e0"
317 "b2183bfe"
318 // } end SEQUENCE (ECPrivateKey)
319 // } end SEQUENCE (PrivateKeyInfo)
320);
Selene Huang31ab4042020-04-29 04:22:39 -0700321
David Drysdaled2cc8c22021-04-15 13:29:45 +0100322string ec_521_key = hex2str(
323 // RFC 5208 s5
324 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
325 "020100" // INTEGER length 1 value 0 (version)
326 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
327 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
328 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
329 "0605" // OBJECT IDENTIFIER length 5 (param)
330 "2B81040023" // 1.3.132.0.35 (secp521r1)
331 // } end SEQUENCE (AlgorithmIdentifier)
332 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
333 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
334 "020101" // INTEGER length 1 value 1 (version)
335 "0442" // OCTET STRING length 0x42 (privateKey)
336 "0011458C586DB5DAA92AFAB03F4FE46A"
337 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
338 "9D18D7D08B5BCFA0E53C75B064AD51C4"
339 "49BAE0258D54B94B1E885DED08ED4FB2"
340 "5CE9"
341 "A18189" // TAG [1] len 0x89 (publicKey) {
342 "03818600040149EC11C6DF0FA122C6A9"
343 "AFD9754A4FA9513A627CA329E349535A"
344 "5629875A8ADFBE27DCB932C051986377"
345 "108D054C28C6F39B6F2C9AF81802F9F3"
346 "26B842FF2E5F3C00AB7635CFB36157FC"
347 "0882D574A10D839C1A0C049DC5E0D775"
348 "E2EE50671A208431BB45E78E70BEFE93"
349 "0DB34818EE4D5C26259F5C6B8E28A652"
350 "950F9F88D7B4B2C9D9"
351 // } end SEQUENCE (ECPrivateKey)
352 // } end SEQUENCE (PrivateKeyInfo)
353);
Selene Huang31ab4042020-04-29 04:22:39 -0700354
David Drysdaled2cc8c22021-04-15 13:29:45 +0100355string ec_256_key_rfc5915 = hex2str(
356 // RFC 5208 s5
357 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
358 "020100" // INTEGER length 1 value 0 (version)
359 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
360 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
361 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
362 "0608" // OBJECT IDENTIFIER length 8 (param)
363 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
364 // } end SEQUENCE (AlgorithmIdentifier)
365 "0479" // OCTET STRING length 0x79 (privateKey) holding...
366 // RFC 5915 s3
367 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
368 "020101" // INTEGER length 1 value 1 (version)
369 "0420" // OCTET STRING length 0x42 (privateKey)
370 "782370a8c8ce5537baadd04dcff079c8"
371 "158cfa9c67b818b38e8d21c9fa750c1d"
372 "a00a" // TAG [0] length 0xa (parameters)
373 "0608" // OBJECT IDENTIFIER length 8
374 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
375 // } end TAG [0]
376 "a144" // TAG [1] length 0x44 (publicKey) {
377 "0342" // BIT STRING length 0x42
378 "00" // no pad bits
379 "04e2cc561ee701da0ad0ef0d176bb0c9"
380 "19d42e79c393fdc1bd6c4010d85cf2cf"
381 "8e68c905464666f98dad4f01573ba810"
382 "78b3428570a439ba3229fbc026c55068"
383 "2f"
384 // } end SEQUENCE (ECPrivateKey)
385 // } end SEQUENCE (PrivateKeyInfo)
386);
Selene Huang31ab4042020-04-29 04:22:39 -0700387
David Drysdaled2cc8c22021-04-15 13:29:45 +0100388string ec_256_key_sec1 = hex2str(
389 // RFC 5208 s5
390 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
391 "020100" // INTEGER length 1 value 0 (version)
392 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
393 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
394 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
395 "0608" // OBJECT IDENTIFIER length 8 (param)
396 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
397 // } end SEQUENCE (AlgorithmIdentifier)
398 "046d" // OCTET STRING length 0x6d (privateKey) holding...
399 // SEC1-v2 C.4
400 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
401 "020101" // INTEGER length 1 value 0x01 (version)
402 "0420" // OCTET STRING length 0x20 (privateKey)
403 "782370a8c8ce5537baadd04dcff079c8"
404 "158cfa9c67b818b38e8d21c9fa750c1d"
405 "a144" // TAG [1] length 0x44 (publicKey) {
406 "0342" // BIT STRING length 0x42
407 "00" // no pad bits
408 "04e2cc561ee701da0ad0ef0d176bb0c9"
409 "19d42e79c393fdc1bd6c4010d85cf2cf"
410 "8e68c905464666f98dad4f01573ba810"
411 "78b3428570a439ba3229fbc026c55068"
412 "2f"
413 // } end TAG [1] (publicKey)
414 // } end SEQUENCE (PrivateKeyInfo)
415);
Selene Huang31ab4042020-04-29 04:22:39 -0700416
417struct RSA_Delete {
418 void operator()(RSA* p) { RSA_free(p); }
419};
420
Selene Huang31ab4042020-04-29 04:22:39 -0700421std::string make_string(const uint8_t* data, size_t length) {
422 return std::string(reinterpret_cast<const char*>(data), length);
423}
424
425template <size_t N>
426std::string make_string(const uint8_t (&a)[N]) {
427 return make_string(a, N);
428}
429
430class AidlBuf : public vector<uint8_t> {
431 typedef vector<uint8_t> super;
432
433 public:
434 AidlBuf() {}
435 AidlBuf(const super& other) : super(other) {}
436 AidlBuf(super&& other) : super(std::move(other)) {}
437 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
438
439 AidlBuf& operator=(const super& other) {
440 super::operator=(other);
441 return *this;
442 }
443
444 AidlBuf& operator=(super&& other) {
445 super::operator=(std::move(other));
446 return *this;
447 }
448
449 AidlBuf& operator=(const string& other) {
450 resize(other.size());
451 for (size_t i = 0; i < other.size(); ++i) {
452 (*this)[i] = static_cast<uint8_t>(other[i]);
453 }
454 return *this;
455 }
456
457 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
458};
459
David Drysdale4dc01072021-04-01 12:17:35 +0100460string device_suffix(const string& name) {
461 size_t pos = name.find('/');
462 if (pos == string::npos) {
463 return name;
464 }
465 return name.substr(pos + 1);
466}
467
468bool matching_rp_instance(const string& km_name,
469 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
470 string km_suffix = device_suffix(km_name);
471
472 vector<string> rp_names =
473 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
474 for (const string& rp_name : rp_names) {
475 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
476 // KeyMint instance, assume they match.
477 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
478 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
479 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
480 return true;
481 }
482 }
483 return false;
484}
485
Selene Huang31ab4042020-04-29 04:22:39 -0700486} // namespace
487
488class NewKeyGenerationTest : public KeyMintAidlTestBase {
489 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700490 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000491 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700492 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700493
Selene Huang31ab4042020-04-29 04:22:39 -0700494 // Check that some unexpected tags/values are NOT present.
495 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
496 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000497 }
498
499 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
500 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
501 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
502 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
503
504 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000505 }
506
507 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
508 // TODO(swillden): Distinguish which params should be in which auth list.
509 AuthorizationSet auths;
510 for (auto& entry : keyCharacteristics) {
511 auths.push_back(AuthorizationSet(entry.authorizations));
512 }
513 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
514
515 // Verify that App data, ROT and auth timeout are NOT included.
516 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
517 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700518 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
519
David Drysdaled2cc8c22021-04-15 13:29:45 +0100520 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
521 // never adds it.
522 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
523
David Drysdale7de9feb2021-03-05 14:56:19 +0000524 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700525 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000526 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700527 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700528 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000529 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700530 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000531
David Drysdalebb3d85e2021-04-13 11:15:51 +0100532 if (check_patchLevels) {
533 // Should include vendor and boot patchlevels.
534 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
535 EXPECT_TRUE(vendor_pl);
536 EXPECT_EQ(*vendor_pl, vendor_patch_level());
537 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
538 EXPECT_TRUE(boot_pl);
539 }
540
David Drysdale7de9feb2021-03-05 14:56:19 +0000541 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700542 }
543};
544
545/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000546 * NewKeyGenerationTest.Aes
547 *
548 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
549 * have correct characteristics.
550 */
551TEST_P(NewKeyGenerationTest, Aes) {
552 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
553 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
554 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
555 SCOPED_TRACE(testing::Message()
556 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
557 vector<uint8_t> key_blob;
558 vector<KeyCharacteristics> key_characteristics;
559 auto builder = AuthorizationSetBuilder()
560 .AesEncryptionKey(key_size)
561 .BlockMode(block_mode)
562 .Padding(padding_mode)
563 .SetDefaultValidity();
564 if (block_mode == BlockMode::GCM) {
565 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
566 }
567 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
568
569 EXPECT_GT(key_blob.size(), 0U);
570 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100571 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000572
573 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
574
575 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
576 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
577 << "Key size " << key_size << "missing";
578
579 CheckedDeleteKey(&key_blob);
580 }
581 }
582 }
583}
584
585/*
586 * NewKeyGenerationTest.AesInvalidSize
587 *
588 * Verifies that specifying an invalid key size for AES key generation returns
589 * UNSUPPORTED_KEY_SIZE.
590 */
591TEST_P(NewKeyGenerationTest, AesInvalidSize) {
592 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
593 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
594 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
595 SCOPED_TRACE(testing::Message()
596 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
597 vector<uint8_t> key_blob;
598 vector<KeyCharacteristics> key_characteristics;
599 auto builder = AuthorizationSetBuilder()
600 .AesEncryptionKey(key_size)
601 .BlockMode(block_mode)
602 .Padding(padding_mode)
603 .SetDefaultValidity();
604 if (block_mode == BlockMode::GCM) {
605 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
606 }
607 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
608 GenerateKey(builder, &key_blob, &key_characteristics));
609 }
610 }
611 }
612
613 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
614 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
615 vector<uint8_t> key_blob;
616 vector<KeyCharacteristics> key_characteristics;
617 // No key size specified
618 auto builder = AuthorizationSetBuilder()
619 .Authorization(TAG_ALGORITHM, Algorithm::AES)
620 .BlockMode(block_mode)
621 .Padding(padding_mode)
622 .SetDefaultValidity();
623 if (block_mode == BlockMode::GCM) {
624 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
625 }
626 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
627 GenerateKey(builder, &key_blob, &key_characteristics));
628 }
629 }
630}
631
632/*
633 * NewKeyGenerationTest.AesInvalidPadding
634 *
635 * Verifies that specifying an invalid padding on AES keys gives a failure
636 * somewhere along the way.
637 */
638TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
639 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
640 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
641 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
642 SCOPED_TRACE(testing::Message()
643 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000644 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800645 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000646 .AesEncryptionKey(key_size)
647 .BlockMode(block_mode)
648 .Padding(padding_mode)
649 .SetDefaultValidity();
650 if (block_mode == BlockMode::GCM) {
651 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
652 }
653
Tommy Chiu3950b452021-05-03 22:01:46 +0800654 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000655 if (result == ErrorCode::OK) {
656 // Key creation was OK but has generated a key that cannot be used.
657 auto params =
658 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800659 if (block_mode == BlockMode::GCM) {
660 params.Authorization(TAG_MAC_LENGTH, 128);
661 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000662 auto result = Begin(KeyPurpose::ENCRYPT, params);
663 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100664 result == ErrorCode::INVALID_KEY_BLOB)
665 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000666 } else {
667 // The KeyMint implementation detected that the generated key
668 // is unusable.
669 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
670 }
671 }
672 }
673 }
674}
675
676/*
677 * NewKeyGenerationTest.AesGcmMissingMinMac
678 *
679 * Verifies that specifying an invalid key size for AES key generation returns
680 * UNSUPPORTED_KEY_SIZE.
681 */
682TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
683 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
684 BlockMode block_mode = BlockMode::GCM;
685 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
686 SCOPED_TRACE(testing::Message()
687 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
688 vector<uint8_t> key_blob;
689 vector<KeyCharacteristics> key_characteristics;
690 // No MIN_MAC_LENGTH provided.
691 auto builder = AuthorizationSetBuilder()
692 .AesEncryptionKey(key_size)
693 .BlockMode(block_mode)
694 .Padding(padding_mode)
695 .SetDefaultValidity();
696 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
697 GenerateKey(builder, &key_blob, &key_characteristics));
698 }
699 }
700}
701
702/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100703 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
704 *
705 * Verifies that specifying an invalid min MAC size for AES key generation returns
706 * UNSUPPORTED_MIN_MAC_LENGTH.
707 */
708TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
709 for (size_t min_mac_len : {88, 136}) {
710 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
711 BlockMode block_mode = BlockMode::GCM;
712 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
713 SCOPED_TRACE(testing::Message()
714 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
715 vector<uint8_t> key_blob;
716 vector<KeyCharacteristics> key_characteristics;
717 auto builder = AuthorizationSetBuilder()
718 .AesEncryptionKey(key_size)
719 .BlockMode(block_mode)
720 .Padding(padding_mode)
721 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
722 .SetDefaultValidity();
723 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
724 GenerateKey(builder, &key_blob, &key_characteristics));
725 }
726 }
727 }
728}
729
730/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000731 * NewKeyGenerationTest.TripleDes
732 *
733 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
734 * have correct characteristics.
735 */
736TEST_P(NewKeyGenerationTest, TripleDes) {
737 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
738 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
739 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
740 SCOPED_TRACE(testing::Message()
741 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
742 vector<uint8_t> key_blob;
743 vector<KeyCharacteristics> key_characteristics;
744 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
745 .TripleDesEncryptionKey(key_size)
746 .BlockMode(block_mode)
747 .Padding(padding_mode)
748 .Authorization(TAG_NO_AUTH_REQUIRED)
749 .SetDefaultValidity(),
750 &key_blob, &key_characteristics));
751
752 EXPECT_GT(key_blob.size(), 0U);
753 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100754 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000755
756 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
757
758 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
759 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
760 << "Key size " << key_size << "missing";
761
762 CheckedDeleteKey(&key_blob);
763 }
764 }
765 }
766}
767
768/*
769 * NewKeyGenerationTest.TripleDesWithAttestation
770 *
771 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
772 * have correct characteristics.
773 *
774 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
775 * put in a certificate) but which isn't an error.
776 */
777TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
778 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
779 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
780 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
781 SCOPED_TRACE(testing::Message()
782 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
783
784 auto challenge = "hello";
785 auto app_id = "foo";
786
787 vector<uint8_t> key_blob;
788 vector<KeyCharacteristics> key_characteristics;
789 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
790 .TripleDesEncryptionKey(key_size)
791 .BlockMode(block_mode)
792 .Padding(padding_mode)
793 .Authorization(TAG_NO_AUTH_REQUIRED)
794 .AttestationChallenge(challenge)
795 .AttestationApplicationId(app_id)
796 .SetDefaultValidity(),
797 &key_blob, &key_characteristics));
798
799 EXPECT_GT(key_blob.size(), 0U);
800 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100801 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000802
803 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
804
805 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
806 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
807 << "Key size " << key_size << "missing";
808
809 CheckedDeleteKey(&key_blob);
810 }
811 }
812 }
813}
814
815/*
816 * NewKeyGenerationTest.TripleDesInvalidSize
817 *
818 * Verifies that specifying an invalid key size for 3-DES key generation returns
819 * UNSUPPORTED_KEY_SIZE.
820 */
821TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
822 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
823 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
824 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
825 SCOPED_TRACE(testing::Message()
826 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
827 vector<uint8_t> key_blob;
828 vector<KeyCharacteristics> key_characteristics;
829 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
830 GenerateKey(AuthorizationSetBuilder()
831 .TripleDesEncryptionKey(key_size)
832 .BlockMode(block_mode)
833 .Padding(padding_mode)
834 .Authorization(TAG_NO_AUTH_REQUIRED)
835 .SetDefaultValidity(),
836 &key_blob, &key_characteristics));
837 }
838 }
839 }
840
841 // Omitting the key size fails.
842 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
843 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
844 SCOPED_TRACE(testing::Message()
845 << "3DES-default-" << block_mode << "-" << padding_mode);
846 vector<uint8_t> key_blob;
847 vector<KeyCharacteristics> key_characteristics;
848 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
849 GenerateKey(AuthorizationSetBuilder()
850 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
851 .BlockMode(block_mode)
852 .Padding(padding_mode)
853 .Authorization(TAG_NO_AUTH_REQUIRED)
854 .SetDefaultValidity(),
855 &key_blob, &key_characteristics));
856 }
857 }
858}
859
860/*
Selene Huang31ab4042020-04-29 04:22:39 -0700861 * NewKeyGenerationTest.Rsa
862 *
863 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
864 * have correct characteristics.
865 */
866TEST_P(NewKeyGenerationTest, Rsa) {
867 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
868 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700869 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700870 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
871 .RsaSigningKey(key_size, 65537)
872 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -0800873 .Padding(PaddingMode::NONE)
874 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -0700875 &key_blob, &key_characteristics));
876
877 ASSERT_GT(key_blob.size(), 0U);
878 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100879 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700880
Shawn Willden7f424372021-01-10 18:06:50 -0700881 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -0700882
883 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
884 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
885 << "Key size " << key_size << "missing";
886 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
887
888 CheckedDeleteKey(&key_blob);
889 }
890}
891
892/*
Qi Wud22ec842020-11-26 13:27:53 +0800893 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700894 *
David Drysdaled2cc8c22021-04-15 13:29:45 +0100895 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
896 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700897 */
898TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -0700899 auto challenge = "hello";
900 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700901
Selene Huang6e46f142021-04-20 19:20:11 -0700902 auto subject = "cert subj 2";
903 vector<uint8_t> subject_der(make_name_from_str(subject));
904
905 uint64_t serial_int = 66;
906 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
907
Selene Huang4f64c222021-04-13 19:54:36 -0700908 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700909 vector<uint8_t> key_blob;
910 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -0700911 ASSERT_EQ(ErrorCode::OK,
912 GenerateKey(AuthorizationSetBuilder()
913 .RsaSigningKey(key_size, 65537)
914 .Digest(Digest::NONE)
915 .Padding(PaddingMode::NONE)
916 .AttestationChallenge(challenge)
917 .AttestationApplicationId(app_id)
918 .Authorization(TAG_NO_AUTH_REQUIRED)
919 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
920 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
921 .SetDefaultValidity(),
922 &key_blob, &key_characteristics));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700923
924 ASSERT_GT(key_blob.size(), 0U);
925 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100926 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700927
928 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
929
930 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
931 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
932 << "Key size " << key_size << "missing";
933 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
934
Selene Huang6e46f142021-04-20 19:20:11 -0700935 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -0700936 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -0700937 ASSERT_GT(cert_chain_.size(), 0);
938
939 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
940 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
941 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
942 sw_enforced, hw_enforced, SecLevel(),
943 cert_chain_[0].encodedCertificate));
944
945 CheckedDeleteKey(&key_blob);
946 }
947}
948
949/*
David Drysdale4dc01072021-04-01 12:17:35 +0100950 * NewKeyGenerationTest.RsaWithRpkAttestation
951 *
952 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
953 * that has been generated using an associate IRemotelyProvisionedComponent.
954 */
955TEST_P(NewKeyGenerationTest, RsaWithRpkAttestation) {
956 // 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);
1485 for (const KeyParameter& tag : extra_tags) {
1486 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1487 vector<uint8_t> key_blob;
1488 vector<KeyCharacteristics> key_characteristics;
1489 AuthorizationSetBuilder builder = base_builder;
1490 builder.push_back(tag);
1491 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1492 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1493 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1494 continue;
1495 }
1496 if (result == ErrorCode::UNSUPPORTED_TAG &&
1497 (tag.tag == TAG_ALLOW_WHILE_ON_BODY || tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED)) {
1498 // Optional tag not supported by this KeyMint implementation.
1499 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);
1510 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID) {
1511 // Expect to find most of the extra tags in the key characteristics
1512 // of the generated key (but not for ATTESTATION_APPLICATION_ID).
1513 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1514 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1515 }
1516
1517 // Verifying the attestation record will check for the specific tag because
1518 // it's included in the authorizations.
1519 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1520 SecLevel(), cert_chain_[0].encodedCertificate));
1521
1522 CheckedDeleteKey(&key_blob);
1523 }
1524
1525 // Device attestation IDs should be rejected for normal attestation requests; these fields
1526 // are only used for device unique attestation.
1527 auto invalid_tags = AuthorizationSetBuilder()
1528 .Authorization(TAG_ATTESTATION_ID_BRAND, "brand")
1529 .Authorization(TAG_ATTESTATION_ID_DEVICE, "device")
1530 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "product")
1531 .Authorization(TAG_ATTESTATION_ID_SERIAL, "serial")
1532 .Authorization(TAG_ATTESTATION_ID_IMEI, "imei")
1533 .Authorization(TAG_ATTESTATION_ID_MEID, "meid")
1534 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer")
1535 .Authorization(TAG_ATTESTATION_ID_MODEL, "model");
1536 for (const KeyParameter& tag : invalid_tags) {
1537 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1538 vector<uint8_t> key_blob;
1539 vector<KeyCharacteristics> key_characteristics;
1540 AuthorizationSetBuilder builder =
1541 AuthorizationSetBuilder()
1542 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001543 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001544 .Digest(Digest::NONE)
1545 .AttestationChallenge(challenge)
1546 .AttestationApplicationId(app_id)
1547 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1548 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1549 .SetDefaultValidity();
1550 builder.push_back(tag);
1551 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1552 GenerateKey(builder, &key_blob, &key_characteristics));
1553 }
1554}
1555
1556/*
1557 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1558 *
1559 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1560 */
1561TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1562 auto challenge = "hello";
1563 auto attest_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
1569 // Earlier versions of the attestation extension schema included a slot:
1570 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1571 // This should never have been included, and should never be filled in.
1572 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1573 // to confirm that this field never makes it into the attestation extension.
1574 vector<uint8_t> key_blob;
1575 vector<KeyCharacteristics> key_characteristics;
1576 auto result = GenerateKey(AuthorizationSetBuilder()
1577 .Authorization(TAG_NO_AUTH_REQUIRED)
1578 .EcdsaSigningKey(EcCurve::P_256)
1579 .Digest(Digest::NONE)
1580 .AttestationChallenge(challenge)
1581 .AttestationApplicationId(attest_app_id)
1582 .Authorization(TAG_APPLICATION_ID, "client_id")
1583 .Authorization(TAG_APPLICATION_DATA, "appdata")
1584 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1585 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1586 .SetDefaultValidity(),
1587 &key_blob, &key_characteristics);
1588 ASSERT_EQ(result, ErrorCode::OK);
1589 ASSERT_GT(key_blob.size(), 0U);
1590
1591 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1592 ASSERT_GT(cert_chain_.size(), 0);
1593 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1594
1595 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1596 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1597 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1598 SecLevel(), cert_chain_[0].encodedCertificate));
1599
1600 // Check that the app id is not in the cert.
1601 string app_id = "clientid";
1602 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1603 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1604 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1605 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1606 cert_chain_[0].encodedCertificate.end());
1607
1608 CheckedDeleteKey(&key_blob);
1609}
1610
1611/*
Selene Huang4f64c222021-04-13 19:54:36 -07001612 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1613 *
1614 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1615 * the key will generate a self signed attestation.
1616 */
1617TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001618 auto subject = "cert subj 2";
1619 vector<uint8_t> subject_der(make_name_from_str(subject));
1620
1621 uint64_t serial_int = 0x123456FFF1234;
1622 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1623
David Drysdaledf09e542021-06-08 15:46:11 +01001624 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001625 vector<uint8_t> key_blob;
1626 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001627 ASSERT_EQ(ErrorCode::OK,
1628 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001629 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001630 .Digest(Digest::NONE)
1631 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1632 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1633 .SetDefaultValidity(),
1634 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001635 ASSERT_GT(key_blob.size(), 0U);
1636 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001637 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001638
1639 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1640
1641 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001642 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001643
1644 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001645 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001646 ASSERT_EQ(cert_chain_.size(), 1);
1647
1648 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1649 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1650
1651 CheckedDeleteKey(&key_blob);
1652 }
1653}
1654
1655/*
1656 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1657 *
1658 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1659 * app id must also be provided or else it will fail.
1660 */
1661TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1662 auto challenge = "hello";
1663 vector<uint8_t> key_blob;
1664 vector<KeyCharacteristics> key_characteristics;
1665
1666 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1667 GenerateKey(AuthorizationSetBuilder()
1668 .EcdsaSigningKey(EcCurve::P_256)
1669 .Digest(Digest::NONE)
1670 .AttestationChallenge(challenge)
1671 .SetDefaultValidity(),
1672 &key_blob, &key_characteristics));
1673}
1674
1675/*
1676 * NewKeyGenerationTest.EcdsaIgnoreAppId
1677 *
1678 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1679 * any appid will be ignored, and keymint will generate a self sign certificate.
1680 */
1681TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1682 auto app_id = "foo";
1683
David Drysdaledf09e542021-06-08 15:46:11 +01001684 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001685 vector<uint8_t> key_blob;
1686 vector<KeyCharacteristics> key_characteristics;
1687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001688 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001689 .Digest(Digest::NONE)
1690 .AttestationApplicationId(app_id)
1691 .SetDefaultValidity(),
1692 &key_blob, &key_characteristics));
1693
1694 ASSERT_GT(key_blob.size(), 0U);
1695 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001696 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001697
1698 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1699
1700 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001701 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001702
1703 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1704 ASSERT_EQ(cert_chain_.size(), 1);
1705
1706 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1707 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1708
1709 CheckedDeleteKey(&key_blob);
1710 }
1711}
1712
1713/*
1714 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1715 *
1716 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1717 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1718 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1719 * to specify how many following bytes will be used to encode the length.
1720 */
1721TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1722 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001723 std::vector<uint32_t> app_id_lengths{143, 258};
1724
1725 for (uint32_t length : app_id_lengths) {
1726 const string app_id(length, 'a');
1727 vector<uint8_t> key_blob;
1728 vector<KeyCharacteristics> key_characteristics;
1729 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1730 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001731 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001732 .Digest(Digest::NONE)
1733 .AttestationChallenge(challenge)
1734 .AttestationApplicationId(app_id)
1735 .SetDefaultValidity(),
1736 &key_blob, &key_characteristics));
1737 ASSERT_GT(key_blob.size(), 0U);
1738 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001739 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001740
1741 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1742
1743 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001744 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001745
1746 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1747 ASSERT_GT(cert_chain_.size(), 0);
1748
1749 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1750 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1751 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1752 sw_enforced, hw_enforced, SecLevel(),
1753 cert_chain_[0].encodedCertificate));
1754
1755 CheckedDeleteKey(&key_blob);
1756 }
1757}
1758
1759/*
Qi Wud22ec842020-11-26 13:27:53 +08001760 * NewKeyGenerationTest.LimitedUsageEcdsa
1761 *
1762 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1763 * resulting keys have correct characteristics.
1764 */
1765TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001766 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001767 vector<uint8_t> key_blob;
1768 vector<KeyCharacteristics> key_characteristics;
1769 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001770 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001771 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001772 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1773 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001774 &key_blob, &key_characteristics));
1775
1776 ASSERT_GT(key_blob.size(), 0U);
1777 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001778 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001779
1780 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1781
1782 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001783 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001784
1785 // Check the usage count limit tag appears in the authorizations.
1786 AuthorizationSet auths;
1787 for (auto& entry : key_characteristics) {
1788 auths.push_back(AuthorizationSet(entry.authorizations));
1789 }
1790 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1791 << "key usage count limit " << 1U << " missing";
1792
1793 CheckedDeleteKey(&key_blob);
1794 }
1795}
1796
1797/*
Selene Huang31ab4042020-04-29 04:22:39 -07001798 * NewKeyGenerationTest.EcdsaDefaultSize
1799 *
David Drysdaledf09e542021-06-08 15:46:11 +01001800 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001801 * UNSUPPORTED_KEY_SIZE.
1802 */
1803TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1804 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1805 GenerateKey(AuthorizationSetBuilder()
1806 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1807 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001808 .Digest(Digest::NONE)
1809 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001810}
1811
1812/*
1813 * NewKeyGenerationTest.EcdsaInvalidSize
1814 *
1815 * Verifies that specifying an invalid key size for EC key generation returns
1816 * UNSUPPORTED_KEY_SIZE.
1817 */
1818TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdaledf09e542021-06-08 15:46:11 +01001819 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001820 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001821 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001822 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001823 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001824 .Digest(Digest::NONE)
1825 .SetDefaultValidity(),
1826 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001827 }
1828
David Drysdaledf09e542021-06-08 15:46:11 +01001829 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1830 GenerateKey(AuthorizationSetBuilder()
1831 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1832 .Authorization(TAG_KEY_SIZE, 190)
1833 .SigningKey()
1834 .Digest(Digest::NONE)
1835 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001836}
1837
1838/*
1839 * NewKeyGenerationTest.EcdsaMismatchKeySize
1840 *
1841 * Verifies that specifying mismatched key size and curve for EC key generation returns
1842 * INVALID_ARGUMENT.
1843 */
1844TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1845 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1846
David Drysdaledf09e542021-06-08 15:46:11 +01001847 auto result = GenerateKey(AuthorizationSetBuilder()
1848 .Authorization(TAG_KEY_SIZE, 224)
1849 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
1850 .Digest(Digest::NONE)
1851 .SetDefaultValidity());
1852 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT ||
1853 result == ErrorCode::UNSUPPORTED_ALGORITHM);
Selene Huang31ab4042020-04-29 04:22:39 -07001854}
1855
1856/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001857 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001858 *
1859 * Verifies that keymint does not support any curve designated as unsupported.
1860 */
1861TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1862 Digest digest;
1863 if (SecLevel() == SecurityLevel::STRONGBOX) {
1864 digest = Digest::SHA_2_256;
1865 } else {
1866 digest = Digest::SHA_2_512;
1867 }
1868 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001869 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1870 .EcdsaSigningKey(curve)
1871 .Digest(digest)
1872 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001873 << "Failed to generate key on curve: " << curve;
1874 CheckedDeleteKey();
1875 }
1876}
1877
1878/*
1879 * NewKeyGenerationTest.Hmac
1880 *
1881 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1882 * characteristics.
1883 */
1884TEST_P(NewKeyGenerationTest, Hmac) {
1885 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1886 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001887 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001888 constexpr size_t key_size = 128;
1889 ASSERT_EQ(ErrorCode::OK,
1890 GenerateKey(
1891 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1892 TAG_MIN_MAC_LENGTH, 128),
1893 &key_blob, &key_characteristics));
1894
1895 ASSERT_GT(key_blob.size(), 0U);
1896 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001897 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001898
Shawn Willden7f424372021-01-10 18:06:50 -07001899 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1900 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1901 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1902 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001903
1904 CheckedDeleteKey(&key_blob);
1905 }
1906}
1907
1908/*
Selene Huang4f64c222021-04-13 19:54:36 -07001909 * NewKeyGenerationTest.HmacNoAttestation
1910 *
1911 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1912 * and app id are provided.
1913 */
1914TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1915 auto challenge = "hello";
1916 auto app_id = "foo";
1917
1918 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1919 vector<uint8_t> key_blob;
1920 vector<KeyCharacteristics> key_characteristics;
1921 constexpr size_t key_size = 128;
1922 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1923 .HmacKey(key_size)
1924 .Digest(digest)
1925 .AttestationChallenge(challenge)
1926 .AttestationApplicationId(app_id)
1927 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1928 &key_blob, &key_characteristics));
1929
1930 ASSERT_GT(key_blob.size(), 0U);
1931 ASSERT_EQ(cert_chain_.size(), 0);
1932 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001933 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001934
1935 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1936 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1937 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1938 << "Key size " << key_size << "missing";
1939
1940 CheckedDeleteKey(&key_blob);
1941 }
1942}
1943
1944/*
Qi Wud22ec842020-11-26 13:27:53 +08001945 * NewKeyGenerationTest.LimitedUsageHmac
1946 *
1947 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1948 * resulting keys have correct characteristics.
1949 */
1950TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1951 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1952 vector<uint8_t> key_blob;
1953 vector<KeyCharacteristics> key_characteristics;
1954 constexpr size_t key_size = 128;
1955 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1956 .HmacKey(key_size)
1957 .Digest(digest)
1958 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1959 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1960 &key_blob, &key_characteristics));
1961
1962 ASSERT_GT(key_blob.size(), 0U);
1963 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001964 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001965
1966 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1967 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1968 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1969 << "Key size " << key_size << "missing";
1970
1971 // Check the usage count limit tag appears in the authorizations.
1972 AuthorizationSet auths;
1973 for (auto& entry : key_characteristics) {
1974 auths.push_back(AuthorizationSet(entry.authorizations));
1975 }
1976 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1977 << "key usage count limit " << 1U << " missing";
1978
1979 CheckedDeleteKey(&key_blob);
1980 }
1981}
1982
1983/*
Selene Huang31ab4042020-04-29 04:22:39 -07001984 * NewKeyGenerationTest.HmacCheckKeySizes
1985 *
1986 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1987 */
1988TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1989 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1990 if (key_size < 64 || key_size % 8 != 0) {
1991 // To keep this test from being very slow, we only test a random fraction of
1992 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1993 // them, we expect to run ~40 of them in each run.
1994 if (key_size % 8 == 0 || random() % 10 == 0) {
1995 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1996 GenerateKey(AuthorizationSetBuilder()
1997 .HmacKey(key_size)
1998 .Digest(Digest::SHA_2_256)
1999 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2000 << "HMAC key size " << key_size << " invalid";
2001 }
2002 } else {
2003 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2004 .HmacKey(key_size)
2005 .Digest(Digest::SHA_2_256)
2006 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2007 << "Failed to generate HMAC key of size " << key_size;
2008 CheckedDeleteKey();
2009 }
2010 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002011 if (SecLevel() == SecurityLevel::STRONGBOX) {
2012 // STRONGBOX devices must not support keys larger than 512 bits.
2013 size_t key_size = 520;
2014 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2015 GenerateKey(AuthorizationSetBuilder()
2016 .HmacKey(key_size)
2017 .Digest(Digest::SHA_2_256)
2018 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2019 << "HMAC key size " << key_size << " unexpectedly valid";
2020 }
Selene Huang31ab4042020-04-29 04:22:39 -07002021}
2022
2023/*
2024 * NewKeyGenerationTest.HmacCheckMinMacLengths
2025 *
2026 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2027 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2028 * specific MAC length that failed, so reproducing a failed run will be easy.
2029 */
2030TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2031 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2032 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2033 // To keep this test from being very long, we only test a random fraction of
2034 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2035 // we expect to run ~17 of them in each run.
2036 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2037 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2038 GenerateKey(AuthorizationSetBuilder()
2039 .HmacKey(128)
2040 .Digest(Digest::SHA_2_256)
2041 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2042 << "HMAC min mac length " << min_mac_length << " invalid.";
2043 }
2044 } else {
2045 EXPECT_EQ(ErrorCode::OK,
2046 GenerateKey(AuthorizationSetBuilder()
2047 .HmacKey(128)
2048 .Digest(Digest::SHA_2_256)
2049 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2050 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2051 CheckedDeleteKey();
2052 }
2053 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002054
2055 // Minimum MAC length must be no more than 512 bits.
2056 size_t min_mac_length = 520;
2057 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2058 GenerateKey(AuthorizationSetBuilder()
2059 .HmacKey(128)
2060 .Digest(Digest::SHA_2_256)
2061 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2062 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002063}
2064
2065/*
2066 * NewKeyGenerationTest.HmacMultipleDigests
2067 *
2068 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2069 */
2070TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
2071 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2072
2073 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2074 GenerateKey(AuthorizationSetBuilder()
2075 .HmacKey(128)
2076 .Digest(Digest::SHA1)
2077 .Digest(Digest::SHA_2_256)
2078 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2079}
2080
2081/*
2082 * NewKeyGenerationTest.HmacDigestNone
2083 *
2084 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2085 */
2086TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2087 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2088 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2089 128)));
2090
2091 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2092 GenerateKey(AuthorizationSetBuilder()
2093 .HmacKey(128)
2094 .Digest(Digest::NONE)
2095 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2096}
2097
Selene Huang4f64c222021-04-13 19:54:36 -07002098/*
2099 * NewKeyGenerationTest.AesNoAttestation
2100 *
2101 * Verifies that attestation parameters to AES keys are ignored and generateKey
2102 * will succeed.
2103 */
2104TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2105 auto challenge = "hello";
2106 auto app_id = "foo";
2107
2108 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2109 .Authorization(TAG_NO_AUTH_REQUIRED)
2110 .AesEncryptionKey(128)
2111 .EcbMode()
2112 .Padding(PaddingMode::PKCS7)
2113 .AttestationChallenge(challenge)
2114 .AttestationApplicationId(app_id)));
2115
2116 ASSERT_EQ(cert_chain_.size(), 0);
2117}
2118
2119/*
2120 * NewKeyGenerationTest.TripleDesNoAttestation
2121 *
2122 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2123 * will be successful. No attestation should be generated.
2124 */
2125TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2126 auto challenge = "hello";
2127 auto app_id = "foo";
2128
2129 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2130 .TripleDesEncryptionKey(168)
2131 .BlockMode(BlockMode::ECB)
2132 .Authorization(TAG_NO_AUTH_REQUIRED)
2133 .Padding(PaddingMode::NONE)
2134 .AttestationChallenge(challenge)
2135 .AttestationApplicationId(app_id)));
2136 ASSERT_EQ(cert_chain_.size(), 0);
2137}
2138
Selene Huang31ab4042020-04-29 04:22:39 -07002139INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2140
2141typedef KeyMintAidlTestBase SigningOperationsTest;
2142
2143/*
2144 * SigningOperationsTest.RsaSuccess
2145 *
2146 * Verifies that raw RSA signature operations succeed.
2147 */
2148TEST_P(SigningOperationsTest, RsaSuccess) {
2149 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2150 .RsaSigningKey(2048, 65537)
2151 .Digest(Digest::NONE)
2152 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002153 .Authorization(TAG_NO_AUTH_REQUIRED)
2154 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002155 string message = "12345678901234567890123456789012";
2156 string signature = SignMessage(
2157 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002158 LocalVerifyMessage(message, signature,
2159 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2160}
2161
2162/*
2163 * SigningOperationsTest.RsaAllPaddingsAndDigests
2164 *
2165 * Verifies RSA signature/verification for all padding modes and digests.
2166 */
2167TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2168 auto authorizations = AuthorizationSetBuilder()
2169 .Authorization(TAG_NO_AUTH_REQUIRED)
2170 .RsaSigningKey(2048, 65537)
2171 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2172 .Padding(PaddingMode::NONE)
2173 .Padding(PaddingMode::RSA_PSS)
2174 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2175 .SetDefaultValidity();
2176
2177 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2178
2179 string message(128, 'a');
2180 string corrupt_message(message);
2181 ++corrupt_message[corrupt_message.size() / 2];
2182
2183 for (auto padding :
2184 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2185 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2186 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2187 // Digesting only makes sense with padding.
2188 continue;
2189 }
2190
2191 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2192 // PSS requires digesting.
2193 continue;
2194 }
2195
2196 string signature =
2197 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2198 LocalVerifyMessage(message, signature,
2199 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2200 }
2201 }
Selene Huang31ab4042020-04-29 04:22:39 -07002202}
2203
2204/*
2205 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2206 *
Shawn Willden7f424372021-01-10 18:06:50 -07002207 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002208 */
2209TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2210 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2211 .Authorization(TAG_NO_AUTH_REQUIRED)
2212 .RsaSigningKey(2048, 65537)
2213 .Digest(Digest::NONE)
2214 .Padding(PaddingMode::NONE)
2215 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002216 .Authorization(TAG_APPLICATION_DATA, "appdata")
2217 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002218
2219 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2220
Selene Huang31ab4042020-04-29 04:22:39 -07002221 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2222 Begin(KeyPurpose::SIGN,
2223 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2224 AbortIfNeeded();
2225 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2226 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2227 .Digest(Digest::NONE)
2228 .Padding(PaddingMode::NONE)
2229 .Authorization(TAG_APPLICATION_ID, "clientid")));
2230 AbortIfNeeded();
2231 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2232 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2233 .Digest(Digest::NONE)
2234 .Padding(PaddingMode::NONE)
2235 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2236 AbortIfNeeded();
2237 EXPECT_EQ(ErrorCode::OK,
2238 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2239 .Digest(Digest::NONE)
2240 .Padding(PaddingMode::NONE)
2241 .Authorization(TAG_APPLICATION_DATA, "appdata")
2242 .Authorization(TAG_APPLICATION_ID, "clientid")));
2243 AbortIfNeeded();
2244}
2245
2246/*
2247 * SigningOperationsTest.RsaPssSha256Success
2248 *
2249 * Verifies that RSA-PSS signature operations succeed.
2250 */
2251TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2252 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2253 .RsaSigningKey(2048, 65537)
2254 .Digest(Digest::SHA_2_256)
2255 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002256 .Authorization(TAG_NO_AUTH_REQUIRED)
2257 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002258 // Use large message, which won't work without digesting.
2259 string message(1024, 'a');
2260 string signature = SignMessage(
2261 message,
2262 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2263}
2264
2265/*
2266 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2267 *
2268 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2269 * supports only unpadded operations.
2270 */
2271TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2272 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2273 .RsaSigningKey(2048, 65537)
2274 .Digest(Digest::NONE)
2275 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002276 .Padding(PaddingMode::NONE)
2277 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002278 string message = "12345678901234567890123456789012";
2279 string signature;
2280
2281 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2282 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2283 .Digest(Digest::NONE)
2284 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2285}
2286
2287/*
2288 * SigningOperationsTest.NoUserConfirmation
2289 *
2290 * Verifies that keymint rejects signing operations for keys with
2291 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2292 * presented.
2293 */
2294TEST_P(SigningOperationsTest, NoUserConfirmation) {
2295 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2297 .RsaSigningKey(1024, 65537)
2298 .Digest(Digest::NONE)
2299 .Padding(PaddingMode::NONE)
2300 .Authorization(TAG_NO_AUTH_REQUIRED)
2301 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2302 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002303
2304 const string message = "12345678901234567890123456789012";
2305 EXPECT_EQ(ErrorCode::OK,
2306 Begin(KeyPurpose::SIGN,
2307 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2308 string signature;
2309 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2310}
2311
2312/*
2313 * SigningOperationsTest.RsaPkcs1Sha256Success
2314 *
2315 * Verifies that digested RSA-PKCS1 signature operations succeed.
2316 */
2317TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2318 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2319 .RsaSigningKey(2048, 65537)
2320 .Digest(Digest::SHA_2_256)
2321 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002322 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2323 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002324 string message(1024, 'a');
2325 string signature = SignMessage(message, AuthorizationSetBuilder()
2326 .Digest(Digest::SHA_2_256)
2327 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2328}
2329
2330/*
2331 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2332 *
2333 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2334 */
2335TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2336 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2337 .RsaSigningKey(2048, 65537)
2338 .Digest(Digest::NONE)
2339 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002340 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2341 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002342 string message(53, 'a');
2343 string signature = SignMessage(message, AuthorizationSetBuilder()
2344 .Digest(Digest::NONE)
2345 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2346}
2347
2348/*
2349 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2350 *
2351 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2352 * given a too-long message.
2353 */
2354TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2355 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2356 .RsaSigningKey(2048, 65537)
2357 .Digest(Digest::NONE)
2358 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002359 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2360 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002361 string message(257, 'a');
2362
2363 EXPECT_EQ(ErrorCode::OK,
2364 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2365 .Digest(Digest::NONE)
2366 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2367 string signature;
2368 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2369}
2370
2371/*
2372 * SigningOperationsTest.RsaPssSha512TooSmallKey
2373 *
2374 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2375 * used with a key that is too small for the message.
2376 *
2377 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2378 * keymint specification requires that salt_size == digest_size, so the message will be
2379 * digest_size * 2 +
2380 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2381 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2382 * for a 1024-bit key.
2383 */
2384TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2385 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2386 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2387 .RsaSigningKey(1024, 65537)
2388 .Digest(Digest::SHA_2_512)
2389 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002390 .Padding(PaddingMode::RSA_PSS)
2391 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002392 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2393 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2394 .Digest(Digest::SHA_2_512)
2395 .Padding(PaddingMode::RSA_PSS)));
2396}
2397
2398/*
2399 * SigningOperationsTest.RsaNoPaddingTooLong
2400 *
2401 * Verifies that raw RSA signature operations fail with the correct error code when
2402 * given a too-long message.
2403 */
2404TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2405 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2406 .RsaSigningKey(2048, 65537)
2407 .Digest(Digest::NONE)
2408 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002409 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2410 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002411 // One byte too long
2412 string message(2048 / 8 + 1, 'a');
2413 ASSERT_EQ(ErrorCode::OK,
2414 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2415 .Digest(Digest::NONE)
2416 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2417 string result;
2418 ErrorCode finish_error_code = Finish(message, &result);
2419 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2420 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2421
2422 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2423 message = string(128 * 1024, 'a');
2424 ASSERT_EQ(ErrorCode::OK,
2425 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2426 .Digest(Digest::NONE)
2427 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2428 finish_error_code = Finish(message, &result);
2429 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2430 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2431}
2432
2433/*
2434 * SigningOperationsTest.RsaAbort
2435 *
2436 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2437 * test, but the behavior should be algorithm and purpose-independent.
2438 */
2439TEST_P(SigningOperationsTest, RsaAbort) {
2440 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2441 .RsaSigningKey(2048, 65537)
2442 .Digest(Digest::NONE)
2443 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002444 .Padding(PaddingMode::NONE)
2445 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002446
2447 ASSERT_EQ(ErrorCode::OK,
2448 Begin(KeyPurpose::SIGN,
2449 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2450 EXPECT_EQ(ErrorCode::OK, Abort());
2451
2452 // Another abort should fail
2453 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2454
2455 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002456 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002457}
2458
2459/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002460 * SigningOperationsTest.RsaNonUniqueParams
2461 *
2462 * Verifies that an operation with multiple padding modes is rejected.
2463 */
2464TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2465 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2466 .RsaSigningKey(2048, 65537)
2467 .Digest(Digest::NONE)
2468 .Digest(Digest::SHA1)
2469 .Authorization(TAG_NO_AUTH_REQUIRED)
2470 .Padding(PaddingMode::NONE)
2471 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2472 .SetDefaultValidity()));
2473
2474 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2475 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2476 .Digest(Digest::NONE)
2477 .Padding(PaddingMode::NONE)
2478 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2479
Tommy Chiuc93c4392021-05-11 18:36:50 +08002480 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2481 .Digest(Digest::NONE)
2482 .Digest(Digest::SHA1)
2483 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2484 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002485
2486 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2487 Begin(KeyPurpose::SIGN,
2488 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2489}
2490
2491/*
Selene Huang31ab4042020-04-29 04:22:39 -07002492 * SigningOperationsTest.RsaUnsupportedPadding
2493 *
2494 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2495 * with a padding mode inappropriate for RSA.
2496 */
2497TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2498 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2499 .RsaSigningKey(2048, 65537)
2500 .Authorization(TAG_NO_AUTH_REQUIRED)
2501 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002502 .Padding(PaddingMode::PKCS7)
2503 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002504 ASSERT_EQ(
2505 ErrorCode::UNSUPPORTED_PADDING_MODE,
2506 Begin(KeyPurpose::SIGN,
2507 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002508 CheckedDeleteKey();
2509
2510 ASSERT_EQ(ErrorCode::OK,
2511 GenerateKey(
2512 AuthorizationSetBuilder()
2513 .RsaSigningKey(2048, 65537)
2514 .Authorization(TAG_NO_AUTH_REQUIRED)
2515 .Digest(Digest::SHA_2_256 /* supported digest */)
2516 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2517 .SetDefaultValidity()));
2518 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2519 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2520 .Digest(Digest::SHA_2_256)
2521 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002522}
2523
2524/*
2525 * SigningOperationsTest.RsaPssNoDigest
2526 *
2527 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2528 */
2529TEST_P(SigningOperationsTest, RsaNoDigest) {
2530 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2531 .RsaSigningKey(2048, 65537)
2532 .Authorization(TAG_NO_AUTH_REQUIRED)
2533 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002534 .Padding(PaddingMode::RSA_PSS)
2535 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002536 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2537 Begin(KeyPurpose::SIGN,
2538 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2539
2540 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2541 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2542}
2543
2544/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002545 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002546 *
2547 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2548 * supported in some cases (as validated in other tests), but a mode must be specified.
2549 */
2550TEST_P(SigningOperationsTest, RsaNoPadding) {
2551 // Padding must be specified
2552 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2553 .RsaKey(2048, 65537)
2554 .Authorization(TAG_NO_AUTH_REQUIRED)
2555 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002556 .Digest(Digest::NONE)
2557 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002558 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2559 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2560}
2561
2562/*
2563 * SigningOperationsTest.RsaShortMessage
2564 *
2565 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2566 */
2567TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2568 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2569 .Authorization(TAG_NO_AUTH_REQUIRED)
2570 .RsaSigningKey(2048, 65537)
2571 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002572 .Padding(PaddingMode::NONE)
2573 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002574
2575 // Barely shorter
2576 string message(2048 / 8 - 1, 'a');
2577 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2578
2579 // Much shorter
2580 message = "a";
2581 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2582}
2583
2584/*
2585 * SigningOperationsTest.RsaSignWithEncryptionKey
2586 *
2587 * Verifies that RSA encryption keys cannot be used to sign.
2588 */
2589TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2590 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2591 .Authorization(TAG_NO_AUTH_REQUIRED)
2592 .RsaEncryptionKey(2048, 65537)
2593 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002594 .Padding(PaddingMode::NONE)
2595 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002596 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2597 Begin(KeyPurpose::SIGN,
2598 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2599}
2600
2601/*
2602 * SigningOperationsTest.RsaSignTooLargeMessage
2603 *
2604 * Verifies that attempting a raw signature of a message which is the same length as the key,
2605 * but numerically larger than the public modulus, fails with the correct error.
2606 */
2607TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2608 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2609 .Authorization(TAG_NO_AUTH_REQUIRED)
2610 .RsaSigningKey(2048, 65537)
2611 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002612 .Padding(PaddingMode::NONE)
2613 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002614
2615 // Largest possible message will always be larger than the public modulus.
2616 string message(2048 / 8, static_cast<char>(0xff));
2617 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2618 .Authorization(TAG_NO_AUTH_REQUIRED)
2619 .Digest(Digest::NONE)
2620 .Padding(PaddingMode::NONE)));
2621 string signature;
2622 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2623}
2624
2625/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002626 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2627 *
2628 * Verifies ECDSA signature/verification for all digests and curves.
2629 */
2630TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2631 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2632
2633 string message = "1234567890";
2634 string corrupt_message = "2234567890";
2635 for (auto curve : ValidCurves()) {
2636 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2637 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2638 .Authorization(TAG_NO_AUTH_REQUIRED)
2639 .EcdsaSigningKey(curve)
2640 .Digest(digests)
2641 .SetDefaultValidity());
2642 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2643 if (error != ErrorCode::OK) {
2644 continue;
2645 }
2646
2647 for (auto digest : digests) {
2648 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2649 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2650 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2651 }
2652
2653 auto rc = DeleteKey();
2654 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2655 }
2656}
2657
2658/*
Selene Huang31ab4042020-04-29 04:22:39 -07002659 * SigningOperationsTest.EcdsaAllCurves
2660 *
2661 * Verifies that ECDSA operations succeed with all possible curves.
2662 */
2663TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2664 for (auto curve : ValidCurves()) {
2665 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2666 .Authorization(TAG_NO_AUTH_REQUIRED)
2667 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002668 .Digest(Digest::SHA_2_256)
2669 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002670 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2671 if (error != ErrorCode::OK) continue;
2672
2673 string message(1024, 'a');
2674 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2675 CheckedDeleteKey();
2676 }
2677}
2678
2679/*
2680 * SigningOperationsTest.EcdsaNoDigestHugeData
2681 *
2682 * Verifies that ECDSA operations support very large messages, even without digesting. This
2683 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2684 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2685 * the framework.
2686 */
2687TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2688 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2689 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002690 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002691 .Digest(Digest::NONE)
2692 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002693 string message(1 * 1024, 'a');
2694 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2695}
2696
2697/*
2698 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2699 *
2700 * Verifies that using an EC key requires the correct app ID/data.
2701 */
2702TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2703 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2704 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002705 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002706 .Digest(Digest::NONE)
2707 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002708 .Authorization(TAG_APPLICATION_DATA, "appdata")
2709 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002710
2711 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2712
Selene Huang31ab4042020-04-29 04:22:39 -07002713 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2714 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2715 AbortIfNeeded();
2716 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2717 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2718 .Digest(Digest::NONE)
2719 .Authorization(TAG_APPLICATION_ID, "clientid")));
2720 AbortIfNeeded();
2721 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2722 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2723 .Digest(Digest::NONE)
2724 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2725 AbortIfNeeded();
2726 EXPECT_EQ(ErrorCode::OK,
2727 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2728 .Digest(Digest::NONE)
2729 .Authorization(TAG_APPLICATION_DATA, "appdata")
2730 .Authorization(TAG_APPLICATION_ID, "clientid")));
2731 AbortIfNeeded();
2732}
2733
2734/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002735 * SigningOperationsTest.EcdsaIncompatibleDigest
2736 *
2737 * Verifies that using an EC key requires compatible digest.
2738 */
2739TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2740 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2741 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002742 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002743 .Digest(Digest::NONE)
2744 .Digest(Digest::SHA1)
2745 .SetDefaultValidity()));
2746 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2747 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2748 AbortIfNeeded();
2749}
2750
2751/*
Selene Huang31ab4042020-04-29 04:22:39 -07002752 * SigningOperationsTest.AesEcbSign
2753 *
2754 * Verifies that attempts to use AES keys to sign fail in the correct way.
2755 */
2756TEST_P(SigningOperationsTest, AesEcbSign) {
2757 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2758 .Authorization(TAG_NO_AUTH_REQUIRED)
2759 .SigningKey()
2760 .AesEncryptionKey(128)
2761 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2762
2763 AuthorizationSet out_params;
2764 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2765 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2766 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2767 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2768}
2769
2770/*
2771 * SigningOperationsTest.HmacAllDigests
2772 *
2773 * Verifies that HMAC works with all digests.
2774 */
2775TEST_P(SigningOperationsTest, HmacAllDigests) {
2776 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2777 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2778 .Authorization(TAG_NO_AUTH_REQUIRED)
2779 .HmacKey(128)
2780 .Digest(digest)
2781 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2782 << "Failed to create HMAC key with digest " << digest;
2783 string message = "12345678901234567890123456789012";
2784 string signature = MacMessage(message, digest, 160);
2785 EXPECT_EQ(160U / 8U, signature.size())
2786 << "Failed to sign with HMAC key with digest " << digest;
2787 CheckedDeleteKey();
2788 }
2789}
2790
2791/*
2792 * SigningOperationsTest.HmacSha256TooLargeMacLength
2793 *
2794 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2795 * digest size.
2796 */
2797TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2798 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2799 .Authorization(TAG_NO_AUTH_REQUIRED)
2800 .HmacKey(128)
2801 .Digest(Digest::SHA_2_256)
2802 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2803 AuthorizationSet output_params;
2804 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2805 AuthorizationSetBuilder()
2806 .Digest(Digest::SHA_2_256)
2807 .Authorization(TAG_MAC_LENGTH, 264),
2808 &output_params));
2809}
2810
2811/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002812 * SigningOperationsTest.HmacSha256InvalidMacLength
2813 *
2814 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2815 * not a multiple of 8.
2816 */
2817TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2818 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2819 .Authorization(TAG_NO_AUTH_REQUIRED)
2820 .HmacKey(128)
2821 .Digest(Digest::SHA_2_256)
2822 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2823 AuthorizationSet output_params;
2824 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2825 AuthorizationSetBuilder()
2826 .Digest(Digest::SHA_2_256)
2827 .Authorization(TAG_MAC_LENGTH, 161),
2828 &output_params));
2829}
2830
2831/*
Selene Huang31ab4042020-04-29 04:22:39 -07002832 * SigningOperationsTest.HmacSha256TooSmallMacLength
2833 *
2834 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2835 * specified minimum MAC length.
2836 */
2837TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2838 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2839 .Authorization(TAG_NO_AUTH_REQUIRED)
2840 .HmacKey(128)
2841 .Digest(Digest::SHA_2_256)
2842 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2843 AuthorizationSet output_params;
2844 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2845 AuthorizationSetBuilder()
2846 .Digest(Digest::SHA_2_256)
2847 .Authorization(TAG_MAC_LENGTH, 120),
2848 &output_params));
2849}
2850
2851/*
2852 * SigningOperationsTest.HmacRfc4231TestCase3
2853 *
2854 * Validates against the test vectors from RFC 4231 test case 3.
2855 */
2856TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2857 string key(20, 0xaa);
2858 string message(50, 0xdd);
2859 uint8_t sha_224_expected[] = {
2860 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2861 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2862 };
2863 uint8_t sha_256_expected[] = {
2864 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2865 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2866 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2867 };
2868 uint8_t sha_384_expected[] = {
2869 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2870 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2871 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2872 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2873 };
2874 uint8_t sha_512_expected[] = {
2875 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2876 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2877 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2878 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2879 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2880 };
2881
2882 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2883 if (SecLevel() != SecurityLevel::STRONGBOX) {
2884 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2885 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2886 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2887 }
2888}
2889
2890/*
2891 * SigningOperationsTest.HmacRfc4231TestCase5
2892 *
2893 * Validates against the test vectors from RFC 4231 test case 5.
2894 */
2895TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2896 string key(20, 0x0c);
2897 string message = "Test With Truncation";
2898
2899 uint8_t sha_224_expected[] = {
2900 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2901 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2902 };
2903 uint8_t sha_256_expected[] = {
2904 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2905 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2906 };
2907 uint8_t sha_384_expected[] = {
2908 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2909 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2910 };
2911 uint8_t sha_512_expected[] = {
2912 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2913 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2914 };
2915
2916 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2917 if (SecLevel() != SecurityLevel::STRONGBOX) {
2918 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2919 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2920 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2921 }
2922}
2923
2924INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2925
2926typedef KeyMintAidlTestBase VerificationOperationsTest;
2927
2928/*
Selene Huang31ab4042020-04-29 04:22:39 -07002929 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2930 *
2931 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2932 */
2933TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2934 string key_material = "HelloThisIsAKey";
2935
2936 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002937 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002938 EXPECT_EQ(ErrorCode::OK,
2939 ImportKey(AuthorizationSetBuilder()
2940 .Authorization(TAG_NO_AUTH_REQUIRED)
2941 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2942 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2943 .Digest(Digest::SHA_2_256)
2944 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2945 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2946 EXPECT_EQ(ErrorCode::OK,
2947 ImportKey(AuthorizationSetBuilder()
2948 .Authorization(TAG_NO_AUTH_REQUIRED)
2949 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2950 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2951 .Digest(Digest::SHA_2_256)
2952 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2953 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2954
2955 string message = "This is a message.";
2956 string signature = SignMessage(
2957 signing_key, message,
2958 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2959
2960 // Signing key should not work.
2961 AuthorizationSet out_params;
2962 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2963 Begin(KeyPurpose::VERIFY, signing_key,
2964 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2965
2966 // Verification key should work.
2967 VerifyMessage(verification_key, message, signature,
2968 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2969
2970 CheckedDeleteKey(&signing_key);
2971 CheckedDeleteKey(&verification_key);
2972}
2973
2974INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2975
2976typedef KeyMintAidlTestBase ExportKeyTest;
2977
2978/*
2979 * ExportKeyTest.RsaUnsupportedKeyFormat
2980 *
2981 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2982 */
2983// TODO(seleneh) add ExportKey to GenerateKey
2984// check result
2985
2986class ImportKeyTest : public KeyMintAidlTestBase {
2987 public:
2988 template <TagType tag_type, Tag tag, typename ValueT>
2989 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2990 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002991 for (auto& entry : key_characteristics_) {
2992 if (entry.securityLevel == SecLevel()) {
2993 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2994 << "Tag " << tag << " with value " << expected
2995 << " not found at security level" << entry.securityLevel;
2996 } else {
2997 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2998 << "Tag " << tag << " found at security level " << entry.securityLevel;
2999 }
Selene Huang31ab4042020-04-29 04:22:39 -07003000 }
3001 }
3002
3003 void CheckOrigin() {
3004 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003005 // Origin isn't a crypto param, but it always lives with them.
3006 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003007 }
3008};
3009
3010/*
3011 * ImportKeyTest.RsaSuccess
3012 *
3013 * Verifies that importing and using an RSA key pair works correctly.
3014 */
3015TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003016 uint32_t key_size;
3017 string key;
3018
3019 if (SecLevel() == SecurityLevel::STRONGBOX) {
3020 key_size = 2048;
3021 key = rsa_2048_key;
3022 } else {
3023 key_size = 1024;
3024 key = rsa_key;
3025 }
3026
Selene Huang31ab4042020-04-29 04:22:39 -07003027 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3028 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003029 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003030 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003031 .Padding(PaddingMode::RSA_PSS)
3032 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003033 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003034
3035 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003036 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003037 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3038 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3039 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3040 CheckOrigin();
3041
3042 string message(1024 / 8, 'a');
3043 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3044 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003045 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003046}
3047
3048/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003049 * ImportKeyTest.RsaSuccessWithoutParams
3050 *
3051 * Verifies that importing and using an RSA key pair without specifying parameters
3052 * works correctly.
3053 */
3054TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3055 uint32_t key_size;
3056 string key;
3057
3058 if (SecLevel() == SecurityLevel::STRONGBOX) {
3059 key_size = 2048;
3060 key = rsa_2048_key;
3061 } else {
3062 key_size = 1024;
3063 key = rsa_key;
3064 }
3065
3066 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3067 .Authorization(TAG_NO_AUTH_REQUIRED)
3068 .SigningKey()
3069 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3070 .Digest(Digest::SHA_2_256)
3071 .Padding(PaddingMode::RSA_PSS)
3072 .SetDefaultValidity(),
3073 KeyFormat::PKCS8, key));
3074
3075 // Key size and public exponent are determined from the imported key material.
3076 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3077 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3078
3079 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3080 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3081 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3082 CheckOrigin();
3083
3084 string message(1024 / 8, 'a');
3085 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3086 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003087 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003088}
3089
3090/*
Selene Huang31ab4042020-04-29 04:22:39 -07003091 * ImportKeyTest.RsaKeySizeMismatch
3092 *
3093 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3094 * correct way.
3095 */
3096TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3097 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3098 ImportKey(AuthorizationSetBuilder()
3099 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3100 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003101 .Padding(PaddingMode::NONE)
3102 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003103 KeyFormat::PKCS8, rsa_key));
3104}
3105
3106/*
3107 * ImportKeyTest.RsaPublicExponentMismatch
3108 *
3109 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3110 * fails in the correct way.
3111 */
3112TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3113 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3114 ImportKey(AuthorizationSetBuilder()
3115 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3116 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003117 .Padding(PaddingMode::NONE)
3118 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003119 KeyFormat::PKCS8, rsa_key));
3120}
3121
3122/*
3123 * ImportKeyTest.EcdsaSuccess
3124 *
3125 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3126 */
3127TEST_P(ImportKeyTest, EcdsaSuccess) {
3128 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3129 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003130 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003131 .Digest(Digest::SHA_2_256)
3132 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003133 KeyFormat::PKCS8, ec_256_key));
3134
3135 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003136 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3137 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3138
3139 CheckOrigin();
3140
3141 string message(32, 'a');
3142 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3143 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003144 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003145}
3146
3147/*
3148 * ImportKeyTest.EcdsaP256RFC5915Success
3149 *
3150 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3151 * correctly.
3152 */
3153TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3154 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3155 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003156 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003157 .Digest(Digest::SHA_2_256)
3158 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003159 KeyFormat::PKCS8, ec_256_key_rfc5915));
3160
3161 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003162 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3163 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3164
3165 CheckOrigin();
3166
3167 string message(32, 'a');
3168 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3169 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003170 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003171}
3172
3173/*
3174 * ImportKeyTest.EcdsaP256SEC1Success
3175 *
3176 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3177 */
3178TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3179 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3180 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003181 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003182 .Digest(Digest::SHA_2_256)
3183 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003184 KeyFormat::PKCS8, ec_256_key_sec1));
3185
3186 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003187 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3188 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3189
3190 CheckOrigin();
3191
3192 string message(32, 'a');
3193 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3194 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003195 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003196}
3197
3198/*
3199 * ImportKeyTest.Ecdsa521Success
3200 *
3201 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3202 */
3203TEST_P(ImportKeyTest, Ecdsa521Success) {
3204 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3205 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3206 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003207 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003208 .Digest(Digest::SHA_2_256)
3209 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003210 KeyFormat::PKCS8, ec_521_key));
3211
3212 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003213 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3214 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3215 CheckOrigin();
3216
3217 string message(32, 'a');
3218 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3219 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003220 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003221}
3222
3223/*
Selene Huang31ab4042020-04-29 04:22:39 -07003224 * ImportKeyTest.EcdsaCurveMismatch
3225 *
3226 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3227 * the correct way.
3228 */
3229TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3230 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3231 ImportKey(AuthorizationSetBuilder()
3232 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003233 .Digest(Digest::NONE)
3234 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003235 KeyFormat::PKCS8, ec_256_key));
3236}
3237
3238/*
3239 * ImportKeyTest.AesSuccess
3240 *
3241 * Verifies that importing and using an AES key works.
3242 */
3243TEST_P(ImportKeyTest, AesSuccess) {
3244 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3245 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3246 .Authorization(TAG_NO_AUTH_REQUIRED)
3247 .AesEncryptionKey(key.size() * 8)
3248 .EcbMode()
3249 .Padding(PaddingMode::PKCS7),
3250 KeyFormat::RAW, key));
3251
3252 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3253 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3254 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3255 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3256 CheckOrigin();
3257
3258 string message = "Hello World!";
3259 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3260 string ciphertext = EncryptMessage(message, params);
3261 string plaintext = DecryptMessage(ciphertext, params);
3262 EXPECT_EQ(message, plaintext);
3263}
3264
3265/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003266 * ImportKeyTest.AesFailure
3267 *
3268 * Verifies that importing an invalid AES key fails.
3269 */
3270TEST_P(ImportKeyTest, AesFailure) {
3271 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3272 uint32_t bitlen = key.size() * 8;
3273 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003274 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003275 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003276 .Authorization(TAG_NO_AUTH_REQUIRED)
3277 .AesEncryptionKey(key_size)
3278 .EcbMode()
3279 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003280 KeyFormat::RAW, key);
3281 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003282 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3283 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003284 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003285
3286 // Explicit key size matches that of the provided key, but it's not a valid size.
3287 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3288 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3289 ImportKey(AuthorizationSetBuilder()
3290 .Authorization(TAG_NO_AUTH_REQUIRED)
3291 .AesEncryptionKey(long_key.size() * 8)
3292 .EcbMode()
3293 .Padding(PaddingMode::PKCS7),
3294 KeyFormat::RAW, long_key));
3295 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3296 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3297 ImportKey(AuthorizationSetBuilder()
3298 .Authorization(TAG_NO_AUTH_REQUIRED)
3299 .AesEncryptionKey(short_key.size() * 8)
3300 .EcbMode()
3301 .Padding(PaddingMode::PKCS7),
3302 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003303}
3304
3305/*
3306 * ImportKeyTest.TripleDesSuccess
3307 *
3308 * Verifies that importing and using a 3DES key works.
3309 */
3310TEST_P(ImportKeyTest, TripleDesSuccess) {
3311 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3312 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3313 .Authorization(TAG_NO_AUTH_REQUIRED)
3314 .TripleDesEncryptionKey(168)
3315 .EcbMode()
3316 .Padding(PaddingMode::PKCS7),
3317 KeyFormat::RAW, key));
3318
3319 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3320 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3321 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3322 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3323 CheckOrigin();
3324
3325 string message = "Hello World!";
3326 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3327 string ciphertext = EncryptMessage(message, params);
3328 string plaintext = DecryptMessage(ciphertext, params);
3329 EXPECT_EQ(message, plaintext);
3330}
3331
3332/*
3333 * ImportKeyTest.TripleDesFailure
3334 *
3335 * Verifies that importing an invalid 3DES key fails.
3336 */
3337TEST_P(ImportKeyTest, TripleDesFailure) {
3338 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003339 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003340 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003341 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003342 auto result = ImportKey(AuthorizationSetBuilder()
David Drysdale7de9feb2021-03-05 14:56:19 +00003343 .Authorization(TAG_NO_AUTH_REQUIRED)
3344 .TripleDesEncryptionKey(key_size)
3345 .EcbMode()
3346 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003347 KeyFormat::RAW, key);
3348 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003349 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3350 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003351 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003352 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003353 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003354 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3355 ImportKey(AuthorizationSetBuilder()
3356 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003357 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003358 .EcbMode()
3359 .Padding(PaddingMode::PKCS7),
3360 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003361 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003362 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3363 ImportKey(AuthorizationSetBuilder()
3364 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003365 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003366 .EcbMode()
3367 .Padding(PaddingMode::PKCS7),
3368 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003369}
3370
3371/*
3372 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003373 *
3374 * Verifies that importing and using an HMAC key works.
3375 */
3376TEST_P(ImportKeyTest, HmacKeySuccess) {
3377 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3378 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3379 .Authorization(TAG_NO_AUTH_REQUIRED)
3380 .HmacKey(key.size() * 8)
3381 .Digest(Digest::SHA_2_256)
3382 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3383 KeyFormat::RAW, key));
3384
3385 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3386 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3387 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3388 CheckOrigin();
3389
3390 string message = "Hello World!";
3391 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3392 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3393}
3394
3395INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3396
3397auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003398 // IKeyMintDevice.aidl
3399 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3400 "020100" // INTEGER length 1 value 0x00 (version)
3401 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3402 "934bf94e2aa28a3f83c9f79297250262"
3403 "fbe3276b5a1c91159bbfa3ef8957aac8"
3404 "4b59b30b455a79c2973480823d8b3863"
3405 "c3deef4a8e243590268d80e18751a0e1"
3406 "30f67ce6a1ace9f79b95e097474febc9"
3407 "81195b1d13a69086c0863f66a7b7fdb4"
3408 "8792227b1ac5e2489febdf087ab54864"
3409 "83033a6f001ca5d1ec1e27f5c30f4cec"
3410 "2642074a39ae68aee552e196627a8e3d"
3411 "867e67a8c01b11e75f13cca0a97ab668"
3412 "b50cda07a8ecb7cd8e3dd7009c963653"
3413 "4f6f239cffe1fc8daa466f78b676c711"
3414 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3415 "99b801597d5220e307eaa5bee507fb94"
3416 "d1fa69f9e519b2de315bac92c36f2ea1"
3417 "fa1df4478c0ddedeae8c70e0233cd098"
3418 "040c" // OCTET STRING length 0x0c (initializationVector)
3419 "d796b02c370f1fa4cc0124f1"
3420 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3421 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3422 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3423 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3424 "3106" // SET length 0x06
3425 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3426 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3427 // } end SET
3428 // } end [1]
3429 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3430 "020120" // INTEGER length 1 value 0x20 (AES)
3431 // } end [2]
3432 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3433 "02020100" // INTEGER length 2 value 0x100
3434 // } end [3]
3435 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3436 "3103" // SET length 0x03 {
3437 "020101" // INTEGER length 1 value 0x01 (ECB)
3438 // } end SET
3439 // } end [4]
3440 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3441 "3103" // SET length 0x03 {
3442 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3443 // } end SET
3444 // } end [5]
3445 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3446 // (noAuthRequired)
3447 "0500" // NULL
3448 // } end [503]
3449 // } end SEQUENCE (AuthorizationList)
3450 // } end SEQUENCE (KeyDescription)
3451 "0420" // OCTET STRING length 0x20 (encryptedKey)
3452 "ccd540855f833a5e1480bfd2d36faf3a"
3453 "eee15df5beabe2691bc82dde2a7aa910"
3454 "0410" // OCTET STRING length 0x10 (tag)
3455 "64c9f689c60ff6223ab6e6999e0eb6e5"
3456 // } SEQUENCE (SecureKeyWrapper)
3457);
Selene Huang31ab4042020-04-29 04:22:39 -07003458
3459auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003460 // IKeyMintDevice.aidl
3461 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3462 "020100" // INTEGER length 1 value 0x00 (version)
3463 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3464 "aad93ed5924f283b4bb5526fbe7a1412"
3465 "f9d9749ec30db9062b29e574a8546f33"
3466 "c88732452f5b8e6a391ee76c39ed1712"
3467 "c61d8df6213dec1cffbc17a8c6d04c7b"
3468 "30893d8daa9b2015213e219468215532"
3469 "07f8f9931c4caba23ed3bee28b36947e"
3470 "47f10e0a5c3dc51c988a628daad3e5e1"
3471 "f4005e79c2d5a96c284b4b8d7e4948f3"
3472 "31e5b85dd5a236f85579f3ea1d1b8484"
3473 "87470bdb0ab4f81a12bee42c99fe0df4"
3474 "bee3759453e69ad1d68a809ce06b949f"
3475 "7694a990429b2fe81e066ff43e56a216"
3476 "02db70757922a4bcc23ab89f1e35da77"
3477 "586775f423e519c2ea394caf48a28d0c"
3478 "8020f1dcf6b3a68ec246f615ae96dae9"
3479 "a079b1f6eb959033c1af5c125fd94168"
3480 "040c" // OCTET STRING length 0x0c (initializationVector)
3481 "6d9721d08589581ab49204a3"
3482 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3483 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3484 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3485 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3486 "3106" // SET length 0x06
3487 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3488 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3489 // } end SET
3490 // } end [1]
3491 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3492 "020120" // INTEGER length 1 value 0x20 (AES)
3493 // } end [2]
3494 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3495 "02020100" // INTEGER length 2 value 0x100
3496 // } end [3]
3497 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3498 "3103" // SET length 0x03 {
3499 "020101" // INTEGER length 1 value 0x01 (ECB)
3500 // } end SET
3501 // } end [4]
3502 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3503 "3103" // SET length 0x03 {
3504 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3505 // } end SET
3506 // } end [5]
3507 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3508 // (noAuthRequired)
3509 "0500" // NULL
3510 // } end [503]
3511 // } end SEQUENCE (AuthorizationList)
3512 // } end SEQUENCE (KeyDescription)
3513 "0420" // OCTET STRING length 0x20 (encryptedKey)
3514 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3515 "c20d1f99a9a024a76f35c8e2cab9b68d"
3516 "0410" // OCTET STRING length 0x10 (tag)
3517 "2560c70109ae67c030f00b98b512a670"
3518 // } SEQUENCE (SecureKeyWrapper)
3519);
Selene Huang31ab4042020-04-29 04:22:39 -07003520
3521auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003522 // RFC 5208 s5
3523 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3524 "020100" // INTEGER length 1 value 0x00 (version)
3525 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3526 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3527 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3528 "0500" // NULL (parameters)
3529 // } SEQUENCE (AlgorithmIdentifier)
3530 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3531 // RFC 8017 A.1.2
3532 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3533 "020100" // INTEGER length 1 value 0x00 (version)
3534 "02820101" // INTEGER length 0x0101 (modulus) value...
3535 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3536 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3537 "7b06e673a837313d56b1c725150a3fef" // 0x30
3538 "86acbddc41bb759c2854eae32d35841e" // 0x40
3539 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3540 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3541 "312d7bd5921ffaea1347c157406fef71" // 0x70
3542 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3543 "f4645c11f5c1374c3886427411c44979" // 0x90
3544 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3545 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3546 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3547 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3548 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3549 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3550 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3551 "55" // 0x101
3552 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3553 "02820100" // INTEGER length 0x100 (privateExponent) value...
3554 "431447b6251908112b1ee76f99f3711a" // 0x10
3555 "52b6630960046c2de70de188d833f8b8" // 0x20
3556 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3557 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3558 "e710b630a03adc683b5d2c43080e52be" // 0x50
3559 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3560 "822bccff087d63c940ba8a45f670feb2" // 0x70
3561 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3562 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3563 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3564 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3565 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3566 "52659d5a5ba05b663737a8696281865b" // 0xd0
3567 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3568 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3569 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3570 "028181" // INTEGER length 0x81 (prime1) value...
3571 "00de392e18d682c829266cc3454e1d61" // 0x10
3572 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3573 "ff841be5bac82a164c5970007047b8c5" // 0x30
3574 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3575 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3576 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3577 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3578 "9e91346130748a6e3c124f9149d71c74" // 0x80
3579 "35"
3580 "028181" // INTEGER length 0x81 (prime2) value...
3581 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3582 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3583 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3584 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3585 "9ed39a2d934c880440aed8832f984316" // 0x50
3586 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3587 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3588 "b880677c068e1be936e81288815252a8" // 0x80
3589 "a1"
3590 "028180" // INTEGER length 0x80 (exponent1) value...
3591 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3592 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3593 "5a063212a4f105a3764743e53281988a" // 0x30
3594 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3595 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3596 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3597 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3598 "4719d6e2b9439823719cd08bcd031781" // 0x80
3599 "028181" // INTEGER length 0x81 (exponent2) value...
3600 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3601 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3602 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3603 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3604 "1254186af30b22c10582a8a43e34fe94" // 0x50
3605 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3606 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3607 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3608 "61"
3609 "028181" // INTEGER length 0x81 (coefficient) value...
3610 "00c931617c77829dfb1270502be9195c" // 0x10
3611 "8f2830885f57dba869536811e6864236" // 0x20
3612 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3613 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3614 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3615 "959356210723287b0affcc9f727044d4" // 0x60
3616 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3617 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3618 "22"
3619 // } SEQUENCE
3620 // } SEQUENCE ()
3621);
Selene Huang31ab4042020-04-29 04:22:39 -07003622
3623string zero_masking_key =
3624 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3625string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3626
3627class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3628
3629TEST_P(ImportWrappedKeyTest, Success) {
3630 auto wrapping_key_desc = AuthorizationSetBuilder()
3631 .RsaEncryptionKey(2048, 65537)
3632 .Digest(Digest::SHA_2_256)
3633 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003634 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3635 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003636
3637 ASSERT_EQ(ErrorCode::OK,
3638 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3639 AuthorizationSetBuilder()
3640 .Digest(Digest::SHA_2_256)
3641 .Padding(PaddingMode::RSA_OAEP)));
3642
3643 string message = "Hello World!";
3644 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3645 string ciphertext = EncryptMessage(message, params);
3646 string plaintext = DecryptMessage(ciphertext, params);
3647 EXPECT_EQ(message, plaintext);
3648}
3649
David Drysdaled2cc8c22021-04-15 13:29:45 +01003650/*
3651 * ImportWrappedKeyTest.SuccessSidsIgnored
3652 *
3653 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3654 * include Tag:USER_SECURE_ID.
3655 */
3656TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3657 auto wrapping_key_desc = AuthorizationSetBuilder()
3658 .RsaEncryptionKey(2048, 65537)
3659 .Digest(Digest::SHA_2_256)
3660 .Padding(PaddingMode::RSA_OAEP)
3661 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3662 .SetDefaultValidity();
3663
3664 int64_t password_sid = 42;
3665 int64_t biometric_sid = 24;
3666 ASSERT_EQ(ErrorCode::OK,
3667 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3668 AuthorizationSetBuilder()
3669 .Digest(Digest::SHA_2_256)
3670 .Padding(PaddingMode::RSA_OAEP),
3671 password_sid, biometric_sid));
3672
3673 string message = "Hello World!";
3674 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3675 string ciphertext = EncryptMessage(message, params);
3676 string plaintext = DecryptMessage(ciphertext, params);
3677 EXPECT_EQ(message, plaintext);
3678}
3679
Selene Huang31ab4042020-04-29 04:22:39 -07003680TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3681 auto wrapping_key_desc = AuthorizationSetBuilder()
3682 .RsaEncryptionKey(2048, 65537)
3683 .Digest(Digest::SHA_2_256)
3684 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003685 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3686 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003687
3688 ASSERT_EQ(ErrorCode::OK,
3689 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3690 AuthorizationSetBuilder()
3691 .Digest(Digest::SHA_2_256)
3692 .Padding(PaddingMode::RSA_OAEP)));
3693}
3694
3695TEST_P(ImportWrappedKeyTest, WrongMask) {
3696 auto wrapping_key_desc = AuthorizationSetBuilder()
3697 .RsaEncryptionKey(2048, 65537)
3698 .Digest(Digest::SHA_2_256)
3699 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003700 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3701 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003702
3703 ASSERT_EQ(
3704 ErrorCode::VERIFICATION_FAILED,
3705 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3706 AuthorizationSetBuilder()
3707 .Digest(Digest::SHA_2_256)
3708 .Padding(PaddingMode::RSA_OAEP)));
3709}
3710
3711TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3712 auto wrapping_key_desc = AuthorizationSetBuilder()
3713 .RsaEncryptionKey(2048, 65537)
3714 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003715 .Padding(PaddingMode::RSA_OAEP)
3716 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003717
3718 ASSERT_EQ(
3719 ErrorCode::INCOMPATIBLE_PURPOSE,
3720 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3721 AuthorizationSetBuilder()
3722 .Digest(Digest::SHA_2_256)
3723 .Padding(PaddingMode::RSA_OAEP)));
3724}
3725
David Drysdaled2cc8c22021-04-15 13:29:45 +01003726TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3727 auto wrapping_key_desc = AuthorizationSetBuilder()
3728 .RsaEncryptionKey(2048, 65537)
3729 .Digest(Digest::SHA_2_256)
3730 .Padding(PaddingMode::RSA_PSS)
3731 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3732 .SetDefaultValidity();
3733
3734 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3735 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3736 AuthorizationSetBuilder()
3737 .Digest(Digest::SHA_2_256)
3738 .Padding(PaddingMode::RSA_OAEP)));
3739}
3740
3741TEST_P(ImportWrappedKeyTest, WrongDigest) {
3742 auto wrapping_key_desc = AuthorizationSetBuilder()
3743 .RsaEncryptionKey(2048, 65537)
3744 .Digest(Digest::SHA_2_512)
3745 .Padding(PaddingMode::RSA_OAEP)
3746 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3747 .SetDefaultValidity();
3748
3749 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3750 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3751 AuthorizationSetBuilder()
3752 .Digest(Digest::SHA_2_256)
3753 .Padding(PaddingMode::RSA_OAEP)));
3754}
3755
Selene Huang31ab4042020-04-29 04:22:39 -07003756INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3757
3758typedef KeyMintAidlTestBase EncryptionOperationsTest;
3759
3760/*
3761 * EncryptionOperationsTest.RsaNoPaddingSuccess
3762 *
David Drysdale59cae642021-05-12 13:52:03 +01003763 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003764 */
3765TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003766 for (uint64_t exponent : {3, 65537}) {
3767 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3768 .Authorization(TAG_NO_AUTH_REQUIRED)
3769 .RsaEncryptionKey(2048, exponent)
3770 .Padding(PaddingMode::NONE)
3771 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003772
David Drysdaled2cc8c22021-04-15 13:29:45 +01003773 string message = string(2048 / 8, 'a');
3774 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003775 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003776 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003777
David Drysdale59cae642021-05-12 13:52:03 +01003778 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003779 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003780
David Drysdaled2cc8c22021-04-15 13:29:45 +01003781 // Unpadded RSA is deterministic
3782 EXPECT_EQ(ciphertext1, ciphertext2);
3783
3784 CheckedDeleteKey();
3785 }
Selene Huang31ab4042020-04-29 04:22:39 -07003786}
3787
3788/*
3789 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3790 *
David Drysdale59cae642021-05-12 13:52:03 +01003791 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003792 */
3793TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3794 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3795 .Authorization(TAG_NO_AUTH_REQUIRED)
3796 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003797 .Padding(PaddingMode::NONE)
3798 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003799
3800 string message = "1";
3801 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3802
David Drysdale59cae642021-05-12 13:52:03 +01003803 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003804 EXPECT_EQ(2048U / 8, ciphertext.size());
3805
3806 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3807 string plaintext = DecryptMessage(ciphertext, params);
3808
3809 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003810}
3811
3812/*
Selene Huang31ab4042020-04-29 04:22:39 -07003813 * EncryptionOperationsTest.RsaOaepSuccess
3814 *
David Drysdale59cae642021-05-12 13:52:03 +01003815 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003816 */
3817TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3818 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3819
3820 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01003821 ASSERT_EQ(ErrorCode::OK,
3822 GenerateKey(AuthorizationSetBuilder()
3823 .Authorization(TAG_NO_AUTH_REQUIRED)
3824 .RsaEncryptionKey(key_size, 65537)
3825 .Padding(PaddingMode::RSA_OAEP)
3826 .Digest(digests)
3827 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3828 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003829
3830 string message = "Hello";
3831
3832 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01003833 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3834
3835 auto params = AuthorizationSetBuilder()
3836 .Digest(digest)
3837 .Padding(PaddingMode::RSA_OAEP)
3838 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3839 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003840 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3841 EXPECT_EQ(key_size / 8, ciphertext1.size());
3842
David Drysdale59cae642021-05-12 13:52:03 +01003843 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003844 EXPECT_EQ(key_size / 8, ciphertext2.size());
3845
3846 // OAEP randomizes padding so every result should be different (with astronomically high
3847 // probability).
3848 EXPECT_NE(ciphertext1, ciphertext2);
3849
3850 string plaintext1 = DecryptMessage(ciphertext1, params);
3851 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3852 string plaintext2 = DecryptMessage(ciphertext2, params);
3853 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3854
3855 // Decrypting corrupted ciphertext should fail.
3856 size_t offset_to_corrupt = random() % ciphertext1.size();
3857 char corrupt_byte;
3858 do {
3859 corrupt_byte = static_cast<char>(random() % 256);
3860 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3861 ciphertext1[offset_to_corrupt] = corrupt_byte;
3862
3863 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3864 string result;
3865 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3866 EXPECT_EQ(0U, result.size());
3867 }
3868}
3869
3870/*
3871 * EncryptionOperationsTest.RsaOaepInvalidDigest
3872 *
David Drysdale59cae642021-05-12 13:52:03 +01003873 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003874 * without a digest.
3875 */
3876TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3877 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3878 .Authorization(TAG_NO_AUTH_REQUIRED)
3879 .RsaEncryptionKey(2048, 65537)
3880 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003881 .Digest(Digest::NONE)
3882 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003883
3884 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003885 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003886}
3887
3888/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003889 * EncryptionOperationsTest.RsaOaepInvalidPadding
3890 *
David Drysdale59cae642021-05-12 13:52:03 +01003891 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003892 * with a padding value that is only suitable for signing/verifying.
3893 */
3894TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3895 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3896 .Authorization(TAG_NO_AUTH_REQUIRED)
3897 .RsaEncryptionKey(2048, 65537)
3898 .Padding(PaddingMode::RSA_PSS)
3899 .Digest(Digest::NONE)
3900 .SetDefaultValidity()));
3901
3902 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003903 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003904}
3905
3906/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003907 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003908 *
David Drysdale59cae642021-05-12 13:52:03 +01003909 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003910 * with a different digest than was used to encrypt.
3911 */
3912TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3913 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3914
3915 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3916 .Authorization(TAG_NO_AUTH_REQUIRED)
3917 .RsaEncryptionKey(1024, 65537)
3918 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003919 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3920 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003921 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01003922 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07003923 message,
3924 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3925
3926 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3927 .Digest(Digest::SHA_2_256)
3928 .Padding(PaddingMode::RSA_OAEP)));
3929 string result;
3930 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3931 EXPECT_EQ(0U, result.size());
3932}
3933
3934/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003935 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3936 *
David Drysdale59cae642021-05-12 13:52:03 +01003937 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003938 * digests.
3939 */
3940TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3941 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3942
3943 size_t key_size = 2048; // Need largish key for SHA-512 test.
3944 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3945 .OaepMGFDigest(digests)
3946 .Authorization(TAG_NO_AUTH_REQUIRED)
3947 .RsaEncryptionKey(key_size, 65537)
3948 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003949 .Digest(Digest::SHA_2_256)
3950 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003951
3952 string message = "Hello";
3953
3954 for (auto digest : digests) {
3955 auto params = AuthorizationSetBuilder()
3956 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3957 .Digest(Digest::SHA_2_256)
3958 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01003959 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003960 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3961 EXPECT_EQ(key_size / 8, ciphertext1.size());
3962
David Drysdale59cae642021-05-12 13:52:03 +01003963 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003964 EXPECT_EQ(key_size / 8, ciphertext2.size());
3965
3966 // OAEP randomizes padding so every result should be different (with astronomically high
3967 // probability).
3968 EXPECT_NE(ciphertext1, ciphertext2);
3969
3970 string plaintext1 = DecryptMessage(ciphertext1, params);
3971 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3972 string plaintext2 = DecryptMessage(ciphertext2, params);
3973 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3974
3975 // Decrypting corrupted ciphertext should fail.
3976 size_t offset_to_corrupt = random() % ciphertext1.size();
3977 char corrupt_byte;
3978 do {
3979 corrupt_byte = static_cast<char>(random() % 256);
3980 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3981 ciphertext1[offset_to_corrupt] = corrupt_byte;
3982
3983 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3984 string result;
3985 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3986 EXPECT_EQ(0U, result.size());
3987 }
3988}
3989
3990/*
3991 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3992 *
David Drysdale59cae642021-05-12 13:52:03 +01003993 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003994 * with incompatible MGF digest.
3995 */
3996TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
3997 ASSERT_EQ(ErrorCode::OK,
3998 GenerateKey(AuthorizationSetBuilder()
3999 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4000 .Authorization(TAG_NO_AUTH_REQUIRED)
4001 .RsaEncryptionKey(2048, 65537)
4002 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004003 .Digest(Digest::SHA_2_256)
4004 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004005 string message = "Hello World!";
4006
4007 auto params = AuthorizationSetBuilder()
4008 .Padding(PaddingMode::RSA_OAEP)
4009 .Digest(Digest::SHA_2_256)
4010 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004011 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004012}
4013
4014/*
4015 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4016 *
4017 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4018 * with unsupported MGF digest.
4019 */
4020TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4021 ASSERT_EQ(ErrorCode::OK,
4022 GenerateKey(AuthorizationSetBuilder()
4023 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4024 .Authorization(TAG_NO_AUTH_REQUIRED)
4025 .RsaEncryptionKey(2048, 65537)
4026 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004027 .Digest(Digest::SHA_2_256)
4028 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004029 string message = "Hello World!";
4030
4031 auto params = AuthorizationSetBuilder()
4032 .Padding(PaddingMode::RSA_OAEP)
4033 .Digest(Digest::SHA_2_256)
4034 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004035 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004036}
4037
4038/*
Selene Huang31ab4042020-04-29 04:22:39 -07004039 * EncryptionOperationsTest.RsaPkcs1Success
4040 *
4041 * Verifies that RSA PKCS encryption/decrypts works.
4042 */
4043TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4044 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4045 .Authorization(TAG_NO_AUTH_REQUIRED)
4046 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004047 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4048 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004049
4050 string message = "Hello World!";
4051 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004052 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004053 EXPECT_EQ(2048U / 8, ciphertext1.size());
4054
David Drysdale59cae642021-05-12 13:52:03 +01004055 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004056 EXPECT_EQ(2048U / 8, ciphertext2.size());
4057
4058 // PKCS1 v1.5 randomizes padding so every result should be different.
4059 EXPECT_NE(ciphertext1, ciphertext2);
4060
4061 string plaintext = DecryptMessage(ciphertext1, params);
4062 EXPECT_EQ(message, plaintext);
4063
4064 // Decrypting corrupted ciphertext should fail.
4065 size_t offset_to_corrupt = random() % ciphertext1.size();
4066 char corrupt_byte;
4067 do {
4068 corrupt_byte = static_cast<char>(random() % 256);
4069 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4070 ciphertext1[offset_to_corrupt] = corrupt_byte;
4071
4072 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4073 string result;
4074 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4075 EXPECT_EQ(0U, result.size());
4076}
4077
4078/*
Selene Huang31ab4042020-04-29 04:22:39 -07004079 * EncryptionOperationsTest.EcdsaEncrypt
4080 *
4081 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4082 */
4083TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4084 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4085 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004086 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004087 .Digest(Digest::NONE)
4088 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004089 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4090 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4091 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4092}
4093
4094/*
4095 * EncryptionOperationsTest.HmacEncrypt
4096 *
4097 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4098 */
4099TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4100 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4101 .Authorization(TAG_NO_AUTH_REQUIRED)
4102 .HmacKey(128)
4103 .Digest(Digest::SHA_2_256)
4104 .Padding(PaddingMode::NONE)
4105 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4106 auto params = AuthorizationSetBuilder()
4107 .Digest(Digest::SHA_2_256)
4108 .Padding(PaddingMode::NONE)
4109 .Authorization(TAG_MAC_LENGTH, 128);
4110 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4111 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4112}
4113
4114/*
4115 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4116 *
4117 * Verifies that AES ECB mode works.
4118 */
4119TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4120 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4121 .Authorization(TAG_NO_AUTH_REQUIRED)
4122 .AesEncryptionKey(128)
4123 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4124 .Padding(PaddingMode::NONE)));
4125
4126 ASSERT_GT(key_blob_.size(), 0U);
4127 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4128
4129 // Two-block message.
4130 string message = "12345678901234567890123456789012";
4131 string ciphertext1 = EncryptMessage(message, params);
4132 EXPECT_EQ(message.size(), ciphertext1.size());
4133
4134 string ciphertext2 = EncryptMessage(string(message), params);
4135 EXPECT_EQ(message.size(), ciphertext2.size());
4136
4137 // ECB is deterministic.
4138 EXPECT_EQ(ciphertext1, ciphertext2);
4139
4140 string plaintext = DecryptMessage(ciphertext1, params);
4141 EXPECT_EQ(message, plaintext);
4142}
4143
4144/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004145 * EncryptionOperationsTest.AesEcbUnknownTag
4146 *
4147 * Verifies that AES ECB operations ignore unknown tags.
4148 */
4149TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4150 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4151 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4152 KeyParameter unknown_param;
4153 unknown_param.tag = unknown_tag;
4154
4155 vector<KeyCharacteristics> key_characteristics;
4156 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4157 .Authorization(TAG_NO_AUTH_REQUIRED)
4158 .AesEncryptionKey(128)
4159 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4160 .Padding(PaddingMode::NONE)
4161 .Authorization(unknown_param),
4162 &key_blob_, &key_characteristics));
4163 ASSERT_GT(key_blob_.size(), 0U);
4164
4165 // Unknown tags should not be returned in key characteristics.
4166 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4167 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4168 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4169 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4170
4171 // Encrypt without mentioning the unknown parameter.
4172 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4173 string message = "12345678901234567890123456789012";
4174 string ciphertext = EncryptMessage(message, params);
4175 EXPECT_EQ(message.size(), ciphertext.size());
4176
4177 // Decrypt including the unknown parameter.
4178 auto decrypt_params = AuthorizationSetBuilder()
4179 .BlockMode(BlockMode::ECB)
4180 .Padding(PaddingMode::NONE)
4181 .Authorization(unknown_param);
4182 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4183 EXPECT_EQ(message, plaintext);
4184}
4185
4186/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004187 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004188 *
4189 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4190 */
4191TEST_P(EncryptionOperationsTest, AesWrongMode) {
4192 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4193 .Authorization(TAG_NO_AUTH_REQUIRED)
4194 .AesEncryptionKey(128)
4195 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4196 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004197 ASSERT_GT(key_blob_.size(), 0U);
4198
Selene Huang31ab4042020-04-29 04:22:39 -07004199 EXPECT_EQ(
4200 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4201 Begin(KeyPurpose::ENCRYPT,
4202 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4203}
4204
4205/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004206 * EncryptionOperationsTest.AesWrongPadding
4207 *
4208 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4209 */
4210TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4211 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4212 .Authorization(TAG_NO_AUTH_REQUIRED)
4213 .AesEncryptionKey(128)
4214 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4215 .Padding(PaddingMode::NONE)));
4216 ASSERT_GT(key_blob_.size(), 0U);
4217
4218 EXPECT_EQ(
4219 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4220 Begin(KeyPurpose::ENCRYPT,
4221 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4222}
4223
4224/*
4225 * EncryptionOperationsTest.AesInvalidParams
4226 *
4227 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4228 */
4229TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4230 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4231 .Authorization(TAG_NO_AUTH_REQUIRED)
4232 .AesEncryptionKey(128)
4233 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4234 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4235 .Padding(PaddingMode::NONE)
4236 .Padding(PaddingMode::PKCS7)));
4237 ASSERT_GT(key_blob_.size(), 0U);
4238
4239 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4240 .BlockMode(BlockMode::CBC)
4241 .BlockMode(BlockMode::ECB)
4242 .Padding(PaddingMode::NONE));
4243 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4244 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4245
4246 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4247 .BlockMode(BlockMode::ECB)
4248 .Padding(PaddingMode::NONE)
4249 .Padding(PaddingMode::PKCS7));
4250 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4251 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4252}
4253
4254/*
Selene Huang31ab4042020-04-29 04:22:39 -07004255 * EncryptionOperationsTest.AesWrongPurpose
4256 *
4257 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4258 * specified.
4259 */
4260TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4261 auto err = GenerateKey(AuthorizationSetBuilder()
4262 .Authorization(TAG_NO_AUTH_REQUIRED)
4263 .AesKey(128)
4264 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4265 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4266 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4267 .Padding(PaddingMode::NONE));
4268 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4269 ASSERT_GT(key_blob_.size(), 0U);
4270
4271 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4272 .BlockMode(BlockMode::GCM)
4273 .Padding(PaddingMode::NONE)
4274 .Authorization(TAG_MAC_LENGTH, 128));
4275 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4276
4277 CheckedDeleteKey();
4278
4279 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4280 .Authorization(TAG_NO_AUTH_REQUIRED)
4281 .AesKey(128)
4282 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4283 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4284 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4285 .Padding(PaddingMode::NONE)));
4286
4287 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4288 .BlockMode(BlockMode::GCM)
4289 .Padding(PaddingMode::NONE)
4290 .Authorization(TAG_MAC_LENGTH, 128));
4291 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4292}
4293
4294/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004295 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004296 *
4297 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4298 * multiple of the block size and no padding is specified.
4299 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004300TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4301 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4302 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4303 .Authorization(TAG_NO_AUTH_REQUIRED)
4304 .AesEncryptionKey(128)
4305 .Authorization(TAG_BLOCK_MODE, blockMode)
4306 .Padding(PaddingMode::NONE)));
4307 // Message is slightly shorter than two blocks.
4308 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004309
David Drysdaled2cc8c22021-04-15 13:29:45 +01004310 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4311 AuthorizationSet out_params;
4312 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4313 string ciphertext;
4314 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4315 EXPECT_EQ(0U, ciphertext.size());
4316
4317 CheckedDeleteKey();
4318 }
Selene Huang31ab4042020-04-29 04:22:39 -07004319}
4320
4321/*
4322 * EncryptionOperationsTest.AesEcbPkcs7Padding
4323 *
4324 * Verifies that AES PKCS7 padding works for any message length.
4325 */
4326TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4327 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4328 .Authorization(TAG_NO_AUTH_REQUIRED)
4329 .AesEncryptionKey(128)
4330 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4331 .Padding(PaddingMode::PKCS7)));
4332
4333 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4334
4335 // Try various message lengths; all should work.
4336 for (size_t i = 0; i < 32; ++i) {
4337 string message(i, 'a');
4338 string ciphertext = EncryptMessage(message, params);
4339 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4340 string plaintext = DecryptMessage(ciphertext, params);
4341 EXPECT_EQ(message, plaintext);
4342 }
4343}
4344
4345/*
4346 * EncryptionOperationsTest.AesEcbWrongPadding
4347 *
4348 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4349 * specified.
4350 */
4351TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4352 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4353 .Authorization(TAG_NO_AUTH_REQUIRED)
4354 .AesEncryptionKey(128)
4355 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4356 .Padding(PaddingMode::NONE)));
4357
4358 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4359
4360 // Try various message lengths; all should fail
4361 for (size_t i = 0; i < 32; ++i) {
4362 string message(i, 'a');
4363 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4364 }
4365}
4366
4367/*
4368 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4369 *
4370 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4371 */
4372TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4373 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4374 .Authorization(TAG_NO_AUTH_REQUIRED)
4375 .AesEncryptionKey(128)
4376 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4377 .Padding(PaddingMode::PKCS7)));
4378
4379 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4380
4381 string message = "a";
4382 string ciphertext = EncryptMessage(message, params);
4383 EXPECT_EQ(16U, ciphertext.size());
4384 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07004385
Seth Moore7a55ae32021-06-23 14:28:11 -07004386 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
4387 ++ciphertext[ciphertext.size() / 2];
4388
4389 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4390 string plaintext;
4391 ErrorCode error = Finish(message, &plaintext);
4392 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
4393 // This is the expected error, we can exit the test now.
4394 return;
4395 } else {
4396 // Very small chance we got valid decryption, so try again.
4397 ASSERT_EQ(error, ErrorCode::OK);
4398 }
4399 }
4400 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07004401}
4402
4403vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4404 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004405 EXPECT_TRUE(iv);
4406 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004407}
4408
4409/*
4410 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4411 *
4412 * Verifies that AES CTR mode works.
4413 */
4414TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4415 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4416 .Authorization(TAG_NO_AUTH_REQUIRED)
4417 .AesEncryptionKey(128)
4418 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4419 .Padding(PaddingMode::NONE)));
4420
4421 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4422
4423 string message = "123";
4424 AuthorizationSet out_params;
4425 string ciphertext1 = EncryptMessage(message, params, &out_params);
4426 vector<uint8_t> iv1 = CopyIv(out_params);
4427 EXPECT_EQ(16U, iv1.size());
4428
4429 EXPECT_EQ(message.size(), ciphertext1.size());
4430
4431 out_params.Clear();
4432 string ciphertext2 = EncryptMessage(message, params, &out_params);
4433 vector<uint8_t> iv2 = CopyIv(out_params);
4434 EXPECT_EQ(16U, iv2.size());
4435
4436 // IVs should be random, so ciphertexts should differ.
4437 EXPECT_NE(ciphertext1, ciphertext2);
4438
4439 auto params_iv1 =
4440 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4441 auto params_iv2 =
4442 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4443
4444 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4445 EXPECT_EQ(message, plaintext);
4446 plaintext = DecryptMessage(ciphertext2, params_iv2);
4447 EXPECT_EQ(message, plaintext);
4448
4449 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4450 plaintext = DecryptMessage(ciphertext1, params_iv2);
4451 EXPECT_NE(message, plaintext);
4452 plaintext = DecryptMessage(ciphertext2, params_iv1);
4453 EXPECT_NE(message, plaintext);
4454}
4455
4456/*
4457 * EncryptionOperationsTest.AesIncremental
4458 *
4459 * Verifies that AES works, all modes, when provided data in various size increments.
4460 */
4461TEST_P(EncryptionOperationsTest, AesIncremental) {
4462 auto block_modes = {
4463 BlockMode::ECB,
4464 BlockMode::CBC,
4465 BlockMode::CTR,
4466 BlockMode::GCM,
4467 };
4468
4469 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4470 .Authorization(TAG_NO_AUTH_REQUIRED)
4471 .AesEncryptionKey(128)
4472 .BlockMode(block_modes)
4473 .Padding(PaddingMode::NONE)
4474 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4475
4476 for (int increment = 1; increment <= 240; ++increment) {
4477 for (auto block_mode : block_modes) {
4478 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004479 auto params =
4480 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4481 if (block_mode == BlockMode::GCM) {
4482 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4483 }
Selene Huang31ab4042020-04-29 04:22:39 -07004484
4485 AuthorizationSet output_params;
4486 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4487
4488 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004489 string to_send;
4490 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004491 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004492 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004493 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4494 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004495
4496 switch (block_mode) {
4497 case BlockMode::GCM:
4498 EXPECT_EQ(message.size() + 16, ciphertext.size());
4499 break;
4500 case BlockMode::CTR:
4501 EXPECT_EQ(message.size(), ciphertext.size());
4502 break;
4503 case BlockMode::CBC:
4504 case BlockMode::ECB:
4505 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4506 break;
4507 }
4508
4509 auto iv = output_params.GetTagValue(TAG_NONCE);
4510 switch (block_mode) {
4511 case BlockMode::CBC:
4512 case BlockMode::GCM:
4513 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004514 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4515 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4516 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004517 break;
4518
4519 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004520 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004521 break;
4522 }
4523
4524 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4525 << "Decrypt begin() failed for block mode " << block_mode;
4526
4527 string plaintext;
4528 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004529 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004530 }
4531 ErrorCode error = Finish(to_send, &plaintext);
4532 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4533 << " and increment " << increment;
4534 if (error == ErrorCode::OK) {
4535 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4536 << block_mode << " and increment " << increment;
4537 }
4538 }
4539 }
4540}
4541
4542struct AesCtrSp80038aTestVector {
4543 const char* key;
4544 const char* nonce;
4545 const char* plaintext;
4546 const char* ciphertext;
4547};
4548
4549// These test vectors are taken from
4550// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4551static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4552 // AES-128
4553 {
4554 "2b7e151628aed2a6abf7158809cf4f3c",
4555 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4556 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4557 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4558 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4559 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4560 },
4561 // AES-192
4562 {
4563 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4564 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4565 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4566 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4567 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4568 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4569 },
4570 // AES-256
4571 {
4572 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4573 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4574 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4575 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4576 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4577 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4578 },
4579};
4580
4581/*
4582 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4583 *
4584 * Verifies AES CTR implementation against SP800-38A test vectors.
4585 */
4586TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4587 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4588 for (size_t i = 0; i < 3; i++) {
4589 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4590 const string key = hex2str(test.key);
4591 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4592 InvalidSizes.end())
4593 continue;
4594 const string nonce = hex2str(test.nonce);
4595 const string plaintext = hex2str(test.plaintext);
4596 const string ciphertext = hex2str(test.ciphertext);
4597 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4598 }
4599}
4600
4601/*
4602 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4603 *
4604 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4605 */
4606TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4607 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4608 .Authorization(TAG_NO_AUTH_REQUIRED)
4609 .AesEncryptionKey(128)
4610 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4611 .Padding(PaddingMode::PKCS7)));
4612 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4613 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4614}
4615
4616/*
4617 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4618 *
4619 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4620 */
4621TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4622 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4623 .Authorization(TAG_NO_AUTH_REQUIRED)
4624 .AesEncryptionKey(128)
4625 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4626 .Authorization(TAG_CALLER_NONCE)
4627 .Padding(PaddingMode::NONE)));
4628
4629 auto params = AuthorizationSetBuilder()
4630 .BlockMode(BlockMode::CTR)
4631 .Padding(PaddingMode::NONE)
4632 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4633 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4634
4635 params = AuthorizationSetBuilder()
4636 .BlockMode(BlockMode::CTR)
4637 .Padding(PaddingMode::NONE)
4638 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4639 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4640
4641 params = AuthorizationSetBuilder()
4642 .BlockMode(BlockMode::CTR)
4643 .Padding(PaddingMode::NONE)
4644 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4645 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4646}
4647
4648/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004649 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004650 *
4651 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4652 */
4653TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4654 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4655 .Authorization(TAG_NO_AUTH_REQUIRED)
4656 .AesEncryptionKey(128)
4657 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4658 .Padding(PaddingMode::NONE)));
4659 // Two-block message.
4660 string message = "12345678901234567890123456789012";
4661 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4662 AuthorizationSet out_params;
4663 string ciphertext1 = EncryptMessage(message, params, &out_params);
4664 vector<uint8_t> iv1 = CopyIv(out_params);
4665 EXPECT_EQ(message.size(), ciphertext1.size());
4666
4667 out_params.Clear();
4668
4669 string ciphertext2 = EncryptMessage(message, params, &out_params);
4670 vector<uint8_t> iv2 = CopyIv(out_params);
4671 EXPECT_EQ(message.size(), ciphertext2.size());
4672
4673 // IVs should be random, so ciphertexts should differ.
4674 EXPECT_NE(ciphertext1, ciphertext2);
4675
4676 params.push_back(TAG_NONCE, iv1);
4677 string plaintext = DecryptMessage(ciphertext1, params);
4678 EXPECT_EQ(message, plaintext);
4679}
4680
4681/*
4682 * EncryptionOperationsTest.AesCallerNonce
4683 *
4684 * Verifies that AES caller-provided nonces work correctly.
4685 */
4686TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4688 .Authorization(TAG_NO_AUTH_REQUIRED)
4689 .AesEncryptionKey(128)
4690 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4691 .Authorization(TAG_CALLER_NONCE)
4692 .Padding(PaddingMode::NONE)));
4693
4694 string message = "12345678901234567890123456789012";
4695
4696 // Don't specify nonce, should get a random one.
4697 AuthorizationSetBuilder params =
4698 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4699 AuthorizationSet out_params;
4700 string ciphertext = EncryptMessage(message, params, &out_params);
4701 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004702 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004703
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004704 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004705 string plaintext = DecryptMessage(ciphertext, params);
4706 EXPECT_EQ(message, plaintext);
4707
4708 // Now specify a nonce, should also work.
4709 params = AuthorizationSetBuilder()
4710 .BlockMode(BlockMode::CBC)
4711 .Padding(PaddingMode::NONE)
4712 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4713 out_params.Clear();
4714 ciphertext = EncryptMessage(message, params, &out_params);
4715
4716 // Decrypt with correct nonce.
4717 plaintext = DecryptMessage(ciphertext, params);
4718 EXPECT_EQ(message, plaintext);
4719
4720 // Try with wrong nonce.
4721 params = AuthorizationSetBuilder()
4722 .BlockMode(BlockMode::CBC)
4723 .Padding(PaddingMode::NONE)
4724 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4725 plaintext = DecryptMessage(ciphertext, params);
4726 EXPECT_NE(message, plaintext);
4727}
4728
4729/*
4730 * EncryptionOperationsTest.AesCallerNonceProhibited
4731 *
4732 * Verifies that caller-provided nonces are not permitted when not specified in the key
4733 * authorizations.
4734 */
4735TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4736 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4737 .Authorization(TAG_NO_AUTH_REQUIRED)
4738 .AesEncryptionKey(128)
4739 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4740 .Padding(PaddingMode::NONE)));
4741
4742 string message = "12345678901234567890123456789012";
4743
4744 // Don't specify nonce, should get a random one.
4745 AuthorizationSetBuilder params =
4746 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4747 AuthorizationSet out_params;
4748 string ciphertext = EncryptMessage(message, params, &out_params);
4749 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004750 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004751
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004752 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004753 string plaintext = DecryptMessage(ciphertext, params);
4754 EXPECT_EQ(message, plaintext);
4755
4756 // Now specify a nonce, should fail
4757 params = AuthorizationSetBuilder()
4758 .BlockMode(BlockMode::CBC)
4759 .Padding(PaddingMode::NONE)
4760 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4761 out_params.Clear();
4762 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4763}
4764
4765/*
4766 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4767 *
4768 * Verifies that AES GCM mode works.
4769 */
4770TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4771 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4772 .Authorization(TAG_NO_AUTH_REQUIRED)
4773 .AesEncryptionKey(128)
4774 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4775 .Padding(PaddingMode::NONE)
4776 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4777
4778 string aad = "foobar";
4779 string message = "123456789012345678901234567890123456";
4780
4781 auto begin_params = AuthorizationSetBuilder()
4782 .BlockMode(BlockMode::GCM)
4783 .Padding(PaddingMode::NONE)
4784 .Authorization(TAG_MAC_LENGTH, 128);
4785
Selene Huang31ab4042020-04-29 04:22:39 -07004786 // Encrypt
4787 AuthorizationSet begin_out_params;
4788 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4789 << "Begin encrypt";
4790 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004791 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4792 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004793 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4794
4795 // Grab nonce
4796 begin_params.push_back(begin_out_params);
4797
4798 // Decrypt.
4799 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004800 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004801 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004802 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004803 EXPECT_EQ(message.length(), plaintext.length());
4804 EXPECT_EQ(message, plaintext);
4805}
4806
4807/*
4808 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4809 *
4810 * Verifies that AES GCM mode works, even when there's a long delay
4811 * between operations.
4812 */
4813TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4814 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4815 .Authorization(TAG_NO_AUTH_REQUIRED)
4816 .AesEncryptionKey(128)
4817 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4818 .Padding(PaddingMode::NONE)
4819 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4820
4821 string aad = "foobar";
4822 string message = "123456789012345678901234567890123456";
4823
4824 auto begin_params = AuthorizationSetBuilder()
4825 .BlockMode(BlockMode::GCM)
4826 .Padding(PaddingMode::NONE)
4827 .Authorization(TAG_MAC_LENGTH, 128);
4828
Selene Huang31ab4042020-04-29 04:22:39 -07004829 // Encrypt
4830 AuthorizationSet begin_out_params;
4831 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4832 << "Begin encrypt";
4833 string ciphertext;
4834 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004835 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004836 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004837 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004838
4839 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4840
4841 // Grab nonce
4842 begin_params.push_back(begin_out_params);
4843
4844 // Decrypt.
4845 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4846 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004847 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004848 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004849 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004850 sleep(5);
4851 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4852 EXPECT_EQ(message.length(), plaintext.length());
4853 EXPECT_EQ(message, plaintext);
4854}
4855
4856/*
4857 * EncryptionOperationsTest.AesGcmDifferentNonces
4858 *
4859 * Verifies that encrypting the same data with different nonces produces different outputs.
4860 */
4861TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4862 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4863 .Authorization(TAG_NO_AUTH_REQUIRED)
4864 .AesEncryptionKey(128)
4865 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4866 .Padding(PaddingMode::NONE)
4867 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4868 .Authorization(TAG_CALLER_NONCE)));
4869
4870 string aad = "foobar";
4871 string message = "123456789012345678901234567890123456";
4872 string nonce1 = "000000000000";
4873 string nonce2 = "111111111111";
4874 string nonce3 = "222222222222";
4875
4876 string ciphertext1 =
4877 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4878 string ciphertext2 =
4879 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4880 string ciphertext3 =
4881 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4882
4883 ASSERT_NE(ciphertext1, ciphertext2);
4884 ASSERT_NE(ciphertext1, ciphertext3);
4885 ASSERT_NE(ciphertext2, ciphertext3);
4886}
4887
4888/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004889 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4890 *
4891 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4892 */
4893TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4894 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4895 .Authorization(TAG_NO_AUTH_REQUIRED)
4896 .AesEncryptionKey(128)
4897 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4898 .Padding(PaddingMode::NONE)
4899 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4900
4901 string aad = "foobar";
4902 string message = "123456789012345678901234567890123456";
4903
4904 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4905 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4906 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4907
4908 ASSERT_NE(ciphertext1, ciphertext2);
4909 ASSERT_NE(ciphertext1, ciphertext3);
4910 ASSERT_NE(ciphertext2, ciphertext3);
4911}
4912
4913/*
Selene Huang31ab4042020-04-29 04:22:39 -07004914 * EncryptionOperationsTest.AesGcmTooShortTag
4915 *
4916 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4917 */
4918TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4919 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4920 .Authorization(TAG_NO_AUTH_REQUIRED)
4921 .AesEncryptionKey(128)
4922 .BlockMode(BlockMode::GCM)
4923 .Padding(PaddingMode::NONE)
4924 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4925 string message = "123456789012345678901234567890123456";
4926 auto params = AuthorizationSetBuilder()
4927 .BlockMode(BlockMode::GCM)
4928 .Padding(PaddingMode::NONE)
4929 .Authorization(TAG_MAC_LENGTH, 96);
4930
4931 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4932}
4933
4934/*
4935 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4936 *
4937 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4938 */
4939TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4940 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4941 .Authorization(TAG_NO_AUTH_REQUIRED)
4942 .AesEncryptionKey(128)
4943 .BlockMode(BlockMode::GCM)
4944 .Padding(PaddingMode::NONE)
4945 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4946 string aad = "foobar";
4947 string message = "123456789012345678901234567890123456";
4948 auto params = AuthorizationSetBuilder()
4949 .BlockMode(BlockMode::GCM)
4950 .Padding(PaddingMode::NONE)
4951 .Authorization(TAG_MAC_LENGTH, 128);
4952
Selene Huang31ab4042020-04-29 04:22:39 -07004953 // Encrypt
4954 AuthorizationSet begin_out_params;
4955 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4956 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004957 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004958
4959 AuthorizationSet finish_out_params;
4960 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004961 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4962 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004963
4964 params = AuthorizationSetBuilder()
4965 .Authorizations(begin_out_params)
4966 .BlockMode(BlockMode::GCM)
4967 .Padding(PaddingMode::NONE)
4968 .Authorization(TAG_MAC_LENGTH, 96);
4969
4970 // Decrypt.
4971 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4972}
4973
4974/*
4975 * EncryptionOperationsTest.AesGcmCorruptKey
4976 *
4977 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4978 */
4979TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4980 const uint8_t nonce_bytes[] = {
4981 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4982 };
4983 string nonce = make_string(nonce_bytes);
4984 const uint8_t ciphertext_bytes[] = {
4985 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4986 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4987 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4988 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4989 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4990 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4991 };
4992 string ciphertext = make_string(ciphertext_bytes);
4993
4994 auto params = AuthorizationSetBuilder()
4995 .BlockMode(BlockMode::GCM)
4996 .Padding(PaddingMode::NONE)
4997 .Authorization(TAG_MAC_LENGTH, 128)
4998 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
4999
5000 auto import_params = AuthorizationSetBuilder()
5001 .Authorization(TAG_NO_AUTH_REQUIRED)
5002 .AesEncryptionKey(128)
5003 .BlockMode(BlockMode::GCM)
5004 .Padding(PaddingMode::NONE)
5005 .Authorization(TAG_CALLER_NONCE)
5006 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5007
5008 // Import correct key and decrypt
5009 const uint8_t key_bytes[] = {
5010 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5011 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5012 };
5013 string key = make_string(key_bytes);
5014 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5015 string plaintext = DecryptMessage(ciphertext, params);
5016 CheckedDeleteKey();
5017
5018 // Corrupt key and attempt to decrypt
5019 key[0] = 0;
5020 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5021 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5022 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5023 CheckedDeleteKey();
5024}
5025
5026/*
5027 * EncryptionOperationsTest.AesGcmAadNoData
5028 *
5029 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5030 * encrypt.
5031 */
5032TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5033 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5034 .Authorization(TAG_NO_AUTH_REQUIRED)
5035 .AesEncryptionKey(128)
5036 .BlockMode(BlockMode::GCM)
5037 .Padding(PaddingMode::NONE)
5038 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5039
5040 string aad = "1234567890123456";
5041 auto params = AuthorizationSetBuilder()
5042 .BlockMode(BlockMode::GCM)
5043 .Padding(PaddingMode::NONE)
5044 .Authorization(TAG_MAC_LENGTH, 128);
5045
Selene Huang31ab4042020-04-29 04:22:39 -07005046 // Encrypt
5047 AuthorizationSet begin_out_params;
5048 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5049 string ciphertext;
5050 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005051 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5052 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005053 EXPECT_TRUE(finish_out_params.empty());
5054
5055 // Grab nonce
5056 params.push_back(begin_out_params);
5057
5058 // Decrypt.
5059 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005060 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005061 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005062 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005063
5064 EXPECT_TRUE(finish_out_params.empty());
5065
5066 EXPECT_EQ("", plaintext);
5067}
5068
5069/*
5070 * EncryptionOperationsTest.AesGcmMultiPartAad
5071 *
5072 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5073 * chunks.
5074 */
5075TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5076 const size_t tag_bits = 128;
5077 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5078 .Authorization(TAG_NO_AUTH_REQUIRED)
5079 .AesEncryptionKey(128)
5080 .BlockMode(BlockMode::GCM)
5081 .Padding(PaddingMode::NONE)
5082 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5083
5084 string message = "123456789012345678901234567890123456";
5085 auto begin_params = AuthorizationSetBuilder()
5086 .BlockMode(BlockMode::GCM)
5087 .Padding(PaddingMode::NONE)
5088 .Authorization(TAG_MAC_LENGTH, tag_bits);
5089 AuthorizationSet begin_out_params;
5090
Selene Huang31ab4042020-04-29 04:22:39 -07005091 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5092
5093 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005094 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5095 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005096 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005097 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5098 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005099
Selene Huang31ab4042020-04-29 04:22:39 -07005100 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005101 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005102
5103 // Grab nonce.
5104 begin_params.push_back(begin_out_params);
5105
5106 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005107 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005108 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005109 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005110 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005111 EXPECT_EQ(message, plaintext);
5112}
5113
5114/*
5115 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5116 *
5117 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5118 */
5119TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5120 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5121 .Authorization(TAG_NO_AUTH_REQUIRED)
5122 .AesEncryptionKey(128)
5123 .BlockMode(BlockMode::GCM)
5124 .Padding(PaddingMode::NONE)
5125 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5126
5127 string message = "123456789012345678901234567890123456";
5128 auto begin_params = AuthorizationSetBuilder()
5129 .BlockMode(BlockMode::GCM)
5130 .Padding(PaddingMode::NONE)
5131 .Authorization(TAG_MAC_LENGTH, 128);
5132 AuthorizationSet begin_out_params;
5133
Selene Huang31ab4042020-04-29 04:22:39 -07005134 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5135
Shawn Willden92d79c02021-02-19 07:31:55 -07005136 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005137 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005138 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5139 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005140
David Drysdaled2cc8c22021-04-15 13:29:45 +01005141 // The failure should have already cancelled the operation.
5142 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5143
Shawn Willden92d79c02021-02-19 07:31:55 -07005144 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005145}
5146
5147/*
5148 * EncryptionOperationsTest.AesGcmBadAad
5149 *
5150 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5151 */
5152TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5153 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5154 .Authorization(TAG_NO_AUTH_REQUIRED)
5155 .AesEncryptionKey(128)
5156 .BlockMode(BlockMode::GCM)
5157 .Padding(PaddingMode::NONE)
5158 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5159
5160 string message = "12345678901234567890123456789012";
5161 auto begin_params = AuthorizationSetBuilder()
5162 .BlockMode(BlockMode::GCM)
5163 .Padding(PaddingMode::NONE)
5164 .Authorization(TAG_MAC_LENGTH, 128);
5165
Selene Huang31ab4042020-04-29 04:22:39 -07005166 // Encrypt
5167 AuthorizationSet begin_out_params;
5168 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005169 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005170 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005171 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005172
5173 // Grab nonce
5174 begin_params.push_back(begin_out_params);
5175
Selene Huang31ab4042020-04-29 04:22:39 -07005176 // Decrypt.
5177 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005178 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005179 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005180 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005181}
5182
5183/*
5184 * EncryptionOperationsTest.AesGcmWrongNonce
5185 *
5186 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5187 */
5188TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5189 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5190 .Authorization(TAG_NO_AUTH_REQUIRED)
5191 .AesEncryptionKey(128)
5192 .BlockMode(BlockMode::GCM)
5193 .Padding(PaddingMode::NONE)
5194 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5195
5196 string message = "12345678901234567890123456789012";
5197 auto begin_params = AuthorizationSetBuilder()
5198 .BlockMode(BlockMode::GCM)
5199 .Padding(PaddingMode::NONE)
5200 .Authorization(TAG_MAC_LENGTH, 128);
5201
Selene Huang31ab4042020-04-29 04:22:39 -07005202 // Encrypt
5203 AuthorizationSet begin_out_params;
5204 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005205 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005206 string ciphertext;
5207 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005208 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005209
5210 // Wrong nonce
5211 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5212
5213 // Decrypt.
5214 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005215 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005216 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005217 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005218
5219 // With wrong nonce, should have gotten garbage plaintext (or none).
5220 EXPECT_NE(message, plaintext);
5221}
5222
5223/*
5224 * EncryptionOperationsTest.AesGcmCorruptTag
5225 *
5226 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5227 */
5228TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5229 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5230 .Authorization(TAG_NO_AUTH_REQUIRED)
5231 .AesEncryptionKey(128)
5232 .BlockMode(BlockMode::GCM)
5233 .Padding(PaddingMode::NONE)
5234 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5235
5236 string aad = "1234567890123456";
5237 string message = "123456789012345678901234567890123456";
5238
5239 auto params = AuthorizationSetBuilder()
5240 .BlockMode(BlockMode::GCM)
5241 .Padding(PaddingMode::NONE)
5242 .Authorization(TAG_MAC_LENGTH, 128);
5243
Selene Huang31ab4042020-04-29 04:22:39 -07005244 // Encrypt
5245 AuthorizationSet begin_out_params;
5246 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005247 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005248 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005249 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005250
5251 // Corrupt tag
5252 ++(*ciphertext.rbegin());
5253
5254 // Grab nonce
5255 params.push_back(begin_out_params);
5256
5257 // Decrypt.
5258 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005259 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005260 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005261 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005262}
5263
5264/*
5265 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5266 *
5267 * Verifies that 3DES is basically functional.
5268 */
5269TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5270 auto auths = AuthorizationSetBuilder()
5271 .TripleDesEncryptionKey(168)
5272 .BlockMode(BlockMode::ECB)
5273 .Authorization(TAG_NO_AUTH_REQUIRED)
5274 .Padding(PaddingMode::NONE);
5275
5276 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5277 // Two-block message.
5278 string message = "1234567890123456";
5279 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5280 string ciphertext1 = EncryptMessage(message, inParams);
5281 EXPECT_EQ(message.size(), ciphertext1.size());
5282
5283 string ciphertext2 = EncryptMessage(string(message), inParams);
5284 EXPECT_EQ(message.size(), ciphertext2.size());
5285
5286 // ECB is deterministic.
5287 EXPECT_EQ(ciphertext1, ciphertext2);
5288
5289 string plaintext = DecryptMessage(ciphertext1, inParams);
5290 EXPECT_EQ(message, plaintext);
5291}
5292
5293/*
5294 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5295 *
5296 * Verifies that CBC keys reject ECB usage.
5297 */
5298TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5299 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5300 .TripleDesEncryptionKey(168)
5301 .BlockMode(BlockMode::CBC)
5302 .Authorization(TAG_NO_AUTH_REQUIRED)
5303 .Padding(PaddingMode::NONE)));
5304
5305 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5306 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5307}
5308
5309/*
5310 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5311 *
5312 * Tests ECB mode with PKCS#7 padding, various message sizes.
5313 */
5314TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5315 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5316 .TripleDesEncryptionKey(168)
5317 .BlockMode(BlockMode::ECB)
5318 .Authorization(TAG_NO_AUTH_REQUIRED)
5319 .Padding(PaddingMode::PKCS7)));
5320
5321 for (size_t i = 0; i < 32; ++i) {
5322 string message(i, 'a');
5323 auto inParams =
5324 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5325 string ciphertext = EncryptMessage(message, inParams);
5326 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5327 string plaintext = DecryptMessage(ciphertext, inParams);
5328 EXPECT_EQ(message, plaintext);
5329 }
5330}
5331
5332/*
5333 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5334 *
5335 * Verifies that keys configured for no padding reject PKCS7 padding
5336 */
5337TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5338 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5339 .TripleDesEncryptionKey(168)
5340 .BlockMode(BlockMode::ECB)
5341 .Authorization(TAG_NO_AUTH_REQUIRED)
5342 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005343 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5344 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005345}
5346
5347/*
5348 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5349 *
5350 * Verifies that corrupted padding is detected.
5351 */
5352TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5353 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5354 .TripleDesEncryptionKey(168)
5355 .BlockMode(BlockMode::ECB)
5356 .Authorization(TAG_NO_AUTH_REQUIRED)
5357 .Padding(PaddingMode::PKCS7)));
5358
5359 string message = "a";
5360 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5361 EXPECT_EQ(8U, ciphertext.size());
5362 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005363
5364 AuthorizationSetBuilder begin_params;
5365 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5366 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07005367
5368 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5369 ++ciphertext[ciphertext.size() / 2];
5370
5371 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5372 string plaintext;
5373 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5374 ErrorCode error = Finish(&plaintext);
5375 if (error == ErrorCode::INVALID_ARGUMENT) {
5376 // This is the expected error, we can exit the test now.
5377 return;
5378 } else {
5379 // Very small chance we got valid decryption, so try again.
5380 ASSERT_EQ(error, ErrorCode::OK);
5381 }
5382 }
5383 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005384}
5385
5386struct TripleDesTestVector {
5387 const char* name;
5388 const KeyPurpose purpose;
5389 const BlockMode block_mode;
5390 const PaddingMode padding_mode;
5391 const char* key;
5392 const char* iv;
5393 const char* input;
5394 const char* output;
5395};
5396
5397// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5398// of the NIST vectors are multiples of the block size.
5399static const TripleDesTestVector kTripleDesTestVectors[] = {
5400 {
5401 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5402 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5403 "", // IV
5404 "329d86bdf1bc5af4", // input
5405 "d946c2756d78633f", // output
5406 },
5407 {
5408 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5409 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5410 "", // IV
5411 "6b1540781b01ce1997adae102dbf3c5b", // input
5412 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5413 },
5414 {
5415 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5416 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5417 "", // IV
5418 "6daad94ce08acfe7", // input
5419 "660e7d32dcc90e79", // output
5420 },
5421 {
5422 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5423 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5424 "", // IV
5425 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5426 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5427 },
5428 {
5429 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5430 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5431 "43f791134c5647ba", // IV
5432 "dcc153cef81d6f24", // input
5433 "92538bd8af18d3ba", // output
5434 },
5435 {
5436 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5437 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5438 "c2e999cb6249023c", // IV
5439 "c689aee38a301bb316da75db36f110b5", // input
5440 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5441 },
5442 {
5443 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5444 PaddingMode::PKCS7,
5445 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5446 "c2e999cb6249023c", // IV
5447 "c689aee38a301bb316da75db36f110b500", // input
5448 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5449 },
5450 {
5451 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5452 PaddingMode::PKCS7,
5453 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5454 "c2e999cb6249023c", // IV
5455 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5456 "c689aee38a301bb316da75db36f110b500", // output
5457 },
5458 {
5459 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5460 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5461 "41746c7e442d3681", // IV
5462 "c53a7b0ec40600fe", // input
5463 "d4f00eb455de1034", // output
5464 },
5465 {
5466 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5467 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5468 "3982bc02c3727d45", // IV
5469 "6006f10adef52991fcc777a1238bbb65", // input
5470 "edae09288e9e3bc05746d872b48e3b29", // output
5471 },
5472};
5473
5474/*
5475 * EncryptionOperationsTest.TripleDesTestVector
5476 *
5477 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5478 */
5479TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5480 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5481 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5482 SCOPED_TRACE(test->name);
5483 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5484 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5485 hex2str(test->output));
5486 }
5487}
5488
5489/*
5490 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5491 *
5492 * Validates CBC mode functionality.
5493 */
5494TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5495 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5496 .TripleDesEncryptionKey(168)
5497 .BlockMode(BlockMode::CBC)
5498 .Authorization(TAG_NO_AUTH_REQUIRED)
5499 .Padding(PaddingMode::NONE)));
5500
5501 ASSERT_GT(key_blob_.size(), 0U);
5502
5503 // Two-block message.
5504 string message = "1234567890123456";
5505 vector<uint8_t> iv1;
5506 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5507 EXPECT_EQ(message.size(), ciphertext1.size());
5508
5509 vector<uint8_t> iv2;
5510 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5511 EXPECT_EQ(message.size(), ciphertext2.size());
5512
5513 // IVs should be random, so ciphertexts should differ.
5514 EXPECT_NE(iv1, iv2);
5515 EXPECT_NE(ciphertext1, ciphertext2);
5516
5517 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5518 EXPECT_EQ(message, plaintext);
5519}
5520
5521/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005522 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5523 *
5524 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5525 */
5526TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5527 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5528 .TripleDesEncryptionKey(168)
5529 .BlockMode(BlockMode::CBC)
5530 .Authorization(TAG_NO_AUTH_REQUIRED)
5531 .Authorization(TAG_CALLER_NONCE)
5532 .Padding(PaddingMode::NONE)));
5533 auto params = AuthorizationSetBuilder()
5534 .BlockMode(BlockMode::CBC)
5535 .Padding(PaddingMode::NONE)
5536 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5537 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5538}
5539
5540/*
Selene Huang31ab4042020-04-29 04:22:39 -07005541 * EncryptionOperationsTest.TripleDesCallerIv
5542 *
5543 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5544 */
5545TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5546 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5547 .TripleDesEncryptionKey(168)
5548 .BlockMode(BlockMode::CBC)
5549 .Authorization(TAG_NO_AUTH_REQUIRED)
5550 .Authorization(TAG_CALLER_NONCE)
5551 .Padding(PaddingMode::NONE)));
5552 string message = "1234567890123456";
5553 vector<uint8_t> iv;
5554 // Don't specify IV, should get a random one.
5555 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5556 EXPECT_EQ(message.size(), ciphertext1.size());
5557 EXPECT_EQ(8U, iv.size());
5558
5559 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5560 EXPECT_EQ(message, plaintext);
5561
5562 // Now specify an IV, should also work.
5563 iv = AidlBuf("abcdefgh");
5564 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5565
5566 // Decrypt with correct IV.
5567 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5568 EXPECT_EQ(message, plaintext);
5569
5570 // Now try with wrong IV.
5571 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5572 EXPECT_NE(message, plaintext);
5573}
5574
5575/*
5576 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5577 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005578 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005579 */
5580TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5581 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5582 .TripleDesEncryptionKey(168)
5583 .BlockMode(BlockMode::CBC)
5584 .Authorization(TAG_NO_AUTH_REQUIRED)
5585 .Padding(PaddingMode::NONE)));
5586
5587 string message = "12345678901234567890123456789012";
5588 vector<uint8_t> iv;
5589 // Don't specify nonce, should get a random one.
5590 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5591 EXPECT_EQ(message.size(), ciphertext1.size());
5592 EXPECT_EQ(8U, iv.size());
5593
5594 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5595 EXPECT_EQ(message, plaintext);
5596
5597 // Now specify a nonce, should fail.
5598 auto input_params = AuthorizationSetBuilder()
5599 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5600 .BlockMode(BlockMode::CBC)
5601 .Padding(PaddingMode::NONE);
5602 AuthorizationSet output_params;
5603 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5604 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5605}
5606
5607/*
5608 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5609 *
5610 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5611 */
5612TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5613 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5614 .TripleDesEncryptionKey(168)
5615 .BlockMode(BlockMode::ECB)
5616 .Authorization(TAG_NO_AUTH_REQUIRED)
5617 .Padding(PaddingMode::NONE)));
5618 // Two-block message.
5619 string message = "1234567890123456";
5620 auto begin_params =
5621 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5622 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5623}
5624
5625/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005626 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005627 *
5628 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5629 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005630TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5631 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5632 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5633 .TripleDesEncryptionKey(168)
5634 .BlockMode(blockMode)
5635 .Authorization(TAG_NO_AUTH_REQUIRED)
5636 .Padding(PaddingMode::NONE)));
5637 // Message is slightly shorter than two blocks.
5638 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005639
David Drysdaled2cc8c22021-04-15 13:29:45 +01005640 auto begin_params =
5641 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5642 AuthorizationSet output_params;
5643 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5644 string ciphertext;
5645 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5646
5647 CheckedDeleteKey();
5648 }
Selene Huang31ab4042020-04-29 04:22:39 -07005649}
5650
5651/*
5652 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5653 *
5654 * Verifies that PKCS7 padding works correctly in CBC mode.
5655 */
5656TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5657 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5658 .TripleDesEncryptionKey(168)
5659 .BlockMode(BlockMode::CBC)
5660 .Authorization(TAG_NO_AUTH_REQUIRED)
5661 .Padding(PaddingMode::PKCS7)));
5662
5663 // Try various message lengths; all should work.
5664 for (size_t i = 0; i < 32; ++i) {
5665 string message(i, 'a');
5666 vector<uint8_t> iv;
5667 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5668 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5669 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5670 EXPECT_EQ(message, plaintext);
5671 }
5672}
5673
5674/*
5675 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5676 *
5677 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5678 */
5679TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5680 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5681 .TripleDesEncryptionKey(168)
5682 .BlockMode(BlockMode::CBC)
5683 .Authorization(TAG_NO_AUTH_REQUIRED)
5684 .Padding(PaddingMode::NONE)));
5685
5686 // Try various message lengths; all should fail.
5687 for (size_t i = 0; i < 32; ++i) {
5688 auto begin_params =
5689 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5690 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5691 }
5692}
5693
5694/*
5695 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5696 *
5697 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5698 */
5699TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5700 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5701 .TripleDesEncryptionKey(168)
5702 .BlockMode(BlockMode::CBC)
5703 .Authorization(TAG_NO_AUTH_REQUIRED)
5704 .Padding(PaddingMode::PKCS7)));
5705
5706 string message = "a";
5707 vector<uint8_t> iv;
5708 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5709 EXPECT_EQ(8U, ciphertext.size());
5710 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005711
5712 auto begin_params = AuthorizationSetBuilder()
5713 .BlockMode(BlockMode::CBC)
5714 .Padding(PaddingMode::PKCS7)
5715 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07005716
5717 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5718 ++ciphertext[ciphertext.size() / 2];
5719 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5720 string plaintext;
5721 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5722 ErrorCode error = Finish(&plaintext);
5723 if (error == ErrorCode::INVALID_ARGUMENT) {
5724 // This is the expected error, we can exit the test now.
5725 return;
5726 } else {
5727 // Very small chance we got valid decryption, so try again.
5728 ASSERT_EQ(error, ErrorCode::OK);
5729 }
5730 }
5731 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005732}
5733
5734/*
5735 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5736 *
5737 * Verifies that 3DES CBC works with many different input sizes.
5738 */
5739TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5740 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5741 .TripleDesEncryptionKey(168)
5742 .BlockMode(BlockMode::CBC)
5743 .Authorization(TAG_NO_AUTH_REQUIRED)
5744 .Padding(PaddingMode::NONE)));
5745
5746 int increment = 7;
5747 string message(240, 'a');
5748 AuthorizationSet input_params =
5749 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5750 AuthorizationSet output_params;
5751 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5752
5753 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005754 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005755 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005756 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5757 EXPECT_EQ(message.size(), ciphertext.size());
5758
5759 // Move TAG_NONCE into input_params
5760 input_params = output_params;
5761 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5762 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5763 output_params.Clear();
5764
5765 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5766 string plaintext;
5767 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005768 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005769 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5770 EXPECT_EQ(ciphertext.size(), plaintext.size());
5771 EXPECT_EQ(message, plaintext);
5772}
5773
5774INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5775
5776typedef KeyMintAidlTestBase MaxOperationsTest;
5777
5778/*
5779 * MaxOperationsTest.TestLimitAes
5780 *
5781 * Verifies that the max uses per boot tag works correctly with AES keys.
5782 */
5783TEST_P(MaxOperationsTest, TestLimitAes) {
5784 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5785
5786 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5787 .Authorization(TAG_NO_AUTH_REQUIRED)
5788 .AesEncryptionKey(128)
5789 .EcbMode()
5790 .Padding(PaddingMode::NONE)
5791 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5792
5793 string message = "1234567890123456";
5794
5795 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5796
5797 EncryptMessage(message, params);
5798 EncryptMessage(message, params);
5799 EncryptMessage(message, params);
5800
5801 // Fourth time should fail.
5802 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5803}
5804
5805/*
Qi Wud22ec842020-11-26 13:27:53 +08005806 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005807 *
5808 * Verifies that the max uses per boot tag works correctly with RSA keys.
5809 */
5810TEST_P(MaxOperationsTest, TestLimitRsa) {
5811 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5812
5813 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5814 .Authorization(TAG_NO_AUTH_REQUIRED)
5815 .RsaSigningKey(1024, 65537)
5816 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005817 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5818 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005819
5820 string message = "1234567890123456";
5821
5822 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5823
5824 SignMessage(message, params);
5825 SignMessage(message, params);
5826 SignMessage(message, params);
5827
5828 // Fourth time should fail.
5829 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5830}
5831
5832INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5833
Qi Wud22ec842020-11-26 13:27:53 +08005834typedef KeyMintAidlTestBase UsageCountLimitTest;
5835
5836/*
Qi Wubeefae42021-01-28 23:16:37 +08005837 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005838 *
Qi Wubeefae42021-01-28 23:16:37 +08005839 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005840 */
Qi Wubeefae42021-01-28 23:16:37 +08005841TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005842 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5843
5844 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5845 .Authorization(TAG_NO_AUTH_REQUIRED)
5846 .AesEncryptionKey(128)
5847 .EcbMode()
5848 .Padding(PaddingMode::NONE)
5849 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5850
5851 // Check the usage count limit tag appears in the authorizations.
5852 AuthorizationSet auths;
5853 for (auto& entry : key_characteristics_) {
5854 auths.push_back(AuthorizationSet(entry.authorizations));
5855 }
5856 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5857 << "key usage count limit " << 1U << " missing";
5858
5859 string message = "1234567890123456";
5860 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5861
Qi Wubeefae42021-01-28 23:16:37 +08005862 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5863 AuthorizationSet keystore_auths =
5864 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5865
Qi Wud22ec842020-11-26 13:27:53 +08005866 // First usage of AES key should work.
5867 EncryptMessage(message, params);
5868
Qi Wud22ec842020-11-26 13:27:53 +08005869 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5870 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5871 // must be invalidated from secure storage (such as RPMB partition).
5872 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5873 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005874 // Usage count limit tag is enforced by keystore, keymint does nothing.
5875 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005876 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5877 }
5878}
5879
5880/*
Qi Wubeefae42021-01-28 23:16:37 +08005881 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005882 *
Qi Wubeefae42021-01-28 23:16:37 +08005883 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005884 */
Qi Wubeefae42021-01-28 23:16:37 +08005885TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5886 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5887
5888 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5889 .Authorization(TAG_NO_AUTH_REQUIRED)
5890 .AesEncryptionKey(128)
5891 .EcbMode()
5892 .Padding(PaddingMode::NONE)
5893 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5894
5895 // Check the usage count limit tag appears in the authorizations.
5896 AuthorizationSet auths;
5897 for (auto& entry : key_characteristics_) {
5898 auths.push_back(AuthorizationSet(entry.authorizations));
5899 }
5900 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5901 << "key usage count limit " << 3U << " missing";
5902
5903 string message = "1234567890123456";
5904 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5905
5906 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5907 AuthorizationSet keystore_auths =
5908 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5909
5910 EncryptMessage(message, params);
5911 EncryptMessage(message, params);
5912 EncryptMessage(message, params);
5913
5914 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5915 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5916 // must be invalidated from secure storage (such as RPMB partition).
5917 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5918 } else {
5919 // Usage count limit tag is enforced by keystore, keymint does nothing.
5920 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5921 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5922 }
5923}
5924
5925/*
5926 * UsageCountLimitTest.TestSingleUseRsa
5927 *
5928 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5929 */
5930TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005931 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5932
5933 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5934 .Authorization(TAG_NO_AUTH_REQUIRED)
5935 .RsaSigningKey(1024, 65537)
5936 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005937 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5938 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005939
5940 // Check the usage count limit tag appears in the authorizations.
5941 AuthorizationSet auths;
5942 for (auto& entry : key_characteristics_) {
5943 auths.push_back(AuthorizationSet(entry.authorizations));
5944 }
5945 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5946 << "key usage count limit " << 1U << " missing";
5947
5948 string message = "1234567890123456";
5949 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5950
Qi Wubeefae42021-01-28 23:16:37 +08005951 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5952 AuthorizationSet keystore_auths =
5953 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5954
Qi Wud22ec842020-11-26 13:27:53 +08005955 // First usage of RSA key should work.
5956 SignMessage(message, params);
5957
Qi Wud22ec842020-11-26 13:27:53 +08005958 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5959 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5960 // must be invalidated from secure storage (such as RPMB partition).
5961 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5962 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005963 // Usage count limit tag is enforced by keystore, keymint does nothing.
5964 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5965 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5966 }
5967}
5968
5969/*
5970 * UsageCountLimitTest.TestLimitUseRsa
5971 *
5972 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5973 */
5974TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5975 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5976
5977 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5978 .Authorization(TAG_NO_AUTH_REQUIRED)
5979 .RsaSigningKey(1024, 65537)
5980 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005981 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5982 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005983
5984 // Check the usage count limit tag appears in the authorizations.
5985 AuthorizationSet auths;
5986 for (auto& entry : key_characteristics_) {
5987 auths.push_back(AuthorizationSet(entry.authorizations));
5988 }
5989 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5990 << "key usage count limit " << 3U << " missing";
5991
5992 string message = "1234567890123456";
5993 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5994
5995 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5996 AuthorizationSet keystore_auths =
5997 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5998
5999 SignMessage(message, params);
6000 SignMessage(message, params);
6001 SignMessage(message, params);
6002
6003 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6004 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6005 // must be invalidated from secure storage (such as RPMB partition).
6006 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6007 } else {
6008 // Usage count limit tag is enforced by keystore, keymint does nothing.
6009 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006010 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6011 }
6012}
6013
Qi Wu8e727f72021-02-11 02:49:33 +08006014/*
6015 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6016 *
6017 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6018 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6019 * in hardware.
6020 */
6021TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
6022 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6023
6024 auto error = GenerateKey(AuthorizationSetBuilder()
6025 .RsaSigningKey(2048, 65537)
6026 .Digest(Digest::NONE)
6027 .Padding(PaddingMode::NONE)
6028 .Authorization(TAG_NO_AUTH_REQUIRED)
6029 .Authorization(TAG_ROLLBACK_RESISTANCE)
6030 .SetDefaultValidity());
6031 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6032
6033 if (error == ErrorCode::OK) {
6034 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6035 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6036 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6037 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6038
6039 // The KeyMint should also enforce single use key in hardware when it supports rollback
6040 // resistance.
6041 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6042 .Authorization(TAG_NO_AUTH_REQUIRED)
6043 .RsaSigningKey(1024, 65537)
6044 .NoDigestOrPadding()
6045 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6046 .SetDefaultValidity()));
6047
6048 // Check the usage count limit tag appears in the hardware authorizations.
6049 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6050 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6051 << "key usage count limit " << 1U << " missing";
6052
6053 string message = "1234567890123456";
6054 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6055
6056 // First usage of RSA key should work.
6057 SignMessage(message, params);
6058
6059 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6060 // must be invalidated from secure storage (such as RPMB partition).
6061 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6062 }
6063}
6064
Qi Wud22ec842020-11-26 13:27:53 +08006065INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6066
David Drysdale7de9feb2021-03-05 14:56:19 +00006067typedef KeyMintAidlTestBase GetHardwareInfoTest;
6068
6069TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6070 // Retrieving hardware info should give the same result each time.
6071 KeyMintHardwareInfo info;
6072 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6073 KeyMintHardwareInfo info2;
6074 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6075 EXPECT_EQ(info, info2);
6076}
6077
6078INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6079
Selene Huang31ab4042020-04-29 04:22:39 -07006080typedef KeyMintAidlTestBase AddEntropyTest;
6081
6082/*
6083 * AddEntropyTest.AddEntropy
6084 *
6085 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6086 * is actually added.
6087 */
6088TEST_P(AddEntropyTest, AddEntropy) {
6089 string data = "foo";
6090 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6091}
6092
6093/*
6094 * AddEntropyTest.AddEmptyEntropy
6095 *
6096 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6097 */
6098TEST_P(AddEntropyTest, AddEmptyEntropy) {
6099 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6100}
6101
6102/*
6103 * AddEntropyTest.AddLargeEntropy
6104 *
6105 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6106 */
6107TEST_P(AddEntropyTest, AddLargeEntropy) {
6108 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6109}
6110
David Drysdalebb3d85e2021-04-13 11:15:51 +01006111/*
6112 * AddEntropyTest.AddTooLargeEntropy
6113 *
6114 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6115 */
6116TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6117 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6118 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6119}
6120
Selene Huang31ab4042020-04-29 04:22:39 -07006121INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6122
Selene Huang31ab4042020-04-29 04:22:39 -07006123typedef KeyMintAidlTestBase KeyDeletionTest;
6124
6125/**
6126 * KeyDeletionTest.DeleteKey
6127 *
6128 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6129 * valid key blob.
6130 */
6131TEST_P(KeyDeletionTest, DeleteKey) {
6132 auto error = GenerateKey(AuthorizationSetBuilder()
6133 .RsaSigningKey(2048, 65537)
6134 .Digest(Digest::NONE)
6135 .Padding(PaddingMode::NONE)
6136 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006137 .Authorization(TAG_ROLLBACK_RESISTANCE)
6138 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006139 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6140
6141 // Delete must work if rollback protection is implemented
6142 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006143 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006144 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6145
6146 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6147
6148 string message = "12345678901234567890123456789012";
6149 AuthorizationSet begin_out_params;
6150 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6151 Begin(KeyPurpose::SIGN, key_blob_,
6152 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6153 &begin_out_params));
6154 AbortIfNeeded();
6155 key_blob_ = AidlBuf();
6156 }
6157}
6158
6159/**
6160 * KeyDeletionTest.DeleteInvalidKey
6161 *
6162 * This test checks that the HAL excepts invalid key blobs..
6163 */
6164TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6165 // Generate key just to check if rollback protection is implemented
6166 auto error = GenerateKey(AuthorizationSetBuilder()
6167 .RsaSigningKey(2048, 65537)
6168 .Digest(Digest::NONE)
6169 .Padding(PaddingMode::NONE)
6170 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006171 .Authorization(TAG_ROLLBACK_RESISTANCE)
6172 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006173 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6174
6175 // Delete must work if rollback protection is implemented
6176 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006177 AuthorizationSet enforced(SecLevelAuthorizations());
6178 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006179
6180 // Delete the key we don't care about the result at this point.
6181 DeleteKey();
6182
6183 // Now create an invalid key blob and delete it.
6184 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6185
6186 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6187 }
6188}
6189
6190/**
6191 * KeyDeletionTest.DeleteAllKeys
6192 *
6193 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6194 *
6195 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6196 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6197 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6198 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6199 * credentials stored in Keystore/Keymint.
6200 */
6201TEST_P(KeyDeletionTest, DeleteAllKeys) {
6202 if (!arm_deleteAllKeys) return;
6203 auto error = GenerateKey(AuthorizationSetBuilder()
6204 .RsaSigningKey(2048, 65537)
6205 .Digest(Digest::NONE)
6206 .Padding(PaddingMode::NONE)
6207 .Authorization(TAG_NO_AUTH_REQUIRED)
6208 .Authorization(TAG_ROLLBACK_RESISTANCE));
6209 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6210
6211 // Delete must work if rollback protection is implemented
6212 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006213 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006214 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6215
6216 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
6217
6218 string message = "12345678901234567890123456789012";
6219 AuthorizationSet begin_out_params;
6220
6221 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6222 Begin(KeyPurpose::SIGN, key_blob_,
6223 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6224 &begin_out_params));
6225 AbortIfNeeded();
6226 key_blob_ = AidlBuf();
6227 }
6228}
6229
6230INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
6231
David Drysdaled2cc8c22021-04-15 13:29:45 +01006232typedef KeyMintAidlTestBase KeyUpgradeTest;
6233
6234/**
6235 * KeyUpgradeTest.UpgradeInvalidKey
6236 *
6237 * This test checks that the HAL excepts invalid key blobs..
6238 */
6239TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
6240 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
6241
6242 std::vector<uint8_t> new_blob;
6243 Status result = keymint_->upgradeKey(key_blob,
6244 AuthorizationSetBuilder()
6245 .Authorization(TAG_APPLICATION_ID, "clientid")
6246 .Authorization(TAG_APPLICATION_DATA, "appdata")
6247 .vector_data(),
6248 &new_blob);
6249 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
6250}
6251
6252INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
6253
Selene Huang31ab4042020-04-29 04:22:39 -07006254using UpgradeKeyTest = KeyMintAidlTestBase;
6255
6256/*
6257 * UpgradeKeyTest.UpgradeKey
6258 *
6259 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
6260 */
6261TEST_P(UpgradeKeyTest, UpgradeKey) {
6262 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6263 .AesEncryptionKey(128)
6264 .Padding(PaddingMode::NONE)
6265 .Authorization(TAG_NO_AUTH_REQUIRED)));
6266
6267 auto result = UpgradeKey(key_blob_);
6268
6269 // Key doesn't need upgrading. Should get okay, but no new key blob.
6270 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
6271}
6272
6273INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
6274
6275using ClearOperationsTest = KeyMintAidlTestBase;
6276
6277/*
6278 * ClearSlotsTest.TooManyOperations
6279 *
6280 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
6281 * operations are started without being finished or aborted. Also verifies
6282 * that aborting the operations clears the operations.
6283 *
6284 */
6285TEST_P(ClearOperationsTest, TooManyOperations) {
6286 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6287 .Authorization(TAG_NO_AUTH_REQUIRED)
6288 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08006289 .Padding(PaddingMode::NONE)
6290 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006291
6292 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
6293 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08006294 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07006295 AuthorizationSet out_params;
6296 ErrorCode result;
6297 size_t i;
6298
6299 for (i = 0; i < max_operations; i++) {
6300 result = Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params, op_handles[i]);
6301 if (ErrorCode::OK != result) {
6302 break;
6303 }
6304 }
6305 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
6306 // Try again just in case there's a weird overflow bug
6307 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
6308 Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6309 for (size_t j = 0; j < i; j++) {
6310 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
6311 << "Aboort failed for i = " << j << std::endl;
6312 }
6313 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, key_blob_, params, &out_params));
6314 AbortIfNeeded();
6315}
6316
6317INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
6318
6319typedef KeyMintAidlTestBase TransportLimitTest;
6320
6321/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006322 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07006323 *
6324 * Verifies that passing input data to finish succeeds as expected.
6325 */
6326TEST_P(TransportLimitTest, LargeFinishInput) {
6327 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6328 .Authorization(TAG_NO_AUTH_REQUIRED)
6329 .AesEncryptionKey(128)
6330 .BlockMode(BlockMode::ECB)
6331 .Padding(PaddingMode::NONE)));
6332
6333 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
6334 auto cipher_params =
6335 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6336
6337 AuthorizationSet out_params;
6338 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
6339
6340 string plain_message = std::string(1 << msg_size, 'x');
6341 string encrypted_message;
6342 auto rc = Finish(plain_message, &encrypted_message);
6343
6344 EXPECT_EQ(ErrorCode::OK, rc);
6345 EXPECT_EQ(plain_message.size(), encrypted_message.size())
6346 << "Encrypt finish returned OK, but did not consume all of the given input";
6347 cipher_params.push_back(out_params);
6348
6349 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
6350
6351 string decrypted_message;
6352 rc = Finish(encrypted_message, &decrypted_message);
6353 EXPECT_EQ(ErrorCode::OK, rc);
6354 EXPECT_EQ(plain_message.size(), decrypted_message.size())
6355 << "Decrypt finish returned OK, did not consume all of the given input";
6356 }
6357}
6358
6359INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
6360
David Zeuthene0c40892021-01-08 12:54:11 -05006361typedef KeyMintAidlTestBase KeyAgreementTest;
6362
6363int CurveToOpenSslCurveName(EcCurve curve) {
6364 switch (curve) {
6365 case EcCurve::P_224:
6366 return NID_secp224r1;
6367 case EcCurve::P_256:
6368 return NID_X9_62_prime256v1;
6369 case EcCurve::P_384:
6370 return NID_secp384r1;
6371 case EcCurve::P_521:
6372 return NID_secp521r1;
6373 }
6374}
6375
6376/*
6377 * KeyAgreementTest.Ecdh
6378 *
6379 * Verifies that ECDH works for all curves
6380 */
6381TEST_P(KeyAgreementTest, Ecdh) {
6382 // Because it's possible to use this API with keys on different curves, we
6383 // check all N^2 combinations where N is the number of supported
6384 // curves.
6385 //
6386 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
6387 // lot more curves we can be smart about things and just pick |otherCurve| so
6388 // it's not |curve| and that way we end up with only 2*N runs
6389 //
6390 for (auto curve : ValidCurves()) {
6391 for (auto localCurve : ValidCurves()) {
6392 // Generate EC key locally (with access to private key material)
6393 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
6394 int curveName = CurveToOpenSslCurveName(localCurve);
6395 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
6396 ASSERT_NE(group, nullptr);
6397 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
6398 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
6399 auto pkey = EVP_PKEY_Ptr(EVP_PKEY_new());
6400 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(pkey.get(), ecKey.get()), 1);
6401
6402 // Get encoded form of the public part of the locally generated key...
6403 unsigned char* p = nullptr;
6404 int encodedPublicKeySize = i2d_PUBKEY(pkey.get(), &p);
6405 ASSERT_GT(encodedPublicKeySize, 0);
6406 vector<uint8_t> encodedPublicKey(
6407 reinterpret_cast<const uint8_t*>(p),
6408 reinterpret_cast<const uint8_t*>(p + encodedPublicKeySize));
6409 OPENSSL_free(p);
6410
6411 // Generate EC key in KeyMint (only access to public key material)
6412 vector<uint8_t> challenge = {0x41, 0x42};
6413 EXPECT_EQ(
6414 ErrorCode::OK,
6415 GenerateKey(AuthorizationSetBuilder()
6416 .Authorization(TAG_NO_AUTH_REQUIRED)
6417 .Authorization(TAG_EC_CURVE, curve)
6418 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
6419 .Authorization(TAG_ALGORITHM, Algorithm::EC)
6420 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
Janis Danisevskis164bb872021-02-09 11:30:25 -08006421 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
6422 .SetDefaultValidity()))
David Zeuthene0c40892021-01-08 12:54:11 -05006423 << "Failed to generate key";
6424 ASSERT_GT(cert_chain_.size(), 0);
6425 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
6426 ASSERT_NE(kmKeyCert, nullptr);
6427 // Check that keyAgreement (bit 4) is set in KeyUsage
6428 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
6429 auto kmPkey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
6430 ASSERT_NE(kmPkey, nullptr);
6431 if (dump_Attestations) {
6432 for (size_t n = 0; n < cert_chain_.size(); n++) {
6433 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
6434 }
6435 }
6436
6437 // Now that we have the two keys, we ask KeyMint to perform ECDH...
6438 if (curve != localCurve) {
6439 // If the keys are using different curves KeyMint should fail with
6440 // ErrorCode:INVALID_ARGUMENT. Check that.
6441 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6442 string ZabFromKeyMintStr;
6443 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
6444 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6445 &ZabFromKeyMintStr));
6446
6447 } else {
6448 // Otherwise if the keys are using the same curve, it should work.
6449 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
6450 string ZabFromKeyMintStr;
6451 EXPECT_EQ(ErrorCode::OK,
6452 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
6453 &ZabFromKeyMintStr));
6454 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
6455
6456 // Perform local ECDH between the two keys so we can check if we get the same Zab..
6457 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(pkey.get(), nullptr));
6458 ASSERT_NE(ctx, nullptr);
6459 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
6460 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPkey.get()), 1);
6461 size_t ZabFromTestLen = 0;
6462 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
6463 vector<uint8_t> ZabFromTest;
6464 ZabFromTest.resize(ZabFromTestLen);
6465 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
6466
6467 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
6468 }
6469
6470 CheckedDeleteKey();
6471 }
6472 }
6473}
6474
6475INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
6476
David Drysdaled2cc8c22021-04-15 13:29:45 +01006477using DestroyAttestationIdsTest = KeyMintAidlTestBase;
6478
6479// This is a problematic test, as it can render the device under test permanently unusable.
6480// Re-enable and run at your own risk.
6481TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
6482 auto result = DestroyAttestationIds();
6483 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
6484}
6485
6486INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
6487
Shawn Willdend659c7c2021-02-19 14:51:51 -07006488using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006489
David Drysdaledb0dcf52021-05-18 11:43:31 +01006490/*
6491 * EarlyBootKeyTest.CreateEarlyBootKeys
6492 *
6493 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
6494 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006495TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01006496 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006497 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6498 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6499
David Drysdaleadfe6112021-05-27 12:00:53 +01006500 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6501 ASSERT_GT(keyData.blob.size(), 0U);
6502 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6503 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6504 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006505 CheckedDeleteKey(&aesKeyData.blob);
6506 CheckedDeleteKey(&hmacKeyData.blob);
6507 CheckedDeleteKey(&rsaKeyData.blob);
6508 CheckedDeleteKey(&ecdsaKeyData.blob);
6509}
6510
David Drysdaledb0dcf52021-05-18 11:43:31 +01006511/*
David Drysdaleadfe6112021-05-27 12:00:53 +01006512 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
6513 *
6514 * Verifies that creating an early boot key with attestation succeeds.
6515 */
6516TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
6517 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
6518 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
6519 builder->AttestationChallenge("challenge");
6520 builder->AttestationApplicationId("app_id");
6521 });
6522
6523 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
6524 ASSERT_GT(keyData.blob.size(), 0U);
6525 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
6526 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
6527 }
6528 CheckedDeleteKey(&aesKeyData.blob);
6529 CheckedDeleteKey(&hmacKeyData.blob);
6530 CheckedDeleteKey(&rsaKeyData.blob);
6531 CheckedDeleteKey(&ecdsaKeyData.blob);
6532}
6533
6534/*
6535 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01006536 *
6537 * Verifies that using early boot keys at a later stage fails.
6538 */
6539TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
6540 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6541 .Authorization(TAG_NO_AUTH_REQUIRED)
6542 .Authorization(TAG_EARLY_BOOT_ONLY)
6543 .HmacKey(128)
6544 .Digest(Digest::SHA_2_256)
6545 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
6546 AuthorizationSet output_params;
6547 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
6548 AuthorizationSetBuilder()
6549 .Digest(Digest::SHA_2_256)
6550 .Authorization(TAG_MAC_LENGTH, 256),
6551 &output_params));
6552}
6553
6554/*
6555 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
6556 *
6557 * Verifies that importing early boot keys fails.
6558 */
6559TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
6560 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
6561 .Authorization(TAG_NO_AUTH_REQUIRED)
6562 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01006563 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01006564 .Digest(Digest::SHA_2_256)
6565 .SetDefaultValidity(),
6566 KeyFormat::PKCS8, ec_256_key));
6567}
6568
David Drysdaled2cc8c22021-04-15 13:29:45 +01006569// 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 +00006570// boot stage, which no proper Android device is by the time we can run VTS. To use this,
6571// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
6572// early boot, so you'll have to reboot between runs.
6573TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
6574 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6575 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
6576 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
6577 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6578 EXPECT_TRUE(
6579 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6580 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6581 EXPECT_TRUE(
6582 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
6583
6584 // Should be able to use keys, since early boot has not ended
6585 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6586 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6587 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6588 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6589
6590 // End early boot
6591 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
6592 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
6593
6594 // Should not be able to use already-created keys.
6595 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
6596 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
6597 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
6598 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
6599
6600 CheckedDeleteKey(&aesKeyData.blob);
6601 CheckedDeleteKey(&hmacKeyData.blob);
6602 CheckedDeleteKey(&rsaKeyData.blob);
6603 CheckedDeleteKey(&ecdsaKeyData.blob);
6604
6605 // Should not be able to create new keys
6606 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
6607 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
6608
6609 CheckedDeleteKey(&aesKeyData.blob);
6610 CheckedDeleteKey(&hmacKeyData.blob);
6611 CheckedDeleteKey(&rsaKeyData.blob);
6612 CheckedDeleteKey(&ecdsaKeyData.blob);
6613}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006614
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006615INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
6616
Shawn Willdend659c7c2021-02-19 14:51:51 -07006617using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006618
6619// This may be a problematic test. It can't be run repeatedly without unlocking the device in
6620// between runs... and on most test devices there are no enrolled credentials so it can't be
6621// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
6622// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
6623// a manual test process, which includes unlocking between runs, which is why it's included here.
6624// Well, that and the fact that it's the only test we can do without also making calls into the
6625// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
6626// implications might be, so that may or may not be a solution.
6627TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
6628 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
6629 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
6630
6631 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
6632 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
6633 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
6634 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
6635
6636 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01006637 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006638 ASSERT_EQ(ErrorCode::OK, rc);
6639 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
6640 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
6641 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
6642 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
6643
6644 CheckedDeleteKey(&aesKeyData.blob);
6645 CheckedDeleteKey(&hmacKeyData.blob);
6646 CheckedDeleteKey(&rsaKeyData.blob);
6647 CheckedDeleteKey(&ecdsaKeyData.blob);
6648}
Shawn Willdend659c7c2021-02-19 14:51:51 -07006649
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00006650INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
6651
Janis Danisevskis24c04702020-12-16 18:28:39 -08006652} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07006653
6654int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07006655 std::cout << "Testing ";
6656 auto halInstances =
6657 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
6658 std::cout << "HAL instances:\n";
6659 for (auto& entry : halInstances) {
6660 std::cout << " " << entry << '\n';
6661 }
6662
Selene Huang31ab4042020-04-29 04:22:39 -07006663 ::testing::InitGoogleTest(&argc, argv);
6664 for (int i = 1; i < argc; ++i) {
6665 if (argv[i][0] == '-') {
6666 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07006667 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6668 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07006669 }
6670 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07006671 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
6672 dump_Attestations = true;
6673 } else {
6674 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07006675 }
David Drysdalebb3d85e2021-04-13 11:15:51 +01006676 // TODO(drysdale): Remove this flag when available KeyMint devices comply with spec
6677 if (std::string(argv[i]) == "--check_patchLevels") {
6678 aidl::android::hardware::security::keymint::test::check_patchLevels = true;
6679 }
Selene Huang31ab4042020-04-29 04:22:39 -07006680 }
6681 }
Shawn Willden08a7e432020-12-11 13:05:27 +00006682 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07006683}