blob: f5239edf0ea4a2496499921ce5fd07669358caaa [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) {
1952 auto challenge = "hello";
1953 auto app_id = "foo";
1954 auto subject = "cert subj 2";
1955 vector<uint8_t> subject_der(make_name_from_str(subject));
1956 uint64_t serial_int = 0x1010;
1957 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
1958 const AuthorizationSetBuilder base_builder =
1959 AuthorizationSetBuilder()
1960 .Authorization(TAG_NO_AUTH_REQUIRED)
1961 .EcdsaSigningKey(EcCurve::P_256)
1962 .Digest(Digest::NONE)
1963 .AttestationChallenge(challenge)
1964 .AttestationApplicationId(app_id)
1965 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
1966 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
1967 .SetDefaultValidity();
1968
1969 // Various ATTESTATION_ID_* tags that map to fields in the attestation extension ASN.1 schema.
1970 auto extra_tags = AuthorizationSetBuilder();
1971 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_BRAND, "ro.product.brand");
1972 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_DEVICE, "ro.product.device");
1973 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_PRODUCT, "ro.product.name");
1974 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_SERIAL, "ro.serial");
1975 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MANUFACTURER, "ro.product.manufacturer");
1976 add_tag_from_prop(&extra_tags, TAG_ATTESTATION_ID_MODEL, "ro.product.model");
1977
1978 for (const KeyParameter& tag : extra_tags) {
1979 SCOPED_TRACE(testing::Message() << "tag-" << tag);
1980 vector<uint8_t> key_blob;
1981 vector<KeyCharacteristics> key_characteristics;
1982 AuthorizationSetBuilder builder = base_builder;
1983 builder.push_back(tag);
1984 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00001985 // Strongbox may not support factory provisioned attestation key.
1986 if (SecLevel() == SecurityLevel::STRONGBOX) {
1987 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) return;
1988 }
David Drysdalec53b7d92021-10-11 12:35:58 +01001989 if (result == ErrorCode::CANNOT_ATTEST_IDS) {
1990 // Device ID attestation is optional; KeyMint may not support it at all.
1991 continue;
1992 }
1993 ASSERT_EQ(result, ErrorCode::OK);
1994 ASSERT_GT(key_blob.size(), 0U);
1995
1996 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
1997 ASSERT_GT(cert_chain_.size(), 0);
1998 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
1999
2000 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2001 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2002
2003 // The attested key characteristics will not contain APPLICATION_ID_* fields (their
2004 // spec definitions all have "Must never appear in KeyCharacteristics"), but the
2005 // attestation extension should contain them, so make sure the extra tag is added.
2006 hw_enforced.push_back(tag);
2007
2008 // Verifying the attestation record will check for the specific tag because
2009 // it's included in the authorizations.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002010 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2011 hw_enforced, SecLevel(),
2012 cert_chain_[0].encodedCertificate));
David Drysdalec53b7d92021-10-11 12:35:58 +01002013
2014 CheckedDeleteKey(&key_blob);
2015 }
2016}
2017
2018/*
David Drysdale565ccc72021-10-11 12:49:50 +01002019 * NewKeyGenerationTest.EcdsaAttestationUniqueId
2020 *
2021 * Verifies that creation of an attested ECDSA key with a UNIQUE_ID included.
2022 */
2023TEST_P(NewKeyGenerationTest, EcdsaAttestationUniqueId) {
2024 auto get_unique_id = [this](const std::string& app_id, uint64_t datetime,
David Drysdale13f2a402021-11-01 11:40:08 +00002025 vector<uint8_t>* unique_id, bool reset = false) {
David Drysdale565ccc72021-10-11 12:49:50 +01002026 auto challenge = "hello";
2027 auto subject = "cert subj 2";
2028 vector<uint8_t> subject_der(make_name_from_str(subject));
2029 uint64_t serial_int = 0x1010;
2030 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
David Drysdale13f2a402021-11-01 11:40:08 +00002031 AuthorizationSetBuilder builder =
David Drysdale565ccc72021-10-11 12:49:50 +01002032 AuthorizationSetBuilder()
2033 .Authorization(TAG_NO_AUTH_REQUIRED)
2034 .Authorization(TAG_INCLUDE_UNIQUE_ID)
2035 .EcdsaSigningKey(EcCurve::P_256)
2036 .Digest(Digest::NONE)
2037 .AttestationChallenge(challenge)
2038 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2039 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2040 .AttestationApplicationId(app_id)
2041 .Authorization(TAG_CREATION_DATETIME, datetime)
2042 .SetDefaultValidity();
David Drysdale13f2a402021-11-01 11:40:08 +00002043 if (reset) {
2044 builder.Authorization(TAG_RESET_SINCE_ID_ROTATION);
2045 }
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002046 auto result = GenerateKey(builder);
2047 if (SecLevel() == SecurityLevel::STRONGBOX) {
2048 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2049 result = GenerateKeyWithSelfSignedAttestKey(
2050 AuthorizationSetBuilder()
2051 .EcdsaKey(EcCurve::P_256)
2052 .AttestKey()
2053 .SetDefaultValidity(), /* attest key params */
2054 builder, &key_blob_, &key_characteristics_, &cert_chain_);
2055 }
2056 }
2057 ASSERT_EQ(ErrorCode::OK, result);
David Drysdale565ccc72021-10-11 12:49:50 +01002058 ASSERT_GT(key_blob_.size(), 0U);
2059
2060 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2061 ASSERT_GT(cert_chain_.size(), 0);
2062 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2063
2064 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics_);
2065 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics_);
2066
2067 // Check that the unique ID field in the extension is non-empty.
David Drysdale7dff4fc2021-12-10 10:10:52 +00002068 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, sw_enforced,
2069 hw_enforced, SecLevel(),
2070 cert_chain_[0].encodedCertificate, unique_id));
David Drysdale565ccc72021-10-11 12:49:50 +01002071 EXPECT_GT(unique_id->size(), 0);
2072 CheckedDeleteKey();
2073 };
2074
2075 // Generate unique ID
2076 auto app_id = "foo";
2077 uint64_t cert_date = 1619621648000; // Wed Apr 28 14:54:08 2021 in ms since epoch
2078 vector<uint8_t> unique_id;
2079 get_unique_id(app_id, cert_date, &unique_id);
2080
2081 // Generating a new key with the same parameters should give the same unique ID.
2082 vector<uint8_t> unique_id2;
2083 get_unique_id(app_id, cert_date, &unique_id2);
2084 EXPECT_EQ(unique_id, unique_id2);
2085
2086 // Generating a new key with a slightly different date should give the same unique ID.
2087 uint64_t rounded_date = cert_date / 2592000000LLU;
2088 uint64_t min_date = rounded_date * 2592000000LLU;
2089 uint64_t max_date = ((rounded_date + 1) * 2592000000LLU) - 1;
2090
2091 vector<uint8_t> unique_id3;
2092 get_unique_id(app_id, min_date, &unique_id3);
2093 EXPECT_EQ(unique_id, unique_id3);
2094
2095 vector<uint8_t> unique_id4;
2096 get_unique_id(app_id, max_date, &unique_id4);
2097 EXPECT_EQ(unique_id, unique_id4);
2098
2099 // A different attestation application ID should yield a different unique ID.
2100 auto app_id2 = "different_foo";
2101 vector<uint8_t> unique_id5;
2102 get_unique_id(app_id2, cert_date, &unique_id5);
2103 EXPECT_NE(unique_id, unique_id5);
2104
2105 // A radically different date should yield a different unique ID.
2106 vector<uint8_t> unique_id6;
2107 get_unique_id(app_id, 1611621648000, &unique_id6);
2108 EXPECT_NE(unique_id, unique_id6);
2109
2110 vector<uint8_t> unique_id7;
2111 get_unique_id(app_id, max_date + 1, &unique_id7);
2112 EXPECT_NE(unique_id, unique_id7);
2113
2114 vector<uint8_t> unique_id8;
2115 get_unique_id(app_id, min_date - 1, &unique_id8);
2116 EXPECT_NE(unique_id, unique_id8);
David Drysdale13f2a402021-11-01 11:40:08 +00002117
2118 // Marking RESET_SINCE_ID_ROTATION should give a different unique ID.
2119 vector<uint8_t> unique_id9;
2120 get_unique_id(app_id, cert_date, &unique_id9, /* reset_id = */ true);
2121 EXPECT_NE(unique_id, unique_id9);
David Drysdale565ccc72021-10-11 12:49:50 +01002122}
2123
2124/*
David Drysdale37af4b32021-05-14 16:46:59 +01002125 * NewKeyGenerationTest.EcdsaAttestationTagNoApplicationId
2126 *
2127 * Verifies that creation of an attested ECDSA key does not include APPLICATION_ID.
2128 */
2129TEST_P(NewKeyGenerationTest, EcdsaAttestationTagNoApplicationId) {
2130 auto challenge = "hello";
2131 auto attest_app_id = "foo";
2132 auto subject = "cert subj 2";
2133 vector<uint8_t> subject_der(make_name_from_str(subject));
2134 uint64_t serial_int = 0x1010;
2135 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2136
2137 // Earlier versions of the attestation extension schema included a slot:
2138 // applicationId [601] EXPLICIT OCTET_STRING OPTIONAL,
2139 // This should never have been included, and should never be filled in.
2140 // Generate an attested key that include APPLICATION_ID and APPLICATION_DATA,
2141 // to confirm that this field never makes it into the attestation extension.
2142 vector<uint8_t> key_blob;
2143 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002144 auto builder = AuthorizationSetBuilder()
2145 .Authorization(TAG_NO_AUTH_REQUIRED)
2146 .EcdsaSigningKey(EcCurve::P_256)
2147 .Digest(Digest::NONE)
2148 .AttestationChallenge(challenge)
2149 .AttestationApplicationId(attest_app_id)
2150 .Authorization(TAG_APPLICATION_ID, "client_id")
2151 .Authorization(TAG_APPLICATION_DATA, "appdata")
2152 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2153 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2154 .SetDefaultValidity();
2155
2156 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002157 // Strongbox may not support factory provisioned attestation key.
2158 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002159 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2160 result = GenerateKeyWithSelfSignedAttestKey(
2161 AuthorizationSetBuilder()
2162 .EcdsaKey(EcCurve::P_256)
2163 .AttestKey()
2164 .SetDefaultValidity(), /* attest key params */
2165 builder, &key_blob, &key_characteristics);
2166 }
subrahmanyaman05642492022-02-05 07:10:56 +00002167 }
David Drysdale37af4b32021-05-14 16:46:59 +01002168 ASSERT_EQ(result, ErrorCode::OK);
2169 ASSERT_GT(key_blob.size(), 0U);
2170
2171 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2172 ASSERT_GT(cert_chain_.size(), 0);
2173 verify_subject_and_serial(cert_chain_[0], serial_int, subject, /* self_signed = */ false);
2174
2175 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2176 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002177 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, attest_app_id, sw_enforced,
2178 hw_enforced, SecLevel(),
2179 cert_chain_[0].encodedCertificate));
David Drysdale37af4b32021-05-14 16:46:59 +01002180
2181 // Check that the app id is not in the cert.
2182 string app_id = "clientid";
2183 std::vector<uint8_t> needle(reinterpret_cast<const uint8_t*>(app_id.data()),
2184 reinterpret_cast<const uint8_t*>(app_id.data()) + app_id.size());
2185 ASSERT_EQ(std::search(cert_chain_[0].encodedCertificate.begin(),
2186 cert_chain_[0].encodedCertificate.end(), needle.begin(), needle.end()),
2187 cert_chain_[0].encodedCertificate.end());
2188
2189 CheckedDeleteKey(&key_blob);
2190}
2191
2192/*
Selene Huang4f64c222021-04-13 19:54:36 -07002193 * NewKeyGenerationTest.EcdsaSelfSignAttestation
2194 *
2195 * Verifies that if no challenge is provided to an Ecdsa key generation, then
2196 * the key will generate a self signed attestation.
2197 */
2198TEST_P(NewKeyGenerationTest, EcdsaSelfSignAttestation) {
Selene Huang6e46f142021-04-20 19:20:11 -07002199 auto subject = "cert subj 2";
2200 vector<uint8_t> subject_der(make_name_from_str(subject));
2201
2202 uint64_t serial_int = 0x123456FFF1234;
2203 vector<uint8_t> serial_blob(build_serial_blob(serial_int));
2204
David Drysdaledf09e542021-06-08 15:46:11 +01002205 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002206 vector<uint8_t> key_blob;
2207 vector<KeyCharacteristics> key_characteristics;
Selene Huang6e46f142021-04-20 19:20:11 -07002208 ASSERT_EQ(ErrorCode::OK,
2209 GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002210 .EcdsaSigningKey(curve)
Selene Huang6e46f142021-04-20 19:20:11 -07002211 .Digest(Digest::NONE)
2212 .Authorization(TAG_CERTIFICATE_SERIAL, serial_blob)
2213 .Authorization(TAG_CERTIFICATE_SUBJECT, subject_der)
2214 .SetDefaultValidity(),
2215 &key_blob, &key_characteristics));
Selene Huang4f64c222021-04-13 19:54:36 -07002216 ASSERT_GT(key_blob.size(), 0U);
2217 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002218 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002219
2220 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2221
2222 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002223 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002224
2225 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
Selene Huang6e46f142021-04-20 19:20:11 -07002226 verify_subject_and_serial(cert_chain_[0], serial_int, subject, false);
Selene Huang4f64c222021-04-13 19:54:36 -07002227 ASSERT_EQ(cert_chain_.size(), 1);
2228
2229 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2230 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2231
2232 CheckedDeleteKey(&key_blob);
2233 }
2234}
2235
2236/*
2237 * NewKeyGenerationTest.EcdsaAttestationRequireAppId
2238 *
2239 * Verifies that if attestation challenge is provided to Ecdsa key generation, then
2240 * app id must also be provided or else it will fail.
2241 */
2242TEST_P(NewKeyGenerationTest, EcdsaAttestationRequireAppId) {
2243 auto challenge = "hello";
2244 vector<uint8_t> key_blob;
2245 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002246 auto builder = AuthorizationSetBuilder()
2247 .EcdsaSigningKey(EcCurve::P_256)
2248 .Digest(Digest::NONE)
2249 .AttestationChallenge(challenge)
2250 .SetDefaultValidity();
Selene Huang4f64c222021-04-13 19:54:36 -07002251
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002252 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002253 // Strongbox may not support factory provisioned attestation key.
2254 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002255 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2256 result = GenerateKeyWithSelfSignedAttestKey(
2257 AuthorizationSetBuilder()
2258 .EcdsaKey(EcCurve::P_256)
2259 .AttestKey()
2260 .SetDefaultValidity(), /* attest key params */
2261 builder, &key_blob, &key_characteristics);
2262 }
subrahmanyaman05642492022-02-05 07:10:56 +00002263 }
2264 ASSERT_EQ(ErrorCode::ATTESTATION_APPLICATION_ID_MISSING, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002265}
2266
2267/*
2268 * NewKeyGenerationTest.EcdsaIgnoreAppId
2269 *
2270 * Verifies that if no challenge is provided to the Ecdsa key generation, then
2271 * any appid will be ignored, and keymint will generate a self sign certificate.
2272 */
2273TEST_P(NewKeyGenerationTest, EcdsaIgnoreAppId) {
2274 auto app_id = "foo";
2275
David Drysdaledf09e542021-06-08 15:46:11 +01002276 for (auto curve : ValidCurves()) {
Selene Huang4f64c222021-04-13 19:54:36 -07002277 vector<uint8_t> key_blob;
2278 vector<KeyCharacteristics> key_characteristics;
2279 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002280 .EcdsaSigningKey(curve)
Selene Huang4f64c222021-04-13 19:54:36 -07002281 .Digest(Digest::NONE)
2282 .AttestationApplicationId(app_id)
2283 .SetDefaultValidity(),
2284 &key_blob, &key_characteristics));
2285
2286 ASSERT_GT(key_blob.size(), 0U);
2287 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002288 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002289
2290 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2291
2292 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002293 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002294
2295 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2296 ASSERT_EQ(cert_chain_.size(), 1);
2297
2298 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2299 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
2300
2301 CheckedDeleteKey(&key_blob);
2302 }
2303}
2304
2305/*
2306 * NewKeyGenerationTest.AttestationApplicationIDLengthProperlyEncoded
2307 *
2308 * Verifies that the Attestation Application ID software enforced tag has a proper length encoding.
2309 * Some implementations break strict encoding rules by encoding a length between 127 and 256 in one
2310 * byte. Proper DER encoding specifies that for lengths greater than 127, one byte should be used
2311 * to specify how many following bytes will be used to encode the length.
2312 */
2313TEST_P(NewKeyGenerationTest, AttestationApplicationIDLengthProperlyEncoded) {
2314 auto challenge = "hello";
Selene Huang4f64c222021-04-13 19:54:36 -07002315 std::vector<uint32_t> app_id_lengths{143, 258};
2316
2317 for (uint32_t length : app_id_lengths) {
2318 const string app_id(length, 'a');
2319 vector<uint8_t> key_blob;
2320 vector<KeyCharacteristics> key_characteristics;
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002321 auto builder = AuthorizationSetBuilder()
2322 .Authorization(TAG_NO_AUTH_REQUIRED)
2323 .EcdsaSigningKey(EcCurve::P_256)
2324 .Digest(Digest::NONE)
2325 .AttestationChallenge(challenge)
2326 .AttestationApplicationId(app_id)
2327 .SetDefaultValidity();
2328
2329 auto result = GenerateKey(builder, &key_blob, &key_characteristics);
subrahmanyaman05642492022-02-05 07:10:56 +00002330 // Strongbox may not support factory provisioned attestation key.
2331 if (SecLevel() == SecurityLevel::STRONGBOX) {
subrahmanyaman7d9bc462022-03-16 01:40:39 +00002332 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
2333 result = GenerateKeyWithSelfSignedAttestKey(
2334 AuthorizationSetBuilder()
2335 .EcdsaKey(EcCurve::P_256)
2336 .AttestKey()
2337 .SetDefaultValidity(), /* attest key params */
2338 builder, &key_blob, &key_characteristics);
2339 }
subrahmanyaman05642492022-02-05 07:10:56 +00002340 }
2341 ASSERT_EQ(ErrorCode::OK, result);
Selene Huang4f64c222021-04-13 19:54:36 -07002342 ASSERT_GT(key_blob.size(), 0U);
2343 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002344 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002345
2346 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2347
2348 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002349 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, EcCurve::P_256)) << "Curve P256 missing";
Selene Huang4f64c222021-04-13 19:54:36 -07002350
2351 EXPECT_TRUE(ChainSignaturesAreValid(cert_chain_));
2352 ASSERT_GT(cert_chain_.size(), 0);
2353
2354 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
2355 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
David Drysdale7dff4fc2021-12-10 10:10:52 +00002356 EXPECT_TRUE(verify_attestation_record(AidlVersion(), challenge, app_id, //
Selene Huang4f64c222021-04-13 19:54:36 -07002357 sw_enforced, hw_enforced, SecLevel(),
2358 cert_chain_[0].encodedCertificate));
2359
2360 CheckedDeleteKey(&key_blob);
2361 }
2362}
2363
2364/*
Qi Wud22ec842020-11-26 13:27:53 +08002365 * NewKeyGenerationTest.LimitedUsageEcdsa
2366 *
2367 * Verifies that KeyMint can generate all required EC key sizes with limited usage, and that the
2368 * resulting keys have correct characteristics.
2369 */
2370TEST_P(NewKeyGenerationTest, LimitedUsageEcdsa) {
David Drysdaledf09e542021-06-08 15:46:11 +01002371 for (auto curve : ValidCurves()) {
Qi Wud22ec842020-11-26 13:27:53 +08002372 vector<uint8_t> key_blob;
2373 vector<KeyCharacteristics> key_characteristics;
2374 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
David Drysdaledf09e542021-06-08 15:46:11 +01002375 .EcdsaSigningKey(curve)
Qi Wud22ec842020-11-26 13:27:53 +08002376 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002377 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
2378 .SetDefaultValidity(),
Qi Wud22ec842020-11-26 13:27:53 +08002379 &key_blob, &key_characteristics));
2380
2381 ASSERT_GT(key_blob.size(), 0U);
2382 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002383 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002384
2385 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2386
2387 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::EC));
David Drysdaledf09e542021-06-08 15:46:11 +01002388 EXPECT_TRUE(crypto_params.Contains(TAG_EC_CURVE, curve)) << "Curve " << curve << "missing";
Qi Wud22ec842020-11-26 13:27:53 +08002389
2390 // Check the usage count limit tag appears in the authorizations.
2391 AuthorizationSet auths;
2392 for (auto& entry : key_characteristics) {
2393 auths.push_back(AuthorizationSet(entry.authorizations));
2394 }
2395 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2396 << "key usage count limit " << 1U << " missing";
2397
2398 CheckedDeleteKey(&key_blob);
2399 }
2400}
2401
2402/*
Selene Huang31ab4042020-04-29 04:22:39 -07002403 * NewKeyGenerationTest.EcdsaDefaultSize
2404 *
David Drysdaledf09e542021-06-08 15:46:11 +01002405 * Verifies that failing to specify a curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002406 * UNSUPPORTED_KEY_SIZE.
2407 */
2408TEST_P(NewKeyGenerationTest, EcdsaDefaultSize) {
2409 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2410 GenerateKey(AuthorizationSetBuilder()
2411 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2412 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08002413 .Digest(Digest::NONE)
2414 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002415}
2416
2417/*
David Drysdale42fe1892021-10-14 14:43:46 +01002418 * NewKeyGenerationTest.EcdsaInvalidCurve
Selene Huang31ab4042020-04-29 04:22:39 -07002419 *
David Drysdale42fe1892021-10-14 14:43:46 +01002420 * Verifies that specifying an invalid curve for EC key generation returns
Selene Huang31ab4042020-04-29 04:22:39 -07002421 * UNSUPPORTED_KEY_SIZE.
2422 */
David Drysdale42fe1892021-10-14 14:43:46 +01002423TEST_P(NewKeyGenerationTest, EcdsaInvalidCurve) {
David Drysdaledf09e542021-06-08 15:46:11 +01002424 for (auto curve : InvalidCurves()) {
Selene Huang31ab4042020-04-29 04:22:39 -07002425 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002426 vector<KeyCharacteristics> key_characteristics;
David Drysdale42fe1892021-10-14 14:43:46 +01002427 auto result = GenerateKey(AuthorizationSetBuilder()
2428 .EcdsaSigningKey(curve)
2429 .Digest(Digest::NONE)
2430 .SetDefaultValidity(),
2431 &key_blob, &key_characteristics);
2432 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2433 result == ErrorCode::UNSUPPORTED_EC_CURVE);
Selene Huang31ab4042020-04-29 04:22:39 -07002434 }
2435
David Drysdaledf09e542021-06-08 15:46:11 +01002436 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2437 GenerateKey(AuthorizationSetBuilder()
2438 .Authorization(TAG_ALGORITHM, Algorithm::EC)
2439 .Authorization(TAG_KEY_SIZE, 190)
2440 .SigningKey()
2441 .Digest(Digest::NONE)
2442 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002443}
2444
2445/*
Prashant Patil60f8d4d2022-03-29 13:11:09 +00002446 * NewKeyGenerationTest.EcdsaMissingCurve
2447 *
2448 * Verifies that EC key generation fails if EC_CURVE not specified after KeyMint V2.
2449 */
2450TEST_P(NewKeyGenerationTest, EcdsaMissingCurve) {
2451 if (AidlVersion() < 2) {
2452 /*
2453 * The KeyMint V1 spec required that EC_CURVE be specified for EC keys.
2454 * However, this was not checked at the time so we can only be strict about checking this
2455 * for implementations of KeyMint version 2 and above.
2456 */
2457 GTEST_SKIP() << "Requiring EC_CURVE only strict since KeyMint v2";
2458 }
2459 /* If EC_CURVE not provided, generateKey
2460 * must return ErrorCode::UNSUPPORTED_KEY_SIZE or ErrorCode::UNSUPPORTED_EC_CURVE.
2461 */
2462 auto result = GenerateKey(
2463 AuthorizationSetBuilder().EcdsaKey(256).Digest(Digest::NONE).SetDefaultValidity());
2464 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_KEY_SIZE ||
2465 result == ErrorCode::UNSUPPORTED_EC_CURVE);
2466}
2467
2468/*
Selene Huang31ab4042020-04-29 04:22:39 -07002469 * NewKeyGenerationTest.EcdsaMismatchKeySize
2470 *
2471 * Verifies that specifying mismatched key size and curve for EC key generation returns
2472 * INVALID_ARGUMENT.
2473 */
2474TEST_P(NewKeyGenerationTest, EcdsaMismatchKeySize) {
David Drysdale513bf122021-10-06 11:53:13 +01002475 if (SecLevel() == SecurityLevel::STRONGBOX) {
2476 GTEST_SKIP() << "Test not applicable to StrongBox device";
2477 }
Selene Huang31ab4042020-04-29 04:22:39 -07002478
David Drysdaledf09e542021-06-08 15:46:11 +01002479 auto result = GenerateKey(AuthorizationSetBuilder()
David Drysdaleff819282021-08-18 16:45:50 +01002480 .Authorization(TAG_ALGORITHM, Algorithm::EC)
David Drysdaledf09e542021-06-08 15:46:11 +01002481 .Authorization(TAG_KEY_SIZE, 224)
2482 .Authorization(TAG_EC_CURVE, EcCurve::P_256)
David Drysdaleff819282021-08-18 16:45:50 +01002483 .SigningKey()
David Drysdaledf09e542021-06-08 15:46:11 +01002484 .Digest(Digest::NONE)
2485 .SetDefaultValidity());
David Drysdaleff819282021-08-18 16:45:50 +01002486 ASSERT_TRUE(result == ErrorCode::INVALID_ARGUMENT);
Selene Huang31ab4042020-04-29 04:22:39 -07002487}
2488
2489/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01002490 * NewKeyGenerationTest.EcdsaAllValidCurves
Selene Huang31ab4042020-04-29 04:22:39 -07002491 *
2492 * Verifies that keymint does not support any curve designated as unsupported.
2493 */
2494TEST_P(NewKeyGenerationTest, EcdsaAllValidCurves) {
2495 Digest digest;
2496 if (SecLevel() == SecurityLevel::STRONGBOX) {
2497 digest = Digest::SHA_2_256;
2498 } else {
2499 digest = Digest::SHA_2_512;
2500 }
2501 for (auto curve : ValidCurves()) {
Janis Danisevskis164bb872021-02-09 11:30:25 -08002502 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2503 .EcdsaSigningKey(curve)
2504 .Digest(digest)
2505 .SetDefaultValidity()))
Selene Huang31ab4042020-04-29 04:22:39 -07002506 << "Failed to generate key on curve: " << curve;
2507 CheckedDeleteKey();
2508 }
2509}
2510
2511/*
2512 * NewKeyGenerationTest.Hmac
2513 *
2514 * Verifies that keymint supports all required digests, and that the resulting keys have correct
2515 * characteristics.
2516 */
2517TEST_P(NewKeyGenerationTest, Hmac) {
2518 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2519 vector<uint8_t> key_blob;
Shawn Willden7f424372021-01-10 18:06:50 -07002520 vector<KeyCharacteristics> key_characteristics;
Selene Huang31ab4042020-04-29 04:22:39 -07002521 constexpr size_t key_size = 128;
2522 ASSERT_EQ(ErrorCode::OK,
2523 GenerateKey(
2524 AuthorizationSetBuilder().HmacKey(key_size).Digest(digest).Authorization(
2525 TAG_MIN_MAC_LENGTH, 128),
2526 &key_blob, &key_characteristics));
2527
2528 ASSERT_GT(key_blob.size(), 0U);
2529 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002530 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang31ab4042020-04-29 04:22:39 -07002531
Shawn Willden7f424372021-01-10 18:06:50 -07002532 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2533 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2534 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2535 << "Key size " << key_size << "missing";
Selene Huang31ab4042020-04-29 04:22:39 -07002536
2537 CheckedDeleteKey(&key_blob);
2538 }
2539}
2540
2541/*
Selene Huang4f64c222021-04-13 19:54:36 -07002542 * NewKeyGenerationTest.HmacNoAttestation
2543 *
2544 * Verifies that for Hmac key generation, no attestation will be generated even if challenge
2545 * and app id are provided.
2546 */
2547TEST_P(NewKeyGenerationTest, HmacNoAttestation) {
2548 auto challenge = "hello";
2549 auto app_id = "foo";
2550
2551 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2552 vector<uint8_t> key_blob;
2553 vector<KeyCharacteristics> key_characteristics;
2554 constexpr size_t key_size = 128;
2555 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2556 .HmacKey(key_size)
2557 .Digest(digest)
2558 .AttestationChallenge(challenge)
2559 .AttestationApplicationId(app_id)
2560 .Authorization(TAG_MIN_MAC_LENGTH, 128),
2561 &key_blob, &key_characteristics));
2562
2563 ASSERT_GT(key_blob.size(), 0U);
2564 ASSERT_EQ(cert_chain_.size(), 0);
2565 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002566 CheckCharacteristics(key_blob, key_characteristics);
Selene Huang4f64c222021-04-13 19:54:36 -07002567
2568 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2569 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2570 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2571 << "Key size " << key_size << "missing";
2572
2573 CheckedDeleteKey(&key_blob);
2574 }
2575}
2576
2577/*
Qi Wud22ec842020-11-26 13:27:53 +08002578 * NewKeyGenerationTest.LimitedUsageHmac
2579 *
2580 * Verifies that KeyMint supports all required digests with limited usage Hmac, and that the
2581 * resulting keys have correct characteristics.
2582 */
2583TEST_P(NewKeyGenerationTest, LimitedUsageHmac) {
2584 for (auto digest : ValidDigests(false /* withNone */, true /* withMD5 */)) {
2585 vector<uint8_t> key_blob;
2586 vector<KeyCharacteristics> key_characteristics;
2587 constexpr size_t key_size = 128;
2588 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2589 .HmacKey(key_size)
2590 .Digest(digest)
2591 .Authorization(TAG_MIN_MAC_LENGTH, 128)
2592 .Authorization(TAG_USAGE_COUNT_LIMIT, 1),
2593 &key_blob, &key_characteristics));
2594
2595 ASSERT_GT(key_blob.size(), 0U);
2596 CheckBaseParams(key_characteristics);
David Drysdale300b5552021-05-20 12:05:26 +01002597 CheckCharacteristics(key_blob, key_characteristics);
Qi Wud22ec842020-11-26 13:27:53 +08002598
2599 AuthorizationSet crypto_params = SecLevelAuthorizations(key_characteristics);
2600 EXPECT_TRUE(crypto_params.Contains(TAG_ALGORITHM, Algorithm::HMAC));
2601 EXPECT_TRUE(crypto_params.Contains(TAG_KEY_SIZE, key_size))
2602 << "Key size " << key_size << "missing";
2603
2604 // Check the usage count limit tag appears in the authorizations.
2605 AuthorizationSet auths;
2606 for (auto& entry : key_characteristics) {
2607 auths.push_back(AuthorizationSet(entry.authorizations));
2608 }
2609 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
2610 << "key usage count limit " << 1U << " missing";
2611
2612 CheckedDeleteKey(&key_blob);
2613 }
2614}
2615
2616/*
Selene Huang31ab4042020-04-29 04:22:39 -07002617 * NewKeyGenerationTest.HmacCheckKeySizes
2618 *
2619 * Verifies that keymint supports all key sizes, and rejects all invalid key sizes.
2620 */
2621TEST_P(NewKeyGenerationTest, HmacCheckKeySizes) {
2622 for (size_t key_size = 0; key_size <= 512; ++key_size) {
2623 if (key_size < 64 || key_size % 8 != 0) {
2624 // To keep this test from being very slow, we only test a random fraction of
2625 // non-byte key sizes. We test only ~10% of such cases. Since there are 392 of
2626 // them, we expect to run ~40 of them in each run.
2627 if (key_size % 8 == 0 || random() % 10 == 0) {
2628 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2629 GenerateKey(AuthorizationSetBuilder()
2630 .HmacKey(key_size)
2631 .Digest(Digest::SHA_2_256)
2632 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2633 << "HMAC key size " << key_size << " invalid";
2634 }
2635 } else {
2636 EXPECT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2637 .HmacKey(key_size)
2638 .Digest(Digest::SHA_2_256)
2639 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2640 << "Failed to generate HMAC key of size " << key_size;
2641 CheckedDeleteKey();
2642 }
2643 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002644 if (SecLevel() == SecurityLevel::STRONGBOX) {
2645 // STRONGBOX devices must not support keys larger than 512 bits.
2646 size_t key_size = 520;
2647 EXPECT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
2648 GenerateKey(AuthorizationSetBuilder()
2649 .HmacKey(key_size)
2650 .Digest(Digest::SHA_2_256)
2651 .Authorization(TAG_MIN_MAC_LENGTH, 256)))
2652 << "HMAC key size " << key_size << " unexpectedly valid";
2653 }
Selene Huang31ab4042020-04-29 04:22:39 -07002654}
2655
2656/*
2657 * NewKeyGenerationTest.HmacCheckMinMacLengths
2658 *
2659 * Verifies that keymint supports all required MAC lengths and rejects all invalid lengths. This
2660 * test is probabilistic in order to keep the runtime down, but any failure prints out the
2661 * specific MAC length that failed, so reproducing a failed run will be easy.
2662 */
2663TEST_P(NewKeyGenerationTest, HmacCheckMinMacLengths) {
2664 for (size_t min_mac_length = 0; min_mac_length <= 256; ++min_mac_length) {
2665 if (min_mac_length < 64 || min_mac_length % 8 != 0) {
2666 // To keep this test from being very long, we only test a random fraction of
2667 // non-byte lengths. We test only ~10% of such cases. Since there are 172 of them,
2668 // we expect to run ~17 of them in each run.
2669 if (min_mac_length % 8 == 0 || random() % 10 == 0) {
2670 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2671 GenerateKey(AuthorizationSetBuilder()
2672 .HmacKey(128)
2673 .Digest(Digest::SHA_2_256)
2674 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2675 << "HMAC min mac length " << min_mac_length << " invalid.";
2676 }
2677 } else {
2678 EXPECT_EQ(ErrorCode::OK,
2679 GenerateKey(AuthorizationSetBuilder()
2680 .HmacKey(128)
2681 .Digest(Digest::SHA_2_256)
2682 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2683 << "Failed to generate HMAC key with min MAC length " << min_mac_length;
2684 CheckedDeleteKey();
2685 }
2686 }
David Drysdaled2cc8c22021-04-15 13:29:45 +01002687
2688 // Minimum MAC length must be no more than 512 bits.
2689 size_t min_mac_length = 520;
2690 EXPECT_EQ(ErrorCode::UNSUPPORTED_MIN_MAC_LENGTH,
2691 GenerateKey(AuthorizationSetBuilder()
2692 .HmacKey(128)
2693 .Digest(Digest::SHA_2_256)
2694 .Authorization(TAG_MIN_MAC_LENGTH, min_mac_length)))
2695 << "HMAC min mac length " << min_mac_length << " invalid.";
Selene Huang31ab4042020-04-29 04:22:39 -07002696}
2697
2698/*
2699 * NewKeyGenerationTest.HmacMultipleDigests
2700 *
2701 * Verifies that keymint rejects HMAC key generation with multiple specified digest algorithms.
2702 */
2703TEST_P(NewKeyGenerationTest, HmacMultipleDigests) {
David Drysdale513bf122021-10-06 11:53:13 +01002704 if (SecLevel() == SecurityLevel::STRONGBOX) {
2705 GTEST_SKIP() << "Test not applicable to StrongBox device";
2706 }
Selene Huang31ab4042020-04-29 04:22:39 -07002707
2708 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2709 GenerateKey(AuthorizationSetBuilder()
2710 .HmacKey(128)
2711 .Digest(Digest::SHA1)
2712 .Digest(Digest::SHA_2_256)
2713 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2714}
2715
2716/*
2717 * NewKeyGenerationTest.HmacDigestNone
2718 *
2719 * Verifies that keymint rejects HMAC key generation with no digest or Digest::NONE
2720 */
2721TEST_P(NewKeyGenerationTest, HmacDigestNone) {
2722 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2723 GenerateKey(AuthorizationSetBuilder().HmacKey(128).Authorization(TAG_MIN_MAC_LENGTH,
2724 128)));
2725
2726 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
2727 GenerateKey(AuthorizationSetBuilder()
2728 .HmacKey(128)
2729 .Digest(Digest::NONE)
2730 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
2731}
2732
Selene Huang4f64c222021-04-13 19:54:36 -07002733/*
2734 * NewKeyGenerationTest.AesNoAttestation
2735 *
2736 * Verifies that attestation parameters to AES keys are ignored and generateKey
2737 * will succeed.
2738 */
2739TEST_P(NewKeyGenerationTest, AesNoAttestation) {
2740 auto challenge = "hello";
2741 auto app_id = "foo";
2742
2743 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2744 .Authorization(TAG_NO_AUTH_REQUIRED)
2745 .AesEncryptionKey(128)
2746 .EcbMode()
2747 .Padding(PaddingMode::PKCS7)
2748 .AttestationChallenge(challenge)
2749 .AttestationApplicationId(app_id)));
2750
2751 ASSERT_EQ(cert_chain_.size(), 0);
2752}
2753
2754/*
2755 * NewKeyGenerationTest.TripleDesNoAttestation
2756 *
2757 * Verifies that attesting parameters to 3DES keys are ignored and generate key
2758 * will be successful. No attestation should be generated.
2759 */
2760TEST_P(NewKeyGenerationTest, TripleDesNoAttestation) {
2761 auto challenge = "hello";
2762 auto app_id = "foo";
2763
2764 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2765 .TripleDesEncryptionKey(168)
2766 .BlockMode(BlockMode::ECB)
2767 .Authorization(TAG_NO_AUTH_REQUIRED)
2768 .Padding(PaddingMode::NONE)
2769 .AttestationChallenge(challenge)
2770 .AttestationApplicationId(app_id)));
2771 ASSERT_EQ(cert_chain_.size(), 0);
2772}
2773
Selene Huang31ab4042020-04-29 04:22:39 -07002774INSTANTIATE_KEYMINT_AIDL_TEST(NewKeyGenerationTest);
2775
2776typedef KeyMintAidlTestBase SigningOperationsTest;
2777
2778/*
2779 * SigningOperationsTest.RsaSuccess
2780 *
2781 * Verifies that raw RSA signature operations succeed.
2782 */
2783TEST_P(SigningOperationsTest, RsaSuccess) {
2784 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2785 .RsaSigningKey(2048, 65537)
2786 .Digest(Digest::NONE)
2787 .Padding(PaddingMode::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002788 .Authorization(TAG_NO_AUTH_REQUIRED)
2789 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002790 string message = "12345678901234567890123456789012";
2791 string signature = SignMessage(
2792 message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
David Drysdaledf8f52e2021-05-06 08:10:58 +01002793 LocalVerifyMessage(message, signature,
2794 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
2795}
2796
2797/*
2798 * SigningOperationsTest.RsaAllPaddingsAndDigests
2799 *
2800 * Verifies RSA signature/verification for all padding modes and digests.
2801 */
2802TEST_P(SigningOperationsTest, RsaAllPaddingsAndDigests) {
2803 auto authorizations = AuthorizationSetBuilder()
2804 .Authorization(TAG_NO_AUTH_REQUIRED)
2805 .RsaSigningKey(2048, 65537)
2806 .Digest(ValidDigests(true /* withNone */, true /* withMD5 */))
2807 .Padding(PaddingMode::NONE)
2808 .Padding(PaddingMode::RSA_PSS)
2809 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2810 .SetDefaultValidity();
2811
2812 ASSERT_EQ(ErrorCode::OK, GenerateKey(authorizations));
2813
2814 string message(128, 'a');
2815 string corrupt_message(message);
2816 ++corrupt_message[corrupt_message.size() / 2];
2817
2818 for (auto padding :
2819 {PaddingMode::NONE, PaddingMode::RSA_PSS, PaddingMode::RSA_PKCS1_1_5_SIGN}) {
2820 for (auto digest : ValidDigests(true /* withNone */, true /* withMD5 */)) {
2821 if (padding == PaddingMode::NONE && digest != Digest::NONE) {
2822 // Digesting only makes sense with padding.
2823 continue;
2824 }
2825
2826 if (padding == PaddingMode::RSA_PSS && digest == Digest::NONE) {
2827 // PSS requires digesting.
2828 continue;
2829 }
2830
2831 string signature =
2832 SignMessage(message, AuthorizationSetBuilder().Digest(digest).Padding(padding));
2833 LocalVerifyMessage(message, signature,
2834 AuthorizationSetBuilder().Digest(digest).Padding(padding));
2835 }
2836 }
Selene Huang31ab4042020-04-29 04:22:39 -07002837}
2838
2839/*
2840 * SigningOperationsTest.RsaUseRequiresCorrectAppIdAppData
2841 *
Shawn Willden7f424372021-01-10 18:06:50 -07002842 * Verifies that using an RSA key requires the correct app data.
Selene Huang31ab4042020-04-29 04:22:39 -07002843 */
2844TEST_P(SigningOperationsTest, RsaUseRequiresCorrectAppIdAppData) {
2845 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2846 .Authorization(TAG_NO_AUTH_REQUIRED)
2847 .RsaSigningKey(2048, 65537)
2848 .Digest(Digest::NONE)
2849 .Padding(PaddingMode::NONE)
2850 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08002851 .Authorization(TAG_APPLICATION_DATA, "appdata")
2852 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01002853
2854 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
2855
Selene Huang31ab4042020-04-29 04:22:39 -07002856 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2857 Begin(KeyPurpose::SIGN,
2858 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2859 AbortIfNeeded();
2860 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2861 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2862 .Digest(Digest::NONE)
2863 .Padding(PaddingMode::NONE)
2864 .Authorization(TAG_APPLICATION_ID, "clientid")));
2865 AbortIfNeeded();
2866 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
2867 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2868 .Digest(Digest::NONE)
2869 .Padding(PaddingMode::NONE)
2870 .Authorization(TAG_APPLICATION_DATA, "appdata")));
2871 AbortIfNeeded();
2872 EXPECT_EQ(ErrorCode::OK,
2873 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2874 .Digest(Digest::NONE)
2875 .Padding(PaddingMode::NONE)
2876 .Authorization(TAG_APPLICATION_DATA, "appdata")
2877 .Authorization(TAG_APPLICATION_ID, "clientid")));
2878 AbortIfNeeded();
2879}
2880
2881/*
2882 * SigningOperationsTest.RsaPssSha256Success
2883 *
2884 * Verifies that RSA-PSS signature operations succeed.
2885 */
2886TEST_P(SigningOperationsTest, RsaPssSha256Success) {
2887 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2888 .RsaSigningKey(2048, 65537)
2889 .Digest(Digest::SHA_2_256)
2890 .Padding(PaddingMode::RSA_PSS)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002891 .Authorization(TAG_NO_AUTH_REQUIRED)
2892 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002893 // Use large message, which won't work without digesting.
2894 string message(1024, 'a');
2895 string signature = SignMessage(
2896 message,
2897 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS));
2898}
2899
2900/*
2901 * SigningOperationsTest.RsaPaddingNoneDoesNotAllowOther
2902 *
2903 * Verifies that keymint rejects signature operations that specify a padding mode when the key
2904 * supports only unpadded operations.
2905 */
2906TEST_P(SigningOperationsTest, RsaPaddingNoneDoesNotAllowOther) {
2907 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2908 .RsaSigningKey(2048, 65537)
2909 .Digest(Digest::NONE)
2910 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002911 .Padding(PaddingMode::NONE)
2912 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002913 string message = "12345678901234567890123456789012";
2914 string signature;
2915
2916 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
2917 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
2918 .Digest(Digest::NONE)
2919 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
2920}
2921
2922/*
2923 * SigningOperationsTest.NoUserConfirmation
2924 *
2925 * Verifies that keymint rejects signing operations for keys with
2926 * TRUSTED_CONFIRMATION_REQUIRED and no valid confirmation token
2927 * presented.
2928 */
2929TEST_P(SigningOperationsTest, NoUserConfirmation) {
David Drysdale513bf122021-10-06 11:53:13 +01002930 if (SecLevel() == SecurityLevel::STRONGBOX) {
2931 GTEST_SKIP() << "Test not applicable to StrongBox device";
2932 }
Janis Danisevskis164bb872021-02-09 11:30:25 -08002933 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2934 .RsaSigningKey(1024, 65537)
2935 .Digest(Digest::NONE)
2936 .Padding(PaddingMode::NONE)
2937 .Authorization(TAG_NO_AUTH_REQUIRED)
2938 .Authorization(TAG_TRUSTED_CONFIRMATION_REQUIRED)
2939 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002940
2941 const string message = "12345678901234567890123456789012";
2942 EXPECT_EQ(ErrorCode::OK,
2943 Begin(KeyPurpose::SIGN,
2944 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
2945 string signature;
2946 EXPECT_EQ(ErrorCode::NO_USER_CONFIRMATION, Finish(message, &signature));
2947}
2948
2949/*
2950 * SigningOperationsTest.RsaPkcs1Sha256Success
2951 *
2952 * Verifies that digested RSA-PKCS1 signature operations succeed.
2953 */
2954TEST_P(SigningOperationsTest, RsaPkcs1Sha256Success) {
2955 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2956 .RsaSigningKey(2048, 65537)
2957 .Digest(Digest::SHA_2_256)
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(1024, 'a');
2962 string signature = SignMessage(message, AuthorizationSetBuilder()
2963 .Digest(Digest::SHA_2_256)
2964 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2965}
2966
2967/*
2968 * SigningOperationsTest.RsaPkcs1NoDigestSuccess
2969 *
2970 * Verifies that undigested RSA-PKCS1 signature operations succeed.
2971 */
2972TEST_P(SigningOperationsTest, RsaPkcs1NoDigestSuccess) {
2973 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2974 .RsaSigningKey(2048, 65537)
2975 .Digest(Digest::NONE)
2976 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002977 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2978 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002979 string message(53, 'a');
2980 string signature = SignMessage(message, AuthorizationSetBuilder()
2981 .Digest(Digest::NONE)
2982 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
2983}
2984
2985/*
2986 * SigningOperationsTest.RsaPkcs1NoDigestTooLarge
2987 *
2988 * Verifies that undigested RSA-PKCS1 signature operations fail with the correct error code when
2989 * given a too-long message.
2990 */
2991TEST_P(SigningOperationsTest, RsaPkcs1NoDigestTooLong) {
2992 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
2993 .RsaSigningKey(2048, 65537)
2994 .Digest(Digest::NONE)
2995 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08002996 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
2997 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07002998 string message(257, 'a');
2999
3000 EXPECT_EQ(ErrorCode::OK,
3001 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3002 .Digest(Digest::NONE)
3003 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3004 string signature;
3005 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &signature));
3006}
3007
3008/*
3009 * SigningOperationsTest.RsaPssSha512TooSmallKey
3010 *
3011 * Verifies that undigested RSA-PSS signature operations fail with the correct error code when
3012 * used with a key that is too small for the message.
3013 *
3014 * A PSS-padded message is of length salt_size + digest_size + 16 (sizes in bits), and the
3015 * keymint specification requires that salt_size == digest_size, so the message will be
3016 * digest_size * 2 +
3017 * 16. Such a message can only be signed by a given key if the key is at least that size. This
3018 * test uses SHA512, which has a digest_size == 512, so the message size is 1040 bits, too large
3019 * for a 1024-bit key.
3020 */
3021TEST_P(SigningOperationsTest, RsaPssSha512TooSmallKey) {
David Drysdale513bf122021-10-06 11:53:13 +01003022 if (SecLevel() == SecurityLevel::STRONGBOX) {
3023 GTEST_SKIP() << "Test not applicable to StrongBox device";
3024 }
Selene Huang31ab4042020-04-29 04:22:39 -07003025 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3026 .RsaSigningKey(1024, 65537)
3027 .Digest(Digest::SHA_2_512)
3028 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003029 .Padding(PaddingMode::RSA_PSS)
3030 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003031 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3032 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3033 .Digest(Digest::SHA_2_512)
3034 .Padding(PaddingMode::RSA_PSS)));
3035}
3036
3037/*
3038 * SigningOperationsTest.RsaNoPaddingTooLong
3039 *
3040 * Verifies that raw RSA signature operations fail with the correct error code when
3041 * given a too-long message.
3042 */
3043TEST_P(SigningOperationsTest, RsaNoPaddingTooLong) {
3044 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3045 .RsaSigningKey(2048, 65537)
3046 .Digest(Digest::NONE)
3047 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003048 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3049 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003050 // One byte too long
3051 string message(2048 / 8 + 1, 'a');
3052 ASSERT_EQ(ErrorCode::OK,
3053 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3054 .Digest(Digest::NONE)
3055 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3056 string result;
3057 ErrorCode finish_error_code = Finish(message, &result);
3058 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3059 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3060
3061 // Very large message that should exceed the transfer buffer size of any reasonable TEE.
3062 message = string(128 * 1024, 'a');
3063 ASSERT_EQ(ErrorCode::OK,
3064 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3065 .Digest(Digest::NONE)
3066 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3067 finish_error_code = Finish(message, &result);
3068 EXPECT_TRUE(finish_error_code == ErrorCode::INVALID_INPUT_LENGTH ||
3069 finish_error_code == ErrorCode::INVALID_ARGUMENT);
3070}
3071
3072/*
3073 * SigningOperationsTest.RsaAbort
3074 *
3075 * Verifies that operations can be aborted correctly. Uses an RSA signing operation for the
3076 * test, but the behavior should be algorithm and purpose-independent.
3077 */
3078TEST_P(SigningOperationsTest, RsaAbort) {
3079 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3080 .RsaSigningKey(2048, 65537)
3081 .Digest(Digest::NONE)
3082 .Authorization(TAG_NO_AUTH_REQUIRED)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003083 .Padding(PaddingMode::NONE)
3084 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003085
3086 ASSERT_EQ(ErrorCode::OK,
3087 Begin(KeyPurpose::SIGN,
3088 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3089 EXPECT_EQ(ErrorCode::OK, Abort());
3090
3091 // Another abort should fail
3092 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
3093
3094 // Set to sentinel, so TearDown() doesn't try to abort again.
Janis Danisevskis24c04702020-12-16 18:28:39 -08003095 op_.reset();
Selene Huang31ab4042020-04-29 04:22:39 -07003096}
3097
3098/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003099 * SigningOperationsTest.RsaNonUniqueParams
3100 *
3101 * Verifies that an operation with multiple padding modes is rejected.
3102 */
3103TEST_P(SigningOperationsTest, RsaNonUniqueParams) {
3104 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3105 .RsaSigningKey(2048, 65537)
3106 .Digest(Digest::NONE)
3107 .Digest(Digest::SHA1)
3108 .Authorization(TAG_NO_AUTH_REQUIRED)
3109 .Padding(PaddingMode::NONE)
3110 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)
3111 .SetDefaultValidity()));
3112
3113 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3114 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3115 .Digest(Digest::NONE)
3116 .Padding(PaddingMode::NONE)
3117 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3118
Tommy Chiuc93c4392021-05-11 18:36:50 +08003119 auto result = Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3120 .Digest(Digest::NONE)
3121 .Digest(Digest::SHA1)
3122 .Padding(PaddingMode::RSA_PKCS1_1_5_SIGN));
3123 ASSERT_TRUE(result == ErrorCode::UNSUPPORTED_DIGEST || result == ErrorCode::INVALID_ARGUMENT);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003124
3125 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3126 Begin(KeyPurpose::SIGN,
3127 AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_SIGN)));
3128}
3129
3130/*
Selene Huang31ab4042020-04-29 04:22:39 -07003131 * SigningOperationsTest.RsaUnsupportedPadding
3132 *
3133 * Verifies that RSA operations fail with the correct error (but key gen succeeds) when used
3134 * with a padding mode inappropriate for RSA.
3135 */
3136TEST_P(SigningOperationsTest, RsaUnsupportedPadding) {
3137 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3138 .RsaSigningKey(2048, 65537)
3139 .Authorization(TAG_NO_AUTH_REQUIRED)
3140 .Digest(Digest::SHA_2_256 /* supported digest */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003141 .Padding(PaddingMode::PKCS7)
3142 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003143 ASSERT_EQ(
3144 ErrorCode::UNSUPPORTED_PADDING_MODE,
3145 Begin(KeyPurpose::SIGN,
3146 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::PKCS7)));
David Drysdaled2cc8c22021-04-15 13:29:45 +01003147 CheckedDeleteKey();
3148
3149 ASSERT_EQ(ErrorCode::OK,
3150 GenerateKey(
3151 AuthorizationSetBuilder()
3152 .RsaSigningKey(2048, 65537)
3153 .Authorization(TAG_NO_AUTH_REQUIRED)
3154 .Digest(Digest::SHA_2_256 /* supported digest */)
3155 .Padding(PaddingMode::RSA_OAEP) /* padding mode for encryption only */
3156 .SetDefaultValidity()));
3157 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3158 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3159 .Digest(Digest::SHA_2_256)
3160 .Padding(PaddingMode::RSA_OAEP)));
Selene Huang31ab4042020-04-29 04:22:39 -07003161}
3162
3163/*
3164 * SigningOperationsTest.RsaPssNoDigest
3165 *
3166 * Verifies that RSA PSS operations fail when no digest is used. PSS requires a digest.
3167 */
3168TEST_P(SigningOperationsTest, RsaNoDigest) {
3169 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3170 .RsaSigningKey(2048, 65537)
3171 .Authorization(TAG_NO_AUTH_REQUIRED)
3172 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003173 .Padding(PaddingMode::RSA_PSS)
3174 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003175 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3176 Begin(KeyPurpose::SIGN,
3177 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::RSA_PSS)));
3178
3179 ASSERT_EQ(ErrorCode::UNSUPPORTED_DIGEST,
3180 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS)));
3181}
3182
3183/*
David Drysdale7de9feb2021-03-05 14:56:19 +00003184 * SigningOperationsTest.RsaPssNoPadding
Selene Huang31ab4042020-04-29 04:22:39 -07003185 *
3186 * Verifies that RSA operations fail when no padding mode is specified. PaddingMode::NONE is
3187 * supported in some cases (as validated in other tests), but a mode must be specified.
3188 */
3189TEST_P(SigningOperationsTest, RsaNoPadding) {
3190 // Padding must be specified
3191 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3192 .RsaKey(2048, 65537)
3193 .Authorization(TAG_NO_AUTH_REQUIRED)
3194 .SigningKey()
Janis Danisevskis164bb872021-02-09 11:30:25 -08003195 .Digest(Digest::NONE)
3196 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003197 ASSERT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE,
3198 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3199}
3200
3201/*
3202 * SigningOperationsTest.RsaShortMessage
3203 *
3204 * Verifies that raw RSA signatures succeed with a message shorter than the key size.
3205 */
3206TEST_P(SigningOperationsTest, RsaTooShortMessage) {
3207 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3208 .Authorization(TAG_NO_AUTH_REQUIRED)
3209 .RsaSigningKey(2048, 65537)
3210 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003211 .Padding(PaddingMode::NONE)
3212 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003213
3214 // Barely shorter
3215 string message(2048 / 8 - 1, 'a');
3216 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3217
3218 // Much shorter
3219 message = "a";
3220 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE));
3221}
3222
3223/*
3224 * SigningOperationsTest.RsaSignWithEncryptionKey
3225 *
3226 * Verifies that RSA encryption keys cannot be used to sign.
3227 */
3228TEST_P(SigningOperationsTest, RsaSignWithEncryptionKey) {
3229 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3230 .Authorization(TAG_NO_AUTH_REQUIRED)
3231 .RsaEncryptionKey(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 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3236 Begin(KeyPurpose::SIGN,
3237 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE)));
3238}
3239
3240/*
3241 * SigningOperationsTest.RsaSignTooLargeMessage
3242 *
3243 * Verifies that attempting a raw signature of a message which is the same length as the key,
3244 * but numerically larger than the public modulus, fails with the correct error.
3245 */
3246TEST_P(SigningOperationsTest, RsaSignTooLargeMessage) {
3247 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3248 .Authorization(TAG_NO_AUTH_REQUIRED)
3249 .RsaSigningKey(2048, 65537)
3250 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003251 .Padding(PaddingMode::NONE)
3252 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003253
3254 // Largest possible message will always be larger than the public modulus.
3255 string message(2048 / 8, static_cast<char>(0xff));
3256 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3257 .Authorization(TAG_NO_AUTH_REQUIRED)
3258 .Digest(Digest::NONE)
3259 .Padding(PaddingMode::NONE)));
3260 string signature;
3261 ASSERT_EQ(ErrorCode::INVALID_ARGUMENT, Finish(message, &signature));
3262}
3263
3264/*
David Drysdaledf8f52e2021-05-06 08:10:58 +01003265 * SigningOperationsTest.EcdsaAllDigestsAndCurves
3266 *
David Drysdale42fe1892021-10-14 14:43:46 +01003267 * Verifies ECDSA signature/verification for all digests and required curves.
David Drysdaledf8f52e2021-05-06 08:10:58 +01003268 */
3269TEST_P(SigningOperationsTest, EcdsaAllDigestsAndCurves) {
David Drysdaledf8f52e2021-05-06 08:10:58 +01003270
3271 string message = "1234567890";
3272 string corrupt_message = "2234567890";
3273 for (auto curve : ValidCurves()) {
3274 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
David Drysdale42fe1892021-10-14 14:43:46 +01003275 // Ed25519 only allows Digest::NONE.
3276 auto digests = (curve == EcCurve::CURVE_25519)
3277 ? std::vector<Digest>(1, Digest::NONE)
3278 : ValidDigests(true /* withNone */, false /* withMD5 */);
3279
David Drysdaledf8f52e2021-05-06 08:10:58 +01003280 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3281 .Authorization(TAG_NO_AUTH_REQUIRED)
3282 .EcdsaSigningKey(curve)
3283 .Digest(digests)
3284 .SetDefaultValidity());
3285 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate key for EC curve " << curve;
3286 if (error != ErrorCode::OK) {
3287 continue;
3288 }
3289
3290 for (auto digest : digests) {
3291 SCOPED_TRACE(testing::Message() << "Digest::" << digest);
3292 string signature = SignMessage(message, AuthorizationSetBuilder().Digest(digest));
3293 LocalVerifyMessage(message, signature, AuthorizationSetBuilder().Digest(digest));
3294 }
3295
3296 auto rc = DeleteKey();
3297 ASSERT_TRUE(rc == ErrorCode::OK || rc == ErrorCode::UNIMPLEMENTED);
3298 }
3299}
3300
3301/*
Selene Huang31ab4042020-04-29 04:22:39 -07003302 * SigningOperationsTest.EcdsaAllCurves
3303 *
David Drysdale42fe1892021-10-14 14:43:46 +01003304 * Verifies that ECDSA operations succeed with all required curves.
Selene Huang31ab4042020-04-29 04:22:39 -07003305 */
3306TEST_P(SigningOperationsTest, EcdsaAllCurves) {
3307 for (auto curve : ValidCurves()) {
David Drysdale42fe1892021-10-14 14:43:46 +01003308 Digest digest = (curve == EcCurve::CURVE_25519 ? Digest::NONE : Digest::SHA_2_256);
3309 SCOPED_TRACE(testing::Message() << "Curve::" << curve);
Selene Huang31ab4042020-04-29 04:22:39 -07003310 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3311 .Authorization(TAG_NO_AUTH_REQUIRED)
3312 .EcdsaSigningKey(curve)
David Drysdale42fe1892021-10-14 14:43:46 +01003313 .Digest(digest)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003314 .SetDefaultValidity());
Selene Huang31ab4042020-04-29 04:22:39 -07003315 EXPECT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3316 if (error != ErrorCode::OK) continue;
3317
3318 string message(1024, 'a');
David Drysdale42fe1892021-10-14 14:43:46 +01003319 SignMessage(message, AuthorizationSetBuilder().Digest(digest));
Selene Huang31ab4042020-04-29 04:22:39 -07003320 CheckedDeleteKey();
3321 }
3322}
3323
3324/*
David Drysdale42fe1892021-10-14 14:43:46 +01003325 * SigningOperationsTest.EcdsaCurve25519
3326 *
3327 * Verifies that ECDSA operations succeed with curve25519.
3328 */
3329TEST_P(SigningOperationsTest, EcdsaCurve25519) {
3330 if (!Curve25519Supported()) {
3331 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3332 }
3333
3334 EcCurve curve = EcCurve::CURVE_25519;
3335 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3336 .Authorization(TAG_NO_AUTH_REQUIRED)
3337 .EcdsaSigningKey(curve)
3338 .Digest(Digest::NONE)
3339 .SetDefaultValidity());
3340 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3341
3342 string message(1024, 'a');
3343 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3344 CheckedDeleteKey();
3345}
3346
3347/*
David Drysdalefeab5d92022-01-06 15:46:23 +00003348 * SigningOperationsTest.EcdsaCurve25519MaxSize
3349 *
3350 * Verifies that EDDSA operations with curve25519 under the maximum message size succeed.
3351 */
3352TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSize) {
3353 if (!Curve25519Supported()) {
3354 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3355 }
3356
3357 EcCurve curve = EcCurve::CURVE_25519;
3358 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3359 .Authorization(TAG_NO_AUTH_REQUIRED)
3360 .EcdsaSigningKey(curve)
3361 .Digest(Digest::NONE)
3362 .SetDefaultValidity());
3363 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3364
3365 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3366
3367 for (size_t msg_size : {MAX_ED25519_MSG_SIZE - 1, MAX_ED25519_MSG_SIZE}) {
3368 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3369 string message(msg_size, 'a');
3370
3371 // Attempt to sign via Begin+Finish.
3372 AuthorizationSet out_params;
3373 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3374 EXPECT_TRUE(out_params.empty());
3375 string signature;
3376 auto result = Finish(message, &signature);
3377 EXPECT_EQ(result, ErrorCode::OK);
3378 LocalVerifyMessage(message, signature, params);
3379
3380 // Attempt to sign via Begin+Update+Finish
3381 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3382 EXPECT_TRUE(out_params.empty());
3383 string output;
3384 result = Update(message, &output);
3385 EXPECT_EQ(result, ErrorCode::OK);
3386 EXPECT_EQ(output.size(), 0);
3387 string signature2;
3388 EXPECT_EQ(ErrorCode::OK, Finish({}, &signature2));
3389 LocalVerifyMessage(message, signature2, params);
3390 }
3391
3392 CheckedDeleteKey();
3393}
3394
3395/*
3396 * SigningOperationsTest.EcdsaCurve25519MaxSizeFail
3397 *
3398 * Verifies that EDDSA operations with curve25519 fail when message size is too large.
3399 */
3400TEST_P(SigningOperationsTest, EcdsaCurve25519MaxSizeFail) {
3401 if (!Curve25519Supported()) {
3402 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
3403 }
3404
3405 EcCurve curve = EcCurve::CURVE_25519;
3406 ErrorCode error = GenerateKey(AuthorizationSetBuilder()
3407 .Authorization(TAG_NO_AUTH_REQUIRED)
3408 .EcdsaSigningKey(curve)
3409 .Digest(Digest::NONE)
3410 .SetDefaultValidity());
3411 ASSERT_EQ(ErrorCode::OK, error) << "Failed to generate ECDSA key with curve " << curve;
3412
3413 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
3414
3415 for (size_t msg_size : {MAX_ED25519_MSG_SIZE + 1, MAX_ED25519_MSG_SIZE * 2}) {
3416 SCOPED_TRACE(testing::Message() << "-msg-size=" << msg_size);
3417 string message(msg_size, 'a');
3418
3419 // Attempt to sign via Begin+Finish.
3420 AuthorizationSet out_params;
3421 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3422 EXPECT_TRUE(out_params.empty());
3423 string signature;
3424 auto result = Finish(message, &signature);
3425 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3426
3427 // Attempt to sign via Begin+Update (but never get to Finish)
3428 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, key_blob_, params, &out_params));
3429 EXPECT_TRUE(out_params.empty());
3430 string output;
3431 result = Update(message, &output);
3432 EXPECT_EQ(result, ErrorCode::INVALID_INPUT_LENGTH);
3433 }
3434
3435 CheckedDeleteKey();
3436}
3437
3438/*
Selene Huang31ab4042020-04-29 04:22:39 -07003439 * SigningOperationsTest.EcdsaNoDigestHugeData
3440 *
3441 * Verifies that ECDSA operations support very large messages, even without digesting. This
3442 * should work because ECDSA actually only signs the leftmost L_n bits of the message, however
3443 * large it may be. Not using digesting is a bad idea, but in some cases digesting is done by
3444 * the framework.
3445 */
3446TEST_P(SigningOperationsTest, EcdsaNoDigestHugeData) {
3447 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3448 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003449 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003450 .Digest(Digest::NONE)
3451 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07003452 string message(1 * 1024, 'a');
3453 SignMessage(message, AuthorizationSetBuilder().Digest(Digest::NONE));
3454}
3455
3456/*
3457 * SigningOperationsTest.EcUseRequiresCorrectAppIdAppData
3458 *
3459 * Verifies that using an EC key requires the correct app ID/data.
3460 */
3461TEST_P(SigningOperationsTest, EcUseRequiresCorrectAppIdAppData) {
3462 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3463 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003464 .EcdsaSigningKey(EcCurve::P_256)
Selene Huang31ab4042020-04-29 04:22:39 -07003465 .Digest(Digest::NONE)
3466 .Authorization(TAG_APPLICATION_ID, "clientid")
Janis Danisevskis164bb872021-02-09 11:30:25 -08003467 .Authorization(TAG_APPLICATION_DATA, "appdata")
3468 .SetDefaultValidity()));
David Drysdale300b5552021-05-20 12:05:26 +01003469
3470 CheckAppIdCharacteristics(key_blob_, "clientid", "appdata", key_characteristics_);
3471
Selene Huang31ab4042020-04-29 04:22:39 -07003472 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3473 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::NONE)));
3474 AbortIfNeeded();
3475 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3476 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3477 .Digest(Digest::NONE)
3478 .Authorization(TAG_APPLICATION_ID, "clientid")));
3479 AbortIfNeeded();
3480 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
3481 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3482 .Digest(Digest::NONE)
3483 .Authorization(TAG_APPLICATION_DATA, "appdata")));
3484 AbortIfNeeded();
3485 EXPECT_EQ(ErrorCode::OK,
3486 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder()
3487 .Digest(Digest::NONE)
3488 .Authorization(TAG_APPLICATION_DATA, "appdata")
3489 .Authorization(TAG_APPLICATION_ID, "clientid")));
3490 AbortIfNeeded();
3491}
3492
3493/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003494 * SigningOperationsTest.EcdsaIncompatibleDigest
3495 *
3496 * Verifies that using an EC key requires compatible digest.
3497 */
3498TEST_P(SigningOperationsTest, EcdsaIncompatibleDigest) {
3499 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3500 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003501 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaled2cc8c22021-04-15 13:29:45 +01003502 .Digest(Digest::NONE)
3503 .Digest(Digest::SHA1)
3504 .SetDefaultValidity()));
3505 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
3506 Begin(KeyPurpose::SIGN, AuthorizationSetBuilder().Digest(Digest::SHA_2_256)));
3507 AbortIfNeeded();
3508}
3509
3510/*
Selene Huang31ab4042020-04-29 04:22:39 -07003511 * SigningOperationsTest.AesEcbSign
3512 *
3513 * Verifies that attempts to use AES keys to sign fail in the correct way.
3514 */
3515TEST_P(SigningOperationsTest, AesEcbSign) {
3516 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3517 .Authorization(TAG_NO_AUTH_REQUIRED)
3518 .SigningKey()
3519 .AesEncryptionKey(128)
3520 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)));
3521
3522 AuthorizationSet out_params;
3523 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3524 Begin(KeyPurpose::SIGN, AuthorizationSet() /* in_params */, &out_params));
3525 EXPECT_EQ(ErrorCode::UNSUPPORTED_PURPOSE,
3526 Begin(KeyPurpose::VERIFY, AuthorizationSet() /* in_params */, &out_params));
3527}
3528
3529/*
3530 * SigningOperationsTest.HmacAllDigests
3531 *
3532 * Verifies that HMAC works with all digests.
3533 */
3534TEST_P(SigningOperationsTest, HmacAllDigests) {
3535 for (auto digest : ValidDigests(false /* withNone */, false /* withMD5 */)) {
3536 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3537 .Authorization(TAG_NO_AUTH_REQUIRED)
3538 .HmacKey(128)
3539 .Digest(digest)
3540 .Authorization(TAG_MIN_MAC_LENGTH, 160)))
3541 << "Failed to create HMAC key with digest " << digest;
3542 string message = "12345678901234567890123456789012";
3543 string signature = MacMessage(message, digest, 160);
3544 EXPECT_EQ(160U / 8U, signature.size())
3545 << "Failed to sign with HMAC key with digest " << digest;
3546 CheckedDeleteKey();
3547 }
3548}
3549
3550/*
3551 * SigningOperationsTest.HmacSha256TooLargeMacLength
3552 *
3553 * Verifies that HMAC fails in the correct way when asked to generate a MAC larger than the
3554 * digest size.
3555 */
3556TEST_P(SigningOperationsTest, HmacSha256TooLargeMacLength) {
3557 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3558 .Authorization(TAG_NO_AUTH_REQUIRED)
3559 .HmacKey(128)
3560 .Digest(Digest::SHA_2_256)
3561 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
3562 AuthorizationSet output_params;
3563 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3564 AuthorizationSetBuilder()
3565 .Digest(Digest::SHA_2_256)
3566 .Authorization(TAG_MAC_LENGTH, 264),
3567 &output_params));
3568}
3569
3570/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003571 * SigningOperationsTest.HmacSha256InvalidMacLength
3572 *
3573 * Verifies that HMAC fails in the correct way when asked to generate a MAC whose length is
3574 * not a multiple of 8.
3575 */
3576TEST_P(SigningOperationsTest, HmacSha256InvalidMacLength) {
3577 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3578 .Authorization(TAG_NO_AUTH_REQUIRED)
3579 .HmacKey(128)
3580 .Digest(Digest::SHA_2_256)
3581 .Authorization(TAG_MIN_MAC_LENGTH, 160)));
3582 AuthorizationSet output_params;
3583 EXPECT_EQ(ErrorCode::UNSUPPORTED_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3584 AuthorizationSetBuilder()
3585 .Digest(Digest::SHA_2_256)
3586 .Authorization(TAG_MAC_LENGTH, 161),
3587 &output_params));
3588}
3589
3590/*
Selene Huang31ab4042020-04-29 04:22:39 -07003591 * SigningOperationsTest.HmacSha256TooSmallMacLength
3592 *
3593 * Verifies that HMAC fails in the correct way when asked to generate a MAC smaller than the
3594 * specified minimum MAC length.
3595 */
3596TEST_P(SigningOperationsTest, HmacSha256TooSmallMacLength) {
3597 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
3598 .Authorization(TAG_NO_AUTH_REQUIRED)
3599 .HmacKey(128)
3600 .Digest(Digest::SHA_2_256)
3601 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
3602 AuthorizationSet output_params;
3603 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::SIGN, key_blob_,
3604 AuthorizationSetBuilder()
3605 .Digest(Digest::SHA_2_256)
3606 .Authorization(TAG_MAC_LENGTH, 120),
3607 &output_params));
3608}
3609
3610/*
3611 * SigningOperationsTest.HmacRfc4231TestCase3
3612 *
3613 * Validates against the test vectors from RFC 4231 test case 3.
3614 */
3615TEST_P(SigningOperationsTest, HmacRfc4231TestCase3) {
3616 string key(20, 0xaa);
3617 string message(50, 0xdd);
3618 uint8_t sha_224_expected[] = {
3619 0x7f, 0xb3, 0xcb, 0x35, 0x88, 0xc6, 0xc1, 0xf6, 0xff, 0xa9, 0x69, 0x4d, 0x7d, 0x6a,
3620 0xd2, 0x64, 0x93, 0x65, 0xb0, 0xc1, 0xf6, 0x5d, 0x69, 0xd1, 0xec, 0x83, 0x33, 0xea,
3621 };
3622 uint8_t sha_256_expected[] = {
3623 0x77, 0x3e, 0xa9, 0x1e, 0x36, 0x80, 0x0e, 0x46, 0x85, 0x4d, 0xb8,
3624 0xeb, 0xd0, 0x91, 0x81, 0xa7, 0x29, 0x59, 0x09, 0x8b, 0x3e, 0xf8,
3625 0xc1, 0x22, 0xd9, 0x63, 0x55, 0x14, 0xce, 0xd5, 0x65, 0xfe,
3626 };
3627 uint8_t sha_384_expected[] = {
3628 0x88, 0x06, 0x26, 0x08, 0xd3, 0xe6, 0xad, 0x8a, 0x0a, 0xa2, 0xac, 0xe0,
3629 0x14, 0xc8, 0xa8, 0x6f, 0x0a, 0xa6, 0x35, 0xd9, 0x47, 0xac, 0x9f, 0xeb,
3630 0xe8, 0x3e, 0xf4, 0xe5, 0x59, 0x66, 0x14, 0x4b, 0x2a, 0x5a, 0xb3, 0x9d,
3631 0xc1, 0x38, 0x14, 0xb9, 0x4e, 0x3a, 0xb6, 0xe1, 0x01, 0xa3, 0x4f, 0x27,
3632 };
3633 uint8_t sha_512_expected[] = {
3634 0xfa, 0x73, 0xb0, 0x08, 0x9d, 0x56, 0xa2, 0x84, 0xef, 0xb0, 0xf0, 0x75, 0x6c,
3635 0x89, 0x0b, 0xe9, 0xb1, 0xb5, 0xdb, 0xdd, 0x8e, 0xe8, 0x1a, 0x36, 0x55, 0xf8,
3636 0x3e, 0x33, 0xb2, 0x27, 0x9d, 0x39, 0xbf, 0x3e, 0x84, 0x82, 0x79, 0xa7, 0x22,
3637 0xc8, 0x06, 0xb4, 0x85, 0xa4, 0x7e, 0x67, 0xc8, 0x07, 0xb9, 0x46, 0xa3, 0x37,
3638 0xbe, 0xe8, 0x94, 0x26, 0x74, 0x27, 0x88, 0x59, 0xe1, 0x32, 0x92, 0xfb,
3639 };
3640
3641 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3642 if (SecLevel() != SecurityLevel::STRONGBOX) {
3643 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3644 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3645 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3646 }
3647}
3648
3649/*
3650 * SigningOperationsTest.HmacRfc4231TestCase5
3651 *
3652 * Validates against the test vectors from RFC 4231 test case 5.
3653 */
3654TEST_P(SigningOperationsTest, HmacRfc4231TestCase5) {
3655 string key(20, 0x0c);
3656 string message = "Test With Truncation";
3657
3658 uint8_t sha_224_expected[] = {
3659 0x0e, 0x2a, 0xea, 0x68, 0xa9, 0x0c, 0x8d, 0x37,
3660 0xc9, 0x88, 0xbc, 0xdb, 0x9f, 0xca, 0x6f, 0xa8,
3661 };
3662 uint8_t sha_256_expected[] = {
3663 0xa3, 0xb6, 0x16, 0x74, 0x73, 0x10, 0x0e, 0xe0,
3664 0x6e, 0x0c, 0x79, 0x6c, 0x29, 0x55, 0x55, 0x2b,
3665 };
3666 uint8_t sha_384_expected[] = {
3667 0x3a, 0xbf, 0x34, 0xc3, 0x50, 0x3b, 0x2a, 0x23,
3668 0xa4, 0x6e, 0xfc, 0x61, 0x9b, 0xae, 0xf8, 0x97,
3669 };
3670 uint8_t sha_512_expected[] = {
3671 0x41, 0x5f, 0xad, 0x62, 0x71, 0x58, 0x0a, 0x53,
3672 0x1d, 0x41, 0x79, 0xbc, 0x89, 0x1d, 0x87, 0xa6,
3673 };
3674
3675 CheckHmacTestVector(key, message, Digest::SHA_2_256, make_string(sha_256_expected));
3676 if (SecLevel() != SecurityLevel::STRONGBOX) {
3677 CheckHmacTestVector(key, message, Digest::SHA_2_224, make_string(sha_224_expected));
3678 CheckHmacTestVector(key, message, Digest::SHA_2_384, make_string(sha_384_expected));
3679 CheckHmacTestVector(key, message, Digest::SHA_2_512, make_string(sha_512_expected));
3680 }
3681}
3682
3683INSTANTIATE_KEYMINT_AIDL_TEST(SigningOperationsTest);
3684
3685typedef KeyMintAidlTestBase VerificationOperationsTest;
3686
3687/*
Selene Huang31ab4042020-04-29 04:22:39 -07003688 * VerificationOperationsTest.HmacSigningKeyCannotVerify
3689 *
3690 * Verifies HMAC signing and verification, but that a signing key cannot be used to verify.
3691 */
3692TEST_P(VerificationOperationsTest, HmacSigningKeyCannotVerify) {
3693 string key_material = "HelloThisIsAKey";
3694
3695 vector<uint8_t> signing_key, verification_key;
Shawn Willden7f424372021-01-10 18:06:50 -07003696 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
Selene Huang31ab4042020-04-29 04:22:39 -07003697 EXPECT_EQ(ErrorCode::OK,
3698 ImportKey(AuthorizationSetBuilder()
3699 .Authorization(TAG_NO_AUTH_REQUIRED)
3700 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3701 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3702 .Digest(Digest::SHA_2_256)
3703 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3704 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3705 EXPECT_EQ(ErrorCode::OK,
3706 ImportKey(AuthorizationSetBuilder()
3707 .Authorization(TAG_NO_AUTH_REQUIRED)
3708 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3709 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3710 .Digest(Digest::SHA_2_256)
3711 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3712 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3713
3714 string message = "This is a message.";
3715 string signature = SignMessage(
3716 signing_key, message,
3717 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3718
3719 // Signing key should not work.
3720 AuthorizationSet out_params;
3721 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3722 Begin(KeyPurpose::VERIFY, signing_key,
3723 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &out_params));
3724
3725 // Verification key should work.
3726 VerifyMessage(verification_key, message, signature,
3727 AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
3728
3729 CheckedDeleteKey(&signing_key);
3730 CheckedDeleteKey(&verification_key);
3731}
3732
Prashant Patildec9fdc2021-12-08 15:25:47 +00003733/*
3734 * VerificationOperationsTest.HmacVerificationFailsForCorruptSignature
3735 *
3736 * Verifies HMAC signature verification should fails if message or signature is corrupted.
3737 */
3738TEST_P(VerificationOperationsTest, HmacVerificationFailsForCorruptSignature) {
3739 string key_material = "HelloThisIsAKey";
3740
3741 vector<uint8_t> signing_key, verification_key;
3742 vector<KeyCharacteristics> signing_key_chars, verification_key_chars;
3743 EXPECT_EQ(ErrorCode::OK,
3744 ImportKey(AuthorizationSetBuilder()
3745 .Authorization(TAG_NO_AUTH_REQUIRED)
3746 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3747 .Authorization(TAG_PURPOSE, KeyPurpose::SIGN)
3748 .Digest(Digest::SHA_2_256)
3749 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3750 KeyFormat::RAW, key_material, &signing_key, &signing_key_chars));
3751 EXPECT_EQ(ErrorCode::OK,
3752 ImportKey(AuthorizationSetBuilder()
3753 .Authorization(TAG_NO_AUTH_REQUIRED)
3754 .Authorization(TAG_ALGORITHM, Algorithm::HMAC)
3755 .Authorization(TAG_PURPOSE, KeyPurpose::VERIFY)
3756 .Digest(Digest::SHA_2_256)
3757 .Authorization(TAG_MIN_MAC_LENGTH, 160),
3758 KeyFormat::RAW, key_material, &verification_key, &verification_key_chars));
3759
3760 string message = "This is a message.";
3761 string signature = SignMessage(
3762 signing_key, message,
3763 AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Authorization(TAG_MAC_LENGTH, 160));
3764
3765 AuthorizationSet begin_out_params;
3766 ASSERT_EQ(ErrorCode::OK,
3767 Begin(KeyPurpose::VERIFY, verification_key,
3768 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3769
3770 string corruptMessage = "This is b message."; // Corrupted message
3771 string output;
3772 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(corruptMessage, signature, &output));
3773
3774 ASSERT_EQ(ErrorCode::OK,
3775 Begin(KeyPurpose::VERIFY, verification_key,
3776 AuthorizationSetBuilder().Digest(Digest::SHA_2_256), &begin_out_params));
3777
3778 signature[0] += 1; // Corrupt a signature
3779 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(message, signature, &output));
3780
3781 CheckedDeleteKey(&signing_key);
3782 CheckedDeleteKey(&verification_key);
3783}
3784
Selene Huang31ab4042020-04-29 04:22:39 -07003785INSTANTIATE_KEYMINT_AIDL_TEST(VerificationOperationsTest);
3786
3787typedef KeyMintAidlTestBase ExportKeyTest;
3788
3789/*
3790 * ExportKeyTest.RsaUnsupportedKeyFormat
3791 *
3792 * Verifies that attempting to export RSA keys in PKCS#8 format fails with the correct error.
3793 */
3794// TODO(seleneh) add ExportKey to GenerateKey
3795// check result
3796
3797class ImportKeyTest : public KeyMintAidlTestBase {
3798 public:
3799 template <TagType tag_type, Tag tag, typename ValueT>
3800 void CheckCryptoParam(TypedTag<tag_type, tag> ttag, ValueT expected) {
3801 SCOPED_TRACE("CheckCryptoParam");
Shawn Willden7f424372021-01-10 18:06:50 -07003802 for (auto& entry : key_characteristics_) {
3803 if (entry.securityLevel == SecLevel()) {
3804 EXPECT_TRUE(contains(entry.authorizations, ttag, expected))
3805 << "Tag " << tag << " with value " << expected
3806 << " not found at security level" << entry.securityLevel;
3807 } else {
3808 EXPECT_FALSE(contains(entry.authorizations, ttag, expected))
3809 << "Tag " << tag << " found at security level " << entry.securityLevel;
3810 }
Selene Huang31ab4042020-04-29 04:22:39 -07003811 }
3812 }
3813
3814 void CheckOrigin() {
3815 SCOPED_TRACE("CheckOrigin");
Shawn Willden7f424372021-01-10 18:06:50 -07003816 // Origin isn't a crypto param, but it always lives with them.
3817 return CheckCryptoParam(TAG_ORIGIN, KeyOrigin::IMPORTED);
Selene Huang31ab4042020-04-29 04:22:39 -07003818 }
3819};
3820
3821/*
3822 * ImportKeyTest.RsaSuccess
3823 *
3824 * Verifies that importing and using an RSA key pair works correctly.
3825 */
3826TEST_P(ImportKeyTest, RsaSuccess) {
Selene Huange5727e62021-04-13 22:41:20 -07003827 uint32_t key_size;
3828 string key;
3829
3830 if (SecLevel() == SecurityLevel::STRONGBOX) {
3831 key_size = 2048;
3832 key = rsa_2048_key;
3833 } else {
3834 key_size = 1024;
3835 key = rsa_key;
3836 }
3837
Selene Huang31ab4042020-04-29 04:22:39 -07003838 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3839 .Authorization(TAG_NO_AUTH_REQUIRED)
Selene Huange5727e62021-04-13 22:41:20 -07003840 .RsaSigningKey(key_size, 65537)
Selene Huang31ab4042020-04-29 04:22:39 -07003841 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003842 .Padding(PaddingMode::RSA_PSS)
3843 .SetDefaultValidity(),
Selene Huange5727e62021-04-13 22:41:20 -07003844 KeyFormat::PKCS8, key));
Selene Huang31ab4042020-04-29 04:22:39 -07003845
3846 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
Selene Huange5727e62021-04-13 22:41:20 -07003847 CheckCryptoParam(TAG_KEY_SIZE, key_size);
Selene Huang31ab4042020-04-29 04:22:39 -07003848 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3849 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3850 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3851 CheckOrigin();
3852
3853 string message(1024 / 8, 'a');
3854 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3855 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003856 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003857}
3858
3859/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01003860 * ImportKeyTest.RsaSuccessWithoutParams
3861 *
3862 * Verifies that importing and using an RSA key pair without specifying parameters
3863 * works correctly.
3864 */
3865TEST_P(ImportKeyTest, RsaSuccessWithoutParams) {
3866 uint32_t key_size;
3867 string key;
3868
3869 if (SecLevel() == SecurityLevel::STRONGBOX) {
3870 key_size = 2048;
3871 key = rsa_2048_key;
3872 } else {
3873 key_size = 1024;
3874 key = rsa_key;
3875 }
3876
3877 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3878 .Authorization(TAG_NO_AUTH_REQUIRED)
3879 .SigningKey()
3880 .Authorization(TAG_ALGORITHM, Algorithm::RSA)
3881 .Digest(Digest::SHA_2_256)
3882 .Padding(PaddingMode::RSA_PSS)
3883 .SetDefaultValidity(),
3884 KeyFormat::PKCS8, key));
3885
3886 // Key size and public exponent are determined from the imported key material.
3887 CheckCryptoParam(TAG_KEY_SIZE, key_size);
3888 CheckCryptoParam(TAG_RSA_PUBLIC_EXPONENT, 65537U);
3889
3890 CheckCryptoParam(TAG_ALGORITHM, Algorithm::RSA);
3891 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3892 CheckCryptoParam(TAG_PADDING, PaddingMode::RSA_PSS);
3893 CheckOrigin();
3894
3895 string message(1024 / 8, 'a');
3896 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256).Padding(PaddingMode::RSA_PSS);
3897 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003898 LocalVerifyMessage(message, signature, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01003899}
3900
3901/*
Selene Huang31ab4042020-04-29 04:22:39 -07003902 * ImportKeyTest.RsaKeySizeMismatch
3903 *
3904 * Verifies that importing an RSA key pair with a size that doesn't match the key fails in the
3905 * correct way.
3906 */
3907TEST_P(ImportKeyTest, RsaKeySizeMismatch) {
3908 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3909 ImportKey(AuthorizationSetBuilder()
3910 .RsaSigningKey(2048 /* Doesn't match key */, 65537)
3911 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003912 .Padding(PaddingMode::NONE)
3913 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003914 KeyFormat::PKCS8, rsa_key));
3915}
3916
3917/*
3918 * ImportKeyTest.RsaPublicExponentMismatch
3919 *
3920 * Verifies that importing an RSA key pair with a public exponent that doesn't match the key
3921 * fails in the correct way.
3922 */
3923TEST_P(ImportKeyTest, RsaPublicExponentMismatch) {
3924 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
3925 ImportKey(AuthorizationSetBuilder()
3926 .RsaSigningKey(1024, 3 /* Doesn't match key */)
3927 .Digest(Digest::NONE)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003928 .Padding(PaddingMode::NONE)
3929 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003930 KeyFormat::PKCS8, rsa_key));
3931}
3932
3933/*
David Drysdalee60248c2021-10-04 12:54:13 +01003934 * ImportKeyTest.RsaAttestMultiPurposeFail
3935 *
3936 * Verifies that importing an RSA key pair with purpose ATTEST_KEY+SIGN fails.
3937 */
3938TEST_P(ImportKeyTest, RsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00003939 if (AidlVersion() < 2) {
3940 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
3941 // with other key purposes. However, this was not checked at the time
3942 // so we can only be strict about checking this for implementations of KeyMint
3943 // version 2 and above.
3944 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
3945 }
David Drysdalee60248c2021-10-04 12:54:13 +01003946 uint32_t key_size = 2048;
3947 string key = rsa_2048_key;
3948
3949 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
3950 ImportKey(AuthorizationSetBuilder()
3951 .Authorization(TAG_NO_AUTH_REQUIRED)
3952 .RsaSigningKey(key_size, 65537)
3953 .AttestKey()
3954 .Digest(Digest::SHA_2_256)
3955 .Padding(PaddingMode::RSA_PSS)
3956 .SetDefaultValidity(),
3957 KeyFormat::PKCS8, key));
3958}
3959
3960/*
Selene Huang31ab4042020-04-29 04:22:39 -07003961 * ImportKeyTest.EcdsaSuccess
3962 *
3963 * Verifies that importing and using an ECDSA P-256 key pair works correctly.
3964 */
3965TEST_P(ImportKeyTest, EcdsaSuccess) {
3966 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3967 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003968 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003969 .Digest(Digest::SHA_2_256)
3970 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003971 KeyFormat::PKCS8, ec_256_key));
3972
3973 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07003974 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
3975 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
3976
3977 CheckOrigin();
3978
3979 string message(32, 'a');
3980 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
3981 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01003982 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07003983}
3984
3985/*
3986 * ImportKeyTest.EcdsaP256RFC5915Success
3987 *
3988 * Verifies that importing and using an ECDSA P-256 key pair encoded using RFC5915 works
3989 * correctly.
3990 */
3991TEST_P(ImportKeyTest, EcdsaP256RFC5915Success) {
3992 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
3993 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01003994 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08003995 .Digest(Digest::SHA_2_256)
3996 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07003997 KeyFormat::PKCS8, ec_256_key_rfc5915));
3998
3999 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004000 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4001 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4002
4003 CheckOrigin();
4004
4005 string message(32, 'a');
4006 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4007 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004008 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004009}
4010
4011/*
4012 * ImportKeyTest.EcdsaP256SEC1Success
4013 *
4014 * Verifies that importing and using an ECDSA P-256 key pair encoded using SEC1 works correctly.
4015 */
4016TEST_P(ImportKeyTest, EcdsaP256SEC1Success) {
4017 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4018 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004019 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004020 .Digest(Digest::SHA_2_256)
4021 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004022 KeyFormat::PKCS8, ec_256_key_sec1));
4023
4024 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004025 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4026 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_256);
4027
4028 CheckOrigin();
4029
4030 string message(32, 'a');
4031 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4032 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004033 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004034}
4035
4036/*
4037 * ImportKeyTest.Ecdsa521Success
4038 *
4039 * Verifies that importing and using an ECDSA P-521 key pair works correctly.
4040 */
4041TEST_P(ImportKeyTest, Ecdsa521Success) {
David Drysdale513bf122021-10-06 11:53:13 +01004042 if (SecLevel() == SecurityLevel::STRONGBOX) {
4043 GTEST_SKIP() << "Test not applicable to StrongBox device";
4044 }
Selene Huang31ab4042020-04-29 04:22:39 -07004045 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4046 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01004047 .EcdsaSigningKey(EcCurve::P_521)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004048 .Digest(Digest::SHA_2_256)
4049 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004050 KeyFormat::PKCS8, ec_521_key));
4051
4052 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
Selene Huang31ab4042020-04-29 04:22:39 -07004053 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4054 CheckCryptoParam(TAG_EC_CURVE, EcCurve::P_521);
4055 CheckOrigin();
4056
4057 string message(32, 'a');
4058 auto params = AuthorizationSetBuilder().Digest(Digest::SHA_2_256);
4059 string signature = SignMessage(message, params);
David Drysdaledf8f52e2021-05-06 08:10:58 +01004060 LocalVerifyMessage(message, signature, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004061}
4062
4063/*
Selene Huang31ab4042020-04-29 04:22:39 -07004064 * ImportKeyTest.EcdsaCurveMismatch
4065 *
4066 * Verifies that importing an ECDSA key pair with a curve that doesn't match the key fails in
4067 * the correct way.
4068 */
4069TEST_P(ImportKeyTest, EcdsaCurveMismatch) {
4070 ASSERT_EQ(ErrorCode::IMPORT_PARAMETER_MISMATCH,
4071 ImportKey(AuthorizationSetBuilder()
4072 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004073 .Digest(Digest::NONE)
4074 .SetDefaultValidity(),
Selene Huang31ab4042020-04-29 04:22:39 -07004075 KeyFormat::PKCS8, ec_256_key));
4076}
4077
4078/*
David Drysdalee60248c2021-10-04 12:54:13 +01004079 * ImportKeyTest.EcdsaAttestMultiPurposeFail
4080 *
4081 * Verifies that importing and using an ECDSA P-256 key pair with purpose ATTEST_KEY+SIGN fails.
4082 */
4083TEST_P(ImportKeyTest, EcdsaAttestMultiPurposeFail) {
David Drysdale50a66b82022-03-21 15:21:32 +00004084 if (AidlVersion() < 2) {
4085 // The KeyMint v1 spec required that KeyPurpose::ATTEST_KEY not be combined
4086 // with other key purposes. However, this was not checked at the time
4087 // so we can only be strict about checking this for implementations of KeyMint
4088 // version 2 and above.
4089 GTEST_SKIP() << "Single-purpose for KeyPurpose::ATTEST_KEY only strict since KeyMint v2";
4090 }
David Drysdalee60248c2021-10-04 12:54:13 +01004091 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE,
4092 ImportKey(AuthorizationSetBuilder()
4093 .Authorization(TAG_NO_AUTH_REQUIRED)
4094 .EcdsaSigningKey(EcCurve::P_256)
4095 .AttestKey()
4096 .Digest(Digest::SHA_2_256)
4097 .SetDefaultValidity(),
4098 KeyFormat::PKCS8, ec_256_key));
4099}
4100
4101/*
David Drysdale42fe1892021-10-14 14:43:46 +01004102 * ImportKeyTest.Ed25519RawSuccess
4103 *
4104 * Verifies that importing and using a raw Ed25519 private key works correctly.
4105 */
4106TEST_P(ImportKeyTest, Ed25519RawSuccess) {
4107 if (!Curve25519Supported()) {
4108 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4109 }
4110
4111 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4112 .Authorization(TAG_NO_AUTH_REQUIRED)
4113 .EcdsaSigningKey(EcCurve::CURVE_25519)
4114 .Digest(Digest::NONE)
4115 .SetDefaultValidity(),
4116 KeyFormat::RAW, ed25519_key));
4117 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4118 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4119 CheckOrigin();
4120
4121 // The returned cert should hold the correct public key.
4122 ASSERT_GT(cert_chain_.size(), 0);
4123 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4124 ASSERT_NE(kmKeyCert, nullptr);
4125 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4126 ASSERT_NE(kmPubKey.get(), nullptr);
4127 size_t kmPubKeySize = 32;
4128 uint8_t kmPubKeyData[32];
4129 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4130 ASSERT_EQ(kmPubKeySize, 32);
4131 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4132
4133 string message(32, 'a');
4134 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4135 string signature = SignMessage(message, params);
4136 LocalVerifyMessage(message, signature, params);
4137}
4138
4139/*
4140 * ImportKeyTest.Ed25519Pkcs8Success
4141 *
4142 * Verifies that importing and using a PKCS#8-encoded Ed25519 private key works correctly.
4143 */
4144TEST_P(ImportKeyTest, Ed25519Pkcs8Success) {
4145 if (!Curve25519Supported()) {
4146 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4147 }
4148
4149 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4150 .Authorization(TAG_NO_AUTH_REQUIRED)
4151 .EcdsaSigningKey(EcCurve::CURVE_25519)
4152 .Digest(Digest::NONE)
4153 .SetDefaultValidity(),
4154 KeyFormat::PKCS8, ed25519_pkcs8_key));
4155 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4156 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4157 CheckOrigin();
4158
4159 // The returned cert should hold the correct public key.
4160 ASSERT_GT(cert_chain_.size(), 0);
4161 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
4162 ASSERT_NE(kmKeyCert, nullptr);
4163 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
4164 ASSERT_NE(kmPubKey.get(), nullptr);
4165 size_t kmPubKeySize = 32;
4166 uint8_t kmPubKeyData[32];
4167 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
4168 ASSERT_EQ(kmPubKeySize, 32);
4169 EXPECT_EQ(string(kmPubKeyData, kmPubKeyData + 32), ed25519_pubkey);
4170
4171 string message(32, 'a');
4172 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
4173 string signature = SignMessage(message, params);
4174 LocalVerifyMessage(message, signature, params);
4175}
4176
4177/*
4178 * ImportKeyTest.Ed25519CurveMismatch
4179 *
4180 * Verifies that importing an Ed25519 key pair with a curve that doesn't match the key fails in
4181 * the correct way.
4182 */
4183TEST_P(ImportKeyTest, Ed25519CurveMismatch) {
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,
4189 ImportKey(AuthorizationSetBuilder()
4190 .EcdsaSigningKey(EcCurve::P_224 /* Doesn't match key */)
4191 .Digest(Digest::NONE)
4192 .SetDefaultValidity(),
4193 KeyFormat::RAW, ed25519_key));
4194}
4195
4196/*
4197 * ImportKeyTest.Ed25519FormatMismatch
4198 *
4199 * Verifies that importing an Ed25519 key pair with an invalid format fails.
4200 */
4201TEST_P(ImportKeyTest, Ed25519FormatMismatch) {
4202 if (!Curve25519Supported()) {
4203 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4204 }
4205
4206 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4207 .EcdsaSigningKey(EcCurve::CURVE_25519)
4208 .Digest(Digest::NONE)
4209 .SetDefaultValidity(),
4210 KeyFormat::PKCS8, ed25519_key));
4211 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4212 .EcdsaSigningKey(EcCurve::CURVE_25519)
4213 .Digest(Digest::NONE)
4214 .SetDefaultValidity(),
4215 KeyFormat::RAW, ed25519_pkcs8_key));
4216}
4217
4218/*
4219 * ImportKeyTest.Ed25519PurposeMismatch
4220 *
4221 * Verifies that importing an Ed25519 key pair with an invalid purpose fails.
4222 */
4223TEST_P(ImportKeyTest, Ed25519PurposeMismatch) {
4224 if (!Curve25519Supported()) {
4225 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4226 }
4227
4228 // Can't have both SIGN and ATTEST_KEY
4229 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4230 .EcdsaSigningKey(EcCurve::CURVE_25519)
4231 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4232 .Digest(Digest::NONE)
4233 .SetDefaultValidity(),
4234 KeyFormat::RAW, ed25519_key));
4235 // AGREE_KEY is for X25519 (but can only tell the difference if the import key is in
4236 // PKCS#8 format and so includes an OID).
4237 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4238 .EcdsaKey(EcCurve::CURVE_25519)
4239 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4240 .Digest(Digest::NONE)
4241 .SetDefaultValidity(),
4242 KeyFormat::PKCS8, ed25519_pkcs8_key));
4243}
4244
4245/*
4246 * ImportKeyTest.X25519RawSuccess
4247 *
4248 * Verifies that importing and using a raw X25519 private key works correctly.
4249 */
4250TEST_P(ImportKeyTest, X25519RawSuccess) {
4251 if (!Curve25519Supported()) {
4252 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4253 }
4254
4255 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4256 .Authorization(TAG_NO_AUTH_REQUIRED)
4257 .EcdsaKey(EcCurve::CURVE_25519)
4258 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4259 .SetDefaultValidity(),
4260 KeyFormat::RAW, x25519_key));
4261
4262 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4263 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4264 CheckOrigin();
4265}
4266
4267/*
4268 * ImportKeyTest.X25519Pkcs8Success
4269 *
4270 * Verifies that importing and using a PKCS#8-encoded X25519 private key works correctly.
4271 */
4272TEST_P(ImportKeyTest, X25519Pkcs8Success) {
4273 if (!Curve25519Supported()) {
4274 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4275 }
4276
4277 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4278 .Authorization(TAG_NO_AUTH_REQUIRED)
4279 .EcdsaKey(EcCurve::CURVE_25519)
4280 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4281 .SetDefaultValidity(),
4282 KeyFormat::PKCS8, x25519_pkcs8_key));
4283
4284 CheckCryptoParam(TAG_ALGORITHM, Algorithm::EC);
4285 CheckCryptoParam(TAG_EC_CURVE, EcCurve::CURVE_25519);
4286 CheckOrigin();
4287}
4288
4289/*
4290 * ImportKeyTest.X25519CurveMismatch
4291 *
4292 * Verifies that importing an X25519 key with a curve that doesn't match the key fails in
4293 * the correct way.
4294 */
4295TEST_P(ImportKeyTest, X25519CurveMismatch) {
4296 if (!Curve25519Supported()) {
4297 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4298 }
4299
4300 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4301 .EcdsaKey(EcCurve::P_224 /* Doesn't match key */)
4302 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4303 .SetDefaultValidity(),
4304 KeyFormat::RAW, x25519_key));
4305}
4306
4307/*
4308 * ImportKeyTest.X25519FormatMismatch
4309 *
4310 * Verifies that importing an X25519 key with an invalid format fails.
4311 */
4312TEST_P(ImportKeyTest, X25519FormatMismatch) {
4313 if (!Curve25519Supported()) {
4314 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4315 }
4316
4317 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4318 .EcdsaKey(EcCurve::CURVE_25519)
4319 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4320 .SetDefaultValidity(),
4321 KeyFormat::PKCS8, x25519_key));
4322 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4323 .EcdsaKey(EcCurve::CURVE_25519)
4324 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
4325 .SetDefaultValidity(),
4326 KeyFormat::RAW, x25519_pkcs8_key));
4327}
4328
4329/*
4330 * ImportKeyTest.X25519PurposeMismatch
4331 *
4332 * Verifies that importing an X25519 key pair with an invalid format fails.
4333 */
4334TEST_P(ImportKeyTest, X25519PurposeMismatch) {
4335 if (!Curve25519Supported()) {
4336 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
4337 }
4338
4339 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4340 .EcdsaKey(EcCurve::CURVE_25519)
4341 .Authorization(TAG_PURPOSE, KeyPurpose::ATTEST_KEY)
4342 .SetDefaultValidity(),
4343 KeyFormat::PKCS8, x25519_pkcs8_key));
4344 ASSERT_NE(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4345 .EcdsaSigningKey(EcCurve::CURVE_25519)
4346 .SetDefaultValidity(),
4347 KeyFormat::PKCS8, x25519_pkcs8_key));
4348}
4349
4350/*
Selene Huang31ab4042020-04-29 04:22:39 -07004351 * ImportKeyTest.AesSuccess
4352 *
4353 * Verifies that importing and using an AES key works.
4354 */
4355TEST_P(ImportKeyTest, AesSuccess) {
4356 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4357 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4358 .Authorization(TAG_NO_AUTH_REQUIRED)
4359 .AesEncryptionKey(key.size() * 8)
4360 .EcbMode()
4361 .Padding(PaddingMode::PKCS7),
4362 KeyFormat::RAW, key));
4363
4364 CheckCryptoParam(TAG_ALGORITHM, Algorithm::AES);
4365 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4366 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4367 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4368 CheckOrigin();
4369
4370 string message = "Hello World!";
4371 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4372 string ciphertext = EncryptMessage(message, params);
4373 string plaintext = DecryptMessage(ciphertext, params);
4374 EXPECT_EQ(message, plaintext);
4375}
4376
4377/*
David Drysdale7de9feb2021-03-05 14:56:19 +00004378 * ImportKeyTest.AesFailure
4379 *
4380 * Verifies that importing an invalid AES key fails.
4381 */
4382TEST_P(ImportKeyTest, AesFailure) {
4383 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4384 uint32_t bitlen = key.size() * 8;
4385 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004386 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004387 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004388 .Authorization(TAG_NO_AUTH_REQUIRED)
4389 .AesEncryptionKey(key_size)
4390 .EcbMode()
4391 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004392 KeyFormat::RAW, key);
4393 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004394 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4395 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004396 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004397
4398 // Explicit key size matches that of the provided key, but it's not a valid size.
4399 string long_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4400 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4401 ImportKey(AuthorizationSetBuilder()
4402 .Authorization(TAG_NO_AUTH_REQUIRED)
4403 .AesEncryptionKey(long_key.size() * 8)
4404 .EcbMode()
4405 .Padding(PaddingMode::PKCS7),
4406 KeyFormat::RAW, long_key));
4407 string short_key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4408 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4409 ImportKey(AuthorizationSetBuilder()
4410 .Authorization(TAG_NO_AUTH_REQUIRED)
4411 .AesEncryptionKey(short_key.size() * 8)
4412 .EcbMode()
4413 .Padding(PaddingMode::PKCS7),
4414 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004415}
4416
4417/*
4418 * ImportKeyTest.TripleDesSuccess
4419 *
4420 * Verifies that importing and using a 3DES key works.
4421 */
4422TEST_P(ImportKeyTest, TripleDesSuccess) {
4423 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
4424 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4425 .Authorization(TAG_NO_AUTH_REQUIRED)
4426 .TripleDesEncryptionKey(168)
4427 .EcbMode()
4428 .Padding(PaddingMode::PKCS7),
4429 KeyFormat::RAW, key));
4430
4431 CheckCryptoParam(TAG_ALGORITHM, Algorithm::TRIPLE_DES);
4432 CheckCryptoParam(TAG_KEY_SIZE, 168U);
4433 CheckCryptoParam(TAG_PADDING, PaddingMode::PKCS7);
4434 CheckCryptoParam(TAG_BLOCK_MODE, BlockMode::ECB);
4435 CheckOrigin();
4436
4437 string message = "Hello World!";
4438 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4439 string ciphertext = EncryptMessage(message, params);
4440 string plaintext = DecryptMessage(ciphertext, params);
4441 EXPECT_EQ(message, plaintext);
4442}
4443
4444/*
4445 * ImportKeyTest.TripleDesFailure
4446 *
4447 * Verifies that importing an invalid 3DES key fails.
4448 */
4449TEST_P(ImportKeyTest, TripleDesFailure) {
4450 string key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358");
David Drysdale2a73db32021-05-10 10:58:58 +01004451 uint32_t bitlen = key.size() * 7;
David Drysdale7de9feb2021-03-05 14:56:19 +00004452 for (uint32_t key_size : {bitlen - 1, bitlen + 1, bitlen - 8, bitlen + 8}) {
David Drysdalec9bc2f72021-05-04 10:47:58 +01004453 // Explicit key size doesn't match that of the provided key.
Tommy Chiu3950b452021-05-03 22:01:46 +08004454 auto result = ImportKey(AuthorizationSetBuilder()
Shawn Willden9a7410e2021-08-02 12:28:42 -06004455 .Authorization(TAG_NO_AUTH_REQUIRED)
4456 .TripleDesEncryptionKey(key_size)
4457 .EcbMode()
4458 .Padding(PaddingMode::PKCS7),
Tommy Chiu3950b452021-05-03 22:01:46 +08004459 KeyFormat::RAW, key);
4460 ASSERT_TRUE(result == ErrorCode::IMPORT_PARAMETER_MISMATCH ||
David Drysdalec9bc2f72021-05-04 10:47:58 +01004461 result == ErrorCode::UNSUPPORTED_KEY_SIZE)
4462 << "unexpected result: " << result;
David Drysdale7de9feb2021-03-05 14:56:19 +00004463 }
David Drysdalec9bc2f72021-05-04 10:47:58 +01004464 // Explicit key size matches that of the provided key, but it's not a valid size.
David Drysdale2a73db32021-05-10 10:58:58 +01004465 string long_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f735800");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004466 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4467 ImportKey(AuthorizationSetBuilder()
4468 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004469 .TripleDesEncryptionKey(long_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004470 .EcbMode()
4471 .Padding(PaddingMode::PKCS7),
4472 KeyFormat::RAW, long_key));
David Drysdale2a73db32021-05-10 10:58:58 +01004473 string short_key = hex2str("a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f73");
David Drysdalec9bc2f72021-05-04 10:47:58 +01004474 ASSERT_EQ(ErrorCode::UNSUPPORTED_KEY_SIZE,
4475 ImportKey(AuthorizationSetBuilder()
4476 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdale2a73db32021-05-10 10:58:58 +01004477 .TripleDesEncryptionKey(short_key.size() * 7)
David Drysdalec9bc2f72021-05-04 10:47:58 +01004478 .EcbMode()
4479 .Padding(PaddingMode::PKCS7),
4480 KeyFormat::RAW, short_key));
David Drysdale7de9feb2021-03-05 14:56:19 +00004481}
4482
4483/*
4484 * ImportKeyTest.HmacKeySuccess
Selene Huang31ab4042020-04-29 04:22:39 -07004485 *
4486 * Verifies that importing and using an HMAC key works.
4487 */
4488TEST_P(ImportKeyTest, HmacKeySuccess) {
4489 string key = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
4490 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
4491 .Authorization(TAG_NO_AUTH_REQUIRED)
4492 .HmacKey(key.size() * 8)
4493 .Digest(Digest::SHA_2_256)
4494 .Authorization(TAG_MIN_MAC_LENGTH, 256),
4495 KeyFormat::RAW, key));
4496
4497 CheckCryptoParam(TAG_ALGORITHM, Algorithm::HMAC);
4498 CheckCryptoParam(TAG_KEY_SIZE, 128U);
4499 CheckCryptoParam(TAG_DIGEST, Digest::SHA_2_256);
4500 CheckOrigin();
4501
4502 string message = "Hello World!";
4503 string signature = MacMessage(message, Digest::SHA_2_256, 256);
4504 VerifyMessage(message, signature, AuthorizationSetBuilder().Digest(Digest::SHA_2_256));
4505}
4506
4507INSTANTIATE_KEYMINT_AIDL_TEST(ImportKeyTest);
4508
4509auto wrapped_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004510 // IKeyMintDevice.aidl
4511 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4512 "020100" // INTEGER length 1 value 0x00 (version)
4513 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4514 "934bf94e2aa28a3f83c9f79297250262"
4515 "fbe3276b5a1c91159bbfa3ef8957aac8"
4516 "4b59b30b455a79c2973480823d8b3863"
4517 "c3deef4a8e243590268d80e18751a0e1"
4518 "30f67ce6a1ace9f79b95e097474febc9"
4519 "81195b1d13a69086c0863f66a7b7fdb4"
4520 "8792227b1ac5e2489febdf087ab54864"
4521 "83033a6f001ca5d1ec1e27f5c30f4cec"
4522 "2642074a39ae68aee552e196627a8e3d"
4523 "867e67a8c01b11e75f13cca0a97ab668"
4524 "b50cda07a8ecb7cd8e3dd7009c963653"
4525 "4f6f239cffe1fc8daa466f78b676c711"
4526 "9efb96bce4e69ca2a25d0b34ed9c3ff9"
4527 "99b801597d5220e307eaa5bee507fb94"
4528 "d1fa69f9e519b2de315bac92c36f2ea1"
4529 "fa1df4478c0ddedeae8c70e0233cd098"
4530 "040c" // OCTET STRING length 0x0c (initializationVector)
4531 "d796b02c370f1fa4cc0124f1"
4532 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4533 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4534 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4535 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4536 "3106" // SET length 0x06
4537 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4538 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4539 // } end SET
4540 // } end [1]
4541 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4542 "020120" // INTEGER length 1 value 0x20 (AES)
4543 // } end [2]
4544 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4545 "02020100" // INTEGER length 2 value 0x100
4546 // } end [3]
4547 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode)
4548 "3103" // SET length 0x03 {
4549 "020101" // INTEGER length 1 value 0x01 (ECB)
4550 // } end SET
4551 // } end [4]
4552 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4553 "3103" // SET length 0x03 {
4554 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4555 // } end SET
4556 // } end [5]
4557 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4558 // (noAuthRequired)
4559 "0500" // NULL
4560 // } end [503]
4561 // } end SEQUENCE (AuthorizationList)
4562 // } end SEQUENCE (KeyDescription)
4563 "0420" // OCTET STRING length 0x20 (encryptedKey)
4564 "ccd540855f833a5e1480bfd2d36faf3a"
4565 "eee15df5beabe2691bc82dde2a7aa910"
4566 "0410" // OCTET STRING length 0x10 (tag)
4567 "64c9f689c60ff6223ab6e6999e0eb6e5"
4568 // } SEQUENCE (SecureKeyWrapper)
4569);
Selene Huang31ab4042020-04-29 04:22:39 -07004570
4571auto wrapped_key_masked = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004572 // IKeyMintDevice.aidl
4573 "30820179" // SEQUENCE length 0x179 (SecureKeyWrapper) {
4574 "020100" // INTEGER length 1 value 0x00 (version)
4575 "04820100" // OCTET STRING length 0x100 (encryptedTransportKey)
4576 "aad93ed5924f283b4bb5526fbe7a1412"
4577 "f9d9749ec30db9062b29e574a8546f33"
4578 "c88732452f5b8e6a391ee76c39ed1712"
4579 "c61d8df6213dec1cffbc17a8c6d04c7b"
4580 "30893d8daa9b2015213e219468215532"
4581 "07f8f9931c4caba23ed3bee28b36947e"
4582 "47f10e0a5c3dc51c988a628daad3e5e1"
4583 "f4005e79c2d5a96c284b4b8d7e4948f3"
4584 "31e5b85dd5a236f85579f3ea1d1b8484"
4585 "87470bdb0ab4f81a12bee42c99fe0df4"
4586 "bee3759453e69ad1d68a809ce06b949f"
4587 "7694a990429b2fe81e066ff43e56a216"
4588 "02db70757922a4bcc23ab89f1e35da77"
4589 "586775f423e519c2ea394caf48a28d0c"
4590 "8020f1dcf6b3a68ec246f615ae96dae9"
4591 "a079b1f6eb959033c1af5c125fd94168"
4592 "040c" // OCTET STRING length 0x0c (initializationVector)
4593 "6d9721d08589581ab49204a3"
4594 "302e" // SEQUENCE length 0x2e (KeyDescription) {
4595 "020103" // INTEGER length 1 value 0x03 (keyFormat = RAW)
4596 "3029" // SEQUENCE length 0x29 (AuthorizationList) {
4597 "a108" // [1] context-specific constructed tag=1 length 0x08 { (purpose)
4598 "3106" // SET length 0x06
4599 "020100" // INTEGER length 1 value 0x00 (Encrypt)
4600 "020101" // INTEGER length 1 value 0x01 (Decrypt)
4601 // } end SET
4602 // } end [1]
4603 "a203" // [2] context-specific constructed tag=2 length 0x02 { (algorithm)
4604 "020120" // INTEGER length 1 value 0x20 (AES)
4605 // } end [2]
4606 "a304" // [3] context-specific constructed tag=3 length 0x04 { (keySize)
4607 "02020100" // INTEGER length 2 value 0x100
4608 // } end [3]
4609 "a405" // [4] context-specific constructed tag=4 length 0x05 { (blockMode
4610 "3103" // SET length 0x03 {
4611 "020101" // INTEGER length 1 value 0x01 (ECB)
4612 // } end SET
4613 // } end [4]
4614 "a605" // [6] context-specific constructed tag=6 length 0x05 { (padding)
4615 "3103" // SET length 0x03 {
4616 "020140" // INTEGER length 1 value 0x40 (PKCS7)
4617 // } end SET
4618 // } end [5]
4619 "bf837702" // [503] context-specific constructed tag=503=0x1F7 length 0x02 {
4620 // (noAuthRequired)
4621 "0500" // NULL
4622 // } end [503]
4623 // } end SEQUENCE (AuthorizationList)
4624 // } end SEQUENCE (KeyDescription)
4625 "0420" // OCTET STRING length 0x20 (encryptedKey)
4626 "a61c6e247e25b3e6e69aa78eb03c2d4a"
4627 "c20d1f99a9a024a76f35c8e2cab9b68d"
4628 "0410" // OCTET STRING length 0x10 (tag)
4629 "2560c70109ae67c030f00b98b512a670"
4630 // } SEQUENCE (SecureKeyWrapper)
4631);
Selene Huang31ab4042020-04-29 04:22:39 -07004632
4633auto wrapping_key = hex2str(
David Drysdaled2cc8c22021-04-15 13:29:45 +01004634 // RFC 5208 s5
4635 "308204be" // SEQUENCE length 0x4be (PrivateKeyInfo) {
4636 "020100" // INTEGER length 1 value 0x00 (version)
4637 "300d" // SEQUENCE length 0x0d (AlgorithmIdentifier) {
4638 "0609" // OBJECT IDENTIFIER length 0x09 (algorithm)
4639 "2a864886f70d010101" // 1.2.840.113549.1.1.1 (RSAES-PKCS1-v1_5 encryption scheme)
4640 "0500" // NULL (parameters)
4641 // } SEQUENCE (AlgorithmIdentifier)
4642 "048204a8" // OCTET STRING len 0x4a8 (privateKey), which contains...
4643 // RFC 8017 A.1.2
4644 "308204a4" // SEQUENCE len 0x4a4 (RSAPrivateKey) {
4645 "020100" // INTEGER length 1 value 0x00 (version)
4646 "02820101" // INTEGER length 0x0101 (modulus) value...
4647 "00aec367931d8900ce56b0067f7d70e1" // 0x10
4648 "fc653f3f34d194c1fed50018fb43db93" // 0x20
4649 "7b06e673a837313d56b1c725150a3fef" // 0x30
4650 "86acbddc41bb759c2854eae32d35841e" // 0x40
4651 "fb5c18d82bc90a1cb5c1d55adf245b02" // 0x50
4652 "911f0b7cda88c421ff0ebafe7c0d23be" // 0x60
4653 "312d7bd5921ffaea1347c157406fef71" // 0x70
4654 "8f682643e4e5d33c6703d61c0cf7ac0b" // 0x80
4655 "f4645c11f5c1374c3886427411c44979" // 0x90
4656 "6792e0bef75dec858a2123c36753e02a" // 0xa0
4657 "95a96d7c454b504de385a642e0dfc3e6" // 0xb0
4658 "0ac3a7ee4991d0d48b0172a95f9536f0" // 0xc0
4659 "2ba13cecccb92b727db5c27e5b2f5cec" // 0xd0
4660 "09600b286af5cf14c42024c61ddfe71c" // 0xe0
4661 "2a8d7458f185234cb00e01d282f10f8f" // 0xf0
4662 "c6721d2aed3f4833cca2bd8fa62821dd" // 0x100
4663 "55" // 0x101
4664 "0203010001" // INTEGER length 3 value 0x10001 (publicExponent)
4665 "02820100" // INTEGER length 0x100 (privateExponent) value...
4666 "431447b6251908112b1ee76f99f3711a" // 0x10
4667 "52b6630960046c2de70de188d833f8b8" // 0x20
4668 "b91e4d785caeeeaf4f0f74414e2cda40" // 0x30
4669 "641f7fe24f14c67a88959bdb27766df9" // 0x40
4670 "e710b630a03adc683b5d2c43080e52be" // 0x50
4671 "e71e9eaeb6de297a5fea1072070d181c" // 0x60
4672 "822bccff087d63c940ba8a45f670feb2" // 0x70
4673 "9fb4484d1c95e6d2579ba02aae0a0090" // 0x80
4674 "0c3ebf490e3d2cd7ee8d0e20c536e4dc" // 0x90
4675 "5a5097272888cddd7e91f228b1c4d747" // 0xa0
4676 "4c55b8fcd618c4a957bbddd5ad7407cc" // 0xb0
4677 "312d8d98a5caf7e08f4a0d6b45bb41c6" // 0xc0
4678 "52659d5a5ba05b663737a8696281865b" // 0xd0
4679 "a20fbdd7f851e6c56e8cbe0ddbbf24dc" // 0xe0
4680 "03b2d2cb4c3d540fb0af52e034a2d066" // 0xf0
4681 "98b128e5f101e3b51a34f8d8b4f86181" // 0x100
4682 "028181" // INTEGER length 0x81 (prime1) value...
4683 "00de392e18d682c829266cc3454e1d61" // 0x10
4684 "66242f32d9a1d10577753e904ea7d08b" // 0x20
4685 "ff841be5bac82a164c5970007047b8c5" // 0x30
4686 "17db8f8f84e37bd5988561bdf503d4dc" // 0x40
4687 "2bdb38f885434ae42c355f725c9a60f9" // 0x50
4688 "1f0788e1f1a97223b524b5357fdf72e2" // 0x60
4689 "f696bab7d78e32bf92ba8e1864eab122" // 0x70
4690 "9e91346130748a6e3c124f9149d71c74" // 0x80
4691 "35"
4692 "028181" // INTEGER length 0x81 (prime2) value...
4693 "00c95387c0f9d35f137b57d0d65c397c" // 0x10
4694 "5e21cc251e47008ed62a542409c8b6b6" // 0x20
4695 "ac7f8967b3863ca645fcce49582a9aa1" // 0x30
4696 "7349db6c4a95affdae0dae612e1afac9" // 0x40
4697 "9ed39a2d934c880440aed8832f984316" // 0x50
4698 "3a47f27f392199dc1202f9a0f9bd0830" // 0x60
4699 "8007cb1e4e7f58309366a7de25f7c3c9" // 0x70
4700 "b880677c068e1be936e81288815252a8" // 0x80
4701 "a1"
4702 "028180" // INTEGER length 0x80 (exponent1) value...
4703 "57ff8ca1895080b2cae486ef0adfd791" // 0x10
4704 "fb0235c0b8b36cd6c136e52e4085f4ea" // 0x20
4705 "5a063212a4f105a3764743e53281988a" // 0x30
4706 "ba073f6e0027298e1c4378556e0efca0" // 0x40
4707 "e14ece1af76ad0b030f27af6f0ab35fb" // 0x50
4708 "73a060d8b1a0e142fa2647e93b32e36d" // 0x60
4709 "8282ae0a4de50ab7afe85500a16f43a6" // 0x70
4710 "4719d6e2b9439823719cd08bcd031781" // 0x80
4711 "028181" // INTEGER length 0x81 (exponent2) value...
4712 "00ba73b0bb28e3f81e9bd1c568713b10" // 0x10
4713 "1241acc607976c4ddccc90e65b6556ca" // 0x20
4714 "31516058f92b6e09f3b160ff0e374ec4" // 0x30
4715 "0d78ae4d4979fde6ac06a1a400c61dd3" // 0x40
4716 "1254186af30b22c10582a8a43e34fe94" // 0x50
4717 "9c5f3b9755bae7baa7b7b7a6bd03b38c" // 0x60
4718 "ef55c86885fc6c1978b9cee7ef33da50" // 0x70
4719 "7c9df6b9277cff1e6aaa5d57aca52846" // 0x80
4720 "61"
4721 "028181" // INTEGER length 0x81 (coefficient) value...
4722 "00c931617c77829dfb1270502be9195c" // 0x10
4723 "8f2830885f57dba869536811e6864236" // 0x20
4724 "d0c4736a0008a145af36b8357a7c3d13" // 0x30
4725 "9966d04c4e00934ea1aede3bb6b8ec84" // 0x40
4726 "1dc95e3f579751e2bfdfe27ae778983f" // 0x50
4727 "959356210723287b0affcc9f727044d4" // 0x60
4728 "8c373f1babde0724fa17a4fd4da0902c" // 0x70
4729 "7c9b9bf27ba61be6ad02dfddda8f4e68" // 0x80
4730 "22"
4731 // } SEQUENCE
4732 // } SEQUENCE ()
4733);
Selene Huang31ab4042020-04-29 04:22:39 -07004734
4735string zero_masking_key =
4736 hex2str("0000000000000000000000000000000000000000000000000000000000000000");
4737string masking_key = hex2str("D796B02C370F1FA4CC0124F14EC8CBEBE987E825246265050F399A51FD477DFC");
4738
4739class ImportWrappedKeyTest : public KeyMintAidlTestBase {};
4740
4741TEST_P(ImportWrappedKeyTest, Success) {
4742 auto wrapping_key_desc = AuthorizationSetBuilder()
4743 .RsaEncryptionKey(2048, 65537)
4744 .Digest(Digest::SHA_2_256)
4745 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004746 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4747 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004748
4749 ASSERT_EQ(ErrorCode::OK,
4750 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4751 AuthorizationSetBuilder()
4752 .Digest(Digest::SHA_2_256)
4753 .Padding(PaddingMode::RSA_OAEP)));
4754
4755 string message = "Hello World!";
4756 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4757 string ciphertext = EncryptMessage(message, params);
4758 string plaintext = DecryptMessage(ciphertext, params);
4759 EXPECT_EQ(message, plaintext);
4760}
4761
David Drysdaled2cc8c22021-04-15 13:29:45 +01004762/*
4763 * ImportWrappedKeyTest.SuccessSidsIgnored
4764 *
4765 * Verifies that password_sid and biometric_sid are ignored on import if the authorizations don't
4766 * include Tag:USER_SECURE_ID.
4767 */
4768TEST_P(ImportWrappedKeyTest, SuccessSidsIgnored) {
4769 auto wrapping_key_desc = AuthorizationSetBuilder()
4770 .RsaEncryptionKey(2048, 65537)
4771 .Digest(Digest::SHA_2_256)
4772 .Padding(PaddingMode::RSA_OAEP)
4773 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4774 .SetDefaultValidity();
4775
4776 int64_t password_sid = 42;
4777 int64_t biometric_sid = 24;
4778 ASSERT_EQ(ErrorCode::OK,
4779 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4780 AuthorizationSetBuilder()
4781 .Digest(Digest::SHA_2_256)
4782 .Padding(PaddingMode::RSA_OAEP),
4783 password_sid, biometric_sid));
4784
4785 string message = "Hello World!";
4786 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
4787 string ciphertext = EncryptMessage(message, params);
4788 string plaintext = DecryptMessage(ciphertext, params);
4789 EXPECT_EQ(message, plaintext);
4790}
4791
Selene Huang31ab4042020-04-29 04:22:39 -07004792TEST_P(ImportWrappedKeyTest, SuccessMasked) {
4793 auto wrapping_key_desc = AuthorizationSetBuilder()
4794 .RsaEncryptionKey(2048, 65537)
4795 .Digest(Digest::SHA_2_256)
4796 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004797 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4798 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004799
4800 ASSERT_EQ(ErrorCode::OK,
4801 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, masking_key,
4802 AuthorizationSetBuilder()
4803 .Digest(Digest::SHA_2_256)
4804 .Padding(PaddingMode::RSA_OAEP)));
4805}
4806
4807TEST_P(ImportWrappedKeyTest, WrongMask) {
4808 auto wrapping_key_desc = AuthorizationSetBuilder()
4809 .RsaEncryptionKey(2048, 65537)
4810 .Digest(Digest::SHA_2_256)
4811 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004812 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4813 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004814
4815 ASSERT_EQ(
4816 ErrorCode::VERIFICATION_FAILED,
4817 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4818 AuthorizationSetBuilder()
4819 .Digest(Digest::SHA_2_256)
4820 .Padding(PaddingMode::RSA_OAEP)));
4821}
4822
4823TEST_P(ImportWrappedKeyTest, WrongPurpose) {
4824 auto wrapping_key_desc = AuthorizationSetBuilder()
4825 .RsaEncryptionKey(2048, 65537)
4826 .Digest(Digest::SHA_2_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004827 .Padding(PaddingMode::RSA_OAEP)
4828 .SetDefaultValidity();
Selene Huang31ab4042020-04-29 04:22:39 -07004829
4830 ASSERT_EQ(
4831 ErrorCode::INCOMPATIBLE_PURPOSE,
4832 ImportWrappedKey(wrapped_key_masked, wrapping_key, wrapping_key_desc, zero_masking_key,
4833 AuthorizationSetBuilder()
4834 .Digest(Digest::SHA_2_256)
4835 .Padding(PaddingMode::RSA_OAEP)));
4836}
4837
David Drysdaled2cc8c22021-04-15 13:29:45 +01004838TEST_P(ImportWrappedKeyTest, WrongPaddingMode) {
4839 auto wrapping_key_desc = AuthorizationSetBuilder()
4840 .RsaEncryptionKey(2048, 65537)
4841 .Digest(Digest::SHA_2_256)
4842 .Padding(PaddingMode::RSA_PSS)
4843 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4844 .SetDefaultValidity();
4845
4846 ASSERT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE,
4847 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4848 AuthorizationSetBuilder()
4849 .Digest(Digest::SHA_2_256)
4850 .Padding(PaddingMode::RSA_OAEP)));
4851}
4852
4853TEST_P(ImportWrappedKeyTest, WrongDigest) {
4854 auto wrapping_key_desc = AuthorizationSetBuilder()
4855 .RsaEncryptionKey(2048, 65537)
4856 .Digest(Digest::SHA_2_512)
4857 .Padding(PaddingMode::RSA_OAEP)
4858 .Authorization(TAG_PURPOSE, KeyPurpose::WRAP_KEY)
4859 .SetDefaultValidity();
4860
4861 ASSERT_EQ(ErrorCode::INCOMPATIBLE_DIGEST,
4862 ImportWrappedKey(wrapped_key, wrapping_key, wrapping_key_desc, zero_masking_key,
4863 AuthorizationSetBuilder()
4864 .Digest(Digest::SHA_2_256)
4865 .Padding(PaddingMode::RSA_OAEP)));
4866}
4867
Selene Huang31ab4042020-04-29 04:22:39 -07004868INSTANTIATE_KEYMINT_AIDL_TEST(ImportWrappedKeyTest);
4869
4870typedef KeyMintAidlTestBase EncryptionOperationsTest;
4871
4872/*
4873 * EncryptionOperationsTest.RsaNoPaddingSuccess
4874 *
David Drysdale59cae642021-05-12 13:52:03 +01004875 * Verifies that raw RSA decryption works.
Selene Huang31ab4042020-04-29 04:22:39 -07004876 */
4877TEST_P(EncryptionOperationsTest, RsaNoPaddingSuccess) {
subrahmanyaman05642492022-02-05 07:10:56 +00004878 for (uint64_t exponent : ValidExponents()) {
David Drysdaled2cc8c22021-04-15 13:29:45 +01004879 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4880 .Authorization(TAG_NO_AUTH_REQUIRED)
4881 .RsaEncryptionKey(2048, exponent)
4882 .Padding(PaddingMode::NONE)
4883 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004884
David Drysdaled2cc8c22021-04-15 13:29:45 +01004885 string message = string(2048 / 8, 'a');
4886 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004887 string ciphertext1 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004888 EXPECT_EQ(2048U / 8, ciphertext1.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004889
David Drysdale59cae642021-05-12 13:52:03 +01004890 string ciphertext2 = LocalRsaEncryptMessage(message, params);
David Drysdaled2cc8c22021-04-15 13:29:45 +01004891 EXPECT_EQ(2048U / 8, ciphertext2.size());
Selene Huang31ab4042020-04-29 04:22:39 -07004892
David Drysdaled2cc8c22021-04-15 13:29:45 +01004893 // Unpadded RSA is deterministic
4894 EXPECT_EQ(ciphertext1, ciphertext2);
4895
4896 CheckedDeleteKey();
4897 }
Selene Huang31ab4042020-04-29 04:22:39 -07004898}
4899
4900/*
4901 * EncryptionOperationsTest.RsaNoPaddingShortMessage
4902 *
David Drysdale59cae642021-05-12 13:52:03 +01004903 * Verifies that raw RSA decryption of short messages works.
Selene Huang31ab4042020-04-29 04:22:39 -07004904 */
4905TEST_P(EncryptionOperationsTest, RsaNoPaddingShortMessage) {
4906 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4907 .Authorization(TAG_NO_AUTH_REQUIRED)
4908 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004909 .Padding(PaddingMode::NONE)
4910 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004911
4912 string message = "1";
4913 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
4914
David Drysdale59cae642021-05-12 13:52:03 +01004915 string ciphertext = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004916 EXPECT_EQ(2048U / 8, ciphertext.size());
4917
4918 string expected_plaintext = string(2048U / 8 - 1, 0) + message;
4919 string plaintext = DecryptMessage(ciphertext, params);
4920
4921 EXPECT_EQ(expected_plaintext, plaintext);
Selene Huang31ab4042020-04-29 04:22:39 -07004922}
4923
4924/*
Selene Huang31ab4042020-04-29 04:22:39 -07004925 * EncryptionOperationsTest.RsaOaepSuccess
4926 *
David Drysdale59cae642021-05-12 13:52:03 +01004927 * Verifies that RSA-OAEP decryption operations work, with all digests.
Selene Huang31ab4042020-04-29 04:22:39 -07004928 */
4929TEST_P(EncryptionOperationsTest, RsaOaepSuccess) {
4930 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
4931
4932 size_t key_size = 2048; // Need largish key for SHA-512 test.
David Drysdale59cae642021-05-12 13:52:03 +01004933 ASSERT_EQ(ErrorCode::OK,
4934 GenerateKey(AuthorizationSetBuilder()
4935 .Authorization(TAG_NO_AUTH_REQUIRED)
4936 .RsaEncryptionKey(key_size, 65537)
4937 .Padding(PaddingMode::RSA_OAEP)
4938 .Digest(digests)
4939 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1)
4940 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004941
4942 string message = "Hello";
4943
4944 for (auto digest : digests) {
David Drysdale59cae642021-05-12 13:52:03 +01004945 SCOPED_TRACE(testing::Message() << "digest-" << digest);
4946
4947 auto params = AuthorizationSetBuilder()
4948 .Digest(digest)
4949 .Padding(PaddingMode::RSA_OAEP)
4950 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA1);
4951 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004952 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
4953 EXPECT_EQ(key_size / 8, ciphertext1.size());
4954
David Drysdale59cae642021-05-12 13:52:03 +01004955 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07004956 EXPECT_EQ(key_size / 8, ciphertext2.size());
4957
4958 // OAEP randomizes padding so every result should be different (with astronomically high
4959 // probability).
4960 EXPECT_NE(ciphertext1, ciphertext2);
4961
4962 string plaintext1 = DecryptMessage(ciphertext1, params);
4963 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
4964 string plaintext2 = DecryptMessage(ciphertext2, params);
4965 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
4966
4967 // Decrypting corrupted ciphertext should fail.
4968 size_t offset_to_corrupt = random() % ciphertext1.size();
4969 char corrupt_byte;
4970 do {
4971 corrupt_byte = static_cast<char>(random() % 256);
4972 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
4973 ciphertext1[offset_to_corrupt] = corrupt_byte;
4974
4975 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
4976 string result;
4977 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
4978 EXPECT_EQ(0U, result.size());
4979 }
4980}
4981
4982/*
4983 * EncryptionOperationsTest.RsaOaepInvalidDigest
4984 *
David Drysdale59cae642021-05-12 13:52:03 +01004985 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Selene Huang31ab4042020-04-29 04:22:39 -07004986 * without a digest.
4987 */
4988TEST_P(EncryptionOperationsTest, RsaOaepInvalidDigest) {
4989 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
4990 .Authorization(TAG_NO_AUTH_REQUIRED)
4991 .RsaEncryptionKey(2048, 65537)
4992 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08004993 .Digest(Digest::NONE)
4994 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07004995
4996 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_OAEP).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01004997 EXPECT_EQ(ErrorCode::INCOMPATIBLE_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Selene Huang31ab4042020-04-29 04:22:39 -07004998}
4999
5000/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005001 * EncryptionOperationsTest.RsaOaepInvalidPadding
5002 *
David Drysdale59cae642021-05-12 13:52:03 +01005003 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
David Drysdaled2cc8c22021-04-15 13:29:45 +01005004 * with a padding value that is only suitable for signing/verifying.
5005 */
5006TEST_P(EncryptionOperationsTest, RsaOaepInvalidPadding) {
5007 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5008 .Authorization(TAG_NO_AUTH_REQUIRED)
5009 .RsaEncryptionKey(2048, 65537)
5010 .Padding(PaddingMode::RSA_PSS)
5011 .Digest(Digest::NONE)
5012 .SetDefaultValidity()));
5013
5014 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PSS).Digest(Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005015 EXPECT_EQ(ErrorCode::UNSUPPORTED_PADDING_MODE, Begin(KeyPurpose::DECRYPT, params));
David Drysdaled2cc8c22021-04-15 13:29:45 +01005016}
5017
5018/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005019 * EncryptionOperationsTest.RsaOaepDecryptWithWrongDigest
Selene Huang31ab4042020-04-29 04:22:39 -07005020 *
David Drysdale59cae642021-05-12 13:52:03 +01005021 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07005022 * with a different digest than was used to encrypt.
5023 */
5024TEST_P(EncryptionOperationsTest, RsaOaepDecryptWithWrongDigest) {
David Drysdale513bf122021-10-06 11:53:13 +01005025 if (SecLevel() == SecurityLevel::STRONGBOX) {
5026 GTEST_SKIP() << "Test not applicable to StrongBox device";
5027 }
Selene Huang31ab4042020-04-29 04:22:39 -07005028
5029 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5030 .Authorization(TAG_NO_AUTH_REQUIRED)
5031 .RsaEncryptionKey(1024, 65537)
5032 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005033 .Digest(Digest::SHA_2_224, Digest::SHA_2_256)
5034 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005035 string message = "Hello World!";
David Drysdale59cae642021-05-12 13:52:03 +01005036 string ciphertext = LocalRsaEncryptMessage(
Selene Huang31ab4042020-04-29 04:22:39 -07005037 message,
5038 AuthorizationSetBuilder().Digest(Digest::SHA_2_224).Padding(PaddingMode::RSA_OAEP));
5039
5040 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5041 .Digest(Digest::SHA_2_256)
5042 .Padding(PaddingMode::RSA_OAEP)));
5043 string result;
5044 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext, &result));
5045 EXPECT_EQ(0U, result.size());
5046}
5047
5048/*
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005049 * EncryptionOperationsTest.RsaOaepWithMGFDigestSuccess
5050 *
David Drysdale59cae642021-05-12 13:52:03 +01005051 * Verifies that RSA-OAEP decryption operations work, with all SHA 256 digests and all type of MGF1
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005052 * digests.
5053 */
5054TEST_P(EncryptionOperationsTest, RsaOaepWithMGFDigestSuccess) {
5055 auto digests = ValidDigests(false /* withNone */, true /* withMD5 */);
5056
5057 size_t key_size = 2048; // Need largish key for SHA-512 test.
5058 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5059 .OaepMGFDigest(digests)
5060 .Authorization(TAG_NO_AUTH_REQUIRED)
5061 .RsaEncryptionKey(key_size, 65537)
5062 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005063 .Digest(Digest::SHA_2_256)
5064 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005065
5066 string message = "Hello";
5067
5068 for (auto digest : digests) {
5069 auto params = AuthorizationSetBuilder()
5070 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, digest)
5071 .Digest(Digest::SHA_2_256)
5072 .Padding(PaddingMode::RSA_OAEP);
David Drysdale59cae642021-05-12 13:52:03 +01005073 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005074 if (HasNonfatalFailure()) std::cout << "-->" << digest << std::endl;
5075 EXPECT_EQ(key_size / 8, ciphertext1.size());
5076
David Drysdale59cae642021-05-12 13:52:03 +01005077 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005078 EXPECT_EQ(key_size / 8, ciphertext2.size());
5079
5080 // OAEP randomizes padding so every result should be different (with astronomically high
5081 // probability).
5082 EXPECT_NE(ciphertext1, ciphertext2);
5083
5084 string plaintext1 = DecryptMessage(ciphertext1, params);
5085 EXPECT_EQ(message, plaintext1) << "RSA-OAEP failed with digest " << digest;
5086 string plaintext2 = DecryptMessage(ciphertext2, params);
5087 EXPECT_EQ(message, plaintext2) << "RSA-OAEP failed with digest " << digest;
5088
5089 // Decrypting corrupted ciphertext should fail.
5090 size_t offset_to_corrupt = random() % ciphertext1.size();
5091 char corrupt_byte;
5092 do {
5093 corrupt_byte = static_cast<char>(random() % 256);
5094 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5095 ciphertext1[offset_to_corrupt] = corrupt_byte;
5096
5097 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5098 string result;
5099 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5100 EXPECT_EQ(0U, result.size());
5101 }
5102}
5103
5104/*
5105 * EncryptionOperationsTest.RsaOaepWithMGFIncompatibleDigest
5106 *
David Drysdale59cae642021-05-12 13:52:03 +01005107 * Verifies that RSA-OAEP decryption operations fail in the correct way when asked to operate
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005108 * with incompatible MGF digest.
5109 */
5110TEST_P(EncryptionOperationsTest, RsaOaepWithMGFIncompatibleDigest) {
5111 ASSERT_EQ(ErrorCode::OK,
5112 GenerateKey(AuthorizationSetBuilder()
5113 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5114 .Authorization(TAG_NO_AUTH_REQUIRED)
5115 .RsaEncryptionKey(2048, 65537)
5116 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005117 .Digest(Digest::SHA_2_256)
5118 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005119 string message = "Hello World!";
5120
5121 auto params = AuthorizationSetBuilder()
5122 .Padding(PaddingMode::RSA_OAEP)
5123 .Digest(Digest::SHA_2_256)
5124 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_224);
David Drysdale59cae642021-05-12 13:52:03 +01005125 EXPECT_EQ(ErrorCode::INCOMPATIBLE_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005126}
5127
5128/*
5129 * EncryptionOperationsTest.RsaOaepWithMGFUnsupportedDigest
5130 *
5131 * Verifies that RSA-OAEP encryption operations fail in the correct way when asked to operate
5132 * with unsupported MGF digest.
5133 */
5134TEST_P(EncryptionOperationsTest, RsaOaepWithMGFUnsupportedDigest) {
5135 ASSERT_EQ(ErrorCode::OK,
5136 GenerateKey(AuthorizationSetBuilder()
5137 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::SHA_2_256)
5138 .Authorization(TAG_NO_AUTH_REQUIRED)
5139 .RsaEncryptionKey(2048, 65537)
5140 .Padding(PaddingMode::RSA_OAEP)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005141 .Digest(Digest::SHA_2_256)
5142 .SetDefaultValidity()));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005143 string message = "Hello World!";
5144
5145 auto params = AuthorizationSetBuilder()
5146 .Padding(PaddingMode::RSA_OAEP)
5147 .Digest(Digest::SHA_2_256)
5148 .Authorization(TAG_RSA_OAEP_MGF_DIGEST, Digest::NONE);
David Drysdale59cae642021-05-12 13:52:03 +01005149 EXPECT_EQ(ErrorCode::UNSUPPORTED_MGF_DIGEST, Begin(KeyPurpose::DECRYPT, params));
Chirag Pathak8b7455a2020-12-21 18:42:52 -05005150}
5151
5152/*
Selene Huang31ab4042020-04-29 04:22:39 -07005153 * EncryptionOperationsTest.RsaPkcs1Success
5154 *
5155 * Verifies that RSA PKCS encryption/decrypts works.
5156 */
5157TEST_P(EncryptionOperationsTest, RsaPkcs1Success) {
5158 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5159 .Authorization(TAG_NO_AUTH_REQUIRED)
5160 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005161 .Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT)
5162 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005163
5164 string message = "Hello World!";
5165 auto params = AuthorizationSetBuilder().Padding(PaddingMode::RSA_PKCS1_1_5_ENCRYPT);
David Drysdale59cae642021-05-12 13:52:03 +01005166 string ciphertext1 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005167 EXPECT_EQ(2048U / 8, ciphertext1.size());
5168
David Drysdale59cae642021-05-12 13:52:03 +01005169 string ciphertext2 = LocalRsaEncryptMessage(message, params);
Selene Huang31ab4042020-04-29 04:22:39 -07005170 EXPECT_EQ(2048U / 8, ciphertext2.size());
5171
5172 // PKCS1 v1.5 randomizes padding so every result should be different.
5173 EXPECT_NE(ciphertext1, ciphertext2);
5174
5175 string plaintext = DecryptMessage(ciphertext1, params);
5176 EXPECT_EQ(message, plaintext);
5177
5178 // Decrypting corrupted ciphertext should fail.
5179 size_t offset_to_corrupt = random() % ciphertext1.size();
5180 char corrupt_byte;
5181 do {
5182 corrupt_byte = static_cast<char>(random() % 256);
5183 } while (corrupt_byte == ciphertext1[offset_to_corrupt]);
5184 ciphertext1[offset_to_corrupt] = corrupt_byte;
5185
5186 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5187 string result;
5188 EXPECT_EQ(ErrorCode::UNKNOWN_ERROR, Finish(ciphertext1, &result));
5189 EXPECT_EQ(0U, result.size());
5190}
5191
5192/*
Selene Huang31ab4042020-04-29 04:22:39 -07005193 * EncryptionOperationsTest.EcdsaEncrypt
5194 *
5195 * Verifies that attempting to use ECDSA keys to encrypt fails in the correct way.
5196 */
5197TEST_P(EncryptionOperationsTest, EcdsaEncrypt) {
5198 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5199 .Authorization(TAG_NO_AUTH_REQUIRED)
David Drysdaledf09e542021-06-08 15:46:11 +01005200 .EcdsaSigningKey(EcCurve::P_256)
Janis Danisevskis164bb872021-02-09 11:30:25 -08005201 .Digest(Digest::NONE)
5202 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07005203 auto params = AuthorizationSetBuilder().Digest(Digest::NONE);
5204 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5205 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5206}
5207
5208/*
5209 * EncryptionOperationsTest.HmacEncrypt
5210 *
5211 * Verifies that attempting to use HMAC keys to encrypt fails in the correct way.
5212 */
5213TEST_P(EncryptionOperationsTest, HmacEncrypt) {
5214 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5215 .Authorization(TAG_NO_AUTH_REQUIRED)
5216 .HmacKey(128)
5217 .Digest(Digest::SHA_2_256)
5218 .Padding(PaddingMode::NONE)
5219 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5220 auto params = AuthorizationSetBuilder()
5221 .Digest(Digest::SHA_2_256)
5222 .Padding(PaddingMode::NONE)
5223 .Authorization(TAG_MAC_LENGTH, 128);
5224 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::ENCRYPT, params));
5225 ASSERT_EQ(ErrorCode::UNSUPPORTED_PURPOSE, Begin(KeyPurpose::DECRYPT, params));
5226}
5227
5228/*
5229 * EncryptionOperationsTest.AesEcbRoundTripSuccess
5230 *
5231 * Verifies that AES ECB mode works.
5232 */
5233TEST_P(EncryptionOperationsTest, AesEcbRoundTripSuccess) {
5234 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5235 .Authorization(TAG_NO_AUTH_REQUIRED)
5236 .AesEncryptionKey(128)
5237 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5238 .Padding(PaddingMode::NONE)));
5239
5240 ASSERT_GT(key_blob_.size(), 0U);
5241 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5242
5243 // Two-block message.
5244 string message = "12345678901234567890123456789012";
5245 string ciphertext1 = EncryptMessage(message, params);
5246 EXPECT_EQ(message.size(), ciphertext1.size());
5247
5248 string ciphertext2 = EncryptMessage(string(message), params);
5249 EXPECT_EQ(message.size(), ciphertext2.size());
5250
5251 // ECB is deterministic.
5252 EXPECT_EQ(ciphertext1, ciphertext2);
5253
5254 string plaintext = DecryptMessage(ciphertext1, params);
5255 EXPECT_EQ(message, plaintext);
5256}
5257
5258/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005259 * EncryptionOperationsTest.AesEcbUnknownTag
5260 *
5261 * Verifies that AES ECB operations ignore unknown tags.
5262 */
5263TEST_P(EncryptionOperationsTest, AesEcbUnknownTag) {
5264 int32_t unknown_tag_value = ((7 << 28) /* TagType:BOOL */ | 150);
5265 Tag unknown_tag = static_cast<Tag>(unknown_tag_value);
5266 KeyParameter unknown_param;
5267 unknown_param.tag = unknown_tag;
5268
5269 vector<KeyCharacteristics> key_characteristics;
5270 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5271 .Authorization(TAG_NO_AUTH_REQUIRED)
5272 .AesEncryptionKey(128)
5273 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5274 .Padding(PaddingMode::NONE)
5275 .Authorization(unknown_param),
5276 &key_blob_, &key_characteristics));
5277 ASSERT_GT(key_blob_.size(), 0U);
5278
5279 // Unknown tags should not be returned in key characteristics.
5280 AuthorizationSet hw_enforced = HwEnforcedAuthorizations(key_characteristics);
5281 AuthorizationSet sw_enforced = SwEnforcedAuthorizations(key_characteristics);
5282 EXPECT_EQ(hw_enforced.find(unknown_tag), -1);
5283 EXPECT_EQ(sw_enforced.find(unknown_tag), -1);
5284
5285 // Encrypt without mentioning the unknown parameter.
5286 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
5287 string message = "12345678901234567890123456789012";
5288 string ciphertext = EncryptMessage(message, params);
5289 EXPECT_EQ(message.size(), ciphertext.size());
5290
5291 // Decrypt including the unknown parameter.
5292 auto decrypt_params = AuthorizationSetBuilder()
5293 .BlockMode(BlockMode::ECB)
5294 .Padding(PaddingMode::NONE)
5295 .Authorization(unknown_param);
5296 string plaintext = DecryptMessage(ciphertext, decrypt_params);
5297 EXPECT_EQ(message, plaintext);
5298}
5299
5300/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005301 * EncryptionOperationsTest.AesWrongMode
Selene Huang31ab4042020-04-29 04:22:39 -07005302 *
5303 * Verifies that AES encryption fails in the correct way when an unauthorized mode is specified.
5304 */
5305TEST_P(EncryptionOperationsTest, AesWrongMode) {
5306 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5307 .Authorization(TAG_NO_AUTH_REQUIRED)
5308 .AesEncryptionKey(128)
5309 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5310 .Padding(PaddingMode::NONE)));
Selene Huang31ab4042020-04-29 04:22:39 -07005311 ASSERT_GT(key_blob_.size(), 0U);
5312
Selene Huang31ab4042020-04-29 04:22:39 -07005313 EXPECT_EQ(
5314 ErrorCode::INCOMPATIBLE_BLOCK_MODE,
5315 Begin(KeyPurpose::ENCRYPT,
5316 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE)));
5317}
5318
5319/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005320 * EncryptionOperationsTest.AesWrongPadding
5321 *
5322 * Verifies that AES encryption fails in the correct way when an unauthorized padding is specified.
5323 */
5324TEST_P(EncryptionOperationsTest, AesWrongPadding) {
5325 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5326 .Authorization(TAG_NO_AUTH_REQUIRED)
5327 .AesEncryptionKey(128)
5328 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5329 .Padding(PaddingMode::NONE)));
5330 ASSERT_GT(key_blob_.size(), 0U);
5331
5332 EXPECT_EQ(
5333 ErrorCode::INCOMPATIBLE_PADDING_MODE,
5334 Begin(KeyPurpose::ENCRYPT,
5335 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7)));
5336}
5337
5338/*
5339 * EncryptionOperationsTest.AesInvalidParams
5340 *
5341 * Verifies that AES encryption fails in the correct way when an duplicate parameters are specified.
5342 */
5343TEST_P(EncryptionOperationsTest, AesInvalidParams) {
5344 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5345 .Authorization(TAG_NO_AUTH_REQUIRED)
5346 .AesEncryptionKey(128)
5347 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5348 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5349 .Padding(PaddingMode::NONE)
5350 .Padding(PaddingMode::PKCS7)));
5351 ASSERT_GT(key_blob_.size(), 0U);
5352
5353 auto result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5354 .BlockMode(BlockMode::CBC)
5355 .BlockMode(BlockMode::ECB)
5356 .Padding(PaddingMode::NONE));
5357 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_BLOCK_MODE ||
5358 result == ErrorCode::UNSUPPORTED_BLOCK_MODE);
5359
5360 result = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5361 .BlockMode(BlockMode::ECB)
5362 .Padding(PaddingMode::NONE)
5363 .Padding(PaddingMode::PKCS7));
5364 EXPECT_TRUE(result == ErrorCode::INCOMPATIBLE_PADDING_MODE ||
5365 result == ErrorCode::UNSUPPORTED_PADDING_MODE);
5366}
5367
5368/*
Selene Huang31ab4042020-04-29 04:22:39 -07005369 * EncryptionOperationsTest.AesWrongPurpose
5370 *
5371 * Verifies that AES encryption fails in the correct way when an unauthorized purpose is
5372 * specified.
5373 */
5374TEST_P(EncryptionOperationsTest, AesWrongPurpose) {
5375 auto err = GenerateKey(AuthorizationSetBuilder()
5376 .Authorization(TAG_NO_AUTH_REQUIRED)
5377 .AesKey(128)
5378 .Authorization(TAG_PURPOSE, KeyPurpose::ENCRYPT)
5379 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5380 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5381 .Padding(PaddingMode::NONE));
5382 ASSERT_EQ(ErrorCode::OK, err) << "Got " << err;
5383 ASSERT_GT(key_blob_.size(), 0U);
5384
5385 err = Begin(KeyPurpose::DECRYPT, AuthorizationSetBuilder()
5386 .BlockMode(BlockMode::GCM)
5387 .Padding(PaddingMode::NONE)
5388 .Authorization(TAG_MAC_LENGTH, 128));
5389 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5390
5391 CheckedDeleteKey();
5392
5393 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5394 .Authorization(TAG_NO_AUTH_REQUIRED)
5395 .AesKey(128)
5396 .Authorization(TAG_PURPOSE, KeyPurpose::DECRYPT)
5397 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5398 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5399 .Padding(PaddingMode::NONE)));
5400
5401 err = Begin(KeyPurpose::ENCRYPT, AuthorizationSetBuilder()
5402 .BlockMode(BlockMode::GCM)
5403 .Padding(PaddingMode::NONE)
5404 .Authorization(TAG_MAC_LENGTH, 128));
5405 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PURPOSE, err) << "Got " << err;
5406}
5407
5408/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005409 * EncryptionOperationsTest.AesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07005410 *
5411 * Verifies that AES encryption fails in the correct way when provided an input that is not a
5412 * multiple of the block size and no padding is specified.
5413 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01005414TEST_P(EncryptionOperationsTest, AesEcbCbcNoPaddingWrongInputSize) {
5415 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
5416 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5417 .Authorization(TAG_NO_AUTH_REQUIRED)
5418 .AesEncryptionKey(128)
5419 .Authorization(TAG_BLOCK_MODE, blockMode)
5420 .Padding(PaddingMode::NONE)));
5421 // Message is slightly shorter than two blocks.
5422 string message(16 * 2 - 1, 'a');
Selene Huang31ab4042020-04-29 04:22:39 -07005423
David Drysdaled2cc8c22021-04-15 13:29:45 +01005424 auto params = AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
5425 AuthorizationSet out_params;
5426 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5427 string ciphertext;
5428 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, &ciphertext));
5429 EXPECT_EQ(0U, ciphertext.size());
5430
5431 CheckedDeleteKey();
5432 }
Selene Huang31ab4042020-04-29 04:22:39 -07005433}
5434
5435/*
5436 * EncryptionOperationsTest.AesEcbPkcs7Padding
5437 *
5438 * Verifies that AES PKCS7 padding works for any message length.
5439 */
5440TEST_P(EncryptionOperationsTest, AesEcbPkcs7Padding) {
5441 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5442 .Authorization(TAG_NO_AUTH_REQUIRED)
5443 .AesEncryptionKey(128)
5444 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5445 .Padding(PaddingMode::PKCS7)));
5446
5447 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5448
5449 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08005450 for (size_t i = 0; i <= 48; i++) {
5451 SCOPED_TRACE(testing::Message() << "i = " << i);
5452 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character.
5453 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07005454 string ciphertext = EncryptMessage(message, params);
5455 EXPECT_EQ(i + 16 - (i % 16), ciphertext.size());
5456 string plaintext = DecryptMessage(ciphertext, params);
5457 EXPECT_EQ(message, plaintext);
5458 }
5459}
5460
5461/*
5462 * EncryptionOperationsTest.AesEcbWrongPadding
5463 *
5464 * Verifies that AES enryption fails in the correct way when an unauthorized padding mode is
5465 * specified.
5466 */
5467TEST_P(EncryptionOperationsTest, AesEcbWrongPadding) {
5468 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5469 .Authorization(TAG_NO_AUTH_REQUIRED)
5470 .AesEncryptionKey(128)
5471 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5472 .Padding(PaddingMode::NONE)));
5473
5474 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5475
5476 // Try various message lengths; all should fail
Brian J Murray734c8412022-01-13 14:55:30 -08005477 for (size_t i = 0; i <= 48; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07005478 string message(i, 'a');
5479 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5480 }
5481}
5482
5483/*
5484 * EncryptionOperationsTest.AesEcbPkcs7PaddingCorrupted
5485 *
5486 * Verifies that AES decryption fails in the correct way when the padding is corrupted.
5487 */
5488TEST_P(EncryptionOperationsTest, AesEcbPkcs7PaddingCorrupted) {
5489 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5490 .Authorization(TAG_NO_AUTH_REQUIRED)
5491 .AesEncryptionKey(128)
5492 .Authorization(TAG_BLOCK_MODE, BlockMode::ECB)
5493 .Padding(PaddingMode::PKCS7)));
5494
5495 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
5496
5497 string message = "a";
5498 string ciphertext = EncryptMessage(message, params);
5499 EXPECT_EQ(16U, ciphertext.size());
5500 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07005501
Seth Moore7a55ae32021-06-23 14:28:11 -07005502 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
5503 ++ciphertext[ciphertext.size() / 2];
5504
5505 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
5506 string plaintext;
5507 ErrorCode error = Finish(message, &plaintext);
5508 if (error == ErrorCode::INVALID_INPUT_LENGTH) {
5509 // This is the expected error, we can exit the test now.
5510 return;
5511 } else {
5512 // Very small chance we got valid decryption, so try again.
5513 ASSERT_EQ(error, ErrorCode::OK);
5514 }
5515 }
5516 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07005517}
5518
5519vector<uint8_t> CopyIv(const AuthorizationSet& set) {
5520 auto iv = set.GetTagValue(TAG_NONCE);
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005521 EXPECT_TRUE(iv);
5522 return iv->get();
Selene Huang31ab4042020-04-29 04:22:39 -07005523}
5524
5525/*
5526 * EncryptionOperationsTest.AesCtrRoundTripSuccess
5527 *
5528 * Verifies that AES CTR mode works.
5529 */
5530TEST_P(EncryptionOperationsTest, AesCtrRoundTripSuccess) {
5531 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5532 .Authorization(TAG_NO_AUTH_REQUIRED)
5533 .AesEncryptionKey(128)
5534 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5535 .Padding(PaddingMode::NONE)));
5536
5537 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5538
5539 string message = "123";
5540 AuthorizationSet out_params;
5541 string ciphertext1 = EncryptMessage(message, params, &out_params);
5542 vector<uint8_t> iv1 = CopyIv(out_params);
5543 EXPECT_EQ(16U, iv1.size());
5544
5545 EXPECT_EQ(message.size(), ciphertext1.size());
5546
5547 out_params.Clear();
5548 string ciphertext2 = EncryptMessage(message, params, &out_params);
5549 vector<uint8_t> iv2 = CopyIv(out_params);
5550 EXPECT_EQ(16U, iv2.size());
5551
5552 // IVs should be random, so ciphertexts should differ.
5553 EXPECT_NE(ciphertext1, ciphertext2);
5554
5555 auto params_iv1 =
5556 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv1);
5557 auto params_iv2 =
5558 AuthorizationSetBuilder().Authorizations(params).Authorization(TAG_NONCE, iv2);
5559
5560 string plaintext = DecryptMessage(ciphertext1, params_iv1);
5561 EXPECT_EQ(message, plaintext);
5562 plaintext = DecryptMessage(ciphertext2, params_iv2);
5563 EXPECT_EQ(message, plaintext);
5564
5565 // Using the wrong IV will result in a "valid" decryption, but the data will be garbage.
5566 plaintext = DecryptMessage(ciphertext1, params_iv2);
5567 EXPECT_NE(message, plaintext);
5568 plaintext = DecryptMessage(ciphertext2, params_iv1);
5569 EXPECT_NE(message, plaintext);
5570}
5571
5572/*
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305573 * EncryptionOperationsTest.AesEcbIncremental
Selene Huang31ab4042020-04-29 04:22:39 -07005574 *
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305575 * Verifies that AES works for ECB block mode, when provided data in various size increments.
Selene Huang31ab4042020-04-29 04:22:39 -07005576 */
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305577TEST_P(EncryptionOperationsTest, AesEcbIncremental) {
5578 CheckAesIncrementalEncryptOperation(BlockMode::ECB, 240);
5579}
Selene Huang31ab4042020-04-29 04:22:39 -07005580
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305581/*
5582 * EncryptionOperationsTest.AesCbcIncremental
5583 *
5584 * Verifies that AES works for CBC block mode, when provided data in various size increments.
5585 */
5586TEST_P(EncryptionOperationsTest, AesCbcIncremental) {
5587 CheckAesIncrementalEncryptOperation(BlockMode::CBC, 240);
5588}
Selene Huang31ab4042020-04-29 04:22:39 -07005589
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305590/*
5591 * EncryptionOperationsTest.AesCtrIncremental
5592 *
5593 * Verifies that AES works for CTR block mode, when provided data in various size increments.
5594 */
5595TEST_P(EncryptionOperationsTest, AesCtrIncremental) {
5596 CheckAesIncrementalEncryptOperation(BlockMode::CTR, 240);
5597}
Selene Huang31ab4042020-04-29 04:22:39 -07005598
anil.hiranniah19a4ca12022-03-03 17:39:30 +05305599/*
5600 * EncryptionOperationsTest.AesGcmIncremental
5601 *
5602 * Verifies that AES works for GCM block mode, when provided data in various size increments.
5603 */
5604TEST_P(EncryptionOperationsTest, AesGcmIncremental) {
5605 CheckAesIncrementalEncryptOperation(BlockMode::GCM, 240);
Selene Huang31ab4042020-04-29 04:22:39 -07005606}
5607
5608struct AesCtrSp80038aTestVector {
5609 const char* key;
5610 const char* nonce;
5611 const char* plaintext;
5612 const char* ciphertext;
5613};
5614
5615// These test vectors are taken from
5616// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section F.5.
5617static const AesCtrSp80038aTestVector kAesCtrSp80038aTestVectors[] = {
5618 // AES-128
5619 {
5620 "2b7e151628aed2a6abf7158809cf4f3c",
5621 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5622 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5623 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5624 "874d6191b620e3261bef6864990db6ce9806f66b7970fdff8617187bb9fffdff"
5625 "5ae4df3edbd5d35e5b4f09020db03eab1e031dda2fbe03d1792170a0f3009cee",
5626 },
5627 // AES-192
5628 {
5629 "8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b",
5630 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5631 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5632 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5633 "1abc932417521ca24f2b0459fe7e6e0b090339ec0aa6faefd5ccc2c6f4ce8e94"
5634 "1e36b26bd1ebc670d1bd1d665620abf74f78a7f6d29809585a97daec58c6b050",
5635 },
5636 // AES-256
5637 {
5638 "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4",
5639 "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff",
5640 "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e51"
5641 "30c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710",
5642 "601ec313775789a5b7a7f504bbf3d228f443e3ca4d62b59aca84e990cacaf5c5"
5643 "2b0930daa23de94ce87017ba2d84988ddfc9c58db67aada613c2dd08457941a6",
5644 },
5645};
5646
5647/*
5648 * EncryptionOperationsTest.AesCtrSp80038aTestVector
5649 *
5650 * Verifies AES CTR implementation against SP800-38A test vectors.
5651 */
5652TEST_P(EncryptionOperationsTest, AesCtrSp80038aTestVector) {
5653 std::vector<uint32_t> InvalidSizes = InvalidKeySizes(Algorithm::AES);
5654 for (size_t i = 0; i < 3; i++) {
5655 const AesCtrSp80038aTestVector& test(kAesCtrSp80038aTestVectors[i]);
5656 const string key = hex2str(test.key);
5657 if (std::find(InvalidSizes.begin(), InvalidSizes.end(), (key.size() * 8)) !=
5658 InvalidSizes.end())
5659 continue;
5660 const string nonce = hex2str(test.nonce);
5661 const string plaintext = hex2str(test.plaintext);
5662 const string ciphertext = hex2str(test.ciphertext);
5663 CheckAesCtrTestVector(key, nonce, plaintext, ciphertext);
5664 }
5665}
5666
5667/*
5668 * EncryptionOperationsTest.AesCtrIncompatiblePaddingMode
5669 *
5670 * Verifies that keymint rejects use of CTR mode with PKCS7 padding in the correct way.
5671 */
5672TEST_P(EncryptionOperationsTest, AesCtrIncompatiblePaddingMode) {
5673 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5674 .Authorization(TAG_NO_AUTH_REQUIRED)
5675 .AesEncryptionKey(128)
5676 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5677 .Padding(PaddingMode::PKCS7)));
5678 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CTR).Padding(PaddingMode::NONE);
5679 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, params));
5680}
5681
5682/*
5683 * EncryptionOperationsTest.AesCtrInvalidCallerNonce
5684 *
5685 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5686 */
5687TEST_P(EncryptionOperationsTest, AesCtrInvalidCallerNonce) {
5688 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5689 .Authorization(TAG_NO_AUTH_REQUIRED)
5690 .AesEncryptionKey(128)
5691 .Authorization(TAG_BLOCK_MODE, BlockMode::CTR)
5692 .Authorization(TAG_CALLER_NONCE)
5693 .Padding(PaddingMode::NONE)));
5694
5695 auto params = AuthorizationSetBuilder()
5696 .BlockMode(BlockMode::CTR)
5697 .Padding(PaddingMode::NONE)
5698 .Authorization(TAG_NONCE, AidlBuf(string(1, 'a')));
5699 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5700
5701 params = AuthorizationSetBuilder()
5702 .BlockMode(BlockMode::CTR)
5703 .Padding(PaddingMode::NONE)
5704 .Authorization(TAG_NONCE, AidlBuf(string(15, 'a')));
5705 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5706
5707 params = AuthorizationSetBuilder()
5708 .BlockMode(BlockMode::CTR)
5709 .Padding(PaddingMode::NONE)
5710 .Authorization(TAG_NONCE, AidlBuf(string(17, 'a')));
5711 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
5712}
5713
5714/*
David Drysdale7de9feb2021-03-05 14:56:19 +00005715 * EncryptionOperationsTest.AesCbcRoundTripSuccess
Selene Huang31ab4042020-04-29 04:22:39 -07005716 *
5717 * Verifies that keymint fails correctly when the user supplies an incorrect-size nonce.
5718 */
5719TEST_P(EncryptionOperationsTest, AesCbcRoundTripSuccess) {
5720 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5721 .Authorization(TAG_NO_AUTH_REQUIRED)
5722 .AesEncryptionKey(128)
5723 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5724 .Padding(PaddingMode::NONE)));
5725 // Two-block message.
5726 string message = "12345678901234567890123456789012";
5727 auto params = AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5728 AuthorizationSet out_params;
5729 string ciphertext1 = EncryptMessage(message, params, &out_params);
5730 vector<uint8_t> iv1 = CopyIv(out_params);
5731 EXPECT_EQ(message.size(), ciphertext1.size());
5732
5733 out_params.Clear();
5734
5735 string ciphertext2 = EncryptMessage(message, params, &out_params);
5736 vector<uint8_t> iv2 = CopyIv(out_params);
5737 EXPECT_EQ(message.size(), ciphertext2.size());
5738
5739 // IVs should be random, so ciphertexts should differ.
5740 EXPECT_NE(ciphertext1, ciphertext2);
5741
5742 params.push_back(TAG_NONCE, iv1);
5743 string plaintext = DecryptMessage(ciphertext1, params);
5744 EXPECT_EQ(message, plaintext);
5745}
5746
5747/*
5748 * EncryptionOperationsTest.AesCallerNonce
5749 *
5750 * Verifies that AES caller-provided nonces work correctly.
5751 */
5752TEST_P(EncryptionOperationsTest, AesCallerNonce) {
5753 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5754 .Authorization(TAG_NO_AUTH_REQUIRED)
5755 .AesEncryptionKey(128)
5756 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5757 .Authorization(TAG_CALLER_NONCE)
5758 .Padding(PaddingMode::NONE)));
5759
5760 string message = "12345678901234567890123456789012";
5761
5762 // Don't specify nonce, should get a random one.
5763 AuthorizationSetBuilder params =
5764 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5765 AuthorizationSet out_params;
5766 string ciphertext = EncryptMessage(message, params, &out_params);
5767 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005768 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005769
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005770 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005771 string plaintext = DecryptMessage(ciphertext, params);
5772 EXPECT_EQ(message, plaintext);
5773
5774 // Now specify a nonce, should also work.
5775 params = AuthorizationSetBuilder()
5776 .BlockMode(BlockMode::CBC)
5777 .Padding(PaddingMode::NONE)
5778 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5779 out_params.Clear();
5780 ciphertext = EncryptMessage(message, params, &out_params);
5781
5782 // Decrypt with correct nonce.
5783 plaintext = DecryptMessage(ciphertext, params);
5784 EXPECT_EQ(message, plaintext);
5785
5786 // Try with wrong nonce.
5787 params = AuthorizationSetBuilder()
5788 .BlockMode(BlockMode::CBC)
5789 .Padding(PaddingMode::NONE)
5790 .Authorization(TAG_NONCE, AidlBuf("aaaaaaaaaaaaaaaa"));
5791 plaintext = DecryptMessage(ciphertext, params);
5792 EXPECT_NE(message, plaintext);
5793}
5794
5795/*
5796 * EncryptionOperationsTest.AesCallerNonceProhibited
5797 *
5798 * Verifies that caller-provided nonces are not permitted when not specified in the key
5799 * authorizations.
5800 */
5801TEST_P(EncryptionOperationsTest, AesCallerNonceProhibited) {
5802 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5803 .Authorization(TAG_NO_AUTH_REQUIRED)
5804 .AesEncryptionKey(128)
5805 .Authorization(TAG_BLOCK_MODE, BlockMode::CBC)
5806 .Padding(PaddingMode::NONE)));
5807
5808 string message = "12345678901234567890123456789012";
5809
5810 // Don't specify nonce, should get a random one.
5811 AuthorizationSetBuilder params =
5812 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
5813 AuthorizationSet out_params;
5814 string ciphertext = EncryptMessage(message, params, &out_params);
5815 EXPECT_EQ(message.size(), ciphertext.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005816 EXPECT_EQ(16U, out_params.GetTagValue(TAG_NONCE)->get().size());
Selene Huang31ab4042020-04-29 04:22:39 -07005817
Janis Danisevskis5ba09332020-12-17 10:05:15 -08005818 params.push_back(TAG_NONCE, out_params.GetTagValue(TAG_NONCE)->get());
Selene Huang31ab4042020-04-29 04:22:39 -07005819 string plaintext = DecryptMessage(ciphertext, params);
5820 EXPECT_EQ(message, plaintext);
5821
5822 // Now specify a nonce, should fail
5823 params = AuthorizationSetBuilder()
5824 .BlockMode(BlockMode::CBC)
5825 .Padding(PaddingMode::NONE)
5826 .Authorization(TAG_NONCE, AidlBuf("abcdefghijklmnop"));
5827 out_params.Clear();
5828 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED, Begin(KeyPurpose::ENCRYPT, params, &out_params));
5829}
5830
5831/*
5832 * EncryptionOperationsTest.AesGcmRoundTripSuccess
5833 *
5834 * Verifies that AES GCM mode works.
5835 */
5836TEST_P(EncryptionOperationsTest, AesGcmRoundTripSuccess) {
5837 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5838 .Authorization(TAG_NO_AUTH_REQUIRED)
5839 .AesEncryptionKey(128)
5840 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5841 .Padding(PaddingMode::NONE)
5842 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5843
5844 string aad = "foobar";
5845 string message = "123456789012345678901234567890123456";
5846
5847 auto begin_params = AuthorizationSetBuilder()
5848 .BlockMode(BlockMode::GCM)
5849 .Padding(PaddingMode::NONE)
5850 .Authorization(TAG_MAC_LENGTH, 128);
5851
Selene Huang31ab4042020-04-29 04:22:39 -07005852 // Encrypt
5853 AuthorizationSet begin_out_params;
5854 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5855 << "Begin encrypt";
5856 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005857 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
5858 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005859 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5860
5861 // Grab nonce
5862 begin_params.push_back(begin_out_params);
5863
5864 // Decrypt.
5865 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
Shawn Willden92d79c02021-02-19 07:31:55 -07005866 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005867 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005868 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005869 EXPECT_EQ(message.length(), plaintext.length());
5870 EXPECT_EQ(message, plaintext);
5871}
5872
5873/*
5874 * EncryptionOperationsTest.AesGcmRoundTripWithDelaySuccess
5875 *
5876 * Verifies that AES GCM mode works, even when there's a long delay
5877 * between operations.
5878 */
5879TEST_P(EncryptionOperationsTest, AesGcmRoundTripWithDelaySuccess) {
5880 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5881 .Authorization(TAG_NO_AUTH_REQUIRED)
5882 .AesEncryptionKey(128)
5883 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5884 .Padding(PaddingMode::NONE)
5885 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5886
5887 string aad = "foobar";
5888 string message = "123456789012345678901234567890123456";
5889
5890 auto begin_params = AuthorizationSetBuilder()
5891 .BlockMode(BlockMode::GCM)
5892 .Padding(PaddingMode::NONE)
5893 .Authorization(TAG_MAC_LENGTH, 128);
5894
Selene Huang31ab4042020-04-29 04:22:39 -07005895 // Encrypt
5896 AuthorizationSet begin_out_params;
5897 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params))
5898 << "Begin encrypt";
5899 string ciphertext;
5900 AuthorizationSet update_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07005901 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005902 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005903 ASSERT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07005904
5905 ASSERT_EQ(ciphertext.length(), message.length() + 16);
5906
5907 // Grab nonce
5908 begin_params.push_back(begin_out_params);
5909
5910 // Decrypt.
5911 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params)) << "Begin decrypt";
5912 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07005913 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07005914 sleep(5);
Shawn Willden92d79c02021-02-19 07:31:55 -07005915 ASSERT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07005916 sleep(5);
5917 EXPECT_EQ(ErrorCode::OK, Finish("", &plaintext));
5918 EXPECT_EQ(message.length(), plaintext.length());
5919 EXPECT_EQ(message, plaintext);
5920}
5921
5922/*
5923 * EncryptionOperationsTest.AesGcmDifferentNonces
5924 *
5925 * Verifies that encrypting the same data with different nonces produces different outputs.
5926 */
5927TEST_P(EncryptionOperationsTest, AesGcmDifferentNonces) {
5928 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5929 .Authorization(TAG_NO_AUTH_REQUIRED)
5930 .AesEncryptionKey(128)
5931 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5932 .Padding(PaddingMode::NONE)
5933 .Authorization(TAG_MIN_MAC_LENGTH, 128)
5934 .Authorization(TAG_CALLER_NONCE)));
5935
5936 string aad = "foobar";
5937 string message = "123456789012345678901234567890123456";
5938 string nonce1 = "000000000000";
5939 string nonce2 = "111111111111";
5940 string nonce3 = "222222222222";
5941
5942 string ciphertext1 =
5943 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce1));
5944 string ciphertext2 =
5945 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce2));
5946 string ciphertext3 =
5947 EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128, AidlBuf(nonce3));
5948
5949 ASSERT_NE(ciphertext1, ciphertext2);
5950 ASSERT_NE(ciphertext1, ciphertext3);
5951 ASSERT_NE(ciphertext2, ciphertext3);
5952}
5953
5954/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01005955 * EncryptionOperationsTest.AesGcmDifferentAutoNonces
5956 *
5957 * Verifies that encrypting the same data with KeyMint generated nonces produces different outputs.
5958 */
5959TEST_P(EncryptionOperationsTest, AesGcmDifferentAutoNonces) {
5960 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5961 .Authorization(TAG_NO_AUTH_REQUIRED)
5962 .AesEncryptionKey(128)
5963 .Authorization(TAG_BLOCK_MODE, BlockMode::GCM)
5964 .Padding(PaddingMode::NONE)
5965 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5966
5967 string aad = "foobar";
5968 string message = "123456789012345678901234567890123456";
5969
5970 string ciphertext1 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5971 string ciphertext2 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5972 string ciphertext3 = EncryptMessage(message, BlockMode::GCM, PaddingMode::NONE, 128);
5973
5974 ASSERT_NE(ciphertext1, ciphertext2);
5975 ASSERT_NE(ciphertext1, ciphertext3);
5976 ASSERT_NE(ciphertext2, ciphertext3);
5977}
5978
5979/*
Selene Huang31ab4042020-04-29 04:22:39 -07005980 * EncryptionOperationsTest.AesGcmTooShortTag
5981 *
5982 * Verifies that AES GCM mode fails correctly when a too-short tag length is specified.
5983 */
5984TEST_P(EncryptionOperationsTest, AesGcmTooShortTag) {
5985 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
5986 .Authorization(TAG_NO_AUTH_REQUIRED)
5987 .AesEncryptionKey(128)
5988 .BlockMode(BlockMode::GCM)
5989 .Padding(PaddingMode::NONE)
5990 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
5991 string message = "123456789012345678901234567890123456";
5992 auto params = AuthorizationSetBuilder()
5993 .BlockMode(BlockMode::GCM)
5994 .Padding(PaddingMode::NONE)
5995 .Authorization(TAG_MAC_LENGTH, 96);
5996
5997 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::ENCRYPT, params));
5998}
5999
6000/*
6001 * EncryptionOperationsTest.AesGcmTooShortTagOnDecrypt
6002 *
6003 * Verifies that AES GCM mode fails correctly when a too-short tag is provided to decryption.
6004 */
6005TEST_P(EncryptionOperationsTest, AesGcmTooShortTagOnDecrypt) {
6006 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6007 .Authorization(TAG_NO_AUTH_REQUIRED)
6008 .AesEncryptionKey(128)
6009 .BlockMode(BlockMode::GCM)
6010 .Padding(PaddingMode::NONE)
6011 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6012 string aad = "foobar";
6013 string message = "123456789012345678901234567890123456";
6014 auto params = AuthorizationSetBuilder()
6015 .BlockMode(BlockMode::GCM)
6016 .Padding(PaddingMode::NONE)
6017 .Authorization(TAG_MAC_LENGTH, 128);
6018
Selene Huang31ab4042020-04-29 04:22:39 -07006019 // Encrypt
6020 AuthorizationSet begin_out_params;
6021 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6022 EXPECT_EQ(1U, begin_out_params.size());
Janis Danisevskis5ba09332020-12-17 10:05:15 -08006023 ASSERT_TRUE(begin_out_params.GetTagValue(TAG_NONCE));
Selene Huang31ab4042020-04-29 04:22:39 -07006024
6025 AuthorizationSet finish_out_params;
6026 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006027 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6028 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006029
6030 params = AuthorizationSetBuilder()
6031 .Authorizations(begin_out_params)
6032 .BlockMode(BlockMode::GCM)
6033 .Padding(PaddingMode::NONE)
6034 .Authorization(TAG_MAC_LENGTH, 96);
6035
6036 // Decrypt.
6037 EXPECT_EQ(ErrorCode::INVALID_MAC_LENGTH, Begin(KeyPurpose::DECRYPT, params));
6038}
6039
6040/*
6041 * EncryptionOperationsTest.AesGcmCorruptKey
6042 *
6043 * Verifies that AES GCM mode fails correctly when the decryption key is incorrect.
6044 */
6045TEST_P(EncryptionOperationsTest, AesGcmCorruptKey) {
6046 const uint8_t nonce_bytes[] = {
6047 0xb7, 0x94, 0x37, 0xae, 0x08, 0xff, 0x35, 0x5d, 0x7d, 0x8a, 0x4d, 0x0f,
6048 };
6049 string nonce = make_string(nonce_bytes);
6050 const uint8_t ciphertext_bytes[] = {
6051 0xb3, 0xf6, 0x79, 0x9e, 0x8f, 0x93, 0x26, 0xf2, 0xdf, 0x1e, 0x80, 0xfc,
6052 0xd2, 0xcb, 0x16, 0xd7, 0x8c, 0x9d, 0xc7, 0xcc, 0x14, 0xbb, 0x67, 0x78,
6053 0x62, 0xdc, 0x6c, 0x63, 0x9b, 0x3a, 0x63, 0x38, 0xd2, 0x4b, 0x31, 0x2d,
6054 0x39, 0x89, 0xe5, 0x92, 0x0b, 0x5d, 0xbf, 0xc9, 0x76, 0x76, 0x5e, 0xfb,
6055 0xfe, 0x57, 0xbb, 0x38, 0x59, 0x40, 0xa7, 0xa4, 0x3b, 0xdf, 0x05, 0xbd,
6056 0xda, 0xe3, 0xc9, 0xd6, 0xa2, 0xfb, 0xbd, 0xfc, 0xc0, 0xcb, 0xa0,
6057 };
6058 string ciphertext = make_string(ciphertext_bytes);
6059
6060 auto params = AuthorizationSetBuilder()
6061 .BlockMode(BlockMode::GCM)
6062 .Padding(PaddingMode::NONE)
6063 .Authorization(TAG_MAC_LENGTH, 128)
6064 .Authorization(TAG_NONCE, nonce.data(), nonce.size());
6065
6066 auto import_params = AuthorizationSetBuilder()
6067 .Authorization(TAG_NO_AUTH_REQUIRED)
6068 .AesEncryptionKey(128)
6069 .BlockMode(BlockMode::GCM)
6070 .Padding(PaddingMode::NONE)
6071 .Authorization(TAG_CALLER_NONCE)
6072 .Authorization(TAG_MIN_MAC_LENGTH, 128);
6073
6074 // Import correct key and decrypt
6075 const uint8_t key_bytes[] = {
6076 0xba, 0x76, 0x35, 0x4f, 0x0a, 0xed, 0x6e, 0x8d,
6077 0x91, 0xf4, 0x5c, 0x4f, 0xf5, 0xa0, 0x62, 0xdb,
6078 };
6079 string key = make_string(key_bytes);
6080 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6081 string plaintext = DecryptMessage(ciphertext, params);
6082 CheckedDeleteKey();
6083
6084 // Corrupt key and attempt to decrypt
6085 key[0] = 0;
6086 ASSERT_EQ(ErrorCode::OK, ImportKey(import_params, KeyFormat::RAW, key));
6087 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
6088 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
6089 CheckedDeleteKey();
6090}
6091
6092/*
6093 * EncryptionOperationsTest.AesGcmAadNoData
6094 *
6095 * Verifies that AES GCM mode works when provided additional authenticated data, but no data to
6096 * encrypt.
6097 */
6098TEST_P(EncryptionOperationsTest, AesGcmAadNoData) {
6099 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6100 .Authorization(TAG_NO_AUTH_REQUIRED)
6101 .AesEncryptionKey(128)
6102 .BlockMode(BlockMode::GCM)
6103 .Padding(PaddingMode::NONE)
6104 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6105
6106 string aad = "1234567890123456";
6107 auto params = AuthorizationSetBuilder()
6108 .BlockMode(BlockMode::GCM)
6109 .Padding(PaddingMode::NONE)
6110 .Authorization(TAG_MAC_LENGTH, 128);
6111
Selene Huang31ab4042020-04-29 04:22:39 -07006112 // Encrypt
6113 AuthorizationSet begin_out_params;
6114 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
6115 string ciphertext;
6116 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006117 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
6118 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006119 EXPECT_TRUE(finish_out_params.empty());
6120
6121 // Grab nonce
6122 params.push_back(begin_out_params);
6123
6124 // Decrypt.
6125 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006126 ASSERT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006127 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006128 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006129
6130 EXPECT_TRUE(finish_out_params.empty());
6131
6132 EXPECT_EQ("", plaintext);
6133}
6134
6135/*
6136 * EncryptionOperationsTest.AesGcmMultiPartAad
6137 *
6138 * Verifies that AES GCM mode works when provided additional authenticated data in multiple
6139 * chunks.
6140 */
6141TEST_P(EncryptionOperationsTest, AesGcmMultiPartAad) {
6142 const size_t tag_bits = 128;
6143 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6144 .Authorization(TAG_NO_AUTH_REQUIRED)
6145 .AesEncryptionKey(128)
6146 .BlockMode(BlockMode::GCM)
6147 .Padding(PaddingMode::NONE)
6148 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6149
6150 string message = "123456789012345678901234567890123456";
6151 auto begin_params = AuthorizationSetBuilder()
6152 .BlockMode(BlockMode::GCM)
6153 .Padding(PaddingMode::NONE)
6154 .Authorization(TAG_MAC_LENGTH, tag_bits);
6155 AuthorizationSet begin_out_params;
6156
Selene Huang31ab4042020-04-29 04:22:39 -07006157 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6158
6159 // No data, AAD only.
Shawn Willden92d79c02021-02-19 07:31:55 -07006160 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
6161 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006162 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006163 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6164 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006165
Selene Huang31ab4042020-04-29 04:22:39 -07006166 // Expect 128-bit (16-byte) tag appended to ciphertext.
Shawn Willden92d79c02021-02-19 07:31:55 -07006167 EXPECT_EQ(message.size() + (tag_bits / 8), ciphertext.size());
Selene Huang31ab4042020-04-29 04:22:39 -07006168
6169 // Grab nonce.
6170 begin_params.push_back(begin_out_params);
6171
6172 // Decrypt
Selene Huang31ab4042020-04-29 04:22:39 -07006173 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006174 EXPECT_EQ(ErrorCode::OK, UpdateAad("foofoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006175 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006176 EXPECT_EQ(ErrorCode::OK, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006177 EXPECT_EQ(message, plaintext);
6178}
6179
6180/*
6181 * EncryptionOperationsTest.AesGcmAadOutOfOrder
6182 *
6183 * Verifies that AES GCM mode fails correctly when given AAD after data to encipher.
6184 */
6185TEST_P(EncryptionOperationsTest, AesGcmAadOutOfOrder) {
6186 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6187 .Authorization(TAG_NO_AUTH_REQUIRED)
6188 .AesEncryptionKey(128)
6189 .BlockMode(BlockMode::GCM)
6190 .Padding(PaddingMode::NONE)
6191 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6192
6193 string message = "123456789012345678901234567890123456";
6194 auto begin_params = AuthorizationSetBuilder()
6195 .BlockMode(BlockMode::GCM)
6196 .Padding(PaddingMode::NONE)
6197 .Authorization(TAG_MAC_LENGTH, 128);
6198 AuthorizationSet begin_out_params;
6199
Selene Huang31ab4042020-04-29 04:22:39 -07006200 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
6201
Shawn Willden92d79c02021-02-19 07:31:55 -07006202 EXPECT_EQ(ErrorCode::OK, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006203 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006204 EXPECT_EQ(ErrorCode::OK, Update(message, &ciphertext));
6205 EXPECT_EQ(ErrorCode::INVALID_TAG, UpdateAad("foo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006206
David Drysdaled2cc8c22021-04-15 13:29:45 +01006207 // The failure should have already cancelled the operation.
6208 EXPECT_EQ(ErrorCode::INVALID_OPERATION_HANDLE, Abort());
6209
Shawn Willden92d79c02021-02-19 07:31:55 -07006210 op_ = {};
Selene Huang31ab4042020-04-29 04:22:39 -07006211}
6212
6213/*
6214 * EncryptionOperationsTest.AesGcmBadAad
6215 *
6216 * Verifies that AES GCM decryption fails correctly when additional authenticated date is wrong.
6217 */
6218TEST_P(EncryptionOperationsTest, AesGcmBadAad) {
6219 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6220 .Authorization(TAG_NO_AUTH_REQUIRED)
6221 .AesEncryptionKey(128)
6222 .BlockMode(BlockMode::GCM)
6223 .Padding(PaddingMode::NONE)
6224 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6225
6226 string message = "12345678901234567890123456789012";
6227 auto begin_params = AuthorizationSetBuilder()
6228 .BlockMode(BlockMode::GCM)
6229 .Padding(PaddingMode::NONE)
6230 .Authorization(TAG_MAC_LENGTH, 128);
6231
Selene Huang31ab4042020-04-29 04:22:39 -07006232 // Encrypt
6233 AuthorizationSet begin_out_params;
6234 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006235 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006236 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006237 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006238
6239 // Grab nonce
6240 begin_params.push_back(begin_out_params);
6241
Selene Huang31ab4042020-04-29 04:22:39 -07006242 // Decrypt.
6243 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006244 EXPECT_EQ(ErrorCode::OK, UpdateAad("barfoo"));
Selene Huang31ab4042020-04-29 04:22:39 -07006245 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006246 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006247}
6248
6249/*
6250 * EncryptionOperationsTest.AesGcmWrongNonce
6251 *
6252 * Verifies that AES GCM decryption fails correctly when the nonce is incorrect.
6253 */
6254TEST_P(EncryptionOperationsTest, AesGcmWrongNonce) {
6255 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6256 .Authorization(TAG_NO_AUTH_REQUIRED)
6257 .AesEncryptionKey(128)
6258 .BlockMode(BlockMode::GCM)
6259 .Padding(PaddingMode::NONE)
6260 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6261
6262 string message = "12345678901234567890123456789012";
6263 auto begin_params = AuthorizationSetBuilder()
6264 .BlockMode(BlockMode::GCM)
6265 .Padding(PaddingMode::NONE)
6266 .Authorization(TAG_MAC_LENGTH, 128);
6267
Selene Huang31ab4042020-04-29 04:22:39 -07006268 // Encrypt
6269 AuthorizationSet begin_out_params;
6270 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006271 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006272 string ciphertext;
6273 AuthorizationSet finish_out_params;
Shawn Willden92d79c02021-02-19 07:31:55 -07006274 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006275
6276 // Wrong nonce
6277 begin_params.push_back(TAG_NONCE, AidlBuf("123456789012"));
6278
6279 // Decrypt.
6280 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006281 EXPECT_EQ(ErrorCode::OK, UpdateAad("foobar"));
Selene Huang31ab4042020-04-29 04:22:39 -07006282 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006283 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006284
6285 // With wrong nonce, should have gotten garbage plaintext (or none).
6286 EXPECT_NE(message, plaintext);
6287}
6288
6289/*
6290 * EncryptionOperationsTest.AesGcmCorruptTag
6291 *
6292 * Verifies that AES GCM decryption fails correctly when the tag is wrong.
6293 */
6294TEST_P(EncryptionOperationsTest, AesGcmCorruptTag) {
6295 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6296 .Authorization(TAG_NO_AUTH_REQUIRED)
6297 .AesEncryptionKey(128)
6298 .BlockMode(BlockMode::GCM)
6299 .Padding(PaddingMode::NONE)
6300 .Authorization(TAG_MIN_MAC_LENGTH, 128)));
6301
6302 string aad = "1234567890123456";
6303 string message = "123456789012345678901234567890123456";
6304
6305 auto params = AuthorizationSetBuilder()
6306 .BlockMode(BlockMode::GCM)
6307 .Padding(PaddingMode::NONE)
6308 .Authorization(TAG_MAC_LENGTH, 128);
6309
Selene Huang31ab4042020-04-29 04:22:39 -07006310 // Encrypt
6311 AuthorizationSet begin_out_params;
6312 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params, &begin_out_params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006313 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006314 string ciphertext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006315 EXPECT_EQ(ErrorCode::OK, Finish(message, &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006316
6317 // Corrupt tag
6318 ++(*ciphertext.rbegin());
6319
6320 // Grab nonce
6321 params.push_back(begin_out_params);
6322
6323 // Decrypt.
6324 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, params));
Shawn Willden92d79c02021-02-19 07:31:55 -07006325 EXPECT_EQ(ErrorCode::OK, UpdateAad(aad));
Selene Huang31ab4042020-04-29 04:22:39 -07006326 string plaintext;
Shawn Willden92d79c02021-02-19 07:31:55 -07006327 EXPECT_EQ(ErrorCode::VERIFICATION_FAILED, Finish(ciphertext, &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006328}
6329
6330/*
6331 * EncryptionOperationsTest.TripleDesEcbRoundTripSuccess
6332 *
6333 * Verifies that 3DES is basically functional.
6334 */
6335TEST_P(EncryptionOperationsTest, TripleDesEcbRoundTripSuccess) {
6336 auto auths = AuthorizationSetBuilder()
6337 .TripleDesEncryptionKey(168)
6338 .BlockMode(BlockMode::ECB)
6339 .Authorization(TAG_NO_AUTH_REQUIRED)
6340 .Padding(PaddingMode::NONE);
6341
6342 ASSERT_EQ(ErrorCode::OK, GenerateKey(auths));
6343 // Two-block message.
6344 string message = "1234567890123456";
6345 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6346 string ciphertext1 = EncryptMessage(message, inParams);
6347 EXPECT_EQ(message.size(), ciphertext1.size());
6348
6349 string ciphertext2 = EncryptMessage(string(message), inParams);
6350 EXPECT_EQ(message.size(), ciphertext2.size());
6351
6352 // ECB is deterministic.
6353 EXPECT_EQ(ciphertext1, ciphertext2);
6354
6355 string plaintext = DecryptMessage(ciphertext1, inParams);
6356 EXPECT_EQ(message, plaintext);
6357}
6358
6359/*
6360 * EncryptionOperationsTest.TripleDesEcbNotAuthorized
6361 *
6362 * Verifies that CBC keys reject ECB usage.
6363 */
6364TEST_P(EncryptionOperationsTest, TripleDesEcbNotAuthorized) {
6365 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6366 .TripleDesEncryptionKey(168)
6367 .BlockMode(BlockMode::CBC)
6368 .Authorization(TAG_NO_AUTH_REQUIRED)
6369 .Padding(PaddingMode::NONE)));
6370
6371 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
6372 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
6373}
6374
6375/*
6376 * EncryptionOperationsTest.TripleDesEcbPkcs7Padding
6377 *
6378 * Tests ECB mode with PKCS#7 padding, various message sizes.
6379 */
6380TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7Padding) {
6381 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6382 .TripleDesEncryptionKey(168)
6383 .BlockMode(BlockMode::ECB)
6384 .Authorization(TAG_NO_AUTH_REQUIRED)
6385 .Padding(PaddingMode::PKCS7)));
6386
6387 for (size_t i = 0; i < 32; ++i) {
6388 string message(i, 'a');
6389 auto inParams =
6390 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6391 string ciphertext = EncryptMessage(message, inParams);
6392 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6393 string plaintext = DecryptMessage(ciphertext, inParams);
6394 EXPECT_EQ(message, plaintext);
6395 }
6396}
6397
6398/*
6399 * EncryptionOperationsTest.TripleDesEcbNoPaddingKeyWithPkcs7Padding
6400 *
6401 * Verifies that keys configured for no padding reject PKCS7 padding
6402 */
6403TEST_P(EncryptionOperationsTest, TripleDesEcbNoPaddingKeyWithPkcs7Padding) {
6404 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6405 .TripleDesEncryptionKey(168)
6406 .BlockMode(BlockMode::ECB)
6407 .Authorization(TAG_NO_AUTH_REQUIRED)
6408 .Padding(PaddingMode::NONE)));
David Drysdale7de9feb2021-03-05 14:56:19 +00006409 auto inParams = AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::PKCS7);
6410 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, inParams));
Selene Huang31ab4042020-04-29 04:22:39 -07006411}
6412
6413/*
6414 * EncryptionOperationsTest.TripleDesEcbPkcs7PaddingCorrupted
6415 *
6416 * Verifies that corrupted padding is detected.
6417 */
6418TEST_P(EncryptionOperationsTest, TripleDesEcbPkcs7PaddingCorrupted) {
6419 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6420 .TripleDesEncryptionKey(168)
6421 .BlockMode(BlockMode::ECB)
6422 .Authorization(TAG_NO_AUTH_REQUIRED)
6423 .Padding(PaddingMode::PKCS7)));
6424
6425 string message = "a";
6426 string ciphertext = EncryptMessage(message, BlockMode::ECB, PaddingMode::PKCS7);
6427 EXPECT_EQ(8U, ciphertext.size());
6428 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006429
6430 AuthorizationSetBuilder begin_params;
6431 begin_params.push_back(TAG_BLOCK_MODE, BlockMode::ECB);
6432 begin_params.push_back(TAG_PADDING, PaddingMode::PKCS7);
Seth Moore7a55ae32021-06-23 14:28:11 -07006433
6434 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
6435 ++ciphertext[ciphertext.size() / 2];
6436
6437 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6438 string plaintext;
6439 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6440 ErrorCode error = Finish(&plaintext);
6441 if (error == ErrorCode::INVALID_ARGUMENT) {
6442 // This is the expected error, we can exit the test now.
6443 return;
6444 } else {
6445 // Very small chance we got valid decryption, so try again.
6446 ASSERT_EQ(error, ErrorCode::OK);
6447 }
6448 }
6449 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006450}
6451
6452struct TripleDesTestVector {
6453 const char* name;
6454 const KeyPurpose purpose;
6455 const BlockMode block_mode;
6456 const PaddingMode padding_mode;
6457 const char* key;
6458 const char* iv;
6459 const char* input;
6460 const char* output;
6461};
6462
6463// These test vectors are from NIST CAVP, plus a few custom variants to test padding, since all
6464// of the NIST vectors are multiples of the block size.
6465static const TripleDesTestVector kTripleDesTestVectors[] = {
6466 {
6467 "TECBMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6468 "a2b5bc67da13dc92cd9d344aa238544a0e1fa79ef76810cd", // key
6469 "", // IV
6470 "329d86bdf1bc5af4", // input
6471 "d946c2756d78633f", // output
6472 },
6473 {
6474 "TECBMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::ECB, PaddingMode::NONE,
6475 "49e692290d2a5e46bace79b9648a4c5d491004c262dc9d49", // key
6476 "", // IV
6477 "6b1540781b01ce1997adae102dbf3c5b", // input
6478 "4d0dc182d6e481ac4a3dc6ab6976ccae", // output
6479 },
6480 {
6481 "TECBMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6482 "52daec2ac7dc1958377392682f37860b2cc1ea2304bab0e9", // key
6483 "", // IV
6484 "6daad94ce08acfe7", // input
6485 "660e7d32dcc90e79", // output
6486 },
6487 {
6488 "TECBMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::ECB, PaddingMode::NONE,
6489 "7f8fe3d3f4a48394fb682c2919926d6ddfce8932529229ce", // key
6490 "", // IV
6491 "e9653a0a1f05d31b9acd12d73aa9879d", // input
6492 "9b2ae9d998efe62f1b592e7e1df8ff38", // output
6493 },
6494 {
6495 "TCBCMMT3 Encrypt 0", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6496 "b5cb1504802326c73df186e3e352a20de643b0d63ee30e37", // key
6497 "43f791134c5647ba", // IV
6498 "dcc153cef81d6f24", // input
6499 "92538bd8af18d3ba", // output
6500 },
6501 {
6502 "TCBCMMT3 Encrypt 1", KeyPurpose::ENCRYPT, BlockMode::CBC, PaddingMode::NONE,
6503 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6504 "c2e999cb6249023c", // IV
6505 "c689aee38a301bb316da75db36f110b5", // input
6506 "e9afaba5ec75ea1bbe65506655bb4ecb", // output
6507 },
6508 {
6509 "TCBCMMT3 Encrypt 1 PKCS7 variant", KeyPurpose::ENCRYPT, BlockMode::CBC,
6510 PaddingMode::PKCS7,
6511 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6512 "c2e999cb6249023c", // IV
6513 "c689aee38a301bb316da75db36f110b500", // input
6514 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // output
6515 },
6516 {
6517 "TCBCMMT3 Encrypt 1 PKCS7 decrypted", KeyPurpose::DECRYPT, BlockMode::CBC,
6518 PaddingMode::PKCS7,
6519 "a49d7564199e97cb529d2c9d97bf2f98d35edf57ba1f7358", // key
6520 "c2e999cb6249023c", // IV
6521 "e9afaba5ec75ea1bbe65506655bb4ecb825aa27ec0656156", // input
6522 "c689aee38a301bb316da75db36f110b500", // output
6523 },
6524 {
6525 "TCBCMMT3 Decrypt 0", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6526 "5eb6040d46082c7aa7d06dfd08dfeac8c18364c1548c3ba1", // key
6527 "41746c7e442d3681", // IV
6528 "c53a7b0ec40600fe", // input
6529 "d4f00eb455de1034", // output
6530 },
6531 {
6532 "TCBCMMT3 Decrypt 1", KeyPurpose::DECRYPT, BlockMode::CBC, PaddingMode::NONE,
6533 "5b1cce7c0dc1ec49130dfb4af45785ab9179e567f2c7d549", // key
6534 "3982bc02c3727d45", // IV
6535 "6006f10adef52991fcc777a1238bbb65", // input
6536 "edae09288e9e3bc05746d872b48e3b29", // output
6537 },
6538};
6539
6540/*
6541 * EncryptionOperationsTest.TripleDesTestVector
6542 *
6543 * Verifies that NIST (plus a few extra) test vectors produce the correct results.
6544 */
6545TEST_P(EncryptionOperationsTest, TripleDesTestVector) {
6546 constexpr size_t num_tests = sizeof(kTripleDesTestVectors) / sizeof(TripleDesTestVector);
6547 for (auto* test = kTripleDesTestVectors; test < kTripleDesTestVectors + num_tests; ++test) {
6548 SCOPED_TRACE(test->name);
6549 CheckTripleDesTestVector(test->purpose, test->block_mode, test->padding_mode,
6550 hex2str(test->key), hex2str(test->iv), hex2str(test->input),
6551 hex2str(test->output));
6552 }
6553}
6554
6555/*
6556 * EncryptionOperationsTest.TripleDesCbcRoundTripSuccess
6557 *
6558 * Validates CBC mode functionality.
6559 */
6560TEST_P(EncryptionOperationsTest, TripleDesCbcRoundTripSuccess) {
6561 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6562 .TripleDesEncryptionKey(168)
6563 .BlockMode(BlockMode::CBC)
6564 .Authorization(TAG_NO_AUTH_REQUIRED)
6565 .Padding(PaddingMode::NONE)));
6566
6567 ASSERT_GT(key_blob_.size(), 0U);
6568
Brian J Murray734c8412022-01-13 14:55:30 -08006569 // Four-block message.
6570 string message = "12345678901234561234567890123456";
Selene Huang31ab4042020-04-29 04:22:39 -07006571 vector<uint8_t> iv1;
6572 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv1);
6573 EXPECT_EQ(message.size(), ciphertext1.size());
6574
6575 vector<uint8_t> iv2;
6576 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv2);
6577 EXPECT_EQ(message.size(), ciphertext2.size());
6578
6579 // IVs should be random, so ciphertexts should differ.
6580 EXPECT_NE(iv1, iv2);
6581 EXPECT_NE(ciphertext1, ciphertext2);
6582
6583 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv1);
6584 EXPECT_EQ(message, plaintext);
6585}
6586
6587/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006588 * EncryptionOperationsTest.TripleDesInvalidCallerIv
6589 *
6590 * Validates that keymint fails correctly when the user supplies an incorrect-size IV.
6591 */
6592TEST_P(EncryptionOperationsTest, TripleDesInvalidCallerIv) {
6593 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6594 .TripleDesEncryptionKey(168)
6595 .BlockMode(BlockMode::CBC)
6596 .Authorization(TAG_NO_AUTH_REQUIRED)
6597 .Authorization(TAG_CALLER_NONCE)
6598 .Padding(PaddingMode::NONE)));
6599 auto params = AuthorizationSetBuilder()
6600 .BlockMode(BlockMode::CBC)
6601 .Padding(PaddingMode::NONE)
6602 .Authorization(TAG_NONCE, AidlBuf("abcdefg"));
6603 EXPECT_EQ(ErrorCode::INVALID_NONCE, Begin(KeyPurpose::ENCRYPT, params));
6604}
6605
6606/*
Selene Huang31ab4042020-04-29 04:22:39 -07006607 * EncryptionOperationsTest.TripleDesCallerIv
6608 *
6609 * Validates that 3DES keys can allow caller-specified IVs, and use them correctly.
6610 */
6611TEST_P(EncryptionOperationsTest, TripleDesCallerIv) {
6612 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6613 .TripleDesEncryptionKey(168)
6614 .BlockMode(BlockMode::CBC)
6615 .Authorization(TAG_NO_AUTH_REQUIRED)
6616 .Authorization(TAG_CALLER_NONCE)
6617 .Padding(PaddingMode::NONE)));
6618 string message = "1234567890123456";
6619 vector<uint8_t> iv;
6620 // Don't specify IV, should get a random one.
6621 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6622 EXPECT_EQ(message.size(), ciphertext1.size());
6623 EXPECT_EQ(8U, iv.size());
6624
6625 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6626 EXPECT_EQ(message, plaintext);
6627
6628 // Now specify an IV, should also work.
6629 iv = AidlBuf("abcdefgh");
6630 string ciphertext2 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, iv);
6631
6632 // Decrypt with correct IV.
6633 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, iv);
6634 EXPECT_EQ(message, plaintext);
6635
6636 // Now try with wrong IV.
6637 plaintext = DecryptMessage(ciphertext2, BlockMode::CBC, PaddingMode::NONE, AidlBuf("aaaaaaaa"));
6638 EXPECT_NE(message, plaintext);
6639}
6640
6641/*
6642 * EncryptionOperationsTest, TripleDesCallerNonceProhibited.
6643 *
David Drysdaled2cc8c22021-04-15 13:29:45 +01006644 * Verifies that 3DES keys without TAG_CALLER_NONCE do not allow caller-specified IVs.
Selene Huang31ab4042020-04-29 04:22:39 -07006645 */
6646TEST_P(EncryptionOperationsTest, TripleDesCallerNonceProhibited) {
6647 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6648 .TripleDesEncryptionKey(168)
6649 .BlockMode(BlockMode::CBC)
6650 .Authorization(TAG_NO_AUTH_REQUIRED)
6651 .Padding(PaddingMode::NONE)));
6652
6653 string message = "12345678901234567890123456789012";
6654 vector<uint8_t> iv;
6655 // Don't specify nonce, should get a random one.
6656 string ciphertext1 = EncryptMessage(message, BlockMode::CBC, PaddingMode::NONE, &iv);
6657 EXPECT_EQ(message.size(), ciphertext1.size());
6658 EXPECT_EQ(8U, iv.size());
6659
6660 string plaintext = DecryptMessage(ciphertext1, BlockMode::CBC, PaddingMode::NONE, iv);
6661 EXPECT_EQ(message, plaintext);
6662
6663 // Now specify a nonce, should fail.
6664 auto input_params = AuthorizationSetBuilder()
6665 .Authorization(TAG_NONCE, AidlBuf("abcdefgh"))
6666 .BlockMode(BlockMode::CBC)
6667 .Padding(PaddingMode::NONE);
6668 AuthorizationSet output_params;
6669 EXPECT_EQ(ErrorCode::CALLER_NONCE_PROHIBITED,
6670 Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6671}
6672
6673/*
6674 * EncryptionOperationsTest.TripleDesCbcNotAuthorized
6675 *
6676 * Verifies that 3DES ECB-only keys do not allow CBC usage.
6677 */
6678TEST_P(EncryptionOperationsTest, TripleDesCbcNotAuthorized) {
6679 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6680 .TripleDesEncryptionKey(168)
6681 .BlockMode(BlockMode::ECB)
6682 .Authorization(TAG_NO_AUTH_REQUIRED)
6683 .Padding(PaddingMode::NONE)));
6684 // Two-block message.
6685 string message = "1234567890123456";
6686 auto begin_params =
6687 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6688 EXPECT_EQ(ErrorCode::INCOMPATIBLE_BLOCK_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6689}
6690
6691/*
David Drysdaled2cc8c22021-04-15 13:29:45 +01006692 * EncryptionOperationsTest.TripleDesEcbCbcNoPaddingWrongInputSize
Selene Huang31ab4042020-04-29 04:22:39 -07006693 *
6694 * Verifies that unpadded CBC operations reject inputs that are not a multiple of block size.
6695 */
David Drysdaled2cc8c22021-04-15 13:29:45 +01006696TEST_P(EncryptionOperationsTest, TripleDesEcbCbcNoPaddingWrongInputSize) {
6697 for (BlockMode blockMode : {BlockMode::ECB, BlockMode::CBC}) {
6698 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6699 .TripleDesEncryptionKey(168)
6700 .BlockMode(blockMode)
6701 .Authorization(TAG_NO_AUTH_REQUIRED)
6702 .Padding(PaddingMode::NONE)));
6703 // Message is slightly shorter than two blocks.
6704 string message = "123456789012345";
Selene Huang31ab4042020-04-29 04:22:39 -07006705
David Drysdaled2cc8c22021-04-15 13:29:45 +01006706 auto begin_params =
6707 AuthorizationSetBuilder().BlockMode(blockMode).Padding(PaddingMode::NONE);
6708 AuthorizationSet output_params;
6709 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, begin_params, &output_params));
6710 string ciphertext;
6711 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, Finish(message, "", &ciphertext));
6712
6713 CheckedDeleteKey();
6714 }
Selene Huang31ab4042020-04-29 04:22:39 -07006715}
6716
6717/*
6718 * EncryptionOperationsTest, TripleDesCbcPkcs7Padding.
6719 *
6720 * Verifies that PKCS7 padding works correctly in CBC mode.
6721 */
6722TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7Padding) {
6723 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6724 .TripleDesEncryptionKey(168)
6725 .BlockMode(BlockMode::CBC)
6726 .Authorization(TAG_NO_AUTH_REQUIRED)
6727 .Padding(PaddingMode::PKCS7)));
6728
6729 // Try various message lengths; all should work.
Brian J Murray734c8412022-01-13 14:55:30 -08006730 for (size_t i = 0; i <= 32; i++) {
6731 SCOPED_TRACE(testing::Message() << "i = " << i);
6732 // Edge case: '\t' (0x09) is also a valid PKCS7 padding character, albeit not for 3DES.
6733 string message(i, '\t');
Selene Huang31ab4042020-04-29 04:22:39 -07006734 vector<uint8_t> iv;
6735 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6736 EXPECT_EQ(i + 8 - (i % 8), ciphertext.size());
6737 string plaintext = DecryptMessage(ciphertext, BlockMode::CBC, PaddingMode::PKCS7, iv);
6738 EXPECT_EQ(message, plaintext);
6739 }
6740}
6741
6742/*
6743 * EncryptionOperationsTest.TripleDesCbcNoPaddingKeyWithPkcs7Padding
6744 *
6745 * Verifies that a key that requires PKCS7 padding cannot be used in unpadded mode.
6746 */
6747TEST_P(EncryptionOperationsTest, TripleDesCbcNoPaddingKeyWithPkcs7Padding) {
6748 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6749 .TripleDesEncryptionKey(168)
6750 .BlockMode(BlockMode::CBC)
6751 .Authorization(TAG_NO_AUTH_REQUIRED)
6752 .Padding(PaddingMode::NONE)));
6753
6754 // Try various message lengths; all should fail.
Brian J Murray734c8412022-01-13 14:55:30 -08006755 for (size_t i = 0; i <= 32; i++) {
Selene Huang31ab4042020-04-29 04:22:39 -07006756 auto begin_params =
6757 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::PKCS7);
6758 EXPECT_EQ(ErrorCode::INCOMPATIBLE_PADDING_MODE, Begin(KeyPurpose::ENCRYPT, begin_params));
6759 }
6760}
6761
6762/*
6763 * EncryptionOperationsTest.TripleDesCbcPkcs7PaddingCorrupted
6764 *
6765 * Verifies that corrupted PKCS7 padding is rejected during decryption.
6766 */
6767TEST_P(EncryptionOperationsTest, TripleDesCbcPkcs7PaddingCorrupted) {
6768 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6769 .TripleDesEncryptionKey(168)
6770 .BlockMode(BlockMode::CBC)
6771 .Authorization(TAG_NO_AUTH_REQUIRED)
6772 .Padding(PaddingMode::PKCS7)));
6773
6774 string message = "a";
6775 vector<uint8_t> iv;
6776 string ciphertext = EncryptMessage(message, BlockMode::CBC, PaddingMode::PKCS7, &iv);
6777 EXPECT_EQ(8U, ciphertext.size());
6778 EXPECT_NE(ciphertext, message);
Selene Huang31ab4042020-04-29 04:22:39 -07006779
6780 auto begin_params = AuthorizationSetBuilder()
6781 .BlockMode(BlockMode::CBC)
6782 .Padding(PaddingMode::PKCS7)
6783 .Authorization(TAG_NONCE, iv);
Seth Moore7a55ae32021-06-23 14:28:11 -07006784
6785 for (size_t i = 0; i < kMaxPaddingCorruptionRetries; ++i) {
Brian J Murray734c8412022-01-13 14:55:30 -08006786 SCOPED_TRACE(testing::Message() << "i = " << i);
Seth Moore7a55ae32021-06-23 14:28:11 -07006787 ++ciphertext[ciphertext.size() / 2];
6788 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, begin_params));
6789 string plaintext;
6790 EXPECT_EQ(ErrorCode::OK, Update(ciphertext, &plaintext));
6791 ErrorCode error = Finish(&plaintext);
6792 if (error == ErrorCode::INVALID_ARGUMENT) {
6793 // This is the expected error, we can exit the test now.
6794 return;
6795 } else {
6796 // Very small chance we got valid decryption, so try again.
6797 ASSERT_EQ(error, ErrorCode::OK);
6798 }
6799 }
6800 FAIL() << "Corrupt ciphertext should have failed to decrypt by now.";
Selene Huang31ab4042020-04-29 04:22:39 -07006801}
6802
6803/*
6804 * EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding.
6805 *
6806 * Verifies that 3DES CBC works with many different input sizes.
6807 */
6808TEST_P(EncryptionOperationsTest, TripleDesCbcIncrementalNoPadding) {
6809 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6810 .TripleDesEncryptionKey(168)
6811 .BlockMode(BlockMode::CBC)
6812 .Authorization(TAG_NO_AUTH_REQUIRED)
6813 .Padding(PaddingMode::NONE)));
6814
6815 int increment = 7;
6816 string message(240, 'a');
6817 AuthorizationSet input_params =
6818 AuthorizationSetBuilder().BlockMode(BlockMode::CBC).Padding(PaddingMode::NONE);
6819 AuthorizationSet output_params;
6820 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, input_params, &output_params));
6821
6822 string ciphertext;
Selene Huang31ab4042020-04-29 04:22:39 -07006823 for (size_t i = 0; i < message.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006824 EXPECT_EQ(ErrorCode::OK, Update(message.substr(i, increment), &ciphertext));
Selene Huang31ab4042020-04-29 04:22:39 -07006825 EXPECT_EQ(ErrorCode::OK, Finish(&ciphertext));
6826 EXPECT_EQ(message.size(), ciphertext.size());
6827
6828 // Move TAG_NONCE into input_params
6829 input_params = output_params;
6830 input_params.push_back(TAG_BLOCK_MODE, BlockMode::CBC);
6831 input_params.push_back(TAG_PADDING, PaddingMode::NONE);
6832 output_params.Clear();
6833
6834 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, input_params, &output_params));
6835 string plaintext;
6836 for (size_t i = 0; i < ciphertext.size(); i += increment)
Shawn Willden92d79c02021-02-19 07:31:55 -07006837 EXPECT_EQ(ErrorCode::OK, Update(ciphertext.substr(i, increment), &plaintext));
Selene Huang31ab4042020-04-29 04:22:39 -07006838 EXPECT_EQ(ErrorCode::OK, Finish(&plaintext));
6839 EXPECT_EQ(ciphertext.size(), plaintext.size());
6840 EXPECT_EQ(message, plaintext);
6841}
6842
6843INSTANTIATE_KEYMINT_AIDL_TEST(EncryptionOperationsTest);
6844
6845typedef KeyMintAidlTestBase MaxOperationsTest;
6846
6847/*
6848 * MaxOperationsTest.TestLimitAes
6849 *
6850 * Verifies that the max uses per boot tag works correctly with AES keys.
6851 */
6852TEST_P(MaxOperationsTest, TestLimitAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006853 if (SecLevel() == SecurityLevel::STRONGBOX) {
6854 GTEST_SKIP() << "Test not applicable to StrongBox device";
6855 }
Selene Huang31ab4042020-04-29 04:22:39 -07006856
6857 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6858 .Authorization(TAG_NO_AUTH_REQUIRED)
6859 .AesEncryptionKey(128)
6860 .EcbMode()
6861 .Padding(PaddingMode::NONE)
6862 .Authorization(TAG_MAX_USES_PER_BOOT, 3)));
6863
6864 string message = "1234567890123456";
6865
6866 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6867
6868 EncryptMessage(message, params);
6869 EncryptMessage(message, params);
6870 EncryptMessage(message, params);
6871
6872 // Fourth time should fail.
6873 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::ENCRYPT, params));
6874}
6875
6876/*
Qi Wud22ec842020-11-26 13:27:53 +08006877 * MaxOperationsTest.TestLimitRsa
Selene Huang31ab4042020-04-29 04:22:39 -07006878 *
6879 * Verifies that the max uses per boot tag works correctly with RSA keys.
6880 */
6881TEST_P(MaxOperationsTest, TestLimitRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01006882 if (SecLevel() == SecurityLevel::STRONGBOX) {
6883 GTEST_SKIP() << "Test not applicable to StrongBox device";
6884 }
Selene Huang31ab4042020-04-29 04:22:39 -07006885
6886 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6887 .Authorization(TAG_NO_AUTH_REQUIRED)
6888 .RsaSigningKey(1024, 65537)
6889 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08006890 .Authorization(TAG_MAX_USES_PER_BOOT, 3)
6891 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07006892
6893 string message = "1234567890123456";
6894
6895 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
6896
6897 SignMessage(message, params);
6898 SignMessage(message, params);
6899 SignMessage(message, params);
6900
6901 // Fourth time should fail.
6902 EXPECT_EQ(ErrorCode::KEY_MAX_OPS_EXCEEDED, Begin(KeyPurpose::SIGN, params));
6903}
6904
6905INSTANTIATE_KEYMINT_AIDL_TEST(MaxOperationsTest);
6906
Qi Wud22ec842020-11-26 13:27:53 +08006907typedef KeyMintAidlTestBase UsageCountLimitTest;
6908
6909/*
Qi Wubeefae42021-01-28 23:16:37 +08006910 * UsageCountLimitTest.TestSingleUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006911 *
Qi Wubeefae42021-01-28 23:16:37 +08006912 * Verifies that the usage count limit tag = 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006913 */
Qi Wubeefae42021-01-28 23:16:37 +08006914TEST_P(UsageCountLimitTest, TestSingleUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006915 if (SecLevel() == SecurityLevel::STRONGBOX) {
6916 GTEST_SKIP() << "Test not applicable to StrongBox device";
6917 }
Qi Wud22ec842020-11-26 13:27:53 +08006918
6919 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6920 .Authorization(TAG_NO_AUTH_REQUIRED)
6921 .AesEncryptionKey(128)
6922 .EcbMode()
6923 .Padding(PaddingMode::NONE)
6924 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)));
6925
6926 // Check the usage count limit tag appears in the authorizations.
6927 AuthorizationSet auths;
6928 for (auto& entry : key_characteristics_) {
6929 auths.push_back(AuthorizationSet(entry.authorizations));
6930 }
6931 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
6932 << "key usage count limit " << 1U << " missing";
6933
6934 string message = "1234567890123456";
6935 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6936
Qi Wubeefae42021-01-28 23:16:37 +08006937 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6938 AuthorizationSet keystore_auths =
6939 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6940
Qi Wud22ec842020-11-26 13:27:53 +08006941 // First usage of AES key should work.
6942 EncryptMessage(message, params);
6943
Qi Wud22ec842020-11-26 13:27:53 +08006944 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
6945 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6946 // must be invalidated from secure storage (such as RPMB partition).
6947 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6948 } else {
Qi Wubeefae42021-01-28 23:16:37 +08006949 // Usage count limit tag is enforced by keystore, keymint does nothing.
6950 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
Qi Wud22ec842020-11-26 13:27:53 +08006951 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6952 }
6953}
6954
6955/*
Qi Wubeefae42021-01-28 23:16:37 +08006956 * UsageCountLimitTest.TestLimitedUseAes
Qi Wud22ec842020-11-26 13:27:53 +08006957 *
Qi Wubeefae42021-01-28 23:16:37 +08006958 * Verifies that the usage count limit tag > 1 works correctly with AES keys.
Qi Wud22ec842020-11-26 13:27:53 +08006959 */
Qi Wubeefae42021-01-28 23:16:37 +08006960TEST_P(UsageCountLimitTest, TestLimitedUseAes) {
David Drysdale513bf122021-10-06 11:53:13 +01006961 if (SecLevel() == SecurityLevel::STRONGBOX) {
6962 GTEST_SKIP() << "Test not applicable to StrongBox device";
6963 }
Qi Wubeefae42021-01-28 23:16:37 +08006964
6965 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
6966 .Authorization(TAG_NO_AUTH_REQUIRED)
6967 .AesEncryptionKey(128)
6968 .EcbMode()
6969 .Padding(PaddingMode::NONE)
6970 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)));
6971
6972 // Check the usage count limit tag appears in the authorizations.
6973 AuthorizationSet auths;
6974 for (auto& entry : key_characteristics_) {
6975 auths.push_back(AuthorizationSet(entry.authorizations));
6976 }
6977 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
6978 << "key usage count limit " << 3U << " missing";
6979
6980 string message = "1234567890123456";
6981 auto params = AuthorizationSetBuilder().EcbMode().Padding(PaddingMode::NONE);
6982
6983 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
6984 AuthorizationSet keystore_auths =
6985 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
6986
6987 EncryptMessage(message, params);
6988 EncryptMessage(message, params);
6989 EncryptMessage(message, params);
6990
6991 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
6992 // Usage count limit tag is enforced by hardware. After using the key, the key blob
6993 // must be invalidated from secure storage (such as RPMB partition).
6994 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::ENCRYPT, params));
6995 } else {
6996 // Usage count limit tag is enforced by keystore, keymint does nothing.
6997 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
6998 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, params));
6999 }
7000}
7001
7002/*
7003 * UsageCountLimitTest.TestSingleUseRsa
7004 *
7005 * Verifies that the usage count limit tag = 1 works correctly with RSA keys.
7006 */
7007TEST_P(UsageCountLimitTest, TestSingleUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007008 if (SecLevel() == SecurityLevel::STRONGBOX) {
7009 GTEST_SKIP() << "Test not applicable to StrongBox device";
7010 }
Qi Wud22ec842020-11-26 13:27:53 +08007011
7012 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7013 .Authorization(TAG_NO_AUTH_REQUIRED)
7014 .RsaSigningKey(1024, 65537)
7015 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007016 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7017 .SetDefaultValidity()));
Qi Wud22ec842020-11-26 13:27:53 +08007018
7019 // Check the usage count limit tag appears in the authorizations.
7020 AuthorizationSet auths;
7021 for (auto& entry : key_characteristics_) {
7022 auths.push_back(AuthorizationSet(entry.authorizations));
7023 }
7024 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7025 << "key usage count limit " << 1U << " missing";
7026
7027 string message = "1234567890123456";
7028 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7029
Qi Wubeefae42021-01-28 23:16:37 +08007030 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7031 AuthorizationSet keystore_auths =
7032 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7033
Qi Wud22ec842020-11-26 13:27:53 +08007034 // First usage of RSA key should work.
7035 SignMessage(message, params);
7036
Qi Wud22ec842020-11-26 13:27:53 +08007037 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U)) {
7038 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7039 // must be invalidated from secure storage (such as RPMB partition).
7040 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7041 } else {
Qi Wubeefae42021-01-28 23:16:37 +08007042 // Usage count limit tag is enforced by keystore, keymint does nothing.
7043 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U));
7044 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
7045 }
7046}
7047
7048/*
7049 * UsageCountLimitTest.TestLimitUseRsa
7050 *
7051 * Verifies that the usage count limit tag > 1 works correctly with RSA keys.
7052 */
7053TEST_P(UsageCountLimitTest, TestLimitUseRsa) {
David Drysdale513bf122021-10-06 11:53:13 +01007054 if (SecLevel() == SecurityLevel::STRONGBOX) {
7055 GTEST_SKIP() << "Test not applicable to StrongBox device";
7056 }
Qi Wubeefae42021-01-28 23:16:37 +08007057
7058 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7059 .Authorization(TAG_NO_AUTH_REQUIRED)
7060 .RsaSigningKey(1024, 65537)
7061 .NoDigestOrPadding()
Janis Danisevskis164bb872021-02-09 11:30:25 -08007062 .Authorization(TAG_USAGE_COUNT_LIMIT, 3)
7063 .SetDefaultValidity()));
Qi Wubeefae42021-01-28 23:16:37 +08007064
7065 // Check the usage count limit tag appears in the authorizations.
7066 AuthorizationSet auths;
7067 for (auto& entry : key_characteristics_) {
7068 auths.push_back(AuthorizationSet(entry.authorizations));
7069 }
7070 EXPECT_TRUE(auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U))
7071 << "key usage count limit " << 3U << " missing";
7072
7073 string message = "1234567890123456";
7074 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7075
7076 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7077 AuthorizationSet keystore_auths =
7078 SecLevelAuthorizations(key_characteristics_, SecurityLevel::KEYSTORE);
7079
7080 SignMessage(message, params);
7081 SignMessage(message, params);
7082 SignMessage(message, params);
7083
7084 if (hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U)) {
7085 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7086 // must be invalidated from secure storage (such as RPMB partition).
7087 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
7088 } else {
7089 // Usage count limit tag is enforced by keystore, keymint does nothing.
7090 EXPECT_TRUE(keystore_auths.Contains(TAG_USAGE_COUNT_LIMIT, 3U));
Qi Wud22ec842020-11-26 13:27:53 +08007091 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::SIGN, params));
7092 }
7093}
7094
Qi Wu8e727f72021-02-11 02:49:33 +08007095/*
7096 * UsageCountLimitTest.TestSingleUseKeyAndRollbackResistance
7097 *
7098 * Verifies that when rollback resistance is supported by the KeyMint implementation with
7099 * the secure hardware, the single use key with usage count limit tag = 1 must also be enforced
7100 * in hardware.
7101 */
7102TEST_P(UsageCountLimitTest, TestSingleUseKeyAndRollbackResistance) {
David Drysdale513bf122021-10-06 11:53:13 +01007103 if (SecLevel() == SecurityLevel::STRONGBOX) {
7104 GTEST_SKIP() << "Test not applicable to StrongBox device";
7105 }
Qi Wu8e727f72021-02-11 02:49:33 +08007106
7107 auto error = GenerateKey(AuthorizationSetBuilder()
7108 .RsaSigningKey(2048, 65537)
7109 .Digest(Digest::NONE)
7110 .Padding(PaddingMode::NONE)
7111 .Authorization(TAG_NO_AUTH_REQUIRED)
7112 .Authorization(TAG_ROLLBACK_RESISTANCE)
7113 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007114 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7115 GTEST_SKIP() << "Rollback resistance not supported";
Qi Wu8e727f72021-02-11 02:49:33 +08007116 }
David Drysdale513bf122021-10-06 11:53:13 +01007117
7118 // Rollback resistance is supported by KeyMint, verify it is enforced in hardware.
7119 ASSERT_EQ(ErrorCode::OK, error);
7120 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7121 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
7122 ASSERT_EQ(ErrorCode::OK, DeleteKey());
7123
7124 // The KeyMint should also enforce single use key in hardware when it supports rollback
7125 // resistance.
7126 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7127 .Authorization(TAG_NO_AUTH_REQUIRED)
7128 .RsaSigningKey(1024, 65537)
7129 .NoDigestOrPadding()
7130 .Authorization(TAG_USAGE_COUNT_LIMIT, 1)
7131 .SetDefaultValidity()));
7132
7133 // Check the usage count limit tag appears in the hardware authorizations.
7134 AuthorizationSet hardware_auths = HwEnforcedAuthorizations(key_characteristics_);
7135 EXPECT_TRUE(hardware_auths.Contains(TAG_USAGE_COUNT_LIMIT, 1U))
7136 << "key usage count limit " << 1U << " missing";
7137
7138 string message = "1234567890123456";
7139 auto params = AuthorizationSetBuilder().NoDigestOrPadding();
7140
7141 // First usage of RSA key should work.
7142 SignMessage(message, params);
7143
7144 // Usage count limit tag is enforced by hardware. After using the key, the key blob
7145 // must be invalidated from secure storage (such as RPMB partition).
7146 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB, Begin(KeyPurpose::SIGN, params));
Qi Wu8e727f72021-02-11 02:49:33 +08007147}
7148
Qi Wud22ec842020-11-26 13:27:53 +08007149INSTANTIATE_KEYMINT_AIDL_TEST(UsageCountLimitTest);
7150
David Drysdale7de9feb2021-03-05 14:56:19 +00007151typedef KeyMintAidlTestBase GetHardwareInfoTest;
7152
7153TEST_P(GetHardwareInfoTest, GetHardwareInfo) {
7154 // Retrieving hardware info should give the same result each time.
7155 KeyMintHardwareInfo info;
7156 ASSERT_TRUE(keyMint().getHardwareInfo(&info).isOk());
7157 KeyMintHardwareInfo info2;
7158 ASSERT_TRUE(keyMint().getHardwareInfo(&info2).isOk());
7159 EXPECT_EQ(info, info2);
7160}
7161
7162INSTANTIATE_KEYMINT_AIDL_TEST(GetHardwareInfoTest);
7163
Selene Huang31ab4042020-04-29 04:22:39 -07007164typedef KeyMintAidlTestBase AddEntropyTest;
7165
7166/*
7167 * AddEntropyTest.AddEntropy
7168 *
7169 * Verifies that the addRngEntropy method doesn't blow up. There's no way to test that entropy
7170 * is actually added.
7171 */
7172TEST_P(AddEntropyTest, AddEntropy) {
7173 string data = "foo";
7174 EXPECT_TRUE(keyMint().addRngEntropy(vector<uint8_t>(data.begin(), data.end())).isOk());
7175}
7176
7177/*
7178 * AddEntropyTest.AddEmptyEntropy
7179 *
7180 * Verifies that the addRngEntropy method doesn't blow up when given an empty buffer.
7181 */
7182TEST_P(AddEntropyTest, AddEmptyEntropy) {
7183 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf()).isOk());
7184}
7185
7186/*
7187 * AddEntropyTest.AddLargeEntropy
7188 *
7189 * Verifies that the addRngEntropy method doesn't blow up when given a largish amount of data.
7190 */
7191TEST_P(AddEntropyTest, AddLargeEntropy) {
7192 EXPECT_TRUE(keyMint().addRngEntropy(AidlBuf(string(2 * 1024, 'a'))).isOk());
7193}
7194
David Drysdalebb3d85e2021-04-13 11:15:51 +01007195/*
7196 * AddEntropyTest.AddTooLargeEntropy
7197 *
7198 * Verifies that the addRngEntropy method rejects more than 2KiB of data.
7199 */
7200TEST_P(AddEntropyTest, AddTooLargeEntropy) {
7201 ErrorCode rc = GetReturnErrorCode(keyMint().addRngEntropy(AidlBuf(string(2 * 1024 + 1, 'a'))));
7202 EXPECT_EQ(ErrorCode::INVALID_INPUT_LENGTH, rc);
7203}
7204
Selene Huang31ab4042020-04-29 04:22:39 -07007205INSTANTIATE_KEYMINT_AIDL_TEST(AddEntropyTest);
7206
Selene Huang31ab4042020-04-29 04:22:39 -07007207typedef KeyMintAidlTestBase KeyDeletionTest;
7208
7209/**
7210 * KeyDeletionTest.DeleteKey
7211 *
7212 * This test checks that if rollback protection is implemented, DeleteKey invalidates a formerly
7213 * valid key blob.
7214 */
7215TEST_P(KeyDeletionTest, DeleteKey) {
7216 auto error = GenerateKey(AuthorizationSetBuilder()
7217 .RsaSigningKey(2048, 65537)
7218 .Digest(Digest::NONE)
7219 .Padding(PaddingMode::NONE)
7220 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007221 .Authorization(TAG_ROLLBACK_RESISTANCE)
7222 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007223 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7224 GTEST_SKIP() << "Rollback resistance not supported";
7225 }
Selene Huang31ab4042020-04-29 04:22:39 -07007226
7227 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007228 ASSERT_EQ(ErrorCode::OK, error);
7229 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7230 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007231
David Drysdale513bf122021-10-06 11:53:13 +01007232 ASSERT_EQ(ErrorCode::OK, DeleteKey(true /* keep key blob */));
Selene Huang31ab4042020-04-29 04:22:39 -07007233
David Drysdale513bf122021-10-06 11:53:13 +01007234 string message = "12345678901234567890123456789012";
7235 AuthorizationSet begin_out_params;
7236 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7237 Begin(KeyPurpose::SIGN, key_blob_,
7238 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7239 &begin_out_params));
7240 AbortIfNeeded();
7241 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007242}
7243
7244/**
7245 * KeyDeletionTest.DeleteInvalidKey
7246 *
7247 * This test checks that the HAL excepts invalid key blobs..
7248 */
7249TEST_P(KeyDeletionTest, DeleteInvalidKey) {
7250 // Generate key just to check if rollback protection is implemented
7251 auto error = GenerateKey(AuthorizationSetBuilder()
7252 .RsaSigningKey(2048, 65537)
7253 .Digest(Digest::NONE)
7254 .Padding(PaddingMode::NONE)
7255 .Authorization(TAG_NO_AUTH_REQUIRED)
Qi Wu8e727f72021-02-11 02:49:33 +08007256 .Authorization(TAG_ROLLBACK_RESISTANCE)
7257 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007258 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7259 GTEST_SKIP() << "Rollback resistance not supported";
7260 }
Selene Huang31ab4042020-04-29 04:22:39 -07007261
7262 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007263 ASSERT_EQ(ErrorCode::OK, error);
7264 AuthorizationSet enforced(SecLevelAuthorizations());
7265 ASSERT_TRUE(enforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007266
David Drysdale513bf122021-10-06 11:53:13 +01007267 // Delete the key we don't care about the result at this point.
7268 DeleteKey();
Selene Huang31ab4042020-04-29 04:22:39 -07007269
David Drysdale513bf122021-10-06 11:53:13 +01007270 // Now create an invalid key blob and delete it.
7271 key_blob_ = AidlBuf("just some garbage data which is not a valid key blob");
Selene Huang31ab4042020-04-29 04:22:39 -07007272
David Drysdale513bf122021-10-06 11:53:13 +01007273 ASSERT_EQ(ErrorCode::OK, DeleteKey());
Selene Huang31ab4042020-04-29 04:22:39 -07007274}
7275
7276/**
7277 * KeyDeletionTest.DeleteAllKeys
7278 *
7279 * This test is disarmed by default. To arm it use --arm_deleteAllKeys.
7280 *
7281 * BEWARE: This test has serious side effects. All user keys will be lost! This includes
7282 * FBE/FDE encryption keys, which means that the device will not even boot until after the
7283 * device has been wiped manually (e.g., fastboot flashall -w), and new FBE/FDE keys have
7284 * been provisioned. Use this test only on dedicated testing devices that have no valuable
7285 * credentials stored in Keystore/Keymint.
7286 */
7287TEST_P(KeyDeletionTest, DeleteAllKeys) {
David Drysdale513bf122021-10-06 11:53:13 +01007288 if (!arm_deleteAllKeys) {
7289 GTEST_SKIP() << "Option --arm_deleteAllKeys not set";
7290 return;
7291 }
Selene Huang31ab4042020-04-29 04:22:39 -07007292 auto error = GenerateKey(AuthorizationSetBuilder()
7293 .RsaSigningKey(2048, 65537)
7294 .Digest(Digest::NONE)
7295 .Padding(PaddingMode::NONE)
7296 .Authorization(TAG_NO_AUTH_REQUIRED)
Shawn Willden9a7410e2021-08-02 12:28:42 -06007297 .Authorization(TAG_ROLLBACK_RESISTANCE)
7298 .SetDefaultValidity());
David Drysdale513bf122021-10-06 11:53:13 +01007299 if (error == ErrorCode::ROLLBACK_RESISTANCE_UNAVAILABLE) {
7300 GTEST_SKIP() << "Rollback resistance not supported";
7301 }
Selene Huang31ab4042020-04-29 04:22:39 -07007302
7303 // Delete must work if rollback protection is implemented
David Drysdale513bf122021-10-06 11:53:13 +01007304 ASSERT_EQ(ErrorCode::OK, error);
7305 AuthorizationSet hardwareEnforced(SecLevelAuthorizations());
7306 ASSERT_TRUE(hardwareEnforced.Contains(TAG_ROLLBACK_RESISTANCE));
Selene Huang31ab4042020-04-29 04:22:39 -07007307
David Drysdale513bf122021-10-06 11:53:13 +01007308 ASSERT_EQ(ErrorCode::OK, DeleteAllKeys());
Selene Huang31ab4042020-04-29 04:22:39 -07007309
David Drysdale513bf122021-10-06 11:53:13 +01007310 string message = "12345678901234567890123456789012";
7311 AuthorizationSet begin_out_params;
Selene Huang31ab4042020-04-29 04:22:39 -07007312
David Drysdale513bf122021-10-06 11:53:13 +01007313 EXPECT_EQ(ErrorCode::INVALID_KEY_BLOB,
7314 Begin(KeyPurpose::SIGN, key_blob_,
7315 AuthorizationSetBuilder().Digest(Digest::NONE).Padding(PaddingMode::NONE),
7316 &begin_out_params));
7317 AbortIfNeeded();
7318 key_blob_ = AidlBuf();
Selene Huang31ab4042020-04-29 04:22:39 -07007319}
7320
7321INSTANTIATE_KEYMINT_AIDL_TEST(KeyDeletionTest);
7322
David Drysdaled2cc8c22021-04-15 13:29:45 +01007323typedef KeyMintAidlTestBase KeyUpgradeTest;
7324
7325/**
7326 * KeyUpgradeTest.UpgradeInvalidKey
7327 *
7328 * This test checks that the HAL excepts invalid key blobs..
7329 */
7330TEST_P(KeyUpgradeTest, UpgradeInvalidKey) {
7331 AidlBuf key_blob = AidlBuf("just some garbage data which is not a valid key blob");
7332
7333 std::vector<uint8_t> new_blob;
7334 Status result = keymint_->upgradeKey(key_blob,
7335 AuthorizationSetBuilder()
7336 .Authorization(TAG_APPLICATION_ID, "clientid")
7337 .Authorization(TAG_APPLICATION_DATA, "appdata")
7338 .vector_data(),
7339 &new_blob);
7340 ASSERT_EQ(ErrorCode::INVALID_KEY_BLOB, GetReturnErrorCode(result));
7341}
7342
7343INSTANTIATE_KEYMINT_AIDL_TEST(KeyUpgradeTest);
7344
Selene Huang31ab4042020-04-29 04:22:39 -07007345using UpgradeKeyTest = KeyMintAidlTestBase;
7346
7347/*
7348 * UpgradeKeyTest.UpgradeKey
7349 *
7350 * Verifies that calling upgrade key on an up-to-date key works (i.e. does nothing).
7351 */
7352TEST_P(UpgradeKeyTest, UpgradeKey) {
7353 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7354 .AesEncryptionKey(128)
7355 .Padding(PaddingMode::NONE)
7356 .Authorization(TAG_NO_AUTH_REQUIRED)));
7357
7358 auto result = UpgradeKey(key_blob_);
7359
7360 // Key doesn't need upgrading. Should get okay, but no new key blob.
7361 EXPECT_EQ(result, std::make_pair(ErrorCode::OK, vector<uint8_t>()));
7362}
7363
7364INSTANTIATE_KEYMINT_AIDL_TEST(UpgradeKeyTest);
7365
7366using ClearOperationsTest = KeyMintAidlTestBase;
7367
7368/*
7369 * ClearSlotsTest.TooManyOperations
7370 *
7371 * Verifies that TOO_MANY_OPERATIONS is returned after the max number of
7372 * operations are started without being finished or aborted. Also verifies
7373 * that aborting the operations clears the operations.
7374 *
7375 */
7376TEST_P(ClearOperationsTest, TooManyOperations) {
7377 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7378 .Authorization(TAG_NO_AUTH_REQUIRED)
7379 .RsaEncryptionKey(2048, 65537)
Janis Danisevskis164bb872021-02-09 11:30:25 -08007380 .Padding(PaddingMode::NONE)
7381 .SetDefaultValidity()));
Selene Huang31ab4042020-04-29 04:22:39 -07007382
7383 auto params = AuthorizationSetBuilder().Padding(PaddingMode::NONE);
7384 constexpr size_t max_operations = 100; // set to arbituary large number
Janis Danisevskis24c04702020-12-16 18:28:39 -08007385 std::shared_ptr<IKeyMintOperation> op_handles[max_operations];
Selene Huang31ab4042020-04-29 04:22:39 -07007386 AuthorizationSet out_params;
7387 ErrorCode result;
7388 size_t i;
7389
7390 for (i = 0; i < max_operations; i++) {
subrahmanyaman05642492022-02-05 07:10:56 +00007391 result = Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params, op_handles[i]);
Selene Huang31ab4042020-04-29 04:22:39 -07007392 if (ErrorCode::OK != result) {
7393 break;
7394 }
7395 }
7396 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS, result);
7397 // Try again just in case there's a weird overflow bug
7398 EXPECT_EQ(ErrorCode::TOO_MANY_OPERATIONS,
subrahmanyaman05642492022-02-05 07:10:56 +00007399 Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007400 for (size_t j = 0; j < i; j++) {
7401 EXPECT_EQ(ErrorCode::OK, Abort(op_handles[j]))
7402 << "Aboort failed for i = " << j << std::endl;
7403 }
subrahmanyaman05642492022-02-05 07:10:56 +00007404 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, key_blob_, params, &out_params));
Selene Huang31ab4042020-04-29 04:22:39 -07007405 AbortIfNeeded();
7406}
7407
7408INSTANTIATE_KEYMINT_AIDL_TEST(ClearOperationsTest);
7409
7410typedef KeyMintAidlTestBase TransportLimitTest;
7411
7412/*
David Drysdale7de9feb2021-03-05 14:56:19 +00007413 * TransportLimitTest.LargeFinishInput
Selene Huang31ab4042020-04-29 04:22:39 -07007414 *
7415 * Verifies that passing input data to finish succeeds as expected.
7416 */
7417TEST_P(TransportLimitTest, LargeFinishInput) {
7418 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7419 .Authorization(TAG_NO_AUTH_REQUIRED)
7420 .AesEncryptionKey(128)
7421 .BlockMode(BlockMode::ECB)
7422 .Padding(PaddingMode::NONE)));
7423
7424 for (int msg_size = 8 /* 256 bytes */; msg_size <= 11 /* 2 KiB */; msg_size++) {
7425 auto cipher_params =
7426 AuthorizationSetBuilder().BlockMode(BlockMode::ECB).Padding(PaddingMode::NONE);
7427
7428 AuthorizationSet out_params;
7429 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::ENCRYPT, cipher_params, &out_params));
7430
7431 string plain_message = std::string(1 << msg_size, 'x');
7432 string encrypted_message;
7433 auto rc = Finish(plain_message, &encrypted_message);
7434
7435 EXPECT_EQ(ErrorCode::OK, rc);
7436 EXPECT_EQ(plain_message.size(), encrypted_message.size())
7437 << "Encrypt finish returned OK, but did not consume all of the given input";
7438 cipher_params.push_back(out_params);
7439
7440 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::DECRYPT, cipher_params));
7441
7442 string decrypted_message;
7443 rc = Finish(encrypted_message, &decrypted_message);
7444 EXPECT_EQ(ErrorCode::OK, rc);
7445 EXPECT_EQ(plain_message.size(), decrypted_message.size())
7446 << "Decrypt finish returned OK, did not consume all of the given input";
7447 }
7448}
7449
7450INSTANTIATE_KEYMINT_AIDL_TEST(TransportLimitTest);
7451
Seth Moored79a0ec2021-12-13 20:03:33 +00007452static int EcdhCurveToOpenSslCurveName(EcCurve curve) {
David Zeuthene0c40892021-01-08 12:54:11 -05007453 switch (curve) {
7454 case EcCurve::P_224:
7455 return NID_secp224r1;
7456 case EcCurve::P_256:
7457 return NID_X9_62_prime256v1;
7458 case EcCurve::P_384:
7459 return NID_secp384r1;
7460 case EcCurve::P_521:
7461 return NID_secp521r1;
Seth Moored79a0ec2021-12-13 20:03:33 +00007462 case EcCurve::CURVE_25519:
7463 return NID_X25519;
David Zeuthene0c40892021-01-08 12:54:11 -05007464 }
7465}
7466
David Drysdale42fe1892021-10-14 14:43:46 +01007467class KeyAgreementTest : public KeyMintAidlTestBase {
7468 protected:
7469 void GenerateLocalEcKey(EcCurve localCurve, EVP_PKEY_Ptr* localPrivKey,
7470 std::vector<uint8_t>* localPublicKey) {
7471 // Generate EC key locally (with access to private key material)
7472 if (localCurve == EcCurve::CURVE_25519) {
7473 uint8_t privKeyData[32];
7474 uint8_t pubKeyData[32];
7475 X25519_keypair(pubKeyData, privKeyData);
7476 *localPublicKey = vector<uint8_t>(pubKeyData, pubKeyData + 32);
7477 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new_raw_private_key(
7478 EVP_PKEY_X25519, nullptr, privKeyData, sizeof(privKeyData)));
7479 } else {
7480 auto ecKey = EC_KEY_Ptr(EC_KEY_new());
7481 int curveName = EcdhCurveToOpenSslCurveName(localCurve);
7482 auto group = EC_GROUP_Ptr(EC_GROUP_new_by_curve_name(curveName));
7483 ASSERT_NE(group, nullptr);
7484 ASSERT_EQ(EC_KEY_set_group(ecKey.get(), group.get()), 1);
7485 ASSERT_EQ(EC_KEY_generate_key(ecKey.get()), 1);
7486 *localPrivKey = EVP_PKEY_Ptr(EVP_PKEY_new());
7487 ASSERT_EQ(EVP_PKEY_set1_EC_KEY(localPrivKey->get(), ecKey.get()), 1);
7488
7489 // Get encoded form of the public part of the locally generated key...
7490 unsigned char* p = nullptr;
7491 int localPublicKeySize = i2d_PUBKEY(localPrivKey->get(), &p);
7492 ASSERT_GT(localPublicKeySize, 0);
7493 *localPublicKey =
7494 vector<uint8_t>(reinterpret_cast<const uint8_t*>(p),
7495 reinterpret_cast<const uint8_t*>(p + localPublicKeySize));
7496 OPENSSL_free(p);
7497 }
7498 }
7499
7500 void GenerateKeyMintEcKey(EcCurve curve, EVP_PKEY_Ptr* kmPubKey) {
7501 vector<uint8_t> challenge = {0x41, 0x42};
subrahmanyaman7d9bc462022-03-16 01:40:39 +00007502 auto builder = AuthorizationSetBuilder()
7503 .Authorization(TAG_NO_AUTH_REQUIRED)
7504 .Authorization(TAG_EC_CURVE, curve)
7505 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7506 .Authorization(TAG_ALGORITHM, Algorithm::EC)
7507 .Authorization(TAG_ATTESTATION_APPLICATION_ID, {0x61, 0x62})
7508 .Authorization(TAG_ATTESTATION_CHALLENGE, challenge)
7509 .SetDefaultValidity();
7510 ErrorCode result = GenerateKey(builder);
7511
7512 if (SecLevel() == SecurityLevel::STRONGBOX) {
7513 if (result == ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED) {
7514 result = GenerateKeyWithSelfSignedAttestKey(
7515 AuthorizationSetBuilder()
7516 .EcdsaKey(EcCurve::P_256)
7517 .AttestKey()
7518 .SetDefaultValidity(), /* attest key params */
7519 builder, &key_blob_, &key_characteristics_, &cert_chain_);
7520 }
7521 }
David Drysdale42fe1892021-10-14 14:43:46 +01007522 ASSERT_EQ(ErrorCode::OK, result) << "Failed to generate key";
7523 ASSERT_GT(cert_chain_.size(), 0);
7524 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7525 ASSERT_NE(kmKeyCert, nullptr);
7526 // Check that keyAgreement (bit 4) is set in KeyUsage
7527 EXPECT_TRUE((X509_get_key_usage(kmKeyCert.get()) & X509v3_KU_KEY_AGREEMENT) != 0);
7528 *kmPubKey = EVP_PKEY_Ptr(X509_get_pubkey(kmKeyCert.get()));
7529 ASSERT_NE(*kmPubKey, nullptr);
7530 if (dump_Attestations) {
7531 for (size_t n = 0; n < cert_chain_.size(); n++) {
7532 std::cout << bin2hex(cert_chain_[n].encodedCertificate) << std::endl;
7533 }
7534 }
7535 }
7536
7537 void CheckAgreement(EVP_PKEY_Ptr kmPubKey, EVP_PKEY_Ptr localPrivKey,
7538 const std::vector<uint8_t>& localPublicKey) {
7539 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7540 string ZabFromKeyMintStr;
7541 ASSERT_EQ(ErrorCode::OK,
7542 Finish(string(localPublicKey.begin(), localPublicKey.end()), &ZabFromKeyMintStr));
7543 vector<uint8_t> ZabFromKeyMint(ZabFromKeyMintStr.begin(), ZabFromKeyMintStr.end());
7544 vector<uint8_t> ZabFromTest;
7545
7546 if (EVP_PKEY_id(kmPubKey.get()) == EVP_PKEY_X25519) {
7547 size_t kmPubKeySize = 32;
7548 uint8_t kmPubKeyData[32];
7549 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7550 ASSERT_EQ(kmPubKeySize, 32);
7551
7552 uint8_t localPrivKeyData[32];
7553 size_t localPrivKeySize = 32;
7554 ASSERT_EQ(1, EVP_PKEY_get_raw_private_key(localPrivKey.get(), localPrivKeyData,
7555 &localPrivKeySize));
7556 ASSERT_EQ(localPrivKeySize, 32);
7557
7558 uint8_t sharedKey[32];
7559 ASSERT_EQ(1, X25519(sharedKey, localPrivKeyData, kmPubKeyData));
7560 ZabFromTest = std::vector<uint8_t>(sharedKey, sharedKey + 32);
7561 } else {
7562 // Perform local ECDH between the two keys so we can check if we get the same Zab..
7563 auto ctx = EVP_PKEY_CTX_Ptr(EVP_PKEY_CTX_new(localPrivKey.get(), nullptr));
7564 ASSERT_NE(ctx, nullptr);
7565 ASSERT_EQ(EVP_PKEY_derive_init(ctx.get()), 1);
7566 ASSERT_EQ(EVP_PKEY_derive_set_peer(ctx.get(), kmPubKey.get()), 1);
7567 size_t ZabFromTestLen = 0;
7568 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), nullptr, &ZabFromTestLen), 1);
7569 ZabFromTest.resize(ZabFromTestLen);
7570 ASSERT_EQ(EVP_PKEY_derive(ctx.get(), ZabFromTest.data(), &ZabFromTestLen), 1);
7571 }
7572 EXPECT_EQ(ZabFromKeyMint, ZabFromTest);
7573 }
7574};
7575
David Zeuthene0c40892021-01-08 12:54:11 -05007576/*
7577 * KeyAgreementTest.Ecdh
7578 *
David Drysdale42fe1892021-10-14 14:43:46 +01007579 * Verifies that ECDH works for all required curves
David Zeuthene0c40892021-01-08 12:54:11 -05007580 */
7581TEST_P(KeyAgreementTest, Ecdh) {
7582 // Because it's possible to use this API with keys on different curves, we
7583 // check all N^2 combinations where N is the number of supported
7584 // curves.
7585 //
7586 // This is not a big deal as N is 4 so we only do 16 runs. If we end up with a
7587 // lot more curves we can be smart about things and just pick |otherCurve| so
7588 // it's not |curve| and that way we end up with only 2*N runs
7589 //
7590 for (auto curve : ValidCurves()) {
7591 for (auto localCurve : ValidCurves()) {
7592 // Generate EC key locally (with access to private key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007593 EVP_PKEY_Ptr localPrivKey;
7594 vector<uint8_t> localPublicKey;
7595 GenerateLocalEcKey(localCurve, &localPrivKey, &localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007596
7597 // Generate EC key in KeyMint (only access to public key material)
David Drysdale42fe1892021-10-14 14:43:46 +01007598 EVP_PKEY_Ptr kmPubKey;
7599 GenerateKeyMintEcKey(curve, &kmPubKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007600
7601 // Now that we have the two keys, we ask KeyMint to perform ECDH...
7602 if (curve != localCurve) {
7603 // If the keys are using different curves KeyMint should fail with
7604 // ErrorCode:INVALID_ARGUMENT. Check that.
7605 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7606 string ZabFromKeyMintStr;
7607 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
David Drysdale42fe1892021-10-14 14:43:46 +01007608 Finish(string(localPublicKey.begin(), localPublicKey.end()),
David Zeuthene0c40892021-01-08 12:54:11 -05007609 &ZabFromKeyMintStr));
7610
7611 } else {
7612 // Otherwise if the keys are using the same curve, it should work.
David Drysdale42fe1892021-10-14 14:43:46 +01007613 CheckAgreement(std::move(kmPubKey), std::move(localPrivKey), localPublicKey);
David Zeuthene0c40892021-01-08 12:54:11 -05007614 }
7615
7616 CheckedDeleteKey();
7617 }
7618 }
7619}
7620
David Drysdale42fe1892021-10-14 14:43:46 +01007621/*
7622 * KeyAgreementTest.EcdhCurve25519
7623 *
7624 * Verifies that ECDH works for curve25519. This is also covered by the general
7625 * KeyAgreementTest.Ecdh case, but is pulled out separately here because this curve was added after
7626 * KeyMint 1.0.
7627 */
7628TEST_P(KeyAgreementTest, EcdhCurve25519) {
7629 if (!Curve25519Supported()) {
7630 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7631 }
7632
7633 // Generate EC key in KeyMint (only access to public key material)
7634 EcCurve curve = EcCurve::CURVE_25519;
7635 EVP_PKEY_Ptr kmPubKey = nullptr;
7636 GenerateKeyMintEcKey(curve, &kmPubKey);
7637
7638 // Generate EC key on same curve locally (with access to private key material).
7639 EVP_PKEY_Ptr privKey;
7640 vector<uint8_t> encodedPublicKey;
7641 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7642
7643 // Agree on a key between local and KeyMint and check it.
7644 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7645
7646 CheckedDeleteKey();
7647}
7648
7649/*
7650 * KeyAgreementTest.EcdhCurve25519Imported
7651 *
7652 * Verifies that ECDH works for an imported curve25519 key.
7653 */
7654TEST_P(KeyAgreementTest, EcdhCurve25519Imported) {
7655 if (!Curve25519Supported()) {
7656 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7657 }
7658
7659 // Import x25519 key into KeyMint.
7660 EcCurve curve = EcCurve::CURVE_25519;
7661 ASSERT_EQ(ErrorCode::OK, ImportKey(AuthorizationSetBuilder()
7662 .Authorization(TAG_NO_AUTH_REQUIRED)
7663 .EcdsaKey(EcCurve::CURVE_25519)
7664 .Authorization(TAG_PURPOSE, KeyPurpose::AGREE_KEY)
7665 .SetDefaultValidity(),
7666 KeyFormat::PKCS8, x25519_pkcs8_key));
7667 ASSERT_GT(cert_chain_.size(), 0);
7668 X509_Ptr kmKeyCert(parse_cert_blob(cert_chain_[0].encodedCertificate));
7669 ASSERT_NE(kmKeyCert, nullptr);
7670 EVP_PKEY_Ptr kmPubKey(X509_get_pubkey(kmKeyCert.get()));
7671 ASSERT_NE(kmPubKey.get(), nullptr);
7672
7673 // Expect the import to emit corresponding public key data.
7674 size_t kmPubKeySize = 32;
7675 uint8_t kmPubKeyData[32];
7676 ASSERT_EQ(1, EVP_PKEY_get_raw_public_key(kmPubKey.get(), kmPubKeyData, &kmPubKeySize));
7677 ASSERT_EQ(kmPubKeySize, 32);
7678 EXPECT_EQ(bin2hex(std::vector<uint8_t>(kmPubKeyData, kmPubKeyData + 32)),
7679 bin2hex(std::vector<uint8_t>(x25519_pubkey.begin(), x25519_pubkey.end())));
7680
7681 // Generate EC key on same curve locally (with access to private key material).
7682 EVP_PKEY_Ptr privKey;
7683 vector<uint8_t> encodedPublicKey;
7684 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7685
7686 // Agree on a key between local and KeyMint and check it.
7687 CheckAgreement(std::move(kmPubKey), std::move(privKey), encodedPublicKey);
7688
7689 CheckedDeleteKey();
7690}
7691
7692/*
7693 * KeyAgreementTest.EcdhCurve25519InvalidSize
7694 *
7695 * Verifies that ECDH fails for curve25519 if the wrong size of public key is provided.
7696 */
7697TEST_P(KeyAgreementTest, EcdhCurve25519InvalidSize) {
7698 if (!Curve25519Supported()) {
7699 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7700 }
7701
7702 // Generate EC key in KeyMint (only access to public key material)
7703 EcCurve curve = EcCurve::CURVE_25519;
7704 EVP_PKEY_Ptr kmPubKey = nullptr;
7705 GenerateKeyMintEcKey(curve, &kmPubKey);
7706
7707 // Generate EC key on same curve locally (with access to private key material).
7708 EVP_PKEY_Ptr privKey;
7709 vector<uint8_t> encodedPublicKey;
7710 GenerateLocalEcKey(curve, &privKey, &encodedPublicKey);
7711
7712 ASSERT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7713 string ZabFromKeyMintStr;
7714 // Send in an incomplete public key.
7715 ASSERT_NE(ErrorCode::OK, Finish(string(encodedPublicKey.begin(), encodedPublicKey.end() - 1),
7716 &ZabFromKeyMintStr));
7717
7718 CheckedDeleteKey();
7719}
7720
7721/*
7722 * KeyAgreementTest.EcdhCurve25519Mismatch
7723 *
7724 * Verifies that ECDH fails between curve25519 and other curves.
7725 */
7726TEST_P(KeyAgreementTest, EcdhCurve25519Mismatch) {
7727 if (!Curve25519Supported()) {
7728 GTEST_SKIP() << "Test not applicable to device that is not expected to support curve 25519";
7729 }
7730
7731 // Generate EC key in KeyMint (only access to public key material)
7732 EcCurve curve = EcCurve::CURVE_25519;
7733 EVP_PKEY_Ptr kmPubKey = nullptr;
7734 GenerateKeyMintEcKey(curve, &kmPubKey);
7735
7736 for (auto localCurve : ValidCurves()) {
7737 if (localCurve == curve) {
7738 continue;
7739 }
7740 // Generate EC key on a different curve locally (with access to private key material).
7741 EVP_PKEY_Ptr privKey;
7742 vector<uint8_t> encodedPublicKey;
7743 GenerateLocalEcKey(localCurve, &privKey, &encodedPublicKey);
7744
7745 EXPECT_EQ(ErrorCode::OK, Begin(KeyPurpose::AGREE_KEY, AuthorizationSetBuilder()));
7746 string ZabFromKeyMintStr;
7747 EXPECT_EQ(ErrorCode::INVALID_ARGUMENT,
7748 Finish(string(encodedPublicKey.begin(), encodedPublicKey.end()),
7749 &ZabFromKeyMintStr));
7750 }
7751
7752 CheckedDeleteKey();
7753}
7754
David Zeuthene0c40892021-01-08 12:54:11 -05007755INSTANTIATE_KEYMINT_AIDL_TEST(KeyAgreementTest);
7756
David Drysdaled2cc8c22021-04-15 13:29:45 +01007757using DestroyAttestationIdsTest = KeyMintAidlTestBase;
7758
7759// This is a problematic test, as it can render the device under test permanently unusable.
7760// Re-enable and run at your own risk.
7761TEST_P(DestroyAttestationIdsTest, DISABLED_DestroyTest) {
7762 auto result = DestroyAttestationIds();
7763 EXPECT_TRUE(result == ErrorCode::OK || result == ErrorCode::UNIMPLEMENTED);
7764}
7765
7766INSTANTIATE_KEYMINT_AIDL_TEST(DestroyAttestationIdsTest);
7767
Shawn Willdend659c7c2021-02-19 14:51:51 -07007768using EarlyBootKeyTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007769
David Drysdaledb0dcf52021-05-18 11:43:31 +01007770/*
7771 * EarlyBootKeyTest.CreateEarlyBootKeys
7772 *
7773 * Verifies that creating early boot keys succeeds, even at a later stage (after boot).
7774 */
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007775TEST_P(EarlyBootKeyTest, CreateEarlyBootKeys) {
David Drysdaledb0dcf52021-05-18 11:43:31 +01007776 // Early boot keys can be created after early boot.
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007777 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7778 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7779
David Drysdaleadfe6112021-05-27 12:00:53 +01007780 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
7781 ASSERT_GT(keyData.blob.size(), 0U);
7782 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7783 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7784 }
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007785 CheckedDeleteKey(&aesKeyData.blob);
7786 CheckedDeleteKey(&hmacKeyData.blob);
7787 CheckedDeleteKey(&rsaKeyData.blob);
7788 CheckedDeleteKey(&ecdsaKeyData.blob);
7789}
7790
David Drysdaledb0dcf52021-05-18 11:43:31 +01007791/*
David Drysdaleadfe6112021-05-27 12:00:53 +01007792 * EarlyBootKeyTest.CreateAttestedEarlyBootKey
7793 *
7794 * Verifies that creating an early boot key with attestation succeeds.
7795 */
7796TEST_P(EarlyBootKeyTest, CreateAttestedEarlyBootKey) {
7797 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] = CreateTestKeys(
7798 TAG_EARLY_BOOT_ONLY, ErrorCode::OK, [](AuthorizationSetBuilder* builder) {
7799 builder->AttestationChallenge("challenge");
7800 builder->AttestationApplicationId("app_id");
7801 });
7802
7803 for (const auto& keyData : {aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData}) {
subrahmanyaman05642492022-02-05 07:10:56 +00007804 // Strongbox may not support factory attestation. Key creation might fail with
7805 // ErrorCode::ATTESTATION_KEYS_NOT_PROVISIONED
7806 if (SecLevel() == SecurityLevel::STRONGBOX && keyData.blob.size() == 0U) {
7807 continue;
7808 }
David Drysdaleadfe6112021-05-27 12:00:53 +01007809 ASSERT_GT(keyData.blob.size(), 0U);
7810 AuthorizationSet crypto_params = SecLevelAuthorizations(keyData.characteristics);
7811 EXPECT_TRUE(crypto_params.Contains(TAG_EARLY_BOOT_ONLY)) << crypto_params;
7812 }
7813 CheckedDeleteKey(&aesKeyData.blob);
7814 CheckedDeleteKey(&hmacKeyData.blob);
subrahmanyaman05642492022-02-05 07:10:56 +00007815 if (rsaKeyData.blob.size() != 0U) {
7816 CheckedDeleteKey(&rsaKeyData.blob);
7817 }
7818 if (ecdsaKeyData.blob.size() != 0U) {
7819 CheckedDeleteKey(&ecdsaKeyData.blob);
7820 }
David Drysdaleadfe6112021-05-27 12:00:53 +01007821}
7822
7823/*
7824 * EarlyBootKeyTest.UseEarlyBootKeyFailure
David Drysdaledb0dcf52021-05-18 11:43:31 +01007825 *
7826 * Verifies that using early boot keys at a later stage fails.
7827 */
7828TEST_P(EarlyBootKeyTest, UseEarlyBootKeyFailure) {
7829 ASSERT_EQ(ErrorCode::OK, GenerateKey(AuthorizationSetBuilder()
7830 .Authorization(TAG_NO_AUTH_REQUIRED)
7831 .Authorization(TAG_EARLY_BOOT_ONLY)
7832 .HmacKey(128)
7833 .Digest(Digest::SHA_2_256)
7834 .Authorization(TAG_MIN_MAC_LENGTH, 256)));
7835 AuthorizationSet output_params;
7836 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, Begin(KeyPurpose::SIGN, key_blob_,
7837 AuthorizationSetBuilder()
7838 .Digest(Digest::SHA_2_256)
7839 .Authorization(TAG_MAC_LENGTH, 256),
7840 &output_params));
7841}
7842
7843/*
7844 * EarlyBootKeyTest.ImportEarlyBootKeyFailure
7845 *
7846 * Verifies that importing early boot keys fails.
7847 */
7848TEST_P(EarlyBootKeyTest, ImportEarlyBootKeyFailure) {
7849 ASSERT_EQ(ErrorCode::EARLY_BOOT_ENDED, ImportKey(AuthorizationSetBuilder()
7850 .Authorization(TAG_NO_AUTH_REQUIRED)
7851 .Authorization(TAG_EARLY_BOOT_ONLY)
David Drysdaledf09e542021-06-08 15:46:11 +01007852 .EcdsaSigningKey(EcCurve::P_256)
David Drysdaledb0dcf52021-05-18 11:43:31 +01007853 .Digest(Digest::SHA_2_256)
7854 .SetDefaultValidity(),
7855 KeyFormat::PKCS8, ec_256_key));
7856}
7857
David Drysdaled2cc8c22021-04-15 13:29:45 +01007858// 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 +00007859// boot stage, which no proper Android device is by the time we can run VTS. To use this,
7860// un-disable it and modify vold to remove the call to earlyBootEnded(). Running the test will end
7861// early boot, so you'll have to reboot between runs.
7862TEST_P(EarlyBootKeyTest, DISABLED_FullTest) {
7863 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7864 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::OK);
7865 // TAG_EARLY_BOOT_ONLY should be in hw-enforced.
7866 EXPECT_TRUE(HwEnforcedAuthorizations(aesKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7867 EXPECT_TRUE(
7868 HwEnforcedAuthorizations(hmacKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7869 EXPECT_TRUE(HwEnforcedAuthorizations(rsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7870 EXPECT_TRUE(
7871 HwEnforcedAuthorizations(ecdsaKeyData.characteristics).Contains(TAG_EARLY_BOOT_ONLY));
7872
7873 // Should be able to use keys, since early boot has not ended
7874 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7875 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7876 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7877 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7878
7879 // End early boot
7880 ErrorCode earlyBootResult = GetReturnErrorCode(keyMint().earlyBootEnded());
7881 EXPECT_EQ(earlyBootResult, ErrorCode::OK);
7882
7883 // Should not be able to use already-created keys.
7884 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseAesKey(aesKeyData.blob));
7885 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseHmacKey(hmacKeyData.blob));
7886 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseRsaKey(rsaKeyData.blob));
7887 EXPECT_EQ(ErrorCode::EARLY_BOOT_ENDED, UseEcdsaKey(ecdsaKeyData.blob));
7888
7889 CheckedDeleteKey(&aesKeyData.blob);
7890 CheckedDeleteKey(&hmacKeyData.blob);
7891 CheckedDeleteKey(&rsaKeyData.blob);
7892 CheckedDeleteKey(&ecdsaKeyData.blob);
7893
7894 // Should not be able to create new keys
7895 std::tie(aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData) =
7896 CreateTestKeys(TAG_EARLY_BOOT_ONLY, ErrorCode::EARLY_BOOT_ENDED);
7897
7898 CheckedDeleteKey(&aesKeyData.blob);
7899 CheckedDeleteKey(&hmacKeyData.blob);
7900 CheckedDeleteKey(&rsaKeyData.blob);
7901 CheckedDeleteKey(&ecdsaKeyData.blob);
7902}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007903
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007904INSTANTIATE_KEYMINT_AIDL_TEST(EarlyBootKeyTest);
7905
Shawn Willdend659c7c2021-02-19 14:51:51 -07007906using UnlockedDeviceRequiredTest = KeyMintAidlTestBase;
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007907
7908// This may be a problematic test. It can't be run repeatedly without unlocking the device in
7909// between runs... and on most test devices there are no enrolled credentials so it can't be
7910// unlocked at all, meaning the only way to get the test to pass again on a properly-functioning
7911// device is to reboot it. For that reason, this is disabled by default. It can be used as part of
7912// a manual test process, which includes unlocking between runs, which is why it's included here.
7913// Well, that and the fact that it's the only test we can do without also making calls into the
7914// Gatekeeper HAL. We haven't written any cross-HAL tests, and don't know what all of the
7915// implications might be, so that may or may not be a solution.
7916TEST_P(UnlockedDeviceRequiredTest, DISABLED_KeysBecomeUnusable) {
7917 auto [aesKeyData, hmacKeyData, rsaKeyData, ecdsaKeyData] =
7918 CreateTestKeys(TAG_UNLOCKED_DEVICE_REQUIRED, ErrorCode::OK);
7919
7920 EXPECT_EQ(ErrorCode::OK, UseAesKey(aesKeyData.blob));
7921 EXPECT_EQ(ErrorCode::OK, UseHmacKey(hmacKeyData.blob));
7922 EXPECT_EQ(ErrorCode::OK, UseRsaKey(rsaKeyData.blob));
7923 EXPECT_EQ(ErrorCode::OK, UseEcdsaKey(ecdsaKeyData.blob));
7924
7925 ErrorCode rc = GetReturnErrorCode(
David Drysdaled2cc8c22021-04-15 13:29:45 +01007926 keyMint().deviceLocked(false /* passwordOnly */, {} /* timestampToken */));
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007927 ASSERT_EQ(ErrorCode::OK, rc);
7928 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseAesKey(aesKeyData.blob));
7929 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseHmacKey(hmacKeyData.blob));
7930 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseRsaKey(rsaKeyData.blob));
7931 EXPECT_EQ(ErrorCode::DEVICE_LOCKED, UseEcdsaKey(ecdsaKeyData.blob));
7932
7933 CheckedDeleteKey(&aesKeyData.blob);
7934 CheckedDeleteKey(&hmacKeyData.blob);
7935 CheckedDeleteKey(&rsaKeyData.blob);
7936 CheckedDeleteKey(&ecdsaKeyData.blob);
7937}
Shawn Willdend659c7c2021-02-19 14:51:51 -07007938
Chirag Pathak9ea6a0a2021-02-01 23:54:27 +00007939INSTANTIATE_KEYMINT_AIDL_TEST(UnlockedDeviceRequiredTest);
7940
Janis Danisevskis24c04702020-12-16 18:28:39 -08007941} // namespace aidl::android::hardware::security::keymint::test
Selene Huang31ab4042020-04-29 04:22:39 -07007942
7943int main(int argc, char** argv) {
Shawn Willden7c130392020-12-21 09:58:22 -07007944 std::cout << "Testing ";
7945 auto halInstances =
7946 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::build_params();
7947 std::cout << "HAL instances:\n";
7948 for (auto& entry : halInstances) {
7949 std::cout << " " << entry << '\n';
7950 }
7951
Selene Huang31ab4042020-04-29 04:22:39 -07007952 ::testing::InitGoogleTest(&argc, argv);
7953 for (int i = 1; i < argc; ++i) {
7954 if (argv[i][0] == '-') {
7955 if (std::string(argv[i]) == "--arm_deleteAllKeys") {
Shawn Willden7c130392020-12-21 09:58:22 -07007956 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
7957 arm_deleteAllKeys = true;
Selene Huang31ab4042020-04-29 04:22:39 -07007958 }
7959 if (std::string(argv[i]) == "--dump_attestations") {
Shawn Willden7c130392020-12-21 09:58:22 -07007960 aidl::android::hardware::security::keymint::test::KeyMintAidlTestBase::
7961 dump_Attestations = true;
7962 } else {
7963 std::cout << "NOT dumping attestations" << std::endl;
Selene Huang31ab4042020-04-29 04:22:39 -07007964 }
David Drysdaledbbbe2e2021-12-02 07:44:23 +00007965 if (std::string(argv[i]) == "--skip_boot_pl_check") {
7966 // Allow checks of BOOT_PATCHLEVEL to be disabled, so that the tests can
7967 // be run in emulated environments that don't have the normal bootloader
7968 // interactions.
7969 aidl::android::hardware::security::keymint::test::check_boot_pl = false;
7970 }
Selene Huang31ab4042020-04-29 04:22:39 -07007971 }
7972 }
Shawn Willden08a7e432020-12-11 13:05:27 +00007973 return RUN_ALL_TESTS();
Selene Huang31ab4042020-04-29 04:22:39 -07007974}