blob: b8d0c200fcc1217e7ccf5eea329c45b49dbf576e [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 Drysdale42fe1892021-10-14 14:43:46 +010025#include <openssl/curve25519.h>
David Zeuthene0c40892021-01-08 12:54:11 -050026#include <openssl/ec.h>
Selene Huang31ab4042020-04-29 04:22:39 -070027#include <openssl/evp.h>
28#include <openssl/mem.h>
David Zeuthene0c40892021-01-08 12:54:11 -050029#include <openssl/x509v3.h>
Selene Huang31ab4042020-04-29 04:22:39 -070030
31#include <cutils/properties.h>
32
David Drysdale4dc01072021-04-01 12:17:35 +010033#include <android/binder_manager.h>
34
35#include <aidl/android/hardware/security/keymint/IRemotelyProvisionedComponent.h>
Janis Danisevskis24c04702020-12-16 18:28:39 -080036#include <aidl/android/hardware/security/keymint/KeyFormat.h>
Selene Huang31ab4042020-04-29 04:22:39 -070037
Shawn Willden08a7e432020-12-11 13:05:27 +000038#include <keymint_support/key_param_output.h>
39#include <keymint_support/openssl_utils.h>
Selene Huang31ab4042020-04-29 04:22:39 -070040
41#include "KeyMintAidlTestBase.h"
42
Janis Danisevskis24c04702020-12-16 18:28:39 -080043using aidl::android::hardware::security::keymint::AuthorizationSet;
44using aidl::android::hardware::security::keymint::KeyCharacteristics;
45using aidl::android::hardware::security::keymint::KeyFormat;
Selene Huang31ab4042020-04-29 04:22:39 -070046
Selene Huang31ab4042020-04-29 04:22:39 -070047namespace std {
48
Janis Danisevskis24c04702020-12-16 18:28:39 -080049using namespace aidl::android::hardware::security::keymint;
Selene Huang31ab4042020-04-29 04:22:39 -070050
51template <>
52struct std::equal_to<KeyCharacteristics> {
53 bool operator()(const KeyCharacteristics& a, const KeyCharacteristics& b) const {
Shawn Willden7f424372021-01-10 18:06:50 -070054 if (a.securityLevel != b.securityLevel) return false;
Selene Huang31ab4042020-04-29 04:22:39 -070055
Shawn Willden7f424372021-01-10 18:06:50 -070056 // this isn't very efficient. Oh, well.
57 AuthorizationSet a_auths(a.authorizations);
58 AuthorizationSet b_auths(b.authorizations);
Selene Huang31ab4042020-04-29 04:22:39 -070059
Shawn Willden7f424372021-01-10 18:06:50 -070060 a_auths.Sort();
61 b_auths.Sort();
62
63 return a_auths == b_auths;
Selene Huang31ab4042020-04-29 04:22:39 -070064 }
65};
66
67} // namespace std
68
Janis Danisevskis24c04702020-12-16 18:28:39 -080069namespace aidl::android::hardware::security::keymint::test {
Shawn Willden08a7e432020-12-11 13:05:27 +000070
Selene Huang31ab4042020-04-29 04:22:39 -070071namespace {
72
David Drysdalefeab5d92022-01-06 15:46:23 +000073// Maximum supported Ed25519 message size.
74const size_t MAX_ED25519_MSG_SIZE = 16 * 1024;
75
David Drysdaledbbbe2e2021-12-02 07:44:23 +000076// Whether to check that BOOT_PATCHLEVEL is populated.
77bool check_boot_pl = true;
78
Seth Moore7a55ae32021-06-23 14:28:11 -070079// The maximum number of times we'll attempt to verify that corruption
David Drysdale4c1f6ac2021-11-25 16:08:29 +000080// of an encrypted blob results in an error. Retries are necessary as there
Seth Moore7a55ae32021-06-23 14:28:11 -070081// is a small (roughly 1/256) chance that corrupting ciphertext still results
82// in valid PKCS7 padding.
83constexpr size_t kMaxPaddingCorruptionRetries = 8;
84
Selene Huang31ab4042020-04-29 04:22:39 -070085template <TagType tag_type, Tag tag, typename ValueT>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000086bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag> ttag,
87 ValueT expected_value) {
Selene Huang31ab4042020-04-29 04:22:39 -070088 auto it = std::find_if(set.begin(), set.end(), [&](const KeyParameter& param) {
Janis Danisevskis5ba09332020-12-17 10:05:15 -080089 if (auto p = authorizationValue(ttag, param)) {
90 return *p == expected_value;
91 }
92 return false;
Selene Huang31ab4042020-04-29 04:22:39 -070093 });
94 return (it != set.end());
95}
96
97template <TagType tag_type, Tag tag>
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +000098bool contains(const vector<KeyParameter>& set, TypedTag<tag_type, tag>) {
Selene Huang31ab4042020-04-29 04:22:39 -070099 auto it = std::find_if(set.begin(), set.end(),
100 [&](const KeyParameter& param) { return param.tag == tag; });
101 return (it != set.end());
102}
103
104constexpr char hex_value[256] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
105 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
106 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
107 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9'
108 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F'
109 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
110 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f'
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 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
116 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
117 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
118 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //
119 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
120
121string hex2str(string a) {
122 string b;
123 size_t num = a.size() / 2;
124 b.resize(num);
125 for (size_t i = 0; i < num; i++) {
126 b[i] = (hex_value[a[i * 2] & 0xFF] << 4) + (hex_value[a[i * 2 + 1] & 0xFF]);
127 }
128 return b;
129}
130
David Drysdaled2cc8c22021-04-15 13:29:45 +0100131string rsa_key = hex2str(
132 // RFC 5208 s5
133 "30820275" // SEQUENCE length 0x275 (PrivateKeyInfo) {
134 "020100" // INTEGER length 1 value 0x00 (version)
135 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
136 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
137 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
138 "0500" // NULL (parameters)
139 // } end SEQUENCE (AlgorithmIdentifier)
140 "0482025f" // OCTET STRING length 0x25f (privateKey) holding...
141 // RFC 8017 A.1.2
142 "3082025b" // SEQUENCE length 0x25b (RSAPrivateKey) {
143 "020100" // INTEGER length 1 value 0x00 (version)
144 "028181" // INTEGER length 0x81 value (modulus) ...
145 "00c6095409047d8634812d5a218176e4"
146 "5c41d60a75b13901f234226cffe77652"
147 "1c5a77b9e389417b71c0b6a44d13afe4"
148 "e4a2805d46c9da2935adb1ff0c1f24ea"
149 "06e62b20d776430a4d435157233c6f91"
150 "6783c30e310fcbd89b85c2d567711697"
151 "85ac12bca244abda72bfb19fc44d27c8"
152 "1e1d92de284f4061edfd99280745ea6d"
153 "25"
154 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
155 "028180" // INTEGER length 0x80 (privateExponent) value...
156 "1be0f04d9cae3718691f035338308e91"
157 "564b55899ffb5084d2460e6630257e05"
158 "b3ceab02972dfabcd6ce5f6ee2589eb6"
159 "7911ed0fac16e43a444b8c861e544a05"
160 "93365772f8baf6b22fc9e3c5f1024b06"
161 "3ac080a7b2234cf8aee8f6c47bbf4fd3"
162 "ace7240290bef16c0b3f7f3cdd64ce3a"
163 "b5912cf6e32f39ab188358afcccd8081"
164 "0241" // INTEGER length 0x41 (prime1)
165 "00e4b49ef50f765d3b24dde01aceaaf1"
166 "30f2c76670a91a61ae08af497b4a82be"
167 "6dee8fcdd5e3f7ba1cfb1f0c926b88f8"
168 "8c92bfab137fba2285227b83c342ff7c"
169 "55"
170 "0241" // INTEGER length 0x41 (prime2)
171 "00ddabb5839c4c7f6bf3d4183231f005"
172 "b31aa58affdda5c79e4cce217f6bc930"
173 "dbe563d480706c24e9ebfcab28a6cdef"
174 "d324b77e1bf7251b709092c24ff501fd"
175 "91"
176 "0240" // INTEGER length 0x40 (exponent1)
177 "23d4340eda3445d8cd26c14411da6fdc"
178 "a63c1ccd4b80a98ad52b78cc8ad8beb2"
179 "842c1d280405bc2f6c1bea214a1d742a"
180 "b996b35b63a82a5e470fa88dbf823cdd"
181 "0240" // INTEGER length 0x40 (exponent2)
182 "1b7b57449ad30d1518249a5f56bb9829"
183 "4d4b6ac12ffc86940497a5a5837a6cf9"
184 "46262b494526d328c11e1126380fde04"
185 "c24f916dec250892db09a6d77cdba351"
186 "0240" // INTEGER length 0x40 (coefficient)
187 "7762cd8f4d050da56bd591adb515d24d"
188 "7ccd32cca0d05f866d583514bd7324d5"
189 "f33645e8ed8b4a1cb3cc4a1d67987399"
190 "f2a09f5b3fb68c88d5e5d90ac33492d6"
191 // } end SEQUENCE (PrivateKey)
192 // } end SEQUENCE (PrivateKeyInfo)
193);
Selene Huang31ab4042020-04-29 04:22:39 -0700194
Selene Huange5727e62021-04-13 22:41:20 -0700195/*
196 * DER-encoded PKCS#8 format RSA key. Generated using:
197 *
198 * openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt -outform der | hexdump -e '30/1 "%02X" "\n"'
199 */
David Drysdaled2cc8c22021-04-15 13:29:45 +0100200string rsa_2048_key = hex2str(
201 // RFC 5208 s5
202 "308204BD" // SEQUENCE length 0x4bd (PrivateKeyInfo) {
203 "020100" // INTEGER length 1 value 0x00 (version)
204 "300D" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
205 "0609" // OBJECT IDENTIFIER length 9 (algorithm)
206 "2A864886F70D010101" // 1.2.840.113549.1.1.1 (rsaEncryption)
207 "0500" // NULL (parameters)
208 // } end SEQUENCE (AlgorithmIdentifier)
209 "048204A7" // OCTET STRING length 0x25f (privateKey) holding...
210 // RFC 8017 A.1.2
211 "308204A3" // SEQUENCE length 0x4a3 (RSAPrivateKey) {
212 "020100" // INTEGER length 1 value 0x00 (version)
213 "02820101" // INTEGER length 0x101 value (modulus) ...
214 "00BEBC342B56D443B1299F9A6A7056E8"
215 "0A897E318476A5A18029E63B2ED739A6"
216 "1791D339F58DC763D9D14911F2EDEC38"
217 "3DEE11F6319B44510E7A3ECD9B79B973"
218 "82E49500ACF8117DC89CAF0E621F7775"
219 "6554A2FD4664BFE7AB8B59AB48340DBF"
220 "A27B93B5A81F6ECDEB02D0759307128D"
221 "F3E3BAD4055C8B840216DFAA5700670E"
222 "6C5126F0962FCB70FF308F25049164CC"
223 "F76CC2DA66A7DD9A81A714C2809D6918"
224 "6133D29D84568E892B6FFBF3199BDB14"
225 "383EE224407F190358F111A949552ABA"
226 "6714227D1BD7F6B20DD0CB88F9467B71"
227 "9339F33BFF35B3870B3F62204E4286B0"
228 "948EA348B524544B5F9838F29EE643B0"
229 "79EEF8A713B220D7806924CDF7295070"
230 "C5"
231 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
232 "02820100" // INTEGER length 0x100 (privateExponent) value...
233 "69F377F35F2F584EF075353CCD1CA997"
234 "38DB3DBC7C7FF35F9366CE176DFD1B13"
235 "5AB10030344ABF5FBECF1D4659FDEF1C"
236 "0FC430834BE1BE3911951377BB3D563A"
237 "2EA9CA8F4AD9C48A8CE6FD516A735C66"
238 "2686C7B4B3C09A7B8354133E6F93F790"
239 "D59EAEB92E84C9A4339302CCE28FDF04"
240 "CCCAFA7DE3F3A827D4F6F7D38E68B0EC"
241 "6AB706645BF074A4E4090D06FB163124"
242 "365FD5EE7A20D350E9958CC30D91326E"
243 "1B292E9EF5DB408EC42DAF737D201497"
244 "04D0A678A0FB5B5446863B099228A352"
245 "D604BA8091A164D01D5AB05397C71EAD"
246 "20BE2A08FC528FE442817809C787FEE4"
247 "AB97F97B9130D022153EDC6EB6CBE7B0"
248 "F8E3473F2E901209B5DB10F93604DB01"
249 "028181" // INTEGER length 0x81 (prime1)
250 "00E83C0998214941EA4F9293F1B77E2E"
251 "99E6CF305FAF358238E126124FEAF2EB"
252 "9724B2EA7B78E6032343821A80E55D1D"
253 "88FB12D220C3F41A56142FEC85796D19"
254 "17F1E8C774F142B67D3D6E7B7E6B4383"
255 "E94DB5929089DBB346D5BDAB40CC2D96"
256 "EE0409475E175C63BF78CFD744136740"
257 "838127EA723FF3FE7FA368C1311B4A4E"
258 "05"
259 "028181" // INTEGER length 0x81 (prime2)
260 "00D240FCC0F5D7715CDE21CB2DC86EA1"
261 "46132EA3B06F61FF2AF54BF38473F59D"
262 "ADCCE32B5F4CC32DD0BA6F509347B4B5"
263 "B1B58C39F95E4798CCBB43E83D0119AC"
264 "F532F359CA743C85199F0286610E2009"
265 "97D7312917179AC9B67558773212EC96"
266 "1E8BCE7A3CC809BC5486A96E4B0E6AF3"
267 "94D94E066A0900B7B70E82A44FB30053"
268 "C1"
269 "028181" // INTEGER length 0x81 (exponent1)
270 "00AD15DA1CBD6A492B66851BA8C316D3"
271 "8AB700E2CFDDD926A658003513C54BAA"
272 "152B30021D667D20078F500F8AD3E7F3"
273 "945D74A891ED1A28EAD0FEEAEC8C14A8"
274 "E834CF46A13D1378C99D18940823CFDD"
275 "27EC5810D59339E0C34198AC638E09C8"
276 "7CBB1B634A9864AE9F4D5EB2D53514F6"
277 "7B4CAEC048C8AB849A02E397618F3271"
278 "35"
279 "028180" // INTEGER length 0x80 (exponent2)
280 "1FA2C1A5331880A92D8F3E281C617108"
281 "BF38244F16E352E69ED417C7153F9EC3"
282 "18F211839C643DCF8B4DD67CE2AC312E"
283 "95178D5D952F06B1BF779F4916924B70"
284 "F582A23F11304E02A5E7565AE22A35E7"
285 "4FECC8B6FDC93F92A1A37703E4CF0E63"
286 "783BD02EB716A7ECBBFA606B10B74D01"
287 "579522E7EF84D91FC522292108D902C1"
288 "028180" // INTEGER length 0x80 (coefficient)
289 "796FE3825F9DCC85DF22D58690065D93"
290 "898ACD65C087BEA8DA3A63BF4549B795"
291 "E2CD0E3BE08CDEBD9FCF1720D9CDC507"
292 "0D74F40DED8E1102C52152A31B6165F8"
293 "3A6722AECFCC35A493D7634664B888A0"
294 "8D3EB034F12EA28BFEE346E205D33482"
295 "7F778B16ED40872BD29FCB36536B6E93"
296 "FFB06778696B4A9D81BB0A9423E63DE5"
297 // } end SEQUENCE (PrivateKey)
298 // } end SEQUENCE (PrivateKeyInfo)
299);
Selene Huange5727e62021-04-13 22:41:20 -0700300
David Drysdaled2cc8c22021-04-15 13:29:45 +0100301string ec_256_key = hex2str(
302 // RFC 5208 s5
303 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
304 "020100" // INTEGER length 1 value 0 (version)
305 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
306 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
307 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
308 "0608" // OBJECT IDENTIFIER length 8 (param)
309 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
310 // } end SEQUENCE (AlgorithmIdentifier)
311 "046d" // OCTET STRING length 0x6d (privateKey) holding...
312 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
313 "020101" // INTEGER length 1 value 1 (version)
314 "0420" // OCTET STRING length 0x20 (privateKey)
315 "737c2ecd7b8d1940bf2930aa9b4ed3ff"
316 "941eed09366bc03299986481f3a4d859"
317 "a144" // TAG [1] len 0x44 (publicKey) {
318 "03420004bf85d7720d07c25461683bc6"
319 "48b4778a9a14dd8a024e3bdd8c7ddd9a"
320 "b2b528bbc7aa1b51f14ebbbb0bd0ce21"
321 "bcc41c6eb00083cf3376d11fd44949e0"
322 "b2183bfe"
323 // } end SEQUENCE (ECPrivateKey)
324 // } end SEQUENCE (PrivateKeyInfo)
325);
Selene Huang31ab4042020-04-29 04:22:39 -0700326
David Drysdaled2cc8c22021-04-15 13:29:45 +0100327string ec_521_key = hex2str(
328 // RFC 5208 s5
329 "3081EE" // SEQUENCE length 0xee (PrivateKeyInfo) {
330 "020100" // INTEGER length 1 value 0 (version)
331 "3010" // SEQUENCE length 0x10 (AlgorithmIdentifier) {
332 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
333 "2A8648CE3D0201" // 1.2.840.10045.2.1 (ecPublicKey)
334 "0605" // OBJECT IDENTIFIER length 5 (param)
335 "2B81040023" // 1.3.132.0.35 (secp521r1)
336 // } end SEQUENCE (AlgorithmIdentifier)
337 "0481D6" // OCTET STRING length 0xd6 (privateKey) holding...
338 "3081D3" // SEQUENCE length 0xd3 (ECPrivateKey)
339 "020101" // INTEGER length 1 value 1 (version)
340 "0442" // OCTET STRING length 0x42 (privateKey)
341 "0011458C586DB5DAA92AFAB03F4FE46A"
342 "A9D9C3CE9A9B7A006A8384BEC4C78E8E"
343 "9D18D7D08B5BCFA0E53C75B064AD51C4"
344 "49BAE0258D54B94B1E885DED08ED4FB2"
345 "5CE9"
346 "A18189" // TAG [1] len 0x89 (publicKey) {
347 "03818600040149EC11C6DF0FA122C6A9"
348 "AFD9754A4FA9513A627CA329E349535A"
349 "5629875A8ADFBE27DCB932C051986377"
350 "108D054C28C6F39B6F2C9AF81802F9F3"
351 "26B842FF2E5F3C00AB7635CFB36157FC"
352 "0882D574A10D839C1A0C049DC5E0D775"
353 "E2EE50671A208431BB45E78E70BEFE93"
354 "0DB34818EE4D5C26259F5C6B8E28A652"
355 "950F9F88D7B4B2C9D9"
356 // } end SEQUENCE (ECPrivateKey)
357 // } end SEQUENCE (PrivateKeyInfo)
358);
Selene Huang31ab4042020-04-29 04:22:39 -0700359
David Drysdaled2cc8c22021-04-15 13:29:45 +0100360string ec_256_key_rfc5915 = hex2str(
361 // RFC 5208 s5
362 "308193" // SEQUENCE length 0x93 (PrivateKeyInfo) {
363 "020100" // INTEGER length 1 value 0 (version)
364 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
365 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
366 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
367 "0608" // OBJECT IDENTIFIER length 8 (param)
368 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
369 // } end SEQUENCE (AlgorithmIdentifier)
370 "0479" // OCTET STRING length 0x79 (privateKey) holding...
371 // RFC 5915 s3
372 "3077" // SEQUENCE length 0x77 (ECPrivateKey)
373 "020101" // INTEGER length 1 value 1 (version)
374 "0420" // OCTET STRING length 0x42 (privateKey)
375 "782370a8c8ce5537baadd04dcff079c8"
376 "158cfa9c67b818b38e8d21c9fa750c1d"
377 "a00a" // TAG [0] length 0xa (parameters)
378 "0608" // OBJECT IDENTIFIER length 8
379 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
380 // } end TAG [0]
381 "a144" // TAG [1] length 0x44 (publicKey) {
382 "0342" // BIT STRING length 0x42
383 "00" // no pad bits
384 "04e2cc561ee701da0ad0ef0d176bb0c9"
385 "19d42e79c393fdc1bd6c4010d85cf2cf"
386 "8e68c905464666f98dad4f01573ba810"
387 "78b3428570a439ba3229fbc026c55068"
388 "2f"
389 // } end SEQUENCE (ECPrivateKey)
390 // } end SEQUENCE (PrivateKeyInfo)
391);
Selene Huang31ab4042020-04-29 04:22:39 -0700392
David Drysdaled2cc8c22021-04-15 13:29:45 +0100393string ec_256_key_sec1 = hex2str(
394 // RFC 5208 s5
395 "308187" // SEQUENCE length 0x87 (PrivateKeyInfo) {
396 "020100" // INTEGER length 1 value 0 (version)
397 "3013" // SEQUENCE length 0x13 (AlgorithmIdentifier) {
398 "0607" // OBJECT IDENTIFIER length 7 (algorithm)
399 "2a8648ce3d0201" // 1.2.840.10045.2.1 (ecPublicKey)
400 "0608" // OBJECT IDENTIFIER length 8 (param)
401 "2a8648ce3d030107" // 1.2.840.10045.3.1.7 (secp256r1)
402 // } end SEQUENCE (AlgorithmIdentifier)
403 "046d" // OCTET STRING length 0x6d (privateKey) holding...
404 // SEC1-v2 C.4
405 "306b" // SEQUENCE length 0x6b (ECPrivateKey)
406 "020101" // INTEGER length 1 value 0x01 (version)
407 "0420" // OCTET STRING length 0x20 (privateKey)
408 "782370a8c8ce5537baadd04dcff079c8"
409 "158cfa9c67b818b38e8d21c9fa750c1d"
410 "a144" // TAG [1] length 0x44 (publicKey) {
411 "0342" // BIT STRING length 0x42
412 "00" // no pad bits
413 "04e2cc561ee701da0ad0ef0d176bb0c9"
414 "19d42e79c393fdc1bd6c4010d85cf2cf"
415 "8e68c905464666f98dad4f01573ba810"
416 "78b3428570a439ba3229fbc026c55068"
417 "2f"
418 // } end TAG [1] (publicKey)
419 // } end SEQUENCE (PrivateKeyInfo)
420);
Selene Huang31ab4042020-04-29 04:22:39 -0700421
David Drysdale42fe1892021-10-14 14:43:46 +0100422/**
423 * Ed25519 key pair generated as follows:
424 * ```
425 * % openssl req -x509 -newkey ED25519 -days 700 -nodes \
426 * -keyout ed25519_priv.key -out ed25519.pem * -subj "/CN=fake.ed25519.com"
427 * Generating a ED25519 private key writing new private key to
428 * 'ed25519_priv.key'
429 * -----
430 * % cat ed25519_priv.key
431 * -----BEGIN PRIVATE KEY-----
432 * MC4CAQAwBQYDK2VwBCIEIKl3A5quNywcj1P+0XI9SBalFPIvO52NxceMLRH6dVmR
433 * -----END PRIVATE KEY-----
434 * % der2ascii -pem -i ed25519_priv.key
435 * SEQUENCE {
436 * INTEGER { 0 }
437 * SEQUENCE {
438 * # ed25519
439 * OBJECT_IDENTIFIER { 1.3.101.112 }
440 * }
441 * OCTET_STRING {
442 * OCTET_STRING { `a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991` }
443 * }
444 * }
445 * % cat ed25519.pem
446 * -----BEGIN CERTIFICATE-----
447 * MIIBSjCB/aADAgECAhR0Jron3eKcdgqyecv/eEfGWAzn8DAFBgMrZXAwGzEZMBcG
448 * A1UEAwwQZmFrZS5lZDI1NTE5LmNvbTAeFw0yMTEwMjAwODI3NDJaFw0yMzA5MjAw
449 * ODI3NDJaMBsxGTAXBgNVBAMMEGZha2UuZWQyNTUxOS5jb20wKjAFBgMrZXADIQDv
450 * uwHz+3TaQ69D2digxlz0fFfsZg0rPqgQae3jBPRWkaNTMFEwHQYDVR0OBBYEFN9O
451 * od30SY4JTs66ZR403UPya+iXMB8GA1UdIwQYMBaAFN9Ood30SY4JTs66ZR403UPy
452 * a+iXMA8GA1UdEwEB/wQFMAMBAf8wBQYDK2VwA0EAKjVrYQjuE/gEL2j/ABpDbFjV
453 * Ilg5tJ6MN/P3psAv3Cs7f0X1lFqdlt15nJ/6aj2cmGCwNRXt5wcyYDKNu+v2Dw==
454 * -----END CERTIFICATE-----
455 * % openssl x509 -in ed25519.pem -text -noout
456 * Certificate:
457 * Data:
458 * Version: 3 (0x2)
459 * Serial Number:
460 * 74:26:ba:27:dd:e2:9c:76:0a:b2:79:cb:ff:78:47:c6:58:0c:e7:f0
461 * Signature Algorithm: ED25519
462 * Issuer: CN = fake.ed25519.com
463 * Validity
464 * Not Before: Oct 20 08:27:42 2021 GMT
465 * Not After : Sep 20 08:27:42 2023 GMT
466 * Subject: CN = fake.ed25519.com
467 * Subject Public Key Info:
468 * Public Key Algorithm: ED25519
469 * ED25519 Public-Key:
470 * pub:
471 * ef:bb:01:f3:fb:74:da:43:af:43:d9:d8:a0:c6:5c:
472 * f4:7c:57:ec:66:0d:2b:3e:a8:10:69:ed:e3:04:f4:
473 * 56:91
474 * X509v3 extensions:
475 * X509v3 Subject Key Identifier:
476 * DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
477 * X509v3 Authority Key Identifier:
478 * keyid:DF:4E:A1:DD:F4:49:8E:09:4E:CE:BA:65:1E:34:DD:43:F2:6B:E8:97
479 *
480 * X509v3 Basic Constraints: critical
481 * CA:TRUE
482 * Signature Algorithm: ED25519
483 * 2a:35:6b:61:08:ee:13:f8:04:2f:68:ff:00:1a:43:6c:58:d5:
484 * 22:58:39:b4:9e:8c:37:f3:f7:a6:c0:2f:dc:2b:3b:7f:45:f5:
485 * 94:5a:9d:96:dd:79:9c:9f:fa:6a:3d:9c:98:60:b0:35:15:ed:
486 * e7:07:32:60:32:8d:bb:eb:f6:0f
487 * ```
488 */
489string ed25519_key = hex2str("a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991");
490string ed25519_pkcs8_key = hex2str(
491 // RFC 5208 s5
492 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
493 "0201" // INTEGER length 1 (Version)
494 "00" // version 0
495 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
496 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
497 "2b6570" // 1.3.101.112 (id-Ed125519 RFC 8410 s3)
498 // } end SEQUENCE (AlgorithmIdentifier)
499 "0422" // OCTET STRING length 0x22 (PrivateKey)
500 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
501 "a977039aae372c1c8f53fed1723d4816a514f22f3b9d8dc5c78c2d11fa755991"
502 // } end SEQUENCE (PrivateKeyInfo)
503);
504string ed25519_pubkey = hex2str("efbb01f3fb74da43af43d9d8a0c65cf47c57ec660d2b3ea81069ede304f45691");
505
506/**
507 * X25519 key pair generated as follows:
508 * ```
509 * % openssl genpkey -algorithm X25519 > x25519_priv.key
510 * % cat x25519_priv.key
511 * -----BEGIN PRIVATE KEY-----
512 * MC4CAQAwBQYDK2VuBCIEIGgPwF3NLwQx/Sfwr2nfJvXitwlDNh3Skzh+TISN/y1C
513 * -----END PRIVATE KEY-----
514 * % der2ascii -pem -i x25519_priv.key
515 * SEQUENCE {
516 * INTEGER { 0 }
517 * SEQUENCE {
518 * # x25519
519 * OBJECT_IDENTIFIER { 1.3.101.110 }
520 * }
521 * OCTET_STRING {
522 * OCTET_STRING { `680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42` }
523 * }
524 * }
525 * ```
526 */
527
528string x25519_key = hex2str("680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
529string x25519_pkcs8_key = hex2str(
530 // RFC 5208 s5
531 "302e" // SEQUENCE length 0x2e (PrivateKeyInfo) {
532 "0201" // INTEGER length 1 (Version)
533 "00" // version 0
534 "3005" // SEQUENCE length 05 (AlgorithmIdentifier) {
535 "0603" // OBJECT IDENTIFIER length 3 (algorithm)
536 "2b656e" // 1.3.101.110 (id-X125519 RFC 8410 s3)
537 "0422" // OCTET STRING length 0x22 (PrivateKey)
538 "0420" // OCTET STRING length 0x20 (RFC 8410 s7)
539 "680fc05dcd2f0431fd27f0af69df26f5e2b70943361dd293387e4c848dff2d42");
540string x25519_pubkey = hex2str("be46925a857f17831d6d454b9d3d36a4a30166edf80eb82b684661c3e258f768");
541
Selene Huang31ab4042020-04-29 04:22:39 -0700542struct RSA_Delete {
543 void operator()(RSA* p) { RSA_free(p); }
544};
545
Selene Huang31ab4042020-04-29 04:22:39 -0700546std::string make_string(const uint8_t* data, size_t length) {
547 return std::string(reinterpret_cast<const char*>(data), length);
548}
549
550template <size_t N>
551std::string make_string(const uint8_t (&a)[N]) {
552 return make_string(a, N);
553}
554
555class AidlBuf : public vector<uint8_t> {
556 typedef vector<uint8_t> super;
557
558 public:
559 AidlBuf() {}
560 AidlBuf(const super& other) : super(other) {}
561 AidlBuf(super&& other) : super(std::move(other)) {}
562 explicit AidlBuf(const std::string& other) : AidlBuf() { *this = other; }
563
564 AidlBuf& operator=(const super& other) {
565 super::operator=(other);
566 return *this;
567 }
568
569 AidlBuf& operator=(super&& other) {
570 super::operator=(std::move(other));
571 return *this;
572 }
573
574 AidlBuf& operator=(const string& other) {
575 resize(other.size());
576 for (size_t i = 0; i < other.size(); ++i) {
577 (*this)[i] = static_cast<uint8_t>(other[i]);
578 }
579 return *this;
580 }
581
582 string to_string() const { return string(reinterpret_cast<const char*>(data()), size()); }
583};
584
David Drysdale4dc01072021-04-01 12:17:35 +0100585string device_suffix(const string& name) {
586 size_t pos = name.find('/');
587 if (pos == string::npos) {
588 return name;
589 }
590 return name.substr(pos + 1);
591}
592
593bool matching_rp_instance(const string& km_name,
594 std::shared_ptr<IRemotelyProvisionedComponent>* rp) {
595 string km_suffix = device_suffix(km_name);
596
597 vector<string> rp_names =
598 ::android::getAidlHalInstanceNames(IRemotelyProvisionedComponent::descriptor);
599 for (const string& rp_name : rp_names) {
600 // If the suffix of the RemotelyProvisionedComponent instance equals the suffix of the
601 // KeyMint instance, assume they match.
602 if (device_suffix(rp_name) == km_suffix && AServiceManager_isDeclared(rp_name.c_str())) {
603 ::ndk::SpAIBinder binder(AServiceManager_waitForService(rp_name.c_str()));
604 *rp = IRemotelyProvisionedComponent::fromBinder(binder);
605 return true;
606 }
607 }
608 return false;
609}
610
Selene Huang31ab4042020-04-29 04:22:39 -0700611} // namespace
612
613class NewKeyGenerationTest : public KeyMintAidlTestBase {
614 protected:
Shawn Willden7f424372021-01-10 18:06:50 -0700615 void CheckBaseParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000616 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
Selene Huang31ab4042020-04-29 04:22:39 -0700617 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
Selene Huang31ab4042020-04-29 04:22:39 -0700618
Selene Huang31ab4042020-04-29 04:22:39 -0700619 // Check that some unexpected tags/values are NOT present.
620 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
621 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
David Drysdale7de9feb2021-03-05 14:56:19 +0000622 }
623
624 void CheckSymmetricParams(const vector<KeyCharacteristics>& keyCharacteristics) {
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000625 AuthorizationSet auths = CheckCommonParams(keyCharacteristics, KeyOrigin::GENERATED);
David Drysdale7de9feb2021-03-05 14:56:19 +0000626 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::ENCRYPT));
627 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
628
629 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
David Drysdale7de9feb2021-03-05 14:56:19 +0000630 }
631
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000632 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics,
633 const KeyOrigin expectedKeyOrigin) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000634 // TODO(swillden): Distinguish which params should be in which auth list.
635 AuthorizationSet auths;
636 for (auto& entry : keyCharacteristics) {
637 auths.push_back(AuthorizationSet(entry.authorizations));
638 }
Subrahmanyaman812a9d12022-05-04 02:11:04 +0000639 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, expectedKeyOrigin));
David Drysdale7de9feb2021-03-05 14:56:19 +0000640
641 // Verify that App data, ROT and auth timeout are NOT included.
642 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
643 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700644 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
645
David Drysdaled2cc8c22021-04-15 13:29:45 +0100646 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
647 // never adds it.
648 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
649
David Drysdale7de9feb2021-03-05 14:56:19 +0000650 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700651 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000652 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700653 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700654 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000655 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700656 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000657
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000658 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100659 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
660 EXPECT_TRUE(vendor_pl);
661 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000662
663 // Should include boot patchlevel (but there are some test scenarios where this is not
664 // possible).
665 if (check_boot_pl) {
666 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
667 EXPECT_TRUE(boot_pl);
668 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100669
David Drysdale7de9feb2021-03-05 14:56:19 +0000670 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700671 }
672};
673
674/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000675 * NewKeyGenerationTest.Aes
676 *
677 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
678 * have correct characteristics.
679 */
680TEST_P(NewKeyGenerationTest, Aes) {
681 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
682 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
683 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
684 SCOPED_TRACE(testing::Message()
685 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
686 vector<uint8_t> key_blob;
687 vector<KeyCharacteristics> key_characteristics;
688 auto builder = AuthorizationSetBuilder()
689 .AesEncryptionKey(key_size)
690 .BlockMode(block_mode)
691 .Padding(padding_mode)
692 .SetDefaultValidity();
693 if (block_mode == BlockMode::GCM) {
694 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
695 }
696 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
697
698 EXPECT_GT(key_blob.size(), 0U);
699 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100700 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000701
702 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
703
704 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
705 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
706 << "Key size " << key_size << "missing";
707
708 CheckedDeleteKey(&key_blob);
709 }
710 }
711 }
712}
713
714/*
715 * NewKeyGenerationTest.AesInvalidSize
716 *
717 * Verifies that specifying an invalid key size for AES key generation returns
718 * UNSUPPORTED_KEY_SIZE.
719 */
720TEST_P(NewKeyGenerationTest, AesInvalidSize) {
721 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
722 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
723 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
724 SCOPED_TRACE(testing::Message()
725 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
726 vector<uint8_t> key_blob;
727 vector<KeyCharacteristics> key_characteristics;
728 auto builder = AuthorizationSetBuilder()
729 .AesEncryptionKey(key_size)
730 .BlockMode(block_mode)
731 .Padding(padding_mode)
732 .SetDefaultValidity();
733 if (block_mode == BlockMode::GCM) {
734 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
735 }
736 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
737 GenerateKey(builder, &key_blob, &key_characteristics));
738 }
739 }
740 }
741
742 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
743 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100744 SCOPED_TRACE(testing::Message() << "AES-unknown-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000745 vector<uint8_t> key_blob;
746 vector<KeyCharacteristics> key_characteristics;
747 // No key size specified
748 auto builder = AuthorizationSetBuilder()
749 .Authorization(TAG_ALGORITHM, Algorithm::AES)
750 .BlockMode(block_mode)
751 .Padding(padding_mode)
752 .SetDefaultValidity();
753 if (block_mode == BlockMode::GCM) {
754 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
755 }
756 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
757 GenerateKey(builder, &key_blob, &key_characteristics));
758 }
759 }
760}
761
762/*
763 * NewKeyGenerationTest.AesInvalidPadding
764 *
765 * Verifies that specifying an invalid padding on AES keys gives a failure
766 * somewhere along the way.
767 */
768TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
769 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
770 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
771 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
772 SCOPED_TRACE(testing::Message()
773 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000774 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800775 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000776 .AesEncryptionKey(key_size)
777 .BlockMode(block_mode)
778 .Padding(padding_mode)
779 .SetDefaultValidity();
780 if (block_mode == BlockMode::GCM) {
781 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
782 }
783
Tommy Chiu3950b452021-05-03 22:01:46 +0800784 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000785 if (result == ErrorCode::OK) {
786 // Key creation was OK but has generated a key that cannot be used.
787 auto params =
788 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800789 if (block_mode == BlockMode::GCM) {
790 params.Authorization(TAG_MAC_LENGTH, 128);
791 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000792 auto result = Begin(KeyPurpose::ENCRYPT, params);
793 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100794 result == ErrorCode::INVALID_KEY_BLOB)
795 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000796 } else {
797 // The KeyMint implementation detected that the generated key
798 // is unusable.
799 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
800 }
801 }
802 }
803 }
804}
805
806/*
807 * NewKeyGenerationTest.AesGcmMissingMinMac
808 *
809 * Verifies that specifying an invalid key size for AES key generation returns
810 * UNSUPPORTED_KEY_SIZE.
811 */
812TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
813 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
814 BlockMode block_mode = BlockMode::GCM;
815 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
816 SCOPED_TRACE(testing::Message()
817 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
818 vector<uint8_t> key_blob;
819 vector<KeyCharacteristics> key_characteristics;
820 // No MIN_MAC_LENGTH provided.
821 auto builder = AuthorizationSetBuilder()
822 .AesEncryptionKey(key_size)
823 .BlockMode(block_mode)
824 .Padding(padding_mode)
825 .SetDefaultValidity();
826 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
827 GenerateKey(builder, &key_blob, &key_characteristics));
828 }
829 }
830}
831
832/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100833 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
834 *
835 * Verifies that specifying an invalid min MAC size for AES key generation returns
836 * UNSUPPORTED_MIN_MAC_LENGTH.
837 */
838TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
839 for (size_t min_mac_len : {88, 136}) {
840 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
841 BlockMode block_mode = BlockMode::GCM;
842 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
843 SCOPED_TRACE(testing::Message()
844 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
845 vector<uint8_t> key_blob;
846 vector<KeyCharacteristics> key_characteristics;
847 auto builder = AuthorizationSetBuilder()
848 .AesEncryptionKey(key_size)
849 .BlockMode(block_mode)
850 .Padding(padding_mode)
851 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
852 .SetDefaultValidity();
853 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
854 GenerateKey(builder, &key_blob, &key_characteristics));
855 }
856 }
857 }
858}
859
860/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000861 * NewKeyGenerationTest.TripleDes
862 *
863 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
864 * have correct characteristics.
865 */
866TEST_P(NewKeyGenerationTest, TripleDes) {
867 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
868 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
869 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
870 SCOPED_TRACE(testing::Message()
871 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
872 vector<uint8_t> key_blob;
873 vector<KeyCharacteristics> key_characteristics;
874 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
875 .TripleDesEncryptionKey(key_size)
876 .BlockMode(block_mode)
877 .Padding(padding_mode)
878 .Authorization(TAG_NO_AUTH_REQUIRED)
879 .SetDefaultValidity(),
880 &key_blob, &key_characteristics));
881
882 EXPECT_GT(key_blob.size(), 0U);
883 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100884 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000885
886 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
887
888 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
889 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
890 << "Key size " << key_size << "missing";
891
892 CheckedDeleteKey(&key_blob);
893 }
894 }
895 }
896}
897
898/*
899 * NewKeyGenerationTest.TripleDesWithAttestation
900 *
901 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
902 * have correct characteristics.
903 *
904 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
905 * put in a certificate) but which isn't an error.
906 */
907TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
908 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
909 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
910 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
911 SCOPED_TRACE(testing::Message()
912 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
913
914 auto challenge = "hello";
915 auto app_id = "foo";
916
917 vector<uint8_t> key_blob;
918 vector<KeyCharacteristics> key_characteristics;
919 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
920 .TripleDesEncryptionKey(key_size)
921 .BlockMode(block_mode)
922 .Padding(padding_mode)
923 .Authorization(TAG_NO_AUTH_REQUIRED)
924 .AttestationChallenge(challenge)
925 .AttestationApplicationId(app_id)
926 .SetDefaultValidity(),
927 &key_blob, &key_characteristics));
928
929 EXPECT_GT(key_blob.size(), 0U);
930 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100931 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000932
933 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
934
935 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
936 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
937 << "Key size " << key_size << "missing";
938
939 CheckedDeleteKey(&key_blob);
940 }
941 }
942 }
943}
944
945/*
946 * NewKeyGenerationTest.TripleDesInvalidSize
947 *
948 * Verifies that specifying an invalid key size for 3-DES key generation returns
949 * UNSUPPORTED_KEY_SIZE.
950 */
951TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
952 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
953 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
954 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
955 SCOPED_TRACE(testing::Message()
956 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
957 vector<uint8_t> key_blob;
958 vector<KeyCharacteristics> key_characteristics;
959 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
960 GenerateKey(AuthorizationSetBuilder()
961 .TripleDesEncryptionKey(key_size)
962 .BlockMode(block_mode)
963 .Padding(padding_mode)
964 .Authorization(TAG_NO_AUTH_REQUIRED)
965 .SetDefaultValidity(),
966 &key_blob, &key_characteristics));
967 }
968 }
969 }
970
971 // Omitting the key size fails.
972 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
973 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
974 SCOPED_TRACE(testing::Message()
975 << "3DES-default-" << block_mode << "-" << padding_mode);
976 vector<uint8_t> key_blob;
977 vector<KeyCharacteristics> key_characteristics;
978 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
979 GenerateKey(AuthorizationSetBuilder()
980 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
981 .BlockMode(block_mode)
982 .Padding(padding_mode)
983 .Authorization(TAG_NO_AUTH_REQUIRED)
984 .SetDefaultValidity(),
985 &key_blob, &key_characteristics));
986 }
987 }
988}
989
990/*
Selene Huang31ab4042020-04-29 04:22:39 -0700991 * NewKeyGenerationTest.Rsa
992 *
993 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
994 * have correct characteristics.
995 */
996TEST_P(NewKeyGenerationTest, Rsa) {
997 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +0100998 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -0700999 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001000 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1002 .RsaSigningKey(key_size, 65537)
1003 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001004 .Padding(PaddingMode::NONE)
1005 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001006 &key_blob, &key_characteristics));
1007
1008 ASSERT_GT(key_blob.size(), 0U);
1009 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001010 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001011
Shawn Willden7f424372021-01-10 18:06:50 -07001012 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001013
1014 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1015 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1016 << "Key size " << key_size << "missing";
1017 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1018
1019 CheckedDeleteKey(&key_blob);
1020 }
1021}
1022
1023/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001024 * NewKeyGenerationTest.RsaWithMissingValidity
1025 *
1026 * Verifies that keymint returns an error while generating asymmetric key
1027 * without providing NOT_BEFORE and NOT_AFTER parameters.
1028 */
1029TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001030 if (AidlVersion() < 2) {
1031 /*
1032 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1033 * specified for asymmetric key generation. However, this was not
1034 * checked at the time so we can only be strict about checking this for
1035 * implementations of KeyMint version 2 and above.
1036 */
1037 GTEST_SKIP() << "Validity strict since KeyMint v2";
1038 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001039 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1040 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1041 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1042
1043 vector<uint8_t> key_blob;
1044 vector<KeyCharacteristics> key_characteristics;
1045 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1046 GenerateKey(AuthorizationSetBuilder()
1047 .RsaSigningKey(2048, 65537)
1048 .Digest(Digest::NONE)
1049 .Padding(PaddingMode::NONE)
1050 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1051 kUndefinedExpirationDateTime),
1052 &key_blob, &key_characteristics));
1053
1054 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1055 GenerateKey(AuthorizationSetBuilder()
1056 .RsaSigningKey(2048, 65537)
1057 .Digest(Digest::NONE)
1058 .Padding(PaddingMode::NONE)
1059 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1060 &key_blob, &key_characteristics));
1061}
1062
1063/*
Qi Wud22ec842020-11-26 13:27:53 +08001064 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001065 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001066 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1067 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001068 */
1069TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001070 auto challenge = "hello";
1071 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001072
Selene Huang6e46f142021-04-20 19:20:11 -07001073 auto subject = "cert subj 2";
1074 vector<uint8_t> subject_der(make_name_from_str(subject));
1075
1076 uint64_t serial_int = 66;
1077 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1078
Selene Huang4f64c222021-04-13 19:54:36 -07001079 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001080 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001081 vector<uint8_t> key_blob;
1082 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001083 auto builder = AuthorizationSetBuilder()
1084 .RsaSigningKey(key_size, 65537)
1085 .Digest(Digest::NONE)
1086 .Padding(PaddingMode::NONE)
1087 .AttestationChallenge(challenge)
1088 .AttestationApplicationId(app_id)
1089 .Authorization(TAG_NO_AUTH_REQUIRED)
1090 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1091 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1092 .SetDefaultValidity();
1093
1094 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001095 // Strongbox may not support factory provisioned attestation key.
1096 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001097 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1098 result = GenerateKeyWithSelfSignedAttestKey(
1099 AuthorizationSetBuilder()
1100 .RsaKey(key_size, 65537)
1101 .AttestKey()
1102 .SetDefaultValidity(), /* attest key params */
1103 builder, &key_blob, &key_characteristics);
1104 }
subrahmanyaman05642492022-02-05 07:10:56 +00001105 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001106 ASSERT_EQ(ErrorCode::OK, result);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001107 ASSERT_GT(key_blob.size(), 0U);
1108 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001109 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001110
1111 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1112
1113 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1114 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1115 << "Key size " << key_size << "missing";
1116 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1117
David Drysdalea8a888e2022-06-08 12:43:56 +01001118 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001119 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001120 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001121
1122 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1123 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001124 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001125 sw_enforced, hw_enforced, SecLevel(),
1126 cert_chain_[0].encodedCertificate));
1127
1128 CheckedDeleteKey(&key_blob);
1129 }
1130}
1131
1132/*
David Drysdale4dc01072021-04-01 12:17:35 +01001133 * NewKeyGenerationTest.RsaWithRpkAttestation
1134 *
1135 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
1136 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +01001137 *
1138 * This test is disabled because the KeyMint specification does not require that implementations
1139 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
1140 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +01001141 */
David Drysdale0fce69d2021-04-13 17:22:13 +01001142TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +01001143 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1144 // instance.
1145 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1146 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1147 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1148
1149 // Generate a P-256 keypair to use as an attestation key.
1150 MacedPublicKey macedPubKey;
1151 std::vector<uint8_t> privateKeyBlob;
1152 auto status =
1153 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1154 ASSERT_TRUE(status.isOk());
1155 vector<uint8_t> coseKeyData;
1156 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1157
1158 AttestationKey attestation_key;
1159 attestation_key.keyBlob = std::move(privateKeyBlob);
1160 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1161
1162 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001163 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdale4dc01072021-04-01 12:17:35 +01001164 auto challenge = "hello";
1165 auto app_id = "foo";
1166
1167 vector<uint8_t> key_blob;
1168 vector<KeyCharacteristics> key_characteristics;
1169 ASSERT_EQ(ErrorCode::OK,
1170 GenerateKey(AuthorizationSetBuilder()
1171 .RsaSigningKey(key_size, 65537)
1172 .Digest(Digest::NONE)
1173 .Padding(PaddingMode::NONE)
1174 .AttestationChallenge(challenge)
1175 .AttestationApplicationId(app_id)
1176 .Authorization(TAG_NO_AUTH_REQUIRED)
1177 .SetDefaultValidity(),
1178 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1179
1180 ASSERT_GT(key_blob.size(), 0U);
1181 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001182 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001183
1184 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1185
1186 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1187 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1188 << "Key size " << key_size << "missing";
1189 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1190
1191 // Attestation by itself is not valid (last entry is not self-signed).
1192 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1193
1194 // The signature over the attested key should correspond to the P256 public key.
David Drysdalea8a888e2022-06-08 12:43:56 +01001195 ASSERT_GT(cert_chain_.size(), 0);
David Drysdale4dc01072021-04-01 12:17:35 +01001196 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1197 ASSERT_TRUE(key_cert.get());
1198 EVP_PKEY_Ptr signing_pubkey;
1199 p256_pub_key(coseKeyData, &signing_pubkey);
1200 ASSERT_TRUE(signing_pubkey.get());
1201
1202 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1203 << "Verification of attested certificate failed "
1204 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1205
1206 CheckedDeleteKey(&key_blob);
1207 }
1208}
1209
1210/*
Selene Huang4f64c222021-04-13 19:54:36 -07001211 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1212 *
1213 * Verifies that keymint attestation for RSA encryption keys with challenge and
1214 * app id is also successful.
1215 */
1216TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1217 auto key_size = 2048;
1218 auto challenge = "hello";
1219 auto app_id = "foo";
1220
Selene Huang6e46f142021-04-20 19:20:11 -07001221 auto subject = "subj 2";
1222 vector<uint8_t> subject_der(make_name_from_str(subject));
1223
1224 uint64_t serial_int = 111166;
1225 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1226
Selene Huang4f64c222021-04-13 19:54:36 -07001227 vector<uint8_t> key_blob;
1228 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001229 auto builder = AuthorizationSetBuilder()
1230 .RsaEncryptionKey(key_size, 65537)
1231 .Padding(PaddingMode::NONE)
1232 .AttestationChallenge(challenge)
1233 .AttestationApplicationId(app_id)
1234 .Authorization(TAG_NO_AUTH_REQUIRED)
1235 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1236 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1237 .SetDefaultValidity();
1238
1239 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001240 // Strongbox may not support factory provisioned attestation key.
1241 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001242 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1243 result = GenerateKeyWithSelfSignedAttestKey(
1244 AuthorizationSetBuilder()
1245 .RsaKey(key_size, 65537)
1246 .AttestKey()
1247 .SetDefaultValidity(), /* attest key params */
1248 builder, &key_blob, &key_characteristics);
1249 }
subrahmanyaman05642492022-02-05 07:10:56 +00001250 }
1251 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001252
1253 ASSERT_GT(key_blob.size(), 0U);
1254 AuthorizationSet auths;
1255 for (auto& entry : key_characteristics) {
1256 auths.push_back(AuthorizationSet(entry.authorizations));
1257 }
1258
1259 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1260 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1261
1262 // Verify that App data and ROT are NOT included.
1263 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1264 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1265
1266 // Check that some unexpected tags/values are NOT present.
1267 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1268 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1269
1270 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1271
1272 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1273 ASSERT_TRUE(os_ver);
1274 EXPECT_EQ(*os_ver, os_version());
1275
1276 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1277
1278 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1279 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1280 << "Key size " << key_size << "missing";
1281 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1282
David Drysdalea8a888e2022-06-08 12:43:56 +01001283 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001284 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001285 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001286
1287 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1288 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001289 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001290 sw_enforced, hw_enforced, SecLevel(),
1291 cert_chain_[0].encodedCertificate));
1292
1293 CheckedDeleteKey(&key_blob);
1294}
1295
1296/*
1297 * NewKeyGenerationTest.RsaWithSelfSign
1298 *
1299 * Verifies that attesting to RSA key generation is successful, and returns
1300 * self signed certificate if no challenge is provided. And signing etc
1301 * works as expected.
1302 */
1303TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001304 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1305 vector<uint8_t> subject_der(make_name_from_str(subject));
1306
1307 uint64_t serial_int = 0;
1308 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1309
Selene Huang4f64c222021-04-13 19:54:36 -07001310 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001311 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang4f64c222021-04-13 19:54:36 -07001312 vector<uint8_t> key_blob;
1313 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001314 ASSERT_EQ(ErrorCode::OK,
1315 GenerateKey(AuthorizationSetBuilder()
1316 .RsaSigningKey(key_size, 65537)
1317 .Digest(Digest::NONE)
1318 .Padding(PaddingMode::NONE)
1319 .Authorization(TAG_NO_AUTH_REQUIRED)
1320 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1321 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1322 .SetDefaultValidity(),
1323 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001324
1325 ASSERT_GT(key_blob.size(), 0U);
1326 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001327 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001328
1329 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1330
1331 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1332 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1333 << "Key size " << key_size << "missing";
1334 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1335
David Drysdalea8a888e2022-06-08 12:43:56 +01001336 ASSERT_EQ(cert_chain_.size(), 1);
Selene Huang6e46f142021-04-20 19:20:11 -07001337 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001338 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang4f64c222021-04-13 19:54:36 -07001339
1340 CheckedDeleteKey(&key_blob);
1341 }
1342}
1343
1344/*
1345 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1346 *
1347 * Verifies that attesting to RSA checks for missing app ID.
1348 */
1349TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1350 auto challenge = "hello";
1351 vector<uint8_t> key_blob;
1352 vector<KeyCharacteristics> key_characteristics;
1353
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001354 auto builder = AuthorizationSetBuilder()
1355 .RsaSigningKey(2048, 65537)
1356 .Digest(Digest::NONE)
1357 .Padding(PaddingMode::NONE)
1358 .AttestationChallenge(challenge)
1359 .Authorization(TAG_NO_AUTH_REQUIRED)
1360 .SetDefaultValidity();
1361
1362 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001363 // Strongbox may not support factory provisioned attestation key.
1364 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001365 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1366 result = GenerateKeyWithSelfSignedAttestKey(
1367 AuthorizationSetBuilder()
1368 .RsaKey(2048, 65537)
1369 .AttestKey()
1370 .SetDefaultValidity(), /* attest key params */
1371 builder, &key_blob, &key_characteristics);
1372 }
subrahmanyaman05642492022-02-05 07:10:56 +00001373 }
1374 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001375}
1376
1377/*
1378 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1379 *
1380 * Verifies that attesting to RSA ignores app id if challenge is missing.
1381 */
1382TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1383 auto key_size = 2048;
1384 auto app_id = "foo";
1385
Selene Huang6e46f142021-04-20 19:20:11 -07001386 auto subject = "cert subj 2";
1387 vector<uint8_t> subject_der(make_name_from_str(subject));
1388
1389 uint64_t serial_int = 1;
1390 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1391
Selene Huang4f64c222021-04-13 19:54:36 -07001392 vector<uint8_t> key_blob;
1393 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001394 ASSERT_EQ(ErrorCode::OK,
1395 GenerateKey(AuthorizationSetBuilder()
1396 .RsaSigningKey(key_size, 65537)
1397 .Digest(Digest::NONE)
1398 .Padding(PaddingMode::NONE)
1399 .AttestationApplicationId(app_id)
1400 .Authorization(TAG_NO_AUTH_REQUIRED)
1401 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1402 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1403 .SetDefaultValidity(),
1404 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001405
1406 ASSERT_GT(key_blob.size(), 0U);
1407 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001408 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001409
1410 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1411
1412 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1413 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1414 << "Key size " << key_size << "missing";
1415 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1416
David Drysdalea8a888e2022-06-08 12:43:56 +01001417 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001418 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001419 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1420 ASSERT_EQ(cert_chain_.size(), 1);
1421
1422 CheckedDeleteKey(&key_blob);
1423}
1424
1425/*
Qi Wud22ec842020-11-26 13:27:53 +08001426 * NewKeyGenerationTest.LimitedUsageRsa
1427 *
1428 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1429 * resulting keys have correct characteristics.
1430 */
1431TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1432 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001433 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wud22ec842020-11-26 13:27:53 +08001434 vector<uint8_t> key_blob;
1435 vector<KeyCharacteristics> key_characteristics;
1436 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1437 .RsaSigningKey(key_size, 65537)
1438 .Digest(Digest::NONE)
1439 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001440 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1441 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001442 &key_blob, &key_characteristics));
1443
1444 ASSERT_GT(key_blob.size(), 0U);
1445 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001446 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001447
1448 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1449
1450 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1451 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1452 << "Key size " << key_size << "missing";
1453 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1454
1455 // Check the usage count limit tag appears in the authorizations.
1456 AuthorizationSet auths;
1457 for (auto& entry : key_characteristics) {
1458 auths.push_back(AuthorizationSet(entry.authorizations));
1459 }
1460 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1461 << "key usage count limit " << 1U << " missing";
1462
1463 CheckedDeleteKey(&key_blob);
1464 }
1465}
1466
1467/*
Qi Wubeefae42021-01-28 23:16:37 +08001468 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1469 *
1470 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1471 * resulting keys have correct characteristics and attestation.
1472 */
1473TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001474 auto challenge = "hello";
1475 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001476
Selene Huang6e46f142021-04-20 19:20:11 -07001477 auto subject = "cert subj 2";
1478 vector<uint8_t> subject_der(make_name_from_str(subject));
1479
1480 uint64_t serial_int = 66;
1481 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1482
Selene Huang4f64c222021-04-13 19:54:36 -07001483 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001484 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Qi Wubeefae42021-01-28 23:16:37 +08001485 vector<uint8_t> key_blob;
1486 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001487 auto builder = AuthorizationSetBuilder()
1488 .RsaSigningKey(key_size, 65537)
1489 .Digest(Digest::NONE)
1490 .Padding(PaddingMode::NONE)
1491 .AttestationChallenge(challenge)
1492 .AttestationApplicationId(app_id)
1493 .Authorization(TAG_NO_AUTH_REQUIRED)
1494 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1495 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1496 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1497 .SetDefaultValidity();
1498
1499 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001500 // Strongbox may not support factory provisioned attestation key.
1501 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001502 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1503 result = GenerateKeyWithSelfSignedAttestKey(
1504 AuthorizationSetBuilder()
1505 .RsaKey(key_size, 65537)
1506 .AttestKey()
1507 .SetDefaultValidity(), /* attest key params */
1508 builder, &key_blob, &key_characteristics);
1509 }
subrahmanyaman05642492022-02-05 07:10:56 +00001510 }
1511 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001512
1513 ASSERT_GT(key_blob.size(), 0U);
1514 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001515 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001516
1517 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1518
1519 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1520 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1521 << "Key size " << key_size << "missing";
1522 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1523
1524 // Check the usage count limit tag appears in the authorizations.
1525 AuthorizationSet auths;
1526 for (auto& entry : key_characteristics) {
1527 auths.push_back(AuthorizationSet(entry.authorizations));
1528 }
1529 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1530 << "key usage count limit " << 1U << " missing";
1531
1532 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001533 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001534 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001535 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001536
1537 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1538 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001539 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001540 sw_enforced, hw_enforced, SecLevel(),
1541 cert_chain_[0].encodedCertificate));
1542
1543 CheckedDeleteKey(&key_blob);
1544 }
1545}
1546
1547/*
Selene Huang31ab4042020-04-29 04:22:39 -07001548 * NewKeyGenerationTest.NoInvalidRsaSizes
1549 *
1550 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1551 */
1552TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1553 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001554 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07001555 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001556 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001557 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1558 GenerateKey(AuthorizationSetBuilder()
1559 .RsaSigningKey(key_size, 65537)
1560 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001561 .Padding(PaddingMode::NONE)
1562 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001563 &key_blob, &key_characteristics));
1564 }
1565}
1566
1567/*
1568 * NewKeyGenerationTest.RsaNoDefaultSize
1569 *
1570 * Verifies that failing to specify a key size for RSA key generation returns
1571 * UNSUPPORTED_KEY_SIZE.
1572 */
1573TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1574 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1575 GenerateKey(AuthorizationSetBuilder()
1576 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1577 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001578 .SigningKey()
1579 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001580}
1581
1582/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001583 * NewKeyGenerationTest.RsaMissingParams
1584 *
1585 * Verifies that omitting optional tags works.
1586 */
1587TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1588 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001589 SCOPED_TRACE(testing::Message() << "RSA-" << key_size);
David Drysdaled2cc8c22021-04-15 13:29:45 +01001590 ASSERT_EQ(ErrorCode::OK,
1591 GenerateKey(
1592 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1593 CheckedDeleteKey();
1594 }
1595}
1596
1597/*
Selene Huang31ab4042020-04-29 04:22:39 -07001598 * NewKeyGenerationTest.Ecdsa
1599 *
David Drysdale42fe1892021-10-14 14:43:46 +01001600 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001601 * have correct characteristics.
1602 */
1603TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001604 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001605 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07001606 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001607 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001608 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001609 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001610 .Digest(Digest::NONE)
1611 .SetDefaultValidity(),
1612 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001613 ASSERT_GT(key_blob.size(), 0U);
1614 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001615 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001616
Shawn Willden7f424372021-01-10 18:06:50 -07001617 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001618
1619 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001620 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001621
1622 CheckedDeleteKey(&key_blob);
1623 }
1624}
1625
1626/*
David Drysdale42fe1892021-10-14 14:43:46 +01001627 * NewKeyGenerationTest.EcdsaCurve25519
1628 *
1629 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1630 * has correct characteristics.
1631 */
1632TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1633 if (!Curve25519Supported()) {
1634 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1635 }
1636
1637 EcCurve curve = EcCurve::CURVE_25519;
1638 vector<uint8_t> key_blob;
1639 vector<KeyCharacteristics> key_characteristics;
1640 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1641 .EcdsaSigningKey(curve)
1642 .Digest(Digest::NONE)
1643 .SetDefaultValidity(),
1644 &key_blob, &key_characteristics);
1645 ASSERT_EQ(result, ErrorCode::OK);
1646 ASSERT_GT(key_blob.size(), 0U);
1647
1648 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1649 ASSERT_GT(cert_chain_.size(), 0);
1650
1651 CheckBaseParams(key_characteristics);
1652 CheckCharacteristics(key_blob, key_characteristics);
1653
1654 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1655
1656 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1657 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1658
1659 CheckedDeleteKey(&key_blob);
1660}
1661
1662/*
1663 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1664 *
1665 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1666 * SIGN and AGREE_KEY.
1667 */
1668TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1669 if (!Curve25519Supported()) {
1670 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1671 }
1672
1673 EcCurve curve = EcCurve::CURVE_25519;
1674 vector<uint8_t> key_blob;
1675 vector<KeyCharacteristics> key_characteristics;
1676 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1677 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1678 .EcdsaSigningKey(curve)
1679 .Digest(Digest::NONE)
1680 .SetDefaultValidity(),
1681 &key_blob, &key_characteristics);
1682 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1683}
1684
1685/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001686 * NewKeyGenerationTest.EcdsaWithMissingValidity
1687 *
1688 * Verifies that keymint returns an error while generating asymmetric key
1689 * without providing NOT_BEFORE and NOT_AFTER parameters.
1690 */
1691TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
Tommy Chiu7d22f602022-11-14 21:03:34 +08001692 if (AidlVersion() < 2) {
1693 /*
1694 * The KeyMint V1 spec required that CERTIFICATE_NOT_{BEFORE,AFTER} be
1695 * specified for asymmetric key generation. However, this was not
1696 * checked at the time so we can only be strict about checking this for
1697 * implementations of KeyMint version 2 and above.
1698 */
1699 GTEST_SKIP() << "Validity strict since KeyMint v2";
1700 }
Prashant Patil6c1adf02021-11-22 06:21:21 +00001701 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1702 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1703 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1704
1705 vector<uint8_t> key_blob;
1706 vector<KeyCharacteristics> key_characteristics;
1707 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1708 GenerateKey(AuthorizationSetBuilder()
1709 .EcdsaSigningKey(EcCurve::P_256)
1710 .Digest(Digest::NONE)
1711 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1712 kUndefinedExpirationDateTime),
1713 &key_blob, &key_characteristics));
1714
1715 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1716 GenerateKey(AuthorizationSetBuilder()
1717 .EcdsaSigningKey(EcCurve::P_256)
1718 .Digest(Digest::NONE)
1719 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1720 &key_blob, &key_characteristics));
1721}
1722
1723/*
Selene Huang4f64c222021-04-13 19:54:36 -07001724 * NewKeyGenerationTest.EcdsaAttestation
1725 *
1726 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1727 * an attestation will be generated.
1728 */
1729TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1730 auto challenge = "hello";
1731 auto app_id = "foo";
1732
Selene Huang6e46f142021-04-20 19:20:11 -07001733 auto subject = "cert subj 2";
1734 vector<uint8_t> subject_der(make_name_from_str(subject));
1735
1736 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1737 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1738
David Drysdaledf09e542021-06-08 15:46:11 +01001739 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01001740 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07001741 vector<uint8_t> key_blob;
1742 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001743 auto builder = AuthorizationSetBuilder()
1744 .Authorization(TAG_NO_AUTH_REQUIRED)
1745 .EcdsaSigningKey(curve)
1746 .Digest(Digest::NONE)
1747 .AttestationChallenge(challenge)
1748 .AttestationApplicationId(app_id)
1749 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1750 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1751 .SetDefaultValidity();
1752
1753 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001754 // Strongbox may not support factory provisioned attestation key.
1755 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001756 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1757 result = GenerateKeyWithSelfSignedAttestKey(
1758 AuthorizationSetBuilder()
1759 .EcdsaKey(curve)
1760 .AttestKey()
1761 .SetDefaultValidity(), /* attest key params */
1762 builder, &key_blob, &key_characteristics);
1763 }
subrahmanyaman05642492022-02-05 07:10:56 +00001764 }
1765 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001766 ASSERT_GT(key_blob.size(), 0U);
1767 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001768 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001769
1770 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1771
1772 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001773 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001774
1775 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1776 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001777 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001778
1779 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1780 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001781 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001782 sw_enforced, hw_enforced, SecLevel(),
1783 cert_chain_[0].encodedCertificate));
1784
1785 CheckedDeleteKey(&key_blob);
1786 }
1787}
1788
1789/*
David Drysdale42fe1892021-10-14 14:43:46 +01001790 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1791 *
1792 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1793 * an attestation will be generated.
1794 */
1795TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1796 if (!Curve25519Supported()) {
1797 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1798 }
1799
1800 EcCurve curve = EcCurve::CURVE_25519;
1801 auto challenge = "hello";
1802 auto app_id = "foo";
1803
1804 auto subject = "cert subj 2";
1805 vector<uint8_t> subject_der(make_name_from_str(subject));
1806
1807 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1808 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1809
1810 vector<uint8_t> key_blob;
1811 vector<KeyCharacteristics> key_characteristics;
1812 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1813 .Authorization(TAG_NO_AUTH_REQUIRED)
1814 .EcdsaSigningKey(curve)
1815 .Digest(Digest::NONE)
1816 .AttestationChallenge(challenge)
1817 .AttestationApplicationId(app_id)
1818 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1819 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1820 .SetDefaultValidity(),
1821 &key_blob, &key_characteristics);
1822 ASSERT_EQ(ErrorCode::OK, result);
1823 ASSERT_GT(key_blob.size(), 0U);
1824 CheckBaseParams(key_characteristics);
1825 CheckCharacteristics(key_blob, key_characteristics);
1826
1827 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1828
1829 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1830 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1831
1832 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1833 ASSERT_GT(cert_chain_.size(), 0);
1834 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1835
1836 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1837 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1838 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1839 sw_enforced, hw_enforced, SecLevel(),
1840 cert_chain_[0].encodedCertificate));
1841
1842 CheckedDeleteKey(&key_blob);
1843}
1844
1845/*
David Drysdale37af4b32021-05-14 16:46:59 +01001846 * NewKeyGenerationTest.EcdsaAttestationTags
1847 *
1848 * Verifies that creation of an attested ECDSA key includes various tags in the
1849 * attestation extension.
1850 */
1851TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1852 auto challenge = "hello";
1853 auto app_id = "foo";
1854 auto subject = "cert subj 2";
1855 vector<uint8_t> subject_der(make_name_from_str(subject));
1856 uint64_t serial_int = 0x1010;
1857 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1858 const AuthorizationSetBuilder base_builder =
1859 AuthorizationSetBuilder()
1860 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001861 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001862 .Digest(Digest::NONE)
1863 .AttestationChallenge(challenge)
1864 .AttestationApplicationId(app_id)
1865 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1866 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1867 .SetDefaultValidity();
1868
1869 // Various tags that map to fields in the attestation extension ASN.1 schema.
1870 auto extra_tags = AuthorizationSetBuilder()
1871 .Authorization(TAG_ROLLBACK_RESISTANCE)
1872 .Authorization(TAG_EARLY_BOOT_ONLY)
1873 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1874 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1875 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1876 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1877 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1878 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1879 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1880 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1881 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1882 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001883
David Drysdale37af4b32021-05-14 16:46:59 +01001884 for (const KeyParameter& tag : extra_tags) {
1885 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1886 vector<uint8_t> key_blob;
1887 vector<KeyCharacteristics> key_characteristics;
1888 AuthorizationSetBuilder builder = base_builder;
1889 builder.push_back(tag);
1890 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1891 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1892 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1893 continue;
1894 }
Seth Mooreb393b082021-07-12 14:18:28 -07001895 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1896 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001897 continue;
1898 }
subrahmanyaman05642492022-02-05 07:10:56 +00001899 // Strongbox may not support factory provisioned attestation key.
1900 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001901 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1902 result = GenerateKeyWithSelfSignedAttestKey(
1903 AuthorizationSetBuilder()
1904 .EcdsaKey(EcCurve::P_256)
1905 .AttestKey()
1906 .SetDefaultValidity(), /* attest key params */
1907 builder, &key_blob, &key_characteristics);
1908 }
subrahmanyaman05642492022-02-05 07:10:56 +00001909 }
David Drysdale37af4b32021-05-14 16:46:59 +01001910 ASSERT_EQ(result, ErrorCode::OK);
1911 ASSERT_GT(key_blob.size(), 0U);
1912
1913 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1914 ASSERT_GT(cert_chain_.size(), 0);
1915 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1916
1917 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1918 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001919 // Some tags are optional, so don't require them to be in the enforcements.
1920 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001921 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1922 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1923 }
1924
1925 // Verifying the attestation record will check for the specific tag because
1926 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001927 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1928 hw_enforced, SecLevel(),
1929 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001930
1931 CheckedDeleteKey(&key_blob);
1932 }
1933
David Drysdalec53b7d92021-10-11 12:35:58 +01001934 // Collection of invalid attestation ID tags.
1935 auto invalid_tags =
1936 AuthorizationSetBuilder()
1937 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1938 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1939 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1940 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1941 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1942 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1943 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1944 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001945 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001946 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001947 vector<uint8_t> key_blob;
1948 vector<KeyCharacteristics> key_characteristics;
1949 AuthorizationSetBuilder builder =
1950 AuthorizationSetBuilder()
1951 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001952 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001953 .Digest(Digest::NONE)
1954 .AttestationChallenge(challenge)
1955 .AttestationApplicationId(app_id)
1956 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1957 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1958 .SetDefaultValidity();
1959 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001960
1961 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
1962 // Strongbox may not support factory provisioned attestation key.
1963 if (SecLevel() == SecurityLevel::STRONGBOX) {
1964 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1965 error = GenerateKeyWithSelfSignedAttestKey(
1966 AuthorizationSetBuilder()
1967 .EcdsaKey(EcCurve::P_256)
1968 .AttestKey()
1969 .SetDefaultValidity(), /* attest key params */
1970 builder, &key_blob, &key_characteristics);
1971 }
1972 }
1973 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01001974 }
1975}
1976
1977/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001978 * NewKeyGenerationTest.EcdsaAttestationIdTags
1979 *
1980 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1981 * attestation extension.
1982 */
1983TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01001984 if (is_gsi_image()) {
1985 // GSI sets up a standard set of device identifiers that may not match
1986 // the device identifiers held by the device.
1987 GTEST_SKIP() << "Test not applicable under GSI";
1988 }
David Drysdalec53b7d92021-10-11 12:35:58 +01001989 auto challenge = "hello";
1990 auto app_id = "foo";
1991 auto subject = "cert subj 2";
1992 vector<uint8_t> subject_der(make_name_from_str(subject));
1993 uint64_t serial_int = 0x1010;
1994 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1995 const AuthorizationSetBuilder base_builder =
1996 AuthorizationSetBuilder()
1997 .Authorization(TAG_NO_AUTH_REQUIRED)
1998 .EcdsaSigningKey(EcCurve::P_256)
1999 .Digest(Digest::NONE)
2000 .AttestationChallenge(challenge)
2001 .AttestationApplicationId(app_id)
2002 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2003 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2004 .SetDefaultValidity();
2005
2006 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
2007 auto extra_tags = AuthorizationSetBuilder();
2008 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
2009 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
2010 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
Tri Vo799e4352022-11-07 17:23:50 -08002011 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serialno");
David Drysdalec53b7d92021-10-11 12:35:58 +01002012 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
2013 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
2014
2015 for (const KeyParameter& tag : extra_tags) {
2016 SCOPED_TRACE(testing::Message() << "tag-" << tag);
2017 vector<uint8_t> key_blob;
2018 vector<KeyCharacteristics> key_characteristics;
2019 AuthorizationSetBuilder builder = base_builder;
2020 builder.push_back(tag);
2021 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002022 // Strongbox may not support factory provisioned attestation key.
2023 if (SecLevel() == SecurityLevel::STRONGBOX) {
2024 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
2025 }
Prashant Patil88ad1892022-03-15 16:31:02 +00002026 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
2027 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01002028 continue;
2029 }
2030 ASSERT_EQ(result, ErrorCode::OK);
2031 ASSERT_GT(key_blob.size(), 0U);
2032
2033 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2034 ASSERT_GT(cert_chain_.size(), 0);
2035 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2036
2037 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2038 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2039
2040 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2041 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2042 // attestation extension should contain them, so make sure the extra tag is added.
2043 hw_enforced.push_back(tag);
2044
2045 // Verifying the attestation record will check for the specific tag because
2046 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002047 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2048 hw_enforced, SecLevel(),
2049 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002050
2051 CheckedDeleteKey(&key_blob);
2052 }
2053}
2054
2055/*
David Drysdale565ccc72021-10-11 12:49:50 +01002056 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2057 *
2058 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2059 */
2060TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2061 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002062 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002063 auto challenge = "hello";
2064 auto subject = "cert subj 2";
2065 vector<uint8_t> subject_der(make_name_from_str(subject));
2066 uint64_t serial_int = 0x1010;
2067 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002068 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002069 AuthorizationSetBuilder()
2070 .Authorization(TAG_NO_AUTH_REQUIRED)
2071 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2072 .EcdsaSigningKey(EcCurve::P_256)
2073 .Digest(Digest::NONE)
2074 .AttestationChallenge(challenge)
2075 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2076 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2077 .AttestationApplicationId(app_id)
2078 .Authorization(TAG_CREATION_DATETIME, datetime)
2079 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002080 if (reset) {
2081 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2082 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002083 auto result = GenerateKey(builder);
2084 if (SecLevel() == SecurityLevel::STRONGBOX) {
2085 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2086 result = GenerateKeyWithSelfSignedAttestKey(
2087 AuthorizationSetBuilder()
2088 .EcdsaKey(EcCurve::P_256)
2089 .AttestKey()
2090 .SetDefaultValidity(), /* attest key params */
2091 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2092 }
2093 }
2094 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002095 ASSERT_GT(key_blob_.size(), 0U);
2096
2097 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2098 ASSERT_GT(cert_chain_.size(), 0);
2099 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2100
2101 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2102 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2103
2104 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002105 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2106 hw_enforced, SecLevel(),
2107 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002108 EXPECT_GT(unique_id->size(), 0);
2109 CheckedDeleteKey();
2110 };
2111
2112 // Generate unique ID
2113 auto app_id = "foo";
2114 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2115 vector<uint8_t> unique_id;
2116 get_unique_id(app_id, cert_date, &unique_id);
2117
2118 // Generating a new key with the same parameters should give the same unique ID.
2119 vector<uint8_t> unique_id2;
2120 get_unique_id(app_id, cert_date, &unique_id2);
2121 EXPECT_EQ(unique_id, unique_id2);
2122
2123 // Generating a new key with a slightly different date should give the same unique ID.
2124 uint64_t rounded_date = cert_date / 2592000000LLU;
2125 uint64_t min_date = rounded_date * 2592000000LLU;
2126 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2127
2128 vector<uint8_t> unique_id3;
2129 get_unique_id(app_id, min_date, &unique_id3);
2130 EXPECT_EQ(unique_id, unique_id3);
2131
2132 vector<uint8_t> unique_id4;
2133 get_unique_id(app_id, max_date, &unique_id4);
2134 EXPECT_EQ(unique_id, unique_id4);
2135
2136 // A different attestation application ID should yield a different unique ID.
2137 auto app_id2 = "different_foo";
2138 vector<uint8_t> unique_id5;
2139 get_unique_id(app_id2, cert_date, &unique_id5);
2140 EXPECT_NE(unique_id, unique_id5);
2141
2142 // A radically different date should yield a different unique ID.
2143 vector<uint8_t> unique_id6;
2144 get_unique_id(app_id, 1611621648000, &unique_id6);
2145 EXPECT_NE(unique_id, unique_id6);
2146
2147 vector<uint8_t> unique_id7;
2148 get_unique_id(app_id, max_date + 1, &unique_id7);
2149 EXPECT_NE(unique_id, unique_id7);
2150
2151 vector<uint8_t> unique_id8;
2152 get_unique_id(app_id, min_date - 1, &unique_id8);
2153 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002154
2155 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2156 vector<uint8_t> unique_id9;
2157 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2158 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002159}
2160
2161/*
David Drysdale37af4b32021-05-14 16:46:59 +01002162 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2163 *
2164 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2165 */
2166TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2167 auto challenge = "hello";
2168 auto attest_app_id = "foo";
2169 auto subject = "cert subj 2";
2170 vector<uint8_t> subject_der(make_name_from_str(subject));
2171 uint64_t serial_int = 0x1010;
2172 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2173
2174 // Earlier versions of the attestation extension schema included a slot:
2175 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2176 // This should never have been included, and should never be filled in.
2177 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2178 // to confirm that this field never makes it into the attestation extension.
2179 vector<uint8_t> key_blob;
2180 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002181 auto builder = AuthorizationSetBuilder()
2182 .Authorization(TAG_NO_AUTH_REQUIRED)
2183 .EcdsaSigningKey(EcCurve::P_256)
2184 .Digest(Digest::NONE)
2185 .AttestationChallenge(challenge)
2186 .AttestationApplicationId(attest_app_id)
2187 .Authorization(TAG_APPLICATION_ID, "client_id")
2188 .Authorization(TAG_APPLICATION_DATA, "appdata")
2189 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2190 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2191 .SetDefaultValidity();
2192
2193 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002194 // Strongbox may not support factory provisioned attestation key.
2195 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002196 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2197 result = GenerateKeyWithSelfSignedAttestKey(
2198 AuthorizationSetBuilder()
2199 .EcdsaKey(EcCurve::P_256)
2200 .AttestKey()
2201 .SetDefaultValidity(), /* attest key params */
2202 builder, &key_blob, &key_characteristics);
2203 }
subrahmanyaman05642492022-02-05 07:10:56 +00002204 }
David Drysdale37af4b32021-05-14 16:46:59 +01002205 ASSERT_EQ(result, ErrorCode::OK);
2206 ASSERT_GT(key_blob.size(), 0U);
2207
2208 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2209 ASSERT_GT(cert_chain_.size(), 0);
2210 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2211
2212 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2213 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002214 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2215 hw_enforced, SecLevel(),
2216 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002217
2218 // Check that the app id is not in the cert.
2219 string app_id = "clientid";
2220 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2221 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2222 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2223 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2224 cert_chain_[0].encodedCertificate.end());
2225
2226 CheckedDeleteKey(&key_blob);
2227}
2228
2229/*
Selene Huang4f64c222021-04-13 19:54:36 -07002230 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2231 *
2232 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2233 * the key will generate a self signed attestation.
2234 */
2235TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002236 auto subject = "cert subj 2";
2237 vector<uint8_t> subject_der(make_name_from_str(subject));
2238
2239 uint64_t serial_int = 0x123456FFF1234;
2240 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2241
David Drysdaledf09e542021-06-08 15:46:11 +01002242 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002243 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002244 vector<uint8_t> key_blob;
2245 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002246 ASSERT_EQ(ErrorCode::OK,
2247 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002248 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002249 .Digest(Digest::NONE)
2250 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2251 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2252 .SetDefaultValidity(),
2253 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002254 ASSERT_GT(key_blob.size(), 0U);
2255 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002256 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002257
2258 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2259
2260 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002261 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002262
2263 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2264 ASSERT_EQ(cert_chain_.size(), 1);
David Drysdalea8a888e2022-06-08 12:43:56 +01002265 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002266
2267 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2268 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2269
2270 CheckedDeleteKey(&key_blob);
2271 }
2272}
2273
2274/*
2275 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2276 *
2277 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2278 * app id must also be provided or else it will fail.
2279 */
2280TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2281 auto challenge = "hello";
2282 vector<uint8_t> key_blob;
2283 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002284 auto builder = AuthorizationSetBuilder()
2285 .EcdsaSigningKey(EcCurve::P_256)
2286 .Digest(Digest::NONE)
2287 .AttestationChallenge(challenge)
2288 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002289
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002290 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002291 // Strongbox may not support factory provisioned attestation key.
2292 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002293 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2294 result = GenerateKeyWithSelfSignedAttestKey(
2295 AuthorizationSetBuilder()
2296 .EcdsaKey(EcCurve::P_256)
2297 .AttestKey()
2298 .SetDefaultValidity(), /* attest key params */
2299 builder, &key_blob, &key_characteristics);
2300 }
subrahmanyaman05642492022-02-05 07:10:56 +00002301 }
2302 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002303}
2304
2305/*
2306 * NewKeyGenerationTest.EcdsaIgnoreAppId
2307 *
2308 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2309 * any appid will be ignored, and keymint will generate a self sign certificate.
2310 */
2311TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2312 auto app_id = "foo";
2313
David Drysdaledf09e542021-06-08 15:46:11 +01002314 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002315 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang4f64c222021-04-13 19:54:36 -07002316 vector<uint8_t> key_blob;
2317 vector<KeyCharacteristics> key_characteristics;
2318 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002319 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002320 .Digest(Digest::NONE)
2321 .AttestationApplicationId(app_id)
2322 .SetDefaultValidity(),
2323 &key_blob, &key_characteristics));
2324
2325 ASSERT_GT(key_blob.size(), 0U);
2326 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002327 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002328
2329 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2330
2331 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002332 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002333
2334 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2335 ASSERT_EQ(cert_chain_.size(), 1);
2336
2337 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2338 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2339
2340 CheckedDeleteKey(&key_blob);
2341 }
2342}
2343
2344/*
2345 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2346 *
2347 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2348 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2349 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2350 * to specify how many following bytes will be used to encode the length.
2351 */
2352TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2353 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002354 std::vector<uint32_t> app_id_lengths{143, 258};
2355
2356 for (uint32_t length : app_id_lengths) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002357 SCOPED_TRACE(testing::Message() << "app_id_len=" << length);
Selene Huang4f64c222021-04-13 19:54:36 -07002358 const string app_id(length, 'a');
2359 vector<uint8_t> key_blob;
2360 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002361 auto builder = AuthorizationSetBuilder()
2362 .Authorization(TAG_NO_AUTH_REQUIRED)
2363 .EcdsaSigningKey(EcCurve::P_256)
2364 .Digest(Digest::NONE)
2365 .AttestationChallenge(challenge)
2366 .AttestationApplicationId(app_id)
2367 .SetDefaultValidity();
2368
2369 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002370 // Strongbox may not support factory provisioned attestation key.
2371 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002372 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2373 result = GenerateKeyWithSelfSignedAttestKey(
2374 AuthorizationSetBuilder()
2375 .EcdsaKey(EcCurve::P_256)
2376 .AttestKey()
2377 .SetDefaultValidity(), /* attest key params */
2378 builder, &key_blob, &key_characteristics);
2379 }
subrahmanyaman05642492022-02-05 07:10:56 +00002380 }
2381 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002382 ASSERT_GT(key_blob.size(), 0U);
2383 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002384 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002385
2386 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2387
2388 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002389 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002390
2391 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2392 ASSERT_GT(cert_chain_.size(), 0);
2393
2394 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2395 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002396 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002397 sw_enforced, hw_enforced, SecLevel(),
2398 cert_chain_[0].encodedCertificate));
2399
2400 CheckedDeleteKey(&key_blob);
2401 }
2402}
2403
2404/*
Qi Wud22ec842020-11-26 13:27:53 +08002405 * NewKeyGenerationTest.LimitedUsageEcdsa
2406 *
2407 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2408 * resulting keys have correct characteristics.
2409 */
2410TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002411 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002412 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Qi Wud22ec842020-11-26 13:27:53 +08002413 vector<uint8_t> key_blob;
2414 vector<KeyCharacteristics> key_characteristics;
2415 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002416 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002417 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002418 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2419 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002420 &key_blob, &key_characteristics));
2421
2422 ASSERT_GT(key_blob.size(), 0U);
2423 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002424 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002425
2426 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2427
2428 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002429 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002430
2431 // Check the usage count limit tag appears in the authorizations.
2432 AuthorizationSet auths;
2433 for (auto& entry : key_characteristics) {
2434 auths.push_back(AuthorizationSet(entry.authorizations));
2435 }
2436 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2437 << "key usage count limit " << 1U << " missing";
2438
2439 CheckedDeleteKey(&key_blob);
2440 }
2441}
2442
2443/*
Selene Huang31ab4042020-04-29 04:22:39 -07002444 * NewKeyGenerationTest.EcdsaDefaultSize
2445 *
David Drysdaledf09e542021-06-08 15:46:11 +01002446 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002447 * UNSUPPORTED_KEY_SIZE.
2448 */
2449TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2450 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2451 GenerateKey(AuthorizationSetBuilder()
2452 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2453 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002454 .Digest(Digest::NONE)
2455 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002456}
2457
2458/*
David Drysdale42fe1892021-10-14 14:43:46 +01002459 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002460 *
David Drysdale42fe1892021-10-14 14:43:46 +01002461 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002462 * UNSUPPORTED_KEY_SIZE.
2463 */
David Drysdale42fe1892021-10-14 14:43:46 +01002464TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002465 for (auto curve : InvalidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002466 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07002467 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002468 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002469 auto result = GenerateKey(AuthorizationSetBuilder()
2470 .EcdsaSigningKey(curve)
2471 .Digest(Digest::NONE)
2472 .SetDefaultValidity(),
2473 &key_blob, &key_characteristics);
2474 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2475 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002476 }
2477
David Drysdaledf09e542021-06-08 15:46:11 +01002478 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2479 GenerateKey(AuthorizationSetBuilder()
2480 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2481 .Authorization(TAG_KEY_SIZE, 190)
2482 .SigningKey()
2483 .Digest(Digest::NONE)
2484 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002485}
2486
2487/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002488 * NewKeyGenerationTest.EcdsaMissingCurve
2489 *
2490 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2491 */
2492TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2493 if (AidlVersion() < 2) {
2494 /*
2495 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2496 * However, this was not checked at the time so we can only be strict about checking this
2497 * for implementations of KeyMint version 2 and above.
2498 */
2499 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2500 }
2501 /* If EC_CURVE not provided, generateKey
2502 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2503 */
2504 auto result = GenerateKey(
2505 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2506 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2507 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2508}
2509
2510/*
Selene Huang31ab4042020-04-29 04:22:39 -07002511 * NewKeyGenerationTest.EcdsaMismatchKeySize
2512 *
2513 * Verifies that specifying mismatched key size and curve for EC key generation returns
2514 * INVALID_ARGUMENT.
2515 */
2516TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002517 if (SecLevel() == SecurityLevel::STRONGBOX) {
2518 GTEST_SKIP() << "Test not applicable to StrongBox device";
2519 }
Selene Huang31ab4042020-04-29 04:22:39 -07002520
David Drysdaledf09e542021-06-08 15:46:11 +01002521 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002522 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002523 .Authorization(TAG_KEY_SIZE, 224)
2524 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002525 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002526 .Digest(Digest::NONE)
2527 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002528 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002529}
2530
2531/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002532 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002533 *
2534 * Verifies that keymint does not support any curve designated as unsupported.
2535 */
2536TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2537 Digest digest;
2538 if (SecLevel() == SecurityLevel::STRONGBOX) {
2539 digest = Digest::SHA_2_256;
2540 } else {
2541 digest = Digest::SHA_2_512;
2542 }
2543 for (auto curve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002544 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Janis Danisevskis164bb872021-02-09 11:30:25 -08002545 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2546 .EcdsaSigningKey(curve)
2547 .Digest(digest)
2548 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002549 << "Failed to generate key on curve: " << curve;
2550 CheckedDeleteKey();
2551 }
2552}
2553
2554/*
2555 * NewKeyGenerationTest.Hmac
2556 *
2557 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2558 * characteristics.
2559 */
2560TEST_P(NewKeyGenerationTest, Hmac) {
2561 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002562 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07002563 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002564 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002565 constexpr size_t key_size = 128;
2566 ASSERT_EQ(ErrorCode::OK,
2567 GenerateKey(
2568 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2569 TAG_MIN_MAC_LENGTH, 128),
2570 &key_blob, &key_characteristics));
2571
2572 ASSERT_GT(key_blob.size(), 0U);
2573 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002574 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002575
Shawn Willden7f424372021-01-10 18:06:50 -07002576 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2577 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2578 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2579 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002580
2581 CheckedDeleteKey(&key_blob);
2582 }
2583}
2584
2585/*
Selene Huang4f64c222021-04-13 19:54:36 -07002586 * NewKeyGenerationTest.HmacNoAttestation
2587 *
2588 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2589 * and app id are provided.
2590 */
2591TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2592 auto challenge = "hello";
2593 auto app_id = "foo";
2594
2595 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002596 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang4f64c222021-04-13 19:54:36 -07002597 vector<uint8_t> key_blob;
2598 vector<KeyCharacteristics> key_characteristics;
2599 constexpr size_t key_size = 128;
2600 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2601 .HmacKey(key_size)
2602 .Digest(digest)
2603 .AttestationChallenge(challenge)
2604 .AttestationApplicationId(app_id)
2605 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2606 &key_blob, &key_characteristics));
2607
2608 ASSERT_GT(key_blob.size(), 0U);
2609 ASSERT_EQ(cert_chain_.size(), 0);
2610 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002611 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002612
2613 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2614 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2615 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2616 << "Key size " << key_size << "missing";
2617
2618 CheckedDeleteKey(&key_blob);
2619 }
2620}
2621
2622/*
Qi Wud22ec842020-11-26 13:27:53 +08002623 * NewKeyGenerationTest.LimitedUsageHmac
2624 *
2625 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2626 * resulting keys have correct characteristics.
2627 */
2628TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2629 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002630 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Qi Wud22ec842020-11-26 13:27:53 +08002631 vector<uint8_t> key_blob;
2632 vector<KeyCharacteristics> key_characteristics;
2633 constexpr size_t key_size = 128;
2634 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2635 .HmacKey(key_size)
2636 .Digest(digest)
2637 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2638 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2639 &key_blob, &key_characteristics));
2640
2641 ASSERT_GT(key_blob.size(), 0U);
2642 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002643 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002644
2645 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2646 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2647 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2648 << "Key size " << key_size << "missing";
2649
2650 // Check the usage count limit tag appears in the authorizations.
2651 AuthorizationSet auths;
2652 for (auto& entry : key_characteristics) {
2653 auths.push_back(AuthorizationSet(entry.authorizations));
2654 }
2655 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2656 << "key usage count limit " << 1U << " missing";
2657
2658 CheckedDeleteKey(&key_blob);
2659 }
2660}
2661
2662/*
Selene Huang31ab4042020-04-29 04:22:39 -07002663 * NewKeyGenerationTest.HmacCheckKeySizes
2664 *
2665 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2666 */
2667TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2668 for (size_t key_size = 0; key_size <= 512; ++key_size) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002669 SCOPED_TRACE(testing::Message() << "HMAC-" << key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07002670 if (key_size < 64 || key_size % 8 != 0) {
2671 // To keep this test from being very slow, we only test a random fraction of
2672 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2673 // them, we expect to run ~40 of them in each run.
2674 if (key_size % 8 == 0 || random() % 10 == 0) {
2675 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2676 GenerateKey(AuthorizationSetBuilder()
2677 .HmacKey(key_size)
2678 .Digest(Digest::SHA_2_256)
2679 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2680 << "HMAC key size " << key_size << " invalid";
2681 }
2682 } else {
2683 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2684 .HmacKey(key_size)
2685 .Digest(Digest::SHA_2_256)
2686 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2687 << "Failed to generate HMAC key of size " << key_size;
2688 CheckedDeleteKey();
2689 }
2690 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002691 if (SecLevel() == SecurityLevel::STRONGBOX) {
2692 // STRONGBOX devices must not support keys larger than 512 bits.
2693 size_t key_size = 520;
2694 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2695 GenerateKey(AuthorizationSetBuilder()
2696 .HmacKey(key_size)
2697 .Digest(Digest::SHA_2_256)
2698 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2699 << "HMAC key size " << key_size << " unexpectedly valid";
2700 }
Selene Huang31ab4042020-04-29 04:22:39 -07002701}
2702
2703/*
2704 * NewKeyGenerationTest.HmacCheckMinMacLengths
2705 *
2706 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2707 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2708 * specific MAC length that failed, so reproducing a failed run will be easy.
2709 */
2710TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2711 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002712 SCOPED_TRACE(testing::Message() << "MIN_MAC_LENGTH=" << min_mac_length);
Selene Huang31ab4042020-04-29 04:22:39 -07002713 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2714 // To keep this test from being very long, we only test a random fraction of
2715 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2716 // we expect to run ~17 of them in each run.
2717 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2718 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2719 GenerateKey(AuthorizationSetBuilder()
2720 .HmacKey(128)
2721 .Digest(Digest::SHA_2_256)
2722 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2723 << "HMAC min mac length " << min_mac_length << " invalid.";
2724 }
2725 } else {
2726 EXPECT_EQ(ErrorCode::OK,
2727 GenerateKey(AuthorizationSetBuilder()
2728 .HmacKey(128)
2729 .Digest(Digest::SHA_2_256)
2730 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2731 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2732 CheckedDeleteKey();
2733 }
2734 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002735
2736 // Minimum MAC length must be no more than 512 bits.
2737 size_t min_mac_length = 520;
2738 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2739 GenerateKey(AuthorizationSetBuilder()
2740 .HmacKey(128)
2741 .Digest(Digest::SHA_2_256)
2742 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2743 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002744}
2745
2746/*
2747 * NewKeyGenerationTest.HmacMultipleDigests
2748 *
2749 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2750 */
2751TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002752 if (SecLevel() == SecurityLevel::STRONGBOX) {
2753 GTEST_SKIP() << "Test not applicable to StrongBox device";
2754 }
Selene Huang31ab4042020-04-29 04:22:39 -07002755
2756 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2757 GenerateKey(AuthorizationSetBuilder()
2758 .HmacKey(128)
2759 .Digest(Digest::SHA1)
2760 .Digest(Digest::SHA_2_256)
2761 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2762}
2763
2764/*
2765 * NewKeyGenerationTest.HmacDigestNone
2766 *
2767 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2768 */
2769TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2770 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2771 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2772 128)));
2773
2774 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2775 GenerateKey(AuthorizationSetBuilder()
2776 .HmacKey(128)
2777 .Digest(Digest::NONE)
2778 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2779}
2780
Selene Huang4f64c222021-04-13 19:54:36 -07002781/*
2782 * NewKeyGenerationTest.AesNoAttestation
2783 *
2784 * Verifies that attestation parameters to AES keys are ignored and generateKey
2785 * will succeed.
2786 */
2787TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2788 auto challenge = "hello";
2789 auto app_id = "foo";
2790
2791 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2792 .Authorization(TAG_NO_AUTH_REQUIRED)
2793 .AesEncryptionKey(128)
2794 .EcbMode()
2795 .Padding(PaddingMode::PKCS7)
2796 .AttestationChallenge(challenge)
2797 .AttestationApplicationId(app_id)));
2798
2799 ASSERT_EQ(cert_chain_.size(), 0);
2800}
2801
2802/*
2803 * NewKeyGenerationTest.TripleDesNoAttestation
2804 *
2805 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2806 * will be successful. No attestation should be generated.
2807 */
2808TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2809 auto challenge = "hello";
2810 auto app_id = "foo";
2811
2812 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2813 .TripleDesEncryptionKey(168)
2814 .BlockMode(BlockMode::ECB)
2815 .Authorization(TAG_NO_AUTH_REQUIRED)
2816 .Padding(PaddingMode::NONE)
2817 .AttestationChallenge(challenge)
2818 .AttestationApplicationId(app_id)));
2819 ASSERT_EQ(cert_chain_.size(), 0);
2820}
2821
Selene Huang31ab4042020-04-29 04:22:39 -07002822INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2823
2824typedef KeyMintAidlTestBase SigningOperationsTest;
2825
2826/*
2827 * SigningOperationsTest.RsaSuccess
2828 *
2829 * Verifies that raw RSA signature operations succeed.
2830 */
2831TEST_P(SigningOperationsTest, RsaSuccess) {
2832 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2833 .RsaSigningKey(2048, 65537)
2834 .Digest(Digest::NONE)
2835 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002836 .Authorization(TAG_NO_AUTH_REQUIRED)
2837 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002838 string message = "12345678901234567890123456789012";
2839 string signature = SignMessage(
2840 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002841 LocalVerifyMessage(message, signature,
2842 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2843}
2844
2845/*
2846 * SigningOperationsTest.RsaAllPaddingsAndDigests
2847 *
2848 * Verifies RSA signature/verification for all padding modes and digests.
2849 */
2850TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2851 auto authorizations = AuthorizationSetBuilder()
2852 .Authorization(TAG_NO_AUTH_REQUIRED)
2853 .RsaSigningKey(2048, 65537)
2854 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2855 .Padding(PaddingMode::NONE)
2856 .Padding(PaddingMode::RSA_PSS)
2857 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2858 .SetDefaultValidity();
2859
2860 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2861
2862 string message(128, 'a');
2863 string corrupt_message(message);
2864 ++corrupt_message[corrupt_message.size() / 2];
2865
2866 for (auto padding :
2867 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2868 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01002869 SCOPED_TRACE(testing::Message() << "RSA padding=" << padding << " digest=" << digest);
David Drysdaledf8f52e2021-05-06 08:10:58 +01002870 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2871 // Digesting only makes sense with padding.
2872 continue;
2873 }
2874
2875 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2876 // PSS requires digesting.
2877 continue;
2878 }
2879
2880 string signature =
2881 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2882 LocalVerifyMessage(message, signature,
2883 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2884 }
2885 }
Selene Huang31ab4042020-04-29 04:22:39 -07002886}
2887
2888/*
2889 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2890 *
Shawn Willden7f424372021-01-10 18:06:50 -07002891 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002892 */
2893TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2894 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2895 .Authorization(TAG_NO_AUTH_REQUIRED)
2896 .RsaSigningKey(2048, 65537)
2897 .Digest(Digest::NONE)
2898 .Padding(PaddingMode::NONE)
2899 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002900 .Authorization(TAG_APPLICATION_DATA, "appdata")
2901 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002902
2903 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2904
Selene Huang31ab4042020-04-29 04:22:39 -07002905 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2906 Begin(KeyPurpose::SIGN,
2907 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2908 AbortIfNeeded();
2909 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2910 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2911 .Digest(Digest::NONE)
2912 .Padding(PaddingMode::NONE)
2913 .Authorization(TAG_APPLICATION_ID, "clientid")));
2914 AbortIfNeeded();
2915 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2916 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2917 .Digest(Digest::NONE)
2918 .Padding(PaddingMode::NONE)
2919 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2920 AbortIfNeeded();
2921 EXPECT_EQ(ErrorCode::OK,
2922 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2923 .Digest(Digest::NONE)
2924 .Padding(PaddingMode::NONE)
2925 .Authorization(TAG_APPLICATION_DATA, "appdata")
2926 .Authorization(TAG_APPLICATION_ID, "clientid")));
2927 AbortIfNeeded();
2928}
2929
2930/*
2931 * SigningOperationsTest.RsaPssSha256Success
2932 *
2933 * Verifies that RSA-PSS signature operations succeed.
2934 */
2935TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2936 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2937 .RsaSigningKey(2048, 65537)
2938 .Digest(Digest::SHA_2_256)
2939 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002940 .Authorization(TAG_NO_AUTH_REQUIRED)
2941 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002942 // Use large message, which won't work without digesting.
2943 string message(1024, 'a');
2944 string signature = SignMessage(
2945 message,
2946 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2947}
2948
2949/*
2950 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2951 *
2952 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2953 * supports only unpadded operations.
2954 */
2955TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2956 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2957 .RsaSigningKey(2048, 65537)
2958 .Digest(Digest::NONE)
2959 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002960 .Padding(PaddingMode::NONE)
2961 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002962 string message = "12345678901234567890123456789012";
2963 string signature;
2964
2965 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2966 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2967 .Digest(Digest::NONE)
2968 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2969}
2970
2971/*
2972 * SigningOperationsTest.NoUserConfirmation
2973 *
2974 * Verifies that keymint rejects signing operations for keys with
2975 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2976 * presented.
2977 */
2978TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002979 if (SecLevel() == SecurityLevel::STRONGBOX) {
2980 GTEST_SKIP() << "Test not applicable to StrongBox device";
2981 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002982 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2983 .RsaSigningKey(1024, 65537)
2984 .Digest(Digest::NONE)
2985 .Padding(PaddingMode::NONE)
2986 .Authorization(TAG_NO_AUTH_REQUIRED)
2987 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2988 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002989
2990 const string message = "12345678901234567890123456789012";
2991 EXPECT_EQ(ErrorCode::OK,
2992 Begin(KeyPurpose::SIGN,
2993 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2994 string signature;
2995 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2996}
2997
2998/*
2999 * SigningOperationsTest.RsaPkcs1Sha256Success
3000 *
3001 * Verifies that digested RSA-PKCS1 signature operations succeed.
3002 */
3003TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
3004 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3005 .RsaSigningKey(2048, 65537)
3006 .Digest(Digest::SHA_2_256)
3007 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003008 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3009 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003010 string message(1024, 'a');
3011 string signature = SignMessage(message, AuthorizationSetBuilder()
3012 .Digest(Digest::SHA_2_256)
3013 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3014}
3015
3016/*
3017 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
3018 *
3019 * Verifies that undigested RSA-PKCS1 signature operations succeed.
3020 */
3021TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
3022 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3023 .RsaSigningKey(2048, 65537)
3024 .Digest(Digest::NONE)
3025 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003026 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3027 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003028 string message(53, 'a');
3029 string signature = SignMessage(message, AuthorizationSetBuilder()
3030 .Digest(Digest::NONE)
3031 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3032}
3033
3034/*
3035 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
3036 *
3037 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
3038 * given a too-long message.
3039 */
3040TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
3041 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3042 .RsaSigningKey(2048, 65537)
3043 .Digest(Digest::NONE)
3044 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003045 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3046 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003047 string message(257, 'a');
3048
3049 EXPECT_EQ(ErrorCode::OK,
3050 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3051 .Digest(Digest::NONE)
3052 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3053 string signature;
3054 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3055}
3056
3057/*
3058 * SigningOperationsTest.RsaPssSha512TooSmallKey
3059 *
3060 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3061 * used with a key that is too small for the message.
3062 *
3063 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3064 * keymint specification requires that salt_size == digest_size, so the message will be
3065 * digest_size * 2 +
3066 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3067 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3068 * for a 1024-bit key.
3069 */
3070TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003071 if (SecLevel() == SecurityLevel::STRONGBOX) {
3072 GTEST_SKIP() << "Test not applicable to StrongBox device";
3073 }
Selene Huang31ab4042020-04-29 04:22:39 -07003074 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3075 .RsaSigningKey(1024, 65537)
3076 .Digest(Digest::SHA_2_512)
3077 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003078 .Padding(PaddingMode::RSA_PSS)
3079 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003080 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3081 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3082 .Digest(Digest::SHA_2_512)
3083 .Padding(PaddingMode::RSA_PSS)));
3084}
3085
3086/*
3087 * SigningOperationsTest.RsaNoPaddingTooLong
3088 *
3089 * Verifies that raw RSA signature operations fail with the correct error code when
3090 * given a too-long message.
3091 */
3092TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3093 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3094 .RsaSigningKey(2048, 65537)
3095 .Digest(Digest::NONE)
3096 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003097 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3098 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003099 // One byte too long
3100 string message(2048 / 8 + 1, 'a');
3101 ASSERT_EQ(ErrorCode::OK,
3102 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3103 .Digest(Digest::NONE)
3104 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3105 string result;
3106 ErrorCode finish_error_code = Finish(message, &result);
3107 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3108 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3109
3110 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3111 message = string(128 * 1024, 'a');
3112 ASSERT_EQ(ErrorCode::OK,
3113 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3114 .Digest(Digest::NONE)
3115 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3116 finish_error_code = Finish(message, &result);
3117 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3118 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3119}
3120
3121/*
3122 * SigningOperationsTest.RsaAbort
3123 *
3124 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3125 * test, but the behavior should be algorithm and purpose-independent.
3126 */
3127TEST_P(SigningOperationsTest, RsaAbort) {
3128 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3129 .RsaSigningKey(2048, 65537)
3130 .Digest(Digest::NONE)
3131 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003132 .Padding(PaddingMode::NONE)
3133 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003134
3135 ASSERT_EQ(ErrorCode::OK,
3136 Begin(KeyPurpose::SIGN,
3137 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3138 EXPECT_EQ(ErrorCode::OK, Abort());
3139
3140 // Another abort should fail
3141 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3142
3143 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003144 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003145}
3146
3147/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003148 * SigningOperationsTest.RsaNonUniqueParams
3149 *
3150 * Verifies that an operation with multiple padding modes is rejected.
3151 */
3152TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3153 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3154 .RsaSigningKey(2048, 65537)
3155 .Digest(Digest::NONE)
3156 .Digest(Digest::SHA1)
3157 .Authorization(TAG_NO_AUTH_REQUIRED)
3158 .Padding(PaddingMode::NONE)
3159 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3160 .SetDefaultValidity()));
3161
3162 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3163 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3164 .Digest(Digest::NONE)
3165 .Padding(PaddingMode::NONE)
3166 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3167
Tommy Chiuc93c4392021-05-11 18:36:50 +08003168 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3169 .Digest(Digest::NONE)
3170 .Digest(Digest::SHA1)
3171 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3172 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003173
3174 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3175 Begin(KeyPurpose::SIGN,
3176 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3177}
3178
3179/*
Selene Huang31ab4042020-04-29 04:22:39 -07003180 * SigningOperationsTest.RsaUnsupportedPadding
3181 *
3182 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3183 * with a padding mode inappropriate for RSA.
3184 */
3185TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3186 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3187 .RsaSigningKey(2048, 65537)
3188 .Authorization(TAG_NO_AUTH_REQUIRED)
3189 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003190 .Padding(PaddingMode::PKCS7)
3191 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003192 ASSERT_EQ(
3193 ErrorCode::UNSUPPORTED_PADDING_MODE,
3194 Begin(KeyPurpose::SIGN,
3195 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003196 CheckedDeleteKey();
3197
3198 ASSERT_EQ(ErrorCode::OK,
3199 GenerateKey(
3200 AuthorizationSetBuilder()
3201 .RsaSigningKey(2048, 65537)
3202 .Authorization(TAG_NO_AUTH_REQUIRED)
3203 .Digest(Digest::SHA_2_256 /* supported digest */)
3204 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3205 .SetDefaultValidity()));
3206 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3207 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3208 .Digest(Digest::SHA_2_256)
3209 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003210}
3211
3212/*
3213 * SigningOperationsTest.RsaPssNoDigest
3214 *
3215 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3216 */
3217TEST_P(SigningOperationsTest, RsaNoDigest) {
3218 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3219 .RsaSigningKey(2048, 65537)
3220 .Authorization(TAG_NO_AUTH_REQUIRED)
3221 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003222 .Padding(PaddingMode::RSA_PSS)
3223 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003224 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3225 Begin(KeyPurpose::SIGN,
3226 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3227
3228 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3229 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3230}
3231
3232/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003233 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003234 *
3235 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3236 * supported in some cases (as validated in other tests), but a mode must be specified.
3237 */
3238TEST_P(SigningOperationsTest, RsaNoPadding) {
3239 // Padding must be specified
3240 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3241 .RsaKey(2048, 65537)
3242 .Authorization(TAG_NO_AUTH_REQUIRED)
3243 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003244 .Digest(Digest::NONE)
3245 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003246 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3247 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3248}
3249
3250/*
3251 * SigningOperationsTest.RsaShortMessage
3252 *
3253 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3254 */
3255TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3256 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3257 .Authorization(TAG_NO_AUTH_REQUIRED)
3258 .RsaSigningKey(2048, 65537)
3259 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003260 .Padding(PaddingMode::NONE)
3261 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003262
3263 // Barely shorter
3264 string message(2048 / 8 - 1, 'a');
3265 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3266
3267 // Much shorter
3268 message = "a";
3269 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3270}
3271
3272/*
3273 * SigningOperationsTest.RsaSignWithEncryptionKey
3274 *
3275 * Verifies that RSA encryption keys cannot be used to sign.
3276 */
3277TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3278 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3279 .Authorization(TAG_NO_AUTH_REQUIRED)
3280 .RsaEncryptionKey(2048, 65537)
3281 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003282 .Padding(PaddingMode::NONE)
3283 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003284 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3285 Begin(KeyPurpose::SIGN,
3286 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3287}
3288
3289/*
3290 * SigningOperationsTest.RsaSignTooLargeMessage
3291 *
3292 * Verifies that attempting a raw signature of a message which is the same length as the key,
3293 * but numerically larger than the public modulus, fails with the correct error.
3294 */
3295TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3296 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3297 .Authorization(TAG_NO_AUTH_REQUIRED)
3298 .RsaSigningKey(2048, 65537)
3299 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003300 .Padding(PaddingMode::NONE)
3301 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003302
3303 // Largest possible message will always be larger than the public modulus.
3304 string message(2048 / 8, static_cast<char>(0xff));
3305 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3306 .Authorization(TAG_NO_AUTH_REQUIRED)
3307 .Digest(Digest::NONE)
3308 .Padding(PaddingMode::NONE)));
3309 string signature;
3310 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3311}
3312
3313/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003314 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3315 *
David Drysdale42fe1892021-10-14 14:43:46 +01003316 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003317 */
3318TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003319
3320 string message = "1234567890";
3321 string corrupt_message = "2234567890";
3322 for (auto curve : ValidCurves()) {
3323 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003324 // Ed25519 only allows Digest::NONE.
3325 auto digests = (curve == EcCurve::CURVE_25519)
3326 ? std::vector<Digest>(1, Digest::NONE)
3327 : ValidDigests(true /* withNone */, false /* withMD5 */);
3328
David Drysdaledf8f52e2021-05-06 08:10:58 +01003329 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3330 .Authorization(TAG_NO_AUTH_REQUIRED)
3331 .EcdsaSigningKey(curve)
3332 .Digest(digests)
3333 .SetDefaultValidity());
3334 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3335 if (error != ErrorCode::OK) {
3336 continue;
3337 }
3338
3339 for (auto digest : digests) {
3340 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3341 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3342 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3343 }
3344
3345 auto rc = DeleteKey();
3346 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3347 }
3348}
3349
3350/*
Selene Huang31ab4042020-04-29 04:22:39 -07003351 * SigningOperationsTest.EcdsaAllCurves
3352 *
David Drysdale42fe1892021-10-14 14:43:46 +01003353 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003354 */
3355TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3356 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003357 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3358 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003359 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3360 .Authorization(TAG_NO_AUTH_REQUIRED)
3361 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003362 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003363 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003364 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3365 if (error != ErrorCode::OK) continue;
3366
3367 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003368 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003369 CheckedDeleteKey();
3370 }
3371}
3372
3373/*
David Drysdale42fe1892021-10-14 14:43:46 +01003374 * SigningOperationsTest.EcdsaCurve25519
3375 *
3376 * Verifies that ECDSA operations succeed with curve25519.
3377 */
3378TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3379 if (!Curve25519Supported()) {
3380 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3381 }
3382
3383 EcCurve curve = EcCurve::CURVE_25519;
3384 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3385 .Authorization(TAG_NO_AUTH_REQUIRED)
3386 .EcdsaSigningKey(curve)
3387 .Digest(Digest::NONE)
3388 .SetDefaultValidity());
3389 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3390
3391 string message(1024, 'a');
3392 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3393 CheckedDeleteKey();
3394}
3395
3396/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003397 * SigningOperationsTest.EcdsaCurve25519MaxSize
3398 *
3399 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3400 */
3401TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3402 if (!Curve25519Supported()) {
3403 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3404 }
3405
3406 EcCurve curve = EcCurve::CURVE_25519;
3407 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3408 .Authorization(TAG_NO_AUTH_REQUIRED)
3409 .EcdsaSigningKey(curve)
3410 .Digest(Digest::NONE)
3411 .SetDefaultValidity());
3412 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3413
3414 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3415
3416 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3417 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3418 string message(msg_size, 'a');
3419
3420 // Attempt to sign via Begin+Finish.
3421 AuthorizationSet out_params;
3422 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3423 EXPECT_TRUE(out_params.empty());
3424 string signature;
3425 auto result = Finish(message, &signature);
3426 EXPECT_EQ(result, ErrorCode::OK);
3427 LocalVerifyMessage(message, signature, params);
3428
3429 // Attempt to sign via Begin+Update+Finish
3430 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3431 EXPECT_TRUE(out_params.empty());
3432 string output;
3433 result = Update(message, &output);
3434 EXPECT_EQ(result, ErrorCode::OK);
3435 EXPECT_EQ(output.size(), 0);
3436 string signature2;
3437 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3438 LocalVerifyMessage(message, signature2, params);
3439 }
3440
3441 CheckedDeleteKey();
3442}
3443
3444/*
3445 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3446 *
3447 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3448 */
3449TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3450 if (!Curve25519Supported()) {
3451 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3452 }
3453
3454 EcCurve curve = EcCurve::CURVE_25519;
3455 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3456 .Authorization(TAG_NO_AUTH_REQUIRED)
3457 .EcdsaSigningKey(curve)
3458 .Digest(Digest::NONE)
3459 .SetDefaultValidity());
3460 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3461
3462 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3463
3464 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3465 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3466 string message(msg_size, 'a');
3467
3468 // Attempt to sign via Begin+Finish.
3469 AuthorizationSet out_params;
3470 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3471 EXPECT_TRUE(out_params.empty());
3472 string signature;
3473 auto result = Finish(message, &signature);
3474 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3475
3476 // Attempt to sign via Begin+Update (but never get to Finish)
3477 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3478 EXPECT_TRUE(out_params.empty());
3479 string output;
3480 result = Update(message, &output);
3481 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3482 }
3483
3484 CheckedDeleteKey();
3485}
3486
3487/*
Selene Huang31ab4042020-04-29 04:22:39 -07003488 * SigningOperationsTest.EcdsaNoDigestHugeData
3489 *
3490 * Verifies that ECDSA operations support very large messages, even without digesting. This
3491 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3492 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3493 * the framework.
3494 */
3495TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3496 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3497 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003498 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003499 .Digest(Digest::NONE)
3500 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003501 string message(1 * 1024, 'a');
3502 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3503}
3504
3505/*
3506 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3507 *
3508 * Verifies that using an EC key requires the correct app ID/data.
3509 */
3510TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3511 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3512 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003513 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003514 .Digest(Digest::NONE)
3515 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003516 .Authorization(TAG_APPLICATION_DATA, "appdata")
3517 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003518
3519 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3520
Selene Huang31ab4042020-04-29 04:22:39 -07003521 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3522 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3523 AbortIfNeeded();
3524 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3525 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3526 .Digest(Digest::NONE)
3527 .Authorization(TAG_APPLICATION_ID, "clientid")));
3528 AbortIfNeeded();
3529 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3530 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3531 .Digest(Digest::NONE)
3532 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3533 AbortIfNeeded();
3534 EXPECT_EQ(ErrorCode::OK,
3535 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3536 .Digest(Digest::NONE)
3537 .Authorization(TAG_APPLICATION_DATA, "appdata")
3538 .Authorization(TAG_APPLICATION_ID, "clientid")));
3539 AbortIfNeeded();
3540}
3541
3542/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003543 * SigningOperationsTest.EcdsaIncompatibleDigest
3544 *
3545 * Verifies that using an EC key requires compatible digest.
3546 */
3547TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3548 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3549 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003550 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003551 .Digest(Digest::NONE)
3552 .Digest(Digest::SHA1)
3553 .SetDefaultValidity()));
3554 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3555 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3556 AbortIfNeeded();
3557}
3558
3559/*
Selene Huang31ab4042020-04-29 04:22:39 -07003560 * SigningOperationsTest.AesEcbSign
3561 *
3562 * Verifies that attempts to use AES keys to sign fail in the correct way.
3563 */
3564TEST_P(SigningOperationsTest, AesEcbSign) {
3565 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3566 .Authorization(TAG_NO_AUTH_REQUIRED)
3567 .SigningKey()
3568 .AesEncryptionKey(128)
3569 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3570
3571 AuthorizationSet out_params;
3572 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3573 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3574 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3575 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3576}
3577
3578/*
3579 * SigningOperationsTest.HmacAllDigests
3580 *
3581 * Verifies that HMAC works with all digests.
3582 */
3583TEST_P(SigningOperationsTest, HmacAllDigests) {
3584 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
David Drysdaleb97121d2022-08-12 11:54:08 +01003585 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
Selene Huang31ab4042020-04-29 04:22:39 -07003586 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3587 .Authorization(TAG_NO_AUTH_REQUIRED)
3588 .HmacKey(128)
3589 .Digest(digest)
3590 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3591 << "Failed to create HMAC key with digest " << digest;
3592 string message = "12345678901234567890123456789012";
3593 string signature = MacMessage(message, digest, 160);
3594 EXPECT_EQ(160U / 8U, signature.size())
3595 << "Failed to sign with HMAC key with digest " << digest;
3596 CheckedDeleteKey();
3597 }
3598}
3599
3600/*
3601 * SigningOperationsTest.HmacSha256TooLargeMacLength
3602 *
3603 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3604 * digest size.
3605 */
3606TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3607 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3608 .Authorization(TAG_NO_AUTH_REQUIRED)
3609 .HmacKey(128)
3610 .Digest(Digest::SHA_2_256)
3611 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3612 AuthorizationSet output_params;
3613 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3614 AuthorizationSetBuilder()
3615 .Digest(Digest::SHA_2_256)
3616 .Authorization(TAG_MAC_LENGTH, 264),
3617 &output_params));
3618}
3619
3620/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003621 * SigningOperationsTest.HmacSha256InvalidMacLength
3622 *
3623 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3624 * not a multiple of 8.
3625 */
3626TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3627 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3628 .Authorization(TAG_NO_AUTH_REQUIRED)
3629 .HmacKey(128)
3630 .Digest(Digest::SHA_2_256)
3631 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3632 AuthorizationSet output_params;
3633 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3634 AuthorizationSetBuilder()
3635 .Digest(Digest::SHA_2_256)
3636 .Authorization(TAG_MAC_LENGTH, 161),
3637 &output_params));
3638}
3639
3640/*
Selene Huang31ab4042020-04-29 04:22:39 -07003641 * SigningOperationsTest.HmacSha256TooSmallMacLength
3642 *
3643 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3644 * specified minimum MAC length.
3645 */
3646TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3647 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3648 .Authorization(TAG_NO_AUTH_REQUIRED)
3649 .HmacKey(128)
3650 .Digest(Digest::SHA_2_256)
3651 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3652 AuthorizationSet output_params;
3653 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3654 AuthorizationSetBuilder()
3655 .Digest(Digest::SHA_2_256)
3656 .Authorization(TAG_MAC_LENGTH, 120),
3657 &output_params));
3658}
3659
3660/*
3661 * SigningOperationsTest.HmacRfc4231TestCase3
3662 *
3663 * Validates against the test vectors from RFC 4231 test case 3.
3664 */
3665TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3666 string key(20, 0xaa);
3667 string message(50, 0xdd);
3668 uint8_t sha_224_expected[] = {
3669 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3670 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3671 };
3672 uint8_t sha_256_expected[] = {
3673 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3674 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3675 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3676 };
3677 uint8_t sha_384_expected[] = {
3678 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3679 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3680 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3681 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3682 };
3683 uint8_t sha_512_expected[] = {
3684 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3685 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3686 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3687 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3688 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3689 };
3690
3691 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3692 if (SecLevel() != SecurityLevel::STRONGBOX) {
3693 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3694 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3695 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3696 }
3697}
3698
3699/*
3700 * SigningOperationsTest.HmacRfc4231TestCase5
3701 *
3702 * Validates against the test vectors from RFC 4231 test case 5.
3703 */
3704TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3705 string key(20, 0x0c);
3706 string message = "Test With Truncation";
3707
3708 uint8_t sha_224_expected[] = {
3709 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3710 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3711 };
3712 uint8_t sha_256_expected[] = {
3713 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3714 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3715 };
3716 uint8_t sha_384_expected[] = {
3717 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3718 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3719 };
3720 uint8_t sha_512_expected[] = {
3721 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3722 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3723 };
3724
3725 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3726 if (SecLevel() != SecurityLevel::STRONGBOX) {
3727 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3728 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3729 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3730 }
3731}
3732
3733INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3734
3735typedef KeyMintAidlTestBase VerificationOperationsTest;
3736
3737/*
Selene Huang31ab4042020-04-29 04:22:39 -07003738 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3739 *
3740 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3741 */
3742TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3743 string key_material = "HelloThisIsAKey";
3744
3745 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003746 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003747 EXPECT_EQ(ErrorCode::OK,
3748 ImportKey(AuthorizationSetBuilder()
3749 .Authorization(TAG_NO_AUTH_REQUIRED)
3750 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3751 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3752 .Digest(Digest::SHA_2_256)
3753 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3754 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3755 EXPECT_EQ(ErrorCode::OK,
3756 ImportKey(AuthorizationSetBuilder()
3757 .Authorization(TAG_NO_AUTH_REQUIRED)
3758 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3759 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3760 .Digest(Digest::SHA_2_256)
3761 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3762 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3763
3764 string message = "This is a message.";
3765 string signature = SignMessage(
3766 signing_key, message,
3767 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3768
3769 // Signing key should not work.
3770 AuthorizationSet out_params;
3771 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3772 Begin(KeyPurpose::VERIFY, signing_key,
3773 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3774
3775 // Verification key should work.
3776 VerifyMessage(verification_key, message, signature,
3777 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3778
3779 CheckedDeleteKey(&signing_key);
3780 CheckedDeleteKey(&verification_key);
3781}
3782
Prashant Patildec9fdc2021-12-08 15:25:47 +00003783/*
3784 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3785 *
3786 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3787 */
3788TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3789 string key_material = "HelloThisIsAKey";
3790
3791 vector<uint8_t> signing_key, verification_key;
3792 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3793 EXPECT_EQ(ErrorCode::OK,
3794 ImportKey(AuthorizationSetBuilder()
3795 .Authorization(TAG_NO_AUTH_REQUIRED)
3796 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3797 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3798 .Digest(Digest::SHA_2_256)
3799 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3800 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3801 EXPECT_EQ(ErrorCode::OK,
3802 ImportKey(AuthorizationSetBuilder()
3803 .Authorization(TAG_NO_AUTH_REQUIRED)
3804 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3805 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3806 .Digest(Digest::SHA_2_256)
3807 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3808 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3809
3810 string message = "This is a message.";
3811 string signature = SignMessage(
3812 signing_key, message,
3813 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3814
3815 AuthorizationSet begin_out_params;
3816 ASSERT_EQ(ErrorCode::OK,
3817 Begin(KeyPurpose::VERIFY, verification_key,
3818 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3819
3820 string corruptMessage = "This is b message."; // Corrupted message
3821 string output;
3822 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3823
3824 ASSERT_EQ(ErrorCode::OK,
3825 Begin(KeyPurpose::VERIFY, verification_key,
3826 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3827
3828 signature[0] += 1; // Corrupt a signature
3829 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3830
3831 CheckedDeleteKey(&signing_key);
3832 CheckedDeleteKey(&verification_key);
3833}
3834
Selene Huang31ab4042020-04-29 04:22:39 -07003835INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3836
3837typedef KeyMintAidlTestBase ExportKeyTest;
3838
3839/*
3840 * ExportKeyTest.RsaUnsupportedKeyFormat
3841 *
3842 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3843 */
3844// TODO(seleneh) add ExportKey to GenerateKey
3845// check result
3846
Subrahmanyaman812a9d12022-05-04 02:11:04 +00003847class ImportKeyTest : public NewKeyGenerationTest {
Selene Huang31ab4042020-04-29 04:22:39 -07003848 public:
3849 template <TagType tag_type, Tag tag, typename ValueT>
3850 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3851 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003852 for (auto& entry : key_characteristics_) {
3853 if (entry.securityLevel == SecLevel()) {
3854 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3855 << "Tag " << tag << " with value " << expected
3856 << " not found at security level" << entry.securityLevel;
3857 } else {
3858 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3859 << "Tag " << tag << " found at security level " << entry.securityLevel;
3860 }
Selene Huang31ab4042020-04-29 04:22:39 -07003861 }
3862 }
3863
3864 void CheckOrigin() {
3865 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003866 // Origin isn't a crypto param, but it always lives with them.
3867 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003868 }
3869};
3870
3871/*
3872 * ImportKeyTest.RsaSuccess
3873 *
3874 * Verifies that importing and using an RSA key pair works correctly.
3875 */
3876TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003877 uint32_t key_size;
3878 string key;
3879
3880 if (SecLevel() == SecurityLevel::STRONGBOX) {
3881 key_size = 2048;
3882 key = rsa_2048_key;
3883 } else {
3884 key_size = 1024;
3885 key = rsa_key;
3886 }
3887
Selene Huang31ab4042020-04-29 04:22:39 -07003888 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3889 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003890 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003891 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003892 .Padding(PaddingMode::RSA_PSS)
3893 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003894 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003895
3896 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003897 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003898 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3899 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3900 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3901 CheckOrigin();
3902
3903 string message(1024 / 8, 'a');
3904 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3905 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003906 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003907}
3908
3909/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003910 * ImportKeyTest.RsaSuccessWithoutParams
3911 *
3912 * Verifies that importing and using an RSA key pair without specifying parameters
3913 * works correctly.
3914 */
3915TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3916 uint32_t key_size;
3917 string key;
3918
3919 if (SecLevel() == SecurityLevel::STRONGBOX) {
3920 key_size = 2048;
3921 key = rsa_2048_key;
3922 } else {
3923 key_size = 1024;
3924 key = rsa_key;
3925 }
3926
3927 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3928 .Authorization(TAG_NO_AUTH_REQUIRED)
3929 .SigningKey()
3930 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3931 .Digest(Digest::SHA_2_256)
3932 .Padding(PaddingMode::RSA_PSS)
3933 .SetDefaultValidity(),
3934 KeyFormat::PKCS8, key));
3935
3936 // Key size and public exponent are determined from the imported key material.
3937 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3938 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3939
3940 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3941 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3942 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3943 CheckOrigin();
3944
3945 string message(1024 / 8, 'a');
3946 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3947 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003948 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003949}
3950
3951/*
Selene Huang31ab4042020-04-29 04:22:39 -07003952 * ImportKeyTest.RsaKeySizeMismatch
3953 *
3954 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3955 * correct way.
3956 */
3957TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3958 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3959 ImportKey(AuthorizationSetBuilder()
3960 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3961 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003962 .Padding(PaddingMode::NONE)
3963 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003964 KeyFormat::PKCS8, rsa_key));
3965}
3966
3967/*
3968 * ImportKeyTest.RsaPublicExponentMismatch
3969 *
3970 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3971 * fails in the correct way.
3972 */
3973TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3974 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3975 ImportKey(AuthorizationSetBuilder()
3976 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3977 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003978 .Padding(PaddingMode::NONE)
3979 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003980 KeyFormat::PKCS8, rsa_key));
3981}
3982
3983/*
David Drysdalee60248c2021-10-04 12:54:13 +01003984 * ImportKeyTest.RsaAttestMultiPurposeFail
3985 *
3986 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3987 */
3988TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00003989 if (AidlVersion() < 2) {
3990 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
3991 // with other key purposes. However, this was not checked at the time
3992 // so we can only be strict about checking this for implementations of KeyMint
3993 // version 2 and above.
3994 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
3995 }
David Drysdalee60248c2021-10-04 12:54:13 +01003996 uint32_t key_size = 2048;
3997 string key = rsa_2048_key;
3998
3999 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4000 ImportKey(AuthorizationSetBuilder()
4001 .Authorization(TAG_NO_AUTH_REQUIRED)
4002 .RsaSigningKey(key_size, 65537)
4003 .AttestKey()
4004 .Digest(Digest::SHA_2_256)
4005 .Padding(PaddingMode::RSA_PSS)
4006 .SetDefaultValidity(),
4007 KeyFormat::PKCS8, key));
4008}
4009
4010/*
Selene Huang31ab4042020-04-29 04:22:39 -07004011 * ImportKeyTest.EcdsaSuccess
4012 *
4013 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
4014 */
4015TEST_P(ImportKeyTest, EcdsaSuccess) {
4016 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4017 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004018 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004019 .Digest(Digest::SHA_2_256)
4020 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004021 KeyFormat::PKCS8, ec_256_key));
4022
4023 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004024 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4025 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4026
4027 CheckOrigin();
4028
4029 string message(32, 'a');
4030 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4031 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004032 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004033}
4034
4035/*
4036 * ImportKeyTest.EcdsaP256RFC5915Success
4037 *
4038 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
4039 * correctly.
4040 */
4041TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
4042 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4043 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004044 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004045 .Digest(Digest::SHA_2_256)
4046 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004047 KeyFormat::PKCS8, ec_256_key_rfc5915));
4048
4049 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004050 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4051 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4052
4053 CheckOrigin();
4054
4055 string message(32, 'a');
4056 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4057 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004058 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004059}
4060
4061/*
4062 * ImportKeyTest.EcdsaP256SEC1Success
4063 *
4064 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4065 */
4066TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4067 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4068 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004069 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004070 .Digest(Digest::SHA_2_256)
4071 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004072 KeyFormat::PKCS8, ec_256_key_sec1));
4073
4074 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004075 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4076 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4077
4078 CheckOrigin();
4079
4080 string message(32, 'a');
4081 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4082 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004083 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004084}
4085
4086/*
4087 * ImportKeyTest.Ecdsa521Success
4088 *
4089 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4090 */
4091TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004092 if (SecLevel() == SecurityLevel::STRONGBOX) {
4093 GTEST_SKIP() << "Test not applicable to StrongBox device";
4094 }
Selene Huang31ab4042020-04-29 04:22:39 -07004095 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4096 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004097 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004098 .Digest(Digest::SHA_2_256)
4099 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004100 KeyFormat::PKCS8, ec_521_key));
4101
4102 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004103 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4104 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4105 CheckOrigin();
4106
4107 string message(32, 'a');
4108 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4109 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004110 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004111}
4112
4113/*
Selene Huang31ab4042020-04-29 04:22:39 -07004114 * ImportKeyTest.EcdsaCurveMismatch
4115 *
4116 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4117 * the correct way.
4118 */
4119TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4120 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4121 ImportKey(AuthorizationSetBuilder()
4122 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004123 .Digest(Digest::NONE)
4124 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004125 KeyFormat::PKCS8, ec_256_key));
4126}
4127
4128/*
David Drysdalee60248c2021-10-04 12:54:13 +01004129 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4130 *
4131 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4132 */
4133TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004134 if (AidlVersion() < 2) {
4135 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4136 // with other key purposes. However, this was not checked at the time
4137 // so we can only be strict about checking this for implementations of KeyMint
4138 // version 2 and above.
4139 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4140 }
David Drysdalee60248c2021-10-04 12:54:13 +01004141 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4142 ImportKey(AuthorizationSetBuilder()
4143 .Authorization(TAG_NO_AUTH_REQUIRED)
4144 .EcdsaSigningKey(EcCurve::P_256)
4145 .AttestKey()
4146 .Digest(Digest::SHA_2_256)
4147 .SetDefaultValidity(),
4148 KeyFormat::PKCS8, ec_256_key));
4149}
4150
4151/*
David Drysdale42fe1892021-10-14 14:43:46 +01004152 * ImportKeyTest.Ed25519RawSuccess
4153 *
4154 * Verifies that importing and using a raw Ed25519 private key works correctly.
4155 */
4156TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4157 if (!Curve25519Supported()) {
4158 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4159 }
4160
4161 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4162 .Authorization(TAG_NO_AUTH_REQUIRED)
4163 .EcdsaSigningKey(EcCurve::CURVE_25519)
4164 .Digest(Digest::NONE)
4165 .SetDefaultValidity(),
4166 KeyFormat::RAW, ed25519_key));
4167 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4168 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4169 CheckOrigin();
4170
4171 // The returned cert should hold the correct public key.
4172 ASSERT_GT(cert_chain_.size(), 0);
4173 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4174 ASSERT_NE(kmKeyCert, nullptr);
4175 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4176 ASSERT_NE(kmPubKey.get(), nullptr);
4177 size_t kmPubKeySize = 32;
4178 uint8_t kmPubKeyData[32];
4179 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4180 ASSERT_EQ(kmPubKeySize, 32);
4181 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4182
4183 string message(32, 'a');
4184 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4185 string signature = SignMessage(message, params);
4186 LocalVerifyMessage(message, signature, params);
4187}
4188
4189/*
4190 * ImportKeyTest.Ed25519Pkcs8Success
4191 *
4192 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4193 */
4194TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4195 if (!Curve25519Supported()) {
4196 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4197 }
4198
4199 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4200 .Authorization(TAG_NO_AUTH_REQUIRED)
4201 .EcdsaSigningKey(EcCurve::CURVE_25519)
4202 .Digest(Digest::NONE)
4203 .SetDefaultValidity(),
4204 KeyFormat::PKCS8, ed25519_pkcs8_key));
4205 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4206 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4207 CheckOrigin();
4208
4209 // The returned cert should hold the correct public key.
4210 ASSERT_GT(cert_chain_.size(), 0);
4211 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4212 ASSERT_NE(kmKeyCert, nullptr);
4213 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4214 ASSERT_NE(kmPubKey.get(), nullptr);
4215 size_t kmPubKeySize = 32;
4216 uint8_t kmPubKeyData[32];
4217 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4218 ASSERT_EQ(kmPubKeySize, 32);
4219 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4220
4221 string message(32, 'a');
4222 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4223 string signature = SignMessage(message, params);
4224 LocalVerifyMessage(message, signature, params);
4225}
4226
4227/*
4228 * ImportKeyTest.Ed25519CurveMismatch
4229 *
4230 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4231 * the correct way.
4232 */
4233TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4234 if (!Curve25519Supported()) {
4235 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4236 }
4237
4238 ASSERT_NE(ErrorCode::OK,
4239 ImportKey(AuthorizationSetBuilder()
4240 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4241 .Digest(Digest::NONE)
4242 .SetDefaultValidity(),
4243 KeyFormat::RAW, ed25519_key));
4244}
4245
4246/*
4247 * ImportKeyTest.Ed25519FormatMismatch
4248 *
4249 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4250 */
4251TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4252 if (!Curve25519Supported()) {
4253 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4254 }
4255
4256 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4257 .EcdsaSigningKey(EcCurve::CURVE_25519)
4258 .Digest(Digest::NONE)
4259 .SetDefaultValidity(),
4260 KeyFormat::PKCS8, ed25519_key));
4261 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4262 .EcdsaSigningKey(EcCurve::CURVE_25519)
4263 .Digest(Digest::NONE)
4264 .SetDefaultValidity(),
4265 KeyFormat::RAW, ed25519_pkcs8_key));
4266}
4267
4268/*
4269 * ImportKeyTest.Ed25519PurposeMismatch
4270 *
4271 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4272 */
4273TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4274 if (!Curve25519Supported()) {
4275 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4276 }
4277
4278 // Can't have both SIGN and ATTEST_KEY
4279 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4280 .EcdsaSigningKey(EcCurve::CURVE_25519)
4281 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4282 .Digest(Digest::NONE)
4283 .SetDefaultValidity(),
4284 KeyFormat::RAW, ed25519_key));
4285 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4286 // PKCS#8 format and so includes an OID).
4287 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4288 .EcdsaKey(EcCurve::CURVE_25519)
4289 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4290 .Digest(Digest::NONE)
4291 .SetDefaultValidity(),
4292 KeyFormat::PKCS8, ed25519_pkcs8_key));
4293}
4294
4295/*
4296 * ImportKeyTest.X25519RawSuccess
4297 *
4298 * Verifies that importing and using a raw X25519 private key works correctly.
4299 */
4300TEST_P(ImportKeyTest, X25519RawSuccess) {
4301 if (!Curve25519Supported()) {
4302 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4303 }
4304
4305 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4306 .Authorization(TAG_NO_AUTH_REQUIRED)
4307 .EcdsaKey(EcCurve::CURVE_25519)
4308 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4309 .SetDefaultValidity(),
4310 KeyFormat::RAW, x25519_key));
4311
4312 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4313 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4314 CheckOrigin();
4315}
4316
4317/*
4318 * ImportKeyTest.X25519Pkcs8Success
4319 *
4320 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4321 */
4322TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4323 if (!Curve25519Supported()) {
4324 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4325 }
4326
4327 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4328 .Authorization(TAG_NO_AUTH_REQUIRED)
4329 .EcdsaKey(EcCurve::CURVE_25519)
4330 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4331 .SetDefaultValidity(),
4332 KeyFormat::PKCS8, x25519_pkcs8_key));
4333
4334 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4335 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4336 CheckOrigin();
4337}
4338
4339/*
4340 * ImportKeyTest.X25519CurveMismatch
4341 *
4342 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4343 * the correct way.
4344 */
4345TEST_P(ImportKeyTest, X25519CurveMismatch) {
4346 if (!Curve25519Supported()) {
4347 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4348 }
4349
4350 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4351 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4352 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4353 .SetDefaultValidity(),
4354 KeyFormat::RAW, x25519_key));
4355}
4356
4357/*
4358 * ImportKeyTest.X25519FormatMismatch
4359 *
4360 * Verifies that importing an X25519 key with an invalid format fails.
4361 */
4362TEST_P(ImportKeyTest, X25519FormatMismatch) {
4363 if (!Curve25519Supported()) {
4364 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4365 }
4366
4367 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4368 .EcdsaKey(EcCurve::CURVE_25519)
4369 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4370 .SetDefaultValidity(),
4371 KeyFormat::PKCS8, x25519_key));
4372 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4373 .EcdsaKey(EcCurve::CURVE_25519)
4374 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4375 .SetDefaultValidity(),
4376 KeyFormat::RAW, x25519_pkcs8_key));
4377}
4378
4379/*
4380 * ImportKeyTest.X25519PurposeMismatch
4381 *
4382 * Verifies that importing an X25519 key pair with an invalid format fails.
4383 */
4384TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4385 if (!Curve25519Supported()) {
4386 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4387 }
4388
4389 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4390 .EcdsaKey(EcCurve::CURVE_25519)
4391 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4392 .SetDefaultValidity(),
4393 KeyFormat::PKCS8, x25519_pkcs8_key));
4394 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4395 .EcdsaSigningKey(EcCurve::CURVE_25519)
4396 .SetDefaultValidity(),
4397 KeyFormat::PKCS8, x25519_pkcs8_key));
4398}
4399
4400/*
Selene Huang31ab4042020-04-29 04:22:39 -07004401 * ImportKeyTest.AesSuccess
4402 *
4403 * Verifies that importing and using an AES key works.
4404 */
4405TEST_P(ImportKeyTest, AesSuccess) {
4406 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4407 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4408 .Authorization(TAG_NO_AUTH_REQUIRED)
4409 .AesEncryptionKey(key.size() * 8)
4410 .EcbMode()
4411 .Padding(PaddingMode::PKCS7),
4412 KeyFormat::RAW, key));
4413
4414 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4415 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4416 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4417 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4418 CheckOrigin();
4419
4420 string message = "Hello World!";
4421 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4422 string ciphertext = EncryptMessage(message, params);
4423 string plaintext = DecryptMessage(ciphertext, params);
4424 EXPECT_EQ(message, plaintext);
4425}
4426
4427/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004428 * ImportKeyTest.AesFailure
4429 *
4430 * Verifies that importing an invalid AES key fails.
4431 */
4432TEST_P(ImportKeyTest, AesFailure) {
4433 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4434 uint32_t bitlen = key.size() * 8;
4435 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004436 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004437 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004438 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004439 .Authorization(TAG_NO_AUTH_REQUIRED)
4440 .AesEncryptionKey(key_size)
4441 .EcbMode()
4442 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004443 KeyFormat::RAW, key);
4444 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004445 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4446 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004447 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004448
4449 // Explicit key size matches that of the provided key, but it's not a valid size.
4450 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4451 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4452 ImportKey(AuthorizationSetBuilder()
4453 .Authorization(TAG_NO_AUTH_REQUIRED)
4454 .AesEncryptionKey(long_key.size() * 8)
4455 .EcbMode()
4456 .Padding(PaddingMode::PKCS7),
4457 KeyFormat::RAW, long_key));
4458 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4459 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4460 ImportKey(AuthorizationSetBuilder()
4461 .Authorization(TAG_NO_AUTH_REQUIRED)
4462 .AesEncryptionKey(short_key.size() * 8)
4463 .EcbMode()
4464 .Padding(PaddingMode::PKCS7),
4465 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004466}
4467
4468/*
4469 * ImportKeyTest.TripleDesSuccess
4470 *
4471 * Verifies that importing and using a 3DES key works.
4472 */
4473TEST_P(ImportKeyTest, TripleDesSuccess) {
4474 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4475 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4476 .Authorization(TAG_NO_AUTH_REQUIRED)
4477 .TripleDesEncryptionKey(168)
4478 .EcbMode()
4479 .Padding(PaddingMode::PKCS7),
4480 KeyFormat::RAW, key));
4481
4482 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4483 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4484 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4485 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4486 CheckOrigin();
4487
4488 string message = "Hello World!";
4489 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4490 string ciphertext = EncryptMessage(message, params);
4491 string plaintext = DecryptMessage(ciphertext, params);
4492 EXPECT_EQ(message, plaintext);
4493}
4494
4495/*
4496 * ImportKeyTest.TripleDesFailure
4497 *
4498 * Verifies that importing an invalid 3DES key fails.
4499 */
4500TEST_P(ImportKeyTest, TripleDesFailure) {
4501 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004502 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004503 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004504 SCOPED_TRACE(testing::Message() << "import-key-size=" << key_size);
David Drysdalec9bc2f72021-05-04 10:47:58 +01004505 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004506 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004507 .Authorization(TAG_NO_AUTH_REQUIRED)
4508 .TripleDesEncryptionKey(key_size)
4509 .EcbMode()
4510 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004511 KeyFormat::RAW, key);
4512 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004513 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4514 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004515 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004516 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004517 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004518 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4519 ImportKey(AuthorizationSetBuilder()
4520 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004521 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004522 .EcbMode()
4523 .Padding(PaddingMode::PKCS7),
4524 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004525 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004526 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4527 ImportKey(AuthorizationSetBuilder()
4528 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004529 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004530 .EcbMode()
4531 .Padding(PaddingMode::PKCS7),
4532 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004533}
4534
4535/*
4536 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004537 *
4538 * Verifies that importing and using an HMAC key works.
4539 */
4540TEST_P(ImportKeyTest, HmacKeySuccess) {
4541 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4542 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4543 .Authorization(TAG_NO_AUTH_REQUIRED)
4544 .HmacKey(key.size() * 8)
4545 .Digest(Digest::SHA_2_256)
4546 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4547 KeyFormat::RAW, key));
4548
4549 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4550 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4551 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4552 CheckOrigin();
4553
4554 string message = "Hello World!";
4555 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4556 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4557}
4558
Subrahmanyaman812a9d12022-05-04 02:11:04 +00004559/*
4560 * ImportKeyTest.GetKeyCharacteristics
4561 *
4562 * Verifies that imported keys have the correct characteristics.
4563 */
4564TEST_P(ImportKeyTest, GetKeyCharacteristics) {
4565 vector<uint8_t> key_blob;
4566 vector<KeyCharacteristics> key_characteristics;
4567 auto base_builder = AuthorizationSetBuilder()
4568 .Padding(PaddingMode::NONE)
4569 .Authorization(TAG_NO_AUTH_REQUIRED)
4570 .SetDefaultValidity();
4571 vector<Algorithm> algorithms = {Algorithm::RSA, Algorithm::EC, Algorithm::HMAC, Algorithm::AES,
4572 Algorithm::TRIPLE_DES};
4573 ErrorCode result;
4574 string symKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98"); // 128 bits
4575 string tdesKey = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358"); // 192 bits
4576 for (auto alg : algorithms) {
4577 SCOPED_TRACE(testing::Message() << "Algorithm-" << alg);
4578 AuthorizationSetBuilder builder(base_builder);
4579 switch (alg) {
4580 case Algorithm::RSA:
4581 builder.RsaSigningKey(2048, 65537).Digest(Digest::NONE);
4582
4583 result = ImportKey(builder, KeyFormat::PKCS8, rsa_2048_key, &key_blob,
4584 &key_characteristics);
4585 break;
4586 case Algorithm::EC:
4587 builder.EcdsaSigningKey(EcCurve::P_256).Digest(Digest::NONE);
4588 result = ImportKey(builder, KeyFormat::PKCS8, ec_256_key, &key_blob,
4589 &key_characteristics);
4590 break;
4591 case Algorithm::HMAC:
4592 builder.HmacKey(128)
4593 .Digest(Digest::SHA_2_256)
4594 .Authorization(TAG_MIN_MAC_LENGTH, 128);
4595 result =
4596 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4597 break;
4598 case Algorithm::AES:
4599 builder.AesEncryptionKey(128).BlockMode(BlockMode::ECB);
4600 result =
4601 ImportKey(builder, KeyFormat::RAW, symKey, &key_blob, &key_characteristics);
4602 break;
4603 case Algorithm::TRIPLE_DES:
4604 builder.TripleDesEncryptionKey(168).BlockMode(BlockMode::ECB);
4605 result = ImportKey(builder, KeyFormat::RAW, tdesKey, &key_blob,
4606 &key_characteristics);
4607 break;
4608 default:
4609 ADD_FAILURE() << "Invalid Algorithm " << uint32_t(alg);
4610 continue;
4611 }
4612 ASSERT_EQ(ErrorCode::OK, result);
4613 CheckCharacteristics(key_blob, key_characteristics);
4614 CheckCommonParams(key_characteristics, KeyOrigin::IMPORTED);
4615 }
4616}
4617
Selene Huang31ab4042020-04-29 04:22:39 -07004618INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4619
4620auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004621 // IKeyMintDevice.aidl
4622 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4623 "020100" // INTEGER length 1 value 0x00 (version)
4624 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4625 "934bf94e2aa28a3f83c9f79297250262"
4626 "fbe3276b5a1c91159bbfa3ef8957aac8"
4627 "4b59b30b455a79c2973480823d8b3863"
4628 "c3deef4a8e243590268d80e18751a0e1"
4629 "30f67ce6a1ace9f79b95e097474febc9"
4630 "81195b1d13a69086c0863f66a7b7fdb4"
4631 "8792227b1ac5e2489febdf087ab54864"
4632 "83033a6f001ca5d1ec1e27f5c30f4cec"
4633 "2642074a39ae68aee552e196627a8e3d"
4634 "867e67a8c01b11e75f13cca0a97ab668"
4635 "b50cda07a8ecb7cd8e3dd7009c963653"
4636 "4f6f239cffe1fc8daa466f78b676c711"
4637 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4638 "99b801597d5220e307eaa5bee507fb94"
4639 "d1fa69f9e519b2de315bac92c36f2ea1"
4640 "fa1df4478c0ddedeae8c70e0233cd098"
4641 "040c" // OCTET STRING length 0x0c (initializationVector)
4642 "d796b02c370f1fa4cc0124f1"
4643 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4644 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4645 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4646 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4647 "3106" // SET length 0x06
4648 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4649 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4650 // } end SET
4651 // } end [1]
4652 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4653 "020120" // INTEGER length 1 value 0x20 (AES)
4654 // } end [2]
4655 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4656 "02020100" // INTEGER length 2 value 0x100
4657 // } end [3]
4658 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4659 "3103" // SET length 0x03 {
4660 "020101" // INTEGER length 1 value 0x01 (ECB)
4661 // } end SET
4662 // } end [4]
4663 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4664 "3103" // SET length 0x03 {
4665 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4666 // } end SET
4667 // } end [5]
4668 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4669 // (noAuthRequired)
4670 "0500" // NULL
4671 // } end [503]
4672 // } end SEQUENCE (AuthorizationList)
4673 // } end SEQUENCE (KeyDescription)
4674 "0420" // OCTET STRING length 0x20 (encryptedKey)
4675 "ccd540855f833a5e1480bfd2d36faf3a"
4676 "eee15df5beabe2691bc82dde2a7aa910"
4677 "0410" // OCTET STRING length 0x10 (tag)
4678 "64c9f689c60ff6223ab6e6999e0eb6e5"
4679 // } SEQUENCE (SecureKeyWrapper)
4680);
Selene Huang31ab4042020-04-29 04:22:39 -07004681
4682auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004683 // IKeyMintDevice.aidl
4684 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4685 "020100" // INTEGER length 1 value 0x00 (version)
4686 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4687 "aad93ed5924f283b4bb5526fbe7a1412"
4688 "f9d9749ec30db9062b29e574a8546f33"
4689 "c88732452f5b8e6a391ee76c39ed1712"
4690 "c61d8df6213dec1cffbc17a8c6d04c7b"
4691 "30893d8daa9b2015213e219468215532"
4692 "07f8f9931c4caba23ed3bee28b36947e"
4693 "47f10e0a5c3dc51c988a628daad3e5e1"
4694 "f4005e79c2d5a96c284b4b8d7e4948f3"
4695 "31e5b85dd5a236f85579f3ea1d1b8484"
4696 "87470bdb0ab4f81a12bee42c99fe0df4"
4697 "bee3759453e69ad1d68a809ce06b949f"
4698 "7694a990429b2fe81e066ff43e56a216"
4699 "02db70757922a4bcc23ab89f1e35da77"
4700 "586775f423e519c2ea394caf48a28d0c"
4701 "8020f1dcf6b3a68ec246f615ae96dae9"
4702 "a079b1f6eb959033c1af5c125fd94168"
4703 "040c" // OCTET STRING length 0x0c (initializationVector)
4704 "6d9721d08589581ab49204a3"
4705 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4706 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4707 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4708 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4709 "3106" // SET length 0x06
4710 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4711 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4712 // } end SET
4713 // } end [1]
4714 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4715 "020120" // INTEGER length 1 value 0x20 (AES)
4716 // } end [2]
4717 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4718 "02020100" // INTEGER length 2 value 0x100
4719 // } end [3]
4720 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4721 "3103" // SET length 0x03 {
4722 "020101" // INTEGER length 1 value 0x01 (ECB)
4723 // } end SET
4724 // } end [4]
4725 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4726 "3103" // SET length 0x03 {
4727 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4728 // } end SET
4729 // } end [5]
4730 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4731 // (noAuthRequired)
4732 "0500" // NULL
4733 // } end [503]
4734 // } end SEQUENCE (AuthorizationList)
4735 // } end SEQUENCE (KeyDescription)
4736 "0420" // OCTET STRING length 0x20 (encryptedKey)
4737 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4738 "c20d1f99a9a024a76f35c8e2cab9b68d"
4739 "0410" // OCTET STRING length 0x10 (tag)
4740 "2560c70109ae67c030f00b98b512a670"
4741 // } SEQUENCE (SecureKeyWrapper)
4742);
Selene Huang31ab4042020-04-29 04:22:39 -07004743
4744auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004745 // RFC 5208 s5
4746 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4747 "020100" // INTEGER length 1 value 0x00 (version)
4748 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4749 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4750 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4751 "0500" // NULL (parameters)
4752 // } SEQUENCE (AlgorithmIdentifier)
4753 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4754 // RFC 8017 A.1.2
4755 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4756 "020100" // INTEGER length 1 value 0x00 (version)
4757 "02820101" // INTEGER length 0x0101 (modulus) value...
4758 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4759 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4760 "7b06e673a837313d56b1c725150a3fef" // 0x30
4761 "86acbddc41bb759c2854eae32d35841e" // 0x40
4762 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4763 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4764 "312d7bd5921ffaea1347c157406fef71" // 0x70
4765 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4766 "f4645c11f5c1374c3886427411c44979" // 0x90
4767 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4768 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4769 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4770 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4771 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4772 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4773 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4774 "55" // 0x101
4775 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4776 "02820100" // INTEGER length 0x100 (privateExponent) value...
4777 "431447b6251908112b1ee76f99f3711a" // 0x10
4778 "52b6630960046c2de70de188d833f8b8" // 0x20
4779 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4780 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4781 "e710b630a03adc683b5d2c43080e52be" // 0x50
4782 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4783 "822bccff087d63c940ba8a45f670feb2" // 0x70
4784 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4785 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4786 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4787 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4788 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4789 "52659d5a5ba05b663737a8696281865b" // 0xd0
4790 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4791 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4792 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4793 "028181" // INTEGER length 0x81 (prime1) value...
4794 "00de392e18d682c829266cc3454e1d61" // 0x10
4795 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4796 "ff841be5bac82a164c5970007047b8c5" // 0x30
4797 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4798 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4799 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4800 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4801 "9e91346130748a6e3c124f9149d71c74" // 0x80
4802 "35"
4803 "028181" // INTEGER length 0x81 (prime2) value...
4804 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4805 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4806 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4807 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4808 "9ed39a2d934c880440aed8832f984316" // 0x50
4809 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4810 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4811 "b880677c068e1be936e81288815252a8" // 0x80
4812 "a1"
4813 "028180" // INTEGER length 0x80 (exponent1) value...
4814 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4815 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4816 "5a063212a4f105a3764743e53281988a" // 0x30
4817 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4818 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4819 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4820 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4821 "4719d6e2b9439823719cd08bcd031781" // 0x80
4822 "028181" // INTEGER length 0x81 (exponent2) value...
4823 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4824 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4825 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4826 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4827 "1254186af30b22c10582a8a43e34fe94" // 0x50
4828 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4829 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4830 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4831 "61"
4832 "028181" // INTEGER length 0x81 (coefficient) value...
4833 "00c931617c77829dfb1270502be9195c" // 0x10
4834 "8f2830885f57dba869536811e6864236" // 0x20
4835 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4836 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4837 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4838 "959356210723287b0affcc9f727044d4" // 0x60
4839 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4840 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4841 "22"
4842 // } SEQUENCE
4843 // } SEQUENCE ()
4844);
Selene Huang31ab4042020-04-29 04:22:39 -07004845
4846string zero_masking_key =
4847 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4848string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4849
4850class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4851
4852TEST_P(ImportWrappedKeyTest, Success) {
4853 auto wrapping_key_desc = AuthorizationSetBuilder()
4854 .RsaEncryptionKey(2048, 65537)
4855 .Digest(Digest::SHA_2_256)
4856 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004857 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4858 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004859
4860 ASSERT_EQ(ErrorCode::OK,
4861 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4862 AuthorizationSetBuilder()
4863 .Digest(Digest::SHA_2_256)
4864 .Padding(PaddingMode::RSA_OAEP)));
4865
4866 string message = "Hello World!";
4867 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4868 string ciphertext = EncryptMessage(message, params);
4869 string plaintext = DecryptMessage(ciphertext, params);
4870 EXPECT_EQ(message, plaintext);
4871}
4872
David Drysdaled2cc8c22021-04-15 13:29:45 +01004873/*
4874 * ImportWrappedKeyTest.SuccessSidsIgnored
4875 *
4876 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4877 * include Tag:USER_SECURE_ID.
4878 */
4879TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4880 auto wrapping_key_desc = AuthorizationSetBuilder()
4881 .RsaEncryptionKey(2048, 65537)
4882 .Digest(Digest::SHA_2_256)
4883 .Padding(PaddingMode::RSA_OAEP)
4884 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4885 .SetDefaultValidity();
4886
4887 int64_t password_sid = 42;
4888 int64_t biometric_sid = 24;
4889 ASSERT_EQ(ErrorCode::OK,
4890 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4891 AuthorizationSetBuilder()
4892 .Digest(Digest::SHA_2_256)
4893 .Padding(PaddingMode::RSA_OAEP),
4894 password_sid, biometric_sid));
4895
4896 string message = "Hello World!";
4897 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4898 string ciphertext = EncryptMessage(message, params);
4899 string plaintext = DecryptMessage(ciphertext, params);
4900 EXPECT_EQ(message, plaintext);
4901}
4902
Selene Huang31ab4042020-04-29 04:22:39 -07004903TEST_P(ImportWrappedKeyTest, SuccessMasked) {
4904 auto wrapping_key_desc = AuthorizationSetBuilder()
4905 .RsaEncryptionKey(2048, 65537)
4906 .Digest(Digest::SHA_2_256)
4907 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004908 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4909 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004910
4911 ASSERT_EQ(ErrorCode::OK,
4912 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
4913 AuthorizationSetBuilder()
4914 .Digest(Digest::SHA_2_256)
4915 .Padding(PaddingMode::RSA_OAEP)));
4916}
4917
4918TEST_P(ImportWrappedKeyTest, WrongMask) {
4919 auto wrapping_key_desc = AuthorizationSetBuilder()
4920 .RsaEncryptionKey(2048, 65537)
4921 .Digest(Digest::SHA_2_256)
4922 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004923 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4924 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004925
4926 ASSERT_EQ(
4927 ErrorCode::VERIFICATION_FAILED,
4928 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4929 AuthorizationSetBuilder()
4930 .Digest(Digest::SHA_2_256)
4931 .Padding(PaddingMode::RSA_OAEP)));
4932}
4933
4934TEST_P(ImportWrappedKeyTest, WrongPurpose) {
4935 auto wrapping_key_desc = AuthorizationSetBuilder()
4936 .RsaEncryptionKey(2048, 65537)
4937 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004938 .Padding(PaddingMode::RSA_OAEP)
4939 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004940
4941 ASSERT_EQ(
4942 ErrorCode::INCOMPATIBLE_PURPOSE,
4943 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4944 AuthorizationSetBuilder()
4945 .Digest(Digest::SHA_2_256)
4946 .Padding(PaddingMode::RSA_OAEP)));
4947}
4948
David Drysdaled2cc8c22021-04-15 13:29:45 +01004949TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
4950 auto wrapping_key_desc = AuthorizationSetBuilder()
4951 .RsaEncryptionKey(2048, 65537)
4952 .Digest(Digest::SHA_2_256)
4953 .Padding(PaddingMode::RSA_PSS)
4954 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4955 .SetDefaultValidity();
4956
4957 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
4958 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4959 AuthorizationSetBuilder()
4960 .Digest(Digest::SHA_2_256)
4961 .Padding(PaddingMode::RSA_OAEP)));
4962}
4963
4964TEST_P(ImportWrappedKeyTest, WrongDigest) {
4965 auto wrapping_key_desc = AuthorizationSetBuilder()
4966 .RsaEncryptionKey(2048, 65537)
David Drysdaled2cc8c22021-04-15 13:29:45 +01004967 .Padding(PaddingMode::RSA_OAEP)
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08004968 .Digest(Digest::SHA_2_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01004969 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4970 .SetDefaultValidity();
4971
4972 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
4973 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4974 AuthorizationSetBuilder()
Tommy Chiu4fdcccc2022-10-25 20:56:47 +08004975 .Digest(Digest::SHA_2_512)
David Drysdaled2cc8c22021-04-15 13:29:45 +01004976 .Padding(PaddingMode::RSA_OAEP)));
4977}
4978
Selene Huang31ab4042020-04-29 04:22:39 -07004979INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
4980
4981typedef KeyMintAidlTestBase EncryptionOperationsTest;
4982
4983/*
4984 * EncryptionOperationsTest.RsaNoPaddingSuccess
4985 *
David Drysdale59cae642021-05-12 13:52:03 +01004986 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004987 */
4988TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00004989 for (uint64_t exponent : ValidExponents()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01004990 SCOPED_TRACE(testing::Message() << "RSA exponent=" << exponent);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004991 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4992 .Authorization(TAG_NO_AUTH_REQUIRED)
4993 .RsaEncryptionKey(2048, exponent)
4994 .Padding(PaddingMode::NONE)
4995 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004996
David Drysdaled2cc8c22021-04-15 13:29:45 +01004997 string message = string(2048 / 8, 'a');
4998 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004999 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005000 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005001
David Drysdale59cae642021-05-12 13:52:03 +01005002 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005003 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07005004
David Drysdaled2cc8c22021-04-15 13:29:45 +01005005 // Unpadded RSA is deterministic
5006 EXPECT_EQ(ciphertext1, ciphertext2);
5007
5008 CheckedDeleteKey();
5009 }
Selene Huang31ab4042020-04-29 04:22:39 -07005010}
5011
5012/*
5013 * EncryptionOperationsTest.RsaNoPaddingShortMessage
5014 *
David Drysdale59cae642021-05-12 13:52:03 +01005015 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07005016 */
5017TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
5018 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5019 .Authorization(TAG_NO_AUTH_REQUIRED)
5020 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005021 .Padding(PaddingMode::NONE)
5022 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005023
5024 string message = "1";
5025 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
5026
David Drysdale59cae642021-05-12 13:52:03 +01005027 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005028 EXPECT_EQ(2048U / 8, ciphertext.size());
5029
5030 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
5031 string plaintext = DecryptMessage(ciphertext, params);
5032
5033 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07005034}
5035
5036/*
Selene Huang31ab4042020-04-29 04:22:39 -07005037 * EncryptionOperationsTest.RsaOaepSuccess
5038 *
David Drysdale59cae642021-05-12 13:52:03 +01005039 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07005040 */
5041TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
5042 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5043
5044 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01005045 ASSERT_EQ(ErrorCode::OK,
5046 GenerateKey(AuthorizationSetBuilder()
5047 .Authorization(TAG_NO_AUTH_REQUIRED)
5048 .RsaEncryptionKey(key_size, 65537)
5049 .Padding(PaddingMode::RSA_OAEP)
5050 .Digest(digests)
5051 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
5052 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005053
5054 string message = "Hello";
5055
5056 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01005057 SCOPED_TRACE(testing::Message() << "digest-" << digest);
5058
5059 auto params = AuthorizationSetBuilder()
5060 .Digest(digest)
5061 .Padding(PaddingMode::RSA_OAEP)
5062 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
5063 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005064 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5065 EXPECT_EQ(key_size / 8, ciphertext1.size());
5066
David Drysdale59cae642021-05-12 13:52:03 +01005067 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005068 EXPECT_EQ(key_size / 8, ciphertext2.size());
5069
5070 // OAEP randomizes padding so every result should be different (with astronomically high
5071 // probability).
5072 EXPECT_NE(ciphertext1, ciphertext2);
5073
5074 string plaintext1 = DecryptMessage(ciphertext1, params);
5075 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5076 string plaintext2 = DecryptMessage(ciphertext2, params);
5077 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5078
5079 // Decrypting corrupted ciphertext should fail.
5080 size_t offset_to_corrupt = random() % ciphertext1.size();
5081 char corrupt_byte;
5082 do {
5083 corrupt_byte = static_cast<char>(random() % 256);
5084 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5085 ciphertext1[offset_to_corrupt] = corrupt_byte;
5086
5087 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5088 string result;
5089 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5090 EXPECT_EQ(0U, result.size());
5091 }
5092}
5093
5094/*
5095 * EncryptionOperationsTest.RsaOaepInvalidDigest
5096 *
David Drysdale59cae642021-05-12 13:52:03 +01005097 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07005098 * without a digest.
5099 */
5100TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
5101 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5102 .Authorization(TAG_NO_AUTH_REQUIRED)
5103 .RsaEncryptionKey(2048, 65537)
5104 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005105 .Digest(Digest::NONE)
5106 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005107
5108 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005109 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07005110}
5111
5112/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005113 * EncryptionOperationsTest.RsaOaepInvalidPadding
5114 *
David Drysdale59cae642021-05-12 13:52:03 +01005115 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005116 * with a padding value that is only suitable for signing/verifying.
5117 */
5118TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5119 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5120 .Authorization(TAG_NO_AUTH_REQUIRED)
5121 .RsaEncryptionKey(2048, 65537)
5122 .Padding(PaddingMode::RSA_PSS)
5123 .Digest(Digest::NONE)
5124 .SetDefaultValidity()));
5125
5126 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005127 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005128}
5129
5130/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005131 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005132 *
David Drysdale59cae642021-05-12 13:52:03 +01005133 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005134 * with a different digest than was used to encrypt.
5135 */
5136TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005137 if (SecLevel() == SecurityLevel::STRONGBOX) {
5138 GTEST_SKIP() << "Test not applicable to StrongBox device";
5139 }
Selene Huang31ab4042020-04-29 04:22:39 -07005140
5141 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5142 .Authorization(TAG_NO_AUTH_REQUIRED)
5143 .RsaEncryptionKey(1024, 65537)
5144 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005145 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5146 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005147 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005148 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005149 message,
5150 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5151
5152 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5153 .Digest(Digest::SHA_2_256)
5154 .Padding(PaddingMode::RSA_OAEP)));
5155 string result;
5156 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5157 EXPECT_EQ(0U, result.size());
5158}
5159
5160/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005161 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5162 *
David Drysdale59cae642021-05-12 13:52:03 +01005163 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005164 * digests.
5165 */
5166TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5167 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5168
5169 size_t key_size = 2048; // Need largish key for SHA-512 test.
5170 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5171 .OaepMGFDigest(digests)
5172 .Authorization(TAG_NO_AUTH_REQUIRED)
5173 .RsaEncryptionKey(key_size, 65537)
5174 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005175 .Digest(Digest::SHA_2_256)
5176 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005177
5178 string message = "Hello";
5179
5180 for (auto digest : digests) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005181 SCOPED_TRACE(testing::Message() << "digest-" << digest);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005182 auto params = AuthorizationSetBuilder()
5183 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5184 .Digest(Digest::SHA_2_256)
5185 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005186 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005187 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5188 EXPECT_EQ(key_size / 8, ciphertext1.size());
5189
David Drysdale59cae642021-05-12 13:52:03 +01005190 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005191 EXPECT_EQ(key_size / 8, ciphertext2.size());
5192
5193 // OAEP randomizes padding so every result should be different (with astronomically high
5194 // probability).
5195 EXPECT_NE(ciphertext1, ciphertext2);
5196
5197 string plaintext1 = DecryptMessage(ciphertext1, params);
5198 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5199 string plaintext2 = DecryptMessage(ciphertext2, params);
5200 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5201
5202 // Decrypting corrupted ciphertext should fail.
5203 size_t offset_to_corrupt = random() % ciphertext1.size();
5204 char corrupt_byte;
5205 do {
5206 corrupt_byte = static_cast<char>(random() % 256);
5207 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5208 ciphertext1[offset_to_corrupt] = corrupt_byte;
5209
5210 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5211 string result;
5212 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5213 EXPECT_EQ(0U, result.size());
5214 }
5215}
5216
5217/*
David Drysdaleae3727b2021-11-11 09:00:14 +00005218 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultSuccess
5219 *
5220 * Verifies that RSA-OAEP decryption operations work when no MGF digest is
5221 * specified, defaulting to SHA-1.
5222 */
5223TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultSuccess) {
5224 size_t key_size = 2048;
5225 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5226 .Authorization(TAG_NO_AUTH_REQUIRED)
5227 .RsaEncryptionKey(key_size, 65537)
5228 .Padding(PaddingMode::RSA_OAEP)
5229 .Digest(Digest::SHA_2_256)
5230 .SetDefaultValidity()));
5231
5232 // Do local RSA encryption using the default MGF digest of SHA-1.
5233 string message = "Hello";
5234 auto params =
5235 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5236 string ciphertext = LocalRsaEncryptMessage(message, params);
5237 EXPECT_EQ(key_size / 8, ciphertext.size());
5238
5239 // Do KeyMint RSA decryption also using the default MGF digest of SHA-1.
5240 string plaintext = DecryptMessage(ciphertext, params);
5241 EXPECT_EQ(message, plaintext) << "RSA-OAEP failed with default digest";
5242
5243 // Decrypting corrupted ciphertext should fail.
5244 size_t offset_to_corrupt = random() % ciphertext.size();
5245 char corrupt_byte;
5246 do {
5247 corrupt_byte = static_cast<char>(random() % 256);
5248 } while (corrupt_byte == ciphertext[offset_to_corrupt]);
5249 ciphertext[offset_to_corrupt] = corrupt_byte;
5250
5251 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5252 string result;
5253 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5254 EXPECT_EQ(0U, result.size());
5255}
5256
5257/*
5258 * EncryptionOperationsTest.RsaOaepMGFDigestDefaultFail
5259 *
5260 * Verifies that RSA-OAEP decryption operations fail when no MGF digest is
5261 * specified on begin (thus defaulting to SHA-1), but the key characteristics
5262 * has an explicit set of values for MGF_DIGEST that do not contain SHA-1.
5263 */
5264TEST_P(EncryptionOperationsTest, RsaOaepMGFDigestDefaultFail) {
5265 size_t key_size = 2048;
5266 ASSERT_EQ(ErrorCode::OK,
5267 GenerateKey(AuthorizationSetBuilder()
5268 .Authorization(TAG_NO_AUTH_REQUIRED)
5269 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5270 .RsaEncryptionKey(key_size, 65537)
5271 .Padding(PaddingMode::RSA_OAEP)
5272 .Digest(Digest::SHA_2_256)
5273 .SetDefaultValidity()));
5274
5275 // Do local RSA encryption using the default MGF digest of SHA-1.
5276 string message = "Hello";
5277 auto params =
5278 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_OAEP);
5279 string ciphertext = LocalRsaEncryptMessage(message, params);
5280 EXPECT_EQ(key_size / 8, ciphertext.size());
5281
5282 // begin() params do not include MGF_DIGEST, so a default of SHA1 is assumed.
5283 // Key characteristics *do* include values for MGF_DIGEST, so the SHA1 value
5284 // is checked against those values, and found absent.
5285 auto result = Begin(KeyPurpose::DECRYPT, params);
5286 EXPECT_TRUE(result == ErrorCode::UNSUPPORTED_MGF_DIGEST ||
5287 result == ErrorCode::INCOMPATIBLE_MGF_DIGEST);
5288}
5289
5290/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005291 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5292 *
David Drysdale59cae642021-05-12 13:52:03 +01005293 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005294 * with incompatible MGF digest.
5295 */
5296TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5297 ASSERT_EQ(ErrorCode::OK,
5298 GenerateKey(AuthorizationSetBuilder()
5299 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5300 .Authorization(TAG_NO_AUTH_REQUIRED)
5301 .RsaEncryptionKey(2048, 65537)
5302 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005303 .Digest(Digest::SHA_2_256)
5304 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005305 string message = "Hello World!";
5306
5307 auto params = AuthorizationSetBuilder()
5308 .Padding(PaddingMode::RSA_OAEP)
5309 .Digest(Digest::SHA_2_256)
5310 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005311 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005312}
5313
5314/*
5315 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5316 *
5317 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5318 * with unsupported MGF digest.
5319 */
5320TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5321 ASSERT_EQ(ErrorCode::OK,
5322 GenerateKey(AuthorizationSetBuilder()
5323 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5324 .Authorization(TAG_NO_AUTH_REQUIRED)
5325 .RsaEncryptionKey(2048, 65537)
5326 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005327 .Digest(Digest::SHA_2_256)
5328 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005329 string message = "Hello World!";
5330
5331 auto params = AuthorizationSetBuilder()
5332 .Padding(PaddingMode::RSA_OAEP)
5333 .Digest(Digest::SHA_2_256)
5334 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005335 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005336}
5337
5338/*
Selene Huang31ab4042020-04-29 04:22:39 -07005339 * EncryptionOperationsTest.RsaPkcs1Success
5340 *
5341 * Verifies that RSA PKCS encryption/decrypts works.
5342 */
5343TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5344 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5345 .Authorization(TAG_NO_AUTH_REQUIRED)
5346 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005347 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5348 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005349
5350 string message = "Hello World!";
5351 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005352 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005353 EXPECT_EQ(2048U / 8, ciphertext1.size());
5354
David Drysdale59cae642021-05-12 13:52:03 +01005355 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005356 EXPECT_EQ(2048U / 8, ciphertext2.size());
5357
5358 // PKCS1 v1.5 randomizes padding so every result should be different.
5359 EXPECT_NE(ciphertext1, ciphertext2);
5360
5361 string plaintext = DecryptMessage(ciphertext1, params);
5362 EXPECT_EQ(message, plaintext);
5363
5364 // Decrypting corrupted ciphertext should fail.
5365 size_t offset_to_corrupt = random() % ciphertext1.size();
5366 char corrupt_byte;
5367 do {
5368 corrupt_byte = static_cast<char>(random() % 256);
5369 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5370 ciphertext1[offset_to_corrupt] = corrupt_byte;
5371
5372 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5373 string result;
5374 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5375 EXPECT_EQ(0U, result.size());
5376}
5377
5378/*
Selene Huang31ab4042020-04-29 04:22:39 -07005379 * EncryptionOperationsTest.EcdsaEncrypt
5380 *
5381 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5382 */
5383TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5384 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5385 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005386 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005387 .Digest(Digest::NONE)
5388 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005389 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5390 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5391 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5392}
5393
5394/*
5395 * EncryptionOperationsTest.HmacEncrypt
5396 *
5397 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5398 */
5399TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5400 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5401 .Authorization(TAG_NO_AUTH_REQUIRED)
5402 .HmacKey(128)
5403 .Digest(Digest::SHA_2_256)
5404 .Padding(PaddingMode::NONE)
5405 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5406 auto params = AuthorizationSetBuilder()
5407 .Digest(Digest::SHA_2_256)
5408 .Padding(PaddingMode::NONE)
5409 .Authorization(TAG_MAC_LENGTH, 128);
5410 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5411 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5412}
5413
5414/*
5415 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5416 *
5417 * Verifies that AES ECB mode works.
5418 */
5419TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5420 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5421 .Authorization(TAG_NO_AUTH_REQUIRED)
5422 .AesEncryptionKey(128)
5423 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5424 .Padding(PaddingMode::NONE)));
5425
5426 ASSERT_GT(key_blob_.size(), 0U);
5427 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5428
5429 // Two-block message.
5430 string message = "12345678901234567890123456789012";
5431 string ciphertext1 = EncryptMessage(message, params);
5432 EXPECT_EQ(message.size(), ciphertext1.size());
5433
5434 string ciphertext2 = EncryptMessage(string(message), params);
5435 EXPECT_EQ(message.size(), ciphertext2.size());
5436
5437 // ECB is deterministic.
5438 EXPECT_EQ(ciphertext1, ciphertext2);
5439
5440 string plaintext = DecryptMessage(ciphertext1, params);
5441 EXPECT_EQ(message, plaintext);
5442}
5443
5444/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005445 * EncryptionOperationsTest.AesEcbUnknownTag
5446 *
5447 * Verifies that AES ECB operations ignore unknown tags.
5448 */
5449TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5450 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5451 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5452 KeyParameter unknown_param;
5453 unknown_param.tag = unknown_tag;
5454
5455 vector<KeyCharacteristics> key_characteristics;
5456 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5457 .Authorization(TAG_NO_AUTH_REQUIRED)
5458 .AesEncryptionKey(128)
5459 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5460 .Padding(PaddingMode::NONE)
5461 .Authorization(unknown_param),
5462 &key_blob_, &key_characteristics));
5463 ASSERT_GT(key_blob_.size(), 0U);
5464
5465 // Unknown tags should not be returned in key characteristics.
5466 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5467 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5468 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5469 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5470
5471 // Encrypt without mentioning the unknown parameter.
5472 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5473 string message = "12345678901234567890123456789012";
5474 string ciphertext = EncryptMessage(message, params);
5475 EXPECT_EQ(message.size(), ciphertext.size());
5476
5477 // Decrypt including the unknown parameter.
5478 auto decrypt_params = AuthorizationSetBuilder()
5479 .BlockMode(BlockMode::ECB)
5480 .Padding(PaddingMode::NONE)
5481 .Authorization(unknown_param);
5482 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5483 EXPECT_EQ(message, plaintext);
5484}
5485
5486/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005487 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005488 *
5489 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5490 */
5491TEST_P(EncryptionOperationsTest, AesWrongMode) {
5492 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5493 .Authorization(TAG_NO_AUTH_REQUIRED)
5494 .AesEncryptionKey(128)
5495 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5496 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005497 ASSERT_GT(key_blob_.size(), 0U);
5498
Selene Huang31ab4042020-04-29 04:22:39 -07005499 EXPECT_EQ(
5500 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5501 Begin(KeyPurpose::ENCRYPT,
5502 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5503}
5504
5505/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005506 * EncryptionOperationsTest.AesWrongPadding
5507 *
5508 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5509 */
5510TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5511 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5512 .Authorization(TAG_NO_AUTH_REQUIRED)
5513 .AesEncryptionKey(128)
5514 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5515 .Padding(PaddingMode::NONE)));
5516 ASSERT_GT(key_blob_.size(), 0U);
5517
5518 EXPECT_EQ(
5519 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5520 Begin(KeyPurpose::ENCRYPT,
5521 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5522}
5523
5524/*
5525 * EncryptionOperationsTest.AesInvalidParams
5526 *
5527 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5528 */
5529TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5530 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5531 .Authorization(TAG_NO_AUTH_REQUIRED)
5532 .AesEncryptionKey(128)
5533 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5534 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5535 .Padding(PaddingMode::NONE)
5536 .Padding(PaddingMode::PKCS7)));
5537 ASSERT_GT(key_blob_.size(), 0U);
5538
5539 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5540 .BlockMode(BlockMode::CBC)
5541 .BlockMode(BlockMode::ECB)
5542 .Padding(PaddingMode::NONE));
5543 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5544 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5545
5546 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5547 .BlockMode(BlockMode::ECB)
5548 .Padding(PaddingMode::NONE)
5549 .Padding(PaddingMode::PKCS7));
5550 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5551 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5552}
5553
5554/*
Selene Huang31ab4042020-04-29 04:22:39 -07005555 * EncryptionOperationsTest.AesWrongPurpose
5556 *
5557 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5558 * specified.
5559 */
5560TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5561 auto err = GenerateKey(AuthorizationSetBuilder()
5562 .Authorization(TAG_NO_AUTH_REQUIRED)
5563 .AesKey(128)
5564 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5565 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5566 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5567 .Padding(PaddingMode::NONE));
5568 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5569 ASSERT_GT(key_blob_.size(), 0U);
5570
5571 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5572 .BlockMode(BlockMode::GCM)
5573 .Padding(PaddingMode::NONE)
5574 .Authorization(TAG_MAC_LENGTH, 128));
5575 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5576
5577 CheckedDeleteKey();
5578
5579 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5580 .Authorization(TAG_NO_AUTH_REQUIRED)
5581 .AesKey(128)
5582 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5583 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5584 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5585 .Padding(PaddingMode::NONE)));
5586
5587 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5588 .BlockMode(BlockMode::GCM)
5589 .Padding(PaddingMode::NONE)
5590 .Authorization(TAG_MAC_LENGTH, 128));
5591 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5592}
5593
5594/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005595 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005596 *
5597 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5598 * multiple of the block size and no padding is specified.
5599 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005600TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5601 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01005602 SCOPED_TRACE(testing::Message() << "AES-" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01005603 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5604 .Authorization(TAG_NO_AUTH_REQUIRED)
5605 .AesEncryptionKey(128)
5606 .Authorization(TAG_BLOCK_MODE, blockMode)
5607 .Padding(PaddingMode::NONE)));
5608 // Message is slightly shorter than two blocks.
5609 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005610
David Drysdaled2cc8c22021-04-15 13:29:45 +01005611 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5612 AuthorizationSet out_params;
5613 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5614 string ciphertext;
5615 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5616 EXPECT_EQ(0U, ciphertext.size());
5617
5618 CheckedDeleteKey();
5619 }
Selene Huang31ab4042020-04-29 04:22:39 -07005620}
5621
5622/*
5623 * EncryptionOperationsTest.AesEcbPkcs7Padding
5624 *
5625 * Verifies that AES PKCS7 padding works for any message length.
5626 */
5627TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5628 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5629 .Authorization(TAG_NO_AUTH_REQUIRED)
5630 .AesEncryptionKey(128)
5631 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5632 .Padding(PaddingMode::PKCS7)));
5633
5634 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5635
5636 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005637 for (size_t i = 0; i <= 48; i++) {
5638 SCOPED_TRACE(testing::Message() << "i = " << i);
5639 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5640 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005641 string ciphertext = EncryptMessage(message, params);
5642 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5643 string plaintext = DecryptMessage(ciphertext, params);
5644 EXPECT_EQ(message, plaintext);
5645 }
5646}
5647
5648/*
5649 * EncryptionOperationsTest.AesEcbWrongPadding
5650 *
5651 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5652 * specified.
5653 */
5654TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5655 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5656 .Authorization(TAG_NO_AUTH_REQUIRED)
5657 .AesEncryptionKey(128)
5658 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5659 .Padding(PaddingMode::NONE)));
5660
5661 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5662
5663 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005664 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005665 string message(i, 'a');
5666 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5667 }
5668}
5669
5670/*
5671 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5672 *
5673 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5674 */
5675TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5676 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5677 .Authorization(TAG_NO_AUTH_REQUIRED)
5678 .AesEncryptionKey(128)
5679 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5680 .Padding(PaddingMode::PKCS7)));
5681
5682 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5683
5684 string message = "a";
5685 string ciphertext = EncryptMessage(message, params);
5686 EXPECT_EQ(16U, ciphertext.size());
5687 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005688
Seth Moore7a55ae32021-06-23 14:28:11 -07005689 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5690 ++ciphertext[ciphertext.size() / 2];
5691
5692 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5693 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005694 ErrorCode error = Finish(ciphertext, &plaintext);
5695 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005696 // This is the expected error, we can exit the test now.
5697 return;
5698 } else {
5699 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005700 ASSERT_EQ(error, ErrorCode::OK)
5701 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005702 }
5703 }
5704 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005705}
5706
David Drysdaleb8093292022-04-08 12:22:35 +01005707/*
5708 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5709 *
5710 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5711 */
5712TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5713 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5714 .Authorization(TAG_NO_AUTH_REQUIRED)
5715 .AesEncryptionKey(128)
5716 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5717 .Padding(PaddingMode::PKCS7)));
5718
5719 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5720
5721 string message = "a";
5722 string ciphertext = EncryptMessage(message, params);
5723 EXPECT_EQ(16U, ciphertext.size());
5724 EXPECT_NE(ciphertext, message);
5725
5726 // Shorten the ciphertext.
5727 ciphertext.resize(ciphertext.size() - 1);
5728 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5729 string plaintext;
5730 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5731}
5732
Selene Huang31ab4042020-04-29 04:22:39 -07005733vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5734 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005735 EXPECT_TRUE(iv);
5736 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005737}
5738
5739/*
5740 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5741 *
5742 * Verifies that AES CTR mode works.
5743 */
5744TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5745 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5746 .Authorization(TAG_NO_AUTH_REQUIRED)
5747 .AesEncryptionKey(128)
5748 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5749 .Padding(PaddingMode::NONE)));
5750
5751 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5752
5753 string message = "123";
5754 AuthorizationSet out_params;
5755 string ciphertext1 = EncryptMessage(message, params, &out_params);
5756 vector<uint8_t> iv1 = CopyIv(out_params);
5757 EXPECT_EQ(16U, iv1.size());
5758
5759 EXPECT_EQ(message.size(), ciphertext1.size());
5760
5761 out_params.Clear();
5762 string ciphertext2 = EncryptMessage(message, params, &out_params);
5763 vector<uint8_t> iv2 = CopyIv(out_params);
5764 EXPECT_EQ(16U, iv2.size());
5765
5766 // IVs should be random, so ciphertexts should differ.
5767 EXPECT_NE(ciphertext1, ciphertext2);
5768
5769 auto params_iv1 =
5770 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5771 auto params_iv2 =
5772 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5773
5774 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5775 EXPECT_EQ(message, plaintext);
5776 plaintext = DecryptMessage(ciphertext2, params_iv2);
5777 EXPECT_EQ(message, plaintext);
5778
5779 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5780 plaintext = DecryptMessage(ciphertext1, params_iv2);
5781 EXPECT_NE(message, plaintext);
5782 plaintext = DecryptMessage(ciphertext2, params_iv1);
5783 EXPECT_NE(message, plaintext);
5784}
5785
5786/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305787 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005788 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305789 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005790 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305791TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5792 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5793}
Selene Huang31ab4042020-04-29 04:22:39 -07005794
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305795/*
5796 * EncryptionOperationsTest.AesCbcIncremental
5797 *
5798 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5799 */
5800TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5801 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5802}
Selene Huang31ab4042020-04-29 04:22:39 -07005803
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305804/*
5805 * EncryptionOperationsTest.AesCtrIncremental
5806 *
5807 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5808 */
5809TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5810 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5811}
Selene Huang31ab4042020-04-29 04:22:39 -07005812
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305813/*
5814 * EncryptionOperationsTest.AesGcmIncremental
5815 *
5816 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5817 */
5818TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5819 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005820}
5821
Prashant Patildd5f7f02022-07-06 18:58:07 +00005822/*
5823 * EncryptionOperationsTest.Aes128CBCNoPaddingOneByteAtATime
5824 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5825 */
5826TEST_P(EncryptionOperationsTest, Aes128CBCNoPaddingOneByteAtATime) {
5827 string kat_key = hex2str("7E3D723C09A9852B24F584F9D916F6A8");
5828 string kat_iv = hex2str("944AE274D983892EADE422274858A96A");
5829 string kat_plaintext =
5830 hex2str("044E15899A080AADEB6778F64323B64D2CBCBADB338DF93B9AC459D4F41029"
5831 "809FFF37081C22EF278F896AB213A2A631");
5832 string kat_ciphertext =
5833 hex2str("B419293FCBD686F2913D1CF947E510D42FAFEDE5593C98AFD6AEE272596A"
5834 "56FE42C22F2A5E3B6A02BA9D8D0DE1E9A810");
5835 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5836 kat_ciphertext);
5837}
5838
5839/*
5840 * EncryptionOperationsTest.Aes128CBCPKCS7PaddingOneByteAtATime
5841 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5842 */
5843TEST_P(EncryptionOperationsTest, Aes128CBCPKCS7PaddingOneByteAtATime) {
5844 string kat_key = hex2str("F16E698472578E919D92806262C5169F");
5845 string kat_iv = hex2str("EF743540F8421ACA128A3247521F3E7D");
5846 string kat_plaintext =
5847 hex2str("5BEBF33569D90BF5E853814E12E7C7AA5758013F755773E29F4A25EC26EEB7"
5848 "65F7F2DC251F7DC62AEFCA1E8A5A11A1DCD44F0BD8FB593A5AE3");
5849 string kat_ciphertext =
5850 hex2str("3197CF6DB9466188B5FED375329324EE7D6092A8C0E41DFAF49E3724271427"
5851 "896D56A6243C0D59D6639722AF93CD53449BDDABF9C5F153EBDBFED9ED98C8CC37");
5852 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5853 kat_plaintext, kat_ciphertext);
5854}
5855
5856/*
5857 * EncryptionOperationsTest.Aes128CTRNoPaddingOneByteAtATime
5858 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5859 */
5860TEST_P(EncryptionOperationsTest, Aes128CTRNoPaddingOneByteAtATime) {
5861 string kat_key = hex2str("4713a7b2f93efe809b42ecc45213ef9f");
5862 string kat_iv = hex2str("ebfa19b0ebf3d57feabd4c4bd04bea01");
5863 string kat_plaintext =
5864 hex2str("6d2c07e1fc86f99c6e2a8f6567828b4262a9c23d0f3ed8ab32482283c79796"
5865 "f0adba1bcd3736084996452a917fae98005aebe61f9e91c3");
5866 string kat_ciphertext =
5867 hex2str("345deb1d67b95e600e05cad4c32ec381aadb3e2c1ec7e0fb956dc38e6860cf"
5868 "0553535566e1b12fa9f87d29266ca26df427233df035df28");
5869 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
5870 kat_ciphertext);
5871}
5872
5873/*
5874 * EncryptionOperationsTest.Aes128ECBNoPaddingOneByteAtATime
5875 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
5876 */
5877TEST_P(EncryptionOperationsTest, Aes128ECBNoPaddingOneByteAtATime) {
5878 string kat_key = hex2str("7DA2467F068854B3CB36E5C333A16619");
5879 string kat_plaintext =
5880 hex2str("9A07C9575AD9CE209DF9F3953965CEBE8208587C7AE575A1904BF25048946D"
5881 "7B6168A9A27BCE554BEA94EF26E6C742A0");
5882 string kat_ciphertext =
5883 hex2str("8C47E49420FC92AC4CA2C601BC3F8AC31D01B260B7B849F2B8EEDFFFED8F36"
5884 "C31CBDA0D22F95C9C2A48C347E8C77AC82");
5885 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
5886 kat_ciphertext);
5887}
5888
5889/*
5890 * EncryptionOperationsTest.Aes128ECBPKCS7PaddingOneByteAtATime
5891 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
5892 */
5893TEST_P(EncryptionOperationsTest, Aes128ECBPKCS7PaddingOneByteAtATime) {
5894 string kat_key = hex2str("C3BE04BCCB3D99B85290F113FE7AF194");
5895 string kat_plaintext =
5896 hex2str("348C213FD8DF3F990C20C5ACBF07B34B6264AE245784A5A6176DBFB1C2E7DD"
5897 "27E52CC92B8EEE40614F05B507B355F6354A2705BD86");
5898 string kat_ciphertext =
5899 hex2str("07CD05C41FEDEDDC5DB4B3E35E676153184A119AA4DFDDC290616F1FA60093"
5900 "1DE6BEA9BDB90D1D733899946F8C8E5C0C4383F99F5D88E27F3EBC0C6E52759ED3");
5901 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
5902 kat_ciphertext);
5903}
5904
5905/*
5906 * EncryptionOperationsTest.Aes128GCMNoPaddingOneByteAtATime
5907 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
5908 */
5909TEST_P(EncryptionOperationsTest, Aes128GCMNoPaddingOneByteAtATime) {
5910 string kat_key = hex2str("ba76354f0aed6e8d91f45c4ff5a062db");
5911 string kat_iv = hex2str("b79437ae08ff355d7d8a4d0f");
5912 string kat_plaintext =
5913 hex2str("6d7596a8fd56ceaec61de7940984b7736fec44f572afc3c8952e4dc6541e2b"
5914 "c6a702c440a37610989543f63fedb047ca2173bc18581944");
5915 string kat_ciphertext =
5916 hex2str("b3f6799e8f9326f2df1e80fcd2cb16d78c9dc7cc14bb677862dc6c639b3a63"
5917 "38d24b312d3989e5920b5dbfc976765efbfe57bb385940a7a43bdf05bddae3c9d6a2fb"
5918 "bdfcc0cba0");
5919
5920 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
5921 kat_ciphertext);
5922}
5923
5924/*
5925 * EncryptionOperationsTest.Aes192CBCNoPaddingOneByteAtATime
5926 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
5927 */
5928TEST_P(EncryptionOperationsTest, Aes192CBCNoPaddingOneByteAtATime) {
5929 if (SecLevel() == SecurityLevel::STRONGBOX) {
5930 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5931 }
5932 string kat_key = hex2str("be8cc4e25cce46e5d55725e2391f7d3cf59ed60062f5a43b");
5933 string kat_iv = hex2str("80a199aab0eee77e7762ddf3b3a32f40");
5934 string kat_plaintext =
5935 hex2str("064f9200e0df37d4711af4a69d11addf9e1c345d9d8195f9f1f715019ce96a"
5936 "167f2497c994bd496eb80bfb2ba2c9d5af");
5937 string kat_ciphertext =
5938 hex2str("859b90becaa85e95a71e104efbd7a3b723bcbf4eb39865544a05d9e90b6fe5"
5939 "72c134552f3a138e726fbe493b3a839598");
5940 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
5941 kat_ciphertext);
5942}
5943
5944/*
5945 * EncryptionOperationsTest.Aes192CBCPKCS7PaddingOneByteAtATime
5946 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
5947 */
5948TEST_P(EncryptionOperationsTest, Aes192CBCPKCS7PaddingOneByteAtATime) {
5949 if (SecLevel() == SecurityLevel::STRONGBOX) {
5950 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5951 }
5952 string kat_key = hex2str("68969215ec41e4df7d23de0e806f458f52aff492bd7c5263");
5953 string kat_iv = hex2str("e61d13dfbf0533289f0e7950209da418");
5954 string kat_plaintext =
5955 hex2str("8d4c1cac27511ee2d82409a7f378e7e402b0eb189c1eaa5c506eb72a9074"
5956 "b170");
5957 string kat_ciphertext =
5958 hex2str("e70bcd62c595dc1b2b8c197bb91a7447e1be2cbcf3fdc69e7e991faf0f57cf"
5959 "4e3884138ff403a41fd99818708ada301c");
5960 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
5961 kat_plaintext, kat_ciphertext);
5962}
5963
5964/*
5965 * EncryptionOperationsTest.Aes192CTRNoPaddingOneByteAtATime
5966 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
5967 */
5968TEST_P(EncryptionOperationsTest, Aes192CTRNoPaddingOneByteAtATime) {
5969 if (SecLevel() == SecurityLevel::STRONGBOX) {
5970 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5971 }
5972 string kat_key = hex2str("5e2036e790d38815c90beb67a1c9e5aa0e167ef082927317");
5973 string kat_iv = hex2str("df0694959b89054156962d68a226965c");
5974 string kat_plaintext =
5975 hex2str("6ed2781c99e03e45314d6019932220c2c98130c53f9f67ad10ac519adf50e9"
5976 "28091e09cdbbd3b42b");
5977 string kat_ciphertext =
5978 hex2str("e427b6666502e05b82d0b20ae50e862b1936d71266fc49178ac984e71571f2"
5979 "2ae0f90f0c19f42b4a");
5980 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
5981 kat_ciphertext);
5982}
5983
5984/*
5985 * EncryptionOperationsTest.Aes192ECBNoPaddingOneByteAtATime
5986 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
5987 */
5988TEST_P(EncryptionOperationsTest, Aes192ECBNoPaddingOneByteAtATime) {
5989 if (SecLevel() == SecurityLevel::STRONGBOX) {
5990 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
5991 }
5992 string kat_key = hex2str("3cab83fb338ba985fbfe74c5e9d2e900adb570b1d67faf92");
5993 string kat_plaintext =
5994 hex2str("2cc64c335a13fb838f3c6aad0a6b47297ca90bb886ddb059200f0b41740c"
5995 "44ab");
5996 string kat_ciphertext =
5997 hex2str("9c5c825328f5ee0aa24947e374d3f9165f484b39dd808c790d7a12964810"
5998 "2453");
5999 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6000 kat_ciphertext);
6001}
6002
6003/*
6004 * EncryptionOperationsTest.Aes192ECBPKCS7PaddingOneByteAtATime
6005 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6006 */
6007TEST_P(EncryptionOperationsTest, Aes192ECBPKCS7PaddingOneByteAtATime) {
6008 if (SecLevel() == SecurityLevel::STRONGBOX) {
6009 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6010 }
6011 string kat_key = hex2str("d57f4e5446f736c16476ec4db5decc7b1bf3936e4f7e4618");
6012 string kat_plaintext =
6013 hex2str("b115777f1ee7a43a07daa6401e59c46b7a98213a8747eabfbe3ca4ec93524d"
6014 "e2c7");
6015 string kat_ciphertext =
6016 hex2str("1e92cd20da08bb5fa174a7a69879d4fc25a155e6af06d75b26c5b450d273c8"
6017 "bb7e3a889dd4a9589098b44acf1056e7aa");
6018 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6019 kat_ciphertext);
6020}
6021
6022/*
6023 * EncryptionOperationsTest.Aes192GCMNoPaddingOneByteAtATime
6024 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6025 */
6026TEST_P(EncryptionOperationsTest, Aes192GCMNoPaddingOneByteAtATime) {
6027 if (SecLevel() == SecurityLevel::STRONGBOX) {
6028 GTEST_SKIP() << "Key size 192 is not supported by Strongbox.";
6029 }
6030 string kat_key = hex2str("21339fc1d011abca65d50ce2365230603fd47d07e8830f6e");
6031 string kat_iv = hex2str("d5fb1469a8d81dd75286a418");
6032 string kat_plaintext =
6033 hex2str("cf776dedf53a828d51a0073db3ef0dd1ee19e2e9e243ce97e95841bb9ad4e3"
6034 "ff52");
6035 string kat_ciphertext =
6036 hex2str("3a0d48278111d3296bc663df8a5dbeb2474ea47fd85b608f8d9375d9dcf7de"
6037 "1413ad70fb0e1970669095ad77ebb5974ae8");
6038
6039 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6040 kat_ciphertext);
6041}
6042
6043/*
6044 * EncryptionOperationsTest.Aes256CBCNoPaddingOneByteAtATime
6045 * Verifies input and output sizes of AES/CBC/NoPadding Algorithm.
6046 */
6047TEST_P(EncryptionOperationsTest, Aes256CBCNoPaddingOneByteAtATime) {
6048 string kat_key = hex2str("dd2f20dc6b98c100bac919120ff95eb5d96003f8229987b283a1e777b0cd5c30");
6049 string kat_iv = hex2str("23b4d85239fb90db93b07a981e90a170");
6050 string kat_plaintext =
6051 hex2str("2fbe5d46dca5cea433e550d8b291740ab9551c2a2d37680d7fb7b993225f58"
6052 "494cb53caca353e4b637ba05687be20f8d");
6053 string kat_ciphertext =
6054 hex2str("5aba24fc316936c8369061ee8fe463e4faed04288e204456626b988c0e376b"
6055 "6047da1e4fd7c4e1cf2656097f75ae8685");
6056 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::NONE, kat_iv, kat_plaintext,
6057 kat_ciphertext);
6058}
6059
6060/*
6061 * EncryptionOperationsTest.Aes256CBCPKCS7PaddingOneByteAtATime
6062 * Verifies input and output sizes of AES/CBC/PKCS7Padding Algorithm.
6063 */
6064TEST_P(EncryptionOperationsTest, Aes256CBCPKCS7PaddingOneByteAtATime) {
6065 string kat_key = hex2str("03ab2510520f5cfebfab0a17a7f8324c9634911f6fc59e586f85346bb38ac88a");
6066 string kat_iv = hex2str("9af96967195bb0184f129beffa8241ae");
6067 string kat_plaintext =
6068 hex2str("2d6944653ac14988a772a2730b7c5bfa99a21732ae26f40cdc5b3a2874c794"
6069 "2545a82b73c48078b9dae62261c65909");
6070 string kat_ciphertext =
6071 hex2str("26b308f7e1668b55705a79c8b3ad10e244655f705f027f390a5c34e4536f51"
6072 "9403a71987b95124073d69f2a3cb95b0ab");
6073 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CBC, PaddingMode::PKCS7, kat_iv,
6074 kat_plaintext, kat_ciphertext);
6075}
6076
6077/*
6078 * EncryptionOperationsTest.Aes256CTRNoPaddingOneByteAtATime
6079 * Verifies input and output sizes of AES/CTR/NoPadding Algorithm.
6080 */
6081TEST_P(EncryptionOperationsTest, Aes256CTRNoPaddingOneByteAtATime) {
6082 string kat_key = hex2str("928b380a8fed4b4b4cfeb56e0c66a4cb0f9ff58d61ac68bcfd0e3fbd910a684f");
6083 string kat_iv = hex2str("0b678a5249e6eeda461dfb4776b6c58e");
6084 string kat_plaintext =
6085 hex2str("f358de57543b297e997cba46fb9100553d6abd65377e55b9aac3006400ead1"
6086 "1f6db3c884");
6087 string kat_ciphertext =
6088 hex2str("a07a35fbd1776ad81462e1935f542337add60962bf289249476817b6ddd532"
6089 "a7be30d4c3");
6090 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::CTR, PaddingMode::NONE, kat_iv, kat_plaintext,
6091 kat_ciphertext);
6092}
6093
6094/*
6095 * EncryptionOperationsTest.Aes256ECBNoPaddingOneByteAtATime
6096 * Verifies input and output sizes of AES/ECB/NoPadding Algorithm.
6097 */
6098TEST_P(EncryptionOperationsTest, Aes256ECBNoPaddingOneByteAtATime) {
6099 string kat_key = hex2str("fa4622d9cf6485075daedd33d2c4fffdf859e2edb7f7df4f04603f7e647fae90");
6100 string kat_plaintext =
6101 hex2str("96ccabbe0c68970d8cdee2b30ab43c2d61cc50ee68271e77571e72478d713a"
6102 "31a476d6806b8116089c6ec50bb543200f");
6103 string kat_ciphertext =
6104 hex2str("0e81839e9dfbfe3b503d619e676abe5ac80fac3f245d8f09b9134b1b32a67d"
6105 "c83e377faf246288931136bef2a07c0be4");
6106 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::NONE, "", kat_plaintext,
6107 kat_ciphertext);
6108}
6109
6110/*
6111 * EncryptionOperationsTest.Aes256ECBPKCS7PaddingOneByteAtATime
6112 * Verifies input and output sizes of AES/ECB/PKCS7Padding Algorithm.
6113 */
6114TEST_P(EncryptionOperationsTest, Aes256ECBPKCS7PaddingOneByteAtATime) {
6115 string kat_key = hex2str("bf3f07c68467fead0ca8e2754500ab514258abf02eb7e615a493bcaaa45d5ee1");
6116 string kat_plaintext =
6117 hex2str("af0757e49018dad628f16998628a407db5f28291bef3bc2e4d8a5a31fb238e"
6118 "6f");
6119 string kat_ciphertext =
6120 hex2str("21ec3011074bf1ef140643d47130326c5e183f61237c69bc77551ca207d71f"
6121 "c2b90cfac6c8d2d125e5cd9ff353dee0df");
6122 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::ECB, PaddingMode::PKCS7, "", kat_plaintext,
6123 kat_ciphertext);
6124}
6125
6126/*
6127 * EncryptionOperationsTest.Aes256GCMNoPaddingOneByteAtATime
6128 * Verifies input and output sizes of AES/GCM/NoPadding Algorithm.
6129 */
6130TEST_P(EncryptionOperationsTest, Aes256GCMNoPaddingOneByteAtATime) {
6131 string kat_key = hex2str("7972140d831eedac75d5ea515c9a4c3bb124499a90b5f317ac1a685e88fae395");
6132 string kat_iv = hex2str("a66c5252808d823dd4151fed");
6133 string kat_plaintext =
6134 hex2str("c2b9dabf3a55adaa94e8c0d1e77a84a3435aee23b2c3c4abb587b09a9c2afb"
6135 "f0");
6136 string kat_ciphertext =
6137 hex2str("a960619314657b2afb96b93bebb372bffd09e19d53e351f17d1ba2611f9dc3"
6138 "3c9c92d563e8fd381254ac262aa2a4ea0d");
6139
6140 AesCheckEncryptOneByteAtATime(kat_key, BlockMode::GCM, PaddingMode::NONE, kat_iv, kat_plaintext,
6141 kat_ciphertext);
6142}
6143
Selene Huang31ab4042020-04-29 04:22:39 -07006144struct AesCtrSp80038aTestVector {
6145 const char* key;
6146 const char* nonce;
6147 const char* plaintext;
6148 const char* ciphertext;
6149};
6150
6151// These test vectors are taken from
6152// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
6153static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
6154 // AES-128
6155 {
6156 "2b7e151628aed2a6abf7158809cf4f3c",
6157 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6158 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6159 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6160 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
6161 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
6162 },
6163 // AES-192
6164 {
6165 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
6166 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6167 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6168 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6169 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
6170 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
6171 },
6172 // AES-256
6173 {
6174 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
6175 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
6176 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
6177 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
6178 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
6179 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
6180 },
6181};
6182
6183/*
6184 * EncryptionOperationsTest.AesCtrSp80038aTestVector
6185 *
6186 * Verifies AES CTR implementation against SP800-38A test vectors.
6187 */
6188TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
6189 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
6190 for (size_t i = 0; i < 3; i++) {
6191 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
6192 const string key = hex2str(test.key);
6193 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
6194 InvalidSizes.end())
6195 continue;
6196 const string nonce = hex2str(test.nonce);
6197 const string plaintext = hex2str(test.plaintext);
6198 const string ciphertext = hex2str(test.ciphertext);
6199 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
6200 }
6201}
6202
6203/*
6204 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
6205 *
6206 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
6207 */
6208TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
6209 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6210 .Authorization(TAG_NO_AUTH_REQUIRED)
6211 .AesEncryptionKey(128)
6212 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6213 .Padding(PaddingMode::PKCS7)));
6214 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
6215 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
6216}
6217
6218/*
6219 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
6220 *
6221 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6222 */
6223TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
6224 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6225 .Authorization(TAG_NO_AUTH_REQUIRED)
6226 .AesEncryptionKey(128)
6227 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
6228 .Authorization(TAG_CALLER_NONCE)
6229 .Padding(PaddingMode::NONE)));
6230
6231 auto params = AuthorizationSetBuilder()
6232 .BlockMode(BlockMode::CTR)
6233 .Padding(PaddingMode::NONE)
6234 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
6235 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6236
6237 params = AuthorizationSetBuilder()
6238 .BlockMode(BlockMode::CTR)
6239 .Padding(PaddingMode::NONE)
6240 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
6241 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6242
6243 params = AuthorizationSetBuilder()
6244 .BlockMode(BlockMode::CTR)
6245 .Padding(PaddingMode::NONE)
6246 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
6247 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6248}
6249
6250/*
David Drysdale7de9feb2021-03-05 14:56:19 +00006251 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07006252 *
6253 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
6254 */
6255TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
6256 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6257 .Authorization(TAG_NO_AUTH_REQUIRED)
6258 .AesEncryptionKey(128)
6259 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6260 .Padding(PaddingMode::NONE)));
6261 // Two-block message.
6262 string message = "12345678901234567890123456789012";
6263 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6264 AuthorizationSet out_params;
6265 string ciphertext1 = EncryptMessage(message, params, &out_params);
6266 vector<uint8_t> iv1 = CopyIv(out_params);
6267 EXPECT_EQ(message.size(), ciphertext1.size());
6268
6269 out_params.Clear();
6270
6271 string ciphertext2 = EncryptMessage(message, params, &out_params);
6272 vector<uint8_t> iv2 = CopyIv(out_params);
6273 EXPECT_EQ(message.size(), ciphertext2.size());
6274
6275 // IVs should be random, so ciphertexts should differ.
6276 EXPECT_NE(ciphertext1, ciphertext2);
6277
6278 params.push_back(TAG_NONCE, iv1);
6279 string plaintext = DecryptMessage(ciphertext1, params);
6280 EXPECT_EQ(message, plaintext);
6281}
6282
6283/*
Tommy Chiuee705692021-09-23 20:09:13 +08006284 * EncryptionOperationsTest.AesCbcZeroInputSuccessb
6285 *
6286 * Verifies that keymaster generates correct output on zero-input with
6287 * NonePadding mode
6288 */
6289TEST_P(EncryptionOperationsTest, AesCbcZeroInputSuccess) {
6290 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6291 .Authorization(TAG_NO_AUTH_REQUIRED)
6292 .AesEncryptionKey(128)
6293 .BlockMode(BlockMode::CBC)
6294 .Padding(PaddingMode::NONE, PaddingMode::PKCS7)));
6295
6296 // Zero input message
6297 string message = "";
6298 for (auto padding : {PaddingMode::NONE, PaddingMode::PKCS7}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006299 SCOPED_TRACE(testing::Message() << "AES padding=" << padding);
Tommy Chiuee705692021-09-23 20:09:13 +08006300 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(padding);
6301 AuthorizationSet out_params;
6302 string ciphertext1 = EncryptMessage(message, params, &out_params);
6303 vector<uint8_t> iv1 = CopyIv(out_params);
6304 if (padding == PaddingMode::NONE)
6305 EXPECT_EQ(message.size(), ciphertext1.size()) << "PaddingMode: " << padding;
6306 else
6307 EXPECT_EQ(message.size(), ciphertext1.size() - 16) << "PaddingMode: " << padding;
6308
6309 out_params.Clear();
6310
6311 string ciphertext2 = EncryptMessage(message, params, &out_params);
6312 vector<uint8_t> iv2 = CopyIv(out_params);
6313 if (padding == PaddingMode::NONE)
6314 EXPECT_EQ(message.size(), ciphertext2.size()) << "PaddingMode: " << padding;
6315 else
6316 EXPECT_EQ(message.size(), ciphertext2.size() - 16) << "PaddingMode: " << padding;
6317
6318 // IVs should be random
6319 EXPECT_NE(iv1, iv2) << "PaddingMode: " << padding;
6320
6321 params.push_back(TAG_NONCE, iv1);
6322 string plaintext = DecryptMessage(ciphertext1, params);
6323 EXPECT_EQ(message, plaintext) << "PaddingMode: " << padding;
6324 }
6325}
6326
6327/*
Selene Huang31ab4042020-04-29 04:22:39 -07006328 * EncryptionOperationsTest.AesCallerNonce
6329 *
6330 * Verifies that AES caller-provided nonces work correctly.
6331 */
6332TEST_P(EncryptionOperationsTest, AesCallerNonce) {
6333 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6334 .Authorization(TAG_NO_AUTH_REQUIRED)
6335 .AesEncryptionKey(128)
6336 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6337 .Authorization(TAG_CALLER_NONCE)
6338 .Padding(PaddingMode::NONE)));
6339
6340 string message = "12345678901234567890123456789012";
6341
6342 // Don't specify nonce, should get a random one.
6343 AuthorizationSetBuilder params =
6344 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6345 AuthorizationSet out_params;
6346 string ciphertext = EncryptMessage(message, params, &out_params);
6347 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006348 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006349
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006350 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006351 string plaintext = DecryptMessage(ciphertext, params);
6352 EXPECT_EQ(message, plaintext);
6353
6354 // Now specify a nonce, should also work.
6355 params = AuthorizationSetBuilder()
6356 .BlockMode(BlockMode::CBC)
6357 .Padding(PaddingMode::NONE)
6358 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6359 out_params.Clear();
6360 ciphertext = EncryptMessage(message, params, &out_params);
6361
6362 // Decrypt with correct nonce.
6363 plaintext = DecryptMessage(ciphertext, params);
6364 EXPECT_EQ(message, plaintext);
6365
6366 // Try with wrong nonce.
6367 params = AuthorizationSetBuilder()
6368 .BlockMode(BlockMode::CBC)
6369 .Padding(PaddingMode::NONE)
6370 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
6371 plaintext = DecryptMessage(ciphertext, params);
6372 EXPECT_NE(message, plaintext);
6373}
6374
6375/*
6376 * EncryptionOperationsTest.AesCallerNonceProhibited
6377 *
6378 * Verifies that caller-provided nonces are not permitted when not specified in the key
6379 * authorizations.
6380 */
6381TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
6382 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6383 .Authorization(TAG_NO_AUTH_REQUIRED)
6384 .AesEncryptionKey(128)
6385 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
6386 .Padding(PaddingMode::NONE)));
6387
6388 string message = "12345678901234567890123456789012";
6389
6390 // Don't specify nonce, should get a random one.
6391 AuthorizationSetBuilder params =
6392 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6393 AuthorizationSet out_params;
6394 string ciphertext = EncryptMessage(message, params, &out_params);
6395 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006396 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07006397
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006398 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07006399 string plaintext = DecryptMessage(ciphertext, params);
6400 EXPECT_EQ(message, plaintext);
6401
6402 // Now specify a nonce, should fail
6403 params = AuthorizationSetBuilder()
6404 .BlockMode(BlockMode::CBC)
6405 .Padding(PaddingMode::NONE)
6406 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
6407 out_params.Clear();
6408 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
6409}
6410
6411/*
6412 * EncryptionOperationsTest.AesGcmRoundTripSuccess
6413 *
6414 * Verifies that AES GCM mode works.
6415 */
6416TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
6417 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6418 .Authorization(TAG_NO_AUTH_REQUIRED)
6419 .AesEncryptionKey(128)
6420 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6421 .Padding(PaddingMode::NONE)
6422 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6423
6424 string aad = "foobar";
6425 string message = "123456789012345678901234567890123456";
6426
6427 auto begin_params = AuthorizationSetBuilder()
6428 .BlockMode(BlockMode::GCM)
6429 .Padding(PaddingMode::NONE)
6430 .Authorization(TAG_MAC_LENGTH, 128);
6431
Selene Huang31ab4042020-04-29 04:22:39 -07006432 // Encrypt
6433 AuthorizationSet begin_out_params;
6434 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6435 << "Begin encrypt";
6436 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006437 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6438 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006439 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6440
6441 // Grab nonce
6442 begin_params.push_back(begin_out_params);
6443
6444 // Decrypt.
6445 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07006446 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006447 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006448 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006449 EXPECT_EQ(message.length(), plaintext.length());
6450 EXPECT_EQ(message, plaintext);
6451}
6452
6453/*
6454 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
6455 *
6456 * Verifies that AES GCM mode works, even when there's a long delay
6457 * between operations.
6458 */
6459TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
6460 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6461 .Authorization(TAG_NO_AUTH_REQUIRED)
6462 .AesEncryptionKey(128)
6463 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6464 .Padding(PaddingMode::NONE)
6465 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6466
6467 string aad = "foobar";
6468 string message = "123456789012345678901234567890123456";
6469
6470 auto begin_params = AuthorizationSetBuilder()
6471 .BlockMode(BlockMode::GCM)
6472 .Padding(PaddingMode::NONE)
6473 .Authorization(TAG_MAC_LENGTH, 128);
6474
Selene Huang31ab4042020-04-29 04:22:39 -07006475 // Encrypt
6476 AuthorizationSet begin_out_params;
6477 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
6478 << "Begin encrypt";
6479 string ciphertext;
6480 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006481 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006482 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006483 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006484
6485 ASSERT_EQ(ciphertext.length(), message.length() + 16);
6486
6487 // Grab nonce
6488 begin_params.push_back(begin_out_params);
6489
6490 // Decrypt.
6491 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
6492 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006493 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006494 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07006495 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006496 sleep(5);
6497 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
6498 EXPECT_EQ(message.length(), plaintext.length());
6499 EXPECT_EQ(message, plaintext);
6500}
6501
6502/*
6503 * EncryptionOperationsTest.AesGcmDifferentNonces
6504 *
6505 * Verifies that encrypting the same data with different nonces produces different outputs.
6506 */
6507TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
6508 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6509 .Authorization(TAG_NO_AUTH_REQUIRED)
6510 .AesEncryptionKey(128)
6511 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6512 .Padding(PaddingMode::NONE)
6513 .Authorization(TAG_MIN_MAC_LENGTH, 128)
6514 .Authorization(TAG_CALLER_NONCE)));
6515
6516 string aad = "foobar";
6517 string message = "123456789012345678901234567890123456";
6518 string nonce1 = "000000000000";
6519 string nonce2 = "111111111111";
6520 string nonce3 = "222222222222";
6521
6522 string ciphertext1 =
6523 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
6524 string ciphertext2 =
6525 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
6526 string ciphertext3 =
6527 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
6528
6529 ASSERT_NE(ciphertext1, ciphertext2);
6530 ASSERT_NE(ciphertext1, ciphertext3);
6531 ASSERT_NE(ciphertext2, ciphertext3);
6532}
6533
6534/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006535 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
6536 *
6537 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
6538 */
6539TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
6540 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6541 .Authorization(TAG_NO_AUTH_REQUIRED)
6542 .AesEncryptionKey(128)
6543 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
6544 .Padding(PaddingMode::NONE)
6545 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6546
6547 string aad = "foobar";
6548 string message = "123456789012345678901234567890123456";
6549
6550 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6551 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6552 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
6553
6554 ASSERT_NE(ciphertext1, ciphertext2);
6555 ASSERT_NE(ciphertext1, ciphertext3);
6556 ASSERT_NE(ciphertext2, ciphertext3);
6557}
6558
6559/*
Selene Huang31ab4042020-04-29 04:22:39 -07006560 * EncryptionOperationsTest.AesGcmTooShortTag
6561 *
6562 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
6563 */
6564TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
6565 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6566 .Authorization(TAG_NO_AUTH_REQUIRED)
6567 .AesEncryptionKey(128)
6568 .BlockMode(BlockMode::GCM)
6569 .Padding(PaddingMode::NONE)
6570 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6571 string message = "123456789012345678901234567890123456";
6572 auto params = AuthorizationSetBuilder()
6573 .BlockMode(BlockMode::GCM)
6574 .Padding(PaddingMode::NONE)
6575 .Authorization(TAG_MAC_LENGTH, 96);
6576
6577 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6578}
6579
6580/*
6581 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6582 *
6583 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6584 */
6585TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6586 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6587 .Authorization(TAG_NO_AUTH_REQUIRED)
6588 .AesEncryptionKey(128)
6589 .BlockMode(BlockMode::GCM)
6590 .Padding(PaddingMode::NONE)
6591 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6592 string aad = "foobar";
6593 string message = "123456789012345678901234567890123456";
6594 auto params = AuthorizationSetBuilder()
6595 .BlockMode(BlockMode::GCM)
6596 .Padding(PaddingMode::NONE)
6597 .Authorization(TAG_MAC_LENGTH, 128);
6598
Selene Huang31ab4042020-04-29 04:22:39 -07006599 // Encrypt
6600 AuthorizationSet begin_out_params;
6601 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6602 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006603 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006604
6605 AuthorizationSet finish_out_params;
6606 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006607 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6608 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006609
6610 params = AuthorizationSetBuilder()
6611 .Authorizations(begin_out_params)
6612 .BlockMode(BlockMode::GCM)
6613 .Padding(PaddingMode::NONE)
6614 .Authorization(TAG_MAC_LENGTH, 96);
6615
6616 // Decrypt.
6617 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6618}
6619
6620/*
6621 * EncryptionOperationsTest.AesGcmCorruptKey
6622 *
6623 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6624 */
6625TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6626 const uint8_t nonce_bytes[] = {
6627 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6628 };
6629 string nonce = make_string(nonce_bytes);
6630 const uint8_t ciphertext_bytes[] = {
6631 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6632 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6633 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6634 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6635 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6636 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6637 };
6638 string ciphertext = make_string(ciphertext_bytes);
6639
6640 auto params = AuthorizationSetBuilder()
6641 .BlockMode(BlockMode::GCM)
6642 .Padding(PaddingMode::NONE)
6643 .Authorization(TAG_MAC_LENGTH, 128)
6644 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6645
6646 auto import_params = AuthorizationSetBuilder()
6647 .Authorization(TAG_NO_AUTH_REQUIRED)
6648 .AesEncryptionKey(128)
6649 .BlockMode(BlockMode::GCM)
6650 .Padding(PaddingMode::NONE)
6651 .Authorization(TAG_CALLER_NONCE)
6652 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6653
6654 // Import correct key and decrypt
6655 const uint8_t key_bytes[] = {
6656 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6657 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6658 };
6659 string key = make_string(key_bytes);
6660 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6661 string plaintext = DecryptMessage(ciphertext, params);
6662 CheckedDeleteKey();
6663
6664 // Corrupt key and attempt to decrypt
6665 key[0] = 0;
6666 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6667 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6668 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6669 CheckedDeleteKey();
6670}
6671
6672/*
6673 * EncryptionOperationsTest.AesGcmAadNoData
6674 *
6675 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6676 * encrypt.
6677 */
6678TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6680 .Authorization(TAG_NO_AUTH_REQUIRED)
6681 .AesEncryptionKey(128)
6682 .BlockMode(BlockMode::GCM)
6683 .Padding(PaddingMode::NONE)
6684 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6685
6686 string aad = "1234567890123456";
6687 auto params = AuthorizationSetBuilder()
6688 .BlockMode(BlockMode::GCM)
6689 .Padding(PaddingMode::NONE)
6690 .Authorization(TAG_MAC_LENGTH, 128);
6691
Selene Huang31ab4042020-04-29 04:22:39 -07006692 // Encrypt
6693 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006694 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006695 string ciphertext;
6696 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006697 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6698 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006699 EXPECT_TRUE(finish_out_params.empty());
6700
6701 // Grab nonce
6702 params.push_back(begin_out_params);
6703
6704 // Decrypt.
6705 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006706 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006707 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006708 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006709
6710 EXPECT_TRUE(finish_out_params.empty());
6711
6712 EXPECT_EQ("", plaintext);
6713}
6714
6715/*
6716 * EncryptionOperationsTest.AesGcmMultiPartAad
6717 *
6718 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6719 * chunks.
6720 */
6721TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6722 const size_t tag_bits = 128;
6723 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6724 .Authorization(TAG_NO_AUTH_REQUIRED)
6725 .AesEncryptionKey(128)
6726 .BlockMode(BlockMode::GCM)
6727 .Padding(PaddingMode::NONE)
6728 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6729
6730 string message = "123456789012345678901234567890123456";
6731 auto begin_params = AuthorizationSetBuilder()
6732 .BlockMode(BlockMode::GCM)
6733 .Padding(PaddingMode::NONE)
6734 .Authorization(TAG_MAC_LENGTH, tag_bits);
6735 AuthorizationSet begin_out_params;
6736
David Drysdale7fc26b92022-05-13 09:54:24 +01006737 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006738
6739 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006740 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6741 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006742 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006743 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6744 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006745
Selene Huang31ab4042020-04-29 04:22:39 -07006746 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006747 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006748
6749 // Grab nonce.
6750 begin_params.push_back(begin_out_params);
6751
6752 // Decrypt
David Drysdale7fc26b92022-05-13 09:54:24 +01006753 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006754 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006755 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006756 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006757 EXPECT_EQ(message, plaintext);
6758}
6759
6760/*
6761 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6762 *
6763 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6764 */
6765TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6766 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6767 .Authorization(TAG_NO_AUTH_REQUIRED)
6768 .AesEncryptionKey(128)
6769 .BlockMode(BlockMode::GCM)
6770 .Padding(PaddingMode::NONE)
6771 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6772
6773 string message = "123456789012345678901234567890123456";
6774 auto begin_params = AuthorizationSetBuilder()
6775 .BlockMode(BlockMode::GCM)
6776 .Padding(PaddingMode::NONE)
6777 .Authorization(TAG_MAC_LENGTH, 128);
6778 AuthorizationSet begin_out_params;
6779
David Drysdale7fc26b92022-05-13 09:54:24 +01006780 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07006781
Shawn Willden92d79c02021-02-19 07:31:55 -07006782 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006783 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006784 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6785 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006786
David Drysdaled2cc8c22021-04-15 13:29:45 +01006787 // The failure should have already cancelled the operation.
6788 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6789
Shawn Willden92d79c02021-02-19 07:31:55 -07006790 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006791}
6792
6793/*
6794 * EncryptionOperationsTest.AesGcmBadAad
6795 *
6796 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6797 */
6798TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6799 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6800 .Authorization(TAG_NO_AUTH_REQUIRED)
6801 .AesEncryptionKey(128)
6802 .BlockMode(BlockMode::GCM)
6803 .Padding(PaddingMode::NONE)
6804 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6805
6806 string message = "12345678901234567890123456789012";
6807 auto begin_params = AuthorizationSetBuilder()
6808 .BlockMode(BlockMode::GCM)
6809 .Padding(PaddingMode::NONE)
6810 .Authorization(TAG_MAC_LENGTH, 128);
6811
Selene Huang31ab4042020-04-29 04:22:39 -07006812 // Encrypt
6813 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006814 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006815 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006816 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006817 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006818
6819 // Grab nonce
6820 begin_params.push_back(begin_out_params);
6821
Selene Huang31ab4042020-04-29 04:22:39 -07006822 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006823 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006824 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006825 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006826 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006827}
6828
6829/*
6830 * EncryptionOperationsTest.AesGcmWrongNonce
6831 *
6832 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6833 */
6834TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6835 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6836 .Authorization(TAG_NO_AUTH_REQUIRED)
6837 .AesEncryptionKey(128)
6838 .BlockMode(BlockMode::GCM)
6839 .Padding(PaddingMode::NONE)
6840 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6841
6842 string message = "12345678901234567890123456789012";
6843 auto begin_params = AuthorizationSetBuilder()
6844 .BlockMode(BlockMode::GCM)
6845 .Padding(PaddingMode::NONE)
6846 .Authorization(TAG_MAC_LENGTH, 128);
6847
Selene Huang31ab4042020-04-29 04:22:39 -07006848 // Encrypt
6849 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006850 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006851 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006852 string ciphertext;
6853 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006854 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006855
6856 // Wrong nonce
6857 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6858
6859 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006860 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006861 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006862 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006863 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006864
6865 // With wrong nonce, should have gotten garbage plaintext (or none).
6866 EXPECT_NE(message, plaintext);
6867}
6868
6869/*
6870 * EncryptionOperationsTest.AesGcmCorruptTag
6871 *
6872 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6873 */
6874TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6875 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6876 .Authorization(TAG_NO_AUTH_REQUIRED)
6877 .AesEncryptionKey(128)
6878 .BlockMode(BlockMode::GCM)
6879 .Padding(PaddingMode::NONE)
6880 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6881
6882 string aad = "1234567890123456";
6883 string message = "123456789012345678901234567890123456";
6884
6885 auto params = AuthorizationSetBuilder()
6886 .BlockMode(BlockMode::GCM)
6887 .Padding(PaddingMode::NONE)
6888 .Authorization(TAG_MAC_LENGTH, 128);
6889
Selene Huang31ab4042020-04-29 04:22:39 -07006890 // Encrypt
6891 AuthorizationSet begin_out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01006892 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006893 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006894 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006895 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006896
6897 // Corrupt tag
6898 ++(*ciphertext.rbegin());
6899
6900 // Grab nonce
6901 params.push_back(begin_out_params);
6902
6903 // Decrypt.
David Drysdale7fc26b92022-05-13 09:54:24 +01006904 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006905 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006906 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006907 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006908}
6909
6910/*
6911 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6912 *
6913 * Verifies that 3DES is basically functional.
6914 */
6915TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6916 auto auths = AuthorizationSetBuilder()
6917 .TripleDesEncryptionKey(168)
6918 .BlockMode(BlockMode::ECB)
6919 .Authorization(TAG_NO_AUTH_REQUIRED)
6920 .Padding(PaddingMode::NONE);
6921
6922 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6923 // Two-block message.
6924 string message = "1234567890123456";
6925 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6926 string ciphertext1 = EncryptMessage(message, inParams);
6927 EXPECT_EQ(message.size(), ciphertext1.size());
6928
6929 string ciphertext2 = EncryptMessage(string(message), inParams);
6930 EXPECT_EQ(message.size(), ciphertext2.size());
6931
6932 // ECB is deterministic.
6933 EXPECT_EQ(ciphertext1, ciphertext2);
6934
6935 string plaintext = DecryptMessage(ciphertext1, inParams);
6936 EXPECT_EQ(message, plaintext);
6937}
6938
6939/*
6940 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6941 *
6942 * Verifies that CBC keys reject ECB usage.
6943 */
6944TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6945 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6946 .TripleDesEncryptionKey(168)
6947 .BlockMode(BlockMode::CBC)
6948 .Authorization(TAG_NO_AUTH_REQUIRED)
6949 .Padding(PaddingMode::NONE)));
6950
6951 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6952 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6953}
6954
6955/*
6956 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6957 *
6958 * Tests ECB mode with PKCS#7 padding, various message sizes.
6959 */
6960TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6961 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6962 .TripleDesEncryptionKey(168)
6963 .BlockMode(BlockMode::ECB)
6964 .Authorization(TAG_NO_AUTH_REQUIRED)
6965 .Padding(PaddingMode::PKCS7)));
6966
6967 for (size_t i = 0; i < 32; ++i) {
David Drysdaleb97121d2022-08-12 11:54:08 +01006968 SCOPED_TRACE(testing::Message() << "msg size=" << i);
Selene Huang31ab4042020-04-29 04:22:39 -07006969 string message(i, 'a');
6970 auto inParams =
6971 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6972 string ciphertext = EncryptMessage(message, inParams);
6973 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6974 string plaintext = DecryptMessage(ciphertext, inParams);
6975 EXPECT_EQ(message, plaintext);
6976 }
6977}
6978
6979/*
6980 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6981 *
6982 * Verifies that keys configured for no padding reject PKCS7 padding
6983 */
6984TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6985 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6986 .TripleDesEncryptionKey(168)
6987 .BlockMode(BlockMode::ECB)
6988 .Authorization(TAG_NO_AUTH_REQUIRED)
6989 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006990 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6991 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006992}
6993
6994/*
6995 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6996 *
6997 * Verifies that corrupted padding is detected.
6998 */
6999TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
7000 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7001 .TripleDesEncryptionKey(168)
7002 .BlockMode(BlockMode::ECB)
7003 .Authorization(TAG_NO_AUTH_REQUIRED)
7004 .Padding(PaddingMode::PKCS7)));
7005
7006 string message = "a";
7007 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
7008 EXPECT_EQ(8U, ciphertext.size());
7009 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007010
7011 AuthorizationSetBuilder begin_params;
7012 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
7013 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07007014
7015 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
7016 ++ciphertext[ciphertext.size() / 2];
7017
David Drysdale7fc26b92022-05-13 09:54:24 +01007018 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007019 string plaintext;
7020 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7021 ErrorCode error = Finish(&plaintext);
7022 if (error == ErrorCode::INVALID_ARGUMENT) {
7023 // This is the expected error, we can exit the test now.
7024 return;
7025 } else {
7026 // Very small chance we got valid decryption, so try again.
7027 ASSERT_EQ(error, ErrorCode::OK);
7028 }
7029 }
7030 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007031}
7032
7033struct TripleDesTestVector {
7034 const char* name;
7035 const KeyPurpose purpose;
7036 const BlockMode block_mode;
7037 const PaddingMode padding_mode;
7038 const char* key;
7039 const char* iv;
7040 const char* input;
7041 const char* output;
7042};
7043
7044// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
7045// of the NIST vectors are multiples of the block size.
7046static const TripleDesTestVector kTripleDesTestVectors[] = {
7047 {
7048 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7049 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
7050 "", // IV
7051 "329d86bdf1bc5af4", // input
7052 "d946c2756d78633f", // output
7053 },
7054 {
7055 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
7056 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
7057 "", // IV
7058 "6b1540781b01ce1997adae102dbf3c5b", // input
7059 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
7060 },
7061 {
7062 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7063 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
7064 "", // IV
7065 "6daad94ce08acfe7", // input
7066 "660e7d32dcc90e79", // output
7067 },
7068 {
7069 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
7070 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
7071 "", // IV
7072 "e9653a0a1f05d31b9acd12d73aa9879d", // input
7073 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
7074 },
7075 {
7076 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7077 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
7078 "43f791134c5647ba", // IV
7079 "dcc153cef81d6f24", // input
7080 "92538bd8af18d3ba", // output
7081 },
7082 {
7083 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
7084 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7085 "c2e999cb6249023c", // IV
7086 "c689aee38a301bb316da75db36f110b5", // input
7087 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
7088 },
7089 {
7090 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
7091 PaddingMode::PKCS7,
7092 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7093 "c2e999cb6249023c", // IV
7094 "c689aee38a301bb316da75db36f110b500", // input
7095 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
7096 },
7097 {
7098 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
7099 PaddingMode::PKCS7,
7100 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
7101 "c2e999cb6249023c", // IV
7102 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
7103 "c689aee38a301bb316da75db36f110b500", // output
7104 },
7105 {
7106 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7107 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
7108 "41746c7e442d3681", // IV
7109 "c53a7b0ec40600fe", // input
7110 "d4f00eb455de1034", // output
7111 },
7112 {
7113 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
7114 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
7115 "3982bc02c3727d45", // IV
7116 "6006f10adef52991fcc777a1238bbb65", // input
7117 "edae09288e9e3bc05746d872b48e3b29", // output
7118 },
7119};
7120
7121/*
7122 * EncryptionOperationsTest.TripleDesTestVector
7123 *
7124 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
7125 */
7126TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
7127 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
7128 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
7129 SCOPED_TRACE(test->name);
7130 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
7131 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
7132 hex2str(test->output));
7133 }
7134}
7135
7136/*
7137 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
7138 *
7139 * Validates CBC mode functionality.
7140 */
7141TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
7142 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7143 .TripleDesEncryptionKey(168)
7144 .BlockMode(BlockMode::CBC)
7145 .Authorization(TAG_NO_AUTH_REQUIRED)
7146 .Padding(PaddingMode::NONE)));
7147
7148 ASSERT_GT(key_blob_.size(), 0U);
7149
Brian J Murray734c8412022-01-13 14:55:30 -08007150 // Four-block message.
7151 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07007152 vector<uint8_t> iv1;
7153 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
7154 EXPECT_EQ(message.size(), ciphertext1.size());
7155
7156 vector<uint8_t> iv2;
7157 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
7158 EXPECT_EQ(message.size(), ciphertext2.size());
7159
7160 // IVs should be random, so ciphertexts should differ.
7161 EXPECT_NE(iv1, iv2);
7162 EXPECT_NE(ciphertext1, ciphertext2);
7163
7164 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
7165 EXPECT_EQ(message, plaintext);
7166}
7167
7168/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007169 * EncryptionOperationsTest.TripleDesInvalidCallerIv
7170 *
7171 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
7172 */
7173TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
7174 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7175 .TripleDesEncryptionKey(168)
7176 .BlockMode(BlockMode::CBC)
7177 .Authorization(TAG_NO_AUTH_REQUIRED)
7178 .Authorization(TAG_CALLER_NONCE)
7179 .Padding(PaddingMode::NONE)));
7180 auto params = AuthorizationSetBuilder()
7181 .BlockMode(BlockMode::CBC)
7182 .Padding(PaddingMode::NONE)
7183 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
7184 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
7185}
7186
7187/*
Selene Huang31ab4042020-04-29 04:22:39 -07007188 * EncryptionOperationsTest.TripleDesCallerIv
7189 *
7190 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
7191 */
7192TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
7193 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7194 .TripleDesEncryptionKey(168)
7195 .BlockMode(BlockMode::CBC)
7196 .Authorization(TAG_NO_AUTH_REQUIRED)
7197 .Authorization(TAG_CALLER_NONCE)
7198 .Padding(PaddingMode::NONE)));
7199 string message = "1234567890123456";
7200 vector<uint8_t> iv;
7201 // Don't specify IV, should get a random one.
7202 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7203 EXPECT_EQ(message.size(), ciphertext1.size());
7204 EXPECT_EQ(8U, iv.size());
7205
7206 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7207 EXPECT_EQ(message, plaintext);
7208
7209 // Now specify an IV, should also work.
7210 iv = AidlBuf("abcdefgh");
7211 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
7212
7213 // Decrypt with correct IV.
7214 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
7215 EXPECT_EQ(message, plaintext);
7216
7217 // Now try with wrong IV.
7218 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
7219 EXPECT_NE(message, plaintext);
7220}
7221
7222/*
7223 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
7224 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01007225 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07007226 */
7227TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
7228 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7229 .TripleDesEncryptionKey(168)
7230 .BlockMode(BlockMode::CBC)
7231 .Authorization(TAG_NO_AUTH_REQUIRED)
7232 .Padding(PaddingMode::NONE)));
7233
7234 string message = "12345678901234567890123456789012";
7235 vector<uint8_t> iv;
7236 // Don't specify nonce, should get a random one.
7237 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
7238 EXPECT_EQ(message.size(), ciphertext1.size());
7239 EXPECT_EQ(8U, iv.size());
7240
7241 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
7242 EXPECT_EQ(message, plaintext);
7243
7244 // Now specify a nonce, should fail.
7245 auto input_params = AuthorizationSetBuilder()
7246 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
7247 .BlockMode(BlockMode::CBC)
7248 .Padding(PaddingMode::NONE);
7249 AuthorizationSet output_params;
7250 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
7251 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
7252}
7253
7254/*
7255 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
7256 *
7257 * Verifies that 3DES ECB-only keys do not allow CBC usage.
7258 */
7259TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
7260 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7261 .TripleDesEncryptionKey(168)
7262 .BlockMode(BlockMode::ECB)
7263 .Authorization(TAG_NO_AUTH_REQUIRED)
7264 .Padding(PaddingMode::NONE)));
7265 // Two-block message.
7266 string message = "1234567890123456";
7267 auto begin_params =
7268 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7269 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7270}
7271
7272/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01007273 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07007274 *
7275 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
7276 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01007277TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
7278 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007279 SCOPED_TRACE(testing::Message() << "BlockMode::" << blockMode);
David Drysdaled2cc8c22021-04-15 13:29:45 +01007280 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7281 .TripleDesEncryptionKey(168)
7282 .BlockMode(blockMode)
7283 .Authorization(TAG_NO_AUTH_REQUIRED)
7284 .Padding(PaddingMode::NONE)));
7285 // Message is slightly shorter than two blocks.
7286 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07007287
David Drysdaled2cc8c22021-04-15 13:29:45 +01007288 auto begin_params =
7289 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
7290 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007291 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01007292 string ciphertext;
7293 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
7294
7295 CheckedDeleteKey();
7296 }
Selene Huang31ab4042020-04-29 04:22:39 -07007297}
7298
7299/*
7300 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
7301 *
7302 * Verifies that PKCS7 padding works correctly in CBC mode.
7303 */
7304TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
7305 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7306 .TripleDesEncryptionKey(168)
7307 .BlockMode(BlockMode::CBC)
7308 .Authorization(TAG_NO_AUTH_REQUIRED)
7309 .Padding(PaddingMode::PKCS7)));
7310
7311 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08007312 for (size_t i = 0; i <= 32; i++) {
7313 SCOPED_TRACE(testing::Message() << "i = " << i);
7314 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
7315 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07007316 vector<uint8_t> iv;
7317 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7318 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
7319 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
7320 EXPECT_EQ(message, plaintext);
7321 }
7322}
7323
7324/*
7325 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
7326 *
7327 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
7328 */
7329TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
7330 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7331 .TripleDesEncryptionKey(168)
7332 .BlockMode(BlockMode::CBC)
7333 .Authorization(TAG_NO_AUTH_REQUIRED)
7334 .Padding(PaddingMode::NONE)));
7335
7336 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08007337 for (size_t i = 0; i <= 32; i++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01007338 SCOPED_TRACE(testing::Message() << "i = " << i);
Selene Huang31ab4042020-04-29 04:22:39 -07007339 auto begin_params =
7340 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
7341 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
7342 }
7343}
7344
7345/*
7346 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
7347 *
7348 * Verifies that corrupted PKCS7 padding is rejected during decryption.
7349 */
7350TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
7351 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7352 .TripleDesEncryptionKey(168)
7353 .BlockMode(BlockMode::CBC)
7354 .Authorization(TAG_NO_AUTH_REQUIRED)
7355 .Padding(PaddingMode::PKCS7)));
7356
7357 string message = "a";
7358 vector<uint8_t> iv;
7359 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
7360 EXPECT_EQ(8U, ciphertext.size());
7361 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07007362
7363 auto begin_params = AuthorizationSetBuilder()
7364 .BlockMode(BlockMode::CBC)
7365 .Padding(PaddingMode::PKCS7)
7366 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07007367
7368 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08007369 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07007370 ++ciphertext[ciphertext.size() / 2];
David Drysdale7fc26b92022-05-13 09:54:24 +01007371 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Seth Moore7a55ae32021-06-23 14:28:11 -07007372 string plaintext;
7373 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
7374 ErrorCode error = Finish(&plaintext);
7375 if (error == ErrorCode::INVALID_ARGUMENT) {
7376 // This is the expected error, we can exit the test now.
7377 return;
7378 } else {
7379 // Very small chance we got valid decryption, so try again.
7380 ASSERT_EQ(error, ErrorCode::OK);
7381 }
7382 }
7383 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07007384}
7385
7386/*
7387 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
7388 *
7389 * Verifies that 3DES CBC works with many different input sizes.
7390 */
7391TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
7392 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7393 .TripleDesEncryptionKey(168)
7394 .BlockMode(BlockMode::CBC)
7395 .Authorization(TAG_NO_AUTH_REQUIRED)
7396 .Padding(PaddingMode::NONE)));
7397
7398 int increment = 7;
7399 string message(240, 'a');
7400 AuthorizationSet input_params =
7401 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
7402 AuthorizationSet output_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01007403 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007404
7405 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07007406 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007407 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07007408 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
7409 EXPECT_EQ(message.size(), ciphertext.size());
7410
7411 // Move TAG_NONCE into input_params
7412 input_params = output_params;
7413 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
7414 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
7415 output_params.Clear();
7416
David Drysdale7fc26b92022-05-13 09:54:24 +01007417 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007418 string plaintext;
7419 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07007420 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07007421 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
7422 EXPECT_EQ(ciphertext.size(), plaintext.size());
7423 EXPECT_EQ(message, plaintext);
7424}
7425
7426INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
7427
7428typedef KeyMintAidlTestBase MaxOperationsTest;
7429
7430/*
7431 * MaxOperationsTest.TestLimitAes
7432 *
7433 * Verifies that the max uses per boot tag works correctly with AES keys.
7434 */
7435TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007436 if (SecLevel() == SecurityLevel::STRONGBOX) {
7437 GTEST_SKIP() << "Test not applicable to StrongBox device";
7438 }
Selene Huang31ab4042020-04-29 04:22:39 -07007439
7440 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7441 .Authorization(TAG_NO_AUTH_REQUIRED)
7442 .AesEncryptionKey(128)
7443 .EcbMode()
7444 .Padding(PaddingMode::NONE)
7445 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
7446
7447 string message = "1234567890123456";
7448
7449 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7450
7451 EncryptMessage(message, params);
7452 EncryptMessage(message, params);
7453 EncryptMessage(message, params);
7454
7455 // Fourth time should fail.
7456 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
7457}
7458
7459/*
Qi Wud22ec842020-11-26 13:27:53 +08007460 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07007461 *
7462 * Verifies that the max uses per boot tag works correctly with RSA keys.
7463 */
7464TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007465 if (SecLevel() == SecurityLevel::STRONGBOX) {
7466 GTEST_SKIP() << "Test not applicable to StrongBox device";
7467 }
Selene Huang31ab4042020-04-29 04:22:39 -07007468
7469 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7470 .Authorization(TAG_NO_AUTH_REQUIRED)
7471 .RsaSigningKey(1024, 65537)
7472 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007473 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
7474 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007475
7476 string message = "1234567890123456";
7477
7478 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7479
7480 SignMessage(message, params);
7481 SignMessage(message, params);
7482 SignMessage(message, params);
7483
7484 // Fourth time should fail.
7485 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
7486}
7487
7488INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
7489
Qi Wud22ec842020-11-26 13:27:53 +08007490typedef KeyMintAidlTestBase UsageCountLimitTest;
7491
7492/*
Qi Wubeefae42021-01-28 23:16:37 +08007493 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007494 *
Qi Wubeefae42021-01-28 23:16:37 +08007495 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007496 */
Qi Wubeefae42021-01-28 23:16:37 +08007497TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007498 if (SecLevel() == SecurityLevel::STRONGBOX) {
7499 GTEST_SKIP() << "Test not applicable to StrongBox device";
7500 }
Qi Wud22ec842020-11-26 13:27:53 +08007501
7502 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7503 .Authorization(TAG_NO_AUTH_REQUIRED)
7504 .AesEncryptionKey(128)
7505 .EcbMode()
7506 .Padding(PaddingMode::NONE)
7507 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
7508
7509 // Check the usage count limit tag appears in the authorizations.
7510 AuthorizationSet auths;
7511 for (auto& entry : key_characteristics_) {
7512 auths.push_back(AuthorizationSet(entry.authorizations));
7513 }
7514 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7515 << "key usage count limit " << 1U << " missing";
7516
7517 string message = "1234567890123456";
7518 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7519
Qi Wubeefae42021-01-28 23:16:37 +08007520 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7521 AuthorizationSet keystore_auths =
7522 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7523
Qi Wud22ec842020-11-26 13:27:53 +08007524 // First usage of AES key should work.
7525 EncryptMessage(message, params);
7526
Qi Wud22ec842020-11-26 13:27:53 +08007527 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7528 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7529 // must be invalidated from secure storage (such as RPMB partition).
7530 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7531 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007532 // Usage count limit tag is enforced by keystore, keymint does nothing.
7533 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007534 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wud22ec842020-11-26 13:27:53 +08007535 }
7536}
7537
7538/*
Qi Wubeefae42021-01-28 23:16:37 +08007539 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08007540 *
Qi Wubeefae42021-01-28 23:16:37 +08007541 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08007542 */
Qi Wubeefae42021-01-28 23:16:37 +08007543TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01007544 if (SecLevel() == SecurityLevel::STRONGBOX) {
7545 GTEST_SKIP() << "Test not applicable to StrongBox device";
7546 }
Qi Wubeefae42021-01-28 23:16:37 +08007547
7548 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7549 .Authorization(TAG_NO_AUTH_REQUIRED)
7550 .AesEncryptionKey(128)
7551 .EcbMode()
7552 .Padding(PaddingMode::NONE)
7553 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
7554
7555 // Check the usage count limit tag appears in the authorizations.
7556 AuthorizationSet auths;
7557 for (auto& entry : key_characteristics_) {
7558 auths.push_back(AuthorizationSet(entry.authorizations));
7559 }
7560 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7561 << "key usage count limit " << 3U << " missing";
7562
7563 string message = "1234567890123456";
7564 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
7565
7566 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7567 AuthorizationSet keystore_auths =
7568 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7569
7570 EncryptMessage(message, params);
7571 EncryptMessage(message, params);
7572 EncryptMessage(message, params);
7573
7574 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7575 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7576 // must be invalidated from secure storage (such as RPMB partition).
7577 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7578 } else {
7579 // Usage count limit tag is enforced by keystore, keymint does nothing.
7580 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007581 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
Qi Wubeefae42021-01-28 23:16:37 +08007582 }
7583}
7584
7585/*
7586 * UsageCountLimitTest.TestSingleUseRsa
7587 *
7588 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7589 */
7590TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007591 if (SecLevel() == SecurityLevel::STRONGBOX) {
7592 GTEST_SKIP() << "Test not applicable to StrongBox device";
7593 }
Qi Wud22ec842020-11-26 13:27:53 +08007594
7595 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7596 .Authorization(TAG_NO_AUTH_REQUIRED)
7597 .RsaSigningKey(1024, 65537)
7598 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007599 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7600 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007601
7602 // Check the usage count limit tag appears in the authorizations.
7603 AuthorizationSet auths;
7604 for (auto& entry : key_characteristics_) {
7605 auths.push_back(AuthorizationSet(entry.authorizations));
7606 }
7607 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7608 << "key usage count limit " << 1U << " missing";
7609
7610 string message = "1234567890123456";
7611 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7612
Qi Wubeefae42021-01-28 23:16:37 +08007613 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7614 AuthorizationSet keystore_auths =
7615 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7616
Qi Wud22ec842020-11-26 13:27:53 +08007617 // First usage of RSA key should work.
7618 SignMessage(message, params);
7619
Qi Wud22ec842020-11-26 13:27:53 +08007620 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7621 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7622 // must be invalidated from secure storage (such as RPMB partition).
7623 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7624 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007625 // Usage count limit tag is enforced by keystore, keymint does nothing.
7626 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007627 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wubeefae42021-01-28 23:16:37 +08007628 }
7629}
7630
7631/*
7632 * UsageCountLimitTest.TestLimitUseRsa
7633 *
7634 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7635 */
7636TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007637 if (SecLevel() == SecurityLevel::STRONGBOX) {
7638 GTEST_SKIP() << "Test not applicable to StrongBox device";
7639 }
Qi Wubeefae42021-01-28 23:16:37 +08007640
7641 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7642 .Authorization(TAG_NO_AUTH_REQUIRED)
7643 .RsaSigningKey(1024, 65537)
7644 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007645 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7646 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007647
7648 // Check the usage count limit tag appears in the authorizations.
7649 AuthorizationSet auths;
7650 for (auto& entry : key_characteristics_) {
7651 auths.push_back(AuthorizationSet(entry.authorizations));
7652 }
7653 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7654 << "key usage count limit " << 3U << " missing";
7655
7656 string message = "1234567890123456";
7657 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7658
7659 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7660 AuthorizationSet keystore_auths =
7661 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7662
7663 SignMessage(message, params);
7664 SignMessage(message, params);
7665 SignMessage(message, params);
7666
7667 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7668 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7669 // must be invalidated from secure storage (such as RPMB partition).
7670 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7671 } else {
7672 // Usage count limit tag is enforced by keystore, keymint does nothing.
7673 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
David Drysdale7fc26b92022-05-13 09:54:24 +01007674 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
Qi Wud22ec842020-11-26 13:27:53 +08007675 }
7676}
7677
Qi Wu8e727f72021-02-11 02:49:33 +08007678/*
7679 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7680 *
7681 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7682 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7683 * in hardware.
7684 */
7685TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007686 if (SecLevel() == SecurityLevel::STRONGBOX) {
7687 GTEST_SKIP() << "Test not applicable to StrongBox device";
7688 }
Qi Wu8e727f72021-02-11 02:49:33 +08007689
7690 auto error = GenerateKey(AuthorizationSetBuilder()
7691 .RsaSigningKey(2048, 65537)
7692 .Digest(Digest::NONE)
7693 .Padding(PaddingMode::NONE)
7694 .Authorization(TAG_NO_AUTH_REQUIRED)
7695 .Authorization(TAG_ROLLBACK_RESISTANCE)
7696 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007697 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7698 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007699 }
David Drysdale513bf122021-10-06 11:53:13 +01007700
7701 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7702 ASSERT_EQ(ErrorCode::OK, error);
7703 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7704 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7705 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7706
7707 // The KeyMint should also enforce single use key in hardware when it supports rollback
7708 // resistance.
7709 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7710 .Authorization(TAG_NO_AUTH_REQUIRED)
7711 .RsaSigningKey(1024, 65537)
7712 .NoDigestOrPadding()
7713 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7714 .SetDefaultValidity()));
7715
7716 // Check the usage count limit tag appears in the hardware authorizations.
7717 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7718 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7719 << "key usage count limit " << 1U << " missing";
7720
7721 string message = "1234567890123456";
7722 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7723
7724 // First usage of RSA key should work.
7725 SignMessage(message, params);
7726
7727 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7728 // must be invalidated from secure storage (such as RPMB partition).
7729 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007730}
7731
Qi Wud22ec842020-11-26 13:27:53 +08007732INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7733
David Drysdale7de9feb2021-03-05 14:56:19 +00007734typedef KeyMintAidlTestBase GetHardwareInfoTest;
7735
7736TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7737 // Retrieving hardware info should give the same result each time.
7738 KeyMintHardwareInfo info;
7739 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7740 KeyMintHardwareInfo info2;
7741 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7742 EXPECT_EQ(info, info2);
7743}
7744
7745INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7746
Selene Huang31ab4042020-04-29 04:22:39 -07007747typedef KeyMintAidlTestBase AddEntropyTest;
7748
7749/*
7750 * AddEntropyTest.AddEntropy
7751 *
7752 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7753 * is actually added.
7754 */
7755TEST_P(AddEntropyTest, AddEntropy) {
7756 string data = "foo";
7757 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7758}
7759
7760/*
7761 * AddEntropyTest.AddEmptyEntropy
7762 *
7763 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7764 */
7765TEST_P(AddEntropyTest, AddEmptyEntropy) {
7766 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7767}
7768
7769/*
7770 * AddEntropyTest.AddLargeEntropy
7771 *
7772 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7773 */
7774TEST_P(AddEntropyTest, AddLargeEntropy) {
7775 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7776}
7777
David Drysdalebb3d85e2021-04-13 11:15:51 +01007778/*
7779 * AddEntropyTest.AddTooLargeEntropy
7780 *
7781 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7782 */
7783TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7784 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7785 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7786}
7787
Selene Huang31ab4042020-04-29 04:22:39 -07007788INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7789
Selene Huang31ab4042020-04-29 04:22:39 -07007790typedef KeyMintAidlTestBase KeyDeletionTest;
7791
7792/**
7793 * KeyDeletionTest.DeleteKey
7794 *
7795 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7796 * valid key blob.
7797 */
7798TEST_P(KeyDeletionTest, DeleteKey) {
7799 auto error = GenerateKey(AuthorizationSetBuilder()
7800 .RsaSigningKey(2048, 65537)
7801 .Digest(Digest::NONE)
7802 .Padding(PaddingMode::NONE)
7803 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007804 .Authorization(TAG_ROLLBACK_RESISTANCE)
7805 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007806 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7807 GTEST_SKIP() << "Rollback resistance not supported";
7808 }
Selene Huang31ab4042020-04-29 04:22:39 -07007809
7810 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007811 ASSERT_EQ(ErrorCode::OK, error);
7812 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7813 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007814
David Drysdale513bf122021-10-06 11:53:13 +01007815 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007816
David Drysdale513bf122021-10-06 11:53:13 +01007817 string message = "12345678901234567890123456789012";
7818 AuthorizationSet begin_out_params;
7819 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7820 Begin(KeyPurpose::SIGN, key_blob_,
7821 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7822 &begin_out_params));
7823 AbortIfNeeded();
7824 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007825}
7826
7827/**
7828 * KeyDeletionTest.DeleteInvalidKey
7829 *
7830 * This test checks that the HAL excepts invalid key blobs..
7831 */
7832TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7833 // Generate key just to check if rollback protection is implemented
7834 auto error = GenerateKey(AuthorizationSetBuilder()
7835 .RsaSigningKey(2048, 65537)
7836 .Digest(Digest::NONE)
7837 .Padding(PaddingMode::NONE)
7838 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007839 .Authorization(TAG_ROLLBACK_RESISTANCE)
7840 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007841 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7842 GTEST_SKIP() << "Rollback resistance not supported";
7843 }
Selene Huang31ab4042020-04-29 04:22:39 -07007844
7845 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007846 ASSERT_EQ(ErrorCode::OK, error);
7847 AuthorizationSet enforced(SecLevelAuthorizations());
7848 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007849
David Drysdale513bf122021-10-06 11:53:13 +01007850 // Delete the key we don't care about the result at this point.
7851 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007852
David Drysdale513bf122021-10-06 11:53:13 +01007853 // Now create an invalid key blob and delete it.
7854 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007855
David Drysdale513bf122021-10-06 11:53:13 +01007856 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007857}
7858
7859/**
7860 * KeyDeletionTest.DeleteAllKeys
7861 *
7862 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7863 *
7864 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7865 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7866 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7867 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7868 * credentials stored in Keystore/Keymint.
7869 */
7870TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007871 if (!arm_deleteAllKeys) {
7872 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7873 return;
7874 }
Selene Huang31ab4042020-04-29 04:22:39 -07007875 auto error = GenerateKey(AuthorizationSetBuilder()
7876 .RsaSigningKey(2048, 65537)
7877 .Digest(Digest::NONE)
7878 .Padding(PaddingMode::NONE)
7879 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007880 .Authorization(TAG_ROLLBACK_RESISTANCE)
7881 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007882 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7883 GTEST_SKIP() << "Rollback resistance not supported";
7884 }
Selene Huang31ab4042020-04-29 04:22:39 -07007885
7886 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007887 ASSERT_EQ(ErrorCode::OK, error);
7888 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7889 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007890
David Drysdale513bf122021-10-06 11:53:13 +01007891 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007892
David Drysdale513bf122021-10-06 11:53:13 +01007893 string message = "12345678901234567890123456789012";
7894 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007895
David Drysdale513bf122021-10-06 11:53:13 +01007896 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7897 Begin(KeyPurpose::SIGN, key_blob_,
7898 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7899 &begin_out_params));
7900 AbortIfNeeded();
7901 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007902}
7903
7904INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7905
David Drysdaled2cc8c22021-04-15 13:29:45 +01007906typedef KeyMintAidlTestBase KeyUpgradeTest;
7907
7908/**
7909 * KeyUpgradeTest.UpgradeInvalidKey
7910 *
7911 * This test checks that the HAL excepts invalid key blobs..
7912 */
7913TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7914 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7915
7916 std::vector<uint8_t> new_blob;
7917 Status result = keymint_->upgradeKey(key_blob,
7918 AuthorizationSetBuilder()
7919 .Authorization(TAG_APPLICATION_ID, "clientid")
7920 .Authorization(TAG_APPLICATION_DATA, "appdata")
7921 .vector_data(),
7922 &new_blob);
7923 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7924}
7925
7926INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7927
Selene Huang31ab4042020-04-29 04:22:39 -07007928using UpgradeKeyTest = KeyMintAidlTestBase;
7929
7930/*
7931 * UpgradeKeyTest.UpgradeKey
7932 *
7933 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7934 */
7935TEST_P(UpgradeKeyTest, UpgradeKey) {
7936 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7937 .AesEncryptionKey(128)
7938 .Padding(PaddingMode::NONE)
7939 .Authorization(TAG_NO_AUTH_REQUIRED)));
7940
7941 auto result = UpgradeKey(key_blob_);
7942
7943 // Key doesn't need upgrading. Should get okay, but no new key blob.
7944 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7945}
7946
7947INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7948
7949using ClearOperationsTest = KeyMintAidlTestBase;
7950
7951/*
7952 * ClearSlotsTest.TooManyOperations
7953 *
7954 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7955 * operations are started without being finished or aborted. Also verifies
7956 * that aborting the operations clears the operations.
7957 *
7958 */
7959TEST_P(ClearOperationsTest, TooManyOperations) {
7960 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7961 .Authorization(TAG_NO_AUTH_REQUIRED)
7962 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007963 .Padding(PaddingMode::NONE)
7964 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007965
7966 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7967 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007968 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007969 AuthorizationSet out_params;
7970 ErrorCode result;
7971 size_t i;
7972
7973 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00007974 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07007975 if (ErrorCode::OK != result) {
7976 break;
7977 }
7978 }
7979 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7980 // Try again just in case there's a weird overflow bug
7981 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00007982 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007983 for (size_t j = 0; j < i; j++) {
7984 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7985 << "Aboort failed for i = " << j << std::endl;
7986 }
David Drysdale7fc26b92022-05-13 09:54:24 +01007987 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007988 AbortIfNeeded();
7989}
7990
7991INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7992
7993typedef KeyMintAidlTestBase TransportLimitTest;
7994
7995/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007996 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007997 *
7998 * Verifies that passing input data to finish succeeds as expected.
7999 */
8000TEST_P(TransportLimitTest, LargeFinishInput) {
8001 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8002 .Authorization(TAG_NO_AUTH_REQUIRED)
8003 .AesEncryptionKey(128)
8004 .BlockMode(BlockMode::ECB)
8005 .Padding(PaddingMode::NONE)));
8006
8007 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008008 SCOPED_TRACE(testing::Message() << "msg_size = " << msg_size);
Selene Huang31ab4042020-04-29 04:22:39 -07008009 auto cipher_params =
8010 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
8011
8012 AuthorizationSet out_params;
David Drysdale7fc26b92022-05-13 09:54:24 +01008013 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008014
8015 string plain_message = std::string(1 << msg_size, 'x');
8016 string encrypted_message;
8017 auto rc = Finish(plain_message, &encrypted_message);
8018
8019 EXPECT_EQ(ErrorCode::OK, rc);
8020 EXPECT_EQ(plain_message.size(), encrypted_message.size())
8021 << "Encrypt finish returned OK, but did not consume all of the given input";
8022 cipher_params.push_back(out_params);
8023
David Drysdale7fc26b92022-05-13 09:54:24 +01008024 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
Selene Huang31ab4042020-04-29 04:22:39 -07008025
8026 string decrypted_message;
8027 rc = Finish(encrypted_message, &decrypted_message);
8028 EXPECT_EQ(ErrorCode::OK, rc);
8029 EXPECT_EQ(plain_message.size(), decrypted_message.size())
8030 << "Decrypt finish returned OK, did not consume all of the given input";
8031 }
8032}
8033
8034INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
8035
Seth Moored79a0ec2021-12-13 20:03:33 +00008036static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05008037 switch (curve) {
8038 case EcCurve::P_224:
8039 return NID_secp224r1;
8040 case EcCurve::P_256:
8041 return NID_X9_62_prime256v1;
8042 case EcCurve::P_384:
8043 return NID_secp384r1;
8044 case EcCurve::P_521:
8045 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00008046 case EcCurve::CURVE_25519:
8047 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05008048 }
8049}
8050
David Drysdale42fe1892021-10-14 14:43:46 +01008051class KeyAgreementTest : public KeyMintAidlTestBase {
8052 protected:
8053 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
8054 std::vector<uint8_t>* localPublicKey) {
8055 // Generate EC key locally (with access to private key material)
8056 if (localCurve == EcCurve::CURVE_25519) {
8057 uint8_t privKeyData[32];
8058 uint8_t pubKeyData[32];
8059 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01008060 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
8061 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
8062 } else {
8063 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
8064 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
8065 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
8066 ASSERT_NE(group, nullptr);
8067 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
8068 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
8069 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
8070 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01008071 }
David Drysdalea410b772022-05-09 16:44:13 +01008072
8073 // Get encoded form of the public part of the locally generated key...
8074 unsigned char* p = nullptr;
8075 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
8076 ASSERT_GT(localPublicKeySize, 0);
8077 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
8078 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
8079 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01008080 }
8081
8082 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
8083 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00008084 auto builder = AuthorizationSetBuilder()
8085 .Authorization(TAG_NO_AUTH_REQUIRED)
8086 .Authorization(TAG_EC_CURVE, curve)
8087 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8088 .Authorization(TAG_ALGORITHM, Algorithm::EC)
8089 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
8090 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
8091 .SetDefaultValidity();
8092 ErrorCode result = GenerateKey(builder);
8093
8094 if (SecLevel() == SecurityLevel::STRONGBOX) {
8095 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
8096 result = GenerateKeyWithSelfSignedAttestKey(
8097 AuthorizationSetBuilder()
8098 .EcdsaKey(EcCurve::P_256)
8099 .AttestKey()
8100 .SetDefaultValidity(), /* attest key params */
8101 builder, &key_blob_, &key_characteristics_, &cert_chain_);
8102 }
8103 }
David Drysdale42fe1892021-10-14 14:43:46 +01008104 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
8105 ASSERT_GT(cert_chain_.size(), 0);
8106 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8107 ASSERT_NE(kmKeyCert, nullptr);
8108 // Check that keyAgreement (bit 4) is set in KeyUsage
8109 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
8110 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
8111 ASSERT_NE(*kmPubKey, nullptr);
8112 if (dump_Attestations) {
8113 for (size_t n = 0; n < cert_chain_.size(); n++) {
8114 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
8115 }
8116 }
8117 }
8118
8119 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
8120 const std::vector<uint8_t>& localPublicKey) {
8121 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8122 string ZabFromKeyMintStr;
8123 ASSERT_EQ(ErrorCode::OK,
8124 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
8125 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
8126 vector<uint8_t> ZabFromTest;
8127
8128 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
8129 size_t kmPubKeySize = 32;
8130 uint8_t kmPubKeyData[32];
8131 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8132 ASSERT_EQ(kmPubKeySize, 32);
8133
8134 uint8_t localPrivKeyData[32];
8135 size_t localPrivKeySize = 32;
8136 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
8137 &localPrivKeySize));
8138 ASSERT_EQ(localPrivKeySize, 32);
8139
8140 uint8_t sharedKey[32];
8141 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
8142 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
8143 } else {
8144 // Perform local ECDH between the two keys so we can check if we get the same Zab..
8145 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
8146 ASSERT_NE(ctx, nullptr);
8147 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
8148 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
8149 size_t ZabFromTestLen = 0;
8150 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
8151 ZabFromTest.resize(ZabFromTestLen);
8152 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
8153 }
8154 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
8155 }
8156};
8157
David Zeuthene0c40892021-01-08 12:54:11 -05008158/*
8159 * KeyAgreementTest.Ecdh
8160 *
David Drysdale42fe1892021-10-14 14:43:46 +01008161 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05008162 */
8163TEST_P(KeyAgreementTest, Ecdh) {
8164 // Because it's possible to use this API with keys on different curves, we
8165 // check all N^2 combinations where N is the number of supported
8166 // curves.
8167 //
8168 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
8169 // lot more curves we can be smart about things and just pick |otherCurve| so
8170 // it's not |curve| and that way we end up with only 2*N runs
8171 //
8172 for (auto curve : ValidCurves()) {
8173 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01008174 SCOPED_TRACE(testing::Message()
8175 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
8176
David Zeuthene0c40892021-01-08 12:54:11 -05008177 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008178 EVP_PKEY_Ptr localPrivKey;
8179 vector<uint8_t> localPublicKey;
8180 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008181
8182 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01008183 EVP_PKEY_Ptr kmPubKey;
8184 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008185
8186 // Now that we have the two keys, we ask KeyMint to perform ECDH...
8187 if (curve != localCurve) {
8188 // If the keys are using different curves KeyMint should fail with
8189 // ErrorCode:INVALID_ARGUMENT. Check that.
David Drysdale7fc26b92022-05-13 09:54:24 +01008190 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Zeuthene0c40892021-01-08 12:54:11 -05008191 string ZabFromKeyMintStr;
8192 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01008193 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05008194 &ZabFromKeyMintStr));
8195
8196 } else {
8197 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01008198 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05008199 }
8200
8201 CheckedDeleteKey();
8202 }
8203 }
8204}
8205
David Drysdale42fe1892021-10-14 14:43:46 +01008206/*
8207 * KeyAgreementTest.EcdhCurve25519
8208 *
8209 * Verifies that ECDH works for curve25519. This is also covered by the general
8210 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
8211 * KeyMint 1.0.
8212 */
8213TEST_P(KeyAgreementTest, EcdhCurve25519) {
8214 if (!Curve25519Supported()) {
8215 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8216 }
8217
8218 // Generate EC key in KeyMint (only access to public key material)
8219 EcCurve curve = EcCurve::CURVE_25519;
8220 EVP_PKEY_Ptr kmPubKey = nullptr;
8221 GenerateKeyMintEcKey(curve, &kmPubKey);
8222
8223 // Generate EC key on same curve locally (with access to private key material).
8224 EVP_PKEY_Ptr privKey;
8225 vector<uint8_t> encodedPublicKey;
8226 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8227
8228 // Agree on a key between local and KeyMint and check it.
8229 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8230
8231 CheckedDeleteKey();
8232}
8233
8234/*
8235 * KeyAgreementTest.EcdhCurve25519Imported
8236 *
8237 * Verifies that ECDH works for an imported curve25519 key.
8238 */
8239TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
8240 if (!Curve25519Supported()) {
8241 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8242 }
8243
8244 // Import x25519 key into KeyMint.
8245 EcCurve curve = EcCurve::CURVE_25519;
8246 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
8247 .Authorization(TAG_NO_AUTH_REQUIRED)
8248 .EcdsaKey(EcCurve::CURVE_25519)
8249 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
8250 .SetDefaultValidity(),
8251 KeyFormat::PKCS8, x25519_pkcs8_key));
8252 ASSERT_GT(cert_chain_.size(), 0);
8253 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
8254 ASSERT_NE(kmKeyCert, nullptr);
8255 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
8256 ASSERT_NE(kmPubKey.get(), nullptr);
8257
8258 // Expect the import to emit corresponding public key data.
8259 size_t kmPubKeySize = 32;
8260 uint8_t kmPubKeyData[32];
8261 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
8262 ASSERT_EQ(kmPubKeySize, 32);
8263 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
8264 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
8265
8266 // Generate EC key on same curve locally (with access to private key material).
8267 EVP_PKEY_Ptr privKey;
8268 vector<uint8_t> encodedPublicKey;
8269 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8270
8271 // Agree on a key between local and KeyMint and check it.
8272 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
8273
8274 CheckedDeleteKey();
8275}
8276
8277/*
8278 * KeyAgreementTest.EcdhCurve25519InvalidSize
8279 *
8280 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
8281 */
8282TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
8283 if (!Curve25519Supported()) {
8284 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8285 }
8286
8287 // Generate EC key in KeyMint (only access to public key material)
8288 EcCurve curve = EcCurve::CURVE_25519;
8289 EVP_PKEY_Ptr kmPubKey = nullptr;
8290 GenerateKeyMintEcKey(curve, &kmPubKey);
8291
8292 // Generate EC key on same curve locally (with access to private key material).
8293 EVP_PKEY_Ptr privKey;
8294 vector<uint8_t> encodedPublicKey;
8295 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
8296
8297 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
8298 string ZabFromKeyMintStr;
8299 // Send in an incomplete public key.
8300 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
8301 &ZabFromKeyMintStr));
8302
8303 CheckedDeleteKey();
8304}
8305
8306/*
8307 * KeyAgreementTest.EcdhCurve25519Mismatch
8308 *
8309 * Verifies that ECDH fails between curve25519 and other curves.
8310 */
8311TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
8312 if (!Curve25519Supported()) {
8313 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
8314 }
8315
8316 // Generate EC key in KeyMint (only access to public key material)
8317 EcCurve curve = EcCurve::CURVE_25519;
8318 EVP_PKEY_Ptr kmPubKey = nullptr;
8319 GenerateKeyMintEcKey(curve, &kmPubKey);
8320
8321 for (auto localCurve : ValidCurves()) {
David Drysdaleb97121d2022-08-12 11:54:08 +01008322 SCOPED_TRACE(testing::Message() << "local-curve-" << localCurve);
David Drysdale42fe1892021-10-14 14:43:46 +01008323 if (localCurve == curve) {
8324 continue;
8325 }
8326 // Generate EC key on a different curve locally (with access to private key material).
8327 EVP_PKEY_Ptr privKey;
8328 vector<uint8_t> encodedPublicKey;
8329 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
8330
David Drysdale7fc26b92022-05-13 09:54:24 +01008331 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
David Drysdale42fe1892021-10-14 14:43:46 +01008332 string ZabFromKeyMintStr;
8333 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
8334 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
8335 &ZabFromKeyMintStr));
8336 }
8337
8338 CheckedDeleteKey();
8339}
8340
David Zeuthene0c40892021-01-08 12:54:11 -05008341INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
8342
David Drysdaled2cc8c22021-04-15 13:29:45 +01008343using DestroyAttestationIdsTest = KeyMintAidlTestBase;
8344
8345// This is a problematic test, as it can render the device under test permanently unusable.
8346// Re-enable and run at your own risk.
8347TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
8348 auto result = DestroyAttestationIds();
8349 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
8350}
8351
8352INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
8353
Shawn Willdend659c7c2021-02-19 14:51:51 -07008354using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008355
David Drysdaledb0dcf52021-05-18 11:43:31 +01008356/*
8357 * EarlyBootKeyTest.CreateEarlyBootKeys
8358 *
8359 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
8360 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008361TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01008362 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008363 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8364 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8365
David Drysdaleadfe6112021-05-27 12:00:53 +01008366 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
8367 ASSERT_GT(keyData.blob.size(), 0U);
8368 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8369 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8370 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008371 CheckedDeleteKey(&aesKeyData.blob);
8372 CheckedDeleteKey(&hmacKeyData.blob);
8373 CheckedDeleteKey(&rsaKeyData.blob);
8374 CheckedDeleteKey(&ecdsaKeyData.blob);
8375}
8376
David Drysdaledb0dcf52021-05-18 11:43:31 +01008377/*
David Drysdaleadfe6112021-05-27 12:00:53 +01008378 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
8379 *
8380 * Verifies that creating an early boot key with attestation succeeds.
8381 */
8382TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
8383 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
8384 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
8385 builder->AttestationChallenge("challenge");
8386 builder->AttestationApplicationId("app_id");
8387 });
8388
8389 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00008390 // Strongbox may not support factory attestation. Key creation might fail with
8391 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
8392 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
8393 continue;
8394 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008395 ASSERT_GT(keyData.blob.size(), 0U);
8396 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
8397 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
8398 }
8399 CheckedDeleteKey(&aesKeyData.blob);
8400 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00008401 if (rsaKeyData.blob.size() != 0U) {
8402 CheckedDeleteKey(&rsaKeyData.blob);
8403 }
8404 if (ecdsaKeyData.blob.size() != 0U) {
8405 CheckedDeleteKey(&ecdsaKeyData.blob);
8406 }
David Drysdaleadfe6112021-05-27 12:00:53 +01008407}
8408
8409/*
8410 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01008411 *
8412 * Verifies that using early boot keys at a later stage fails.
8413 */
8414TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
8415 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
8416 .Authorization(TAG_NO_AUTH_REQUIRED)
8417 .Authorization(TAG_EARLY_BOOT_ONLY)
8418 .HmacKey(128)
8419 .Digest(Digest::SHA_2_256)
8420 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
8421 AuthorizationSet output_params;
8422 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
8423 AuthorizationSetBuilder()
8424 .Digest(Digest::SHA_2_256)
8425 .Authorization(TAG_MAC_LENGTH, 256),
8426 &output_params));
8427}
8428
8429/*
8430 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
8431 *
8432 * Verifies that importing early boot keys fails.
8433 */
8434TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
8435 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
8436 .Authorization(TAG_NO_AUTH_REQUIRED)
8437 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01008438 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01008439 .Digest(Digest::SHA_2_256)
8440 .SetDefaultValidity(),
8441 KeyFormat::PKCS8, ec_256_key));
8442}
8443
David Drysdaled2cc8c22021-04-15 13:29:45 +01008444// 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 +00008445// boot stage, which no proper Android device is by the time we can run VTS. To use this,
8446// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
8447// early boot, so you'll have to reboot between runs.
8448TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
8449 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8450 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
8451 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
8452 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8453 EXPECT_TRUE(
8454 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8455 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8456 EXPECT_TRUE(
8457 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
8458
8459 // Should be able to use keys, since early boot has not ended
8460 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8461 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8462 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8463 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8464
8465 // End early boot
8466 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
8467 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
8468
8469 // Should not be able to use already-created keys.
8470 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
8471 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
8472 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
8473 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
8474
8475 CheckedDeleteKey(&aesKeyData.blob);
8476 CheckedDeleteKey(&hmacKeyData.blob);
8477 CheckedDeleteKey(&rsaKeyData.blob);
8478 CheckedDeleteKey(&ecdsaKeyData.blob);
8479
8480 // Should not be able to create new keys
8481 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
8482 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
8483
8484 CheckedDeleteKey(&aesKeyData.blob);
8485 CheckedDeleteKey(&hmacKeyData.blob);
8486 CheckedDeleteKey(&rsaKeyData.blob);
8487 CheckedDeleteKey(&ecdsaKeyData.blob);
8488}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008489
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008490INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
8491
Shawn Willdend659c7c2021-02-19 14:51:51 -07008492using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008493
8494// This may be a problematic test. It can't be run repeatedly without unlocking the device in
8495// between runs... and on most test devices there are no enrolled credentials so it can't be
8496// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
8497// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
8498// a manual test process, which includes unlocking between runs, which is why it's included here.
8499// Well, that and the fact that it's the only test we can do without also making calls into the
8500// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
8501// implications might be, so that may or may not be a solution.
8502TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
8503 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
8504 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
8505
8506 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
8507 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
8508 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
8509 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
8510
8511 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01008512 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008513 ASSERT_EQ(ErrorCode::OK, rc);
8514 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
8515 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
8516 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
8517 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
8518
8519 CheckedDeleteKey(&aesKeyData.blob);
8520 CheckedDeleteKey(&hmacKeyData.blob);
8521 CheckedDeleteKey(&rsaKeyData.blob);
8522 CheckedDeleteKey(&ecdsaKeyData.blob);
8523}
Shawn Willdend659c7c2021-02-19 14:51:51 -07008524
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00008525INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
8526
Shawn Willden22fb9c12022-06-02 14:04:33 -06008527using VsrRequirementTest = KeyMintAidlTestBase;
8528
8529TEST_P(VsrRequirementTest, Vsr13Test) {
8530 int vsr_api_level = get_vsr_api_level();
8531 if (vsr_api_level < 33) {
8532 GTEST_SKIP() << "Applies only to VSR API level 33, this device is: " << vsr_api_level;
8533 }
8534 EXPECT_GE(AidlVersion(), 2) << "VSR 13+ requires KeyMint version 2";
8535}
8536
8537INSTANTIATE_KEYMINT_AIDL_TEST(VsrRequirementTest);
8538
Janis Danisevskis24c04702020-12-16 18:28:39 -08008539} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07008540
8541int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07008542 std::cout << "Testing ";
8543 auto halInstances =
8544 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
8545 std::cout << "HAL instances:\n";
8546 for (auto& entry : halInstances) {
8547 std::cout << " " << entry << '\n';
8548 }
8549
Selene Huang31ab4042020-04-29 04:22:39 -07008550 ::testing::InitGoogleTest(&argc, argv);
8551 for (int i = 1; i < argc; ++i) {
8552 if (argv[i][0] == '-') {
8553 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07008554 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8555 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07008556 }
8557 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07008558 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
8559 dump_Attestations = true;
8560 } else {
8561 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07008562 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00008563 if (std::string(argv[i]) == "--skip_boot_pl_check") {
8564 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
8565 // be run in emulated environments that don't have the normal bootloader
8566 // interactions.
8567 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
8568 }
Selene Huang31ab4042020-04-29 04:22:39 -07008569 }
8570 }
Shawn Willden08a7e432020-12-11 13:05:27 +00008571 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07008572}