blob: 651b21f19e0c7fd0e84b5924d8a4e59497db8055 [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 }
Seth Mooreb393b082021-07-12 14:18:28 -07001496 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1497 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001498 continue;
1499 }
1500 ASSERT_EQ(result, ErrorCode::OK);
1501 ASSERT_GT(key_blob.size(), 0U);
1502
1503 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1504 ASSERT_GT(cert_chain_.size(), 0);
1505 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1506
1507 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1508 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001509 // Some tags are optional, so don't require them to be in the enforcements.
1510 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001511 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1512 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1513 }
1514
1515 // Verifying the attestation record will check for the specific tag because
1516 // it's included in the authorizations.
1517 EXPECT_TRUE(verify_attestation_record(challenge, app_id, sw_enforced, hw_enforced,
1518 SecLevel(), cert_chain_[0].encodedCertificate));
1519
1520 CheckedDeleteKey(&key_blob);
1521 }
1522
1523 // Device attestation IDs should be rejected for normal attestation requests; these fields
1524 // are only used for device unique attestation.
1525 auto invalid_tags = AuthorizationSetBuilder()
1526 .Authorization(TAG_ATTESTATION_ID_BRAND, "brand")
1527 .Authorization(TAG_ATTESTATION_ID_DEVICE, "device")
1528 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "product")
1529 .Authorization(TAG_ATTESTATION_ID_SERIAL, "serial")
1530 .Authorization(TAG_ATTESTATION_ID_IMEI, "imei")
1531 .Authorization(TAG_ATTESTATION_ID_MEID, "meid")
1532 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "manufacturer")
1533 .Authorization(TAG_ATTESTATION_ID_MODEL, "model");
1534 for (const KeyParameter& tag : invalid_tags) {
1535 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1536 vector<uint8_t> key_blob;
1537 vector<KeyCharacteristics> key_characteristics;
1538 AuthorizationSetBuilder builder =
1539 AuthorizationSetBuilder()
1540 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001541 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001542 .Digest(Digest::NONE)
1543 .AttestationChallenge(challenge)
1544 .AttestationApplicationId(app_id)
1545 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1546 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1547 .SetDefaultValidity();
1548 builder.push_back(tag);
1549 ASSERT_EQ(ErrorCode::CANNOT_ATTEST_IDS,
1550 GenerateKey(builder, &key_blob, &key_characteristics));
1551 }
1552}
1553
1554/*
1555 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
1556 *
1557 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
1558 */
1559TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
1560 auto challenge = "hello";
1561 auto attest_app_id = "foo";
1562 auto subject = "cert subj 2";
1563 vector<uint8_t> subject_der(make_name_from_str(subject));
1564 uint64_t serial_int = 0x1010;
1565 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1566
1567 // Earlier versions of the attestation extension schema included a slot:
1568 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
1569 // This should never have been included, and should never be filled in.
1570 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
1571 // to confirm that this field never makes it into the attestation extension.
1572 vector<uint8_t> key_blob;
1573 vector<KeyCharacteristics> key_characteristics;
1574 auto result = GenerateKey(AuthorizationSetBuilder()
1575 .Authorization(TAG_NO_AUTH_REQUIRED)
1576 .EcdsaSigningKey(EcCurve::P_256)
1577 .Digest(Digest::NONE)
1578 .AttestationChallenge(challenge)
1579 .AttestationApplicationId(attest_app_id)
1580 .Authorization(TAG_APPLICATION_ID, "client_id")
1581 .Authorization(TAG_APPLICATION_DATA, "appdata")
1582 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1583 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1584 .SetDefaultValidity(),
1585 &key_blob, &key_characteristics);
1586 ASSERT_EQ(result, ErrorCode::OK);
1587 ASSERT_GT(key_blob.size(), 0U);
1588
1589 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1590 ASSERT_GT(cert_chain_.size(), 0);
1591 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1592
1593 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1594 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1595 EXPECT_TRUE(verify_attestation_record(challenge, attest_app_id, sw_enforced, hw_enforced,
1596 SecLevel(), cert_chain_[0].encodedCertificate));
1597
1598 // Check that the app id is not in the cert.
1599 string app_id = "clientid";
1600 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
1601 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
1602 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
1603 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
1604 cert_chain_[0].encodedCertificate.end());
1605
1606 CheckedDeleteKey(&key_blob);
1607}
1608
1609/*
Selene Huang4f64c222021-04-13 19:54:36 -07001610 * NewKeyGenerationTest.EcdsaSelfSignAttestation
1611 *
1612 * Verifies that if no challenge is provided to an Ecdsa key generation, then
1613 * the key will generate a self signed attestation.
1614 */
1615TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07001616 auto subject = "cert subj 2";
1617 vector<uint8_t> subject_der(make_name_from_str(subject));
1618
1619 uint64_t serial_int = 0x123456FFF1234;
1620 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1621
David Drysdaledf09e542021-06-08 15:46:11 +01001622 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001623 vector<uint8_t> key_blob;
1624 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001625 ASSERT_EQ(ErrorCode::OK,
1626 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001627 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07001628 .Digest(Digest::NONE)
1629 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1630 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1631 .SetDefaultValidity(),
1632 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001633 ASSERT_GT(key_blob.size(), 0U);
1634 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001635 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001636
1637 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1638
1639 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001640 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001641
1642 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07001643 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001644 ASSERT_EQ(cert_chain_.size(), 1);
1645
1646 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1647 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1648
1649 CheckedDeleteKey(&key_blob);
1650 }
1651}
1652
1653/*
1654 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
1655 *
1656 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
1657 * app id must also be provided or else it will fail.
1658 */
1659TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
1660 auto challenge = "hello";
1661 vector<uint8_t> key_blob;
1662 vector<KeyCharacteristics> key_characteristics;
1663
1664 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING,
1665 GenerateKey(AuthorizationSetBuilder()
1666 .EcdsaSigningKey(EcCurve::P_256)
1667 .Digest(Digest::NONE)
1668 .AttestationChallenge(challenge)
1669 .SetDefaultValidity(),
1670 &key_blob, &key_characteristics));
1671}
1672
1673/*
1674 * NewKeyGenerationTest.EcdsaIgnoreAppId
1675 *
1676 * Verifies that if no challenge is provided to the Ecdsa key generation, then
1677 * any appid will be ignored, and keymint will generate a self sign certificate.
1678 */
1679TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
1680 auto app_id = "foo";
1681
David Drysdaledf09e542021-06-08 15:46:11 +01001682 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001683 vector<uint8_t> key_blob;
1684 vector<KeyCharacteristics> key_characteristics;
1685 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001686 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07001687 .Digest(Digest::NONE)
1688 .AttestationApplicationId(app_id)
1689 .SetDefaultValidity(),
1690 &key_blob, &key_characteristics));
1691
1692 ASSERT_GT(key_blob.size(), 0U);
1693 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001694 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001695
1696 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1697
1698 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001699 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001700
1701 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1702 ASSERT_EQ(cert_chain_.size(), 1);
1703
1704 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1705 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1706
1707 CheckedDeleteKey(&key_blob);
1708 }
1709}
1710
1711/*
1712 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
1713 *
1714 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
1715 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
1716 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
1717 * to specify how many following bytes will be used to encode the length.
1718 */
1719TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
1720 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07001721 std::vector<uint32_t> app_id_lengths{143, 258};
1722
1723 for (uint32_t length : app_id_lengths) {
1724 const string app_id(length, 'a');
1725 vector<uint8_t> key_blob;
1726 vector<KeyCharacteristics> key_characteristics;
1727 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1728 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001729 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang4f64c222021-04-13 19:54:36 -07001730 .Digest(Digest::NONE)
1731 .AttestationChallenge(challenge)
1732 .AttestationApplicationId(app_id)
1733 .SetDefaultValidity(),
1734 &key_blob, &key_characteristics));
1735 ASSERT_GT(key_blob.size(), 0U);
1736 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001737 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001738
1739 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1740
1741 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001742 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001743
1744 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1745 ASSERT_GT(cert_chain_.size(), 0);
1746
1747 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1748 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1749 EXPECT_TRUE(verify_attestation_record(challenge, app_id, //
1750 sw_enforced, hw_enforced, SecLevel(),
1751 cert_chain_[0].encodedCertificate));
1752
1753 CheckedDeleteKey(&key_blob);
1754 }
1755}
1756
1757/*
Qi Wud22ec842020-11-26 13:27:53 +08001758 * NewKeyGenerationTest.LimitedUsageEcdsa
1759 *
1760 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
1761 * resulting keys have correct characteristics.
1762 */
1763TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001764 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08001765 vector<uint8_t> key_blob;
1766 vector<KeyCharacteristics> key_characteristics;
1767 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001768 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08001769 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001770 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1771 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001772 &key_blob, &key_characteristics));
1773
1774 ASSERT_GT(key_blob.size(), 0U);
1775 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001776 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001777
1778 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1779
1780 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001781 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08001782
1783 // Check the usage count limit tag appears in the authorizations.
1784 AuthorizationSet auths;
1785 for (auto& entry : key_characteristics) {
1786 auths.push_back(AuthorizationSet(entry.authorizations));
1787 }
1788 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1789 << "key usage count limit " << 1U << " missing";
1790
1791 CheckedDeleteKey(&key_blob);
1792 }
1793}
1794
1795/*
Selene Huang31ab4042020-04-29 04:22:39 -07001796 * NewKeyGenerationTest.EcdsaDefaultSize
1797 *
David Drysdaledf09e542021-06-08 15:46:11 +01001798 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07001799 * UNSUPPORTED_KEY_SIZE.
1800 */
1801TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
1802 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1803 GenerateKey(AuthorizationSetBuilder()
1804 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1805 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08001806 .Digest(Digest::NONE)
1807 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001808}
1809
1810/*
1811 * NewKeyGenerationTest.EcdsaInvalidSize
1812 *
1813 * Verifies that specifying an invalid key size for EC key generation returns
1814 * UNSUPPORTED_KEY_SIZE.
1815 */
1816TEST_P(NewKeyGenerationTest, EcdsaInvalidSize) {
David Drysdaledf09e542021-06-08 15:46:11 +01001817 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001818 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001819 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001820 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001821 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001822 .Digest(Digest::NONE)
1823 .SetDefaultValidity(),
1824 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001825 }
1826
David Drysdaledf09e542021-06-08 15:46:11 +01001827 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1828 GenerateKey(AuthorizationSetBuilder()
1829 .Authorization(TAG_ALGORITHM, Algorithm::EC)
1830 .Authorization(TAG_KEY_SIZE, 190)
1831 .SigningKey()
1832 .Digest(Digest::NONE)
1833 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001834}
1835
1836/*
1837 * NewKeyGenerationTest.EcdsaMismatchKeySize
1838 *
1839 * Verifies that specifying mismatched key size and curve for EC key generation returns
1840 * INVALID_ARGUMENT.
1841 */
1842TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
1843 if (SecLevel() == SecurityLevel::STRONGBOX) return;
1844
David Drysdaledf09e542021-06-08 15:46:11 +01001845 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01001846 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01001847 .Authorization(TAG_KEY_SIZE, 224)
1848 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01001849 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01001850 .Digest(Digest::NONE)
1851 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01001852 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07001853}
1854
1855/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001856 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07001857 *
1858 * Verifies that keymint does not support any curve designated as unsupported.
1859 */
1860TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
1861 Digest digest;
1862 if (SecLevel() == SecurityLevel::STRONGBOX) {
1863 digest = Digest::SHA_2_256;
1864 } else {
1865 digest = Digest::SHA_2_512;
1866 }
1867 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08001868 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1869 .EcdsaSigningKey(curve)
1870 .Digest(digest)
1871 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07001872 << "Failed to generate key on curve: " << curve;
1873 CheckedDeleteKey();
1874 }
1875}
1876
1877/*
1878 * NewKeyGenerationTest.Hmac
1879 *
1880 * Verifies that keymint supports all required digests, and that the resulting keys have correct
1881 * characteristics.
1882 */
1883TEST_P(NewKeyGenerationTest, Hmac) {
1884 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1885 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001886 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001887 constexpr size_t key_size = 128;
1888 ASSERT_EQ(ErrorCode::OK,
1889 GenerateKey(
1890 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
1891 TAG_MIN_MAC_LENGTH, 128),
1892 &key_blob, &key_characteristics));
1893
1894 ASSERT_GT(key_blob.size(), 0U);
1895 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001896 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001897
Shawn Willden7f424372021-01-10 18:06:50 -07001898 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1899 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1900 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1901 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001902
1903 CheckedDeleteKey(&key_blob);
1904 }
1905}
1906
1907/*
Selene Huang4f64c222021-04-13 19:54:36 -07001908 * NewKeyGenerationTest.HmacNoAttestation
1909 *
1910 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
1911 * and app id are provided.
1912 */
1913TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
1914 auto challenge = "hello";
1915 auto app_id = "foo";
1916
1917 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1918 vector<uint8_t> key_blob;
1919 vector<KeyCharacteristics> key_characteristics;
1920 constexpr size_t key_size = 128;
1921 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1922 .HmacKey(key_size)
1923 .Digest(digest)
1924 .AttestationChallenge(challenge)
1925 .AttestationApplicationId(app_id)
1926 .Authorization(TAG_MIN_MAC_LENGTH, 128),
1927 &key_blob, &key_characteristics));
1928
1929 ASSERT_GT(key_blob.size(), 0U);
1930 ASSERT_EQ(cert_chain_.size(), 0);
1931 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001932 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001933
1934 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1935 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1936 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1937 << "Key size " << key_size << "missing";
1938
1939 CheckedDeleteKey(&key_blob);
1940 }
1941}
1942
1943/*
Qi Wud22ec842020-11-26 13:27:53 +08001944 * NewKeyGenerationTest.LimitedUsageHmac
1945 *
1946 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
1947 * resulting keys have correct characteristics.
1948 */
1949TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
1950 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
1951 vector<uint8_t> key_blob;
1952 vector<KeyCharacteristics> key_characteristics;
1953 constexpr size_t key_size = 128;
1954 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1955 .HmacKey(key_size)
1956 .Digest(digest)
1957 .Authorization(TAG_MIN_MAC_LENGTH, 128)
1958 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
1959 &key_blob, &key_characteristics));
1960
1961 ASSERT_GT(key_blob.size(), 0U);
1962 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001963 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001964
1965 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1966 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
1967 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1968 << "Key size " << key_size << "missing";
1969
1970 // Check the usage count limit tag appears in the authorizations.
1971 AuthorizationSet auths;
1972 for (auto& entry : key_characteristics) {
1973 auths.push_back(AuthorizationSet(entry.authorizations));
1974 }
1975 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1976 << "key usage count limit " << 1U << " missing";
1977
1978 CheckedDeleteKey(&key_blob);
1979 }
1980}
1981
1982/*
Selene Huang31ab4042020-04-29 04:22:39 -07001983 * NewKeyGenerationTest.HmacCheckKeySizes
1984 *
1985 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
1986 */
1987TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
1988 for (size_t key_size = 0; key_size <= 512; ++key_size) {
1989 if (key_size < 64 || key_size % 8 != 0) {
1990 // To keep this test from being very slow, we only test a random fraction of
1991 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
1992 // them, we expect to run ~40 of them in each run.
1993 if (key_size % 8 == 0 || random() % 10 == 0) {
1994 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1995 GenerateKey(AuthorizationSetBuilder()
1996 .HmacKey(key_size)
1997 .Digest(Digest::SHA_2_256)
1998 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
1999 << "HMAC key size " << key_size << " invalid";
2000 }
2001 } else {
2002 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2003 .HmacKey(key_size)
2004 .Digest(Digest::SHA_2_256)
2005 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2006 << "Failed to generate HMAC key of size " << key_size;
2007 CheckedDeleteKey();
2008 }
2009 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002010 if (SecLevel() == SecurityLevel::STRONGBOX) {
2011 // STRONGBOX devices must not support keys larger than 512 bits.
2012 size_t key_size = 520;
2013 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2014 GenerateKey(AuthorizationSetBuilder()
2015 .HmacKey(key_size)
2016 .Digest(Digest::SHA_2_256)
2017 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2018 << "HMAC key size " << key_size << " unexpectedly valid";
2019 }
Selene Huang31ab4042020-04-29 04:22:39 -07002020}
2021
2022/*
2023 * NewKeyGenerationTest.HmacCheckMinMacLengths
2024 *
2025 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2026 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2027 * specific MAC length that failed, so reproducing a failed run will be easy.
2028 */
2029TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2030 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2031 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2032 // To keep this test from being very long, we only test a random fraction of
2033 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2034 // we expect to run ~17 of them in each run.
2035 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2036 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2037 GenerateKey(AuthorizationSetBuilder()
2038 .HmacKey(128)
2039 .Digest(Digest::SHA_2_256)
2040 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2041 << "HMAC min mac length " << min_mac_length << " invalid.";
2042 }
2043 } else {
2044 EXPECT_EQ(ErrorCode::OK,
2045 GenerateKey(AuthorizationSetBuilder()
2046 .HmacKey(128)
2047 .Digest(Digest::SHA_2_256)
2048 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2049 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2050 CheckedDeleteKey();
2051 }
2052 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002053
2054 // Minimum MAC length must be no more than 512 bits.
2055 size_t min_mac_length = 520;
2056 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2057 GenerateKey(AuthorizationSetBuilder()
2058 .HmacKey(128)
2059 .Digest(Digest::SHA_2_256)
2060 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2061 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002062}
2063
2064/*
2065 * NewKeyGenerationTest.HmacMultipleDigests
2066 *
2067 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2068 */
2069TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
2070 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2071
2072 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2073 GenerateKey(AuthorizationSetBuilder()
2074 .HmacKey(128)
2075 .Digest(Digest::SHA1)
2076 .Digest(Digest::SHA_2_256)
2077 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2078}
2079
2080/*
2081 * NewKeyGenerationTest.HmacDigestNone
2082 *
2083 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2084 */
2085TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2086 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2087 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2088 128)));
2089
2090 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2091 GenerateKey(AuthorizationSetBuilder()
2092 .HmacKey(128)
2093 .Digest(Digest::NONE)
2094 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2095}
2096
Selene Huang4f64c222021-04-13 19:54:36 -07002097/*
2098 * NewKeyGenerationTest.AesNoAttestation
2099 *
2100 * Verifies that attestation parameters to AES keys are ignored and generateKey
2101 * will succeed.
2102 */
2103TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2104 auto challenge = "hello";
2105 auto app_id = "foo";
2106
2107 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2108 .Authorization(TAG_NO_AUTH_REQUIRED)
2109 .AesEncryptionKey(128)
2110 .EcbMode()
2111 .Padding(PaddingMode::PKCS7)
2112 .AttestationChallenge(challenge)
2113 .AttestationApplicationId(app_id)));
2114
2115 ASSERT_EQ(cert_chain_.size(), 0);
2116}
2117
2118/*
2119 * NewKeyGenerationTest.TripleDesNoAttestation
2120 *
2121 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2122 * will be successful. No attestation should be generated.
2123 */
2124TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2125 auto challenge = "hello";
2126 auto app_id = "foo";
2127
2128 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2129 .TripleDesEncryptionKey(168)
2130 .BlockMode(BlockMode::ECB)
2131 .Authorization(TAG_NO_AUTH_REQUIRED)
2132 .Padding(PaddingMode::NONE)
2133 .AttestationChallenge(challenge)
2134 .AttestationApplicationId(app_id)));
2135 ASSERT_EQ(cert_chain_.size(), 0);
2136}
2137
Selene Huang31ab4042020-04-29 04:22:39 -07002138INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2139
2140typedef KeyMintAidlTestBase SigningOperationsTest;
2141
2142/*
2143 * SigningOperationsTest.RsaSuccess
2144 *
2145 * Verifies that raw RSA signature operations succeed.
2146 */
2147TEST_P(SigningOperationsTest, RsaSuccess) {
2148 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2149 .RsaSigningKey(2048, 65537)
2150 .Digest(Digest::NONE)
2151 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002152 .Authorization(TAG_NO_AUTH_REQUIRED)
2153 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002154 string message = "12345678901234567890123456789012";
2155 string signature = SignMessage(
2156 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002157 LocalVerifyMessage(message, signature,
2158 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2159}
2160
2161/*
2162 * SigningOperationsTest.RsaAllPaddingsAndDigests
2163 *
2164 * Verifies RSA signature/verification for all padding modes and digests.
2165 */
2166TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2167 auto authorizations = AuthorizationSetBuilder()
2168 .Authorization(TAG_NO_AUTH_REQUIRED)
2169 .RsaSigningKey(2048, 65537)
2170 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2171 .Padding(PaddingMode::NONE)
2172 .Padding(PaddingMode::RSA_PSS)
2173 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2174 .SetDefaultValidity();
2175
2176 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2177
2178 string message(128, 'a');
2179 string corrupt_message(message);
2180 ++corrupt_message[corrupt_message.size() / 2];
2181
2182 for (auto padding :
2183 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2184 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2185 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2186 // Digesting only makes sense with padding.
2187 continue;
2188 }
2189
2190 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2191 // PSS requires digesting.
2192 continue;
2193 }
2194
2195 string signature =
2196 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2197 LocalVerifyMessage(message, signature,
2198 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2199 }
2200 }
Selene Huang31ab4042020-04-29 04:22:39 -07002201}
2202
2203/*
2204 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2205 *
Shawn Willden7f424372021-01-10 18:06:50 -07002206 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002207 */
2208TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2209 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2210 .Authorization(TAG_NO_AUTH_REQUIRED)
2211 .RsaSigningKey(2048, 65537)
2212 .Digest(Digest::NONE)
2213 .Padding(PaddingMode::NONE)
2214 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002215 .Authorization(TAG_APPLICATION_DATA, "appdata")
2216 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002217
2218 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2219
Selene Huang31ab4042020-04-29 04:22:39 -07002220 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2221 Begin(KeyPurpose::SIGN,
2222 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2223 AbortIfNeeded();
2224 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2225 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2226 .Digest(Digest::NONE)
2227 .Padding(PaddingMode::NONE)
2228 .Authorization(TAG_APPLICATION_ID, "clientid")));
2229 AbortIfNeeded();
2230 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2231 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2232 .Digest(Digest::NONE)
2233 .Padding(PaddingMode::NONE)
2234 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2235 AbortIfNeeded();
2236 EXPECT_EQ(ErrorCode::OK,
2237 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2238 .Digest(Digest::NONE)
2239 .Padding(PaddingMode::NONE)
2240 .Authorization(TAG_APPLICATION_DATA, "appdata")
2241 .Authorization(TAG_APPLICATION_ID, "clientid")));
2242 AbortIfNeeded();
2243}
2244
2245/*
2246 * SigningOperationsTest.RsaPssSha256Success
2247 *
2248 * Verifies that RSA-PSS signature operations succeed.
2249 */
2250TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2251 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2252 .RsaSigningKey(2048, 65537)
2253 .Digest(Digest::SHA_2_256)
2254 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002255 .Authorization(TAG_NO_AUTH_REQUIRED)
2256 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002257 // Use large message, which won't work without digesting.
2258 string message(1024, 'a');
2259 string signature = SignMessage(
2260 message,
2261 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2262}
2263
2264/*
2265 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2266 *
2267 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2268 * supports only unpadded operations.
2269 */
2270TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2271 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2272 .RsaSigningKey(2048, 65537)
2273 .Digest(Digest::NONE)
2274 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002275 .Padding(PaddingMode::NONE)
2276 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002277 string message = "12345678901234567890123456789012";
2278 string signature;
2279
2280 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2281 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2282 .Digest(Digest::NONE)
2283 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2284}
2285
2286/*
2287 * SigningOperationsTest.NoUserConfirmation
2288 *
2289 * Verifies that keymint rejects signing operations for keys with
2290 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2291 * presented.
2292 */
2293TEST_P(SigningOperationsTest, NoUserConfirmation) {
2294 if (SecLevel() == SecurityLevel::STRONGBOX) return;
Janis Danisevskis164bb872021-02-09 11:30:25 -08002295 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2296 .RsaSigningKey(1024, 65537)
2297 .Digest(Digest::NONE)
2298 .Padding(PaddingMode::NONE)
2299 .Authorization(TAG_NO_AUTH_REQUIRED)
2300 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2301 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002302
2303 const string message = "12345678901234567890123456789012";
2304 EXPECT_EQ(ErrorCode::OK,
2305 Begin(KeyPurpose::SIGN,
2306 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2307 string signature;
2308 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2309}
2310
2311/*
2312 * SigningOperationsTest.RsaPkcs1Sha256Success
2313 *
2314 * Verifies that digested RSA-PKCS1 signature operations succeed.
2315 */
2316TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2317 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2318 .RsaSigningKey(2048, 65537)
2319 .Digest(Digest::SHA_2_256)
2320 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002321 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2322 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002323 string message(1024, 'a');
2324 string signature = SignMessage(message, AuthorizationSetBuilder()
2325 .Digest(Digest::SHA_2_256)
2326 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2327}
2328
2329/*
2330 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2331 *
2332 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2333 */
2334TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2335 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2336 .RsaSigningKey(2048, 65537)
2337 .Digest(Digest::NONE)
2338 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002339 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2340 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002341 string message(53, 'a');
2342 string signature = SignMessage(message, AuthorizationSetBuilder()
2343 .Digest(Digest::NONE)
2344 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2345}
2346
2347/*
2348 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2349 *
2350 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2351 * given a too-long message.
2352 */
2353TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2354 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2355 .RsaSigningKey(2048, 65537)
2356 .Digest(Digest::NONE)
2357 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002358 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2359 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002360 string message(257, 'a');
2361
2362 EXPECT_EQ(ErrorCode::OK,
2363 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2364 .Digest(Digest::NONE)
2365 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2366 string signature;
2367 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2368}
2369
2370/*
2371 * SigningOperationsTest.RsaPssSha512TooSmallKey
2372 *
2373 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2374 * used with a key that is too small for the message.
2375 *
2376 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2377 * keymint specification requires that salt_size == digest_size, so the message will be
2378 * digest_size * 2 +
2379 * 16. Such a message can only be signed by a given key if the key is at least that size. This
2380 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
2381 * for a 1024-bit key.
2382 */
2383TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
2384 if (SecLevel() == SecurityLevel::STRONGBOX) return;
2385 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2386 .RsaSigningKey(1024, 65537)
2387 .Digest(Digest::SHA_2_512)
2388 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002389 .Padding(PaddingMode::RSA_PSS)
2390 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002391 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2392 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2393 .Digest(Digest::SHA_2_512)
2394 .Padding(PaddingMode::RSA_PSS)));
2395}
2396
2397/*
2398 * SigningOperationsTest.RsaNoPaddingTooLong
2399 *
2400 * Verifies that raw RSA signature operations fail with the correct error code when
2401 * given a too-long message.
2402 */
2403TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
2404 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2405 .RsaSigningKey(2048, 65537)
2406 .Digest(Digest::NONE)
2407 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002408 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2409 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002410 // One byte too long
2411 string message(2048 / 8 + 1, 'a');
2412 ASSERT_EQ(ErrorCode::OK,
2413 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2414 .Digest(Digest::NONE)
2415 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2416 string result;
2417 ErrorCode finish_error_code = Finish(message, &result);
2418 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2419 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2420
2421 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
2422 message = string(128 * 1024, 'a');
2423 ASSERT_EQ(ErrorCode::OK,
2424 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2425 .Digest(Digest::NONE)
2426 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2427 finish_error_code = Finish(message, &result);
2428 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
2429 finish_error_code == ErrorCode::INVALID_ARGUMENT);
2430}
2431
2432/*
2433 * SigningOperationsTest.RsaAbort
2434 *
2435 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
2436 * test, but the behavior should be algorithm and purpose-independent.
2437 */
2438TEST_P(SigningOperationsTest, RsaAbort) {
2439 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2440 .RsaSigningKey(2048, 65537)
2441 .Digest(Digest::NONE)
2442 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002443 .Padding(PaddingMode::NONE)
2444 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002445
2446 ASSERT_EQ(ErrorCode::OK,
2447 Begin(KeyPurpose::SIGN,
2448 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2449 EXPECT_EQ(ErrorCode::OK, Abort());
2450
2451 // Another abort should fail
2452 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
2453
2454 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08002455 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07002456}
2457
2458/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002459 * SigningOperationsTest.RsaNonUniqueParams
2460 *
2461 * Verifies that an operation with multiple padding modes is rejected.
2462 */
2463TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
2464 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2465 .RsaSigningKey(2048, 65537)
2466 .Digest(Digest::NONE)
2467 .Digest(Digest::SHA1)
2468 .Authorization(TAG_NO_AUTH_REQUIRED)
2469 .Padding(PaddingMode::NONE)
2470 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2471 .SetDefaultValidity()));
2472
2473 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2474 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2475 .Digest(Digest::NONE)
2476 .Padding(PaddingMode::NONE)
2477 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2478
Tommy Chiuc93c4392021-05-11 18:36:50 +08002479 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2480 .Digest(Digest::NONE)
2481 .Digest(Digest::SHA1)
2482 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2483 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01002484
2485 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2486 Begin(KeyPurpose::SIGN,
2487 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2488}
2489
2490/*
Selene Huang31ab4042020-04-29 04:22:39 -07002491 * SigningOperationsTest.RsaUnsupportedPadding
2492 *
2493 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
2494 * with a padding mode inappropriate for RSA.
2495 */
2496TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
2497 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2498 .RsaSigningKey(2048, 65537)
2499 .Authorization(TAG_NO_AUTH_REQUIRED)
2500 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002501 .Padding(PaddingMode::PKCS7)
2502 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002503 ASSERT_EQ(
2504 ErrorCode::UNSUPPORTED_PADDING_MODE,
2505 Begin(KeyPurpose::SIGN,
2506 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01002507 CheckedDeleteKey();
2508
2509 ASSERT_EQ(ErrorCode::OK,
2510 GenerateKey(
2511 AuthorizationSetBuilder()
2512 .RsaSigningKey(2048, 65537)
2513 .Authorization(TAG_NO_AUTH_REQUIRED)
2514 .Digest(Digest::SHA_2_256 /* supported digest */)
2515 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
2516 .SetDefaultValidity()));
2517 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2518 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2519 .Digest(Digest::SHA_2_256)
2520 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07002521}
2522
2523/*
2524 * SigningOperationsTest.RsaPssNoDigest
2525 *
2526 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
2527 */
2528TEST_P(SigningOperationsTest, RsaNoDigest) {
2529 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2530 .RsaSigningKey(2048, 65537)
2531 .Authorization(TAG_NO_AUTH_REQUIRED)
2532 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002533 .Padding(PaddingMode::RSA_PSS)
2534 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002535 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2536 Begin(KeyPurpose::SIGN,
2537 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
2538
2539 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2540 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
2541}
2542
2543/*
David Drysdale7de9feb2021-03-05 14:56:19 +00002544 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07002545 *
2546 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
2547 * supported in some cases (as validated in other tests), but a mode must be specified.
2548 */
2549TEST_P(SigningOperationsTest, RsaNoPadding) {
2550 // Padding must be specified
2551 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2552 .RsaKey(2048, 65537)
2553 .Authorization(TAG_NO_AUTH_REQUIRED)
2554 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002555 .Digest(Digest::NONE)
2556 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002557 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
2558 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2559}
2560
2561/*
2562 * SigningOperationsTest.RsaShortMessage
2563 *
2564 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
2565 */
2566TEST_P(SigningOperationsTest, RsaTooShortMessage) {
2567 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2568 .Authorization(TAG_NO_AUTH_REQUIRED)
2569 .RsaSigningKey(2048, 65537)
2570 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002571 .Padding(PaddingMode::NONE)
2572 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002573
2574 // Barely shorter
2575 string message(2048 / 8 - 1, 'a');
2576 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2577
2578 // Much shorter
2579 message = "a";
2580 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2581}
2582
2583/*
2584 * SigningOperationsTest.RsaSignWithEncryptionKey
2585 *
2586 * Verifies that RSA encryption keys cannot be used to sign.
2587 */
2588TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
2589 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2590 .Authorization(TAG_NO_AUTH_REQUIRED)
2591 .RsaEncryptionKey(2048, 65537)
2592 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002593 .Padding(PaddingMode::NONE)
2594 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002595 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2596 Begin(KeyPurpose::SIGN,
2597 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2598}
2599
2600/*
2601 * SigningOperationsTest.RsaSignTooLargeMessage
2602 *
2603 * Verifies that attempting a raw signature of a message which is the same length as the key,
2604 * but numerically larger than the public modulus, fails with the correct error.
2605 */
2606TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
2607 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2608 .Authorization(TAG_NO_AUTH_REQUIRED)
2609 .RsaSigningKey(2048, 65537)
2610 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002611 .Padding(PaddingMode::NONE)
2612 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002613
2614 // Largest possible message will always be larger than the public modulus.
2615 string message(2048 / 8, static_cast<char>(0xff));
2616 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2617 .Authorization(TAG_NO_AUTH_REQUIRED)
2618 .Digest(Digest::NONE)
2619 .Padding(PaddingMode::NONE)));
2620 string signature;
2621 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
2622}
2623
2624/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01002625 * SigningOperationsTest.EcdsaAllDigestsAndCurves
2626 *
2627 * Verifies ECDSA signature/verification for all digests and curves.
2628 */
2629TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
2630 auto digests = ValidDigests(true /* withNone */, false /* withMD5 */);
2631
2632 string message = "1234567890";
2633 string corrupt_message = "2234567890";
2634 for (auto curve : ValidCurves()) {
2635 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
2636 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2637 .Authorization(TAG_NO_AUTH_REQUIRED)
2638 .EcdsaSigningKey(curve)
2639 .Digest(digests)
2640 .SetDefaultValidity());
2641 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
2642 if (error != ErrorCode::OK) {
2643 continue;
2644 }
2645
2646 for (auto digest : digests) {
2647 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
2648 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
2649 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
2650 }
2651
2652 auto rc = DeleteKey();
2653 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
2654 }
2655}
2656
2657/*
Selene Huang31ab4042020-04-29 04:22:39 -07002658 * SigningOperationsTest.EcdsaAllCurves
2659 *
2660 * Verifies that ECDSA operations succeed with all possible curves.
2661 */
2662TEST_P(SigningOperationsTest, EcdsaAllCurves) {
2663 for (auto curve : ValidCurves()) {
2664 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
2665 .Authorization(TAG_NO_AUTH_REQUIRED)
2666 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002667 .Digest(Digest::SHA_2_256)
2668 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07002669 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
2670 if (error != ErrorCode::OK) continue;
2671
2672 string message(1024, 'a');
2673 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2674 CheckedDeleteKey();
2675 }
2676}
2677
2678/*
2679 * SigningOperationsTest.EcdsaNoDigestHugeData
2680 *
2681 * Verifies that ECDSA operations support very large messages, even without digesting. This
2682 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
2683 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
2684 * the framework.
2685 */
2686TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
2687 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2688 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002689 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002690 .Digest(Digest::NONE)
2691 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002692 string message(1 * 1024, 'a');
2693 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
2694}
2695
2696/*
2697 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
2698 *
2699 * Verifies that using an EC key requires the correct app ID/data.
2700 */
2701TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
2702 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2703 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002704 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07002705 .Digest(Digest::NONE)
2706 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002707 .Authorization(TAG_APPLICATION_DATA, "appdata")
2708 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002709
2710 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2711
Selene Huang31ab4042020-04-29 04:22:39 -07002712 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2713 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
2714 AbortIfNeeded();
2715 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2716 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2717 .Digest(Digest::NONE)
2718 .Authorization(TAG_APPLICATION_ID, "clientid")));
2719 AbortIfNeeded();
2720 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2721 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2722 .Digest(Digest::NONE)
2723 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2724 AbortIfNeeded();
2725 EXPECT_EQ(ErrorCode::OK,
2726 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2727 .Digest(Digest::NONE)
2728 .Authorization(TAG_APPLICATION_DATA, "appdata")
2729 .Authorization(TAG_APPLICATION_ID, "clientid")));
2730 AbortIfNeeded();
2731}
2732
2733/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002734 * SigningOperationsTest.EcdsaIncompatibleDigest
2735 *
2736 * Verifies that using an EC key requires compatible digest.
2737 */
2738TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
2739 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2740 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01002741 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01002742 .Digest(Digest::NONE)
2743 .Digest(Digest::SHA1)
2744 .SetDefaultValidity()));
2745 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
2746 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
2747 AbortIfNeeded();
2748}
2749
2750/*
Selene Huang31ab4042020-04-29 04:22:39 -07002751 * SigningOperationsTest.AesEcbSign
2752 *
2753 * Verifies that attempts to use AES keys to sign fail in the correct way.
2754 */
2755TEST_P(SigningOperationsTest, AesEcbSign) {
2756 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2757 .Authorization(TAG_NO_AUTH_REQUIRED)
2758 .SigningKey()
2759 .AesEncryptionKey(128)
2760 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
2761
2762 AuthorizationSet out_params;
2763 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2764 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
2765 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
2766 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
2767}
2768
2769/*
2770 * SigningOperationsTest.HmacAllDigests
2771 *
2772 * Verifies that HMAC works with all digests.
2773 */
2774TEST_P(SigningOperationsTest, HmacAllDigests) {
2775 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
2776 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2777 .Authorization(TAG_NO_AUTH_REQUIRED)
2778 .HmacKey(128)
2779 .Digest(digest)
2780 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
2781 << "Failed to create HMAC key with digest " << digest;
2782 string message = "12345678901234567890123456789012";
2783 string signature = MacMessage(message, digest, 160);
2784 EXPECT_EQ(160U / 8U, signature.size())
2785 << "Failed to sign with HMAC key with digest " << digest;
2786 CheckedDeleteKey();
2787 }
2788}
2789
2790/*
2791 * SigningOperationsTest.HmacSha256TooLargeMacLength
2792 *
2793 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
2794 * digest size.
2795 */
2796TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
2797 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2798 .Authorization(TAG_NO_AUTH_REQUIRED)
2799 .HmacKey(128)
2800 .Digest(Digest::SHA_2_256)
2801 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
2802 AuthorizationSet output_params;
2803 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2804 AuthorizationSetBuilder()
2805 .Digest(Digest::SHA_2_256)
2806 .Authorization(TAG_MAC_LENGTH, 264),
2807 &output_params));
2808}
2809
2810/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002811 * SigningOperationsTest.HmacSha256InvalidMacLength
2812 *
2813 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
2814 * not a multiple of 8.
2815 */
2816TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
2817 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2818 .Authorization(TAG_NO_AUTH_REQUIRED)
2819 .HmacKey(128)
2820 .Digest(Digest::SHA_2_256)
2821 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
2822 AuthorizationSet output_params;
2823 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2824 AuthorizationSetBuilder()
2825 .Digest(Digest::SHA_2_256)
2826 .Authorization(TAG_MAC_LENGTH, 161),
2827 &output_params));
2828}
2829
2830/*
Selene Huang31ab4042020-04-29 04:22:39 -07002831 * SigningOperationsTest.HmacSha256TooSmallMacLength
2832 *
2833 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
2834 * specified minimum MAC length.
2835 */
2836TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
2837 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2838 .Authorization(TAG_NO_AUTH_REQUIRED)
2839 .HmacKey(128)
2840 .Digest(Digest::SHA_2_256)
2841 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2842 AuthorizationSet output_params;
2843 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
2844 AuthorizationSetBuilder()
2845 .Digest(Digest::SHA_2_256)
2846 .Authorization(TAG_MAC_LENGTH, 120),
2847 &output_params));
2848}
2849
2850/*
2851 * SigningOperationsTest.HmacRfc4231TestCase3
2852 *
2853 * Validates against the test vectors from RFC 4231 test case 3.
2854 */
2855TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
2856 string key(20, 0xaa);
2857 string message(50, 0xdd);
2858 uint8_t sha_224_expected[] = {
2859 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
2860 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
2861 };
2862 uint8_t sha_256_expected[] = {
2863 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
2864 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
2865 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
2866 };
2867 uint8_t sha_384_expected[] = {
2868 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
2869 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
2870 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
2871 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
2872 };
2873 uint8_t sha_512_expected[] = {
2874 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
2875 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
2876 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
2877 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
2878 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
2879 };
2880
2881 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2882 if (SecLevel() != SecurityLevel::STRONGBOX) {
2883 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2884 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2885 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2886 }
2887}
2888
2889/*
2890 * SigningOperationsTest.HmacRfc4231TestCase5
2891 *
2892 * Validates against the test vectors from RFC 4231 test case 5.
2893 */
2894TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
2895 string key(20, 0x0c);
2896 string message = "Test With Truncation";
2897
2898 uint8_t sha_224_expected[] = {
2899 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
2900 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
2901 };
2902 uint8_t sha_256_expected[] = {
2903 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
2904 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
2905 };
2906 uint8_t sha_384_expected[] = {
2907 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
2908 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
2909 };
2910 uint8_t sha_512_expected[] = {
2911 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
2912 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
2913 };
2914
2915 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
2916 if (SecLevel() != SecurityLevel::STRONGBOX) {
2917 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
2918 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
2919 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
2920 }
2921}
2922
2923INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
2924
2925typedef KeyMintAidlTestBase VerificationOperationsTest;
2926
2927/*
Selene Huang31ab4042020-04-29 04:22:39 -07002928 * VerificationOperationsTest.HmacSigningKeyCannotVerify
2929 *
2930 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
2931 */
2932TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
2933 string key_material = "HelloThisIsAKey";
2934
2935 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07002936 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07002937 EXPECT_EQ(ErrorCode::OK,
2938 ImportKey(AuthorizationSetBuilder()
2939 .Authorization(TAG_NO_AUTH_REQUIRED)
2940 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2941 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
2942 .Digest(Digest::SHA_2_256)
2943 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2944 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
2945 EXPECT_EQ(ErrorCode::OK,
2946 ImportKey(AuthorizationSetBuilder()
2947 .Authorization(TAG_NO_AUTH_REQUIRED)
2948 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
2949 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
2950 .Digest(Digest::SHA_2_256)
2951 .Authorization(TAG_MIN_MAC_LENGTH, 160),
2952 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
2953
2954 string message = "This is a message.";
2955 string signature = SignMessage(
2956 signing_key, message,
2957 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
2958
2959 // Signing key should not work.
2960 AuthorizationSet out_params;
2961 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
2962 Begin(KeyPurpose::VERIFY, signing_key,
2963 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
2964
2965 // Verification key should work.
2966 VerifyMessage(verification_key, message, signature,
2967 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
2968
2969 CheckedDeleteKey(&signing_key);
2970 CheckedDeleteKey(&verification_key);
2971}
2972
2973INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
2974
2975typedef KeyMintAidlTestBase ExportKeyTest;
2976
2977/*
2978 * ExportKeyTest.RsaUnsupportedKeyFormat
2979 *
2980 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
2981 */
2982// TODO(seleneh) add ExportKey to GenerateKey
2983// check result
2984
2985class ImportKeyTest : public KeyMintAidlTestBase {
2986 public:
2987 template <TagType tag_type, Tag tag, typename ValueT>
2988 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
2989 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07002990 for (auto& entry : key_characteristics_) {
2991 if (entry.securityLevel == SecLevel()) {
2992 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
2993 << "Tag " << tag << " with value " << expected
2994 << " not found at security level" << entry.securityLevel;
2995 } else {
2996 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
2997 << "Tag " << tag << " found at security level " << entry.securityLevel;
2998 }
Selene Huang31ab4042020-04-29 04:22:39 -07002999 }
3000 }
3001
3002 void CheckOrigin() {
3003 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003004 // Origin isn't a crypto param, but it always lives with them.
3005 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003006 }
3007};
3008
3009/*
3010 * ImportKeyTest.RsaSuccess
3011 *
3012 * Verifies that importing and using an RSA key pair works correctly.
3013 */
3014TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003015 uint32_t key_size;
3016 string key;
3017
3018 if (SecLevel() == SecurityLevel::STRONGBOX) {
3019 key_size = 2048;
3020 key = rsa_2048_key;
3021 } else {
3022 key_size = 1024;
3023 key = rsa_key;
3024 }
3025
Selene Huang31ab4042020-04-29 04:22:39 -07003026 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3027 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003028 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003029 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003030 .Padding(PaddingMode::RSA_PSS)
3031 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003032 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003033
3034 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003035 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003036 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3037 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3038 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3039 CheckOrigin();
3040
3041 string message(1024 / 8, 'a');
3042 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3043 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003044 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003045}
3046
3047/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003048 * ImportKeyTest.RsaSuccessWithoutParams
3049 *
3050 * Verifies that importing and using an RSA key pair without specifying parameters
3051 * works correctly.
3052 */
3053TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3054 uint32_t key_size;
3055 string key;
3056
3057 if (SecLevel() == SecurityLevel::STRONGBOX) {
3058 key_size = 2048;
3059 key = rsa_2048_key;
3060 } else {
3061 key_size = 1024;
3062 key = rsa_key;
3063 }
3064
3065 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3066 .Authorization(TAG_NO_AUTH_REQUIRED)
3067 .SigningKey()
3068 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3069 .Digest(Digest::SHA_2_256)
3070 .Padding(PaddingMode::RSA_PSS)
3071 .SetDefaultValidity(),
3072 KeyFormat::PKCS8, key));
3073
3074 // Key size and public exponent are determined from the imported key material.
3075 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3076 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3077
3078 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3079 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3080 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3081 CheckOrigin();
3082
3083 string message(1024 / 8, 'a');
3084 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3085 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003086 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003087}
3088
3089/*
Selene Huang31ab4042020-04-29 04:22:39 -07003090 * ImportKeyTest.RsaKeySizeMismatch
3091 *
3092 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3093 * correct way.
3094 */
3095TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3096 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3097 ImportKey(AuthorizationSetBuilder()
3098 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3099 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003100 .Padding(PaddingMode::NONE)
3101 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003102 KeyFormat::PKCS8, rsa_key));
3103}
3104
3105/*
3106 * ImportKeyTest.RsaPublicExponentMismatch
3107 *
3108 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3109 * fails in the correct way.
3110 */
3111TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3112 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3113 ImportKey(AuthorizationSetBuilder()
3114 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3115 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003116 .Padding(PaddingMode::NONE)
3117 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003118 KeyFormat::PKCS8, rsa_key));
3119}
3120
3121/*
3122 * ImportKeyTest.EcdsaSuccess
3123 *
3124 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3125 */
3126TEST_P(ImportKeyTest, EcdsaSuccess) {
3127 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3128 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003129 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003130 .Digest(Digest::SHA_2_256)
3131 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003132 KeyFormat::PKCS8, ec_256_key));
3133
3134 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003135 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3136 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3137
3138 CheckOrigin();
3139
3140 string message(32, 'a');
3141 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3142 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003143 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003144}
3145
3146/*
3147 * ImportKeyTest.EcdsaP256RFC5915Success
3148 *
3149 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3150 * correctly.
3151 */
3152TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3153 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3154 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003155 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003156 .Digest(Digest::SHA_2_256)
3157 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003158 KeyFormat::PKCS8, ec_256_key_rfc5915));
3159
3160 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003161 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3162 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3163
3164 CheckOrigin();
3165
3166 string message(32, 'a');
3167 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3168 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003169 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003170}
3171
3172/*
3173 * ImportKeyTest.EcdsaP256SEC1Success
3174 *
3175 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3176 */
3177TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3178 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3179 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003180 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003181 .Digest(Digest::SHA_2_256)
3182 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003183 KeyFormat::PKCS8, ec_256_key_sec1));
3184
3185 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003186 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3187 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3188
3189 CheckOrigin();
3190
3191 string message(32, 'a');
3192 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3193 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003194 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003195}
3196
3197/*
3198 * ImportKeyTest.Ecdsa521Success
3199 *
3200 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
3201 */
3202TEST_P(ImportKeyTest, Ecdsa521Success) {
3203 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3204 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3205 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003206 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003207 .Digest(Digest::SHA_2_256)
3208 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003209 KeyFormat::PKCS8, ec_521_key));
3210
3211 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003212 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3213 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
3214 CheckOrigin();
3215
3216 string message(32, 'a');
3217 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3218 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003219 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003220}
3221
3222/*
Selene Huang31ab4042020-04-29 04:22:39 -07003223 * ImportKeyTest.EcdsaCurveMismatch
3224 *
3225 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
3226 * the correct way.
3227 */
3228TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
3229 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3230 ImportKey(AuthorizationSetBuilder()
3231 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003232 .Digest(Digest::NONE)
3233 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003234 KeyFormat::PKCS8, ec_256_key));
3235}
3236
3237/*
3238 * ImportKeyTest.AesSuccess
3239 *
3240 * Verifies that importing and using an AES key works.
3241 */
3242TEST_P(ImportKeyTest, AesSuccess) {
3243 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3244 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3245 .Authorization(TAG_NO_AUTH_REQUIRED)
3246 .AesEncryptionKey(key.size() * 8)
3247 .EcbMode()
3248 .Padding(PaddingMode::PKCS7),
3249 KeyFormat::RAW, key));
3250
3251 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
3252 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3253 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3254 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3255 CheckOrigin();
3256
3257 string message = "Hello World!";
3258 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3259 string ciphertext = EncryptMessage(message, params);
3260 string plaintext = DecryptMessage(ciphertext, params);
3261 EXPECT_EQ(message, plaintext);
3262}
3263
3264/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003265 * ImportKeyTest.AesFailure
3266 *
3267 * Verifies that importing an invalid AES key fails.
3268 */
3269TEST_P(ImportKeyTest, AesFailure) {
3270 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3271 uint32_t bitlen = key.size() * 8;
3272 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003273 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003274 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003275 .Authorization(TAG_NO_AUTH_REQUIRED)
3276 .AesEncryptionKey(key_size)
3277 .EcbMode()
3278 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003279 KeyFormat::RAW, key);
3280 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003281 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3282 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003283 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003284
3285 // Explicit key size matches that of the provided key, but it's not a valid size.
3286 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3287 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3288 ImportKey(AuthorizationSetBuilder()
3289 .Authorization(TAG_NO_AUTH_REQUIRED)
3290 .AesEncryptionKey(long_key.size() * 8)
3291 .EcbMode()
3292 .Padding(PaddingMode::PKCS7),
3293 KeyFormat::RAW, long_key));
3294 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3295 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3296 ImportKey(AuthorizationSetBuilder()
3297 .Authorization(TAG_NO_AUTH_REQUIRED)
3298 .AesEncryptionKey(short_key.size() * 8)
3299 .EcbMode()
3300 .Padding(PaddingMode::PKCS7),
3301 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003302}
3303
3304/*
3305 * ImportKeyTest.TripleDesSuccess
3306 *
3307 * Verifies that importing and using a 3DES key works.
3308 */
3309TEST_P(ImportKeyTest, TripleDesSuccess) {
3310 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
3311 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3312 .Authorization(TAG_NO_AUTH_REQUIRED)
3313 .TripleDesEncryptionKey(168)
3314 .EcbMode()
3315 .Padding(PaddingMode::PKCS7),
3316 KeyFormat::RAW, key));
3317
3318 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
3319 CheckCryptoParam(TAG_KEY_SIZE, 168U);
3320 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
3321 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
3322 CheckOrigin();
3323
3324 string message = "Hello World!";
3325 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3326 string ciphertext = EncryptMessage(message, params);
3327 string plaintext = DecryptMessage(ciphertext, params);
3328 EXPECT_EQ(message, plaintext);
3329}
3330
3331/*
3332 * ImportKeyTest.TripleDesFailure
3333 *
3334 * Verifies that importing an invalid 3DES key fails.
3335 */
3336TEST_P(ImportKeyTest, TripleDesFailure) {
3337 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01003338 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00003339 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01003340 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08003341 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06003342 .Authorization(TAG_NO_AUTH_REQUIRED)
3343 .TripleDesEncryptionKey(key_size)
3344 .EcbMode()
3345 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08003346 KeyFormat::RAW, key);
3347 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01003348 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
3349 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00003350 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01003351 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01003352 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003353 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3354 ImportKey(AuthorizationSetBuilder()
3355 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003356 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003357 .EcbMode()
3358 .Padding(PaddingMode::PKCS7),
3359 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01003360 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01003361 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
3362 ImportKey(AuthorizationSetBuilder()
3363 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01003364 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01003365 .EcbMode()
3366 .Padding(PaddingMode::PKCS7),
3367 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00003368}
3369
3370/*
3371 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07003372 *
3373 * Verifies that importing and using an HMAC key works.
3374 */
3375TEST_P(ImportKeyTest, HmacKeySuccess) {
3376 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3377 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3378 .Authorization(TAG_NO_AUTH_REQUIRED)
3379 .HmacKey(key.size() * 8)
3380 .Digest(Digest::SHA_2_256)
3381 .Authorization(TAG_MIN_MAC_LENGTH, 256),
3382 KeyFormat::RAW, key));
3383
3384 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
3385 CheckCryptoParam(TAG_KEY_SIZE, 128U);
3386 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3387 CheckOrigin();
3388
3389 string message = "Hello World!";
3390 string signature = MacMessage(message, Digest::SHA_2_256, 256);
3391 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3392}
3393
3394INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
3395
3396auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003397 // IKeyMintDevice.aidl
3398 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3399 "020100" // INTEGER length 1 value 0x00 (version)
3400 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3401 "934bf94e2aa28a3f83c9f79297250262"
3402 "fbe3276b5a1c91159bbfa3ef8957aac8"
3403 "4b59b30b455a79c2973480823d8b3863"
3404 "c3deef4a8e243590268d80e18751a0e1"
3405 "30f67ce6a1ace9f79b95e097474febc9"
3406 "81195b1d13a69086c0863f66a7b7fdb4"
3407 "8792227b1ac5e2489febdf087ab54864"
3408 "83033a6f001ca5d1ec1e27f5c30f4cec"
3409 "2642074a39ae68aee552e196627a8e3d"
3410 "867e67a8c01b11e75f13cca0a97ab668"
3411 "b50cda07a8ecb7cd8e3dd7009c963653"
3412 "4f6f239cffe1fc8daa466f78b676c711"
3413 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
3414 "99b801597d5220e307eaa5bee507fb94"
3415 "d1fa69f9e519b2de315bac92c36f2ea1"
3416 "fa1df4478c0ddedeae8c70e0233cd098"
3417 "040c" // OCTET STRING length 0x0c (initializationVector)
3418 "d796b02c370f1fa4cc0124f1"
3419 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3420 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3421 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3422 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3423 "3106" // SET length 0x06
3424 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3425 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3426 // } end SET
3427 // } end [1]
3428 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3429 "020120" // INTEGER length 1 value 0x20 (AES)
3430 // } end [2]
3431 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3432 "02020100" // INTEGER length 2 value 0x100
3433 // } end [3]
3434 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
3435 "3103" // SET length 0x03 {
3436 "020101" // INTEGER length 1 value 0x01 (ECB)
3437 // } end SET
3438 // } end [4]
3439 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3440 "3103" // SET length 0x03 {
3441 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3442 // } end SET
3443 // } end [5]
3444 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3445 // (noAuthRequired)
3446 "0500" // NULL
3447 // } end [503]
3448 // } end SEQUENCE (AuthorizationList)
3449 // } end SEQUENCE (KeyDescription)
3450 "0420" // OCTET STRING length 0x20 (encryptedKey)
3451 "ccd540855f833a5e1480bfd2d36faf3a"
3452 "eee15df5beabe2691bc82dde2a7aa910"
3453 "0410" // OCTET STRING length 0x10 (tag)
3454 "64c9f689c60ff6223ab6e6999e0eb6e5"
3455 // } SEQUENCE (SecureKeyWrapper)
3456);
Selene Huang31ab4042020-04-29 04:22:39 -07003457
3458auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003459 // IKeyMintDevice.aidl
3460 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
3461 "020100" // INTEGER length 1 value 0x00 (version)
3462 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
3463 "aad93ed5924f283b4bb5526fbe7a1412"
3464 "f9d9749ec30db9062b29e574a8546f33"
3465 "c88732452f5b8e6a391ee76c39ed1712"
3466 "c61d8df6213dec1cffbc17a8c6d04c7b"
3467 "30893d8daa9b2015213e219468215532"
3468 "07f8f9931c4caba23ed3bee28b36947e"
3469 "47f10e0a5c3dc51c988a628daad3e5e1"
3470 "f4005e79c2d5a96c284b4b8d7e4948f3"
3471 "31e5b85dd5a236f85579f3ea1d1b8484"
3472 "87470bdb0ab4f81a12bee42c99fe0df4"
3473 "bee3759453e69ad1d68a809ce06b949f"
3474 "7694a990429b2fe81e066ff43e56a216"
3475 "02db70757922a4bcc23ab89f1e35da77"
3476 "586775f423e519c2ea394caf48a28d0c"
3477 "8020f1dcf6b3a68ec246f615ae96dae9"
3478 "a079b1f6eb959033c1af5c125fd94168"
3479 "040c" // OCTET STRING length 0x0c (initializationVector)
3480 "6d9721d08589581ab49204a3"
3481 "302e" // SEQUENCE length 0x2e (KeyDescription) {
3482 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
3483 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
3484 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
3485 "3106" // SET length 0x06
3486 "020100" // INTEGER length 1 value 0x00 (Encrypt)
3487 "020101" // INTEGER length 1 value 0x01 (Decrypt)
3488 // } end SET
3489 // } end [1]
3490 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
3491 "020120" // INTEGER length 1 value 0x20 (AES)
3492 // } end [2]
3493 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
3494 "02020100" // INTEGER length 2 value 0x100
3495 // } end [3]
3496 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
3497 "3103" // SET length 0x03 {
3498 "020101" // INTEGER length 1 value 0x01 (ECB)
3499 // } end SET
3500 // } end [4]
3501 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
3502 "3103" // SET length 0x03 {
3503 "020140" // INTEGER length 1 value 0x40 (PKCS7)
3504 // } end SET
3505 // } end [5]
3506 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
3507 // (noAuthRequired)
3508 "0500" // NULL
3509 // } end [503]
3510 // } end SEQUENCE (AuthorizationList)
3511 // } end SEQUENCE (KeyDescription)
3512 "0420" // OCTET STRING length 0x20 (encryptedKey)
3513 "a61c6e247e25b3e6e69aa78eb03c2d4a"
3514 "c20d1f99a9a024a76f35c8e2cab9b68d"
3515 "0410" // OCTET STRING length 0x10 (tag)
3516 "2560c70109ae67c030f00b98b512a670"
3517 // } SEQUENCE (SecureKeyWrapper)
3518);
Selene Huang31ab4042020-04-29 04:22:39 -07003519
3520auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01003521 // RFC 5208 s5
3522 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
3523 "020100" // INTEGER length 1 value 0x00 (version)
3524 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
3525 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
3526 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
3527 "0500" // NULL (parameters)
3528 // } SEQUENCE (AlgorithmIdentifier)
3529 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
3530 // RFC 8017 A.1.2
3531 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
3532 "020100" // INTEGER length 1 value 0x00 (version)
3533 "02820101" // INTEGER length 0x0101 (modulus) value...
3534 "00aec367931d8900ce56b0067f7d70e1" // 0x10
3535 "fc653f3f34d194c1fed50018fb43db93" // 0x20
3536 "7b06e673a837313d56b1c725150a3fef" // 0x30
3537 "86acbddc41bb759c2854eae32d35841e" // 0x40
3538 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
3539 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
3540 "312d7bd5921ffaea1347c157406fef71" // 0x70
3541 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
3542 "f4645c11f5c1374c3886427411c44979" // 0x90
3543 "6792e0bef75dec858a2123c36753e02a" // 0xa0
3544 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
3545 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
3546 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
3547 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
3548 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
3549 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
3550 "55" // 0x101
3551 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
3552 "02820100" // INTEGER length 0x100 (privateExponent) value...
3553 "431447b6251908112b1ee76f99f3711a" // 0x10
3554 "52b6630960046c2de70de188d833f8b8" // 0x20
3555 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
3556 "641f7fe24f14c67a88959bdb27766df9" // 0x40
3557 "e710b630a03adc683b5d2c43080e52be" // 0x50
3558 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
3559 "822bccff087d63c940ba8a45f670feb2" // 0x70
3560 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
3561 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
3562 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
3563 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
3564 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
3565 "52659d5a5ba05b663737a8696281865b" // 0xd0
3566 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
3567 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
3568 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
3569 "028181" // INTEGER length 0x81 (prime1) value...
3570 "00de392e18d682c829266cc3454e1d61" // 0x10
3571 "66242f32d9a1d10577753e904ea7d08b" // 0x20
3572 "ff841be5bac82a164c5970007047b8c5" // 0x30
3573 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
3574 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
3575 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
3576 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
3577 "9e91346130748a6e3c124f9149d71c74" // 0x80
3578 "35"
3579 "028181" // INTEGER length 0x81 (prime2) value...
3580 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
3581 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
3582 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
3583 "7349db6c4a95affdae0dae612e1afac9" // 0x40
3584 "9ed39a2d934c880440aed8832f984316" // 0x50
3585 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
3586 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
3587 "b880677c068e1be936e81288815252a8" // 0x80
3588 "a1"
3589 "028180" // INTEGER length 0x80 (exponent1) value...
3590 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
3591 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
3592 "5a063212a4f105a3764743e53281988a" // 0x30
3593 "ba073f6e0027298e1c4378556e0efca0" // 0x40
3594 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
3595 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
3596 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
3597 "4719d6e2b9439823719cd08bcd031781" // 0x80
3598 "028181" // INTEGER length 0x81 (exponent2) value...
3599 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
3600 "1241acc607976c4ddccc90e65b6556ca" // 0x20
3601 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
3602 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
3603 "1254186af30b22c10582a8a43e34fe94" // 0x50
3604 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
3605 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
3606 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
3607 "61"
3608 "028181" // INTEGER length 0x81 (coefficient) value...
3609 "00c931617c77829dfb1270502be9195c" // 0x10
3610 "8f2830885f57dba869536811e6864236" // 0x20
3611 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
3612 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
3613 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
3614 "959356210723287b0affcc9f727044d4" // 0x60
3615 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
3616 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
3617 "22"
3618 // } SEQUENCE
3619 // } SEQUENCE ()
3620);
Selene Huang31ab4042020-04-29 04:22:39 -07003621
3622string zero_masking_key =
3623 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
3624string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
3625
3626class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
3627
3628TEST_P(ImportWrappedKeyTest, Success) {
3629 auto wrapping_key_desc = AuthorizationSetBuilder()
3630 .RsaEncryptionKey(2048, 65537)
3631 .Digest(Digest::SHA_2_256)
3632 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003633 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3634 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003635
3636 ASSERT_EQ(ErrorCode::OK,
3637 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3638 AuthorizationSetBuilder()
3639 .Digest(Digest::SHA_2_256)
3640 .Padding(PaddingMode::RSA_OAEP)));
3641
3642 string message = "Hello World!";
3643 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3644 string ciphertext = EncryptMessage(message, params);
3645 string plaintext = DecryptMessage(ciphertext, params);
3646 EXPECT_EQ(message, plaintext);
3647}
3648
David Drysdaled2cc8c22021-04-15 13:29:45 +01003649/*
3650 * ImportWrappedKeyTest.SuccessSidsIgnored
3651 *
3652 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
3653 * include Tag:USER_SECURE_ID.
3654 */
3655TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
3656 auto wrapping_key_desc = AuthorizationSetBuilder()
3657 .RsaEncryptionKey(2048, 65537)
3658 .Digest(Digest::SHA_2_256)
3659 .Padding(PaddingMode::RSA_OAEP)
3660 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3661 .SetDefaultValidity();
3662
3663 int64_t password_sid = 42;
3664 int64_t biometric_sid = 24;
3665 ASSERT_EQ(ErrorCode::OK,
3666 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3667 AuthorizationSetBuilder()
3668 .Digest(Digest::SHA_2_256)
3669 .Padding(PaddingMode::RSA_OAEP),
3670 password_sid, biometric_sid));
3671
3672 string message = "Hello World!";
3673 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
3674 string ciphertext = EncryptMessage(message, params);
3675 string plaintext = DecryptMessage(ciphertext, params);
3676 EXPECT_EQ(message, plaintext);
3677}
3678
Selene Huang31ab4042020-04-29 04:22:39 -07003679TEST_P(ImportWrappedKeyTest, SuccessMasked) {
3680 auto wrapping_key_desc = AuthorizationSetBuilder()
3681 .RsaEncryptionKey(2048, 65537)
3682 .Digest(Digest::SHA_2_256)
3683 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003684 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3685 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003686
3687 ASSERT_EQ(ErrorCode::OK,
3688 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
3689 AuthorizationSetBuilder()
3690 .Digest(Digest::SHA_2_256)
3691 .Padding(PaddingMode::RSA_OAEP)));
3692}
3693
3694TEST_P(ImportWrappedKeyTest, WrongMask) {
3695 auto wrapping_key_desc = AuthorizationSetBuilder()
3696 .RsaEncryptionKey(2048, 65537)
3697 .Digest(Digest::SHA_2_256)
3698 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003699 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3700 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003701
3702 ASSERT_EQ(
3703 ErrorCode::VERIFICATION_FAILED,
3704 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3705 AuthorizationSetBuilder()
3706 .Digest(Digest::SHA_2_256)
3707 .Padding(PaddingMode::RSA_OAEP)));
3708}
3709
3710TEST_P(ImportWrappedKeyTest, WrongPurpose) {
3711 auto wrapping_key_desc = AuthorizationSetBuilder()
3712 .RsaEncryptionKey(2048, 65537)
3713 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003714 .Padding(PaddingMode::RSA_OAEP)
3715 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07003716
3717 ASSERT_EQ(
3718 ErrorCode::INCOMPATIBLE_PURPOSE,
3719 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
3720 AuthorizationSetBuilder()
3721 .Digest(Digest::SHA_2_256)
3722 .Padding(PaddingMode::RSA_OAEP)));
3723}
3724
David Drysdaled2cc8c22021-04-15 13:29:45 +01003725TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
3726 auto wrapping_key_desc = AuthorizationSetBuilder()
3727 .RsaEncryptionKey(2048, 65537)
3728 .Digest(Digest::SHA_2_256)
3729 .Padding(PaddingMode::RSA_PSS)
3730 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3731 .SetDefaultValidity();
3732
3733 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
3734 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3735 AuthorizationSetBuilder()
3736 .Digest(Digest::SHA_2_256)
3737 .Padding(PaddingMode::RSA_OAEP)));
3738}
3739
3740TEST_P(ImportWrappedKeyTest, WrongDigest) {
3741 auto wrapping_key_desc = AuthorizationSetBuilder()
3742 .RsaEncryptionKey(2048, 65537)
3743 .Digest(Digest::SHA_2_512)
3744 .Padding(PaddingMode::RSA_OAEP)
3745 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
3746 .SetDefaultValidity();
3747
3748 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3749 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
3750 AuthorizationSetBuilder()
3751 .Digest(Digest::SHA_2_256)
3752 .Padding(PaddingMode::RSA_OAEP)));
3753}
3754
Selene Huang31ab4042020-04-29 04:22:39 -07003755INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
3756
3757typedef KeyMintAidlTestBase EncryptionOperationsTest;
3758
3759/*
3760 * EncryptionOperationsTest.RsaNoPaddingSuccess
3761 *
David Drysdale59cae642021-05-12 13:52:03 +01003762 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07003763 */
3764TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01003765 for (uint64_t exponent : {3, 65537}) {
3766 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3767 .Authorization(TAG_NO_AUTH_REQUIRED)
3768 .RsaEncryptionKey(2048, exponent)
3769 .Padding(PaddingMode::NONE)
3770 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003771
David Drysdaled2cc8c22021-04-15 13:29:45 +01003772 string message = string(2048 / 8, 'a');
3773 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003774 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003775 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003776
David Drysdale59cae642021-05-12 13:52:03 +01003777 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003778 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07003779
David Drysdaled2cc8c22021-04-15 13:29:45 +01003780 // Unpadded RSA is deterministic
3781 EXPECT_EQ(ciphertext1, ciphertext2);
3782
3783 CheckedDeleteKey();
3784 }
Selene Huang31ab4042020-04-29 04:22:39 -07003785}
3786
3787/*
3788 * EncryptionOperationsTest.RsaNoPaddingShortMessage
3789 *
David Drysdale59cae642021-05-12 13:52:03 +01003790 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07003791 */
3792TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
3793 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3794 .Authorization(TAG_NO_AUTH_REQUIRED)
3795 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003796 .Padding(PaddingMode::NONE)
3797 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003798
3799 string message = "1";
3800 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
3801
David Drysdale59cae642021-05-12 13:52:03 +01003802 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003803 EXPECT_EQ(2048U / 8, ciphertext.size());
3804
3805 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
3806 string plaintext = DecryptMessage(ciphertext, params);
3807
3808 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07003809}
3810
3811/*
Selene Huang31ab4042020-04-29 04:22:39 -07003812 * EncryptionOperationsTest.RsaOaepSuccess
3813 *
David Drysdale59cae642021-05-12 13:52:03 +01003814 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07003815 */
3816TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
3817 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3818
3819 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01003820 ASSERT_EQ(ErrorCode::OK,
3821 GenerateKey(AuthorizationSetBuilder()
3822 .Authorization(TAG_NO_AUTH_REQUIRED)
3823 .RsaEncryptionKey(key_size, 65537)
3824 .Padding(PaddingMode::RSA_OAEP)
3825 .Digest(digests)
3826 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
3827 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003828
3829 string message = "Hello";
3830
3831 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01003832 SCOPED_TRACE(testing::Message() << "digest-" << digest);
3833
3834 auto params = AuthorizationSetBuilder()
3835 .Digest(digest)
3836 .Padding(PaddingMode::RSA_OAEP)
3837 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
3838 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003839 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3840 EXPECT_EQ(key_size / 8, ciphertext1.size());
3841
David Drysdale59cae642021-05-12 13:52:03 +01003842 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003843 EXPECT_EQ(key_size / 8, ciphertext2.size());
3844
3845 // OAEP randomizes padding so every result should be different (with astronomically high
3846 // probability).
3847 EXPECT_NE(ciphertext1, ciphertext2);
3848
3849 string plaintext1 = DecryptMessage(ciphertext1, params);
3850 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3851 string plaintext2 = DecryptMessage(ciphertext2, params);
3852 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3853
3854 // Decrypting corrupted ciphertext should fail.
3855 size_t offset_to_corrupt = random() % ciphertext1.size();
3856 char corrupt_byte;
3857 do {
3858 corrupt_byte = static_cast<char>(random() % 256);
3859 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3860 ciphertext1[offset_to_corrupt] = corrupt_byte;
3861
3862 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3863 string result;
3864 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3865 EXPECT_EQ(0U, result.size());
3866 }
3867}
3868
3869/*
3870 * EncryptionOperationsTest.RsaOaepInvalidDigest
3871 *
David Drysdale59cae642021-05-12 13:52:03 +01003872 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07003873 * without a digest.
3874 */
3875TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
3876 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3877 .Authorization(TAG_NO_AUTH_REQUIRED)
3878 .RsaEncryptionKey(2048, 65537)
3879 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003880 .Digest(Digest::NONE)
3881 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003882
3883 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003884 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07003885}
3886
3887/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003888 * EncryptionOperationsTest.RsaOaepInvalidPadding
3889 *
David Drysdale59cae642021-05-12 13:52:03 +01003890 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01003891 * with a padding value that is only suitable for signing/verifying.
3892 */
3893TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
3894 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3895 .Authorization(TAG_NO_AUTH_REQUIRED)
3896 .RsaEncryptionKey(2048, 65537)
3897 .Padding(PaddingMode::RSA_PSS)
3898 .Digest(Digest::NONE)
3899 .SetDefaultValidity()));
3900
3901 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01003902 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003903}
3904
3905/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003906 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07003907 *
David Drysdale59cae642021-05-12 13:52:03 +01003908 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07003909 * with a different digest than was used to encrypt.
3910 */
3911TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
3912 if (SecLevel() == SecurityLevel::STRONGBOX) return;
3913
3914 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3915 .Authorization(TAG_NO_AUTH_REQUIRED)
3916 .RsaEncryptionKey(1024, 65537)
3917 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003918 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
3919 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003920 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01003921 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07003922 message,
3923 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
3924
3925 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
3926 .Digest(Digest::SHA_2_256)
3927 .Padding(PaddingMode::RSA_OAEP)));
3928 string result;
3929 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
3930 EXPECT_EQ(0U, result.size());
3931}
3932
3933/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003934 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
3935 *
David Drysdale59cae642021-05-12 13:52:03 +01003936 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003937 * digests.
3938 */
3939TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
3940 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
3941
3942 size_t key_size = 2048; // Need largish key for SHA-512 test.
3943 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3944 .OaepMGFDigest(digests)
3945 .Authorization(TAG_NO_AUTH_REQUIRED)
3946 .RsaEncryptionKey(key_size, 65537)
3947 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003948 .Digest(Digest::SHA_2_256)
3949 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003950
3951 string message = "Hello";
3952
3953 for (auto digest : digests) {
3954 auto params = AuthorizationSetBuilder()
3955 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
3956 .Digest(Digest::SHA_2_256)
3957 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01003958 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003959 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
3960 EXPECT_EQ(key_size / 8, ciphertext1.size());
3961
David Drysdale59cae642021-05-12 13:52:03 +01003962 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003963 EXPECT_EQ(key_size / 8, ciphertext2.size());
3964
3965 // OAEP randomizes padding so every result should be different (with astronomically high
3966 // probability).
3967 EXPECT_NE(ciphertext1, ciphertext2);
3968
3969 string plaintext1 = DecryptMessage(ciphertext1, params);
3970 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
3971 string plaintext2 = DecryptMessage(ciphertext2, params);
3972 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
3973
3974 // Decrypting corrupted ciphertext should fail.
3975 size_t offset_to_corrupt = random() % ciphertext1.size();
3976 char corrupt_byte;
3977 do {
3978 corrupt_byte = static_cast<char>(random() % 256);
3979 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
3980 ciphertext1[offset_to_corrupt] = corrupt_byte;
3981
3982 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
3983 string result;
3984 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
3985 EXPECT_EQ(0U, result.size());
3986 }
3987}
3988
3989/*
3990 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
3991 *
David Drysdale59cae642021-05-12 13:52:03 +01003992 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05003993 * with incompatible MGF digest.
3994 */
3995TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
3996 ASSERT_EQ(ErrorCode::OK,
3997 GenerateKey(AuthorizationSetBuilder()
3998 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
3999 .Authorization(TAG_NO_AUTH_REQUIRED)
4000 .RsaEncryptionKey(2048, 65537)
4001 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004002 .Digest(Digest::SHA_2_256)
4003 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004004 string message = "Hello World!";
4005
4006 auto params = AuthorizationSetBuilder()
4007 .Padding(PaddingMode::RSA_OAEP)
4008 .Digest(Digest::SHA_2_256)
4009 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01004010 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004011}
4012
4013/*
4014 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
4015 *
4016 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
4017 * with unsupported MGF digest.
4018 */
4019TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
4020 ASSERT_EQ(ErrorCode::OK,
4021 GenerateKey(AuthorizationSetBuilder()
4022 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
4023 .Authorization(TAG_NO_AUTH_REQUIRED)
4024 .RsaEncryptionKey(2048, 65537)
4025 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004026 .Digest(Digest::SHA_2_256)
4027 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004028 string message = "Hello World!";
4029
4030 auto params = AuthorizationSetBuilder()
4031 .Padding(PaddingMode::RSA_OAEP)
4032 .Digest(Digest::SHA_2_256)
4033 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004034 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05004035}
4036
4037/*
Selene Huang31ab4042020-04-29 04:22:39 -07004038 * EncryptionOperationsTest.RsaPkcs1Success
4039 *
4040 * Verifies that RSA PKCS encryption/decrypts works.
4041 */
4042TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
4043 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4044 .Authorization(TAG_NO_AUTH_REQUIRED)
4045 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004046 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
4047 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004048
4049 string message = "Hello World!";
4050 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01004051 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004052 EXPECT_EQ(2048U / 8, ciphertext1.size());
4053
David Drysdale59cae642021-05-12 13:52:03 +01004054 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004055 EXPECT_EQ(2048U / 8, ciphertext2.size());
4056
4057 // PKCS1 v1.5 randomizes padding so every result should be different.
4058 EXPECT_NE(ciphertext1, ciphertext2);
4059
4060 string plaintext = DecryptMessage(ciphertext1, params);
4061 EXPECT_EQ(message, plaintext);
4062
4063 // Decrypting corrupted ciphertext should fail.
4064 size_t offset_to_corrupt = random() % ciphertext1.size();
4065 char corrupt_byte;
4066 do {
4067 corrupt_byte = static_cast<char>(random() % 256);
4068 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4069 ciphertext1[offset_to_corrupt] = corrupt_byte;
4070
4071 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4072 string result;
4073 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4074 EXPECT_EQ(0U, result.size());
4075}
4076
4077/*
Selene Huang31ab4042020-04-29 04:22:39 -07004078 * EncryptionOperationsTest.EcdsaEncrypt
4079 *
4080 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
4081 */
4082TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
4083 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4084 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004085 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004086 .Digest(Digest::NONE)
4087 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004088 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4089 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4090 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4091}
4092
4093/*
4094 * EncryptionOperationsTest.HmacEncrypt
4095 *
4096 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
4097 */
4098TEST_P(EncryptionOperationsTest, HmacEncrypt) {
4099 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4100 .Authorization(TAG_NO_AUTH_REQUIRED)
4101 .HmacKey(128)
4102 .Digest(Digest::SHA_2_256)
4103 .Padding(PaddingMode::NONE)
4104 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4105 auto params = AuthorizationSetBuilder()
4106 .Digest(Digest::SHA_2_256)
4107 .Padding(PaddingMode::NONE)
4108 .Authorization(TAG_MAC_LENGTH, 128);
4109 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
4110 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
4111}
4112
4113/*
4114 * EncryptionOperationsTest.AesEcbRoundTripSuccess
4115 *
4116 * Verifies that AES ECB mode works.
4117 */
4118TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
4119 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4120 .Authorization(TAG_NO_AUTH_REQUIRED)
4121 .AesEncryptionKey(128)
4122 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4123 .Padding(PaddingMode::NONE)));
4124
4125 ASSERT_GT(key_blob_.size(), 0U);
4126 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4127
4128 // Two-block message.
4129 string message = "12345678901234567890123456789012";
4130 string ciphertext1 = EncryptMessage(message, params);
4131 EXPECT_EQ(message.size(), ciphertext1.size());
4132
4133 string ciphertext2 = EncryptMessage(string(message), params);
4134 EXPECT_EQ(message.size(), ciphertext2.size());
4135
4136 // ECB is deterministic.
4137 EXPECT_EQ(ciphertext1, ciphertext2);
4138
4139 string plaintext = DecryptMessage(ciphertext1, params);
4140 EXPECT_EQ(message, plaintext);
4141}
4142
4143/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004144 * EncryptionOperationsTest.AesEcbUnknownTag
4145 *
4146 * Verifies that AES ECB operations ignore unknown tags.
4147 */
4148TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
4149 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
4150 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
4151 KeyParameter unknown_param;
4152 unknown_param.tag = unknown_tag;
4153
4154 vector<KeyCharacteristics> key_characteristics;
4155 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4156 .Authorization(TAG_NO_AUTH_REQUIRED)
4157 .AesEncryptionKey(128)
4158 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4159 .Padding(PaddingMode::NONE)
4160 .Authorization(unknown_param),
4161 &key_blob_, &key_characteristics));
4162 ASSERT_GT(key_blob_.size(), 0U);
4163
4164 // Unknown tags should not be returned in key characteristics.
4165 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
4166 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
4167 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
4168 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
4169
4170 // Encrypt without mentioning the unknown parameter.
4171 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
4172 string message = "12345678901234567890123456789012";
4173 string ciphertext = EncryptMessage(message, params);
4174 EXPECT_EQ(message.size(), ciphertext.size());
4175
4176 // Decrypt including the unknown parameter.
4177 auto decrypt_params = AuthorizationSetBuilder()
4178 .BlockMode(BlockMode::ECB)
4179 .Padding(PaddingMode::NONE)
4180 .Authorization(unknown_param);
4181 string plaintext = DecryptMessage(ciphertext, decrypt_params);
4182 EXPECT_EQ(message, plaintext);
4183}
4184
4185/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004186 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07004187 *
4188 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
4189 */
4190TEST_P(EncryptionOperationsTest, AesWrongMode) {
4191 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4192 .Authorization(TAG_NO_AUTH_REQUIRED)
4193 .AesEncryptionKey(128)
4194 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4195 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07004196 ASSERT_GT(key_blob_.size(), 0U);
4197
Selene Huang31ab4042020-04-29 04:22:39 -07004198 EXPECT_EQ(
4199 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
4200 Begin(KeyPurpose::ENCRYPT,
4201 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
4202}
4203
4204/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004205 * EncryptionOperationsTest.AesWrongPadding
4206 *
4207 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
4208 */
4209TEST_P(EncryptionOperationsTest, AesWrongPadding) {
4210 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4211 .Authorization(TAG_NO_AUTH_REQUIRED)
4212 .AesEncryptionKey(128)
4213 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4214 .Padding(PaddingMode::NONE)));
4215 ASSERT_GT(key_blob_.size(), 0U);
4216
4217 EXPECT_EQ(
4218 ErrorCode::INCOMPATIBLE_PADDING_MODE,
4219 Begin(KeyPurpose::ENCRYPT,
4220 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
4221}
4222
4223/*
4224 * EncryptionOperationsTest.AesInvalidParams
4225 *
4226 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
4227 */
4228TEST_P(EncryptionOperationsTest, AesInvalidParams) {
4229 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4230 .Authorization(TAG_NO_AUTH_REQUIRED)
4231 .AesEncryptionKey(128)
4232 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4233 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4234 .Padding(PaddingMode::NONE)
4235 .Padding(PaddingMode::PKCS7)));
4236 ASSERT_GT(key_blob_.size(), 0U);
4237
4238 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4239 .BlockMode(BlockMode::CBC)
4240 .BlockMode(BlockMode::ECB)
4241 .Padding(PaddingMode::NONE));
4242 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
4243 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
4244
4245 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4246 .BlockMode(BlockMode::ECB)
4247 .Padding(PaddingMode::NONE)
4248 .Padding(PaddingMode::PKCS7));
4249 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
4250 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
4251}
4252
4253/*
Selene Huang31ab4042020-04-29 04:22:39 -07004254 * EncryptionOperationsTest.AesWrongPurpose
4255 *
4256 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
4257 * specified.
4258 */
4259TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
4260 auto err = GenerateKey(AuthorizationSetBuilder()
4261 .Authorization(TAG_NO_AUTH_REQUIRED)
4262 .AesKey(128)
4263 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
4264 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4265 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4266 .Padding(PaddingMode::NONE));
4267 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
4268 ASSERT_GT(key_blob_.size(), 0U);
4269
4270 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
4271 .BlockMode(BlockMode::GCM)
4272 .Padding(PaddingMode::NONE)
4273 .Authorization(TAG_MAC_LENGTH, 128));
4274 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4275
4276 CheckedDeleteKey();
4277
4278 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4279 .Authorization(TAG_NO_AUTH_REQUIRED)
4280 .AesKey(128)
4281 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
4282 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4283 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4284 .Padding(PaddingMode::NONE)));
4285
4286 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
4287 .BlockMode(BlockMode::GCM)
4288 .Padding(PaddingMode::NONE)
4289 .Authorization(TAG_MAC_LENGTH, 128));
4290 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
4291}
4292
4293/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004294 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07004295 *
4296 * Verifies that AES encryption fails in the correct way when provided an input that is not a
4297 * multiple of the block size and no padding is specified.
4298 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01004299TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
4300 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
4301 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4302 .Authorization(TAG_NO_AUTH_REQUIRED)
4303 .AesEncryptionKey(128)
4304 .Authorization(TAG_BLOCK_MODE, blockMode)
4305 .Padding(PaddingMode::NONE)));
4306 // Message is slightly shorter than two blocks.
4307 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07004308
David Drysdaled2cc8c22021-04-15 13:29:45 +01004309 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
4310 AuthorizationSet out_params;
4311 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4312 string ciphertext;
4313 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
4314 EXPECT_EQ(0U, ciphertext.size());
4315
4316 CheckedDeleteKey();
4317 }
Selene Huang31ab4042020-04-29 04:22:39 -07004318}
4319
4320/*
4321 * EncryptionOperationsTest.AesEcbPkcs7Padding
4322 *
4323 * Verifies that AES PKCS7 padding works for any message length.
4324 */
4325TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
4326 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4327 .Authorization(TAG_NO_AUTH_REQUIRED)
4328 .AesEncryptionKey(128)
4329 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4330 .Padding(PaddingMode::PKCS7)));
4331
4332 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4333
4334 // Try various message lengths; all should work.
4335 for (size_t i = 0; i < 32; ++i) {
4336 string message(i, 'a');
4337 string ciphertext = EncryptMessage(message, params);
4338 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
4339 string plaintext = DecryptMessage(ciphertext, params);
4340 EXPECT_EQ(message, plaintext);
4341 }
4342}
4343
4344/*
4345 * EncryptionOperationsTest.AesEcbWrongPadding
4346 *
4347 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
4348 * specified.
4349 */
4350TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
4351 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4352 .Authorization(TAG_NO_AUTH_REQUIRED)
4353 .AesEncryptionKey(128)
4354 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4355 .Padding(PaddingMode::NONE)));
4356
4357 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4358
4359 // Try various message lengths; all should fail
4360 for (size_t i = 0; i < 32; ++i) {
4361 string message(i, 'a');
4362 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4363 }
4364}
4365
4366/*
4367 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
4368 *
4369 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
4370 */
4371TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
4372 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4373 .Authorization(TAG_NO_AUTH_REQUIRED)
4374 .AesEncryptionKey(128)
4375 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
4376 .Padding(PaddingMode::PKCS7)));
4377
4378 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4379
4380 string message = "a";
4381 string ciphertext = EncryptMessage(message, params);
4382 EXPECT_EQ(16U, ciphertext.size());
4383 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07004384
Seth Moore7a55ae32021-06-23 14:28:11 -07004385 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
4386 ++ciphertext[ciphertext.size() / 2];
4387
4388 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4389 string plaintext;
4390 ErrorCode error = Finish(message, &plaintext);
4391 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
4392 // This is the expected error, we can exit the test now.
4393 return;
4394 } else {
4395 // Very small chance we got valid decryption, so try again.
4396 ASSERT_EQ(error, ErrorCode::OK);
4397 }
4398 }
4399 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07004400}
4401
4402vector<uint8_t> CopyIv(const AuthorizationSet& set) {
4403 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004404 EXPECT_TRUE(iv);
4405 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07004406}
4407
4408/*
4409 * EncryptionOperationsTest.AesCtrRoundTripSuccess
4410 *
4411 * Verifies that AES CTR mode works.
4412 */
4413TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
4414 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4415 .Authorization(TAG_NO_AUTH_REQUIRED)
4416 .AesEncryptionKey(128)
4417 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4418 .Padding(PaddingMode::NONE)));
4419
4420 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4421
4422 string message = "123";
4423 AuthorizationSet out_params;
4424 string ciphertext1 = EncryptMessage(message, params, &out_params);
4425 vector<uint8_t> iv1 = CopyIv(out_params);
4426 EXPECT_EQ(16U, iv1.size());
4427
4428 EXPECT_EQ(message.size(), ciphertext1.size());
4429
4430 out_params.Clear();
4431 string ciphertext2 = EncryptMessage(message, params, &out_params);
4432 vector<uint8_t> iv2 = CopyIv(out_params);
4433 EXPECT_EQ(16U, iv2.size());
4434
4435 // IVs should be random, so ciphertexts should differ.
4436 EXPECT_NE(ciphertext1, ciphertext2);
4437
4438 auto params_iv1 =
4439 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
4440 auto params_iv2 =
4441 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
4442
4443 string plaintext = DecryptMessage(ciphertext1, params_iv1);
4444 EXPECT_EQ(message, plaintext);
4445 plaintext = DecryptMessage(ciphertext2, params_iv2);
4446 EXPECT_EQ(message, plaintext);
4447
4448 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
4449 plaintext = DecryptMessage(ciphertext1, params_iv2);
4450 EXPECT_NE(message, plaintext);
4451 plaintext = DecryptMessage(ciphertext2, params_iv1);
4452 EXPECT_NE(message, plaintext);
4453}
4454
4455/*
4456 * EncryptionOperationsTest.AesIncremental
4457 *
4458 * Verifies that AES works, all modes, when provided data in various size increments.
4459 */
4460TEST_P(EncryptionOperationsTest, AesIncremental) {
4461 auto block_modes = {
4462 BlockMode::ECB,
4463 BlockMode::CBC,
4464 BlockMode::CTR,
4465 BlockMode::GCM,
4466 };
4467
4468 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4469 .Authorization(TAG_NO_AUTH_REQUIRED)
4470 .AesEncryptionKey(128)
4471 .BlockMode(block_modes)
4472 .Padding(PaddingMode::NONE)
4473 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4474
4475 for (int increment = 1; increment <= 240; ++increment) {
4476 for (auto block_mode : block_modes) {
4477 string message(240, 'a');
Shawn Willden92d79c02021-02-19 07:31:55 -07004478 auto params =
4479 AuthorizationSetBuilder().BlockMode(block_mode).Padding(PaddingMode::NONE);
4480 if (block_mode == BlockMode::GCM) {
4481 params.Authorization(TAG_MAC_LENGTH, 128) /* for GCM */;
4482 }
Selene Huang31ab4042020-04-29 04:22:39 -07004483
4484 AuthorizationSet output_params;
4485 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &output_params));
4486
4487 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07004488 string to_send;
4489 for (size_t i = 0; i < message.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004490 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004491 }
Shawn Willden92d79c02021-02-19 07:31:55 -07004492 EXPECT_EQ(ErrorCode::OK, Finish(to_send, &ciphertext))
4493 << "Error sending " << to_send << " with block mode " << block_mode;
Selene Huang31ab4042020-04-29 04:22:39 -07004494
4495 switch (block_mode) {
4496 case BlockMode::GCM:
4497 EXPECT_EQ(message.size() + 16, ciphertext.size());
4498 break;
4499 case BlockMode::CTR:
4500 EXPECT_EQ(message.size(), ciphertext.size());
4501 break;
4502 case BlockMode::CBC:
4503 case BlockMode::ECB:
4504 EXPECT_EQ(message.size() + message.size() % 16, ciphertext.size());
4505 break;
4506 }
4507
4508 auto iv = output_params.GetTagValue(TAG_NONCE);
4509 switch (block_mode) {
4510 case BlockMode::CBC:
4511 case BlockMode::GCM:
4512 case BlockMode::CTR:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004513 ASSERT_TRUE(iv) << "No IV for block mode " << block_mode;
4514 EXPECT_EQ(block_mode == BlockMode::GCM ? 12U : 16U, iv->get().size());
4515 params.push_back(TAG_NONCE, iv->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004516 break;
4517
4518 case BlockMode::ECB:
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004519 EXPECT_FALSE(iv) << "ECB mode should not generate IV";
Selene Huang31ab4042020-04-29 04:22:39 -07004520 break;
4521 }
4522
4523 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params))
4524 << "Decrypt begin() failed for block mode " << block_mode;
4525
4526 string plaintext;
4527 for (size_t i = 0; i < ciphertext.size(); i += increment) {
Shawn Willden92d79c02021-02-19 07:31:55 -07004528 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004529 }
4530 ErrorCode error = Finish(to_send, &plaintext);
4531 ASSERT_EQ(ErrorCode::OK, error) << "Decryption failed for block mode " << block_mode
4532 << " and increment " << increment;
4533 if (error == ErrorCode::OK) {
4534 ASSERT_EQ(message, plaintext) << "Decryption didn't match for block mode "
4535 << block_mode << " and increment " << increment;
4536 }
4537 }
4538 }
4539}
4540
4541struct AesCtrSp80038aTestVector {
4542 const char* key;
4543 const char* nonce;
4544 const char* plaintext;
4545 const char* ciphertext;
4546};
4547
4548// These test vectors are taken from
4549// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
4550static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
4551 // AES-128
4552 {
4553 "2b7e151628aed2a6abf7158809cf4f3c",
4554 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4555 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4556 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4557 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
4558 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
4559 },
4560 // AES-192
4561 {
4562 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
4563 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4564 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4565 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4566 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
4567 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
4568 },
4569 // AES-256
4570 {
4571 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
4572 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
4573 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
4574 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
4575 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
4576 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
4577 },
4578};
4579
4580/*
4581 * EncryptionOperationsTest.AesCtrSp80038aTestVector
4582 *
4583 * Verifies AES CTR implementation against SP800-38A test vectors.
4584 */
4585TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
4586 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
4587 for (size_t i = 0; i < 3; i++) {
4588 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
4589 const string key = hex2str(test.key);
4590 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
4591 InvalidSizes.end())
4592 continue;
4593 const string nonce = hex2str(test.nonce);
4594 const string plaintext = hex2str(test.plaintext);
4595 const string ciphertext = hex2str(test.ciphertext);
4596 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
4597 }
4598}
4599
4600/*
4601 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
4602 *
4603 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
4604 */
4605TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
4606 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4607 .Authorization(TAG_NO_AUTH_REQUIRED)
4608 .AesEncryptionKey(128)
4609 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4610 .Padding(PaddingMode::PKCS7)));
4611 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
4612 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
4613}
4614
4615/*
4616 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
4617 *
4618 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4619 */
4620TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
4621 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4622 .Authorization(TAG_NO_AUTH_REQUIRED)
4623 .AesEncryptionKey(128)
4624 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
4625 .Authorization(TAG_CALLER_NONCE)
4626 .Padding(PaddingMode::NONE)));
4627
4628 auto params = AuthorizationSetBuilder()
4629 .BlockMode(BlockMode::CTR)
4630 .Padding(PaddingMode::NONE)
4631 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
4632 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4633
4634 params = AuthorizationSetBuilder()
4635 .BlockMode(BlockMode::CTR)
4636 .Padding(PaddingMode::NONE)
4637 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
4638 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4639
4640 params = AuthorizationSetBuilder()
4641 .BlockMode(BlockMode::CTR)
4642 .Padding(PaddingMode::NONE)
4643 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
4644 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
4645}
4646
4647/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004648 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004649 *
4650 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
4651 */
4652TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
4653 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4654 .Authorization(TAG_NO_AUTH_REQUIRED)
4655 .AesEncryptionKey(128)
4656 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4657 .Padding(PaddingMode::NONE)));
4658 // Two-block message.
4659 string message = "12345678901234567890123456789012";
4660 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4661 AuthorizationSet out_params;
4662 string ciphertext1 = EncryptMessage(message, params, &out_params);
4663 vector<uint8_t> iv1 = CopyIv(out_params);
4664 EXPECT_EQ(message.size(), ciphertext1.size());
4665
4666 out_params.Clear();
4667
4668 string ciphertext2 = EncryptMessage(message, params, &out_params);
4669 vector<uint8_t> iv2 = CopyIv(out_params);
4670 EXPECT_EQ(message.size(), ciphertext2.size());
4671
4672 // IVs should be random, so ciphertexts should differ.
4673 EXPECT_NE(ciphertext1, ciphertext2);
4674
4675 params.push_back(TAG_NONCE, iv1);
4676 string plaintext = DecryptMessage(ciphertext1, params);
4677 EXPECT_EQ(message, plaintext);
4678}
4679
4680/*
4681 * EncryptionOperationsTest.AesCallerNonce
4682 *
4683 * Verifies that AES caller-provided nonces work correctly.
4684 */
4685TEST_P(EncryptionOperationsTest, AesCallerNonce) {
4686 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4687 .Authorization(TAG_NO_AUTH_REQUIRED)
4688 .AesEncryptionKey(128)
4689 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4690 .Authorization(TAG_CALLER_NONCE)
4691 .Padding(PaddingMode::NONE)));
4692
4693 string message = "12345678901234567890123456789012";
4694
4695 // Don't specify nonce, should get a random one.
4696 AuthorizationSetBuilder params =
4697 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4698 AuthorizationSet out_params;
4699 string ciphertext = EncryptMessage(message, params, &out_params);
4700 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004701 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004702
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004703 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004704 string plaintext = DecryptMessage(ciphertext, params);
4705 EXPECT_EQ(message, plaintext);
4706
4707 // Now specify a nonce, should also work.
4708 params = AuthorizationSetBuilder()
4709 .BlockMode(BlockMode::CBC)
4710 .Padding(PaddingMode::NONE)
4711 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4712 out_params.Clear();
4713 ciphertext = EncryptMessage(message, params, &out_params);
4714
4715 // Decrypt with correct nonce.
4716 plaintext = DecryptMessage(ciphertext, params);
4717 EXPECT_EQ(message, plaintext);
4718
4719 // Try with wrong nonce.
4720 params = AuthorizationSetBuilder()
4721 .BlockMode(BlockMode::CBC)
4722 .Padding(PaddingMode::NONE)
4723 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
4724 plaintext = DecryptMessage(ciphertext, params);
4725 EXPECT_NE(message, plaintext);
4726}
4727
4728/*
4729 * EncryptionOperationsTest.AesCallerNonceProhibited
4730 *
4731 * Verifies that caller-provided nonces are not permitted when not specified in the key
4732 * authorizations.
4733 */
4734TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
4735 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4736 .Authorization(TAG_NO_AUTH_REQUIRED)
4737 .AesEncryptionKey(128)
4738 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
4739 .Padding(PaddingMode::NONE)));
4740
4741 string message = "12345678901234567890123456789012";
4742
4743 // Don't specify nonce, should get a random one.
4744 AuthorizationSetBuilder params =
4745 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
4746 AuthorizationSet out_params;
4747 string ciphertext = EncryptMessage(message, params, &out_params);
4748 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004749 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07004750
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004751 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07004752 string plaintext = DecryptMessage(ciphertext, params);
4753 EXPECT_EQ(message, plaintext);
4754
4755 // Now specify a nonce, should fail
4756 params = AuthorizationSetBuilder()
4757 .BlockMode(BlockMode::CBC)
4758 .Padding(PaddingMode::NONE)
4759 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
4760 out_params.Clear();
4761 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
4762}
4763
4764/*
4765 * EncryptionOperationsTest.AesGcmRoundTripSuccess
4766 *
4767 * Verifies that AES GCM mode works.
4768 */
4769TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
4770 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4771 .Authorization(TAG_NO_AUTH_REQUIRED)
4772 .AesEncryptionKey(128)
4773 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4774 .Padding(PaddingMode::NONE)
4775 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4776
4777 string aad = "foobar";
4778 string message = "123456789012345678901234567890123456";
4779
4780 auto begin_params = AuthorizationSetBuilder()
4781 .BlockMode(BlockMode::GCM)
4782 .Padding(PaddingMode::NONE)
4783 .Authorization(TAG_MAC_LENGTH, 128);
4784
Selene Huang31ab4042020-04-29 04:22:39 -07004785 // Encrypt
4786 AuthorizationSet begin_out_params;
4787 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4788 << "Begin encrypt";
4789 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004790 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4791 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004792 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4793
4794 // Grab nonce
4795 begin_params.push_back(begin_out_params);
4796
4797 // Decrypt.
4798 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07004799 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004800 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004801 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004802 EXPECT_EQ(message.length(), plaintext.length());
4803 EXPECT_EQ(message, plaintext);
4804}
4805
4806/*
4807 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
4808 *
4809 * Verifies that AES GCM mode works, even when there's a long delay
4810 * between operations.
4811 */
4812TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
4813 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4814 .Authorization(TAG_NO_AUTH_REQUIRED)
4815 .AesEncryptionKey(128)
4816 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4817 .Padding(PaddingMode::NONE)
4818 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4819
4820 string aad = "foobar";
4821 string message = "123456789012345678901234567890123456";
4822
4823 auto begin_params = AuthorizationSetBuilder()
4824 .BlockMode(BlockMode::GCM)
4825 .Padding(PaddingMode::NONE)
4826 .Authorization(TAG_MAC_LENGTH, 128);
4827
Selene Huang31ab4042020-04-29 04:22:39 -07004828 // Encrypt
4829 AuthorizationSet begin_out_params;
4830 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
4831 << "Begin encrypt";
4832 string ciphertext;
4833 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07004834 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004835 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004836 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004837
4838 ASSERT_EQ(ciphertext.length(), message.length() + 16);
4839
4840 // Grab nonce
4841 begin_params.push_back(begin_out_params);
4842
4843 // Decrypt.
4844 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
4845 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004846 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07004847 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07004848 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07004849 sleep(5);
4850 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
4851 EXPECT_EQ(message.length(), plaintext.length());
4852 EXPECT_EQ(message, plaintext);
4853}
4854
4855/*
4856 * EncryptionOperationsTest.AesGcmDifferentNonces
4857 *
4858 * Verifies that encrypting the same data with different nonces produces different outputs.
4859 */
4860TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
4861 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4862 .Authorization(TAG_NO_AUTH_REQUIRED)
4863 .AesEncryptionKey(128)
4864 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4865 .Padding(PaddingMode::NONE)
4866 .Authorization(TAG_MIN_MAC_LENGTH, 128)
4867 .Authorization(TAG_CALLER_NONCE)));
4868
4869 string aad = "foobar";
4870 string message = "123456789012345678901234567890123456";
4871 string nonce1 = "000000000000";
4872 string nonce2 = "111111111111";
4873 string nonce3 = "222222222222";
4874
4875 string ciphertext1 =
4876 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
4877 string ciphertext2 =
4878 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
4879 string ciphertext3 =
4880 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
4881
4882 ASSERT_NE(ciphertext1, ciphertext2);
4883 ASSERT_NE(ciphertext1, ciphertext3);
4884 ASSERT_NE(ciphertext2, ciphertext3);
4885}
4886
4887/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004888 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
4889 *
4890 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
4891 */
4892TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
4893 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4894 .Authorization(TAG_NO_AUTH_REQUIRED)
4895 .AesEncryptionKey(128)
4896 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
4897 .Padding(PaddingMode::NONE)
4898 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4899
4900 string aad = "foobar";
4901 string message = "123456789012345678901234567890123456";
4902
4903 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4904 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4905 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
4906
4907 ASSERT_NE(ciphertext1, ciphertext2);
4908 ASSERT_NE(ciphertext1, ciphertext3);
4909 ASSERT_NE(ciphertext2, ciphertext3);
4910}
4911
4912/*
Selene Huang31ab4042020-04-29 04:22:39 -07004913 * EncryptionOperationsTest.AesGcmTooShortTag
4914 *
4915 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
4916 */
4917TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
4918 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4919 .Authorization(TAG_NO_AUTH_REQUIRED)
4920 .AesEncryptionKey(128)
4921 .BlockMode(BlockMode::GCM)
4922 .Padding(PaddingMode::NONE)
4923 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4924 string message = "123456789012345678901234567890123456";
4925 auto params = AuthorizationSetBuilder()
4926 .BlockMode(BlockMode::GCM)
4927 .Padding(PaddingMode::NONE)
4928 .Authorization(TAG_MAC_LENGTH, 96);
4929
4930 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
4931}
4932
4933/*
4934 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
4935 *
4936 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
4937 */
4938TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
4939 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4940 .Authorization(TAG_NO_AUTH_REQUIRED)
4941 .AesEncryptionKey(128)
4942 .BlockMode(BlockMode::GCM)
4943 .Padding(PaddingMode::NONE)
4944 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
4945 string aad = "foobar";
4946 string message = "123456789012345678901234567890123456";
4947 auto params = AuthorizationSetBuilder()
4948 .BlockMode(BlockMode::GCM)
4949 .Padding(PaddingMode::NONE)
4950 .Authorization(TAG_MAC_LENGTH, 128);
4951
Selene Huang31ab4042020-04-29 04:22:39 -07004952 // Encrypt
4953 AuthorizationSet begin_out_params;
4954 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
4955 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08004956 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07004957
4958 AuthorizationSet finish_out_params;
4959 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07004960 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
4961 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07004962
4963 params = AuthorizationSetBuilder()
4964 .Authorizations(begin_out_params)
4965 .BlockMode(BlockMode::GCM)
4966 .Padding(PaddingMode::NONE)
4967 .Authorization(TAG_MAC_LENGTH, 96);
4968
4969 // Decrypt.
4970 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
4971}
4972
4973/*
4974 * EncryptionOperationsTest.AesGcmCorruptKey
4975 *
4976 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
4977 */
4978TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
4979 const uint8_t nonce_bytes[] = {
4980 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
4981 };
4982 string nonce = make_string(nonce_bytes);
4983 const uint8_t ciphertext_bytes[] = {
4984 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
4985 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
4986 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
4987 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
4988 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
4989 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
4990 };
4991 string ciphertext = make_string(ciphertext_bytes);
4992
4993 auto params = AuthorizationSetBuilder()
4994 .BlockMode(BlockMode::GCM)
4995 .Padding(PaddingMode::NONE)
4996 .Authorization(TAG_MAC_LENGTH, 128)
4997 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
4998
4999 auto import_params = AuthorizationSetBuilder()
5000 .Authorization(TAG_NO_AUTH_REQUIRED)
5001 .AesEncryptionKey(128)
5002 .BlockMode(BlockMode::GCM)
5003 .Padding(PaddingMode::NONE)
5004 .Authorization(TAG_CALLER_NONCE)
5005 .Authorization(TAG_MIN_MAC_LENGTH, 128);
5006
5007 // Import correct key and decrypt
5008 const uint8_t key_bytes[] = {
5009 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
5010 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
5011 };
5012 string key = make_string(key_bytes);
5013 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5014 string plaintext = DecryptMessage(ciphertext, params);
5015 CheckedDeleteKey();
5016
5017 // Corrupt key and attempt to decrypt
5018 key[0] = 0;
5019 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
5020 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5021 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
5022 CheckedDeleteKey();
5023}
5024
5025/*
5026 * EncryptionOperationsTest.AesGcmAadNoData
5027 *
5028 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
5029 * encrypt.
5030 */
5031TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
5032 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5033 .Authorization(TAG_NO_AUTH_REQUIRED)
5034 .AesEncryptionKey(128)
5035 .BlockMode(BlockMode::GCM)
5036 .Padding(PaddingMode::NONE)
5037 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5038
5039 string aad = "1234567890123456";
5040 auto params = AuthorizationSetBuilder()
5041 .BlockMode(BlockMode::GCM)
5042 .Padding(PaddingMode::NONE)
5043 .Authorization(TAG_MAC_LENGTH, 128);
5044
Selene Huang31ab4042020-04-29 04:22:39 -07005045 // Encrypt
5046 AuthorizationSet begin_out_params;
5047 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
5048 string ciphertext;
5049 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005050 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5051 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005052 EXPECT_TRUE(finish_out_params.empty());
5053
5054 // Grab nonce
5055 params.push_back(begin_out_params);
5056
5057 // Decrypt.
5058 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005059 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005060 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005061 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005062
5063 EXPECT_TRUE(finish_out_params.empty());
5064
5065 EXPECT_EQ("", plaintext);
5066}
5067
5068/*
5069 * EncryptionOperationsTest.AesGcmMultiPartAad
5070 *
5071 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
5072 * chunks.
5073 */
5074TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
5075 const size_t tag_bits = 128;
5076 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5077 .Authorization(TAG_NO_AUTH_REQUIRED)
5078 .AesEncryptionKey(128)
5079 .BlockMode(BlockMode::GCM)
5080 .Padding(PaddingMode::NONE)
5081 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5082
5083 string message = "123456789012345678901234567890123456";
5084 auto begin_params = AuthorizationSetBuilder()
5085 .BlockMode(BlockMode::GCM)
5086 .Padding(PaddingMode::NONE)
5087 .Authorization(TAG_MAC_LENGTH, tag_bits);
5088 AuthorizationSet begin_out_params;
5089
Selene Huang31ab4042020-04-29 04:22:39 -07005090 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5091
5092 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07005093 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
5094 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005095 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005096 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5097 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005098
Selene Huang31ab4042020-04-29 04:22:39 -07005099 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07005100 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005101
5102 // Grab nonce.
5103 begin_params.push_back(begin_out_params);
5104
5105 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005106 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005107 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005108 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005109 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005110 EXPECT_EQ(message, plaintext);
5111}
5112
5113/*
5114 * EncryptionOperationsTest.AesGcmAadOutOfOrder
5115 *
5116 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
5117 */
5118TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
5119 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5120 .Authorization(TAG_NO_AUTH_REQUIRED)
5121 .AesEncryptionKey(128)
5122 .BlockMode(BlockMode::GCM)
5123 .Padding(PaddingMode::NONE)
5124 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5125
5126 string message = "123456789012345678901234567890123456";
5127 auto begin_params = AuthorizationSetBuilder()
5128 .BlockMode(BlockMode::GCM)
5129 .Padding(PaddingMode::NONE)
5130 .Authorization(TAG_MAC_LENGTH, 128);
5131 AuthorizationSet begin_out_params;
5132
Selene Huang31ab4042020-04-29 04:22:39 -07005133 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
5134
Shawn Willden92d79c02021-02-19 07:31:55 -07005135 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005136 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005137 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
5138 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005139
David Drysdaled2cc8c22021-04-15 13:29:45 +01005140 // The failure should have already cancelled the operation.
5141 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
5142
Shawn Willden92d79c02021-02-19 07:31:55 -07005143 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07005144}
5145
5146/*
5147 * EncryptionOperationsTest.AesGcmBadAad
5148 *
5149 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
5150 */
5151TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
5152 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5153 .Authorization(TAG_NO_AUTH_REQUIRED)
5154 .AesEncryptionKey(128)
5155 .BlockMode(BlockMode::GCM)
5156 .Padding(PaddingMode::NONE)
5157 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5158
5159 string message = "12345678901234567890123456789012";
5160 auto begin_params = AuthorizationSetBuilder()
5161 .BlockMode(BlockMode::GCM)
5162 .Padding(PaddingMode::NONE)
5163 .Authorization(TAG_MAC_LENGTH, 128);
5164
Selene Huang31ab4042020-04-29 04:22:39 -07005165 // Encrypt
5166 AuthorizationSet begin_out_params;
5167 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005168 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005169 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005170 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005171
5172 // Grab nonce
5173 begin_params.push_back(begin_out_params);
5174
Selene Huang31ab4042020-04-29 04:22:39 -07005175 // Decrypt.
5176 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005177 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07005178 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005179 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005180}
5181
5182/*
5183 * EncryptionOperationsTest.AesGcmWrongNonce
5184 *
5185 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
5186 */
5187TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
5188 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5189 .Authorization(TAG_NO_AUTH_REQUIRED)
5190 .AesEncryptionKey(128)
5191 .BlockMode(BlockMode::GCM)
5192 .Padding(PaddingMode::NONE)
5193 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5194
5195 string message = "12345678901234567890123456789012";
5196 auto begin_params = AuthorizationSetBuilder()
5197 .BlockMode(BlockMode::GCM)
5198 .Padding(PaddingMode::NONE)
5199 .Authorization(TAG_MAC_LENGTH, 128);
5200
Selene Huang31ab4042020-04-29 04:22:39 -07005201 // Encrypt
5202 AuthorizationSet begin_out_params;
5203 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005204 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005205 string ciphertext;
5206 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005207 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005208
5209 // Wrong nonce
5210 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
5211
5212 // Decrypt.
5213 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005214 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07005215 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005216 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005217
5218 // With wrong nonce, should have gotten garbage plaintext (or none).
5219 EXPECT_NE(message, plaintext);
5220}
5221
5222/*
5223 * EncryptionOperationsTest.AesGcmCorruptTag
5224 *
5225 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
5226 */
5227TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
5228 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5229 .Authorization(TAG_NO_AUTH_REQUIRED)
5230 .AesEncryptionKey(128)
5231 .BlockMode(BlockMode::GCM)
5232 .Padding(PaddingMode::NONE)
5233 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5234
5235 string aad = "1234567890123456";
5236 string message = "123456789012345678901234567890123456";
5237
5238 auto params = AuthorizationSetBuilder()
5239 .BlockMode(BlockMode::GCM)
5240 .Padding(PaddingMode::NONE)
5241 .Authorization(TAG_MAC_LENGTH, 128);
5242
Selene Huang31ab4042020-04-29 04:22:39 -07005243 // Encrypt
5244 AuthorizationSet begin_out_params;
5245 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005246 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005247 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005248 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005249
5250 // Corrupt tag
5251 ++(*ciphertext.rbegin());
5252
5253 // Grab nonce
5254 params.push_back(begin_out_params);
5255
5256 // Decrypt.
5257 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07005258 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005259 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005260 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005261}
5262
5263/*
5264 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
5265 *
5266 * Verifies that 3DES is basically functional.
5267 */
5268TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
5269 auto auths = AuthorizationSetBuilder()
5270 .TripleDesEncryptionKey(168)
5271 .BlockMode(BlockMode::ECB)
5272 .Authorization(TAG_NO_AUTH_REQUIRED)
5273 .Padding(PaddingMode::NONE);
5274
5275 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
5276 // Two-block message.
5277 string message = "1234567890123456";
5278 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5279 string ciphertext1 = EncryptMessage(message, inParams);
5280 EXPECT_EQ(message.size(), ciphertext1.size());
5281
5282 string ciphertext2 = EncryptMessage(string(message), inParams);
5283 EXPECT_EQ(message.size(), ciphertext2.size());
5284
5285 // ECB is deterministic.
5286 EXPECT_EQ(ciphertext1, ciphertext2);
5287
5288 string plaintext = DecryptMessage(ciphertext1, inParams);
5289 EXPECT_EQ(message, plaintext);
5290}
5291
5292/*
5293 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
5294 *
5295 * Verifies that CBC keys reject ECB usage.
5296 */
5297TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
5298 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5299 .TripleDesEncryptionKey(168)
5300 .BlockMode(BlockMode::CBC)
5301 .Authorization(TAG_NO_AUTH_REQUIRED)
5302 .Padding(PaddingMode::NONE)));
5303
5304 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5305 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
5306}
5307
5308/*
5309 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
5310 *
5311 * Tests ECB mode with PKCS#7 padding, various message sizes.
5312 */
5313TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
5314 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5315 .TripleDesEncryptionKey(168)
5316 .BlockMode(BlockMode::ECB)
5317 .Authorization(TAG_NO_AUTH_REQUIRED)
5318 .Padding(PaddingMode::PKCS7)));
5319
5320 for (size_t i = 0; i < 32; ++i) {
5321 string message(i, 'a');
5322 auto inParams =
5323 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5324 string ciphertext = EncryptMessage(message, inParams);
5325 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5326 string plaintext = DecryptMessage(ciphertext, inParams);
5327 EXPECT_EQ(message, plaintext);
5328 }
5329}
5330
5331/*
5332 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
5333 *
5334 * Verifies that keys configured for no padding reject PKCS7 padding
5335 */
5336TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
5337 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5338 .TripleDesEncryptionKey(168)
5339 .BlockMode(BlockMode::ECB)
5340 .Authorization(TAG_NO_AUTH_REQUIRED)
5341 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00005342 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5343 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07005344}
5345
5346/*
5347 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
5348 *
5349 * Verifies that corrupted padding is detected.
5350 */
5351TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
5352 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5353 .TripleDesEncryptionKey(168)
5354 .BlockMode(BlockMode::ECB)
5355 .Authorization(TAG_NO_AUTH_REQUIRED)
5356 .Padding(PaddingMode::PKCS7)));
5357
5358 string message = "a";
5359 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
5360 EXPECT_EQ(8U, ciphertext.size());
5361 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005362
5363 AuthorizationSetBuilder begin_params;
5364 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
5365 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07005366
5367 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5368 ++ciphertext[ciphertext.size() / 2];
5369
5370 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5371 string plaintext;
5372 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5373 ErrorCode error = Finish(&plaintext);
5374 if (error == ErrorCode::INVALID_ARGUMENT) {
5375 // This is the expected error, we can exit the test now.
5376 return;
5377 } else {
5378 // Very small chance we got valid decryption, so try again.
5379 ASSERT_EQ(error, ErrorCode::OK);
5380 }
5381 }
5382 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005383}
5384
5385struct TripleDesTestVector {
5386 const char* name;
5387 const KeyPurpose purpose;
5388 const BlockMode block_mode;
5389 const PaddingMode padding_mode;
5390 const char* key;
5391 const char* iv;
5392 const char* input;
5393 const char* output;
5394};
5395
5396// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
5397// of the NIST vectors are multiples of the block size.
5398static const TripleDesTestVector kTripleDesTestVectors[] = {
5399 {
5400 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5401 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
5402 "", // IV
5403 "329d86bdf1bc5af4", // input
5404 "d946c2756d78633f", // output
5405 },
5406 {
5407 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
5408 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
5409 "", // IV
5410 "6b1540781b01ce1997adae102dbf3c5b", // input
5411 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
5412 },
5413 {
5414 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5415 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
5416 "", // IV
5417 "6daad94ce08acfe7", // input
5418 "660e7d32dcc90e79", // output
5419 },
5420 {
5421 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
5422 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
5423 "", // IV
5424 "e9653a0a1f05d31b9acd12d73aa9879d", // input
5425 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
5426 },
5427 {
5428 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5429 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
5430 "43f791134c5647ba", // IV
5431 "dcc153cef81d6f24", // input
5432 "92538bd8af18d3ba", // output
5433 },
5434 {
5435 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
5436 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5437 "c2e999cb6249023c", // IV
5438 "c689aee38a301bb316da75db36f110b5", // input
5439 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
5440 },
5441 {
5442 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
5443 PaddingMode::PKCS7,
5444 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5445 "c2e999cb6249023c", // IV
5446 "c689aee38a301bb316da75db36f110b500", // input
5447 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
5448 },
5449 {
5450 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
5451 PaddingMode::PKCS7,
5452 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
5453 "c2e999cb6249023c", // IV
5454 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
5455 "c689aee38a301bb316da75db36f110b500", // output
5456 },
5457 {
5458 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5459 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
5460 "41746c7e442d3681", // IV
5461 "c53a7b0ec40600fe", // input
5462 "d4f00eb455de1034", // output
5463 },
5464 {
5465 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
5466 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
5467 "3982bc02c3727d45", // IV
5468 "6006f10adef52991fcc777a1238bbb65", // input
5469 "edae09288e9e3bc05746d872b48e3b29", // output
5470 },
5471};
5472
5473/*
5474 * EncryptionOperationsTest.TripleDesTestVector
5475 *
5476 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
5477 */
5478TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
5479 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
5480 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
5481 SCOPED_TRACE(test->name);
5482 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
5483 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
5484 hex2str(test->output));
5485 }
5486}
5487
5488/*
5489 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
5490 *
5491 * Validates CBC mode functionality.
5492 */
5493TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
5494 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5495 .TripleDesEncryptionKey(168)
5496 .BlockMode(BlockMode::CBC)
5497 .Authorization(TAG_NO_AUTH_REQUIRED)
5498 .Padding(PaddingMode::NONE)));
5499
5500 ASSERT_GT(key_blob_.size(), 0U);
5501
5502 // Two-block message.
5503 string message = "1234567890123456";
5504 vector<uint8_t> iv1;
5505 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
5506 EXPECT_EQ(message.size(), ciphertext1.size());
5507
5508 vector<uint8_t> iv2;
5509 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
5510 EXPECT_EQ(message.size(), ciphertext2.size());
5511
5512 // IVs should be random, so ciphertexts should differ.
5513 EXPECT_NE(iv1, iv2);
5514 EXPECT_NE(ciphertext1, ciphertext2);
5515
5516 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
5517 EXPECT_EQ(message, plaintext);
5518}
5519
5520/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005521 * EncryptionOperationsTest.TripleDesInvalidCallerIv
5522 *
5523 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
5524 */
5525TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
5526 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5527 .TripleDesEncryptionKey(168)
5528 .BlockMode(BlockMode::CBC)
5529 .Authorization(TAG_NO_AUTH_REQUIRED)
5530 .Authorization(TAG_CALLER_NONCE)
5531 .Padding(PaddingMode::NONE)));
5532 auto params = AuthorizationSetBuilder()
5533 .BlockMode(BlockMode::CBC)
5534 .Padding(PaddingMode::NONE)
5535 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
5536 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5537}
5538
5539/*
Selene Huang31ab4042020-04-29 04:22:39 -07005540 * EncryptionOperationsTest.TripleDesCallerIv
5541 *
5542 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
5543 */
5544TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
5545 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5546 .TripleDesEncryptionKey(168)
5547 .BlockMode(BlockMode::CBC)
5548 .Authorization(TAG_NO_AUTH_REQUIRED)
5549 .Authorization(TAG_CALLER_NONCE)
5550 .Padding(PaddingMode::NONE)));
5551 string message = "1234567890123456";
5552 vector<uint8_t> iv;
5553 // Don't specify IV, should get a random one.
5554 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5555 EXPECT_EQ(message.size(), ciphertext1.size());
5556 EXPECT_EQ(8U, iv.size());
5557
5558 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5559 EXPECT_EQ(message, plaintext);
5560
5561 // Now specify an IV, should also work.
5562 iv = AidlBuf("abcdefgh");
5563 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
5564
5565 // Decrypt with correct IV.
5566 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
5567 EXPECT_EQ(message, plaintext);
5568
5569 // Now try with wrong IV.
5570 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
5571 EXPECT_NE(message, plaintext);
5572}
5573
5574/*
5575 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
5576 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01005577 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07005578 */
5579TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
5580 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5581 .TripleDesEncryptionKey(168)
5582 .BlockMode(BlockMode::CBC)
5583 .Authorization(TAG_NO_AUTH_REQUIRED)
5584 .Padding(PaddingMode::NONE)));
5585
5586 string message = "12345678901234567890123456789012";
5587 vector<uint8_t> iv;
5588 // Don't specify nonce, should get a random one.
5589 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
5590 EXPECT_EQ(message.size(), ciphertext1.size());
5591 EXPECT_EQ(8U, iv.size());
5592
5593 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
5594 EXPECT_EQ(message, plaintext);
5595
5596 // Now specify a nonce, should fail.
5597 auto input_params = AuthorizationSetBuilder()
5598 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
5599 .BlockMode(BlockMode::CBC)
5600 .Padding(PaddingMode::NONE);
5601 AuthorizationSet output_params;
5602 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
5603 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5604}
5605
5606/*
5607 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
5608 *
5609 * Verifies that 3DES ECB-only keys do not allow CBC usage.
5610 */
5611TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
5612 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5613 .TripleDesEncryptionKey(168)
5614 .BlockMode(BlockMode::ECB)
5615 .Authorization(TAG_NO_AUTH_REQUIRED)
5616 .Padding(PaddingMode::NONE)));
5617 // Two-block message.
5618 string message = "1234567890123456";
5619 auto begin_params =
5620 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5621 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5622}
5623
5624/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005625 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005626 *
5627 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
5628 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005629TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
5630 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5631 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5632 .TripleDesEncryptionKey(168)
5633 .BlockMode(blockMode)
5634 .Authorization(TAG_NO_AUTH_REQUIRED)
5635 .Padding(PaddingMode::NONE)));
5636 // Message is slightly shorter than two blocks.
5637 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07005638
David Drysdaled2cc8c22021-04-15 13:29:45 +01005639 auto begin_params =
5640 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5641 AuthorizationSet output_params;
5642 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
5643 string ciphertext;
5644 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
5645
5646 CheckedDeleteKey();
5647 }
Selene Huang31ab4042020-04-29 04:22:39 -07005648}
5649
5650/*
5651 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
5652 *
5653 * Verifies that PKCS7 padding works correctly in CBC mode.
5654 */
5655TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
5656 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5657 .TripleDesEncryptionKey(168)
5658 .BlockMode(BlockMode::CBC)
5659 .Authorization(TAG_NO_AUTH_REQUIRED)
5660 .Padding(PaddingMode::PKCS7)));
5661
5662 // Try various message lengths; all should work.
5663 for (size_t i = 0; i < 32; ++i) {
5664 string message(i, 'a');
5665 vector<uint8_t> iv;
5666 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5667 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
5668 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
5669 EXPECT_EQ(message, plaintext);
5670 }
5671}
5672
5673/*
5674 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
5675 *
5676 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
5677 */
5678TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
5679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5680 .TripleDesEncryptionKey(168)
5681 .BlockMode(BlockMode::CBC)
5682 .Authorization(TAG_NO_AUTH_REQUIRED)
5683 .Padding(PaddingMode::NONE)));
5684
5685 // Try various message lengths; all should fail.
5686 for (size_t i = 0; i < 32; ++i) {
5687 auto begin_params =
5688 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
5689 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
5690 }
5691}
5692
5693/*
5694 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
5695 *
5696 * Verifies that corrupted PKCS7 padding is rejected during decryption.
5697 */
5698TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
5699 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5700 .TripleDesEncryptionKey(168)
5701 .BlockMode(BlockMode::CBC)
5702 .Authorization(TAG_NO_AUTH_REQUIRED)
5703 .Padding(PaddingMode::PKCS7)));
5704
5705 string message = "a";
5706 vector<uint8_t> iv;
5707 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
5708 EXPECT_EQ(8U, ciphertext.size());
5709 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005710
5711 auto begin_params = AuthorizationSetBuilder()
5712 .BlockMode(BlockMode::CBC)
5713 .Padding(PaddingMode::PKCS7)
5714 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07005715
5716 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5717 ++ciphertext[ciphertext.size() / 2];
5718 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
5719 string plaintext;
5720 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
5721 ErrorCode error = Finish(&plaintext);
5722 if (error == ErrorCode::INVALID_ARGUMENT) {
5723 // This is the expected error, we can exit the test now.
5724 return;
5725 } else {
5726 // Very small chance we got valid decryption, so try again.
5727 ASSERT_EQ(error, ErrorCode::OK);
5728 }
5729 }
5730 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005731}
5732
5733/*
5734 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
5735 *
5736 * Verifies that 3DES CBC works with many different input sizes.
5737 */
5738TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
5739 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5740 .TripleDesEncryptionKey(168)
5741 .BlockMode(BlockMode::CBC)
5742 .Authorization(TAG_NO_AUTH_REQUIRED)
5743 .Padding(PaddingMode::NONE)));
5744
5745 int increment = 7;
5746 string message(240, 'a');
5747 AuthorizationSet input_params =
5748 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5749 AuthorizationSet output_params;
5750 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
5751
5752 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07005753 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005754 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005755 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
5756 EXPECT_EQ(message.size(), ciphertext.size());
5757
5758 // Move TAG_NONCE into input_params
5759 input_params = output_params;
5760 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
5761 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
5762 output_params.Clear();
5763
5764 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
5765 string plaintext;
5766 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07005767 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005768 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
5769 EXPECT_EQ(ciphertext.size(), plaintext.size());
5770 EXPECT_EQ(message, plaintext);
5771}
5772
5773INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
5774
5775typedef KeyMintAidlTestBase MaxOperationsTest;
5776
5777/*
5778 * MaxOperationsTest.TestLimitAes
5779 *
5780 * Verifies that the max uses per boot tag works correctly with AES keys.
5781 */
5782TEST_P(MaxOperationsTest, TestLimitAes) {
5783 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5784
5785 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5786 .Authorization(TAG_NO_AUTH_REQUIRED)
5787 .AesEncryptionKey(128)
5788 .EcbMode()
5789 .Padding(PaddingMode::NONE)
5790 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
5791
5792 string message = "1234567890123456";
5793
5794 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5795
5796 EncryptMessage(message, params);
5797 EncryptMessage(message, params);
5798 EncryptMessage(message, params);
5799
5800 // Fourth time should fail.
5801 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
5802}
5803
5804/*
Qi Wud22ec842020-11-26 13:27:53 +08005805 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07005806 *
5807 * Verifies that the max uses per boot tag works correctly with RSA keys.
5808 */
5809TEST_P(MaxOperationsTest, TestLimitRsa) {
5810 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5811
5812 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5813 .Authorization(TAG_NO_AUTH_REQUIRED)
5814 .RsaSigningKey(1024, 65537)
5815 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005816 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
5817 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005818
5819 string message = "1234567890123456";
5820
5821 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5822
5823 SignMessage(message, params);
5824 SignMessage(message, params);
5825 SignMessage(message, params);
5826
5827 // Fourth time should fail.
5828 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
5829}
5830
5831INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
5832
Qi Wud22ec842020-11-26 13:27:53 +08005833typedef KeyMintAidlTestBase UsageCountLimitTest;
5834
5835/*
Qi Wubeefae42021-01-28 23:16:37 +08005836 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005837 *
Qi Wubeefae42021-01-28 23:16:37 +08005838 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005839 */
Qi Wubeefae42021-01-28 23:16:37 +08005840TEST_P(UsageCountLimitTest, TestSingleUseAes) {
Qi Wud22ec842020-11-26 13:27:53 +08005841 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5842
5843 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5844 .Authorization(TAG_NO_AUTH_REQUIRED)
5845 .AesEncryptionKey(128)
5846 .EcbMode()
5847 .Padding(PaddingMode::NONE)
5848 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
5849
5850 // Check the usage count limit tag appears in the authorizations.
5851 AuthorizationSet auths;
5852 for (auto& entry : key_characteristics_) {
5853 auths.push_back(AuthorizationSet(entry.authorizations));
5854 }
5855 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5856 << "key usage count limit " << 1U << " missing";
5857
5858 string message = "1234567890123456";
5859 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5860
Qi Wubeefae42021-01-28 23:16:37 +08005861 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5862 AuthorizationSet keystore_auths =
5863 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5864
Qi Wud22ec842020-11-26 13:27:53 +08005865 // First usage of AES key should work.
5866 EncryptMessage(message, params);
5867
Qi Wud22ec842020-11-26 13:27:53 +08005868 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5869 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5870 // must be invalidated from secure storage (such as RPMB partition).
5871 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5872 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005873 // Usage count limit tag is enforced by keystore, keymint does nothing.
5874 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08005875 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5876 }
5877}
5878
5879/*
Qi Wubeefae42021-01-28 23:16:37 +08005880 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08005881 *
Qi Wubeefae42021-01-28 23:16:37 +08005882 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08005883 */
Qi Wubeefae42021-01-28 23:16:37 +08005884TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
5885 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5886
5887 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5888 .Authorization(TAG_NO_AUTH_REQUIRED)
5889 .AesEncryptionKey(128)
5890 .EcbMode()
5891 .Padding(PaddingMode::NONE)
5892 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
5893
5894 // Check the usage count limit tag appears in the authorizations.
5895 AuthorizationSet auths;
5896 for (auto& entry : key_characteristics_) {
5897 auths.push_back(AuthorizationSet(entry.authorizations));
5898 }
5899 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5900 << "key usage count limit " << 3U << " missing";
5901
5902 string message = "1234567890123456";
5903 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
5904
5905 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5906 AuthorizationSet keystore_auths =
5907 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5908
5909 EncryptMessage(message, params);
5910 EncryptMessage(message, params);
5911 EncryptMessage(message, params);
5912
5913 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
5914 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5915 // must be invalidated from secure storage (such as RPMB partition).
5916 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
5917 } else {
5918 // Usage count limit tag is enforced by keystore, keymint does nothing.
5919 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
5920 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
5921 }
5922}
5923
5924/*
5925 * UsageCountLimitTest.TestSingleUseRsa
5926 *
5927 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
5928 */
5929TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
Qi Wud22ec842020-11-26 13:27:53 +08005930 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5931
5932 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5933 .Authorization(TAG_NO_AUTH_REQUIRED)
5934 .RsaSigningKey(1024, 65537)
5935 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005936 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
5937 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08005938
5939 // Check the usage count limit tag appears in the authorizations.
5940 AuthorizationSet auths;
5941 for (auto& entry : key_characteristics_) {
5942 auths.push_back(AuthorizationSet(entry.authorizations));
5943 }
5944 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
5945 << "key usage count limit " << 1U << " missing";
5946
5947 string message = "1234567890123456";
5948 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5949
Qi Wubeefae42021-01-28 23:16:37 +08005950 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5951 AuthorizationSet keystore_auths =
5952 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5953
Qi Wud22ec842020-11-26 13:27:53 +08005954 // First usage of RSA key should work.
5955 SignMessage(message, params);
5956
Qi Wud22ec842020-11-26 13:27:53 +08005957 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
5958 // Usage count limit tag is enforced by hardware. After using the key, the key blob
5959 // must be invalidated from secure storage (such as RPMB partition).
5960 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
5961 } else {
Qi Wubeefae42021-01-28 23:16:37 +08005962 // Usage count limit tag is enforced by keystore, keymint does nothing.
5963 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
5964 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
5965 }
5966}
5967
5968/*
5969 * UsageCountLimitTest.TestLimitUseRsa
5970 *
5971 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
5972 */
5973TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
5974 if (SecLevel() == SecurityLevel::STRONGBOX) return;
5975
5976 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5977 .Authorization(TAG_NO_AUTH_REQUIRED)
5978 .RsaSigningKey(1024, 65537)
5979 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08005980 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
5981 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08005982
5983 // Check the usage count limit tag appears in the authorizations.
5984 AuthorizationSet auths;
5985 for (auto& entry : key_characteristics_) {
5986 auths.push_back(AuthorizationSet(entry.authorizations));
5987 }
5988 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
5989 << "key usage count limit " << 3U << " missing";
5990
5991 string message = "1234567890123456";
5992 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
5993
5994 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
5995 AuthorizationSet keystore_auths =
5996 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
5997
5998 SignMessage(message, params);
5999 SignMessage(message, params);
6000 SignMessage(message, params);
6001
6002 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6003 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6004 // must be invalidated from secure storage (such as RPMB partition).
6005 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6006 } else {
6007 // Usage count limit tag is enforced by keystore, keymint does nothing.
6008 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08006009 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
6010 }
6011}
6012
Qi Wu8e727f72021-02-11 02:49:33 +08006013/*
6014 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
6015 *
6016 * Verifies that when rollback resistance is supported by the KeyMint implementation with
6017 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
6018 * in hardware.
6019 */
6020TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
6021 if (SecLevel() == SecurityLevel::STRONGBOX) return;
6022
6023 auto error = GenerateKey(AuthorizationSetBuilder()
6024 .RsaSigningKey(2048, 65537)
6025 .Digest(Digest::NONE)
6026 .Padding(PaddingMode::NONE)
6027 .Authorization(TAG_NO_AUTH_REQUIRED)
6028 .Authorization(TAG_ROLLBACK_RESISTANCE)
6029 .SetDefaultValidity());
6030 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6031
6032 if (error == ErrorCode::OK) {
6033 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
6034 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
6035 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6036 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6037
6038 // The KeyMint should also enforce single use key in hardware when it supports rollback
6039 // resistance.
6040 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6041 .Authorization(TAG_NO_AUTH_REQUIRED)
6042 .RsaSigningKey(1024, 65537)
6043 .NoDigestOrPadding()
6044 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
6045 .SetDefaultValidity()));
6046
6047 // Check the usage count limit tag appears in the hardware authorizations.
6048 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6049 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6050 << "key usage count limit " << 1U << " missing";
6051
6052 string message = "1234567890123456";
6053 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6054
6055 // First usage of RSA key should work.
6056 SignMessage(message, params);
6057
6058 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6059 // must be invalidated from secure storage (such as RPMB partition).
6060 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
6061 }
6062}
6063
Qi Wud22ec842020-11-26 13:27:53 +08006064INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
6065
David Drysdale7de9feb2021-03-05 14:56:19 +00006066typedef KeyMintAidlTestBase GetHardwareInfoTest;
6067
6068TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
6069 // Retrieving hardware info should give the same result each time.
6070 KeyMintHardwareInfo info;
6071 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
6072 KeyMintHardwareInfo info2;
6073 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
6074 EXPECT_EQ(info, info2);
6075}
6076
6077INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
6078
Selene Huang31ab4042020-04-29 04:22:39 -07006079typedef KeyMintAidlTestBase AddEntropyTest;
6080
6081/*
6082 * AddEntropyTest.AddEntropy
6083 *
6084 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
6085 * is actually added.
6086 */
6087TEST_P(AddEntropyTest, AddEntropy) {
6088 string data = "foo";
6089 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
6090}
6091
6092/*
6093 * AddEntropyTest.AddEmptyEntropy
6094 *
6095 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
6096 */
6097TEST_P(AddEntropyTest, AddEmptyEntropy) {
6098 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
6099}
6100
6101/*
6102 * AddEntropyTest.AddLargeEntropy
6103 *
6104 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
6105 */
6106TEST_P(AddEntropyTest, AddLargeEntropy) {
6107 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
6108}
6109
David Drysdalebb3d85e2021-04-13 11:15:51 +01006110/*
6111 * AddEntropyTest.AddTooLargeEntropy
6112 *
6113 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
6114 */
6115TEST_P(AddEntropyTest, AddTooLargeEntropy) {
6116 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
6117 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
6118}
6119
Selene Huang31ab4042020-04-29 04:22:39 -07006120INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
6121
Selene Huang31ab4042020-04-29 04:22:39 -07006122typedef KeyMintAidlTestBase KeyDeletionTest;
6123
6124/**
6125 * KeyDeletionTest.DeleteKey
6126 *
6127 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
6128 * valid key blob.
6129 */
6130TEST_P(KeyDeletionTest, DeleteKey) {
6131 auto error = GenerateKey(AuthorizationSetBuilder()
6132 .RsaSigningKey(2048, 65537)
6133 .Digest(Digest::NONE)
6134 .Padding(PaddingMode::NONE)
6135 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006136 .Authorization(TAG_ROLLBACK_RESISTANCE)
6137 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006138 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6139
6140 // Delete must work if rollback protection is implemented
6141 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006142 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
Selene Huang31ab4042020-04-29 04:22:39 -07006143 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
6144
6145 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
6146
6147 string message = "12345678901234567890123456789012";
6148 AuthorizationSet begin_out_params;
6149 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
6150 Begin(KeyPurpose::SIGN, key_blob_,
6151 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
6152 &begin_out_params));
6153 AbortIfNeeded();
6154 key_blob_ = AidlBuf();
6155 }
6156}
6157
6158/**
6159 * KeyDeletionTest.DeleteInvalidKey
6160 *
6161 * This test checks that the HAL excepts invalid key blobs..
6162 */
6163TEST_P(KeyDeletionTest, DeleteInvalidKey) {
6164 // Generate key just to check if rollback protection is implemented
6165 auto error = GenerateKey(AuthorizationSetBuilder()
6166 .RsaSigningKey(2048, 65537)
6167 .Digest(Digest::NONE)
6168 .Padding(PaddingMode::NONE)
6169 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08006170 .Authorization(TAG_ROLLBACK_RESISTANCE)
6171 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006172 ASSERT_TRUE(error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE || error == ErrorCode::OK);
6173
6174 // Delete must work if rollback protection is implemented
6175 if (error == ErrorCode::OK) {
Shawn Willden7f424372021-01-10 18:06:50 -07006176 AuthorizationSet enforced(SecLevelAuthorizations());
6177 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006178
6179 // Delete the key we don't care about the result at this point.
6180 DeleteKey();
6181
6182 // Now create an invalid key blob and delete it.
6183 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
6184
6185 ASSERT_EQ(ErrorCode::OK, DeleteKey());
6186 }
6187}
6188
6189/**
6190 * KeyDeletionTest.DeleteAllKeys
6191 *
6192 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
6193 *
6194 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
6195 * FBE/FDE encryption keys, which means that the device will not even boot until after the
6196 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
6197 * been provisioned. Use this test only on dedicated testing devices that have no valuable
6198 * credentials stored in Keystore/Keymint.
6199 */
6200TEST_P(KeyDeletionTest, DeleteAllKeys) {
6201 if (!arm_deleteAllKeys) return;
6202 auto error = GenerateKey(AuthorizationSetBuilder()
6203 .RsaSigningKey(2048, 65537)
6204 .Digest(Digest::NONE)
6205 .Padding(PaddingMode::NONE)
6206 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06006207 .Authorization(TAG_ROLLBACK_RESISTANCE)
6208 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07006209 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}