blob: c4c7d7312da0db5b28b1bf909d1f49c27e50be6f [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) {
David Drysdale7de9feb2021-03-05 14:56:19 +0000616 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
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) {
625 AuthorizationSet auths = CheckCommonParams(keyCharacteristics);
626 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
632 AuthorizationSet CheckCommonParams(const vector<KeyCharacteristics>& keyCharacteristics) {
633 // TODO(swillden): Distinguish which params should be in which auth list.
634 AuthorizationSet auths;
635 for (auto& entry : keyCharacteristics) {
636 auths.push_back(AuthorizationSet(entry.authorizations));
637 }
638 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
639
640 // Verify that App data, ROT and auth timeout are NOT included.
641 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
642 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
Selene Huang31ab4042020-04-29 04:22:39 -0700643 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
644
David Drysdaled2cc8c22021-04-15 13:29:45 +0100645 // None of the tests specify CREATION_DATETIME so check that the KeyMint implementation
646 // never adds it.
647 EXPECT_FALSE(auths.Contains(TAG_CREATION_DATETIME));
648
David Drysdale7de9feb2021-03-05 14:56:19 +0000649 // Check OS details match the original hardware info.
Shawn Willden7f424372021-01-10 18:06:50 -0700650 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
David Drysdale7de9feb2021-03-05 14:56:19 +0000651 EXPECT_TRUE(os_ver);
Shawn Willden7f424372021-01-10 18:06:50 -0700652 EXPECT_EQ(*os_ver, os_version());
Shawn Willden7f424372021-01-10 18:06:50 -0700653 auto os_pl = auths.GetTagValue(TAG_OS_PATCHLEVEL);
David Drysdale7de9feb2021-03-05 14:56:19 +0000654 EXPECT_TRUE(os_pl);
Shawn Willden7f424372021-01-10 18:06:50 -0700655 EXPECT_EQ(*os_pl, os_patch_level());
David Drysdale7de9feb2021-03-05 14:56:19 +0000656
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000657 // Should include vendor patchlevel.
David Drysdalef5bfa002021-09-27 17:30:41 +0100658 auto vendor_pl = auths.GetTagValue(TAG_VENDOR_PATCHLEVEL);
659 EXPECT_TRUE(vendor_pl);
660 EXPECT_EQ(*vendor_pl, vendor_patch_level());
David Drysdaledbbbe2e2021-12-02 07:44:23 +0000661
662 // Should include boot patchlevel (but there are some test scenarios where this is not
663 // possible).
664 if (check_boot_pl) {
665 auto boot_pl = auths.GetTagValue(TAG_BOOT_PATCHLEVEL);
666 EXPECT_TRUE(boot_pl);
667 }
David Drysdalebb3d85e2021-04-13 11:15:51 +0100668
David Drysdale7de9feb2021-03-05 14:56:19 +0000669 return auths;
Selene Huang31ab4042020-04-29 04:22:39 -0700670 }
671};
672
673/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000674 * NewKeyGenerationTest.Aes
675 *
676 * Verifies that keymint can generate all required AES key sizes, and that the resulting keys
677 * have correct characteristics.
678 */
679TEST_P(NewKeyGenerationTest, Aes) {
680 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
681 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
682 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
683 SCOPED_TRACE(testing::Message()
684 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
685 vector<uint8_t> key_blob;
686 vector<KeyCharacteristics> key_characteristics;
687 auto builder = AuthorizationSetBuilder()
688 .AesEncryptionKey(key_size)
689 .BlockMode(block_mode)
690 .Padding(padding_mode)
691 .SetDefaultValidity();
692 if (block_mode == BlockMode::GCM) {
693 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
694 }
695 ASSERT_EQ(ErrorCode::OK, GenerateKey(builder, &key_blob, &key_characteristics));
696
697 EXPECT_GT(key_blob.size(), 0U);
698 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100699 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000700
701 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
702
703 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::AES));
704 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
705 << "Key size " << key_size << "missing";
706
707 CheckedDeleteKey(&key_blob);
708 }
709 }
710 }
711}
712
713/*
714 * NewKeyGenerationTest.AesInvalidSize
715 *
716 * Verifies that specifying an invalid key size for AES key generation returns
717 * UNSUPPORTED_KEY_SIZE.
718 */
719TEST_P(NewKeyGenerationTest, AesInvalidSize) {
720 for (auto key_size : InvalidKeySizes(Algorithm::AES)) {
721 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
722 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
723 SCOPED_TRACE(testing::Message()
724 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
725 vector<uint8_t> key_blob;
726 vector<KeyCharacteristics> key_characteristics;
727 auto builder = AuthorizationSetBuilder()
728 .AesEncryptionKey(key_size)
729 .BlockMode(block_mode)
730 .Padding(padding_mode)
731 .SetDefaultValidity();
732 if (block_mode == BlockMode::GCM) {
733 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
734 }
735 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
736 GenerateKey(builder, &key_blob, &key_characteristics));
737 }
738 }
739 }
740
741 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
742 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
743 vector<uint8_t> key_blob;
744 vector<KeyCharacteristics> key_characteristics;
745 // No key size specified
746 auto builder = AuthorizationSetBuilder()
747 .Authorization(TAG_ALGORITHM, Algorithm::AES)
748 .BlockMode(block_mode)
749 .Padding(padding_mode)
750 .SetDefaultValidity();
751 if (block_mode == BlockMode::GCM) {
752 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
753 }
754 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
755 GenerateKey(builder, &key_blob, &key_characteristics));
756 }
757 }
758}
759
760/*
761 * NewKeyGenerationTest.AesInvalidPadding
762 *
763 * Verifies that specifying an invalid padding on AES keys gives a failure
764 * somewhere along the way.
765 */
766TEST_P(NewKeyGenerationTest, AesInvalidPadding) {
767 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
768 for (auto block_mode : ValidBlockModes(Algorithm::AES)) {
769 for (auto padding_mode : InvalidPaddingModes(Algorithm::AES, block_mode)) {
770 SCOPED_TRACE(testing::Message()
771 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
David Drysdale7de9feb2021-03-05 14:56:19 +0000772 auto builder = AuthorizationSetBuilder()
Tommy Chiu3950b452021-05-03 22:01:46 +0800773 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale7de9feb2021-03-05 14:56:19 +0000774 .AesEncryptionKey(key_size)
775 .BlockMode(block_mode)
776 .Padding(padding_mode)
777 .SetDefaultValidity();
778 if (block_mode == BlockMode::GCM) {
779 builder.Authorization(TAG_MIN_MAC_LENGTH, 128);
780 }
781
Tommy Chiu3950b452021-05-03 22:01:46 +0800782 auto result = GenerateKey(builder);
David Drysdale7de9feb2021-03-05 14:56:19 +0000783 if (result == ErrorCode::OK) {
784 // Key creation was OK but has generated a key that cannot be used.
785 auto params =
786 AuthorizationSetBuilder().BlockMode(block_mode).Padding(padding_mode);
Tommy Chiu3950b452021-05-03 22:01:46 +0800787 if (block_mode == BlockMode::GCM) {
788 params.Authorization(TAG_MAC_LENGTH, 128);
789 }
David Drysdale7de9feb2021-03-05 14:56:19 +0000790 auto result = Begin(KeyPurpose::ENCRYPT, params);
791 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
David Drysdalec9bc2f72021-05-04 10:47:58 +0100792 result == ErrorCode::INVALID_KEY_BLOB)
793 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +0000794 } else {
795 // The KeyMint implementation detected that the generated key
796 // is unusable.
797 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, result);
798 }
799 }
800 }
801 }
802}
803
804/*
805 * NewKeyGenerationTest.AesGcmMissingMinMac
806 *
807 * Verifies that specifying an invalid key size for AES key generation returns
808 * UNSUPPORTED_KEY_SIZE.
809 */
810TEST_P(NewKeyGenerationTest, AesGcmMissingMinMac) {
811 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
812 BlockMode block_mode = BlockMode::GCM;
813 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
814 SCOPED_TRACE(testing::Message()
815 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
816 vector<uint8_t> key_blob;
817 vector<KeyCharacteristics> key_characteristics;
818 // No MIN_MAC_LENGTH provided.
819 auto builder = AuthorizationSetBuilder()
820 .AesEncryptionKey(key_size)
821 .BlockMode(block_mode)
822 .Padding(padding_mode)
823 .SetDefaultValidity();
824 EXPECT_EQ(ErrorCode::MISSING_MIN_MAC_LENGTH,
825 GenerateKey(builder, &key_blob, &key_characteristics));
826 }
827 }
828}
829
830/*
David Drysdaled2cc8c22021-04-15 13:29:45 +0100831 * NewKeyGenerationTest.AesGcmMinMacOutOfRange
832 *
833 * Verifies that specifying an invalid min MAC size for AES key generation returns
834 * UNSUPPORTED_MIN_MAC_LENGTH.
835 */
836TEST_P(NewKeyGenerationTest, AesGcmMinMacOutOfRange) {
837 for (size_t min_mac_len : {88, 136}) {
838 for (auto key_size : ValidKeySizes(Algorithm::AES)) {
839 BlockMode block_mode = BlockMode::GCM;
840 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
841 SCOPED_TRACE(testing::Message()
842 << "AES-" << key_size << "-" << block_mode << "-" << padding_mode);
843 vector<uint8_t> key_blob;
844 vector<KeyCharacteristics> key_characteristics;
845 auto builder = AuthorizationSetBuilder()
846 .AesEncryptionKey(key_size)
847 .BlockMode(block_mode)
848 .Padding(padding_mode)
849 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_len)
850 .SetDefaultValidity();
851 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
852 GenerateKey(builder, &key_blob, &key_characteristics));
853 }
854 }
855 }
856}
857
858/*
David Drysdale7de9feb2021-03-05 14:56:19 +0000859 * NewKeyGenerationTest.TripleDes
860 *
861 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
862 * have correct characteristics.
863 */
864TEST_P(NewKeyGenerationTest, TripleDes) {
865 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
866 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
867 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
868 SCOPED_TRACE(testing::Message()
869 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
870 vector<uint8_t> key_blob;
871 vector<KeyCharacteristics> key_characteristics;
872 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
873 .TripleDesEncryptionKey(key_size)
874 .BlockMode(block_mode)
875 .Padding(padding_mode)
876 .Authorization(TAG_NO_AUTH_REQUIRED)
877 .SetDefaultValidity(),
878 &key_blob, &key_characteristics));
879
880 EXPECT_GT(key_blob.size(), 0U);
881 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100882 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000883
884 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
885
886 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
887 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
888 << "Key size " << key_size << "missing";
889
890 CheckedDeleteKey(&key_blob);
891 }
892 }
893 }
894}
895
896/*
897 * NewKeyGenerationTest.TripleDesWithAttestation
898 *
899 * Verifies that keymint can generate all required 3DES key sizes, and that the resulting keys
900 * have correct characteristics.
901 *
902 * Request attestation, which doesn't help for symmetric keys (as there is no public key to
903 * put in a certificate) but which isn't an error.
904 */
905TEST_P(NewKeyGenerationTest, TripleDesWithAttestation) {
906 for (auto key_size : ValidKeySizes(Algorithm::TRIPLE_DES)) {
907 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
908 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
909 SCOPED_TRACE(testing::Message()
910 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
911
912 auto challenge = "hello";
913 auto app_id = "foo";
914
915 vector<uint8_t> key_blob;
916 vector<KeyCharacteristics> key_characteristics;
917 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
918 .TripleDesEncryptionKey(key_size)
919 .BlockMode(block_mode)
920 .Padding(padding_mode)
921 .Authorization(TAG_NO_AUTH_REQUIRED)
922 .AttestationChallenge(challenge)
923 .AttestationApplicationId(app_id)
924 .SetDefaultValidity(),
925 &key_blob, &key_characteristics));
926
927 EXPECT_GT(key_blob.size(), 0U);
928 CheckSymmetricParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +0100929 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale7de9feb2021-03-05 14:56:19 +0000930
931 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
932
933 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::TRIPLE_DES));
934 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
935 << "Key size " << key_size << "missing";
936
937 CheckedDeleteKey(&key_blob);
938 }
939 }
940 }
941}
942
943/*
944 * NewKeyGenerationTest.TripleDesInvalidSize
945 *
946 * Verifies that specifying an invalid key size for 3-DES key generation returns
947 * UNSUPPORTED_KEY_SIZE.
948 */
949TEST_P(NewKeyGenerationTest, TripleDesInvalidSize) {
950 for (auto key_size : InvalidKeySizes(Algorithm::TRIPLE_DES)) {
951 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
952 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
953 SCOPED_TRACE(testing::Message()
954 << "3DES-" << key_size << "-" << block_mode << "-" << padding_mode);
955 vector<uint8_t> key_blob;
956 vector<KeyCharacteristics> key_characteristics;
957 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
958 GenerateKey(AuthorizationSetBuilder()
959 .TripleDesEncryptionKey(key_size)
960 .BlockMode(block_mode)
961 .Padding(padding_mode)
962 .Authorization(TAG_NO_AUTH_REQUIRED)
963 .SetDefaultValidity(),
964 &key_blob, &key_characteristics));
965 }
966 }
967 }
968
969 // Omitting the key size fails.
970 for (auto block_mode : ValidBlockModes(Algorithm::TRIPLE_DES)) {
971 for (auto padding_mode : ValidPaddingModes(Algorithm::AES, block_mode)) {
972 SCOPED_TRACE(testing::Message()
973 << "3DES-default-" << block_mode << "-" << padding_mode);
974 vector<uint8_t> key_blob;
975 vector<KeyCharacteristics> key_characteristics;
976 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
977 GenerateKey(AuthorizationSetBuilder()
978 .Authorization(TAG_ALGORITHM, Algorithm::TRIPLE_DES)
979 .BlockMode(block_mode)
980 .Padding(padding_mode)
981 .Authorization(TAG_NO_AUTH_REQUIRED)
982 .SetDefaultValidity(),
983 &key_blob, &key_characteristics));
984 }
985 }
986}
987
988/*
Selene Huang31ab4042020-04-29 04:22:39 -0700989 * NewKeyGenerationTest.Rsa
990 *
991 * Verifies that keymint can generate all required RSA key sizes, and that the resulting keys
992 * have correct characteristics.
993 */
994TEST_P(NewKeyGenerationTest, Rsa) {
995 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
996 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -0700997 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -0700998 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
999 .RsaSigningKey(key_size, 65537)
1000 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001001 .Padding(PaddingMode::NONE)
1002 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001003 &key_blob, &key_characteristics));
1004
1005 ASSERT_GT(key_blob.size(), 0U);
1006 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001007 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001008
Shawn Willden7f424372021-01-10 18:06:50 -07001009 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001010
1011 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1012 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1013 << "Key size " << key_size << "missing";
1014 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1015
1016 CheckedDeleteKey(&key_blob);
1017 }
1018}
1019
1020/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001021 * NewKeyGenerationTest.RsaWithMissingValidity
1022 *
1023 * Verifies that keymint returns an error while generating asymmetric key
1024 * without providing NOT_BEFORE and NOT_AFTER parameters.
1025 */
1026TEST_P(NewKeyGenerationTest, RsaWithMissingValidity) {
1027 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1028 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1029 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1030
1031 vector<uint8_t> key_blob;
1032 vector<KeyCharacteristics> key_characteristics;
1033 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1034 GenerateKey(AuthorizationSetBuilder()
1035 .RsaSigningKey(2048, 65537)
1036 .Digest(Digest::NONE)
1037 .Padding(PaddingMode::NONE)
1038 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1039 kUndefinedExpirationDateTime),
1040 &key_blob, &key_characteristics));
1041
1042 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1043 GenerateKey(AuthorizationSetBuilder()
1044 .RsaSigningKey(2048, 65537)
1045 .Digest(Digest::NONE)
1046 .Padding(PaddingMode::NONE)
1047 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1048 &key_blob, &key_characteristics));
1049}
1050
1051/*
Qi Wud22ec842020-11-26 13:27:53 +08001052 * NewKeyGenerationTest.RsaWithAttestation
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001053 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01001054 * Verifies that keymint can generate all required RSA key sizes with attestation, and that the
1055 * resulting keys have correct characteristics.
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001056 */
1057TEST_P(NewKeyGenerationTest, RsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001058 auto challenge = "hello";
1059 auto app_id = "foo";
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001060
Selene Huang6e46f142021-04-20 19:20:11 -07001061 auto subject = "cert subj 2";
1062 vector<uint8_t> subject_der(make_name_from_str(subject));
1063
1064 uint64_t serial_int = 66;
1065 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1066
Selene Huang4f64c222021-04-13 19:54:36 -07001067 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001068 vector<uint8_t> key_blob;
1069 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001070 auto builder = AuthorizationSetBuilder()
1071 .RsaSigningKey(key_size, 65537)
1072 .Digest(Digest::NONE)
1073 .Padding(PaddingMode::NONE)
1074 .AttestationChallenge(challenge)
1075 .AttestationApplicationId(app_id)
1076 .Authorization(TAG_NO_AUTH_REQUIRED)
1077 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1078 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1079 .SetDefaultValidity();
1080
1081 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001082 // Strongbox may not support factory provisioned attestation key.
1083 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001084 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1085 result = GenerateKeyWithSelfSignedAttestKey(
1086 AuthorizationSetBuilder()
1087 .RsaKey(key_size, 65537)
1088 .AttestKey()
1089 .SetDefaultValidity(), /* attest key params */
1090 builder, &key_blob, &key_characteristics);
1091 }
subrahmanyaman05642492022-02-05 07:10:56 +00001092 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001093 ASSERT_EQ(ErrorCode::OK, result);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001094 ASSERT_GT(key_blob.size(), 0U);
1095 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001096 CheckCharacteristics(key_blob, key_characteristics);
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001097
1098 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1099
1100 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1101 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1102 << "Key size " << key_size << "missing";
1103 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1104
Selene Huang6e46f142021-04-20 19:20:11 -07001105 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Shawn Willden7c130392020-12-21 09:58:22 -07001106 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001107 ASSERT_GT(cert_chain_.size(), 0);
1108
1109 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1110 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001111 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Shawn Willden0e80b5d2020-12-17 09:07:27 -07001112 sw_enforced, hw_enforced, SecLevel(),
1113 cert_chain_[0].encodedCertificate));
1114
1115 CheckedDeleteKey(&key_blob);
1116 }
1117}
1118
1119/*
David Drysdale4dc01072021-04-01 12:17:35 +01001120 * NewKeyGenerationTest.RsaWithRpkAttestation
1121 *
1122 * Verifies that keymint can generate all required RSA key sizes, using an attestation key
1123 * that has been generated using an associate IRemotelyProvisionedComponent.
David Drysdale0fce69d2021-04-13 17:22:13 +01001124 *
1125 * This test is disabled because the KeyMint specification does not require that implementations
1126 * of the first version of KeyMint have to also implement IRemotelyProvisionedComponent.
1127 * However, the test is kept in the code because KeyMint v2 will impose this requirement.
David Drysdale4dc01072021-04-01 12:17:35 +01001128 */
David Drysdale0fce69d2021-04-13 17:22:13 +01001129TEST_P(NewKeyGenerationTest, DISABLED_RsaWithRpkAttestation) {
David Drysdale4dc01072021-04-01 12:17:35 +01001130 // There should be an IRemotelyProvisionedComponent instance associated with the KeyMint
1131 // instance.
1132 std::shared_ptr<IRemotelyProvisionedComponent> rp;
1133 ASSERT_TRUE(matching_rp_instance(GetParam(), &rp))
1134 << "No IRemotelyProvisionedComponent found that matches KeyMint device " << GetParam();
1135
1136 // Generate a P-256 keypair to use as an attestation key.
1137 MacedPublicKey macedPubKey;
1138 std::vector<uint8_t> privateKeyBlob;
1139 auto status =
1140 rp->generateEcdsaP256KeyPair(/* testMode= */ false, &macedPubKey, &privateKeyBlob);
1141 ASSERT_TRUE(status.isOk());
1142 vector<uint8_t> coseKeyData;
1143 check_maced_pubkey(macedPubKey, /* testMode= */ false, &coseKeyData);
1144
1145 AttestationKey attestation_key;
1146 attestation_key.keyBlob = std::move(privateKeyBlob);
1147 attestation_key.issuerSubjectName = make_name_from_str("Android Keystore Key");
1148
1149 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1150 auto challenge = "hello";
1151 auto app_id = "foo";
1152
1153 vector<uint8_t> key_blob;
1154 vector<KeyCharacteristics> key_characteristics;
1155 ASSERT_EQ(ErrorCode::OK,
1156 GenerateKey(AuthorizationSetBuilder()
1157 .RsaSigningKey(key_size, 65537)
1158 .Digest(Digest::NONE)
1159 .Padding(PaddingMode::NONE)
1160 .AttestationChallenge(challenge)
1161 .AttestationApplicationId(app_id)
1162 .Authorization(TAG_NO_AUTH_REQUIRED)
1163 .SetDefaultValidity(),
1164 attestation_key, &key_blob, &key_characteristics, &cert_chain_));
1165
1166 ASSERT_GT(key_blob.size(), 0U);
1167 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001168 CheckCharacteristics(key_blob, key_characteristics);
David Drysdale4dc01072021-04-01 12:17:35 +01001169
1170 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1171
1172 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1173 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1174 << "Key size " << key_size << "missing";
1175 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1176
1177 // Attestation by itself is not valid (last entry is not self-signed).
1178 EXPECT_FALSE(ChainSignaturesAreValid(cert_chain_));
1179
1180 // The signature over the attested key should correspond to the P256 public key.
1181 X509_Ptr key_cert(parse_cert_blob(cert_chain_[0].encodedCertificate));
1182 ASSERT_TRUE(key_cert.get());
1183 EVP_PKEY_Ptr signing_pubkey;
1184 p256_pub_key(coseKeyData, &signing_pubkey);
1185 ASSERT_TRUE(signing_pubkey.get());
1186
1187 ASSERT_TRUE(X509_verify(key_cert.get(), signing_pubkey.get()))
1188 << "Verification of attested certificate failed "
1189 << "OpenSSL error string: " << ERR_error_string(ERR_get_error(), NULL);
1190
1191 CheckedDeleteKey(&key_blob);
1192 }
1193}
1194
1195/*
Selene Huang4f64c222021-04-13 19:54:36 -07001196 * NewKeyGenerationTest.RsaEncryptionWithAttestation
1197 *
1198 * Verifies that keymint attestation for RSA encryption keys with challenge and
1199 * app id is also successful.
1200 */
1201TEST_P(NewKeyGenerationTest, RsaEncryptionWithAttestation) {
1202 auto key_size = 2048;
1203 auto challenge = "hello";
1204 auto app_id = "foo";
1205
Selene Huang6e46f142021-04-20 19:20:11 -07001206 auto subject = "subj 2";
1207 vector<uint8_t> subject_der(make_name_from_str(subject));
1208
1209 uint64_t serial_int = 111166;
1210 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1211
Selene Huang4f64c222021-04-13 19:54:36 -07001212 vector<uint8_t> key_blob;
1213 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001214 auto builder = AuthorizationSetBuilder()
1215 .RsaEncryptionKey(key_size, 65537)
1216 .Padding(PaddingMode::NONE)
1217 .AttestationChallenge(challenge)
1218 .AttestationApplicationId(app_id)
1219 .Authorization(TAG_NO_AUTH_REQUIRED)
1220 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1221 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1222 .SetDefaultValidity();
1223
1224 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001225 // Strongbox may not support factory provisioned attestation key.
1226 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001227 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1228 result = GenerateKeyWithSelfSignedAttestKey(
1229 AuthorizationSetBuilder()
1230 .RsaKey(key_size, 65537)
1231 .AttestKey()
1232 .SetDefaultValidity(), /* attest key params */
1233 builder, &key_blob, &key_characteristics);
1234 }
subrahmanyaman05642492022-02-05 07:10:56 +00001235 }
1236 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001237
1238 ASSERT_GT(key_blob.size(), 0U);
1239 AuthorizationSet auths;
1240 for (auto& entry : key_characteristics) {
1241 auths.push_back(AuthorizationSet(entry.authorizations));
1242 }
1243
1244 EXPECT_TRUE(auths.Contains(TAG_ORIGIN, KeyOrigin::GENERATED));
1245 EXPECT_TRUE(auths.Contains(TAG_PURPOSE, KeyPurpose::DECRYPT));
1246
1247 // Verify that App data and ROT are NOT included.
1248 EXPECT_FALSE(auths.Contains(TAG_ROOT_OF_TRUST));
1249 EXPECT_FALSE(auths.Contains(TAG_APPLICATION_DATA));
1250
1251 // Check that some unexpected tags/values are NOT present.
1252 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::SIGN));
1253 EXPECT_FALSE(auths.Contains(TAG_PURPOSE, KeyPurpose::VERIFY));
1254
1255 EXPECT_FALSE(auths.Contains(TAG_AUTH_TIMEOUT, 301U));
1256
1257 auto os_ver = auths.GetTagValue(TAG_OS_VERSION);
1258 ASSERT_TRUE(os_ver);
1259 EXPECT_EQ(*os_ver, os_version());
1260
1261 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1262
1263 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1264 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1265 << "Key size " << key_size << "missing";
1266 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1267
Selene Huang6e46f142021-04-20 19:20:11 -07001268 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001269 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1270 ASSERT_GT(cert_chain_.size(), 0);
1271
1272 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1273 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001274 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001275 sw_enforced, hw_enforced, SecLevel(),
1276 cert_chain_[0].encodedCertificate));
1277
1278 CheckedDeleteKey(&key_blob);
1279}
1280
1281/*
1282 * NewKeyGenerationTest.RsaWithSelfSign
1283 *
1284 * Verifies that attesting to RSA key generation is successful, and returns
1285 * self signed certificate if no challenge is provided. And signing etc
1286 * works as expected.
1287 */
1288TEST_P(NewKeyGenerationTest, RsaWithSelfSign) {
Selene Huang6e46f142021-04-20 19:20:11 -07001289 auto subject = "cert subj subj subj subj subj subj 22222222222222222222";
1290 vector<uint8_t> subject_der(make_name_from_str(subject));
1291
1292 uint64_t serial_int = 0;
1293 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1294
Selene Huang4f64c222021-04-13 19:54:36 -07001295 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1296 vector<uint8_t> key_blob;
1297 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001298 ASSERT_EQ(ErrorCode::OK,
1299 GenerateKey(AuthorizationSetBuilder()
1300 .RsaSigningKey(key_size, 65537)
1301 .Digest(Digest::NONE)
1302 .Padding(PaddingMode::NONE)
1303 .Authorization(TAG_NO_AUTH_REQUIRED)
1304 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1305 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1306 .SetDefaultValidity(),
1307 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001308
1309 ASSERT_GT(key_blob.size(), 0U);
1310 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001311 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001312
1313 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1314
1315 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1316 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1317 << "Key size " << key_size << "missing";
1318 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1319
Selene Huang6e46f142021-04-20 19:20:11 -07001320 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001321 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1322 ASSERT_EQ(cert_chain_.size(), 1);
1323
1324 CheckedDeleteKey(&key_blob);
1325 }
1326}
1327
1328/*
1329 * NewKeyGenerationTest.RsaWithAttestationMissAppId
1330 *
1331 * Verifies that attesting to RSA checks for missing app ID.
1332 */
1333TEST_P(NewKeyGenerationTest, RsaWithAttestationMissAppId) {
1334 auto challenge = "hello";
1335 vector<uint8_t> key_blob;
1336 vector<KeyCharacteristics> key_characteristics;
1337
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001338 auto builder = AuthorizationSetBuilder()
1339 .RsaSigningKey(2048, 65537)
1340 .Digest(Digest::NONE)
1341 .Padding(PaddingMode::NONE)
1342 .AttestationChallenge(challenge)
1343 .Authorization(TAG_NO_AUTH_REQUIRED)
1344 .SetDefaultValidity();
1345
1346 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001347 // Strongbox may not support factory provisioned attestation key.
1348 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001349 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1350 result = GenerateKeyWithSelfSignedAttestKey(
1351 AuthorizationSetBuilder()
1352 .RsaKey(2048, 65537)
1353 .AttestKey()
1354 .SetDefaultValidity(), /* attest key params */
1355 builder, &key_blob, &key_characteristics);
1356 }
subrahmanyaman05642492022-02-05 07:10:56 +00001357 }
1358 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001359}
1360
1361/*
1362 * NewKeyGenerationTest.RsaWithAttestationAppIdIgnored
1363 *
1364 * Verifies that attesting to RSA ignores app id if challenge is missing.
1365 */
1366TEST_P(NewKeyGenerationTest, RsaWithAttestationAppIdIgnored) {
1367 auto key_size = 2048;
1368 auto app_id = "foo";
1369
Selene Huang6e46f142021-04-20 19:20:11 -07001370 auto subject = "cert subj 2";
1371 vector<uint8_t> subject_der(make_name_from_str(subject));
1372
1373 uint64_t serial_int = 1;
1374 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1375
Selene Huang4f64c222021-04-13 19:54:36 -07001376 vector<uint8_t> key_blob;
1377 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07001378 ASSERT_EQ(ErrorCode::OK,
1379 GenerateKey(AuthorizationSetBuilder()
1380 .RsaSigningKey(key_size, 65537)
1381 .Digest(Digest::NONE)
1382 .Padding(PaddingMode::NONE)
1383 .AttestationApplicationId(app_id)
1384 .Authorization(TAG_NO_AUTH_REQUIRED)
1385 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1386 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1387 .SetDefaultValidity(),
1388 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07001389
1390 ASSERT_GT(key_blob.size(), 0U);
1391 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001392 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001393
1394 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1395
1396 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1397 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1398 << "Key size " << key_size << "missing";
1399 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1400
Selene Huang6e46f142021-04-20 19:20:11 -07001401 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001402 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1403 ASSERT_EQ(cert_chain_.size(), 1);
1404
1405 CheckedDeleteKey(&key_blob);
1406}
1407
1408/*
Qi Wud22ec842020-11-26 13:27:53 +08001409 * NewKeyGenerationTest.LimitedUsageRsa
1410 *
1411 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1412 * resulting keys have correct characteristics.
1413 */
1414TEST_P(NewKeyGenerationTest, LimitedUsageRsa) {
1415 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1416 vector<uint8_t> key_blob;
1417 vector<KeyCharacteristics> key_characteristics;
1418 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
1419 .RsaSigningKey(key_size, 65537)
1420 .Digest(Digest::NONE)
1421 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001422 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1423 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08001424 &key_blob, &key_characteristics));
1425
1426 ASSERT_GT(key_blob.size(), 0U);
1427 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001428 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08001429
1430 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1431
1432 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1433 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1434 << "Key size " << key_size << "missing";
1435 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1436
1437 // Check the usage count limit tag appears in the authorizations.
1438 AuthorizationSet auths;
1439 for (auto& entry : key_characteristics) {
1440 auths.push_back(AuthorizationSet(entry.authorizations));
1441 }
1442 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1443 << "key usage count limit " << 1U << " missing";
1444
1445 CheckedDeleteKey(&key_blob);
1446 }
1447}
1448
1449/*
Qi Wubeefae42021-01-28 23:16:37 +08001450 * NewKeyGenerationTest.LimitedUsageRsaWithAttestation
1451 *
1452 * Verifies that KeyMint can generate all required RSA key sizes with limited usage, and that the
1453 * resulting keys have correct characteristics and attestation.
1454 */
1455TEST_P(NewKeyGenerationTest, LimitedUsageRsaWithAttestation) {
Selene Huang4f64c222021-04-13 19:54:36 -07001456 auto challenge = "hello";
1457 auto app_id = "foo";
Qi Wubeefae42021-01-28 23:16:37 +08001458
Selene Huang6e46f142021-04-20 19:20:11 -07001459 auto subject = "cert subj 2";
1460 vector<uint8_t> subject_der(make_name_from_str(subject));
1461
1462 uint64_t serial_int = 66;
1463 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1464
Selene Huang4f64c222021-04-13 19:54:36 -07001465 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
Qi Wubeefae42021-01-28 23:16:37 +08001466 vector<uint8_t> key_blob;
1467 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001468 auto builder = AuthorizationSetBuilder()
1469 .RsaSigningKey(key_size, 65537)
1470 .Digest(Digest::NONE)
1471 .Padding(PaddingMode::NONE)
1472 .AttestationChallenge(challenge)
1473 .AttestationApplicationId(app_id)
1474 .Authorization(TAG_NO_AUTH_REQUIRED)
1475 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
1476 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1477 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1478 .SetDefaultValidity();
1479
1480 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001481 // Strongbox may not support factory provisioned attestation key.
1482 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001483 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1484 result = GenerateKeyWithSelfSignedAttestKey(
1485 AuthorizationSetBuilder()
1486 .RsaKey(key_size, 65537)
1487 .AttestKey()
1488 .SetDefaultValidity(), /* attest key params */
1489 builder, &key_blob, &key_characteristics);
1490 }
subrahmanyaman05642492022-02-05 07:10:56 +00001491 }
1492 ASSERT_EQ(ErrorCode::OK, result);
Qi Wubeefae42021-01-28 23:16:37 +08001493
1494 ASSERT_GT(key_blob.size(), 0U);
1495 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001496 CheckCharacteristics(key_blob, key_characteristics);
Qi Wubeefae42021-01-28 23:16:37 +08001497
1498 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1499
1500 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::RSA));
1501 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
1502 << "Key size " << key_size << "missing";
1503 EXPECT_TRUE(crypto_params.Contains(TAG_RSA_PUBLIC_EXPONENT, 65537U));
1504
1505 // Check the usage count limit tag appears in the authorizations.
1506 AuthorizationSet auths;
1507 for (auto& entry : key_characteristics) {
1508 auths.push_back(AuthorizationSet(entry.authorizations));
1509 }
1510 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
1511 << "key usage count limit " << 1U << " missing";
1512
1513 // Check the usage count limit tag also appears in the attestation.
Shawn Willden7c130392020-12-21 09:58:22 -07001514 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Qi Wubeefae42021-01-28 23:16:37 +08001515 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001516 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Qi Wubeefae42021-01-28 23:16:37 +08001517
1518 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1519 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001520 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Qi Wubeefae42021-01-28 23:16:37 +08001521 sw_enforced, hw_enforced, SecLevel(),
1522 cert_chain_[0].encodedCertificate));
1523
1524 CheckedDeleteKey(&key_blob);
1525 }
1526}
1527
1528/*
Selene Huang31ab4042020-04-29 04:22:39 -07001529 * NewKeyGenerationTest.NoInvalidRsaSizes
1530 *
1531 * Verifies that keymint cannot generate any RSA key sizes that are designated as invalid.
1532 */
1533TEST_P(NewKeyGenerationTest, NoInvalidRsaSizes) {
1534 for (auto key_size : InvalidKeySizes(Algorithm::RSA)) {
1535 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001536 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07001537 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1538 GenerateKey(AuthorizationSetBuilder()
1539 .RsaSigningKey(key_size, 65537)
1540 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001541 .Padding(PaddingMode::NONE)
1542 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07001543 &key_blob, &key_characteristics));
1544 }
1545}
1546
1547/*
1548 * NewKeyGenerationTest.RsaNoDefaultSize
1549 *
1550 * Verifies that failing to specify a key size for RSA key generation returns
1551 * UNSUPPORTED_KEY_SIZE.
1552 */
1553TEST_P(NewKeyGenerationTest, RsaNoDefaultSize) {
1554 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
1555 GenerateKey(AuthorizationSetBuilder()
1556 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
1557 .Authorization(TAG_RSA_PUBLIC_EXPONENT, 3U)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001558 .SigningKey()
1559 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07001560}
1561
1562/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01001563 * NewKeyGenerationTest.RsaMissingParams
1564 *
1565 * Verifies that omitting optional tags works.
1566 */
1567TEST_P(NewKeyGenerationTest, RsaMissingParams) {
1568 for (auto key_size : ValidKeySizes(Algorithm::RSA)) {
1569 ASSERT_EQ(ErrorCode::OK,
1570 GenerateKey(
1571 AuthorizationSetBuilder().RsaKey(key_size, 65537).SetDefaultValidity()));
1572 CheckedDeleteKey();
1573 }
1574}
1575
1576/*
Selene Huang31ab4042020-04-29 04:22:39 -07001577 * NewKeyGenerationTest.Ecdsa
1578 *
David Drysdale42fe1892021-10-14 14:43:46 +01001579 * Verifies that keymint can generate all required EC curves, and that the resulting keys
Selene Huang31ab4042020-04-29 04:22:39 -07001580 * have correct characteristics.
1581 */
1582TEST_P(NewKeyGenerationTest, Ecdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01001583 for (auto curve : ValidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07001584 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07001585 vector<KeyCharacteristics> key_characteristics;
Janis Danisevskis164bb872021-02-09 11:30:25 -08001586 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01001587 .EcdsaSigningKey(curve)
Janis Danisevskis164bb872021-02-09 11:30:25 -08001588 .Digest(Digest::NONE)
1589 .SetDefaultValidity(),
1590 &key_blob, &key_characteristics));
Selene Huang31ab4042020-04-29 04:22:39 -07001591 ASSERT_GT(key_blob.size(), 0U);
1592 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001593 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001594
Shawn Willden7f424372021-01-10 18:06:50 -07001595 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07001596
1597 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001598 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07001599
1600 CheckedDeleteKey(&key_blob);
1601 }
1602}
1603
1604/*
David Drysdale42fe1892021-10-14 14:43:46 +01001605 * NewKeyGenerationTest.EcdsaCurve25519
1606 *
1607 * Verifies that keymint can generate a curve25519 key, and that the resulting key
1608 * has correct characteristics.
1609 */
1610TEST_P(NewKeyGenerationTest, EcdsaCurve25519) {
1611 if (!Curve25519Supported()) {
1612 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1613 }
1614
1615 EcCurve curve = EcCurve::CURVE_25519;
1616 vector<uint8_t> key_blob;
1617 vector<KeyCharacteristics> key_characteristics;
1618 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1619 .EcdsaSigningKey(curve)
1620 .Digest(Digest::NONE)
1621 .SetDefaultValidity(),
1622 &key_blob, &key_characteristics);
1623 ASSERT_EQ(result, ErrorCode::OK);
1624 ASSERT_GT(key_blob.size(), 0U);
1625
1626 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1627 ASSERT_GT(cert_chain_.size(), 0);
1628
1629 CheckBaseParams(key_characteristics);
1630 CheckCharacteristics(key_blob, key_characteristics);
1631
1632 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1633
1634 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1635 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1636
1637 CheckedDeleteKey(&key_blob);
1638}
1639
1640/*
1641 * NewKeyGenerationTest.EcCurve25519MultiPurposeFail
1642 *
1643 * Verifies that KeyMint rejects an attempt to generate a curve 25519 key for both
1644 * SIGN and AGREE_KEY.
1645 */
1646TEST_P(NewKeyGenerationTest, EcdsaCurve25519MultiPurposeFail) {
1647 if (!Curve25519Supported()) {
1648 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1649 }
1650
1651 EcCurve curve = EcCurve::CURVE_25519;
1652 vector<uint8_t> key_blob;
1653 vector<KeyCharacteristics> key_characteristics;
1654 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1655 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
1656 .EcdsaSigningKey(curve)
1657 .Digest(Digest::NONE)
1658 .SetDefaultValidity(),
1659 &key_blob, &key_characteristics);
1660 ASSERT_EQ(result, ErrorCode::INCOMPATIBLE_PURPOSE);
1661}
1662
1663/*
Prashant Patil6c1adf02021-11-22 06:21:21 +00001664 * NewKeyGenerationTest.EcdsaWithMissingValidity
1665 *
1666 * Verifies that keymint returns an error while generating asymmetric key
1667 * without providing NOT_BEFORE and NOT_AFTER parameters.
1668 */
1669TEST_P(NewKeyGenerationTest, EcdsaWithMissingValidity) {
1670 // Per RFC 5280 4.1.2.5, an undefined expiration (not-after) field should be set to
1671 // GeneralizedTime 999912312359559, which is 253402300799000 ms from Jan 1, 1970.
1672 constexpr uint64_t kUndefinedExpirationDateTime = 253402300799000;
1673
1674 vector<uint8_t> key_blob;
1675 vector<KeyCharacteristics> key_characteristics;
1676 ASSERT_EQ(ErrorCode::MISSING_NOT_BEFORE,
1677 GenerateKey(AuthorizationSetBuilder()
1678 .EcdsaSigningKey(EcCurve::P_256)
1679 .Digest(Digest::NONE)
1680 .Authorization(TAG_CERTIFICATE_NOT_AFTER,
1681 kUndefinedExpirationDateTime),
1682 &key_blob, &key_characteristics));
1683
1684 ASSERT_EQ(ErrorCode::MISSING_NOT_AFTER,
1685 GenerateKey(AuthorizationSetBuilder()
1686 .EcdsaSigningKey(EcCurve::P_256)
1687 .Digest(Digest::NONE)
1688 .Authorization(TAG_CERTIFICATE_NOT_BEFORE, 0),
1689 &key_blob, &key_characteristics));
1690}
1691
1692/*
Selene Huang4f64c222021-04-13 19:54:36 -07001693 * NewKeyGenerationTest.EcdsaAttestation
1694 *
1695 * Verifies that for all Ecdsa key sizes, if challenge and app id is provided,
1696 * an attestation will be generated.
1697 */
1698TEST_P(NewKeyGenerationTest, EcdsaAttestation) {
1699 auto challenge = "hello";
1700 auto app_id = "foo";
1701
Selene Huang6e46f142021-04-20 19:20:11 -07001702 auto subject = "cert subj 2";
1703 vector<uint8_t> subject_der(make_name_from_str(subject));
1704
1705 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1706 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1707
David Drysdaledf09e542021-06-08 15:46:11 +01001708 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07001709 vector<uint8_t> key_blob;
1710 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001711 auto builder = AuthorizationSetBuilder()
1712 .Authorization(TAG_NO_AUTH_REQUIRED)
1713 .EcdsaSigningKey(curve)
1714 .Digest(Digest::NONE)
1715 .AttestationChallenge(challenge)
1716 .AttestationApplicationId(app_id)
1717 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1718 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1719 .SetDefaultValidity();
1720
1721 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001722 // Strongbox may not support factory provisioned attestation key.
1723 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001724 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1725 result = GenerateKeyWithSelfSignedAttestKey(
1726 AuthorizationSetBuilder()
1727 .EcdsaKey(curve)
1728 .AttestKey()
1729 .SetDefaultValidity(), /* attest key params */
1730 builder, &key_blob, &key_characteristics);
1731 }
subrahmanyaman05642492022-02-05 07:10:56 +00001732 }
1733 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07001734 ASSERT_GT(key_blob.size(), 0U);
1735 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01001736 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07001737
1738 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1739
1740 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01001741 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07001742
1743 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1744 ASSERT_GT(cert_chain_.size(), 0);
Selene Huang6e46f142021-04-20 19:20:11 -07001745 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07001746
1747 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1748 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00001749 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07001750 sw_enforced, hw_enforced, SecLevel(),
1751 cert_chain_[0].encodedCertificate));
1752
1753 CheckedDeleteKey(&key_blob);
1754 }
1755}
1756
1757/*
David Drysdale42fe1892021-10-14 14:43:46 +01001758 * NewKeyGenerationTest.EcdsaAttestationCurve25519
1759 *
1760 * Verifies that for a curve 25519 key, if challenge and app id is provided,
1761 * an attestation will be generated.
1762 */
1763TEST_P(NewKeyGenerationTest, EcdsaAttestationCurve25519) {
1764 if (!Curve25519Supported()) {
1765 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
1766 }
1767
1768 EcCurve curve = EcCurve::CURVE_25519;
1769 auto challenge = "hello";
1770 auto app_id = "foo";
1771
1772 auto subject = "cert subj 2";
1773 vector<uint8_t> subject_der(make_name_from_str(subject));
1774
1775 uint64_t serial_int = 0xFFFFFFFFFFFFFFFF;
1776 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1777
1778 vector<uint8_t> key_blob;
1779 vector<KeyCharacteristics> key_characteristics;
1780 ErrorCode result = GenerateKey(AuthorizationSetBuilder()
1781 .Authorization(TAG_NO_AUTH_REQUIRED)
1782 .EcdsaSigningKey(curve)
1783 .Digest(Digest::NONE)
1784 .AttestationChallenge(challenge)
1785 .AttestationApplicationId(app_id)
1786 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1787 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1788 .SetDefaultValidity(),
1789 &key_blob, &key_characteristics);
1790 ASSERT_EQ(ErrorCode::OK, result);
1791 ASSERT_GT(key_blob.size(), 0U);
1792 CheckBaseParams(key_characteristics);
1793 CheckCharacteristics(key_blob, key_characteristics);
1794
1795 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
1796
1797 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
1798 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
1799
1800 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1801 ASSERT_GT(cert_chain_.size(), 0);
1802 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
1803
1804 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1805 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
1806 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
1807 sw_enforced, hw_enforced, SecLevel(),
1808 cert_chain_[0].encodedCertificate));
1809
1810 CheckedDeleteKey(&key_blob);
1811}
1812
1813/*
David Drysdale37af4b32021-05-14 16:46:59 +01001814 * NewKeyGenerationTest.EcdsaAttestationTags
1815 *
1816 * Verifies that creation of an attested ECDSA key includes various tags in the
1817 * attestation extension.
1818 */
1819TEST_P(NewKeyGenerationTest, EcdsaAttestationTags) {
1820 auto challenge = "hello";
1821 auto app_id = "foo";
1822 auto subject = "cert subj 2";
1823 vector<uint8_t> subject_der(make_name_from_str(subject));
1824 uint64_t serial_int = 0x1010;
1825 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1826 const AuthorizationSetBuilder base_builder =
1827 AuthorizationSetBuilder()
1828 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001829 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001830 .Digest(Digest::NONE)
1831 .AttestationChallenge(challenge)
1832 .AttestationApplicationId(app_id)
1833 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1834 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1835 .SetDefaultValidity();
1836
1837 // Various tags that map to fields in the attestation extension ASN.1 schema.
1838 auto extra_tags = AuthorizationSetBuilder()
1839 .Authorization(TAG_ROLLBACK_RESISTANCE)
1840 .Authorization(TAG_EARLY_BOOT_ONLY)
1841 .Authorization(TAG_ACTIVE_DATETIME, 1619621648000)
1842 .Authorization(TAG_ORIGINATION_EXPIRE_DATETIME, 1619621648000)
1843 .Authorization(TAG_USAGE_EXPIRE_DATETIME, 1619621999000)
1844 .Authorization(TAG_USAGE_COUNT_LIMIT, 42)
1845 .Authorization(TAG_AUTH_TIMEOUT, 100000)
1846 .Authorization(TAG_ALLOW_WHILE_ON_BODY)
1847 .Authorization(TAG_TRUSTED_USER_PRESENCE_REQUIRED)
1848 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
1849 .Authorization(TAG_UNLOCKED_DEVICE_REQUIRED)
1850 .Authorization(TAG_CREATION_DATETIME, 1619621648000);
David Drysdalec53b7d92021-10-11 12:35:58 +01001851
David Drysdale37af4b32021-05-14 16:46:59 +01001852 for (const KeyParameter& tag : extra_tags) {
1853 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1854 vector<uint8_t> key_blob;
1855 vector<KeyCharacteristics> key_characteristics;
1856 AuthorizationSetBuilder builder = base_builder;
1857 builder.push_back(tag);
1858 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
1859 if (result == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE &&
1860 tag.tag == TAG_ROLLBACK_RESISTANCE) {
1861 continue;
1862 }
Seth Mooreb393b082021-07-12 14:18:28 -07001863 if (result == ErrorCode::UNSUPPORTED_TAG && tag.tag == TAG_TRUSTED_USER_PRESENCE_REQUIRED) {
1864 // Tag not required to be supported by all KeyMint implementations.
David Drysdale37af4b32021-05-14 16:46:59 +01001865 continue;
1866 }
subrahmanyaman05642492022-02-05 07:10:56 +00001867 // Strongbox may not support factory provisioned attestation key.
1868 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001869 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1870 result = GenerateKeyWithSelfSignedAttestKey(
1871 AuthorizationSetBuilder()
1872 .EcdsaKey(EcCurve::P_256)
1873 .AttestKey()
1874 .SetDefaultValidity(), /* attest key params */
1875 builder, &key_blob, &key_characteristics);
1876 }
subrahmanyaman05642492022-02-05 07:10:56 +00001877 }
David Drysdale37af4b32021-05-14 16:46:59 +01001878 ASSERT_EQ(result, ErrorCode::OK);
1879 ASSERT_GT(key_blob.size(), 0U);
1880
1881 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1882 ASSERT_GT(cert_chain_.size(), 0);
1883 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1884
1885 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
1886 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
Seth Mooreb393b082021-07-12 14:18:28 -07001887 // Some tags are optional, so don't require them to be in the enforcements.
1888 if (tag.tag != TAG_ATTESTATION_APPLICATION_ID && tag.tag != TAG_ALLOW_WHILE_ON_BODY) {
David Drysdale37af4b32021-05-14 16:46:59 +01001889 EXPECT_TRUE(hw_enforced.Contains(tag.tag) || sw_enforced.Contains(tag.tag))
1890 << tag << " not in hw:" << hw_enforced << " nor sw:" << sw_enforced;
1891 }
1892
1893 // Verifying the attestation record will check for the specific tag because
1894 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00001895 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
1896 hw_enforced, SecLevel(),
1897 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01001898
1899 CheckedDeleteKey(&key_blob);
1900 }
1901
David Drysdalec53b7d92021-10-11 12:35:58 +01001902 // Collection of invalid attestation ID tags.
1903 auto invalid_tags =
1904 AuthorizationSetBuilder()
1905 .Authorization(TAG_ATTESTATION_ID_BRAND, "bogus-brand")
1906 .Authorization(TAG_ATTESTATION_ID_DEVICE, "devious-device")
1907 .Authorization(TAG_ATTESTATION_ID_PRODUCT, "punctured-product")
1908 .Authorization(TAG_ATTESTATION_ID_SERIAL, "suspicious-serial")
1909 .Authorization(TAG_ATTESTATION_ID_IMEI, "invalid-imei")
1910 .Authorization(TAG_ATTESTATION_ID_MEID, "mismatching-meid")
1911 .Authorization(TAG_ATTESTATION_ID_MANUFACTURER, "malformed-manufacturer")
1912 .Authorization(TAG_ATTESTATION_ID_MODEL, "malicious-model");
David Drysdale37af4b32021-05-14 16:46:59 +01001913 for (const KeyParameter& tag : invalid_tags) {
David Drysdalec53b7d92021-10-11 12:35:58 +01001914 SCOPED_TRACE(testing::Message() << "-incorrect-tag-" << tag);
David Drysdale37af4b32021-05-14 16:46:59 +01001915 vector<uint8_t> key_blob;
1916 vector<KeyCharacteristics> key_characteristics;
1917 AuthorizationSetBuilder builder =
1918 AuthorizationSetBuilder()
1919 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01001920 .EcdsaSigningKey(EcCurve::P_256)
David Drysdale37af4b32021-05-14 16:46:59 +01001921 .Digest(Digest::NONE)
1922 .AttestationChallenge(challenge)
1923 .AttestationApplicationId(app_id)
1924 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1925 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1926 .SetDefaultValidity();
1927 builder.push_back(tag);
subrahmanyaman7d9bc462022-03-16 01:40:39 +00001928
1929 auto error = GenerateKey(builder, &key_blob, &key_characteristics);
1930 // Strongbox may not support factory provisioned attestation key.
1931 if (SecLevel() == SecurityLevel::STRONGBOX) {
1932 if (error == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
1933 error = GenerateKeyWithSelfSignedAttestKey(
1934 AuthorizationSetBuilder()
1935 .EcdsaKey(EcCurve::P_256)
1936 .AttestKey()
1937 .SetDefaultValidity(), /* attest key params */
1938 builder, &key_blob, &key_characteristics);
1939 }
1940 }
1941 ASSERT_EQ(error, ErrorCode::CANNOT_ATTEST_IDS);
David Drysdale37af4b32021-05-14 16:46:59 +01001942 }
1943}
1944
1945/*
David Drysdalec53b7d92021-10-11 12:35:58 +01001946 * NewKeyGenerationTest.EcdsaAttestationIdTags
1947 *
1948 * Verifies that creation of an attested ECDSA key includes various ID tags in the
1949 * attestation extension.
1950 */
1951TEST_P(NewKeyGenerationTest, EcdsaAttestationIdTags) {
David Drysdale555ba002022-05-03 18:48:57 +01001952 if (is_gsi_image()) {
1953 // GSI sets up a standard set of device identifiers that may not match
1954 // the device identifiers held by the device.
1955 GTEST_SKIP() << "Test not applicable under GSI";
1956 }
David Drysdalec53b7d92021-10-11 12:35:58 +01001957 auto challenge = "hello";
1958 auto app_id = "foo";
1959 auto subject = "cert subj 2";
1960 vector<uint8_t> subject_der(make_name_from_str(subject));
1961 uint64_t serial_int = 0x1010;
1962 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1963 const AuthorizationSetBuilder base_builder =
1964 AuthorizationSetBuilder()
1965 .Authorization(TAG_NO_AUTH_REQUIRED)
1966 .EcdsaSigningKey(EcCurve::P_256)
1967 .Digest(Digest::NONE)
1968 .AttestationChallenge(challenge)
1969 .AttestationApplicationId(app_id)
1970 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1971 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1972 .SetDefaultValidity();
1973
1974 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1975 auto extra_tags = AuthorizationSetBuilder();
1976 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1977 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1978 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1979 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1980 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1981 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1982
1983 for (const KeyParameter& tag : extra_tags) {
1984 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1985 vector<uint8_t> key_blob;
1986 vector<KeyCharacteristics> key_characteristics;
1987 AuthorizationSetBuilder builder = base_builder;
1988 builder.push_back(tag);
1989 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001990 // Strongbox may not support factory provisioned attestation key.
1991 if (SecLevel() == SecurityLevel::STRONGBOX) {
1992 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1993 }
Prashant Patil88ad1892022-03-15 16:31:02 +00001994 if (result == ErrorCode::CANNOT_ATTEST_IDS && !isDeviceIdAttestationRequired()) {
1995 // ID attestation was optional till api level 32, from api level 33 it is mandatory.
David Drysdalec53b7d92021-10-11 12:35:58 +01001996 continue;
1997 }
1998 ASSERT_EQ(result, ErrorCode::OK);
1999 ASSERT_GT(key_blob.size(), 0U);
2000
2001 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2002 ASSERT_GT(cert_chain_.size(), 0);
2003 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2004
2005 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2006 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2007
2008 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2009 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2010 // attestation extension should contain them, so make sure the extra tag is added.
2011 hw_enforced.push_back(tag);
2012
2013 // Verifying the attestation record will check for the specific tag because
2014 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002015 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2016 hw_enforced, SecLevel(),
2017 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002018
2019 CheckedDeleteKey(&key_blob);
2020 }
2021}
2022
2023/*
David Drysdale565ccc72021-10-11 12:49:50 +01002024 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2025 *
2026 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2027 */
2028TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2029 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002030 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002031 auto challenge = "hello";
2032 auto subject = "cert subj 2";
2033 vector<uint8_t> subject_der(make_name_from_str(subject));
2034 uint64_t serial_int = 0x1010;
2035 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002036 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002037 AuthorizationSetBuilder()
2038 .Authorization(TAG_NO_AUTH_REQUIRED)
2039 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2040 .EcdsaSigningKey(EcCurve::P_256)
2041 .Digest(Digest::NONE)
2042 .AttestationChallenge(challenge)
2043 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2044 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2045 .AttestationApplicationId(app_id)
2046 .Authorization(TAG_CREATION_DATETIME, datetime)
2047 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002048 if (reset) {
2049 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2050 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002051 auto result = GenerateKey(builder);
2052 if (SecLevel() == SecurityLevel::STRONGBOX) {
2053 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2054 result = GenerateKeyWithSelfSignedAttestKey(
2055 AuthorizationSetBuilder()
2056 .EcdsaKey(EcCurve::P_256)
2057 .AttestKey()
2058 .SetDefaultValidity(), /* attest key params */
2059 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2060 }
2061 }
2062 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002063 ASSERT_GT(key_blob_.size(), 0U);
2064
2065 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2066 ASSERT_GT(cert_chain_.size(), 0);
2067 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2068
2069 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2070 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2071
2072 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002073 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2074 hw_enforced, SecLevel(),
2075 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002076 EXPECT_GT(unique_id->size(), 0);
2077 CheckedDeleteKey();
2078 };
2079
2080 // Generate unique ID
2081 auto app_id = "foo";
2082 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2083 vector<uint8_t> unique_id;
2084 get_unique_id(app_id, cert_date, &unique_id);
2085
2086 // Generating a new key with the same parameters should give the same unique ID.
2087 vector<uint8_t> unique_id2;
2088 get_unique_id(app_id, cert_date, &unique_id2);
2089 EXPECT_EQ(unique_id, unique_id2);
2090
2091 // Generating a new key with a slightly different date should give the same unique ID.
2092 uint64_t rounded_date = cert_date / 2592000000LLU;
2093 uint64_t min_date = rounded_date * 2592000000LLU;
2094 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2095
2096 vector<uint8_t> unique_id3;
2097 get_unique_id(app_id, min_date, &unique_id3);
2098 EXPECT_EQ(unique_id, unique_id3);
2099
2100 vector<uint8_t> unique_id4;
2101 get_unique_id(app_id, max_date, &unique_id4);
2102 EXPECT_EQ(unique_id, unique_id4);
2103
2104 // A different attestation application ID should yield a different unique ID.
2105 auto app_id2 = "different_foo";
2106 vector<uint8_t> unique_id5;
2107 get_unique_id(app_id2, cert_date, &unique_id5);
2108 EXPECT_NE(unique_id, unique_id5);
2109
2110 // A radically different date should yield a different unique ID.
2111 vector<uint8_t> unique_id6;
2112 get_unique_id(app_id, 1611621648000, &unique_id6);
2113 EXPECT_NE(unique_id, unique_id6);
2114
2115 vector<uint8_t> unique_id7;
2116 get_unique_id(app_id, max_date + 1, &unique_id7);
2117 EXPECT_NE(unique_id, unique_id7);
2118
2119 vector<uint8_t> unique_id8;
2120 get_unique_id(app_id, min_date - 1, &unique_id8);
2121 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002122
2123 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2124 vector<uint8_t> unique_id9;
2125 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2126 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002127}
2128
2129/*
David Drysdale37af4b32021-05-14 16:46:59 +01002130 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2131 *
2132 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2133 */
2134TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2135 auto challenge = "hello";
2136 auto attest_app_id = "foo";
2137 auto subject = "cert subj 2";
2138 vector<uint8_t> subject_der(make_name_from_str(subject));
2139 uint64_t serial_int = 0x1010;
2140 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2141
2142 // Earlier versions of the attestation extension schema included a slot:
2143 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2144 // This should never have been included, and should never be filled in.
2145 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2146 // to confirm that this field never makes it into the attestation extension.
2147 vector<uint8_t> key_blob;
2148 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002149 auto builder = AuthorizationSetBuilder()
2150 .Authorization(TAG_NO_AUTH_REQUIRED)
2151 .EcdsaSigningKey(EcCurve::P_256)
2152 .Digest(Digest::NONE)
2153 .AttestationChallenge(challenge)
2154 .AttestationApplicationId(attest_app_id)
2155 .Authorization(TAG_APPLICATION_ID, "client_id")
2156 .Authorization(TAG_APPLICATION_DATA, "appdata")
2157 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2158 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2159 .SetDefaultValidity();
2160
2161 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002162 // Strongbox may not support factory provisioned attestation key.
2163 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002164 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2165 result = GenerateKeyWithSelfSignedAttestKey(
2166 AuthorizationSetBuilder()
2167 .EcdsaKey(EcCurve::P_256)
2168 .AttestKey()
2169 .SetDefaultValidity(), /* attest key params */
2170 builder, &key_blob, &key_characteristics);
2171 }
subrahmanyaman05642492022-02-05 07:10:56 +00002172 }
David Drysdale37af4b32021-05-14 16:46:59 +01002173 ASSERT_EQ(result, ErrorCode::OK);
2174 ASSERT_GT(key_blob.size(), 0U);
2175
2176 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2177 ASSERT_GT(cert_chain_.size(), 0);
2178 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2179
2180 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2181 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002182 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2183 hw_enforced, SecLevel(),
2184 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002185
2186 // Check that the app id is not in the cert.
2187 string app_id = "clientid";
2188 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2189 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2190 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2191 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2192 cert_chain_[0].encodedCertificate.end());
2193
2194 CheckedDeleteKey(&key_blob);
2195}
2196
2197/*
Selene Huang4f64c222021-04-13 19:54:36 -07002198 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2199 *
2200 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2201 * the key will generate a self signed attestation.
2202 */
2203TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002204 auto subject = "cert subj 2";
2205 vector<uint8_t> subject_der(make_name_from_str(subject));
2206
2207 uint64_t serial_int = 0x123456FFF1234;
2208 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2209
David Drysdaledf09e542021-06-08 15:46:11 +01002210 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002211 vector<uint8_t> key_blob;
2212 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002213 ASSERT_EQ(ErrorCode::OK,
2214 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002215 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002216 .Digest(Digest::NONE)
2217 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2218 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2219 .SetDefaultValidity(),
2220 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002221 ASSERT_GT(key_blob.size(), 0U);
2222 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002223 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002224
2225 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2226
2227 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002228 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002229
2230 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07002231 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002232 ASSERT_EQ(cert_chain_.size(), 1);
2233
2234 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2235 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2236
2237 CheckedDeleteKey(&key_blob);
2238 }
2239}
2240
2241/*
2242 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2243 *
2244 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2245 * app id must also be provided or else it will fail.
2246 */
2247TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2248 auto challenge = "hello";
2249 vector<uint8_t> key_blob;
2250 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002251 auto builder = AuthorizationSetBuilder()
2252 .EcdsaSigningKey(EcCurve::P_256)
2253 .Digest(Digest::NONE)
2254 .AttestationChallenge(challenge)
2255 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002256
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002257 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002258 // Strongbox may not support factory provisioned attestation key.
2259 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002260 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2261 result = GenerateKeyWithSelfSignedAttestKey(
2262 AuthorizationSetBuilder()
2263 .EcdsaKey(EcCurve::P_256)
2264 .AttestKey()
2265 .SetDefaultValidity(), /* attest key params */
2266 builder, &key_blob, &key_characteristics);
2267 }
subrahmanyaman05642492022-02-05 07:10:56 +00002268 }
2269 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002270}
2271
2272/*
2273 * NewKeyGenerationTest.EcdsaIgnoreAppId
2274 *
2275 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2276 * any appid will be ignored, and keymint will generate a self sign certificate.
2277 */
2278TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2279 auto app_id = "foo";
2280
David Drysdaledf09e542021-06-08 15:46:11 +01002281 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002282 vector<uint8_t> key_blob;
2283 vector<KeyCharacteristics> key_characteristics;
2284 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002285 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002286 .Digest(Digest::NONE)
2287 .AttestationApplicationId(app_id)
2288 .SetDefaultValidity(),
2289 &key_blob, &key_characteristics));
2290
2291 ASSERT_GT(key_blob.size(), 0U);
2292 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002293 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002294
2295 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2296
2297 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002298 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002299
2300 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2301 ASSERT_EQ(cert_chain_.size(), 1);
2302
2303 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2304 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2305
2306 CheckedDeleteKey(&key_blob);
2307 }
2308}
2309
2310/*
2311 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2312 *
2313 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2314 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2315 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2316 * to specify how many following bytes will be used to encode the length.
2317 */
2318TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2319 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002320 std::vector<uint32_t> app_id_lengths{143, 258};
2321
2322 for (uint32_t length : app_id_lengths) {
2323 const string app_id(length, 'a');
2324 vector<uint8_t> key_blob;
2325 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002326 auto builder = AuthorizationSetBuilder()
2327 .Authorization(TAG_NO_AUTH_REQUIRED)
2328 .EcdsaSigningKey(EcCurve::P_256)
2329 .Digest(Digest::NONE)
2330 .AttestationChallenge(challenge)
2331 .AttestationApplicationId(app_id)
2332 .SetDefaultValidity();
2333
2334 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002335 // Strongbox may not support factory provisioned attestation key.
2336 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002337 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2338 result = GenerateKeyWithSelfSignedAttestKey(
2339 AuthorizationSetBuilder()
2340 .EcdsaKey(EcCurve::P_256)
2341 .AttestKey()
2342 .SetDefaultValidity(), /* attest key params */
2343 builder, &key_blob, &key_characteristics);
2344 }
subrahmanyaman05642492022-02-05 07:10:56 +00002345 }
2346 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002347 ASSERT_GT(key_blob.size(), 0U);
2348 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002349 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002350
2351 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2352
2353 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002354 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002355
2356 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2357 ASSERT_GT(cert_chain_.size(), 0);
2358
2359 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2360 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002361 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002362 sw_enforced, hw_enforced, SecLevel(),
2363 cert_chain_[0].encodedCertificate));
2364
2365 CheckedDeleteKey(&key_blob);
2366 }
2367}
2368
2369/*
Qi Wud22ec842020-11-26 13:27:53 +08002370 * NewKeyGenerationTest.LimitedUsageEcdsa
2371 *
2372 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2373 * resulting keys have correct characteristics.
2374 */
2375TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002376 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08002377 vector<uint8_t> key_blob;
2378 vector<KeyCharacteristics> key_characteristics;
2379 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002380 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002381 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002382 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2383 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002384 &key_blob, &key_characteristics));
2385
2386 ASSERT_GT(key_blob.size(), 0U);
2387 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002388 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002389
2390 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2391
2392 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002393 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002394
2395 // Check the usage count limit tag appears in the authorizations.
2396 AuthorizationSet auths;
2397 for (auto& entry : key_characteristics) {
2398 auths.push_back(AuthorizationSet(entry.authorizations));
2399 }
2400 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2401 << "key usage count limit " << 1U << " missing";
2402
2403 CheckedDeleteKey(&key_blob);
2404 }
2405}
2406
2407/*
Selene Huang31ab4042020-04-29 04:22:39 -07002408 * NewKeyGenerationTest.EcdsaDefaultSize
2409 *
David Drysdaledf09e542021-06-08 15:46:11 +01002410 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002411 * UNSUPPORTED_KEY_SIZE.
2412 */
2413TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2414 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2415 GenerateKey(AuthorizationSetBuilder()
2416 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2417 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002418 .Digest(Digest::NONE)
2419 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002420}
2421
2422/*
David Drysdale42fe1892021-10-14 14:43:46 +01002423 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002424 *
David Drysdale42fe1892021-10-14 14:43:46 +01002425 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002426 * UNSUPPORTED_KEY_SIZE.
2427 */
David Drysdale42fe1892021-10-14 14:43:46 +01002428TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002429 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07002430 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002431 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002432 auto result = GenerateKey(AuthorizationSetBuilder()
2433 .EcdsaSigningKey(curve)
2434 .Digest(Digest::NONE)
2435 .SetDefaultValidity(),
2436 &key_blob, &key_characteristics);
2437 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2438 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002439 }
2440
David Drysdaledf09e542021-06-08 15:46:11 +01002441 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2442 GenerateKey(AuthorizationSetBuilder()
2443 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2444 .Authorization(TAG_KEY_SIZE, 190)
2445 .SigningKey()
2446 .Digest(Digest::NONE)
2447 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002448}
2449
2450/*
2451 * NewKeyGenerationTest.EcdsaMismatchKeySize
2452 *
2453 * Verifies that specifying mismatched key size and curve for EC key generation returns
2454 * INVALID_ARGUMENT.
2455 */
2456TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002457 if (SecLevel() == SecurityLevel::STRONGBOX) {
2458 GTEST_SKIP() << "Test not applicable to StrongBox device";
2459 }
Selene Huang31ab4042020-04-29 04:22:39 -07002460
David Drysdaledf09e542021-06-08 15:46:11 +01002461 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002462 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002463 .Authorization(TAG_KEY_SIZE, 224)
2464 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002465 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002466 .Digest(Digest::NONE)
2467 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002468 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002469}
2470
2471/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002472 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002473 *
2474 * Verifies that keymint does not support any curve designated as unsupported.
2475 */
2476TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2477 Digest digest;
2478 if (SecLevel() == SecurityLevel::STRONGBOX) {
2479 digest = Digest::SHA_2_256;
2480 } else {
2481 digest = Digest::SHA_2_512;
2482 }
2483 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002484 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2485 .EcdsaSigningKey(curve)
2486 .Digest(digest)
2487 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002488 << "Failed to generate key on curve: " << curve;
2489 CheckedDeleteKey();
2490 }
2491}
2492
2493/*
2494 * NewKeyGenerationTest.Hmac
2495 *
2496 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2497 * characteristics.
2498 */
2499TEST_P(NewKeyGenerationTest, Hmac) {
2500 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2501 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002502 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002503 constexpr size_t key_size = 128;
2504 ASSERT_EQ(ErrorCode::OK,
2505 GenerateKey(
2506 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2507 TAG_MIN_MAC_LENGTH, 128),
2508 &key_blob, &key_characteristics));
2509
2510 ASSERT_GT(key_blob.size(), 0U);
2511 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002512 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002513
Shawn Willden7f424372021-01-10 18:06:50 -07002514 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2515 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2516 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2517 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002518
2519 CheckedDeleteKey(&key_blob);
2520 }
2521}
2522
2523/*
Selene Huang4f64c222021-04-13 19:54:36 -07002524 * NewKeyGenerationTest.HmacNoAttestation
2525 *
2526 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2527 * and app id are provided.
2528 */
2529TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2530 auto challenge = "hello";
2531 auto app_id = "foo";
2532
2533 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2534 vector<uint8_t> key_blob;
2535 vector<KeyCharacteristics> key_characteristics;
2536 constexpr size_t key_size = 128;
2537 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2538 .HmacKey(key_size)
2539 .Digest(digest)
2540 .AttestationChallenge(challenge)
2541 .AttestationApplicationId(app_id)
2542 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2543 &key_blob, &key_characteristics));
2544
2545 ASSERT_GT(key_blob.size(), 0U);
2546 ASSERT_EQ(cert_chain_.size(), 0);
2547 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002548 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002549
2550 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2551 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2552 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2553 << "Key size " << key_size << "missing";
2554
2555 CheckedDeleteKey(&key_blob);
2556 }
2557}
2558
2559/*
Qi Wud22ec842020-11-26 13:27:53 +08002560 * NewKeyGenerationTest.LimitedUsageHmac
2561 *
2562 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2563 * resulting keys have correct characteristics.
2564 */
2565TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2566 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2567 vector<uint8_t> key_blob;
2568 vector<KeyCharacteristics> key_characteristics;
2569 constexpr size_t key_size = 128;
2570 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2571 .HmacKey(key_size)
2572 .Digest(digest)
2573 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2574 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2575 &key_blob, &key_characteristics));
2576
2577 ASSERT_GT(key_blob.size(), 0U);
2578 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002579 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002580
2581 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2582 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2583 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2584 << "Key size " << key_size << "missing";
2585
2586 // Check the usage count limit tag appears in the authorizations.
2587 AuthorizationSet auths;
2588 for (auto& entry : key_characteristics) {
2589 auths.push_back(AuthorizationSet(entry.authorizations));
2590 }
2591 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2592 << "key usage count limit " << 1U << " missing";
2593
2594 CheckedDeleteKey(&key_blob);
2595 }
2596}
2597
2598/*
Selene Huang31ab4042020-04-29 04:22:39 -07002599 * NewKeyGenerationTest.HmacCheckKeySizes
2600 *
2601 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2602 */
2603TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2604 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2605 if (key_size < 64 || key_size % 8 != 0) {
2606 // To keep this test from being very slow, we only test a random fraction of
2607 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2608 // them, we expect to run ~40 of them in each run.
2609 if (key_size % 8 == 0 || random() % 10 == 0) {
2610 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2611 GenerateKey(AuthorizationSetBuilder()
2612 .HmacKey(key_size)
2613 .Digest(Digest::SHA_2_256)
2614 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2615 << "HMAC key size " << key_size << " invalid";
2616 }
2617 } else {
2618 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2619 .HmacKey(key_size)
2620 .Digest(Digest::SHA_2_256)
2621 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2622 << "Failed to generate HMAC key of size " << key_size;
2623 CheckedDeleteKey();
2624 }
2625 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002626 if (SecLevel() == SecurityLevel::STRONGBOX) {
2627 // STRONGBOX devices must not support keys larger than 512 bits.
2628 size_t key_size = 520;
2629 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2630 GenerateKey(AuthorizationSetBuilder()
2631 .HmacKey(key_size)
2632 .Digest(Digest::SHA_2_256)
2633 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2634 << "HMAC key size " << key_size << " unexpectedly valid";
2635 }
Selene Huang31ab4042020-04-29 04:22:39 -07002636}
2637
2638/*
2639 * NewKeyGenerationTest.HmacCheckMinMacLengths
2640 *
2641 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2642 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2643 * specific MAC length that failed, so reproducing a failed run will be easy.
2644 */
2645TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2646 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2647 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2648 // To keep this test from being very long, we only test a random fraction of
2649 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2650 // we expect to run ~17 of them in each run.
2651 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2652 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2653 GenerateKey(AuthorizationSetBuilder()
2654 .HmacKey(128)
2655 .Digest(Digest::SHA_2_256)
2656 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2657 << "HMAC min mac length " << min_mac_length << " invalid.";
2658 }
2659 } else {
2660 EXPECT_EQ(ErrorCode::OK,
2661 GenerateKey(AuthorizationSetBuilder()
2662 .HmacKey(128)
2663 .Digest(Digest::SHA_2_256)
2664 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2665 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2666 CheckedDeleteKey();
2667 }
2668 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002669
2670 // Minimum MAC length must be no more than 512 bits.
2671 size_t min_mac_length = 520;
2672 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2673 GenerateKey(AuthorizationSetBuilder()
2674 .HmacKey(128)
2675 .Digest(Digest::SHA_2_256)
2676 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2677 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002678}
2679
2680/*
2681 * NewKeyGenerationTest.HmacMultipleDigests
2682 *
2683 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2684 */
2685TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002686 if (SecLevel() == SecurityLevel::STRONGBOX) {
2687 GTEST_SKIP() << "Test not applicable to StrongBox device";
2688 }
Selene Huang31ab4042020-04-29 04:22:39 -07002689
2690 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2691 GenerateKey(AuthorizationSetBuilder()
2692 .HmacKey(128)
2693 .Digest(Digest::SHA1)
2694 .Digest(Digest::SHA_2_256)
2695 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2696}
2697
2698/*
2699 * NewKeyGenerationTest.HmacDigestNone
2700 *
2701 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2702 */
2703TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2704 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2705 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2706 128)));
2707
2708 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2709 GenerateKey(AuthorizationSetBuilder()
2710 .HmacKey(128)
2711 .Digest(Digest::NONE)
2712 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2713}
2714
Selene Huang4f64c222021-04-13 19:54:36 -07002715/*
2716 * NewKeyGenerationTest.AesNoAttestation
2717 *
2718 * Verifies that attestation parameters to AES keys are ignored and generateKey
2719 * will succeed.
2720 */
2721TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2722 auto challenge = "hello";
2723 auto app_id = "foo";
2724
2725 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2726 .Authorization(TAG_NO_AUTH_REQUIRED)
2727 .AesEncryptionKey(128)
2728 .EcbMode()
2729 .Padding(PaddingMode::PKCS7)
2730 .AttestationChallenge(challenge)
2731 .AttestationApplicationId(app_id)));
2732
2733 ASSERT_EQ(cert_chain_.size(), 0);
2734}
2735
2736/*
2737 * NewKeyGenerationTest.TripleDesNoAttestation
2738 *
2739 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2740 * will be successful. No attestation should be generated.
2741 */
2742TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2743 auto challenge = "hello";
2744 auto app_id = "foo";
2745
2746 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2747 .TripleDesEncryptionKey(168)
2748 .BlockMode(BlockMode::ECB)
2749 .Authorization(TAG_NO_AUTH_REQUIRED)
2750 .Padding(PaddingMode::NONE)
2751 .AttestationChallenge(challenge)
2752 .AttestationApplicationId(app_id)));
2753 ASSERT_EQ(cert_chain_.size(), 0);
2754}
2755
Selene Huang31ab4042020-04-29 04:22:39 -07002756INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2757
2758typedef KeyMintAidlTestBase SigningOperationsTest;
2759
2760/*
2761 * SigningOperationsTest.RsaSuccess
2762 *
2763 * Verifies that raw RSA signature operations succeed.
2764 */
2765TEST_P(SigningOperationsTest, RsaSuccess) {
2766 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2767 .RsaSigningKey(2048, 65537)
2768 .Digest(Digest::NONE)
2769 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002770 .Authorization(TAG_NO_AUTH_REQUIRED)
2771 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002772 string message = "12345678901234567890123456789012";
2773 string signature = SignMessage(
2774 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002775 LocalVerifyMessage(message, signature,
2776 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2777}
2778
2779/*
2780 * SigningOperationsTest.RsaAllPaddingsAndDigests
2781 *
2782 * Verifies RSA signature/verification for all padding modes and digests.
2783 */
2784TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2785 auto authorizations = AuthorizationSetBuilder()
2786 .Authorization(TAG_NO_AUTH_REQUIRED)
2787 .RsaSigningKey(2048, 65537)
2788 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2789 .Padding(PaddingMode::NONE)
2790 .Padding(PaddingMode::RSA_PSS)
2791 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2792 .SetDefaultValidity();
2793
2794 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2795
2796 string message(128, 'a');
2797 string corrupt_message(message);
2798 ++corrupt_message[corrupt_message.size() / 2];
2799
2800 for (auto padding :
2801 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2802 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2803 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2804 // Digesting only makes sense with padding.
2805 continue;
2806 }
2807
2808 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2809 // PSS requires digesting.
2810 continue;
2811 }
2812
2813 string signature =
2814 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2815 LocalVerifyMessage(message, signature,
2816 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2817 }
2818 }
Selene Huang31ab4042020-04-29 04:22:39 -07002819}
2820
2821/*
2822 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2823 *
Shawn Willden7f424372021-01-10 18:06:50 -07002824 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002825 */
2826TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2827 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2828 .Authorization(TAG_NO_AUTH_REQUIRED)
2829 .RsaSigningKey(2048, 65537)
2830 .Digest(Digest::NONE)
2831 .Padding(PaddingMode::NONE)
2832 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002833 .Authorization(TAG_APPLICATION_DATA, "appdata")
2834 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002835
2836 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2837
Selene Huang31ab4042020-04-29 04:22:39 -07002838 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2839 Begin(KeyPurpose::SIGN,
2840 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2841 AbortIfNeeded();
2842 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2843 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2844 .Digest(Digest::NONE)
2845 .Padding(PaddingMode::NONE)
2846 .Authorization(TAG_APPLICATION_ID, "clientid")));
2847 AbortIfNeeded();
2848 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2849 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2850 .Digest(Digest::NONE)
2851 .Padding(PaddingMode::NONE)
2852 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2853 AbortIfNeeded();
2854 EXPECT_EQ(ErrorCode::OK,
2855 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2856 .Digest(Digest::NONE)
2857 .Padding(PaddingMode::NONE)
2858 .Authorization(TAG_APPLICATION_DATA, "appdata")
2859 .Authorization(TAG_APPLICATION_ID, "clientid")));
2860 AbortIfNeeded();
2861}
2862
2863/*
2864 * SigningOperationsTest.RsaPssSha256Success
2865 *
2866 * Verifies that RSA-PSS signature operations succeed.
2867 */
2868TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2869 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2870 .RsaSigningKey(2048, 65537)
2871 .Digest(Digest::SHA_2_256)
2872 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002873 .Authorization(TAG_NO_AUTH_REQUIRED)
2874 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002875 // Use large message, which won't work without digesting.
2876 string message(1024, 'a');
2877 string signature = SignMessage(
2878 message,
2879 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2880}
2881
2882/*
2883 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2884 *
2885 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2886 * supports only unpadded operations.
2887 */
2888TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2889 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2890 .RsaSigningKey(2048, 65537)
2891 .Digest(Digest::NONE)
2892 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002893 .Padding(PaddingMode::NONE)
2894 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002895 string message = "12345678901234567890123456789012";
2896 string signature;
2897
2898 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2899 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2900 .Digest(Digest::NONE)
2901 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2902}
2903
2904/*
2905 * SigningOperationsTest.NoUserConfirmation
2906 *
2907 * Verifies that keymint rejects signing operations for keys with
2908 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2909 * presented.
2910 */
2911TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002912 if (SecLevel() == SecurityLevel::STRONGBOX) {
2913 GTEST_SKIP() << "Test not applicable to StrongBox device";
2914 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002915 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2916 .RsaSigningKey(1024, 65537)
2917 .Digest(Digest::NONE)
2918 .Padding(PaddingMode::NONE)
2919 .Authorization(TAG_NO_AUTH_REQUIRED)
2920 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2921 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002922
2923 const string message = "12345678901234567890123456789012";
2924 EXPECT_EQ(ErrorCode::OK,
2925 Begin(KeyPurpose::SIGN,
2926 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2927 string signature;
2928 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2929}
2930
2931/*
2932 * SigningOperationsTest.RsaPkcs1Sha256Success
2933 *
2934 * Verifies that digested RSA-PKCS1 signature operations succeed.
2935 */
2936TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2937 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2938 .RsaSigningKey(2048, 65537)
2939 .Digest(Digest::SHA_2_256)
2940 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002941 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2942 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002943 string message(1024, 'a');
2944 string signature = SignMessage(message, AuthorizationSetBuilder()
2945 .Digest(Digest::SHA_2_256)
2946 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2947}
2948
2949/*
2950 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2951 *
2952 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2953 */
2954TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2955 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2956 .RsaSigningKey(2048, 65537)
2957 .Digest(Digest::NONE)
2958 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002959 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2960 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002961 string message(53, 'a');
2962 string signature = SignMessage(message, AuthorizationSetBuilder()
2963 .Digest(Digest::NONE)
2964 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2965}
2966
2967/*
2968 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2969 *
2970 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2971 * given a too-long message.
2972 */
2973TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2974 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2975 .RsaSigningKey(2048, 65537)
2976 .Digest(Digest::NONE)
2977 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002978 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2979 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002980 string message(257, 'a');
2981
2982 EXPECT_EQ(ErrorCode::OK,
2983 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2984 .Digest(Digest::NONE)
2985 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2986 string signature;
2987 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
2988}
2989
2990/*
2991 * SigningOperationsTest.RsaPssSha512TooSmallKey
2992 *
2993 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
2994 * used with a key that is too small for the message.
2995 *
2996 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
2997 * keymint specification requires that salt_size == digest_size, so the message will be
2998 * digest_size * 2 +
2999 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3000 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3001 * for a 1024-bit key.
3002 */
3003TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003004 if (SecLevel() == SecurityLevel::STRONGBOX) {
3005 GTEST_SKIP() << "Test not applicable to StrongBox device";
3006 }
Selene Huang31ab4042020-04-29 04:22:39 -07003007 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3008 .RsaSigningKey(1024, 65537)
3009 .Digest(Digest::SHA_2_512)
3010 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003011 .Padding(PaddingMode::RSA_PSS)
3012 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003013 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3014 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3015 .Digest(Digest::SHA_2_512)
3016 .Padding(PaddingMode::RSA_PSS)));
3017}
3018
3019/*
3020 * SigningOperationsTest.RsaNoPaddingTooLong
3021 *
3022 * Verifies that raw RSA signature operations fail with the correct error code when
3023 * given a too-long message.
3024 */
3025TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3026 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3027 .RsaSigningKey(2048, 65537)
3028 .Digest(Digest::NONE)
3029 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003030 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3031 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003032 // One byte too long
3033 string message(2048 / 8 + 1, 'a');
3034 ASSERT_EQ(ErrorCode::OK,
3035 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3036 .Digest(Digest::NONE)
3037 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3038 string result;
3039 ErrorCode finish_error_code = Finish(message, &result);
3040 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3041 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3042
3043 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3044 message = string(128 * 1024, 'a');
3045 ASSERT_EQ(ErrorCode::OK,
3046 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3047 .Digest(Digest::NONE)
3048 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3049 finish_error_code = Finish(message, &result);
3050 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3051 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3052}
3053
3054/*
3055 * SigningOperationsTest.RsaAbort
3056 *
3057 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3058 * test, but the behavior should be algorithm and purpose-independent.
3059 */
3060TEST_P(SigningOperationsTest, RsaAbort) {
3061 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3062 .RsaSigningKey(2048, 65537)
3063 .Digest(Digest::NONE)
3064 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003065 .Padding(PaddingMode::NONE)
3066 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003067
3068 ASSERT_EQ(ErrorCode::OK,
3069 Begin(KeyPurpose::SIGN,
3070 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3071 EXPECT_EQ(ErrorCode::OK, Abort());
3072
3073 // Another abort should fail
3074 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3075
3076 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003077 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003078}
3079
3080/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003081 * SigningOperationsTest.RsaNonUniqueParams
3082 *
3083 * Verifies that an operation with multiple padding modes is rejected.
3084 */
3085TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3086 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3087 .RsaSigningKey(2048, 65537)
3088 .Digest(Digest::NONE)
3089 .Digest(Digest::SHA1)
3090 .Authorization(TAG_NO_AUTH_REQUIRED)
3091 .Padding(PaddingMode::NONE)
3092 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3093 .SetDefaultValidity()));
3094
3095 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3096 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3097 .Digest(Digest::NONE)
3098 .Padding(PaddingMode::NONE)
3099 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3100
Tommy Chiuc93c4392021-05-11 18:36:50 +08003101 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3102 .Digest(Digest::NONE)
3103 .Digest(Digest::SHA1)
3104 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3105 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003106
3107 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3108 Begin(KeyPurpose::SIGN,
3109 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3110}
3111
3112/*
Selene Huang31ab4042020-04-29 04:22:39 -07003113 * SigningOperationsTest.RsaUnsupportedPadding
3114 *
3115 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3116 * with a padding mode inappropriate for RSA.
3117 */
3118TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3119 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3120 .RsaSigningKey(2048, 65537)
3121 .Authorization(TAG_NO_AUTH_REQUIRED)
3122 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003123 .Padding(PaddingMode::PKCS7)
3124 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003125 ASSERT_EQ(
3126 ErrorCode::UNSUPPORTED_PADDING_MODE,
3127 Begin(KeyPurpose::SIGN,
3128 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003129 CheckedDeleteKey();
3130
3131 ASSERT_EQ(ErrorCode::OK,
3132 GenerateKey(
3133 AuthorizationSetBuilder()
3134 .RsaSigningKey(2048, 65537)
3135 .Authorization(TAG_NO_AUTH_REQUIRED)
3136 .Digest(Digest::SHA_2_256 /* supported digest */)
3137 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3138 .SetDefaultValidity()));
3139 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3140 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3141 .Digest(Digest::SHA_2_256)
3142 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003143}
3144
3145/*
3146 * SigningOperationsTest.RsaPssNoDigest
3147 *
3148 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3149 */
3150TEST_P(SigningOperationsTest, RsaNoDigest) {
3151 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3152 .RsaSigningKey(2048, 65537)
3153 .Authorization(TAG_NO_AUTH_REQUIRED)
3154 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003155 .Padding(PaddingMode::RSA_PSS)
3156 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003157 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3158 Begin(KeyPurpose::SIGN,
3159 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3160
3161 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3162 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3163}
3164
3165/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003166 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003167 *
3168 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3169 * supported in some cases (as validated in other tests), but a mode must be specified.
3170 */
3171TEST_P(SigningOperationsTest, RsaNoPadding) {
3172 // Padding must be specified
3173 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3174 .RsaKey(2048, 65537)
3175 .Authorization(TAG_NO_AUTH_REQUIRED)
3176 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003177 .Digest(Digest::NONE)
3178 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003179 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3180 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3181}
3182
3183/*
3184 * SigningOperationsTest.RsaShortMessage
3185 *
3186 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3187 */
3188TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3189 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3190 .Authorization(TAG_NO_AUTH_REQUIRED)
3191 .RsaSigningKey(2048, 65537)
3192 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003193 .Padding(PaddingMode::NONE)
3194 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003195
3196 // Barely shorter
3197 string message(2048 / 8 - 1, 'a');
3198 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3199
3200 // Much shorter
3201 message = "a";
3202 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3203}
3204
3205/*
3206 * SigningOperationsTest.RsaSignWithEncryptionKey
3207 *
3208 * Verifies that RSA encryption keys cannot be used to sign.
3209 */
3210TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3211 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3212 .Authorization(TAG_NO_AUTH_REQUIRED)
3213 .RsaEncryptionKey(2048, 65537)
3214 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003215 .Padding(PaddingMode::NONE)
3216 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003217 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3218 Begin(KeyPurpose::SIGN,
3219 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3220}
3221
3222/*
3223 * SigningOperationsTest.RsaSignTooLargeMessage
3224 *
3225 * Verifies that attempting a raw signature of a message which is the same length as the key,
3226 * but numerically larger than the public modulus, fails with the correct error.
3227 */
3228TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3229 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3230 .Authorization(TAG_NO_AUTH_REQUIRED)
3231 .RsaSigningKey(2048, 65537)
3232 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003233 .Padding(PaddingMode::NONE)
3234 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003235
3236 // Largest possible message will always be larger than the public modulus.
3237 string message(2048 / 8, static_cast<char>(0xff));
3238 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3239 .Authorization(TAG_NO_AUTH_REQUIRED)
3240 .Digest(Digest::NONE)
3241 .Padding(PaddingMode::NONE)));
3242 string signature;
3243 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3244}
3245
3246/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003247 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3248 *
David Drysdale42fe1892021-10-14 14:43:46 +01003249 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003250 */
3251TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003252
3253 string message = "1234567890";
3254 string corrupt_message = "2234567890";
3255 for (auto curve : ValidCurves()) {
3256 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003257 // Ed25519 only allows Digest::NONE.
3258 auto digests = (curve == EcCurve::CURVE_25519)
3259 ? std::vector<Digest>(1, Digest::NONE)
3260 : ValidDigests(true /* withNone */, false /* withMD5 */);
3261
David Drysdaledf8f52e2021-05-06 08:10:58 +01003262 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3263 .Authorization(TAG_NO_AUTH_REQUIRED)
3264 .EcdsaSigningKey(curve)
3265 .Digest(digests)
3266 .SetDefaultValidity());
3267 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3268 if (error != ErrorCode::OK) {
3269 continue;
3270 }
3271
3272 for (auto digest : digests) {
3273 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3274 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3275 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3276 }
3277
3278 auto rc = DeleteKey();
3279 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3280 }
3281}
3282
3283/*
Selene Huang31ab4042020-04-29 04:22:39 -07003284 * SigningOperationsTest.EcdsaAllCurves
3285 *
David Drysdale42fe1892021-10-14 14:43:46 +01003286 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003287 */
3288TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3289 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003290 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3291 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003292 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3293 .Authorization(TAG_NO_AUTH_REQUIRED)
3294 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003295 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003296 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003297 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3298 if (error != ErrorCode::OK) continue;
3299
3300 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003301 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003302 CheckedDeleteKey();
3303 }
3304}
3305
3306/*
David Drysdale42fe1892021-10-14 14:43:46 +01003307 * SigningOperationsTest.EcdsaCurve25519
3308 *
3309 * Verifies that ECDSA operations succeed with curve25519.
3310 */
3311TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3312 if (!Curve25519Supported()) {
3313 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3314 }
3315
3316 EcCurve curve = EcCurve::CURVE_25519;
3317 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3318 .Authorization(TAG_NO_AUTH_REQUIRED)
3319 .EcdsaSigningKey(curve)
3320 .Digest(Digest::NONE)
3321 .SetDefaultValidity());
3322 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3323
3324 string message(1024, 'a');
3325 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3326 CheckedDeleteKey();
3327}
3328
3329/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003330 * SigningOperationsTest.EcdsaCurve25519MaxSize
3331 *
3332 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3333 */
3334TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3335 if (!Curve25519Supported()) {
3336 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3337 }
3338
3339 EcCurve curve = EcCurve::CURVE_25519;
3340 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3341 .Authorization(TAG_NO_AUTH_REQUIRED)
3342 .EcdsaSigningKey(curve)
3343 .Digest(Digest::NONE)
3344 .SetDefaultValidity());
3345 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3346
3347 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3348
3349 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3350 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3351 string message(msg_size, 'a');
3352
3353 // Attempt to sign via Begin+Finish.
3354 AuthorizationSet out_params;
3355 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3356 EXPECT_TRUE(out_params.empty());
3357 string signature;
3358 auto result = Finish(message, &signature);
3359 EXPECT_EQ(result, ErrorCode::OK);
3360 LocalVerifyMessage(message, signature, params);
3361
3362 // Attempt to sign via Begin+Update+Finish
3363 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3364 EXPECT_TRUE(out_params.empty());
3365 string output;
3366 result = Update(message, &output);
3367 EXPECT_EQ(result, ErrorCode::OK);
3368 EXPECT_EQ(output.size(), 0);
3369 string signature2;
3370 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3371 LocalVerifyMessage(message, signature2, params);
3372 }
3373
3374 CheckedDeleteKey();
3375}
3376
3377/*
3378 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3379 *
3380 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3381 */
3382TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3383 if (!Curve25519Supported()) {
3384 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3385 }
3386
3387 EcCurve curve = EcCurve::CURVE_25519;
3388 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3389 .Authorization(TAG_NO_AUTH_REQUIRED)
3390 .EcdsaSigningKey(curve)
3391 .Digest(Digest::NONE)
3392 .SetDefaultValidity());
3393 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3394
3395 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3396
3397 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3398 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3399 string message(msg_size, 'a');
3400
3401 // Attempt to sign via Begin+Finish.
3402 AuthorizationSet out_params;
3403 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3404 EXPECT_TRUE(out_params.empty());
3405 string signature;
3406 auto result = Finish(message, &signature);
3407 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3408
3409 // Attempt to sign via Begin+Update (but never get to Finish)
3410 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3411 EXPECT_TRUE(out_params.empty());
3412 string output;
3413 result = Update(message, &output);
3414 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3415 }
3416
3417 CheckedDeleteKey();
3418}
3419
3420/*
Selene Huang31ab4042020-04-29 04:22:39 -07003421 * SigningOperationsTest.EcdsaNoDigestHugeData
3422 *
3423 * Verifies that ECDSA operations support very large messages, even without digesting. This
3424 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3425 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3426 * the framework.
3427 */
3428TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3429 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3430 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003431 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003432 .Digest(Digest::NONE)
3433 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003434 string message(1 * 1024, 'a');
3435 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3436}
3437
3438/*
3439 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3440 *
3441 * Verifies that using an EC key requires the correct app ID/data.
3442 */
3443TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3444 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3445 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003446 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003447 .Digest(Digest::NONE)
3448 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003449 .Authorization(TAG_APPLICATION_DATA, "appdata")
3450 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003451
3452 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3453
Selene Huang31ab4042020-04-29 04:22:39 -07003454 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3455 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3456 AbortIfNeeded();
3457 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3458 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3459 .Digest(Digest::NONE)
3460 .Authorization(TAG_APPLICATION_ID, "clientid")));
3461 AbortIfNeeded();
3462 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3463 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3464 .Digest(Digest::NONE)
3465 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3466 AbortIfNeeded();
3467 EXPECT_EQ(ErrorCode::OK,
3468 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3469 .Digest(Digest::NONE)
3470 .Authorization(TAG_APPLICATION_DATA, "appdata")
3471 .Authorization(TAG_APPLICATION_ID, "clientid")));
3472 AbortIfNeeded();
3473}
3474
3475/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003476 * SigningOperationsTest.EcdsaIncompatibleDigest
3477 *
3478 * Verifies that using an EC key requires compatible digest.
3479 */
3480TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3481 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3482 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003483 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003484 .Digest(Digest::NONE)
3485 .Digest(Digest::SHA1)
3486 .SetDefaultValidity()));
3487 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3488 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3489 AbortIfNeeded();
3490}
3491
3492/*
Selene Huang31ab4042020-04-29 04:22:39 -07003493 * SigningOperationsTest.AesEcbSign
3494 *
3495 * Verifies that attempts to use AES keys to sign fail in the correct way.
3496 */
3497TEST_P(SigningOperationsTest, AesEcbSign) {
3498 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3499 .Authorization(TAG_NO_AUTH_REQUIRED)
3500 .SigningKey()
3501 .AesEncryptionKey(128)
3502 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3503
3504 AuthorizationSet out_params;
3505 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3506 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3507 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3508 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3509}
3510
3511/*
3512 * SigningOperationsTest.HmacAllDigests
3513 *
3514 * Verifies that HMAC works with all digests.
3515 */
3516TEST_P(SigningOperationsTest, HmacAllDigests) {
3517 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
3518 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3519 .Authorization(TAG_NO_AUTH_REQUIRED)
3520 .HmacKey(128)
3521 .Digest(digest)
3522 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3523 << "Failed to create HMAC key with digest " << digest;
3524 string message = "12345678901234567890123456789012";
3525 string signature = MacMessage(message, digest, 160);
3526 EXPECT_EQ(160U / 8U, signature.size())
3527 << "Failed to sign with HMAC key with digest " << digest;
3528 CheckedDeleteKey();
3529 }
3530}
3531
3532/*
3533 * SigningOperationsTest.HmacSha256TooLargeMacLength
3534 *
3535 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3536 * digest size.
3537 */
3538TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3539 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3540 .Authorization(TAG_NO_AUTH_REQUIRED)
3541 .HmacKey(128)
3542 .Digest(Digest::SHA_2_256)
3543 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3544 AuthorizationSet output_params;
3545 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3546 AuthorizationSetBuilder()
3547 .Digest(Digest::SHA_2_256)
3548 .Authorization(TAG_MAC_LENGTH, 264),
3549 &output_params));
3550}
3551
3552/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003553 * SigningOperationsTest.HmacSha256InvalidMacLength
3554 *
3555 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3556 * not a multiple of 8.
3557 */
3558TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3559 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3560 .Authorization(TAG_NO_AUTH_REQUIRED)
3561 .HmacKey(128)
3562 .Digest(Digest::SHA_2_256)
3563 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3564 AuthorizationSet output_params;
3565 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3566 AuthorizationSetBuilder()
3567 .Digest(Digest::SHA_2_256)
3568 .Authorization(TAG_MAC_LENGTH, 161),
3569 &output_params));
3570}
3571
3572/*
Selene Huang31ab4042020-04-29 04:22:39 -07003573 * SigningOperationsTest.HmacSha256TooSmallMacLength
3574 *
3575 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3576 * specified minimum MAC length.
3577 */
3578TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3579 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3580 .Authorization(TAG_NO_AUTH_REQUIRED)
3581 .HmacKey(128)
3582 .Digest(Digest::SHA_2_256)
3583 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3584 AuthorizationSet output_params;
3585 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3586 AuthorizationSetBuilder()
3587 .Digest(Digest::SHA_2_256)
3588 .Authorization(TAG_MAC_LENGTH, 120),
3589 &output_params));
3590}
3591
3592/*
3593 * SigningOperationsTest.HmacRfc4231TestCase3
3594 *
3595 * Validates against the test vectors from RFC 4231 test case 3.
3596 */
3597TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3598 string key(20, 0xaa);
3599 string message(50, 0xdd);
3600 uint8_t sha_224_expected[] = {
3601 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3602 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3603 };
3604 uint8_t sha_256_expected[] = {
3605 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3606 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3607 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3608 };
3609 uint8_t sha_384_expected[] = {
3610 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3611 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3612 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3613 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3614 };
3615 uint8_t sha_512_expected[] = {
3616 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3617 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3618 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3619 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3620 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3621 };
3622
3623 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3624 if (SecLevel() != SecurityLevel::STRONGBOX) {
3625 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3626 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3627 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3628 }
3629}
3630
3631/*
3632 * SigningOperationsTest.HmacRfc4231TestCase5
3633 *
3634 * Validates against the test vectors from RFC 4231 test case 5.
3635 */
3636TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3637 string key(20, 0x0c);
3638 string message = "Test With Truncation";
3639
3640 uint8_t sha_224_expected[] = {
3641 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3642 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3643 };
3644 uint8_t sha_256_expected[] = {
3645 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3646 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3647 };
3648 uint8_t sha_384_expected[] = {
3649 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3650 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3651 };
3652 uint8_t sha_512_expected[] = {
3653 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3654 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3655 };
3656
3657 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3658 if (SecLevel() != SecurityLevel::STRONGBOX) {
3659 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3660 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3661 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3662 }
3663}
3664
3665INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3666
3667typedef KeyMintAidlTestBase VerificationOperationsTest;
3668
3669/*
Selene Huang31ab4042020-04-29 04:22:39 -07003670 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3671 *
3672 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3673 */
3674TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3675 string key_material = "HelloThisIsAKey";
3676
3677 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003678 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003679 EXPECT_EQ(ErrorCode::OK,
3680 ImportKey(AuthorizationSetBuilder()
3681 .Authorization(TAG_NO_AUTH_REQUIRED)
3682 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3683 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3684 .Digest(Digest::SHA_2_256)
3685 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3686 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3687 EXPECT_EQ(ErrorCode::OK,
3688 ImportKey(AuthorizationSetBuilder()
3689 .Authorization(TAG_NO_AUTH_REQUIRED)
3690 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3691 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3692 .Digest(Digest::SHA_2_256)
3693 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3694 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3695
3696 string message = "This is a message.";
3697 string signature = SignMessage(
3698 signing_key, message,
3699 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3700
3701 // Signing key should not work.
3702 AuthorizationSet out_params;
3703 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3704 Begin(KeyPurpose::VERIFY, signing_key,
3705 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3706
3707 // Verification key should work.
3708 VerifyMessage(verification_key, message, signature,
3709 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3710
3711 CheckedDeleteKey(&signing_key);
3712 CheckedDeleteKey(&verification_key);
3713}
3714
Prashant Patildec9fdc2021-12-08 15:25:47 +00003715/*
3716 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3717 *
3718 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3719 */
3720TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3721 string key_material = "HelloThisIsAKey";
3722
3723 vector<uint8_t> signing_key, verification_key;
3724 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3725 EXPECT_EQ(ErrorCode::OK,
3726 ImportKey(AuthorizationSetBuilder()
3727 .Authorization(TAG_NO_AUTH_REQUIRED)
3728 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3729 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3730 .Digest(Digest::SHA_2_256)
3731 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3732 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3733 EXPECT_EQ(ErrorCode::OK,
3734 ImportKey(AuthorizationSetBuilder()
3735 .Authorization(TAG_NO_AUTH_REQUIRED)
3736 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3737 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3738 .Digest(Digest::SHA_2_256)
3739 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3740 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3741
3742 string message = "This is a message.";
3743 string signature = SignMessage(
3744 signing_key, message,
3745 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3746
3747 AuthorizationSet begin_out_params;
3748 ASSERT_EQ(ErrorCode::OK,
3749 Begin(KeyPurpose::VERIFY, verification_key,
3750 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3751
3752 string corruptMessage = "This is b message."; // Corrupted message
3753 string output;
3754 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3755
3756 ASSERT_EQ(ErrorCode::OK,
3757 Begin(KeyPurpose::VERIFY, verification_key,
3758 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3759
3760 signature[0] += 1; // Corrupt a signature
3761 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3762
3763 CheckedDeleteKey(&signing_key);
3764 CheckedDeleteKey(&verification_key);
3765}
3766
Selene Huang31ab4042020-04-29 04:22:39 -07003767INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3768
3769typedef KeyMintAidlTestBase ExportKeyTest;
3770
3771/*
3772 * ExportKeyTest.RsaUnsupportedKeyFormat
3773 *
3774 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3775 */
3776// TODO(seleneh) add ExportKey to GenerateKey
3777// check result
3778
3779class ImportKeyTest : public KeyMintAidlTestBase {
3780 public:
3781 template <TagType tag_type, Tag tag, typename ValueT>
3782 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3783 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003784 for (auto& entry : key_characteristics_) {
3785 if (entry.securityLevel == SecLevel()) {
3786 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3787 << "Tag " << tag << " with value " << expected
3788 << " not found at security level" << entry.securityLevel;
3789 } else {
3790 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3791 << "Tag " << tag << " found at security level " << entry.securityLevel;
3792 }
Selene Huang31ab4042020-04-29 04:22:39 -07003793 }
3794 }
3795
3796 void CheckOrigin() {
3797 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003798 // Origin isn't a crypto param, but it always lives with them.
3799 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003800 }
3801};
3802
3803/*
3804 * ImportKeyTest.RsaSuccess
3805 *
3806 * Verifies that importing and using an RSA key pair works correctly.
3807 */
3808TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003809 uint32_t key_size;
3810 string key;
3811
3812 if (SecLevel() == SecurityLevel::STRONGBOX) {
3813 key_size = 2048;
3814 key = rsa_2048_key;
3815 } else {
3816 key_size = 1024;
3817 key = rsa_key;
3818 }
3819
Selene Huang31ab4042020-04-29 04:22:39 -07003820 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3821 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003822 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003823 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003824 .Padding(PaddingMode::RSA_PSS)
3825 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003826 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003827
3828 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003829 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003830 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3831 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3832 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3833 CheckOrigin();
3834
3835 string message(1024 / 8, 'a');
3836 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3837 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003838 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003839}
3840
3841/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003842 * ImportKeyTest.RsaSuccessWithoutParams
3843 *
3844 * Verifies that importing and using an RSA key pair without specifying parameters
3845 * works correctly.
3846 */
3847TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3848 uint32_t key_size;
3849 string key;
3850
3851 if (SecLevel() == SecurityLevel::STRONGBOX) {
3852 key_size = 2048;
3853 key = rsa_2048_key;
3854 } else {
3855 key_size = 1024;
3856 key = rsa_key;
3857 }
3858
3859 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3860 .Authorization(TAG_NO_AUTH_REQUIRED)
3861 .SigningKey()
3862 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3863 .Digest(Digest::SHA_2_256)
3864 .Padding(PaddingMode::RSA_PSS)
3865 .SetDefaultValidity(),
3866 KeyFormat::PKCS8, key));
3867
3868 // Key size and public exponent are determined from the imported key material.
3869 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3870 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3871
3872 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3873 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3874 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3875 CheckOrigin();
3876
3877 string message(1024 / 8, 'a');
3878 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3879 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003880 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003881}
3882
3883/*
Selene Huang31ab4042020-04-29 04:22:39 -07003884 * ImportKeyTest.RsaKeySizeMismatch
3885 *
3886 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3887 * correct way.
3888 */
3889TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3890 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3891 ImportKey(AuthorizationSetBuilder()
3892 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3893 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003894 .Padding(PaddingMode::NONE)
3895 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003896 KeyFormat::PKCS8, rsa_key));
3897}
3898
3899/*
3900 * ImportKeyTest.RsaPublicExponentMismatch
3901 *
3902 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3903 * fails in the correct way.
3904 */
3905TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3906 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3907 ImportKey(AuthorizationSetBuilder()
3908 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3909 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003910 .Padding(PaddingMode::NONE)
3911 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003912 KeyFormat::PKCS8, rsa_key));
3913}
3914
3915/*
David Drysdalee60248c2021-10-04 12:54:13 +01003916 * ImportKeyTest.RsaAttestMultiPurposeFail
3917 *
3918 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3919 */
3920TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00003921 if (AidlVersion() < 2) {
3922 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
3923 // with other key purposes. However, this was not checked at the time
3924 // so we can only be strict about checking this for implementations of KeyMint
3925 // version 2 and above.
3926 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
3927 }
David Drysdalee60248c2021-10-04 12:54:13 +01003928 uint32_t key_size = 2048;
3929 string key = rsa_2048_key;
3930
3931 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3932 ImportKey(AuthorizationSetBuilder()
3933 .Authorization(TAG_NO_AUTH_REQUIRED)
3934 .RsaSigningKey(key_size, 65537)
3935 .AttestKey()
3936 .Digest(Digest::SHA_2_256)
3937 .Padding(PaddingMode::RSA_PSS)
3938 .SetDefaultValidity(),
3939 KeyFormat::PKCS8, key));
3940}
3941
3942/*
Selene Huang31ab4042020-04-29 04:22:39 -07003943 * ImportKeyTest.EcdsaSuccess
3944 *
3945 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3946 */
3947TEST_P(ImportKeyTest, EcdsaSuccess) {
3948 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3949 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003950 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003951 .Digest(Digest::SHA_2_256)
3952 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003953 KeyFormat::PKCS8, ec_256_key));
3954
3955 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003956 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3957 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3958
3959 CheckOrigin();
3960
3961 string message(32, 'a');
3962 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3963 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003964 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003965}
3966
3967/*
3968 * ImportKeyTest.EcdsaP256RFC5915Success
3969 *
3970 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3971 * correctly.
3972 */
3973TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3974 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3975 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003976 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003977 .Digest(Digest::SHA_2_256)
3978 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003979 KeyFormat::PKCS8, ec_256_key_rfc5915));
3980
3981 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003982 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3983 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3984
3985 CheckOrigin();
3986
3987 string message(32, 'a');
3988 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3989 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003990 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003991}
3992
3993/*
3994 * ImportKeyTest.EcdsaP256SEC1Success
3995 *
3996 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
3997 */
3998TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
3999 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4000 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004001 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004002 .Digest(Digest::SHA_2_256)
4003 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004004 KeyFormat::PKCS8, ec_256_key_sec1));
4005
4006 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004007 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4008 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4009
4010 CheckOrigin();
4011
4012 string message(32, 'a');
4013 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4014 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004015 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004016}
4017
4018/*
4019 * ImportKeyTest.Ecdsa521Success
4020 *
4021 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4022 */
4023TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004024 if (SecLevel() == SecurityLevel::STRONGBOX) {
4025 GTEST_SKIP() << "Test not applicable to StrongBox device";
4026 }
Selene Huang31ab4042020-04-29 04:22:39 -07004027 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4028 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004029 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004030 .Digest(Digest::SHA_2_256)
4031 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004032 KeyFormat::PKCS8, ec_521_key));
4033
4034 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004035 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4036 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4037 CheckOrigin();
4038
4039 string message(32, 'a');
4040 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4041 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004042 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004043}
4044
4045/*
Selene Huang31ab4042020-04-29 04:22:39 -07004046 * ImportKeyTest.EcdsaCurveMismatch
4047 *
4048 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4049 * the correct way.
4050 */
4051TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4052 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4053 ImportKey(AuthorizationSetBuilder()
4054 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004055 .Digest(Digest::NONE)
4056 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004057 KeyFormat::PKCS8, ec_256_key));
4058}
4059
4060/*
David Drysdalee60248c2021-10-04 12:54:13 +01004061 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4062 *
4063 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4064 */
4065TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004066 if (AidlVersion() < 2) {
4067 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4068 // with other key purposes. However, this was not checked at the time
4069 // so we can only be strict about checking this for implementations of KeyMint
4070 // version 2 and above.
4071 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4072 }
David Drysdalee60248c2021-10-04 12:54:13 +01004073 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4074 ImportKey(AuthorizationSetBuilder()
4075 .Authorization(TAG_NO_AUTH_REQUIRED)
4076 .EcdsaSigningKey(EcCurve::P_256)
4077 .AttestKey()
4078 .Digest(Digest::SHA_2_256)
4079 .SetDefaultValidity(),
4080 KeyFormat::PKCS8, ec_256_key));
4081}
4082
4083/*
David Drysdale42fe1892021-10-14 14:43:46 +01004084 * ImportKeyTest.Ed25519RawSuccess
4085 *
4086 * Verifies that importing and using a raw Ed25519 private key works correctly.
4087 */
4088TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4089 if (!Curve25519Supported()) {
4090 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4091 }
4092
4093 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4094 .Authorization(TAG_NO_AUTH_REQUIRED)
4095 .EcdsaSigningKey(EcCurve::CURVE_25519)
4096 .Digest(Digest::NONE)
4097 .SetDefaultValidity(),
4098 KeyFormat::RAW, ed25519_key));
4099 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4100 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4101 CheckOrigin();
4102
4103 // The returned cert should hold the correct public key.
4104 ASSERT_GT(cert_chain_.size(), 0);
4105 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4106 ASSERT_NE(kmKeyCert, nullptr);
4107 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4108 ASSERT_NE(kmPubKey.get(), nullptr);
4109 size_t kmPubKeySize = 32;
4110 uint8_t kmPubKeyData[32];
4111 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4112 ASSERT_EQ(kmPubKeySize, 32);
4113 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4114
4115 string message(32, 'a');
4116 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4117 string signature = SignMessage(message, params);
4118 LocalVerifyMessage(message, signature, params);
4119}
4120
4121/*
4122 * ImportKeyTest.Ed25519Pkcs8Success
4123 *
4124 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4125 */
4126TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4127 if (!Curve25519Supported()) {
4128 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4129 }
4130
4131 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4132 .Authorization(TAG_NO_AUTH_REQUIRED)
4133 .EcdsaSigningKey(EcCurve::CURVE_25519)
4134 .Digest(Digest::NONE)
4135 .SetDefaultValidity(),
4136 KeyFormat::PKCS8, ed25519_pkcs8_key));
4137 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4138 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4139 CheckOrigin();
4140
4141 // The returned cert should hold the correct public key.
4142 ASSERT_GT(cert_chain_.size(), 0);
4143 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4144 ASSERT_NE(kmKeyCert, nullptr);
4145 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4146 ASSERT_NE(kmPubKey.get(), nullptr);
4147 size_t kmPubKeySize = 32;
4148 uint8_t kmPubKeyData[32];
4149 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4150 ASSERT_EQ(kmPubKeySize, 32);
4151 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4152
4153 string message(32, 'a');
4154 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4155 string signature = SignMessage(message, params);
4156 LocalVerifyMessage(message, signature, params);
4157}
4158
4159/*
4160 * ImportKeyTest.Ed25519CurveMismatch
4161 *
4162 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4163 * the correct way.
4164 */
4165TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
4166 if (!Curve25519Supported()) {
4167 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4168 }
4169
4170 ASSERT_NE(ErrorCode::OK,
4171 ImportKey(AuthorizationSetBuilder()
4172 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4173 .Digest(Digest::NONE)
4174 .SetDefaultValidity(),
4175 KeyFormat::RAW, ed25519_key));
4176}
4177
4178/*
4179 * ImportKeyTest.Ed25519FormatMismatch
4180 *
4181 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4182 */
4183TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4184 if (!Curve25519Supported()) {
4185 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4186 }
4187
4188 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4189 .EcdsaSigningKey(EcCurve::CURVE_25519)
4190 .Digest(Digest::NONE)
4191 .SetDefaultValidity(),
4192 KeyFormat::PKCS8, ed25519_key));
4193 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4194 .EcdsaSigningKey(EcCurve::CURVE_25519)
4195 .Digest(Digest::NONE)
4196 .SetDefaultValidity(),
4197 KeyFormat::RAW, ed25519_pkcs8_key));
4198}
4199
4200/*
4201 * ImportKeyTest.Ed25519PurposeMismatch
4202 *
4203 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4204 */
4205TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4206 if (!Curve25519Supported()) {
4207 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4208 }
4209
4210 // Can't have both SIGN and ATTEST_KEY
4211 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4212 .EcdsaSigningKey(EcCurve::CURVE_25519)
4213 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4214 .Digest(Digest::NONE)
4215 .SetDefaultValidity(),
4216 KeyFormat::RAW, ed25519_key));
4217 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4218 // PKCS#8 format and so includes an OID).
4219 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4220 .EcdsaKey(EcCurve::CURVE_25519)
4221 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4222 .Digest(Digest::NONE)
4223 .SetDefaultValidity(),
4224 KeyFormat::PKCS8, ed25519_pkcs8_key));
4225}
4226
4227/*
4228 * ImportKeyTest.X25519RawSuccess
4229 *
4230 * Verifies that importing and using a raw X25519 private key works correctly.
4231 */
4232TEST_P(ImportKeyTest, X25519RawSuccess) {
4233 if (!Curve25519Supported()) {
4234 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4235 }
4236
4237 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4238 .Authorization(TAG_NO_AUTH_REQUIRED)
4239 .EcdsaKey(EcCurve::CURVE_25519)
4240 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4241 .SetDefaultValidity(),
4242 KeyFormat::RAW, x25519_key));
4243
4244 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4245 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4246 CheckOrigin();
4247}
4248
4249/*
4250 * ImportKeyTest.X25519Pkcs8Success
4251 *
4252 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4253 */
4254TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4255 if (!Curve25519Supported()) {
4256 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4257 }
4258
4259 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4260 .Authorization(TAG_NO_AUTH_REQUIRED)
4261 .EcdsaKey(EcCurve::CURVE_25519)
4262 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4263 .SetDefaultValidity(),
4264 KeyFormat::PKCS8, x25519_pkcs8_key));
4265
4266 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4267 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4268 CheckOrigin();
4269}
4270
4271/*
4272 * ImportKeyTest.X25519CurveMismatch
4273 *
4274 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4275 * the correct way.
4276 */
4277TEST_P(ImportKeyTest, X25519CurveMismatch) {
4278 if (!Curve25519Supported()) {
4279 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4280 }
4281
4282 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4283 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4284 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4285 .SetDefaultValidity(),
4286 KeyFormat::RAW, x25519_key));
4287}
4288
4289/*
4290 * ImportKeyTest.X25519FormatMismatch
4291 *
4292 * Verifies that importing an X25519 key with an invalid format fails.
4293 */
4294TEST_P(ImportKeyTest, X25519FormatMismatch) {
4295 if (!Curve25519Supported()) {
4296 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4297 }
4298
4299 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4300 .EcdsaKey(EcCurve::CURVE_25519)
4301 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4302 .SetDefaultValidity(),
4303 KeyFormat::PKCS8, x25519_key));
4304 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4305 .EcdsaKey(EcCurve::CURVE_25519)
4306 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4307 .SetDefaultValidity(),
4308 KeyFormat::RAW, x25519_pkcs8_key));
4309}
4310
4311/*
4312 * ImportKeyTest.X25519PurposeMismatch
4313 *
4314 * Verifies that importing an X25519 key pair with an invalid format fails.
4315 */
4316TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4317 if (!Curve25519Supported()) {
4318 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4319 }
4320
4321 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4322 .EcdsaKey(EcCurve::CURVE_25519)
4323 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4324 .SetDefaultValidity(),
4325 KeyFormat::PKCS8, x25519_pkcs8_key));
4326 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4327 .EcdsaSigningKey(EcCurve::CURVE_25519)
4328 .SetDefaultValidity(),
4329 KeyFormat::PKCS8, x25519_pkcs8_key));
4330}
4331
4332/*
Selene Huang31ab4042020-04-29 04:22:39 -07004333 * ImportKeyTest.AesSuccess
4334 *
4335 * Verifies that importing and using an AES key works.
4336 */
4337TEST_P(ImportKeyTest, AesSuccess) {
4338 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4339 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4340 .Authorization(TAG_NO_AUTH_REQUIRED)
4341 .AesEncryptionKey(key.size() * 8)
4342 .EcbMode()
4343 .Padding(PaddingMode::PKCS7),
4344 KeyFormat::RAW, key));
4345
4346 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4347 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4348 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4349 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4350 CheckOrigin();
4351
4352 string message = "Hello World!";
4353 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4354 string ciphertext = EncryptMessage(message, params);
4355 string plaintext = DecryptMessage(ciphertext, params);
4356 EXPECT_EQ(message, plaintext);
4357}
4358
4359/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004360 * ImportKeyTest.AesFailure
4361 *
4362 * Verifies that importing an invalid AES key fails.
4363 */
4364TEST_P(ImportKeyTest, AesFailure) {
4365 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4366 uint32_t bitlen = key.size() * 8;
4367 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004368 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004369 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004370 .Authorization(TAG_NO_AUTH_REQUIRED)
4371 .AesEncryptionKey(key_size)
4372 .EcbMode()
4373 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004374 KeyFormat::RAW, key);
4375 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004376 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4377 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004378 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004379
4380 // Explicit key size matches that of the provided key, but it's not a valid size.
4381 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4382 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4383 ImportKey(AuthorizationSetBuilder()
4384 .Authorization(TAG_NO_AUTH_REQUIRED)
4385 .AesEncryptionKey(long_key.size() * 8)
4386 .EcbMode()
4387 .Padding(PaddingMode::PKCS7),
4388 KeyFormat::RAW, long_key));
4389 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4390 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4391 ImportKey(AuthorizationSetBuilder()
4392 .Authorization(TAG_NO_AUTH_REQUIRED)
4393 .AesEncryptionKey(short_key.size() * 8)
4394 .EcbMode()
4395 .Padding(PaddingMode::PKCS7),
4396 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004397}
4398
4399/*
4400 * ImportKeyTest.TripleDesSuccess
4401 *
4402 * Verifies that importing and using a 3DES key works.
4403 */
4404TEST_P(ImportKeyTest, TripleDesSuccess) {
4405 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4406 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4407 .Authorization(TAG_NO_AUTH_REQUIRED)
4408 .TripleDesEncryptionKey(168)
4409 .EcbMode()
4410 .Padding(PaddingMode::PKCS7),
4411 KeyFormat::RAW, key));
4412
4413 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4414 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4415 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4416 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4417 CheckOrigin();
4418
4419 string message = "Hello World!";
4420 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4421 string ciphertext = EncryptMessage(message, params);
4422 string plaintext = DecryptMessage(ciphertext, params);
4423 EXPECT_EQ(message, plaintext);
4424}
4425
4426/*
4427 * ImportKeyTest.TripleDesFailure
4428 *
4429 * Verifies that importing an invalid 3DES key fails.
4430 */
4431TEST_P(ImportKeyTest, TripleDesFailure) {
4432 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004433 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004434 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004435 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004436 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004437 .Authorization(TAG_NO_AUTH_REQUIRED)
4438 .TripleDesEncryptionKey(key_size)
4439 .EcbMode()
4440 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004441 KeyFormat::RAW, key);
4442 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004443 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4444 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004445 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004446 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004447 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004448 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4449 ImportKey(AuthorizationSetBuilder()
4450 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004451 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004452 .EcbMode()
4453 .Padding(PaddingMode::PKCS7),
4454 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004455 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004456 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4457 ImportKey(AuthorizationSetBuilder()
4458 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004459 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004460 .EcbMode()
4461 .Padding(PaddingMode::PKCS7),
4462 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004463}
4464
4465/*
4466 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004467 *
4468 * Verifies that importing and using an HMAC key works.
4469 */
4470TEST_P(ImportKeyTest, HmacKeySuccess) {
4471 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4472 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4473 .Authorization(TAG_NO_AUTH_REQUIRED)
4474 .HmacKey(key.size() * 8)
4475 .Digest(Digest::SHA_2_256)
4476 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4477 KeyFormat::RAW, key));
4478
4479 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4480 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4481 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4482 CheckOrigin();
4483
4484 string message = "Hello World!";
4485 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4486 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4487}
4488
4489INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4490
4491auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004492 // IKeyMintDevice.aidl
4493 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4494 "020100" // INTEGER length 1 value 0x00 (version)
4495 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4496 "934bf94e2aa28a3f83c9f79297250262"
4497 "fbe3276b5a1c91159bbfa3ef8957aac8"
4498 "4b59b30b455a79c2973480823d8b3863"
4499 "c3deef4a8e243590268d80e18751a0e1"
4500 "30f67ce6a1ace9f79b95e097474febc9"
4501 "81195b1d13a69086c0863f66a7b7fdb4"
4502 "8792227b1ac5e2489febdf087ab54864"
4503 "83033a6f001ca5d1ec1e27f5c30f4cec"
4504 "2642074a39ae68aee552e196627a8e3d"
4505 "867e67a8c01b11e75f13cca0a97ab668"
4506 "b50cda07a8ecb7cd8e3dd7009c963653"
4507 "4f6f239cffe1fc8daa466f78b676c711"
4508 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4509 "99b801597d5220e307eaa5bee507fb94"
4510 "d1fa69f9e519b2de315bac92c36f2ea1"
4511 "fa1df4478c0ddedeae8c70e0233cd098"
4512 "040c" // OCTET STRING length 0x0c (initializationVector)
4513 "d796b02c370f1fa4cc0124f1"
4514 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4515 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4516 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4517 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4518 "3106" // SET length 0x06
4519 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4520 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4521 // } end SET
4522 // } end [1]
4523 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4524 "020120" // INTEGER length 1 value 0x20 (AES)
4525 // } end [2]
4526 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4527 "02020100" // INTEGER length 2 value 0x100
4528 // } end [3]
4529 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4530 "3103" // SET length 0x03 {
4531 "020101" // INTEGER length 1 value 0x01 (ECB)
4532 // } end SET
4533 // } end [4]
4534 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4535 "3103" // SET length 0x03 {
4536 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4537 // } end SET
4538 // } end [5]
4539 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4540 // (noAuthRequired)
4541 "0500" // NULL
4542 // } end [503]
4543 // } end SEQUENCE (AuthorizationList)
4544 // } end SEQUENCE (KeyDescription)
4545 "0420" // OCTET STRING length 0x20 (encryptedKey)
4546 "ccd540855f833a5e1480bfd2d36faf3a"
4547 "eee15df5beabe2691bc82dde2a7aa910"
4548 "0410" // OCTET STRING length 0x10 (tag)
4549 "64c9f689c60ff6223ab6e6999e0eb6e5"
4550 // } SEQUENCE (SecureKeyWrapper)
4551);
Selene Huang31ab4042020-04-29 04:22:39 -07004552
4553auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004554 // IKeyMintDevice.aidl
4555 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4556 "020100" // INTEGER length 1 value 0x00 (version)
4557 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4558 "aad93ed5924f283b4bb5526fbe7a1412"
4559 "f9d9749ec30db9062b29e574a8546f33"
4560 "c88732452f5b8e6a391ee76c39ed1712"
4561 "c61d8df6213dec1cffbc17a8c6d04c7b"
4562 "30893d8daa9b2015213e219468215532"
4563 "07f8f9931c4caba23ed3bee28b36947e"
4564 "47f10e0a5c3dc51c988a628daad3e5e1"
4565 "f4005e79c2d5a96c284b4b8d7e4948f3"
4566 "31e5b85dd5a236f85579f3ea1d1b8484"
4567 "87470bdb0ab4f81a12bee42c99fe0df4"
4568 "bee3759453e69ad1d68a809ce06b949f"
4569 "7694a990429b2fe81e066ff43e56a216"
4570 "02db70757922a4bcc23ab89f1e35da77"
4571 "586775f423e519c2ea394caf48a28d0c"
4572 "8020f1dcf6b3a68ec246f615ae96dae9"
4573 "a079b1f6eb959033c1af5c125fd94168"
4574 "040c" // OCTET STRING length 0x0c (initializationVector)
4575 "6d9721d08589581ab49204a3"
4576 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4577 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4578 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4579 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4580 "3106" // SET length 0x06
4581 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4582 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4583 // } end SET
4584 // } end [1]
4585 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4586 "020120" // INTEGER length 1 value 0x20 (AES)
4587 // } end [2]
4588 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4589 "02020100" // INTEGER length 2 value 0x100
4590 // } end [3]
4591 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4592 "3103" // SET length 0x03 {
4593 "020101" // INTEGER length 1 value 0x01 (ECB)
4594 // } end SET
4595 // } end [4]
4596 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4597 "3103" // SET length 0x03 {
4598 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4599 // } end SET
4600 // } end [5]
4601 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4602 // (noAuthRequired)
4603 "0500" // NULL
4604 // } end [503]
4605 // } end SEQUENCE (AuthorizationList)
4606 // } end SEQUENCE (KeyDescription)
4607 "0420" // OCTET STRING length 0x20 (encryptedKey)
4608 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4609 "c20d1f99a9a024a76f35c8e2cab9b68d"
4610 "0410" // OCTET STRING length 0x10 (tag)
4611 "2560c70109ae67c030f00b98b512a670"
4612 // } SEQUENCE (SecureKeyWrapper)
4613);
Selene Huang31ab4042020-04-29 04:22:39 -07004614
4615auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004616 // RFC 5208 s5
4617 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4618 "020100" // INTEGER length 1 value 0x00 (version)
4619 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4620 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4621 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4622 "0500" // NULL (parameters)
4623 // } SEQUENCE (AlgorithmIdentifier)
4624 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4625 // RFC 8017 A.1.2
4626 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4627 "020100" // INTEGER length 1 value 0x00 (version)
4628 "02820101" // INTEGER length 0x0101 (modulus) value...
4629 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4630 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4631 "7b06e673a837313d56b1c725150a3fef" // 0x30
4632 "86acbddc41bb759c2854eae32d35841e" // 0x40
4633 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4634 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4635 "312d7bd5921ffaea1347c157406fef71" // 0x70
4636 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4637 "f4645c11f5c1374c3886427411c44979" // 0x90
4638 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4639 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4640 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4641 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4642 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4643 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4644 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4645 "55" // 0x101
4646 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4647 "02820100" // INTEGER length 0x100 (privateExponent) value...
4648 "431447b6251908112b1ee76f99f3711a" // 0x10
4649 "52b6630960046c2de70de188d833f8b8" // 0x20
4650 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4651 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4652 "e710b630a03adc683b5d2c43080e52be" // 0x50
4653 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4654 "822bccff087d63c940ba8a45f670feb2" // 0x70
4655 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4656 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4657 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4658 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4659 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4660 "52659d5a5ba05b663737a8696281865b" // 0xd0
4661 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4662 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4663 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4664 "028181" // INTEGER length 0x81 (prime1) value...
4665 "00de392e18d682c829266cc3454e1d61" // 0x10
4666 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4667 "ff841be5bac82a164c5970007047b8c5" // 0x30
4668 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4669 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4670 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4671 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4672 "9e91346130748a6e3c124f9149d71c74" // 0x80
4673 "35"
4674 "028181" // INTEGER length 0x81 (prime2) value...
4675 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4676 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4677 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4678 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4679 "9ed39a2d934c880440aed8832f984316" // 0x50
4680 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4681 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4682 "b880677c068e1be936e81288815252a8" // 0x80
4683 "a1"
4684 "028180" // INTEGER length 0x80 (exponent1) value...
4685 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4686 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4687 "5a063212a4f105a3764743e53281988a" // 0x30
4688 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4689 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4690 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4691 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4692 "4719d6e2b9439823719cd08bcd031781" // 0x80
4693 "028181" // INTEGER length 0x81 (exponent2) value...
4694 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4695 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4696 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4697 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4698 "1254186af30b22c10582a8a43e34fe94" // 0x50
4699 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4700 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4701 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4702 "61"
4703 "028181" // INTEGER length 0x81 (coefficient) value...
4704 "00c931617c77829dfb1270502be9195c" // 0x10
4705 "8f2830885f57dba869536811e6864236" // 0x20
4706 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4707 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4708 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4709 "959356210723287b0affcc9f727044d4" // 0x60
4710 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4711 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4712 "22"
4713 // } SEQUENCE
4714 // } SEQUENCE ()
4715);
Selene Huang31ab4042020-04-29 04:22:39 -07004716
4717string zero_masking_key =
4718 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4719string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4720
4721class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4722
4723TEST_P(ImportWrappedKeyTest, Success) {
4724 auto wrapping_key_desc = AuthorizationSetBuilder()
4725 .RsaEncryptionKey(2048, 65537)
4726 .Digest(Digest::SHA_2_256)
4727 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004728 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4729 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004730
4731 ASSERT_EQ(ErrorCode::OK,
4732 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4733 AuthorizationSetBuilder()
4734 .Digest(Digest::SHA_2_256)
4735 .Padding(PaddingMode::RSA_OAEP)));
4736
4737 string message = "Hello World!";
4738 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4739 string ciphertext = EncryptMessage(message, params);
4740 string plaintext = DecryptMessage(ciphertext, params);
4741 EXPECT_EQ(message, plaintext);
4742}
4743
David Drysdaled2cc8c22021-04-15 13:29:45 +01004744/*
4745 * ImportWrappedKeyTest.SuccessSidsIgnored
4746 *
4747 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4748 * include Tag:USER_SECURE_ID.
4749 */
4750TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4751 auto wrapping_key_desc = AuthorizationSetBuilder()
4752 .RsaEncryptionKey(2048, 65537)
4753 .Digest(Digest::SHA_2_256)
4754 .Padding(PaddingMode::RSA_OAEP)
4755 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4756 .SetDefaultValidity();
4757
4758 int64_t password_sid = 42;
4759 int64_t biometric_sid = 24;
4760 ASSERT_EQ(ErrorCode::OK,
4761 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4762 AuthorizationSetBuilder()
4763 .Digest(Digest::SHA_2_256)
4764 .Padding(PaddingMode::RSA_OAEP),
4765 password_sid, biometric_sid));
4766
4767 string message = "Hello World!";
4768 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4769 string ciphertext = EncryptMessage(message, params);
4770 string plaintext = DecryptMessage(ciphertext, params);
4771 EXPECT_EQ(message, plaintext);
4772}
4773
Selene Huang31ab4042020-04-29 04:22:39 -07004774TEST_P(ImportWrappedKeyTest, SuccessMasked) {
4775 auto wrapping_key_desc = AuthorizationSetBuilder()
4776 .RsaEncryptionKey(2048, 65537)
4777 .Digest(Digest::SHA_2_256)
4778 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004779 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4780 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004781
4782 ASSERT_EQ(ErrorCode::OK,
4783 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
4784 AuthorizationSetBuilder()
4785 .Digest(Digest::SHA_2_256)
4786 .Padding(PaddingMode::RSA_OAEP)));
4787}
4788
4789TEST_P(ImportWrappedKeyTest, WrongMask) {
4790 auto wrapping_key_desc = AuthorizationSetBuilder()
4791 .RsaEncryptionKey(2048, 65537)
4792 .Digest(Digest::SHA_2_256)
4793 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004794 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4795 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004796
4797 ASSERT_EQ(
4798 ErrorCode::VERIFICATION_FAILED,
4799 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4800 AuthorizationSetBuilder()
4801 .Digest(Digest::SHA_2_256)
4802 .Padding(PaddingMode::RSA_OAEP)));
4803}
4804
4805TEST_P(ImportWrappedKeyTest, WrongPurpose) {
4806 auto wrapping_key_desc = AuthorizationSetBuilder()
4807 .RsaEncryptionKey(2048, 65537)
4808 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004809 .Padding(PaddingMode::RSA_OAEP)
4810 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004811
4812 ASSERT_EQ(
4813 ErrorCode::INCOMPATIBLE_PURPOSE,
4814 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4815 AuthorizationSetBuilder()
4816 .Digest(Digest::SHA_2_256)
4817 .Padding(PaddingMode::RSA_OAEP)));
4818}
4819
David Drysdaled2cc8c22021-04-15 13:29:45 +01004820TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
4821 auto wrapping_key_desc = AuthorizationSetBuilder()
4822 .RsaEncryptionKey(2048, 65537)
4823 .Digest(Digest::SHA_2_256)
4824 .Padding(PaddingMode::RSA_PSS)
4825 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4826 .SetDefaultValidity();
4827
4828 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
4829 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4830 AuthorizationSetBuilder()
4831 .Digest(Digest::SHA_2_256)
4832 .Padding(PaddingMode::RSA_OAEP)));
4833}
4834
4835TEST_P(ImportWrappedKeyTest, WrongDigest) {
4836 auto wrapping_key_desc = AuthorizationSetBuilder()
4837 .RsaEncryptionKey(2048, 65537)
4838 .Digest(Digest::SHA_2_512)
4839 .Padding(PaddingMode::RSA_OAEP)
4840 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4841 .SetDefaultValidity();
4842
4843 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
4844 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4845 AuthorizationSetBuilder()
4846 .Digest(Digest::SHA_2_256)
4847 .Padding(PaddingMode::RSA_OAEP)));
4848}
4849
Selene Huang31ab4042020-04-29 04:22:39 -07004850INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
4851
4852typedef KeyMintAidlTestBase EncryptionOperationsTest;
4853
4854/*
4855 * EncryptionOperationsTest.RsaNoPaddingSuccess
4856 *
David Drysdale59cae642021-05-12 13:52:03 +01004857 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004858 */
4859TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00004860 for (uint64_t exponent : ValidExponents()) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01004861 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4862 .Authorization(TAG_NO_AUTH_REQUIRED)
4863 .RsaEncryptionKey(2048, exponent)
4864 .Padding(PaddingMode::NONE)
4865 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004866
David Drysdaled2cc8c22021-04-15 13:29:45 +01004867 string message = string(2048 / 8, 'a');
4868 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004869 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004870 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004871
David Drysdale59cae642021-05-12 13:52:03 +01004872 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004873 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004874
David Drysdaled2cc8c22021-04-15 13:29:45 +01004875 // Unpadded RSA is deterministic
4876 EXPECT_EQ(ciphertext1, ciphertext2);
4877
4878 CheckedDeleteKey();
4879 }
Selene Huang31ab4042020-04-29 04:22:39 -07004880}
4881
4882/*
4883 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4884 *
David Drysdale59cae642021-05-12 13:52:03 +01004885 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004886 */
4887TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
4888 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4889 .Authorization(TAG_NO_AUTH_REQUIRED)
4890 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004891 .Padding(PaddingMode::NONE)
4892 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004893
4894 string message = "1";
4895 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4896
David Drysdale59cae642021-05-12 13:52:03 +01004897 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004898 EXPECT_EQ(2048U / 8, ciphertext.size());
4899
4900 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4901 string plaintext = DecryptMessage(ciphertext, params);
4902
4903 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004904}
4905
4906/*
Selene Huang31ab4042020-04-29 04:22:39 -07004907 * EncryptionOperationsTest.RsaOaepSuccess
4908 *
David Drysdale59cae642021-05-12 13:52:03 +01004909 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004910 */
4911TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4912 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4913
4914 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01004915 ASSERT_EQ(ErrorCode::OK,
4916 GenerateKey(AuthorizationSetBuilder()
4917 .Authorization(TAG_NO_AUTH_REQUIRED)
4918 .RsaEncryptionKey(key_size, 65537)
4919 .Padding(PaddingMode::RSA_OAEP)
4920 .Digest(digests)
4921 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4922 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004923
4924 string message = "Hello";
4925
4926 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004927 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4928
4929 auto params = AuthorizationSetBuilder()
4930 .Digest(digest)
4931 .Padding(PaddingMode::RSA_OAEP)
4932 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4933 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004934 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4935 EXPECT_EQ(key_size / 8, ciphertext1.size());
4936
David Drysdale59cae642021-05-12 13:52:03 +01004937 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004938 EXPECT_EQ(key_size / 8, ciphertext2.size());
4939
4940 // OAEP randomizes padding so every result should be different (with astronomically high
4941 // probability).
4942 EXPECT_NE(ciphertext1, ciphertext2);
4943
4944 string plaintext1 = DecryptMessage(ciphertext1, params);
4945 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4946 string plaintext2 = DecryptMessage(ciphertext2, params);
4947 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4948
4949 // Decrypting corrupted ciphertext should fail.
4950 size_t offset_to_corrupt = random() % ciphertext1.size();
4951 char corrupt_byte;
4952 do {
4953 corrupt_byte = static_cast<char>(random() % 256);
4954 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4955 ciphertext1[offset_to_corrupt] = corrupt_byte;
4956
4957 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4958 string result;
4959 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4960 EXPECT_EQ(0U, result.size());
4961 }
4962}
4963
4964/*
4965 * EncryptionOperationsTest.RsaOaepInvalidDigest
4966 *
David Drysdale59cae642021-05-12 13:52:03 +01004967 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004968 * without a digest.
4969 */
4970TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4971 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4972 .Authorization(TAG_NO_AUTH_REQUIRED)
4973 .RsaEncryptionKey(2048, 65537)
4974 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004975 .Digest(Digest::NONE)
4976 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004977
4978 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004979 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07004980}
4981
4982/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01004983 * EncryptionOperationsTest.RsaOaepInvalidPadding
4984 *
David Drysdale59cae642021-05-12 13:52:03 +01004985 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01004986 * with a padding value that is only suitable for signing/verifying.
4987 */
4988TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
4989 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4990 .Authorization(TAG_NO_AUTH_REQUIRED)
4991 .RsaEncryptionKey(2048, 65537)
4992 .Padding(PaddingMode::RSA_PSS)
4993 .Digest(Digest::NONE)
4994 .SetDefaultValidity()));
4995
4996 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004997 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01004998}
4999
5000/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005001 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005002 *
David Drysdale59cae642021-05-12 13:52:03 +01005003 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005004 * with a different digest than was used to encrypt.
5005 */
5006TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005007 if (SecLevel() == SecurityLevel::STRONGBOX) {
5008 GTEST_SKIP() << "Test not applicable to StrongBox device";
5009 }
Selene Huang31ab4042020-04-29 04:22:39 -07005010
5011 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5012 .Authorization(TAG_NO_AUTH_REQUIRED)
5013 .RsaEncryptionKey(1024, 65537)
5014 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005015 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5016 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005017 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005018 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005019 message,
5020 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5021
5022 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5023 .Digest(Digest::SHA_2_256)
5024 .Padding(PaddingMode::RSA_OAEP)));
5025 string result;
5026 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5027 EXPECT_EQ(0U, result.size());
5028}
5029
5030/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005031 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5032 *
David Drysdale59cae642021-05-12 13:52:03 +01005033 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005034 * digests.
5035 */
5036TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5037 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5038
5039 size_t key_size = 2048; // Need largish key for SHA-512 test.
5040 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5041 .OaepMGFDigest(digests)
5042 .Authorization(TAG_NO_AUTH_REQUIRED)
5043 .RsaEncryptionKey(key_size, 65537)
5044 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005045 .Digest(Digest::SHA_2_256)
5046 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005047
5048 string message = "Hello";
5049
5050 for (auto digest : digests) {
5051 auto params = AuthorizationSetBuilder()
5052 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5053 .Digest(Digest::SHA_2_256)
5054 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005055 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005056 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5057 EXPECT_EQ(key_size / 8, ciphertext1.size());
5058
David Drysdale59cae642021-05-12 13:52:03 +01005059 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005060 EXPECT_EQ(key_size / 8, ciphertext2.size());
5061
5062 // OAEP randomizes padding so every result should be different (with astronomically high
5063 // probability).
5064 EXPECT_NE(ciphertext1, ciphertext2);
5065
5066 string plaintext1 = DecryptMessage(ciphertext1, params);
5067 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5068 string plaintext2 = DecryptMessage(ciphertext2, params);
5069 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5070
5071 // Decrypting corrupted ciphertext should fail.
5072 size_t offset_to_corrupt = random() % ciphertext1.size();
5073 char corrupt_byte;
5074 do {
5075 corrupt_byte = static_cast<char>(random() % 256);
5076 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5077 ciphertext1[offset_to_corrupt] = corrupt_byte;
5078
5079 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5080 string result;
5081 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5082 EXPECT_EQ(0U, result.size());
5083 }
5084}
5085
5086/*
5087 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5088 *
David Drysdale59cae642021-05-12 13:52:03 +01005089 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005090 * with incompatible MGF digest.
5091 */
5092TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5093 ASSERT_EQ(ErrorCode::OK,
5094 GenerateKey(AuthorizationSetBuilder()
5095 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5096 .Authorization(TAG_NO_AUTH_REQUIRED)
5097 .RsaEncryptionKey(2048, 65537)
5098 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005099 .Digest(Digest::SHA_2_256)
5100 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005101 string message = "Hello World!";
5102
5103 auto params = AuthorizationSetBuilder()
5104 .Padding(PaddingMode::RSA_OAEP)
5105 .Digest(Digest::SHA_2_256)
5106 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005107 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005108}
5109
5110/*
5111 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5112 *
5113 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5114 * with unsupported MGF digest.
5115 */
5116TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5117 ASSERT_EQ(ErrorCode::OK,
5118 GenerateKey(AuthorizationSetBuilder()
5119 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5120 .Authorization(TAG_NO_AUTH_REQUIRED)
5121 .RsaEncryptionKey(2048, 65537)
5122 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005123 .Digest(Digest::SHA_2_256)
5124 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005125 string message = "Hello World!";
5126
5127 auto params = AuthorizationSetBuilder()
5128 .Padding(PaddingMode::RSA_OAEP)
5129 .Digest(Digest::SHA_2_256)
5130 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005131 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005132}
5133
5134/*
Selene Huang31ab4042020-04-29 04:22:39 -07005135 * EncryptionOperationsTest.RsaPkcs1Success
5136 *
5137 * Verifies that RSA PKCS encryption/decrypts works.
5138 */
5139TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5140 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5141 .Authorization(TAG_NO_AUTH_REQUIRED)
5142 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005143 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5144 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005145
5146 string message = "Hello World!";
5147 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005148 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005149 EXPECT_EQ(2048U / 8, ciphertext1.size());
5150
David Drysdale59cae642021-05-12 13:52:03 +01005151 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005152 EXPECT_EQ(2048U / 8, ciphertext2.size());
5153
5154 // PKCS1 v1.5 randomizes padding so every result should be different.
5155 EXPECT_NE(ciphertext1, ciphertext2);
5156
5157 string plaintext = DecryptMessage(ciphertext1, params);
5158 EXPECT_EQ(message, plaintext);
5159
5160 // Decrypting corrupted ciphertext should fail.
5161 size_t offset_to_corrupt = random() % ciphertext1.size();
5162 char corrupt_byte;
5163 do {
5164 corrupt_byte = static_cast<char>(random() % 256);
5165 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5166 ciphertext1[offset_to_corrupt] = corrupt_byte;
5167
5168 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5169 string result;
5170 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5171 EXPECT_EQ(0U, result.size());
5172}
5173
5174/*
Selene Huang31ab4042020-04-29 04:22:39 -07005175 * EncryptionOperationsTest.EcdsaEncrypt
5176 *
5177 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5178 */
5179TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5180 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5181 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005182 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005183 .Digest(Digest::NONE)
5184 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005185 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5186 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5187 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5188}
5189
5190/*
5191 * EncryptionOperationsTest.HmacEncrypt
5192 *
5193 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5194 */
5195TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5196 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5197 .Authorization(TAG_NO_AUTH_REQUIRED)
5198 .HmacKey(128)
5199 .Digest(Digest::SHA_2_256)
5200 .Padding(PaddingMode::NONE)
5201 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5202 auto params = AuthorizationSetBuilder()
5203 .Digest(Digest::SHA_2_256)
5204 .Padding(PaddingMode::NONE)
5205 .Authorization(TAG_MAC_LENGTH, 128);
5206 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5207 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5208}
5209
5210/*
5211 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5212 *
5213 * Verifies that AES ECB mode works.
5214 */
5215TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5216 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5217 .Authorization(TAG_NO_AUTH_REQUIRED)
5218 .AesEncryptionKey(128)
5219 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5220 .Padding(PaddingMode::NONE)));
5221
5222 ASSERT_GT(key_blob_.size(), 0U);
5223 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5224
5225 // Two-block message.
5226 string message = "12345678901234567890123456789012";
5227 string ciphertext1 = EncryptMessage(message, params);
5228 EXPECT_EQ(message.size(), ciphertext1.size());
5229
5230 string ciphertext2 = EncryptMessage(string(message), params);
5231 EXPECT_EQ(message.size(), ciphertext2.size());
5232
5233 // ECB is deterministic.
5234 EXPECT_EQ(ciphertext1, ciphertext2);
5235
5236 string plaintext = DecryptMessage(ciphertext1, params);
5237 EXPECT_EQ(message, plaintext);
5238}
5239
5240/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005241 * EncryptionOperationsTest.AesEcbUnknownTag
5242 *
5243 * Verifies that AES ECB operations ignore unknown tags.
5244 */
5245TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5246 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5247 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5248 KeyParameter unknown_param;
5249 unknown_param.tag = unknown_tag;
5250
5251 vector<KeyCharacteristics> key_characteristics;
5252 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5253 .Authorization(TAG_NO_AUTH_REQUIRED)
5254 .AesEncryptionKey(128)
5255 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5256 .Padding(PaddingMode::NONE)
5257 .Authorization(unknown_param),
5258 &key_blob_, &key_characteristics));
5259 ASSERT_GT(key_blob_.size(), 0U);
5260
5261 // Unknown tags should not be returned in key characteristics.
5262 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5263 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5264 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5265 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5266
5267 // Encrypt without mentioning the unknown parameter.
5268 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5269 string message = "12345678901234567890123456789012";
5270 string ciphertext = EncryptMessage(message, params);
5271 EXPECT_EQ(message.size(), ciphertext.size());
5272
5273 // Decrypt including the unknown parameter.
5274 auto decrypt_params = AuthorizationSetBuilder()
5275 .BlockMode(BlockMode::ECB)
5276 .Padding(PaddingMode::NONE)
5277 .Authorization(unknown_param);
5278 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5279 EXPECT_EQ(message, plaintext);
5280}
5281
5282/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005283 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005284 *
5285 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5286 */
5287TEST_P(EncryptionOperationsTest, AesWrongMode) {
5288 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5289 .Authorization(TAG_NO_AUTH_REQUIRED)
5290 .AesEncryptionKey(128)
5291 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5292 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005293 ASSERT_GT(key_blob_.size(), 0U);
5294
Selene Huang31ab4042020-04-29 04:22:39 -07005295 EXPECT_EQ(
5296 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5297 Begin(KeyPurpose::ENCRYPT,
5298 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5299}
5300
5301/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005302 * EncryptionOperationsTest.AesWrongPadding
5303 *
5304 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5305 */
5306TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5307 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5308 .Authorization(TAG_NO_AUTH_REQUIRED)
5309 .AesEncryptionKey(128)
5310 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5311 .Padding(PaddingMode::NONE)));
5312 ASSERT_GT(key_blob_.size(), 0U);
5313
5314 EXPECT_EQ(
5315 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5316 Begin(KeyPurpose::ENCRYPT,
5317 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5318}
5319
5320/*
5321 * EncryptionOperationsTest.AesInvalidParams
5322 *
5323 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5324 */
5325TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5326 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5327 .Authorization(TAG_NO_AUTH_REQUIRED)
5328 .AesEncryptionKey(128)
5329 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5330 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5331 .Padding(PaddingMode::NONE)
5332 .Padding(PaddingMode::PKCS7)));
5333 ASSERT_GT(key_blob_.size(), 0U);
5334
5335 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5336 .BlockMode(BlockMode::CBC)
5337 .BlockMode(BlockMode::ECB)
5338 .Padding(PaddingMode::NONE));
5339 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5340 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5341
5342 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5343 .BlockMode(BlockMode::ECB)
5344 .Padding(PaddingMode::NONE)
5345 .Padding(PaddingMode::PKCS7));
5346 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5347 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5348}
5349
5350/*
Selene Huang31ab4042020-04-29 04:22:39 -07005351 * EncryptionOperationsTest.AesWrongPurpose
5352 *
5353 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5354 * specified.
5355 */
5356TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5357 auto err = GenerateKey(AuthorizationSetBuilder()
5358 .Authorization(TAG_NO_AUTH_REQUIRED)
5359 .AesKey(128)
5360 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5361 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5362 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5363 .Padding(PaddingMode::NONE));
5364 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5365 ASSERT_GT(key_blob_.size(), 0U);
5366
5367 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5368 .BlockMode(BlockMode::GCM)
5369 .Padding(PaddingMode::NONE)
5370 .Authorization(TAG_MAC_LENGTH, 128));
5371 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5372
5373 CheckedDeleteKey();
5374
5375 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5376 .Authorization(TAG_NO_AUTH_REQUIRED)
5377 .AesKey(128)
5378 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5379 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5380 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5381 .Padding(PaddingMode::NONE)));
5382
5383 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5384 .BlockMode(BlockMode::GCM)
5385 .Padding(PaddingMode::NONE)
5386 .Authorization(TAG_MAC_LENGTH, 128));
5387 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5388}
5389
5390/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005391 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005392 *
5393 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5394 * multiple of the block size and no padding is specified.
5395 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005396TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5397 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5398 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5399 .Authorization(TAG_NO_AUTH_REQUIRED)
5400 .AesEncryptionKey(128)
5401 .Authorization(TAG_BLOCK_MODE, blockMode)
5402 .Padding(PaddingMode::NONE)));
5403 // Message is slightly shorter than two blocks.
5404 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005405
David Drysdaled2cc8c22021-04-15 13:29:45 +01005406 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5407 AuthorizationSet out_params;
5408 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5409 string ciphertext;
5410 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5411 EXPECT_EQ(0U, ciphertext.size());
5412
5413 CheckedDeleteKey();
5414 }
Selene Huang31ab4042020-04-29 04:22:39 -07005415}
5416
5417/*
5418 * EncryptionOperationsTest.AesEcbPkcs7Padding
5419 *
5420 * Verifies that AES PKCS7 padding works for any message length.
5421 */
5422TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5423 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5424 .Authorization(TAG_NO_AUTH_REQUIRED)
5425 .AesEncryptionKey(128)
5426 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5427 .Padding(PaddingMode::PKCS7)));
5428
5429 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5430
5431 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005432 for (size_t i = 0; i <= 48; i++) {
5433 SCOPED_TRACE(testing::Message() << "i = " << i);
5434 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5435 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005436 string ciphertext = EncryptMessage(message, params);
5437 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5438 string plaintext = DecryptMessage(ciphertext, params);
5439 EXPECT_EQ(message, plaintext);
5440 }
5441}
5442
5443/*
5444 * EncryptionOperationsTest.AesEcbWrongPadding
5445 *
5446 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5447 * specified.
5448 */
5449TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5450 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5451 .Authorization(TAG_NO_AUTH_REQUIRED)
5452 .AesEncryptionKey(128)
5453 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5454 .Padding(PaddingMode::NONE)));
5455
5456 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5457
5458 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005459 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005460 string message(i, 'a');
5461 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5462 }
5463}
5464
5465/*
5466 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5467 *
5468 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5469 */
5470TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5471 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5472 .Authorization(TAG_NO_AUTH_REQUIRED)
5473 .AesEncryptionKey(128)
5474 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5475 .Padding(PaddingMode::PKCS7)));
5476
5477 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5478
5479 string message = "a";
5480 string ciphertext = EncryptMessage(message, params);
5481 EXPECT_EQ(16U, ciphertext.size());
5482 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005483
Seth Moore7a55ae32021-06-23 14:28:11 -07005484 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5485 ++ciphertext[ciphertext.size() / 2];
5486
5487 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5488 string plaintext;
David Drysdaleb8093292022-04-08 12:22:35 +01005489 ErrorCode error = Finish(ciphertext, &plaintext);
5490 if (error == ErrorCode::INVALID_ARGUMENT) {
Seth Moore7a55ae32021-06-23 14:28:11 -07005491 // This is the expected error, we can exit the test now.
5492 return;
5493 } else {
5494 // Very small chance we got valid decryption, so try again.
David Drysdaleb8093292022-04-08 12:22:35 +01005495 ASSERT_EQ(error, ErrorCode::OK)
5496 << "Expected INVALID_ARGUMENT or (rarely) OK, got " << error;
Seth Moore7a55ae32021-06-23 14:28:11 -07005497 }
5498 }
5499 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005500}
5501
David Drysdaleb8093292022-04-08 12:22:35 +01005502/*
5503 * EncryptionOperationsTest.AesEcbPkcs7CiphertextTooShort
5504 *
5505 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5506 */
5507TEST_P(EncryptionOperationsTest, AesEcbPkcs7CiphertextTooShort) {
5508 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5509 .Authorization(TAG_NO_AUTH_REQUIRED)
5510 .AesEncryptionKey(128)
5511 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5512 .Padding(PaddingMode::PKCS7)));
5513
5514 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5515
5516 string message = "a";
5517 string ciphertext = EncryptMessage(message, params);
5518 EXPECT_EQ(16U, ciphertext.size());
5519 EXPECT_NE(ciphertext, message);
5520
5521 // Shorten the ciphertext.
5522 ciphertext.resize(ciphertext.size() - 1);
5523 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5524 string plaintext;
5525 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(ciphertext, &plaintext));
5526}
5527
Selene Huang31ab4042020-04-29 04:22:39 -07005528vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5529 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005530 EXPECT_TRUE(iv);
5531 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005532}
5533
5534/*
5535 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5536 *
5537 * Verifies that AES CTR mode works.
5538 */
5539TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5540 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5541 .Authorization(TAG_NO_AUTH_REQUIRED)
5542 .AesEncryptionKey(128)
5543 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5544 .Padding(PaddingMode::NONE)));
5545
5546 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5547
5548 string message = "123";
5549 AuthorizationSet out_params;
5550 string ciphertext1 = EncryptMessage(message, params, &out_params);
5551 vector<uint8_t> iv1 = CopyIv(out_params);
5552 EXPECT_EQ(16U, iv1.size());
5553
5554 EXPECT_EQ(message.size(), ciphertext1.size());
5555
5556 out_params.Clear();
5557 string ciphertext2 = EncryptMessage(message, params, &out_params);
5558 vector<uint8_t> iv2 = CopyIv(out_params);
5559 EXPECT_EQ(16U, iv2.size());
5560
5561 // IVs should be random, so ciphertexts should differ.
5562 EXPECT_NE(ciphertext1, ciphertext2);
5563
5564 auto params_iv1 =
5565 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5566 auto params_iv2 =
5567 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5568
5569 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5570 EXPECT_EQ(message, plaintext);
5571 plaintext = DecryptMessage(ciphertext2, params_iv2);
5572 EXPECT_EQ(message, plaintext);
5573
5574 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5575 plaintext = DecryptMessage(ciphertext1, params_iv2);
5576 EXPECT_NE(message, plaintext);
5577 plaintext = DecryptMessage(ciphertext2, params_iv1);
5578 EXPECT_NE(message, plaintext);
5579}
5580
5581/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305582 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005583 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305584 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005585 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305586TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5587 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5588}
Selene Huang31ab4042020-04-29 04:22:39 -07005589
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305590/*
5591 * EncryptionOperationsTest.AesCbcIncremental
5592 *
5593 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5594 */
5595TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5596 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5597}
Selene Huang31ab4042020-04-29 04:22:39 -07005598
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305599/*
5600 * EncryptionOperationsTest.AesCtrIncremental
5601 *
5602 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5603 */
5604TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5605 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5606}
Selene Huang31ab4042020-04-29 04:22:39 -07005607
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305608/*
5609 * EncryptionOperationsTest.AesGcmIncremental
5610 *
5611 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5612 */
5613TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5614 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005615}
5616
5617struct AesCtrSp80038aTestVector {
5618 const char* key;
5619 const char* nonce;
5620 const char* plaintext;
5621 const char* ciphertext;
5622};
5623
5624// These test vectors are taken from
5625// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
5626static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
5627 // AES-128
5628 {
5629 "2b7e151628aed2a6abf7158809cf4f3c",
5630 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5631 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5632 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5633 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
5634 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
5635 },
5636 // AES-192
5637 {
5638 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
5639 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5640 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5641 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5642 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
5643 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
5644 },
5645 // AES-256
5646 {
5647 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
5648 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5649 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5650 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5651 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
5652 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
5653 },
5654};
5655
5656/*
5657 * EncryptionOperationsTest.AesCtrSp80038aTestVector
5658 *
5659 * Verifies AES CTR implementation against SP800-38A test vectors.
5660 */
5661TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
5662 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
5663 for (size_t i = 0; i < 3; i++) {
5664 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
5665 const string key = hex2str(test.key);
5666 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
5667 InvalidSizes.end())
5668 continue;
5669 const string nonce = hex2str(test.nonce);
5670 const string plaintext = hex2str(test.plaintext);
5671 const string ciphertext = hex2str(test.ciphertext);
5672 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
5673 }
5674}
5675
5676/*
5677 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
5678 *
5679 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
5680 */
5681TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
5682 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5683 .Authorization(TAG_NO_AUTH_REQUIRED)
5684 .AesEncryptionKey(128)
5685 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5686 .Padding(PaddingMode::PKCS7)));
5687 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5688 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5689}
5690
5691/*
5692 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
5693 *
5694 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5695 */
5696TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
5697 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5698 .Authorization(TAG_NO_AUTH_REQUIRED)
5699 .AesEncryptionKey(128)
5700 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5701 .Authorization(TAG_CALLER_NONCE)
5702 .Padding(PaddingMode::NONE)));
5703
5704 auto params = AuthorizationSetBuilder()
5705 .BlockMode(BlockMode::CTR)
5706 .Padding(PaddingMode::NONE)
5707 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
5708 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5709
5710 params = AuthorizationSetBuilder()
5711 .BlockMode(BlockMode::CTR)
5712 .Padding(PaddingMode::NONE)
5713 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
5714 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5715
5716 params = AuthorizationSetBuilder()
5717 .BlockMode(BlockMode::CTR)
5718 .Padding(PaddingMode::NONE)
5719 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
5720 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5721}
5722
5723/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005724 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07005725 *
5726 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5727 */
5728TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
5729 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5730 .Authorization(TAG_NO_AUTH_REQUIRED)
5731 .AesEncryptionKey(128)
5732 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5733 .Padding(PaddingMode::NONE)));
5734 // Two-block message.
5735 string message = "12345678901234567890123456789012";
5736 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5737 AuthorizationSet out_params;
5738 string ciphertext1 = EncryptMessage(message, params, &out_params);
5739 vector<uint8_t> iv1 = CopyIv(out_params);
5740 EXPECT_EQ(message.size(), ciphertext1.size());
5741
5742 out_params.Clear();
5743
5744 string ciphertext2 = EncryptMessage(message, params, &out_params);
5745 vector<uint8_t> iv2 = CopyIv(out_params);
5746 EXPECT_EQ(message.size(), ciphertext2.size());
5747
5748 // IVs should be random, so ciphertexts should differ.
5749 EXPECT_NE(ciphertext1, ciphertext2);
5750
5751 params.push_back(TAG_NONCE, iv1);
5752 string plaintext = DecryptMessage(ciphertext1, params);
5753 EXPECT_EQ(message, plaintext);
5754}
5755
5756/*
5757 * EncryptionOperationsTest.AesCallerNonce
5758 *
5759 * Verifies that AES caller-provided nonces work correctly.
5760 */
5761TEST_P(EncryptionOperationsTest, AesCallerNonce) {
5762 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5763 .Authorization(TAG_NO_AUTH_REQUIRED)
5764 .AesEncryptionKey(128)
5765 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5766 .Authorization(TAG_CALLER_NONCE)
5767 .Padding(PaddingMode::NONE)));
5768
5769 string message = "12345678901234567890123456789012";
5770
5771 // Don't specify nonce, should get a random one.
5772 AuthorizationSetBuilder params =
5773 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5774 AuthorizationSet out_params;
5775 string ciphertext = EncryptMessage(message, params, &out_params);
5776 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005777 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005778
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005779 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005780 string plaintext = DecryptMessage(ciphertext, params);
5781 EXPECT_EQ(message, plaintext);
5782
5783 // Now specify a nonce, should also work.
5784 params = AuthorizationSetBuilder()
5785 .BlockMode(BlockMode::CBC)
5786 .Padding(PaddingMode::NONE)
5787 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5788 out_params.Clear();
5789 ciphertext = EncryptMessage(message, params, &out_params);
5790
5791 // Decrypt with correct nonce.
5792 plaintext = DecryptMessage(ciphertext, params);
5793 EXPECT_EQ(message, plaintext);
5794
5795 // Try with wrong nonce.
5796 params = AuthorizationSetBuilder()
5797 .BlockMode(BlockMode::CBC)
5798 .Padding(PaddingMode::NONE)
5799 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
5800 plaintext = DecryptMessage(ciphertext, params);
5801 EXPECT_NE(message, plaintext);
5802}
5803
5804/*
5805 * EncryptionOperationsTest.AesCallerNonceProhibited
5806 *
5807 * Verifies that caller-provided nonces are not permitted when not specified in the key
5808 * authorizations.
5809 */
5810TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
5811 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5812 .Authorization(TAG_NO_AUTH_REQUIRED)
5813 .AesEncryptionKey(128)
5814 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5815 .Padding(PaddingMode::NONE)));
5816
5817 string message = "12345678901234567890123456789012";
5818
5819 // Don't specify nonce, should get a random one.
5820 AuthorizationSetBuilder params =
5821 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5822 AuthorizationSet out_params;
5823 string ciphertext = EncryptMessage(message, params, &out_params);
5824 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005825 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005826
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005827 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005828 string plaintext = DecryptMessage(ciphertext, params);
5829 EXPECT_EQ(message, plaintext);
5830
5831 // Now specify a nonce, should fail
5832 params = AuthorizationSetBuilder()
5833 .BlockMode(BlockMode::CBC)
5834 .Padding(PaddingMode::NONE)
5835 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5836 out_params.Clear();
5837 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5838}
5839
5840/*
5841 * EncryptionOperationsTest.AesGcmRoundTripSuccess
5842 *
5843 * Verifies that AES GCM mode works.
5844 */
5845TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
5846 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5847 .Authorization(TAG_NO_AUTH_REQUIRED)
5848 .AesEncryptionKey(128)
5849 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5850 .Padding(PaddingMode::NONE)
5851 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5852
5853 string aad = "foobar";
5854 string message = "123456789012345678901234567890123456";
5855
5856 auto begin_params = AuthorizationSetBuilder()
5857 .BlockMode(BlockMode::GCM)
5858 .Padding(PaddingMode::NONE)
5859 .Authorization(TAG_MAC_LENGTH, 128);
5860
Selene Huang31ab4042020-04-29 04:22:39 -07005861 // Encrypt
5862 AuthorizationSet begin_out_params;
5863 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5864 << "Begin encrypt";
5865 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005866 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5867 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005868 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5869
5870 // Grab nonce
5871 begin_params.push_back(begin_out_params);
5872
5873 // Decrypt.
5874 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07005875 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005876 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005877 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005878 EXPECT_EQ(message.length(), plaintext.length());
5879 EXPECT_EQ(message, plaintext);
5880}
5881
5882/*
5883 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
5884 *
5885 * Verifies that AES GCM mode works, even when there's a long delay
5886 * between operations.
5887 */
5888TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
5889 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5890 .Authorization(TAG_NO_AUTH_REQUIRED)
5891 .AesEncryptionKey(128)
5892 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5893 .Padding(PaddingMode::NONE)
5894 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5895
5896 string aad = "foobar";
5897 string message = "123456789012345678901234567890123456";
5898
5899 auto begin_params = AuthorizationSetBuilder()
5900 .BlockMode(BlockMode::GCM)
5901 .Padding(PaddingMode::NONE)
5902 .Authorization(TAG_MAC_LENGTH, 128);
5903
Selene Huang31ab4042020-04-29 04:22:39 -07005904 // Encrypt
5905 AuthorizationSet begin_out_params;
5906 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5907 << "Begin encrypt";
5908 string ciphertext;
5909 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005910 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005911 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005912 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005913
5914 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5915
5916 // Grab nonce
5917 begin_params.push_back(begin_out_params);
5918
5919 // Decrypt.
5920 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5921 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005922 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005923 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005924 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005925 sleep(5);
5926 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5927 EXPECT_EQ(message.length(), plaintext.length());
5928 EXPECT_EQ(message, plaintext);
5929}
5930
5931/*
5932 * EncryptionOperationsTest.AesGcmDifferentNonces
5933 *
5934 * Verifies that encrypting the same data with different nonces produces different outputs.
5935 */
5936TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
5937 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5938 .Authorization(TAG_NO_AUTH_REQUIRED)
5939 .AesEncryptionKey(128)
5940 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5941 .Padding(PaddingMode::NONE)
5942 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5943 .Authorization(TAG_CALLER_NONCE)));
5944
5945 string aad = "foobar";
5946 string message = "123456789012345678901234567890123456";
5947 string nonce1 = "000000000000";
5948 string nonce2 = "111111111111";
5949 string nonce3 = "222222222222";
5950
5951 string ciphertext1 =
5952 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
5953 string ciphertext2 =
5954 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
5955 string ciphertext3 =
5956 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
5957
5958 ASSERT_NE(ciphertext1, ciphertext2);
5959 ASSERT_NE(ciphertext1, ciphertext3);
5960 ASSERT_NE(ciphertext2, ciphertext3);
5961}
5962
5963/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005964 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
5965 *
5966 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
5967 */
5968TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
5969 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5970 .Authorization(TAG_NO_AUTH_REQUIRED)
5971 .AesEncryptionKey(128)
5972 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5973 .Padding(PaddingMode::NONE)
5974 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5975
5976 string aad = "foobar";
5977 string message = "123456789012345678901234567890123456";
5978
5979 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5980 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5981 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5982
5983 ASSERT_NE(ciphertext1, ciphertext2);
5984 ASSERT_NE(ciphertext1, ciphertext3);
5985 ASSERT_NE(ciphertext2, ciphertext3);
5986}
5987
5988/*
Selene Huang31ab4042020-04-29 04:22:39 -07005989 * EncryptionOperationsTest.AesGcmTooShortTag
5990 *
5991 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
5992 */
5993TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
5994 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5995 .Authorization(TAG_NO_AUTH_REQUIRED)
5996 .AesEncryptionKey(128)
5997 .BlockMode(BlockMode::GCM)
5998 .Padding(PaddingMode::NONE)
5999 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6000 string message = "123456789012345678901234567890123456";
6001 auto params = AuthorizationSetBuilder()
6002 .BlockMode(BlockMode::GCM)
6003 .Padding(PaddingMode::NONE)
6004 .Authorization(TAG_MAC_LENGTH, 96);
6005
6006 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
6007}
6008
6009/*
6010 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6011 *
6012 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6013 */
6014TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6015 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6016 .Authorization(TAG_NO_AUTH_REQUIRED)
6017 .AesEncryptionKey(128)
6018 .BlockMode(BlockMode::GCM)
6019 .Padding(PaddingMode::NONE)
6020 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6021 string aad = "foobar";
6022 string message = "123456789012345678901234567890123456";
6023 auto params = AuthorizationSetBuilder()
6024 .BlockMode(BlockMode::GCM)
6025 .Padding(PaddingMode::NONE)
6026 .Authorization(TAG_MAC_LENGTH, 128);
6027
Selene Huang31ab4042020-04-29 04:22:39 -07006028 // Encrypt
6029 AuthorizationSet begin_out_params;
6030 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6031 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006032 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006033
6034 AuthorizationSet finish_out_params;
6035 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006036 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6037 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006038
6039 params = AuthorizationSetBuilder()
6040 .Authorizations(begin_out_params)
6041 .BlockMode(BlockMode::GCM)
6042 .Padding(PaddingMode::NONE)
6043 .Authorization(TAG_MAC_LENGTH, 96);
6044
6045 // Decrypt.
6046 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6047}
6048
6049/*
6050 * EncryptionOperationsTest.AesGcmCorruptKey
6051 *
6052 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6053 */
6054TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6055 const uint8_t nonce_bytes[] = {
6056 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6057 };
6058 string nonce = make_string(nonce_bytes);
6059 const uint8_t ciphertext_bytes[] = {
6060 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6061 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6062 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6063 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6064 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6065 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6066 };
6067 string ciphertext = make_string(ciphertext_bytes);
6068
6069 auto params = AuthorizationSetBuilder()
6070 .BlockMode(BlockMode::GCM)
6071 .Padding(PaddingMode::NONE)
6072 .Authorization(TAG_MAC_LENGTH, 128)
6073 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6074
6075 auto import_params = AuthorizationSetBuilder()
6076 .Authorization(TAG_NO_AUTH_REQUIRED)
6077 .AesEncryptionKey(128)
6078 .BlockMode(BlockMode::GCM)
6079 .Padding(PaddingMode::NONE)
6080 .Authorization(TAG_CALLER_NONCE)
6081 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6082
6083 // Import correct key and decrypt
6084 const uint8_t key_bytes[] = {
6085 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6086 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6087 };
6088 string key = make_string(key_bytes);
6089 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6090 string plaintext = DecryptMessage(ciphertext, params);
6091 CheckedDeleteKey();
6092
6093 // Corrupt key and attempt to decrypt
6094 key[0] = 0;
6095 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6096 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6097 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6098 CheckedDeleteKey();
6099}
6100
6101/*
6102 * EncryptionOperationsTest.AesGcmAadNoData
6103 *
6104 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6105 * encrypt.
6106 */
6107TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6108 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6109 .Authorization(TAG_NO_AUTH_REQUIRED)
6110 .AesEncryptionKey(128)
6111 .BlockMode(BlockMode::GCM)
6112 .Padding(PaddingMode::NONE)
6113 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6114
6115 string aad = "1234567890123456";
6116 auto params = AuthorizationSetBuilder()
6117 .BlockMode(BlockMode::GCM)
6118 .Padding(PaddingMode::NONE)
6119 .Authorization(TAG_MAC_LENGTH, 128);
6120
Selene Huang31ab4042020-04-29 04:22:39 -07006121 // Encrypt
6122 AuthorizationSet begin_out_params;
6123 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6124 string ciphertext;
6125 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006126 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6127 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006128 EXPECT_TRUE(finish_out_params.empty());
6129
6130 // Grab nonce
6131 params.push_back(begin_out_params);
6132
6133 // Decrypt.
6134 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006135 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006136 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006137 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006138
6139 EXPECT_TRUE(finish_out_params.empty());
6140
6141 EXPECT_EQ("", plaintext);
6142}
6143
6144/*
6145 * EncryptionOperationsTest.AesGcmMultiPartAad
6146 *
6147 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6148 * chunks.
6149 */
6150TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6151 const size_t tag_bits = 128;
6152 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6153 .Authorization(TAG_NO_AUTH_REQUIRED)
6154 .AesEncryptionKey(128)
6155 .BlockMode(BlockMode::GCM)
6156 .Padding(PaddingMode::NONE)
6157 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6158
6159 string message = "123456789012345678901234567890123456";
6160 auto begin_params = AuthorizationSetBuilder()
6161 .BlockMode(BlockMode::GCM)
6162 .Padding(PaddingMode::NONE)
6163 .Authorization(TAG_MAC_LENGTH, tag_bits);
6164 AuthorizationSet begin_out_params;
6165
Selene Huang31ab4042020-04-29 04:22:39 -07006166 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6167
6168 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006169 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6170 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006171 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006172 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6173 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006174
Selene Huang31ab4042020-04-29 04:22:39 -07006175 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006176 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006177
6178 // Grab nonce.
6179 begin_params.push_back(begin_out_params);
6180
6181 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07006182 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006183 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006184 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006185 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006186 EXPECT_EQ(message, plaintext);
6187}
6188
6189/*
6190 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6191 *
6192 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6193 */
6194TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6195 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6196 .Authorization(TAG_NO_AUTH_REQUIRED)
6197 .AesEncryptionKey(128)
6198 .BlockMode(BlockMode::GCM)
6199 .Padding(PaddingMode::NONE)
6200 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6201
6202 string message = "123456789012345678901234567890123456";
6203 auto begin_params = AuthorizationSetBuilder()
6204 .BlockMode(BlockMode::GCM)
6205 .Padding(PaddingMode::NONE)
6206 .Authorization(TAG_MAC_LENGTH, 128);
6207 AuthorizationSet begin_out_params;
6208
Selene Huang31ab4042020-04-29 04:22:39 -07006209 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6210
Shawn Willden92d79c02021-02-19 07:31:55 -07006211 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006212 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006213 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6214 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006215
David Drysdaled2cc8c22021-04-15 13:29:45 +01006216 // The failure should have already cancelled the operation.
6217 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6218
Shawn Willden92d79c02021-02-19 07:31:55 -07006219 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006220}
6221
6222/*
6223 * EncryptionOperationsTest.AesGcmBadAad
6224 *
6225 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6226 */
6227TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6228 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6229 .Authorization(TAG_NO_AUTH_REQUIRED)
6230 .AesEncryptionKey(128)
6231 .BlockMode(BlockMode::GCM)
6232 .Padding(PaddingMode::NONE)
6233 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6234
6235 string message = "12345678901234567890123456789012";
6236 auto begin_params = AuthorizationSetBuilder()
6237 .BlockMode(BlockMode::GCM)
6238 .Padding(PaddingMode::NONE)
6239 .Authorization(TAG_MAC_LENGTH, 128);
6240
Selene Huang31ab4042020-04-29 04:22:39 -07006241 // Encrypt
6242 AuthorizationSet begin_out_params;
6243 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006244 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006245 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006246 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006247
6248 // Grab nonce
6249 begin_params.push_back(begin_out_params);
6250
Selene Huang31ab4042020-04-29 04:22:39 -07006251 // Decrypt.
6252 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006253 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006254 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006255 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006256}
6257
6258/*
6259 * EncryptionOperationsTest.AesGcmWrongNonce
6260 *
6261 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6262 */
6263TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6264 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6265 .Authorization(TAG_NO_AUTH_REQUIRED)
6266 .AesEncryptionKey(128)
6267 .BlockMode(BlockMode::GCM)
6268 .Padding(PaddingMode::NONE)
6269 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6270
6271 string message = "12345678901234567890123456789012";
6272 auto begin_params = AuthorizationSetBuilder()
6273 .BlockMode(BlockMode::GCM)
6274 .Padding(PaddingMode::NONE)
6275 .Authorization(TAG_MAC_LENGTH, 128);
6276
Selene Huang31ab4042020-04-29 04:22:39 -07006277 // Encrypt
6278 AuthorizationSet begin_out_params;
6279 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006280 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006281 string ciphertext;
6282 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006283 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006284
6285 // Wrong nonce
6286 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6287
6288 // Decrypt.
6289 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006290 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006291 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006292 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006293
6294 // With wrong nonce, should have gotten garbage plaintext (or none).
6295 EXPECT_NE(message, plaintext);
6296}
6297
6298/*
6299 * EncryptionOperationsTest.AesGcmCorruptTag
6300 *
6301 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6302 */
6303TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6304 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6305 .Authorization(TAG_NO_AUTH_REQUIRED)
6306 .AesEncryptionKey(128)
6307 .BlockMode(BlockMode::GCM)
6308 .Padding(PaddingMode::NONE)
6309 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6310
6311 string aad = "1234567890123456";
6312 string message = "123456789012345678901234567890123456";
6313
6314 auto params = AuthorizationSetBuilder()
6315 .BlockMode(BlockMode::GCM)
6316 .Padding(PaddingMode::NONE)
6317 .Authorization(TAG_MAC_LENGTH, 128);
6318
Selene Huang31ab4042020-04-29 04:22:39 -07006319 // Encrypt
6320 AuthorizationSet begin_out_params;
6321 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006322 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006323 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006324 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006325
6326 // Corrupt tag
6327 ++(*ciphertext.rbegin());
6328
6329 // Grab nonce
6330 params.push_back(begin_out_params);
6331
6332 // Decrypt.
6333 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006334 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006335 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006336 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006337}
6338
6339/*
6340 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6341 *
6342 * Verifies that 3DES is basically functional.
6343 */
6344TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6345 auto auths = AuthorizationSetBuilder()
6346 .TripleDesEncryptionKey(168)
6347 .BlockMode(BlockMode::ECB)
6348 .Authorization(TAG_NO_AUTH_REQUIRED)
6349 .Padding(PaddingMode::NONE);
6350
6351 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6352 // Two-block message.
6353 string message = "1234567890123456";
6354 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6355 string ciphertext1 = EncryptMessage(message, inParams);
6356 EXPECT_EQ(message.size(), ciphertext1.size());
6357
6358 string ciphertext2 = EncryptMessage(string(message), inParams);
6359 EXPECT_EQ(message.size(), ciphertext2.size());
6360
6361 // ECB is deterministic.
6362 EXPECT_EQ(ciphertext1, ciphertext2);
6363
6364 string plaintext = DecryptMessage(ciphertext1, inParams);
6365 EXPECT_EQ(message, plaintext);
6366}
6367
6368/*
6369 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6370 *
6371 * Verifies that CBC keys reject ECB usage.
6372 */
6373TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6374 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6375 .TripleDesEncryptionKey(168)
6376 .BlockMode(BlockMode::CBC)
6377 .Authorization(TAG_NO_AUTH_REQUIRED)
6378 .Padding(PaddingMode::NONE)));
6379
6380 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6381 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6382}
6383
6384/*
6385 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6386 *
6387 * Tests ECB mode with PKCS#7 padding, various message sizes.
6388 */
6389TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6390 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6391 .TripleDesEncryptionKey(168)
6392 .BlockMode(BlockMode::ECB)
6393 .Authorization(TAG_NO_AUTH_REQUIRED)
6394 .Padding(PaddingMode::PKCS7)));
6395
6396 for (size_t i = 0; i < 32; ++i) {
6397 string message(i, 'a');
6398 auto inParams =
6399 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6400 string ciphertext = EncryptMessage(message, inParams);
6401 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6402 string plaintext = DecryptMessage(ciphertext, inParams);
6403 EXPECT_EQ(message, plaintext);
6404 }
6405}
6406
6407/*
6408 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6409 *
6410 * Verifies that keys configured for no padding reject PKCS7 padding
6411 */
6412TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6413 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6414 .TripleDesEncryptionKey(168)
6415 .BlockMode(BlockMode::ECB)
6416 .Authorization(TAG_NO_AUTH_REQUIRED)
6417 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006418 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6419 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006420}
6421
6422/*
6423 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6424 *
6425 * Verifies that corrupted padding is detected.
6426 */
6427TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
6428 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6429 .TripleDesEncryptionKey(168)
6430 .BlockMode(BlockMode::ECB)
6431 .Authorization(TAG_NO_AUTH_REQUIRED)
6432 .Padding(PaddingMode::PKCS7)));
6433
6434 string message = "a";
6435 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
6436 EXPECT_EQ(8U, ciphertext.size());
6437 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006438
6439 AuthorizationSetBuilder begin_params;
6440 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
6441 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07006442
6443 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6444 ++ciphertext[ciphertext.size() / 2];
6445
6446 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6447 string plaintext;
6448 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6449 ErrorCode error = Finish(&plaintext);
6450 if (error == ErrorCode::INVALID_ARGUMENT) {
6451 // This is the expected error, we can exit the test now.
6452 return;
6453 } else {
6454 // Very small chance we got valid decryption, so try again.
6455 ASSERT_EQ(error, ErrorCode::OK);
6456 }
6457 }
6458 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006459}
6460
6461struct TripleDesTestVector {
6462 const char* name;
6463 const KeyPurpose purpose;
6464 const BlockMode block_mode;
6465 const PaddingMode padding_mode;
6466 const char* key;
6467 const char* iv;
6468 const char* input;
6469 const char* output;
6470};
6471
6472// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
6473// of the NIST vectors are multiples of the block size.
6474static const TripleDesTestVector kTripleDesTestVectors[] = {
6475 {
6476 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6477 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
6478 "", // IV
6479 "329d86bdf1bc5af4", // input
6480 "d946c2756d78633f", // output
6481 },
6482 {
6483 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6484 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
6485 "", // IV
6486 "6b1540781b01ce1997adae102dbf3c5b", // input
6487 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
6488 },
6489 {
6490 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6491 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
6492 "", // IV
6493 "6daad94ce08acfe7", // input
6494 "660e7d32dcc90e79", // output
6495 },
6496 {
6497 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6498 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
6499 "", // IV
6500 "e9653a0a1f05d31b9acd12d73aa9879d", // input
6501 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
6502 },
6503 {
6504 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6505 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
6506 "43f791134c5647ba", // IV
6507 "dcc153cef81d6f24", // input
6508 "92538bd8af18d3ba", // output
6509 },
6510 {
6511 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6512 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6513 "c2e999cb6249023c", // IV
6514 "c689aee38a301bb316da75db36f110b5", // input
6515 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
6516 },
6517 {
6518 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
6519 PaddingMode::PKCS7,
6520 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6521 "c2e999cb6249023c", // IV
6522 "c689aee38a301bb316da75db36f110b500", // input
6523 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
6524 },
6525 {
6526 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
6527 PaddingMode::PKCS7,
6528 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6529 "c2e999cb6249023c", // IV
6530 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
6531 "c689aee38a301bb316da75db36f110b500", // output
6532 },
6533 {
6534 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6535 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
6536 "41746c7e442d3681", // IV
6537 "c53a7b0ec40600fe", // input
6538 "d4f00eb455de1034", // output
6539 },
6540 {
6541 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6542 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
6543 "3982bc02c3727d45", // IV
6544 "6006f10adef52991fcc777a1238bbb65", // input
6545 "edae09288e9e3bc05746d872b48e3b29", // output
6546 },
6547};
6548
6549/*
6550 * EncryptionOperationsTest.TripleDesTestVector
6551 *
6552 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
6553 */
6554TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
6555 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
6556 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
6557 SCOPED_TRACE(test->name);
6558 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
6559 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
6560 hex2str(test->output));
6561 }
6562}
6563
6564/*
6565 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
6566 *
6567 * Validates CBC mode functionality.
6568 */
6569TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
6570 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6571 .TripleDesEncryptionKey(168)
6572 .BlockMode(BlockMode::CBC)
6573 .Authorization(TAG_NO_AUTH_REQUIRED)
6574 .Padding(PaddingMode::NONE)));
6575
6576 ASSERT_GT(key_blob_.size(), 0U);
6577
Brian J Murray734c8412022-01-13 14:55:30 -08006578 // Four-block message.
6579 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07006580 vector<uint8_t> iv1;
6581 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
6582 EXPECT_EQ(message.size(), ciphertext1.size());
6583
6584 vector<uint8_t> iv2;
6585 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
6586 EXPECT_EQ(message.size(), ciphertext2.size());
6587
6588 // IVs should be random, so ciphertexts should differ.
6589 EXPECT_NE(iv1, iv2);
6590 EXPECT_NE(ciphertext1, ciphertext2);
6591
6592 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
6593 EXPECT_EQ(message, plaintext);
6594}
6595
6596/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006597 * EncryptionOperationsTest.TripleDesInvalidCallerIv
6598 *
6599 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
6600 */
6601TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
6602 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6603 .TripleDesEncryptionKey(168)
6604 .BlockMode(BlockMode::CBC)
6605 .Authorization(TAG_NO_AUTH_REQUIRED)
6606 .Authorization(TAG_CALLER_NONCE)
6607 .Padding(PaddingMode::NONE)));
6608 auto params = AuthorizationSetBuilder()
6609 .BlockMode(BlockMode::CBC)
6610 .Padding(PaddingMode::NONE)
6611 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
6612 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6613}
6614
6615/*
Selene Huang31ab4042020-04-29 04:22:39 -07006616 * EncryptionOperationsTest.TripleDesCallerIv
6617 *
6618 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
6619 */
6620TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
6621 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6622 .TripleDesEncryptionKey(168)
6623 .BlockMode(BlockMode::CBC)
6624 .Authorization(TAG_NO_AUTH_REQUIRED)
6625 .Authorization(TAG_CALLER_NONCE)
6626 .Padding(PaddingMode::NONE)));
6627 string message = "1234567890123456";
6628 vector<uint8_t> iv;
6629 // Don't specify IV, should get a random one.
6630 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6631 EXPECT_EQ(message.size(), ciphertext1.size());
6632 EXPECT_EQ(8U, iv.size());
6633
6634 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6635 EXPECT_EQ(message, plaintext);
6636
6637 // Now specify an IV, should also work.
6638 iv = AidlBuf("abcdefgh");
6639 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
6640
6641 // Decrypt with correct IV.
6642 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
6643 EXPECT_EQ(message, plaintext);
6644
6645 // Now try with wrong IV.
6646 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
6647 EXPECT_NE(message, plaintext);
6648}
6649
6650/*
6651 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
6652 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01006653 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07006654 */
6655TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
6656 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6657 .TripleDesEncryptionKey(168)
6658 .BlockMode(BlockMode::CBC)
6659 .Authorization(TAG_NO_AUTH_REQUIRED)
6660 .Padding(PaddingMode::NONE)));
6661
6662 string message = "12345678901234567890123456789012";
6663 vector<uint8_t> iv;
6664 // Don't specify nonce, should get a random one.
6665 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6666 EXPECT_EQ(message.size(), ciphertext1.size());
6667 EXPECT_EQ(8U, iv.size());
6668
6669 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6670 EXPECT_EQ(message, plaintext);
6671
6672 // Now specify a nonce, should fail.
6673 auto input_params = AuthorizationSetBuilder()
6674 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
6675 .BlockMode(BlockMode::CBC)
6676 .Padding(PaddingMode::NONE);
6677 AuthorizationSet output_params;
6678 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
6679 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6680}
6681
6682/*
6683 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
6684 *
6685 * Verifies that 3DES ECB-only keys do not allow CBC usage.
6686 */
6687TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
6688 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6689 .TripleDesEncryptionKey(168)
6690 .BlockMode(BlockMode::ECB)
6691 .Authorization(TAG_NO_AUTH_REQUIRED)
6692 .Padding(PaddingMode::NONE)));
6693 // Two-block message.
6694 string message = "1234567890123456";
6695 auto begin_params =
6696 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6697 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6698}
6699
6700/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006701 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07006702 *
6703 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
6704 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01006705TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
6706 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
6707 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6708 .TripleDesEncryptionKey(168)
6709 .BlockMode(blockMode)
6710 .Authorization(TAG_NO_AUTH_REQUIRED)
6711 .Padding(PaddingMode::NONE)));
6712 // Message is slightly shorter than two blocks.
6713 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07006714
David Drysdaled2cc8c22021-04-15 13:29:45 +01006715 auto begin_params =
6716 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
6717 AuthorizationSet output_params;
6718 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
6719 string ciphertext;
6720 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
6721
6722 CheckedDeleteKey();
6723 }
Selene Huang31ab4042020-04-29 04:22:39 -07006724}
6725
6726/*
6727 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
6728 *
6729 * Verifies that PKCS7 padding works correctly in CBC mode.
6730 */
6731TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
6732 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6733 .TripleDesEncryptionKey(168)
6734 .BlockMode(BlockMode::CBC)
6735 .Authorization(TAG_NO_AUTH_REQUIRED)
6736 .Padding(PaddingMode::PKCS7)));
6737
6738 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08006739 for (size_t i = 0; i <= 32; i++) {
6740 SCOPED_TRACE(testing::Message() << "i = " << i);
6741 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
6742 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07006743 vector<uint8_t> iv;
6744 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6745 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6746 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
6747 EXPECT_EQ(message, plaintext);
6748 }
6749}
6750
6751/*
6752 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
6753 *
6754 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
6755 */
6756TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
6757 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6758 .TripleDesEncryptionKey(168)
6759 .BlockMode(BlockMode::CBC)
6760 .Authorization(TAG_NO_AUTH_REQUIRED)
6761 .Padding(PaddingMode::NONE)));
6762
6763 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08006764 for (size_t i = 0; i <= 32; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07006765 auto begin_params =
6766 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
6767 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6768 }
6769}
6770
6771/*
6772 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
6773 *
6774 * Verifies that corrupted PKCS7 padding is rejected during decryption.
6775 */
6776TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
6777 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6778 .TripleDesEncryptionKey(168)
6779 .BlockMode(BlockMode::CBC)
6780 .Authorization(TAG_NO_AUTH_REQUIRED)
6781 .Padding(PaddingMode::PKCS7)));
6782
6783 string message = "a";
6784 vector<uint8_t> iv;
6785 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6786 EXPECT_EQ(8U, ciphertext.size());
6787 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006788
6789 auto begin_params = AuthorizationSetBuilder()
6790 .BlockMode(BlockMode::CBC)
6791 .Padding(PaddingMode::PKCS7)
6792 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07006793
6794 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08006795 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07006796 ++ciphertext[ciphertext.size() / 2];
6797 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6798 string plaintext;
6799 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6800 ErrorCode error = Finish(&plaintext);
6801 if (error == ErrorCode::INVALID_ARGUMENT) {
6802 // This is the expected error, we can exit the test now.
6803 return;
6804 } else {
6805 // Very small chance we got valid decryption, so try again.
6806 ASSERT_EQ(error, ErrorCode::OK);
6807 }
6808 }
6809 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006810}
6811
6812/*
6813 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
6814 *
6815 * Verifies that 3DES CBC works with many different input sizes.
6816 */
6817TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
6818 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6819 .TripleDesEncryptionKey(168)
6820 .BlockMode(BlockMode::CBC)
6821 .Authorization(TAG_NO_AUTH_REQUIRED)
6822 .Padding(PaddingMode::NONE)));
6823
6824 int increment = 7;
6825 string message(240, 'a');
6826 AuthorizationSet input_params =
6827 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6828 AuthorizationSet output_params;
6829 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6830
6831 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07006832 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006833 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006834 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
6835 EXPECT_EQ(message.size(), ciphertext.size());
6836
6837 // Move TAG_NONCE into input_params
6838 input_params = output_params;
6839 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
6840 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
6841 output_params.Clear();
6842
6843 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
6844 string plaintext;
6845 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006846 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006847 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
6848 EXPECT_EQ(ciphertext.size(), plaintext.size());
6849 EXPECT_EQ(message, plaintext);
6850}
6851
6852INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
6853
6854typedef KeyMintAidlTestBase MaxOperationsTest;
6855
6856/*
6857 * MaxOperationsTest.TestLimitAes
6858 *
6859 * Verifies that the max uses per boot tag works correctly with AES keys.
6860 */
6861TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006862 if (SecLevel() == SecurityLevel::STRONGBOX) {
6863 GTEST_SKIP() << "Test not applicable to StrongBox device";
6864 }
Selene Huang31ab4042020-04-29 04:22:39 -07006865
6866 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6867 .Authorization(TAG_NO_AUTH_REQUIRED)
6868 .AesEncryptionKey(128)
6869 .EcbMode()
6870 .Padding(PaddingMode::NONE)
6871 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
6872
6873 string message = "1234567890123456";
6874
6875 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6876
6877 EncryptMessage(message, params);
6878 EncryptMessage(message, params);
6879 EncryptMessage(message, params);
6880
6881 // Fourth time should fail.
6882 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
6883}
6884
6885/*
Qi Wud22ec842020-11-26 13:27:53 +08006886 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07006887 *
6888 * Verifies that the max uses per boot tag works correctly with RSA keys.
6889 */
6890TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006891 if (SecLevel() == SecurityLevel::STRONGBOX) {
6892 GTEST_SKIP() << "Test not applicable to StrongBox device";
6893 }
Selene Huang31ab4042020-04-29 04:22:39 -07006894
6895 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6896 .Authorization(TAG_NO_AUTH_REQUIRED)
6897 .RsaSigningKey(1024, 65537)
6898 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006899 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6900 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006901
6902 string message = "1234567890123456";
6903
6904 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6905
6906 SignMessage(message, params);
6907 SignMessage(message, params);
6908 SignMessage(message, params);
6909
6910 // Fourth time should fail.
6911 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6912}
6913
6914INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6915
Qi Wud22ec842020-11-26 13:27:53 +08006916typedef KeyMintAidlTestBase UsageCountLimitTest;
6917
6918/*
Qi Wubeefae42021-01-28 23:16:37 +08006919 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006920 *
Qi Wubeefae42021-01-28 23:16:37 +08006921 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006922 */
Qi Wubeefae42021-01-28 23:16:37 +08006923TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006924 if (SecLevel() == SecurityLevel::STRONGBOX) {
6925 GTEST_SKIP() << "Test not applicable to StrongBox device";
6926 }
Qi Wud22ec842020-11-26 13:27:53 +08006927
6928 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6929 .Authorization(TAG_NO_AUTH_REQUIRED)
6930 .AesEncryptionKey(128)
6931 .EcbMode()
6932 .Padding(PaddingMode::NONE)
6933 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
6934
6935 // Check the usage count limit tag appears in the authorizations.
6936 AuthorizationSet auths;
6937 for (auto& entry : key_characteristics_) {
6938 auths.push_back(AuthorizationSet(entry.authorizations));
6939 }
6940 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6941 << "key usage count limit " << 1U << " missing";
6942
6943 string message = "1234567890123456";
6944 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6945
Qi Wubeefae42021-01-28 23:16:37 +08006946 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6947 AuthorizationSet keystore_auths =
6948 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6949
Qi Wud22ec842020-11-26 13:27:53 +08006950 // First usage of AES key should work.
6951 EncryptMessage(message, params);
6952
Qi Wud22ec842020-11-26 13:27:53 +08006953 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6954 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6955 // must be invalidated from secure storage (such as RPMB partition).
6956 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6957 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006958 // Usage count limit tag is enforced by keystore, keymint does nothing.
6959 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08006960 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6961 }
6962}
6963
6964/*
Qi Wubeefae42021-01-28 23:16:37 +08006965 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006966 *
Qi Wubeefae42021-01-28 23:16:37 +08006967 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006968 */
Qi Wubeefae42021-01-28 23:16:37 +08006969TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006970 if (SecLevel() == SecurityLevel::STRONGBOX) {
6971 GTEST_SKIP() << "Test not applicable to StrongBox device";
6972 }
Qi Wubeefae42021-01-28 23:16:37 +08006973
6974 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6975 .Authorization(TAG_NO_AUTH_REQUIRED)
6976 .AesEncryptionKey(128)
6977 .EcbMode()
6978 .Padding(PaddingMode::NONE)
6979 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
6980
6981 // Check the usage count limit tag appears in the authorizations.
6982 AuthorizationSet auths;
6983 for (auto& entry : key_characteristics_) {
6984 auths.push_back(AuthorizationSet(entry.authorizations));
6985 }
6986 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6987 << "key usage count limit " << 3U << " missing";
6988
6989 string message = "1234567890123456";
6990 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6991
6992 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6993 AuthorizationSet keystore_auths =
6994 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6995
6996 EncryptMessage(message, params);
6997 EncryptMessage(message, params);
6998 EncryptMessage(message, params);
6999
7000 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7001 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7002 // must be invalidated from secure storage (such as RPMB partition).
7003 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
7004 } else {
7005 // Usage count limit tag is enforced by keystore, keymint does nothing.
7006 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
7007 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
7008 }
7009}
7010
7011/*
7012 * UsageCountLimitTest.TestSingleUseRsa
7013 *
7014 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7015 */
7016TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007017 if (SecLevel() == SecurityLevel::STRONGBOX) {
7018 GTEST_SKIP() << "Test not applicable to StrongBox device";
7019 }
Qi Wud22ec842020-11-26 13:27:53 +08007020
7021 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7022 .Authorization(TAG_NO_AUTH_REQUIRED)
7023 .RsaSigningKey(1024, 65537)
7024 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007025 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7026 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007027
7028 // Check the usage count limit tag appears in the authorizations.
7029 AuthorizationSet auths;
7030 for (auto& entry : key_characteristics_) {
7031 auths.push_back(AuthorizationSet(entry.authorizations));
7032 }
7033 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7034 << "key usage count limit " << 1U << " missing";
7035
7036 string message = "1234567890123456";
7037 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7038
Qi Wubeefae42021-01-28 23:16:37 +08007039 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7040 AuthorizationSet keystore_auths =
7041 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7042
Qi Wud22ec842020-11-26 13:27:53 +08007043 // First usage of RSA key should work.
7044 SignMessage(message, params);
7045
Qi Wud22ec842020-11-26 13:27:53 +08007046 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7047 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7048 // must be invalidated from secure storage (such as RPMB partition).
7049 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7050 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007051 // Usage count limit tag is enforced by keystore, keymint does nothing.
7052 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
7053 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
7054 }
7055}
7056
7057/*
7058 * UsageCountLimitTest.TestLimitUseRsa
7059 *
7060 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7061 */
7062TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007063 if (SecLevel() == SecurityLevel::STRONGBOX) {
7064 GTEST_SKIP() << "Test not applicable to StrongBox device";
7065 }
Qi Wubeefae42021-01-28 23:16:37 +08007066
7067 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7068 .Authorization(TAG_NO_AUTH_REQUIRED)
7069 .RsaSigningKey(1024, 65537)
7070 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007071 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7072 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007073
7074 // Check the usage count limit tag appears in the authorizations.
7075 AuthorizationSet auths;
7076 for (auto& entry : key_characteristics_) {
7077 auths.push_back(AuthorizationSet(entry.authorizations));
7078 }
7079 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7080 << "key usage count limit " << 3U << " missing";
7081
7082 string message = "1234567890123456";
7083 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7084
7085 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7086 AuthorizationSet keystore_auths =
7087 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7088
7089 SignMessage(message, params);
7090 SignMessage(message, params);
7091 SignMessage(message, params);
7092
7093 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7094 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7095 // must be invalidated from secure storage (such as RPMB partition).
7096 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7097 } else {
7098 // Usage count limit tag is enforced by keystore, keymint does nothing.
7099 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08007100 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
7101 }
7102}
7103
Qi Wu8e727f72021-02-11 02:49:33 +08007104/*
7105 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7106 *
7107 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7108 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7109 * in hardware.
7110 */
7111TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007112 if (SecLevel() == SecurityLevel::STRONGBOX) {
7113 GTEST_SKIP() << "Test not applicable to StrongBox device";
7114 }
Qi Wu8e727f72021-02-11 02:49:33 +08007115
7116 auto error = GenerateKey(AuthorizationSetBuilder()
7117 .RsaSigningKey(2048, 65537)
7118 .Digest(Digest::NONE)
7119 .Padding(PaddingMode::NONE)
7120 .Authorization(TAG_NO_AUTH_REQUIRED)
7121 .Authorization(TAG_ROLLBACK_RESISTANCE)
7122 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007123 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7124 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007125 }
David Drysdale513bf122021-10-06 11:53:13 +01007126
7127 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7128 ASSERT_EQ(ErrorCode::OK, error);
7129 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7130 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7131 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7132
7133 // The KeyMint should also enforce single use key in hardware when it supports rollback
7134 // resistance.
7135 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7136 .Authorization(TAG_NO_AUTH_REQUIRED)
7137 .RsaSigningKey(1024, 65537)
7138 .NoDigestOrPadding()
7139 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7140 .SetDefaultValidity()));
7141
7142 // Check the usage count limit tag appears in the hardware authorizations.
7143 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7144 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7145 << "key usage count limit " << 1U << " missing";
7146
7147 string message = "1234567890123456";
7148 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7149
7150 // First usage of RSA key should work.
7151 SignMessage(message, params);
7152
7153 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7154 // must be invalidated from secure storage (such as RPMB partition).
7155 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007156}
7157
Qi Wud22ec842020-11-26 13:27:53 +08007158INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7159
David Drysdale7de9feb2021-03-05 14:56:19 +00007160typedef KeyMintAidlTestBase GetHardwareInfoTest;
7161
7162TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7163 // Retrieving hardware info should give the same result each time.
7164 KeyMintHardwareInfo info;
7165 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7166 KeyMintHardwareInfo info2;
7167 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7168 EXPECT_EQ(info, info2);
7169}
7170
7171INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7172
Selene Huang31ab4042020-04-29 04:22:39 -07007173typedef KeyMintAidlTestBase AddEntropyTest;
7174
7175/*
7176 * AddEntropyTest.AddEntropy
7177 *
7178 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7179 * is actually added.
7180 */
7181TEST_P(AddEntropyTest, AddEntropy) {
7182 string data = "foo";
7183 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7184}
7185
7186/*
7187 * AddEntropyTest.AddEmptyEntropy
7188 *
7189 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7190 */
7191TEST_P(AddEntropyTest, AddEmptyEntropy) {
7192 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7193}
7194
7195/*
7196 * AddEntropyTest.AddLargeEntropy
7197 *
7198 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7199 */
7200TEST_P(AddEntropyTest, AddLargeEntropy) {
7201 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7202}
7203
David Drysdalebb3d85e2021-04-13 11:15:51 +01007204/*
7205 * AddEntropyTest.AddTooLargeEntropy
7206 *
7207 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7208 */
7209TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7210 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7211 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7212}
7213
Selene Huang31ab4042020-04-29 04:22:39 -07007214INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7215
Selene Huang31ab4042020-04-29 04:22:39 -07007216typedef KeyMintAidlTestBase KeyDeletionTest;
7217
7218/**
7219 * KeyDeletionTest.DeleteKey
7220 *
7221 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7222 * valid key blob.
7223 */
7224TEST_P(KeyDeletionTest, DeleteKey) {
7225 auto error = GenerateKey(AuthorizationSetBuilder()
7226 .RsaSigningKey(2048, 65537)
7227 .Digest(Digest::NONE)
7228 .Padding(PaddingMode::NONE)
7229 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007230 .Authorization(TAG_ROLLBACK_RESISTANCE)
7231 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007232 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7233 GTEST_SKIP() << "Rollback resistance not supported";
7234 }
Selene Huang31ab4042020-04-29 04:22:39 -07007235
7236 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007237 ASSERT_EQ(ErrorCode::OK, error);
7238 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7239 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007240
David Drysdale513bf122021-10-06 11:53:13 +01007241 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007242
David Drysdale513bf122021-10-06 11:53:13 +01007243 string message = "12345678901234567890123456789012";
7244 AuthorizationSet begin_out_params;
7245 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7246 Begin(KeyPurpose::SIGN, key_blob_,
7247 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7248 &begin_out_params));
7249 AbortIfNeeded();
7250 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007251}
7252
7253/**
7254 * KeyDeletionTest.DeleteInvalidKey
7255 *
7256 * This test checks that the HAL excepts invalid key blobs..
7257 */
7258TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7259 // Generate key just to check if rollback protection is implemented
7260 auto error = GenerateKey(AuthorizationSetBuilder()
7261 .RsaSigningKey(2048, 65537)
7262 .Digest(Digest::NONE)
7263 .Padding(PaddingMode::NONE)
7264 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007265 .Authorization(TAG_ROLLBACK_RESISTANCE)
7266 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007267 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7268 GTEST_SKIP() << "Rollback resistance not supported";
7269 }
Selene Huang31ab4042020-04-29 04:22:39 -07007270
7271 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007272 ASSERT_EQ(ErrorCode::OK, error);
7273 AuthorizationSet enforced(SecLevelAuthorizations());
7274 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007275
David Drysdale513bf122021-10-06 11:53:13 +01007276 // Delete the key we don't care about the result at this point.
7277 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007278
David Drysdale513bf122021-10-06 11:53:13 +01007279 // Now create an invalid key blob and delete it.
7280 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007281
David Drysdale513bf122021-10-06 11:53:13 +01007282 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007283}
7284
7285/**
7286 * KeyDeletionTest.DeleteAllKeys
7287 *
7288 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7289 *
7290 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7291 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7292 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7293 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7294 * credentials stored in Keystore/Keymint.
7295 */
7296TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007297 if (!arm_deleteAllKeys) {
7298 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7299 return;
7300 }
Selene Huang31ab4042020-04-29 04:22:39 -07007301 auto error = GenerateKey(AuthorizationSetBuilder()
7302 .RsaSigningKey(2048, 65537)
7303 .Digest(Digest::NONE)
7304 .Padding(PaddingMode::NONE)
7305 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007306 .Authorization(TAG_ROLLBACK_RESISTANCE)
7307 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007308 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7309 GTEST_SKIP() << "Rollback resistance not supported";
7310 }
Selene Huang31ab4042020-04-29 04:22:39 -07007311
7312 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007313 ASSERT_EQ(ErrorCode::OK, error);
7314 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7315 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007316
David Drysdale513bf122021-10-06 11:53:13 +01007317 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007318
David Drysdale513bf122021-10-06 11:53:13 +01007319 string message = "12345678901234567890123456789012";
7320 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007321
David Drysdale513bf122021-10-06 11:53:13 +01007322 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7323 Begin(KeyPurpose::SIGN, key_blob_,
7324 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7325 &begin_out_params));
7326 AbortIfNeeded();
7327 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007328}
7329
7330INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7331
David Drysdaled2cc8c22021-04-15 13:29:45 +01007332typedef KeyMintAidlTestBase KeyUpgradeTest;
7333
7334/**
7335 * KeyUpgradeTest.UpgradeInvalidKey
7336 *
7337 * This test checks that the HAL excepts invalid key blobs..
7338 */
7339TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7340 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7341
7342 std::vector<uint8_t> new_blob;
7343 Status result = keymint_->upgradeKey(key_blob,
7344 AuthorizationSetBuilder()
7345 .Authorization(TAG_APPLICATION_ID, "clientid")
7346 .Authorization(TAG_APPLICATION_DATA, "appdata")
7347 .vector_data(),
7348 &new_blob);
7349 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7350}
7351
7352INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7353
Selene Huang31ab4042020-04-29 04:22:39 -07007354using UpgradeKeyTest = KeyMintAidlTestBase;
7355
7356/*
7357 * UpgradeKeyTest.UpgradeKey
7358 *
7359 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7360 */
7361TEST_P(UpgradeKeyTest, UpgradeKey) {
7362 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7363 .AesEncryptionKey(128)
7364 .Padding(PaddingMode::NONE)
7365 .Authorization(TAG_NO_AUTH_REQUIRED)));
7366
7367 auto result = UpgradeKey(key_blob_);
7368
7369 // Key doesn't need upgrading. Should get okay, but no new key blob.
7370 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7371}
7372
7373INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7374
7375using ClearOperationsTest = KeyMintAidlTestBase;
7376
7377/*
7378 * ClearSlotsTest.TooManyOperations
7379 *
7380 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7381 * operations are started without being finished or aborted. Also verifies
7382 * that aborting the operations clears the operations.
7383 *
7384 */
7385TEST_P(ClearOperationsTest, TooManyOperations) {
7386 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7387 .Authorization(TAG_NO_AUTH_REQUIRED)
7388 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007389 .Padding(PaddingMode::NONE)
7390 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007391
7392 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7393 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007394 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007395 AuthorizationSet out_params;
7396 ErrorCode result;
7397 size_t i;
7398
7399 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00007400 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07007401 if (ErrorCode::OK != result) {
7402 break;
7403 }
7404 }
7405 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7406 // Try again just in case there's a weird overflow bug
7407 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00007408 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007409 for (size_t j = 0; j < i; j++) {
7410 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7411 << "Aboort failed for i = " << j << std::endl;
7412 }
subrahmanyaman05642492022-02-05 07:10:56 +00007413 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007414 AbortIfNeeded();
7415}
7416
7417INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7418
7419typedef KeyMintAidlTestBase TransportLimitTest;
7420
7421/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007422 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007423 *
7424 * Verifies that passing input data to finish succeeds as expected.
7425 */
7426TEST_P(TransportLimitTest, LargeFinishInput) {
7427 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7428 .Authorization(TAG_NO_AUTH_REQUIRED)
7429 .AesEncryptionKey(128)
7430 .BlockMode(BlockMode::ECB)
7431 .Padding(PaddingMode::NONE)));
7432
7433 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
7434 auto cipher_params =
7435 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7436
7437 AuthorizationSet out_params;
7438 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
7439
7440 string plain_message = std::string(1 << msg_size, 'x');
7441 string encrypted_message;
7442 auto rc = Finish(plain_message, &encrypted_message);
7443
7444 EXPECT_EQ(ErrorCode::OK, rc);
7445 EXPECT_EQ(plain_message.size(), encrypted_message.size())
7446 << "Encrypt finish returned OK, but did not consume all of the given input";
7447 cipher_params.push_back(out_params);
7448
7449 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
7450
7451 string decrypted_message;
7452 rc = Finish(encrypted_message, &decrypted_message);
7453 EXPECT_EQ(ErrorCode::OK, rc);
7454 EXPECT_EQ(plain_message.size(), decrypted_message.size())
7455 << "Decrypt finish returned OK, did not consume all of the given input";
7456 }
7457}
7458
7459INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
7460
Seth Moored79a0ec2021-12-13 20:03:33 +00007461static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05007462 switch (curve) {
7463 case EcCurve::P_224:
7464 return NID_secp224r1;
7465 case EcCurve::P_256:
7466 return NID_X9_62_prime256v1;
7467 case EcCurve::P_384:
7468 return NID_secp384r1;
7469 case EcCurve::P_521:
7470 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00007471 case EcCurve::CURVE_25519:
7472 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05007473 }
7474}
7475
David Drysdale42fe1892021-10-14 14:43:46 +01007476class KeyAgreementTest : public KeyMintAidlTestBase {
7477 protected:
7478 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
7479 std::vector<uint8_t>* localPublicKey) {
7480 // Generate EC key locally (with access to private key material)
7481 if (localCurve == EcCurve::CURVE_25519) {
7482 uint8_t privKeyData[32];
7483 uint8_t pubKeyData[32];
7484 X25519_keypair(pubKeyData, privKeyData);
David Drysdale42fe1892021-10-14 14:43:46 +01007485 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
7486 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
7487 } else {
7488 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
7489 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
7490 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
7491 ASSERT_NE(group, nullptr);
7492 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
7493 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
7494 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
7495 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
David Drysdale42fe1892021-10-14 14:43:46 +01007496 }
David Drysdalea410b772022-05-09 16:44:13 +01007497
7498 // Get encoded form of the public part of the locally generated key...
7499 unsigned char* p = nullptr;
7500 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
7501 ASSERT_GT(localPublicKeySize, 0);
7502 *localPublicKey = vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
7503 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
7504 OPENSSL_free(p);
David Drysdale42fe1892021-10-14 14:43:46 +01007505 }
7506
7507 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
7508 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00007509 auto builder = AuthorizationSetBuilder()
7510 .Authorization(TAG_NO_AUTH_REQUIRED)
7511 .Authorization(TAG_EC_CURVE, curve)
7512 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7513 .Authorization(TAG_ALGORITHM, Algorithm::EC)
7514 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
7515 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
7516 .SetDefaultValidity();
7517 ErrorCode result = GenerateKey(builder);
7518
7519 if (SecLevel() == SecurityLevel::STRONGBOX) {
7520 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
7521 result = GenerateKeyWithSelfSignedAttestKey(
7522 AuthorizationSetBuilder()
7523 .EcdsaKey(EcCurve::P_256)
7524 .AttestKey()
7525 .SetDefaultValidity(), /* attest key params */
7526 builder, &key_blob_, &key_characteristics_, &cert_chain_);
7527 }
7528 }
David Drysdale42fe1892021-10-14 14:43:46 +01007529 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
7530 ASSERT_GT(cert_chain_.size(), 0);
7531 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7532 ASSERT_NE(kmKeyCert, nullptr);
7533 // Check that keyAgreement (bit 4) is set in KeyUsage
7534 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
7535 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
7536 ASSERT_NE(*kmPubKey, nullptr);
7537 if (dump_Attestations) {
7538 for (size_t n = 0; n < cert_chain_.size(); n++) {
7539 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
7540 }
7541 }
7542 }
7543
7544 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
7545 const std::vector<uint8_t>& localPublicKey) {
7546 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7547 string ZabFromKeyMintStr;
7548 ASSERT_EQ(ErrorCode::OK,
7549 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
7550 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
7551 vector<uint8_t> ZabFromTest;
7552
7553 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
7554 size_t kmPubKeySize = 32;
7555 uint8_t kmPubKeyData[32];
7556 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7557 ASSERT_EQ(kmPubKeySize, 32);
7558
7559 uint8_t localPrivKeyData[32];
7560 size_t localPrivKeySize = 32;
7561 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
7562 &localPrivKeySize));
7563 ASSERT_EQ(localPrivKeySize, 32);
7564
7565 uint8_t sharedKey[32];
7566 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
7567 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
7568 } else {
7569 // Perform local ECDH between the two keys so we can check if we get the same Zab..
7570 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
7571 ASSERT_NE(ctx, nullptr);
7572 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
7573 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
7574 size_t ZabFromTestLen = 0;
7575 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
7576 ZabFromTest.resize(ZabFromTestLen);
7577 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
7578 }
7579 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
7580 }
7581};
7582
David Zeuthene0c40892021-01-08 12:54:11 -05007583/*
7584 * KeyAgreementTest.Ecdh
7585 *
David Drysdale42fe1892021-10-14 14:43:46 +01007586 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05007587 */
7588TEST_P(KeyAgreementTest, Ecdh) {
7589 // Because it's possible to use this API with keys on different curves, we
7590 // check all N^2 combinations where N is the number of supported
7591 // curves.
7592 //
7593 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
7594 // lot more curves we can be smart about things and just pick |otherCurve| so
7595 // it's not |curve| and that way we end up with only 2*N runs
7596 //
7597 for (auto curve : ValidCurves()) {
7598 for (auto localCurve : ValidCurves()) {
David Drysdalea410b772022-05-09 16:44:13 +01007599 SCOPED_TRACE(testing::Message()
7600 << "local-curve-" << localCurve << "-keymint-curve-" << curve);
7601
David Zeuthene0c40892021-01-08 12:54:11 -05007602 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007603 EVP_PKEY_Ptr localPrivKey;
7604 vector<uint8_t> localPublicKey;
7605 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007606
7607 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007608 EVP_PKEY_Ptr kmPubKey;
7609 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007610
7611 // Now that we have the two keys, we ask KeyMint to perform ECDH...
7612 if (curve != localCurve) {
7613 // If the keys are using different curves KeyMint should fail with
7614 // ErrorCode:INVALID_ARGUMENT. Check that.
7615 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7616 string ZabFromKeyMintStr;
7617 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01007618 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05007619 &ZabFromKeyMintStr));
7620
7621 } else {
7622 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01007623 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007624 }
7625
7626 CheckedDeleteKey();
7627 }
7628 }
7629}
7630
David Drysdale42fe1892021-10-14 14:43:46 +01007631/*
7632 * KeyAgreementTest.EcdhCurve25519
7633 *
7634 * Verifies that ECDH works for curve25519. This is also covered by the general
7635 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
7636 * KeyMint 1.0.
7637 */
7638TEST_P(KeyAgreementTest, EcdhCurve25519) {
7639 if (!Curve25519Supported()) {
7640 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7641 }
7642
7643 // Generate EC key in KeyMint (only access to public key material)
7644 EcCurve curve = EcCurve::CURVE_25519;
7645 EVP_PKEY_Ptr kmPubKey = nullptr;
7646 GenerateKeyMintEcKey(curve, &kmPubKey);
7647
7648 // Generate EC key on same curve locally (with access to private key material).
7649 EVP_PKEY_Ptr privKey;
7650 vector<uint8_t> encodedPublicKey;
7651 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7652
7653 // Agree on a key between local and KeyMint and check it.
7654 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7655
7656 CheckedDeleteKey();
7657}
7658
7659/*
7660 * KeyAgreementTest.EcdhCurve25519Imported
7661 *
7662 * Verifies that ECDH works for an imported curve25519 key.
7663 */
7664TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
7665 if (!Curve25519Supported()) {
7666 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7667 }
7668
7669 // Import x25519 key into KeyMint.
7670 EcCurve curve = EcCurve::CURVE_25519;
7671 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
7672 .Authorization(TAG_NO_AUTH_REQUIRED)
7673 .EcdsaKey(EcCurve::CURVE_25519)
7674 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7675 .SetDefaultValidity(),
7676 KeyFormat::PKCS8, x25519_pkcs8_key));
7677 ASSERT_GT(cert_chain_.size(), 0);
7678 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7679 ASSERT_NE(kmKeyCert, nullptr);
7680 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
7681 ASSERT_NE(kmPubKey.get(), nullptr);
7682
7683 // Expect the import to emit corresponding public key data.
7684 size_t kmPubKeySize = 32;
7685 uint8_t kmPubKeyData[32];
7686 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7687 ASSERT_EQ(kmPubKeySize, 32);
7688 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
7689 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
7690
7691 // Generate EC key on same curve locally (with access to private key material).
7692 EVP_PKEY_Ptr privKey;
7693 vector<uint8_t> encodedPublicKey;
7694 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7695
7696 // Agree on a key between local and KeyMint and check it.
7697 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7698
7699 CheckedDeleteKey();
7700}
7701
7702/*
7703 * KeyAgreementTest.EcdhCurve25519InvalidSize
7704 *
7705 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
7706 */
7707TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
7708 if (!Curve25519Supported()) {
7709 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7710 }
7711
7712 // Generate EC key in KeyMint (only access to public key material)
7713 EcCurve curve = EcCurve::CURVE_25519;
7714 EVP_PKEY_Ptr kmPubKey = nullptr;
7715 GenerateKeyMintEcKey(curve, &kmPubKey);
7716
7717 // Generate EC key on same curve locally (with access to private key material).
7718 EVP_PKEY_Ptr privKey;
7719 vector<uint8_t> encodedPublicKey;
7720 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7721
7722 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7723 string ZabFromKeyMintStr;
7724 // Send in an incomplete public key.
7725 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
7726 &ZabFromKeyMintStr));
7727
7728 CheckedDeleteKey();
7729}
7730
7731/*
7732 * KeyAgreementTest.EcdhCurve25519Mismatch
7733 *
7734 * Verifies that ECDH fails between curve25519 and other curves.
7735 */
7736TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
7737 if (!Curve25519Supported()) {
7738 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7739 }
7740
7741 // Generate EC key in KeyMint (only access to public key material)
7742 EcCurve curve = EcCurve::CURVE_25519;
7743 EVP_PKEY_Ptr kmPubKey = nullptr;
7744 GenerateKeyMintEcKey(curve, &kmPubKey);
7745
7746 for (auto localCurve : ValidCurves()) {
7747 if (localCurve == curve) {
7748 continue;
7749 }
7750 // Generate EC key on a different curve locally (with access to private key material).
7751 EVP_PKEY_Ptr privKey;
7752 vector<uint8_t> encodedPublicKey;
7753 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
7754
7755 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7756 string ZabFromKeyMintStr;
7757 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
7758 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
7759 &ZabFromKeyMintStr));
7760 }
7761
7762 CheckedDeleteKey();
7763}
7764
David Zeuthene0c40892021-01-08 12:54:11 -05007765INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
7766
David Drysdaled2cc8c22021-04-15 13:29:45 +01007767using DestroyAttestationIdsTest = KeyMintAidlTestBase;
7768
7769// This is a problematic test, as it can render the device under test permanently unusable.
7770// Re-enable and run at your own risk.
7771TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
7772 auto result = DestroyAttestationIds();
7773 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
7774}
7775
7776INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
7777
Shawn Willdend659c7c2021-02-19 14:51:51 -07007778using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007779
David Drysdaledb0dcf52021-05-18 11:43:31 +01007780/*
7781 * EarlyBootKeyTest.CreateEarlyBootKeys
7782 *
7783 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
7784 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007785TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01007786 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007787 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7788 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7789
David Drysdaleadfe6112021-05-27 12:00:53 +01007790 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
7791 ASSERT_GT(keyData.blob.size(), 0U);
7792 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7793 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7794 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007795 CheckedDeleteKey(&aesKeyData.blob);
7796 CheckedDeleteKey(&hmacKeyData.blob);
7797 CheckedDeleteKey(&rsaKeyData.blob);
7798 CheckedDeleteKey(&ecdsaKeyData.blob);
7799}
7800
David Drysdaledb0dcf52021-05-18 11:43:31 +01007801/*
David Drysdaleadfe6112021-05-27 12:00:53 +01007802 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
7803 *
7804 * Verifies that creating an early boot key with attestation succeeds.
7805 */
7806TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
7807 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
7808 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
7809 builder->AttestationChallenge("challenge");
7810 builder->AttestationApplicationId("app_id");
7811 });
7812
7813 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00007814 // Strongbox may not support factory attestation. Key creation might fail with
7815 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
7816 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
7817 continue;
7818 }
David Drysdaleadfe6112021-05-27 12:00:53 +01007819 ASSERT_GT(keyData.blob.size(), 0U);
7820 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7821 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7822 }
7823 CheckedDeleteKey(&aesKeyData.blob);
7824 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00007825 if (rsaKeyData.blob.size() != 0U) {
7826 CheckedDeleteKey(&rsaKeyData.blob);
7827 }
7828 if (ecdsaKeyData.blob.size() != 0U) {
7829 CheckedDeleteKey(&ecdsaKeyData.blob);
7830 }
David Drysdaleadfe6112021-05-27 12:00:53 +01007831}
7832
7833/*
7834 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01007835 *
7836 * Verifies that using early boot keys at a later stage fails.
7837 */
7838TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
7839 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7840 .Authorization(TAG_NO_AUTH_REQUIRED)
7841 .Authorization(TAG_EARLY_BOOT_ONLY)
7842 .HmacKey(128)
7843 .Digest(Digest::SHA_2_256)
7844 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
7845 AuthorizationSet output_params;
7846 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
7847 AuthorizationSetBuilder()
7848 .Digest(Digest::SHA_2_256)
7849 .Authorization(TAG_MAC_LENGTH, 256),
7850 &output_params));
7851}
7852
7853/*
7854 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
7855 *
7856 * Verifies that importing early boot keys fails.
7857 */
7858TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
7859 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
7860 .Authorization(TAG_NO_AUTH_REQUIRED)
7861 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01007862 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01007863 .Digest(Digest::SHA_2_256)
7864 .SetDefaultValidity(),
7865 KeyFormat::PKCS8, ec_256_key));
7866}
7867
David Drysdaled2cc8c22021-04-15 13:29:45 +01007868// 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 +00007869// boot stage, which no proper Android device is by the time we can run VTS. To use this,
7870// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
7871// early boot, so you'll have to reboot between runs.
7872TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
7873 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7874 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7875 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
7876 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7877 EXPECT_TRUE(
7878 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7879 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7880 EXPECT_TRUE(
7881 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7882
7883 // Should be able to use keys, since early boot has not ended
7884 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7885 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7886 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7887 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7888
7889 // End early boot
7890 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
7891 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
7892
7893 // Should not be able to use already-created keys.
7894 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
7895 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
7896 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
7897 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
7898
7899 CheckedDeleteKey(&aesKeyData.blob);
7900 CheckedDeleteKey(&hmacKeyData.blob);
7901 CheckedDeleteKey(&rsaKeyData.blob);
7902 CheckedDeleteKey(&ecdsaKeyData.blob);
7903
7904 // Should not be able to create new keys
7905 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
7906 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
7907
7908 CheckedDeleteKey(&aesKeyData.blob);
7909 CheckedDeleteKey(&hmacKeyData.blob);
7910 CheckedDeleteKey(&rsaKeyData.blob);
7911 CheckedDeleteKey(&ecdsaKeyData.blob);
7912}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007913
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007914INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
7915
Shawn Willdend659c7c2021-02-19 14:51:51 -07007916using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007917
7918// This may be a problematic test. It can't be run repeatedly without unlocking the device in
7919// between runs... and on most test devices there are no enrolled credentials so it can't be
7920// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
7921// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
7922// a manual test process, which includes unlocking between runs, which is why it's included here.
7923// Well, that and the fact that it's the only test we can do without also making calls into the
7924// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
7925// implications might be, so that may or may not be a solution.
7926TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
7927 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7928 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
7929
7930 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7931 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7932 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7933 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7934
7935 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01007936 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007937 ASSERT_EQ(ErrorCode::OK, rc);
7938 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
7939 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
7940 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
7941 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
7942
7943 CheckedDeleteKey(&aesKeyData.blob);
7944 CheckedDeleteKey(&hmacKeyData.blob);
7945 CheckedDeleteKey(&rsaKeyData.blob);
7946 CheckedDeleteKey(&ecdsaKeyData.blob);
7947}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007948
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007949INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
7950
Janis Danisevskis24c04702020-12-16 18:28:39 -08007951} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07007952
7953int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07007954 std::cout << "Testing ";
7955 auto halInstances =
7956 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
7957 std::cout << "HAL instances:\n";
7958 for (auto& entry : halInstances) {
7959 std::cout << " " << entry << '\n';
7960 }
7961
Selene Huang31ab4042020-04-29 04:22:39 -07007962 ::testing::InitGoogleTest(&argc, argv);
7963 for (int i = 1; i < argc; ++i) {
7964 if (argv[i][0] == '-') {
7965 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07007966 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
7967 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07007968 }
7969 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07007970 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
7971 dump_Attestations = true;
7972 } else {
7973 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07007974 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00007975 if (std::string(argv[i]) == "--skip_boot_pl_check") {
7976 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
7977 // be run in emulated environments that don't have the normal bootloader
7978 // interactions.
7979 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
7980 }
Selene Huang31ab4042020-04-29 04:22:39 -07007981 }
7982 }
Shawn Willden08a7e432020-12-11 13:05:27 +00007983 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07007984}